用Struts2 + Hibernate(3.3.1)做了一个测试程序,查询的时候遇到了强制转换类型错误,数据库是MySQL 5.0,麻烦看下代码,很简单。
异常提示:
[code="java"]
java.lang.ClassCastException: java.lang.String
at org.hibernate.type.DateType.toString(DateType.java:101)
at org.hibernate.type.NullableType.nullSafeToString(NullableType.java:117)
at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:158)
at org.hibernate.type.NullableType.nullSafeSet(NullableType.java:136)
at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:61)
at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:514)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1589)
at org.hibernate.loader.Loader.doQuery(Loader.java:696)
…………
[/code]
Hibernate 映射文件:
[code="xml"]
<!-- MySQL数据库中TIME字段的类型为DATETIME -->
[/code]
DAO类
[code="java"]
package dao;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import model.SData;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class SDao {
private Session session = null;
private Transaction tx = null;
Map<String, String> map = null;
@SuppressWarnings("unchecked")
public List<SData> query( SData data ) {
session = HibernateUtil.getCurrentSession();
try {
String hql = createSQL(data);
Query query = HibernateUtil.getCurrentSession().createQuery(hql);
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
query.setParameter(key, map.get(key));
}
query.setMaxResults(512);
List list = query.list();
return list;
}
catch (HibernateException e) {
HibernateUtil.rollbackTransaction();
}
return null;
}
private String createSQL( SData data ) {
StringBuffer hql = new StringBuffer();
hql.append("from SData as s where 1=1 ");
map = new HashMap<String, String>();
String value = data.getName();
if (value != null && value.length() > 0) {
map.put("name", "%" + value + "%");
hql.append("and s.name like :name ");
}
value = data.getAddr();
if (value != null && value.length() > 0) {
map.put("addr", value);
hql.append("and s.addr = :addr ");
}
Date time = data.getTime();
if (time != null) {
long now = time.getTime();
now = now - now % 86400000 + 57600000;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
map.put("begin", sdf.format(new Date(now)));
map.put("end", sdf.format(new Date(now + 86400000)));
hql.append("and s.time between :begin and :end ");
}
value = data.getLine();
if (value != null && value.length() > 0) {
map.put("line", value);
hql.append("and s.line = :line ");
}
return hql.toString();
}
}
[/code]
个人感觉应该不是大问题,不过我找了很久还是没想出来解决办法,实属无奈来此发帖劳烦大家,求帮忙,感激不尽。