有人知道如何使用hibernate ResultTransformer吗?我想将实体转换为dto。这是我的代码
Criteria criteria = session.createCriteria(Person.class)
criteria.add(Restrictions.eq("id",id));
PersonDto personDto = criteria.uniqueResult();
抛出一个classCastException,表示无法将Person转换为PersonDto。
其他问题: 这段代码工作正常,但为什么不是上面的代码?
Criteria criteria = session.createCriteria(Person.class);
List<PersonDto> personDtos = criteria.list();
答案 0 :(得分:0)
如果你只是想转换实体,也许应该使用像推土机这样的工具 http://dozer.sourceforge.net/documentation/usage.html
使用transformList
的示例Query query = session.createQuery(""
+ "Select DISTINCT VP.versionId as parent from VersionData VP "
+ "INNER JOIN VP.zvitId ZP "
+ "INNER JOIN ZP.childrens CH "
+ "INNER JOIN CH.versions CP "
+ "where CP.zvitId.zvitId = :idList and VP.dend IS NULL"
)
.setParameter("idList", id)
.setResultTransformer(Transformers.aliasToBean(ParentIdList.class));
@SuppressWarnings("unchecked")
List<ParentIdList> result = query.list();
Parent IdList与返回查询值具有相同的属性名称 公共类ParentIdList { private String parent;
/**
* @return the parents
*/
public String getParent()
{
return parent;
}
/**
* @param parents the parents to set
*/
public void setParent(String parents)
{
this.parent = parents;
}
//getters, setters, hashcode, equals
}