我有这样的实体:Hibernate的标准API - 过滤集合属性
@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>();
}
和另一个问题:
@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;
}
使用标准的API我想用过滤集Picturs的独特AlbumDs。我尝试这样的:
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;
}
在这里我得到相册与所有图片关联。他们根本没有被过滤。 当我尝试执行由记录器打印的查询时,我只得到四行,这是给定eventId的图片数量,但在相册中我获取了所有图片。
我也尝试过其他ResultTransformers,但最终得到了很多结果(4)没有明确的结果。
我该错过什么或做错了什么?
原谅我的断语;) – 2011-05-23 19:46:47
做您尝试观看查询休眠产生什么SQL ? – 2011-05-23 21:05:14
我已经写过了。有一个SQL查询只能检索4张图片,但我后来发现,还有另一个检索所有这些图片。我开始相信我的案例不适用于Criteria API :( – 2011-05-23 21:34:03