HQL形式:(构造方法不支持timestamp类型)
public List<Device> queryByMatherBoardId(String matherBoardId) {
String hql = "select new Device(d.id,d.diskSize,d.diskSerial) from Device as d where d.matherBoard=:matherBoard";
return this.getSession().createQuery(hql)
.setParameter("matherBoard", matherBoardId).list();
}
使用这种方式,Device构造方法不支持参数为time类型,会报无法匹配合适的构造方法错误。
SQL形式:
public List<Device> queryByMatherBoardId(String matherBoardId) {
String sql = "select d.id,d.diskSize,d.diskSerial,d.registerTime from cems_device as d where d.matherBoardId=:matherBoardId order by registerTime asc";
List<Device> list = getSession().createSQLQuery(hql)
.setParameter("matherBoardId",matherBoardId)
.list();
return list;
}
使用这种方式呢,虽然不会报错,可以正常查询数据,但是获取的数据却是数组对象,达不到我们需要的实体对象的要求。
查询的数据:select d.id,d.diskSize,d.diskSerial,d.registerTime from cems_device as d where d.matherBoardId='D8924D56-414C-ABCC-935A-A9D506926B31' ORDER BY registerTime ASC
想要得到的数据:像下面这样实体类对象
需要像下面这段代码一样转换下:
public List<Device> queryByMatherBoardId(String matherBoardId) {
Map<String,Object> map = new HashMap<String,Object>();
String hql = "select d.id,d.diskSize,d.diskSerial,d.registerTime from cems_device as d where d.matherBoardId=:matherBoardId order by registerTime asc";
map.put("matherBoardId",matherBoardId);
Query q = getSession().createSQLQuery(hql)
.addScalar("id", StandardBasicTypes.STRING)
.addScalar("diskSize", StandardBasicTypes.INTEGER)
.addScalar("diskSerial", StandardBasicTypes.STRING)
.addScalar("registerTime", StandardBasicTypes.TIMESTAMP)
.setResultTransformer(Transformers.aliasToBean(Device.class));
q = assignValues(q, map);
List<Device> list=(List<Device>)q.list();
return list;
}
/**
* 按名称绑定
* @param query
* @param values
* @return
*/
public Query assignValues(Query query, Map<String, ?> values) {
if (values != null) {
Set<String> keySet = values.keySet();
for (String string : keySet) {
Object obj = values.get(string);
if (obj instanceof Collection<?>) {
query.setParameterList(string, (Collection<?>) obj);
} else if (obj instanceof Object[]) {
query.setParameterList(string, (Object[]) obj);
} else {
query.setParameter(string, obj);
}
}
}
return query;
}
这样就可以把之前对象数组数组转换为实体类对象数据。(主要是可以记住这个转换方法)