Pat*_*ski 4 java filtering hibernate criteria one-to-many
我有这样的实体:
@Entity
public class Album {
private Integer id;
private Integer ownerId;
private String name;
private String description;
private Date created;
@OneToMany @JoinColumn(name = "albumId")
private Set<AlbumUser> users = new HashSet<AlbumUser>();
@OneToMany @JoinColumn(name = "albumId")
private Set<Picture> pictures = new HashSet<Picture>();
}
Run Code Online (Sandbox Code Playgroud)
另一个:
@Entity
public class Picture {
private Integer id;
private Integer creatorId;
private Integer albumId;
private Date created;
private String title;
private String description;
@ManyToOne @JoinColumn(name = "eventId")
private Event event;
}
Run Code Online (Sandbox Code Playgroud)
使用Criteria API我希望获得具有过滤的Picturs集的唯一AlbumD.我尝试这样的事情:
public Album read(Integer albumId, Set<Integer> picFilter) {
Criteria crit = getCurrentSession().createCriteria(Album.class, "album");
crit.add(Restrictions.idEq(albumId));
if (picFilter != null && !picFilter.isEmpty()) {
crit = crit.createAlias("album.pictures", "picture");
crit.add(Restrictions.in("picture.event.id", picFilter));
crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
}
Album resultDs = (Album) crit.uniqueResult();
return resultDs;
}
Run Code Online (Sandbox Code Playgroud)
在这里,我得到Album与所有相关的图片.他们根本没有过滤.当我尝试执行由记录器打印的查询时,我只得到四行,这是给定eventId的图片数量,但在相册中我得到所有图片.
我也试过了其他的ResultTransformers,但是最终得到了很多结果(4)并不是一个明显的结果.
我错过了什么或做错了什么?
您不能通过在查询中包含对集合的限制来过滤与实体关联的集合的内容.查询将仅获取相册.访问Collection时,可以稍后获取Collection的内容.您所做的只是过滤相册以仅检索包含带有事件ID的图片的相册.
如果Collection只包含与Criteria匹配的图片,并且你会获得部分Collection会导致更新问题,因为Hibernate认为已经删除过滤后的项目并更新数据库以反映该更改,实际上删除了项目来自收藏.
如果您只想从Collection中接收一些项目,可以使用Session.createFilter()方法.唯一的问题是,它目前只支持HQL查询.
| 归档时间: |
|
| 查看次数: |
15028 次 |
| 最近记录: |