表格信息:
图片表包含父表媒体
的外键 mediaid----------
id | mediaid | url
========================
104 | 103 | IMG_PATH
383 | 103 | IMG_PATH
384 | 103 | IMG_PATH
395 | 103 | img_path
媒体实体包含图片集合:
private Set<Image> images = new HashSet<Image>(0)`;
@OneToMany(mappedBy = "media", targetEntity = Image.class ,cascade = CascadeType.ALL)
public Set<Image> getImages() {
return images;
}
图片实体代码段:
private Media media;
@ManyToOne
@JoinColumn(name = "mediaId")
public Media getMedia() {
return media;
}
我实现了以下查询,该查询应返回一个Media对象,其中包含fk与其提供的 id 匹配的所有图像的集合。
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Media> cqObject = cb.createQuery(Media.class);
Root<Media> rootEntry = cqObject.from(Media.class);
rootEntry.fetch(Media_.images, JoinType.LEFT);
Predicate predicate = cb.equal(rootEntry.get(Media_.id), id);
cqObject.select(rootEntry).where(predicate);
Media _fetcheMedia = em.createQuery(cqObject).getSingleResult();
返回的Media对象的集合只包含一个图像项。我确定数据库包含指定媒体的多个图像项。
*注意媒体_ 只是一个代表媒体实体的元模型类
Hibernate out for Media对象的id = 103
select media0_.mediaId as mediaId1_8_0_,
images1_.imageId as imageId1_6_1_,
media0_.active as active2_8_0_,
media0_.created as created3_8_0_,
media0_.description as descript4_8_0_,
media0_.listType as listType5_8_0_,
media0_.parentId as parentId6_8_0_,
media0_.propertyTypeId as property7_8_0_,
media0_.seasonId as seasonId8_8_0_,
media0_.status as status9_8_0_,
media0_.userId as userId10_8_0_,
images1_.active as active2_6_1_,
images1_.created as created3_6_1_,
images1_.imageTypeId as imageTyp5_6_1_,
images1_.imageUrl as imageUrl4_6_1_,
images1_.mediaId as mediaId6_6_1_,
images1_.mediaId as mediaId6_6_0__,
images1_.imageId as imageId1_6_0__ from media media0_
left outer join image images1_ on media0_.mediaId=images1_.mediaId where media0_.mediaId=103
答案 0 :(得分:0)
这是我的一个愚蠢的错误,我忘了覆盖Image实体的hashcode和equals方法。添加它们,它知道它应该工作。
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
Image other = (Image) obj;
if (id != other.id)
return false;
return true;
}