参考:http://blog.sina.com.cn/s/blog_4ad7c2540102uzkc.html
最近使用hibernate做项目,在配置实体类的时候有些字段使用了Timestamp类型。一直没出现什么问题,直到今天,使用了hql语句:String hql = “select new BasicSetting(id,subject,content,modifyDt) from BasicSetting”; 但是这样就报错了,错误如下:
org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate appropriate constructor on class [com.sydecm.entity.BasicSetting]. Expected arguments are: int, java.lang.String, java.lang.String, java.util.Date [select new BasicSetting(id,subject,content,modifyDt) from com.sydecm.entity.BasicSetting]
··········省略其他··············
问题:我明明是Timestamp类型,为何报错为 java.util.Date呢?难道不能自动转?但是我如果把hql语句改为“from BasicSetting”是没错的,谁知道具体原因麻烦留言下
解决方案
实体类增加个静态方法和创建与hql语句相对应的有参构造方法
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);
cal.setTime(date);
return new Timestamp(cal.getTimeInMillis());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
cal.setTime(new Date());
return new Timestamp(cal.getTimeInMillis());
}
}
public BasicSetting(Integer id, String subject, String content, Object modifyDt) {
super();
this.id = id;
this.subject = subject;
this.content = content;
this.modifyDt = stringToTimestamp(modifyDt.toString());
}
dao的实现方法
public List<BasicSetting> queryBasicSetting() throws Exception{
String hql = "select new BasicSetting(id,subject,content,modifyDt) from BasicSetting";
Query query = super.createQuery(hql);
List<BasicSetting> basicSettings = query.list();
return basicSettings;
}