1. 程式人生 > >hibernate實體類構造方法內含有Timestamp型別變數時"Unable to locate approprite constructor"錯誤解決方法

hibernate實體類構造方法內含有Timestamp型別變數時"Unable to locate approprite constructor"錯誤解決方法

在使用hibernate時,有時想獲取部分欄位的結果集,可以用如下方法:

可以在hql中使用select new 包名.類名(屬性1,屬性2,....)  from 實體類,同時要在實體類中新增帶參的構造方法,引數的個數和順序與(屬性1,屬性2,....)要保持一致,如此我們得到的List中存放的依然是實體類的物件。

例:

select new User(u.name,u.createTime) from User u order by u.createTime;

public User(String name,Timestamp createTime){
this.name = name;
this.createTime = createTime;
}

然後便遇到了如下錯誤:


解決方法:(2種)

public User(String name,Date createTime){
this.name = name;
this.createTime = Timestamp.valueOf(DateFormat.dateToNor(createTime))
}

or

public User(String name,Object createTime){
this.name = name;
this.createTime = Timestamp.valueOf(createTime.toString());
}


其中DateFormat是我自定義的工具類,其內的dateToNor()方法如下:
public static String dateToNor(Date dates){
		String time= date.format(dates);
		return time;
	}

public static SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

如此包含部分引數的建構函式便可匹配了。