【Hibernate】Unable to locate appropriate constructor on class原因分析
阿新 • • 發佈:2018-11-30
通常我們喜歡將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 publicvoid 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