hibernate实体类构造方法内含有Timestamp类型变量时"Unable to locate approprite constructor"错误解决方法

来源:互联网 发布:windows xp原装系统 编辑:程序博客网 时间:2024/06/05 07:01

在使用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");

如此包含部分参数的构造函数便可匹配了。

参考博文:hibernate hql查询指定字段并获得结果集  hibernate中实体类构造方法中含有Timestamp 类型变量的"no appropriate constructor.." 错误提示的解决办法

阅读全文
0 0
原创粉丝点击