hibernate criteria can't cast to type

描述
criteria动态查询中,先使用setProjection(Projections.rowCount()),获取查询的总数,再通过setProjection(null); 来获取返回的实体列表。
有关联查询的时候会出错: can't cast to type.
原因:
setProjection()会将返回结果方式设为PROJECTION,默认的是 ROOT_ENTITY
public Criteria setProjection(Projection projection) {
  this.projection = projection;
  this.projectionCriteria = this;
  setResultTransformer( PROJECTION );
  return this;
}
 
当setProjection(null)时,返回结果将不会被投影,返回所有查询到的值,所以关联查询时结果查过root entity,不能正确转换为root entity。
解决方法:
在setProjection(null)之后,添加 setResultTransformer( Criteria.ROOT_ENTITY);将返回结果置为root entity。

猜你喜欢

转载自lingceng.iteye.com/blog/1774279
今日推荐