我有一张图片表,每张图片都与画廊表有很多关系。我正在尝试使用org.hibernate.Criteria
来返回链接给定列表库的所有图像。
我一直在尝试以下操作,在这里我遍历画廊列表并为每个画廊创建一个新的createCriteria
(例如,每个必需画廊一个内部连接),这只适用于一个画廊。但是,当我尝试多次时,我收到org.hibernate.QueryException: duplicate association path: galleries
错误...
ImagesDAOCustom.java
public Images getRandomImagesInGallerys(String[] galleryList) {
Session session = sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(Images.class, "image");
// We want an image that is part of all galleries so we need to create
// a join per gallery.
for (String gallery: galleryList) {
criteria.createCriteria("image.galleries", gallery);
criteria.add(Restrictions.eq(gallery + ".name",gallery));
}
criteria.setProjection(Projections.distinct(Projections.property("id")));
List<Integer> imageIdList = criteria.list();
Images result;
if (imageIdList.size() > 0) {
int index = rand.nextInt(imageIdList.size());
result = imagesDAO.findOne(imageIdList.get(index));
} else {
result = null;
}
return result;
}
Images.java
public class Images {
@Id
@GeneratedValue
@Column(name="ugc_images_id")
private int id;
@JsonIgnore
@JsonView(Views.Internal.class)
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name="ugc_image_galleries", joinColumns={@JoinColumn(name="image_id")}, inverseJoinColumns={@JoinColumn(name="gallery_id")})
private Set<Galleries> galleries = new HashSet<>();
...
}
Galleries.java
public class Galleries }
@Id
@GeneratedValue
@Column(name="ugc_galleries_id")
private int id;
@JsonManagedReference
@ManyToMany(mappedBy="galleries")
private Set<Images> images = new HashSet<>();
@Column(name="name")
private String name;
...
}
答案 0 :(得分:0)
我遇到了同样的问题,我搜索了几个小时。
这对我有用:
public Images getRandomImagesInGallerys(String[] galleryList) {
String query = "from Images ";
boolean first = true;
for(String string : galleryList) {
if(first){
query+="where '"+string+"' member of galleries ";
first=false;
} else {
query+="or '"+string+"' member of galleries ";
}
}
entityManager.createQuery(query, Images.class).getResultList();
}
希望对某人有所帮助。