通常我们喜欢将hql查询结果封装到POJO对象
syntax:
select new POJO(id,name) from POJO ;
这种封装需要POJO类提供对应构造器,POJO(id,name)构造方法。
但使用中经常会抛这样的异常:Unable to locate appropriate constructor on class。
出现这个异常需要检查以下几种情况:
1)参数构造器的参数类型是否正确
2)参数构造器的顺序和hql中的顺序是否一致
3)参数构造器的参数个数是否和hql中的个数一致
4)参数构造器的参数类型是否TimeStamp
其中第4种情况较为复杂
这里提供参数构造器的参数类型是TimeStamp的解决方法:
super.getHibernateTemplate().find("select new Student(id,name,date) from Student");
1 实体类: 2 public class Student { 3 private Long id; 4 private String name; 5 private String address; 6 private Timestamp date; 7 public Long getId() { 8 return id; 9 } 10 public void setId(Long id) { 11 this.id = id; 12 } 13 public String getName() { 14 return name; 15 } 16 public void setName(String name) { 17 this.name = name; 18 } 19 public String getAddress() { 20 return address; 21 } 22 public void setAddress(String address) { 23 this.address = address; 24 } 25 public Timestamp getDate() { 26 return date; 27 } 28 public void setDate(Timestamp date) { 29 this.date = date; 30 } 31 public Student() { 32 super(); 33 } 34 //注意些处的构造方法 35 public Student(Long id, String name, Object date) { 36 this.id=id; 37 this.name = name; 38 this.date = stringToTimestamp(date.toString()); 39 } 40 41 public static Timestamp stringToTimestamp(String dateStr){ 42 43 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 44 Calendar cal = Calendar.getInstance(); 45 try { 46 Date date = sdf.parse(dateStr); 47 date.getTime(); 48 cal.setTime(date); 49 return new Timestamp(cal.getTimeInMillis()); 50 } catch (ParseException e) { 51 e.printStackTrace(); 52 } 53 54 cal.setTime(new Date()); 55 return new Timestamp(cal.getTimeInMillis()); 56 } 57 }
出处:http://blog.sina.com.cn/s/blog_4ad7c2540102uzkc.html
【Hibernate】Unable to locate appropriate constructor on class原因分析