Unable to locate appropriate constructor on class__java

來源:互聯網
上載者:User

通常我們喜歡將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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.