通常我們喜歡將hql查詢結果封裝到POJO對象
syntax:
select new POJO(id,name) from POJO ;
Unable to locate appropriate constructor on class
這種封裝需要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");
實體類:
public class Student {
private Long id;
private String name;
private String address;
private Timestamp date;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Timestamp getDate() {
return date;
}
public void setDate(Timestamp date) {
this.date = date;
}
public Student() {
super();
}
//注意些處的構造方法
public Student(Long id, String name, Object date) {
this.id=id;
this.name = name;
this.date = stringToTimestamp(date.toString());
}
public static Timestamp stringToTimestamp(String dateStr){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
try {
Date date = sdf.parse(dateStr);
date.getTime();
cal.setTime(date);
return new Timestamp(cal.getTimeInMillis());
} catch (ParseException e) {
e.printStackTrace();
}
cal.setTime(new Date());
return new Timestamp(cal.getTimeInMillis());
}
}
出處:http://blog.sina.com.cn/staratsky