我试图用Hibernate 5选择父元素Mods的子元素(多对一)modsVersionses。同时,modsVersionses应该被modsVersionses.id过滤。
我尝试过这样的事情:
Session s = sessionFactory.getCurrentSession();
CriteriaBuilder criteriaBuilder = s.getEntityManagerFactory().getCriteriaBuilder();
CriteriaQuery<Mods> criteriaQuery = criteriaBuilder.createQuery(Mods.class);
Root<Mods> root = criteriaQuery.from(Mods.class);
criteriaQuery.select(root.get("modsVersionses"));
criteriaQuery
.where(criteriaBuilder.equal(root.get("id"), id)).where(criteriaBuilder.equal(root.get("modsVersionses").get("id"), versionId));
List<Mods> resultList = s.createQuery(criteriaQuery).getResultList();
Mods mod = resultList.get(0);
但是我在代码.where(criteriaBuilder.equal(root.get("modsVersionses").get("id"), versionId))
上得到了IllegalStateException。
如何通过id正确过滤子元素?
谢谢!
更新1 :借助@JB Nizet帮助我进行了更改,现在我的代码是:
Session s = sessionFactory.getCurrentSession(); CriteriaBuilder cb = s.getEntityManagerFactory()。getCriteriaBuilder();
CriteriaQuery<Mod> cq = cb.createQuery(Mod.class);
SetJoin<Mod, ModVersion> modsVersionsesNode = cq.from(Mod.class).join(Mod_.modsVersionses);
cq.where(
cb.equal(
modsVersionsesNode.get(ModVersion_.id), versionId
)
);
List<Mod> mods = s.createQuery(cq).getResultList();
但是我仍然无法理解,如何选择不是Mod对象,而只选择ModVersion?
答案 0 :(得分:0)
解决了,感谢@JB Nizet:
Session s = sessionFactory.getCurrentSession();
CriteriaBuilder cb = s.getEntityManagerFactory().getCriteriaBuilder();
CriteriaQuery<ModVersion> cq = cb.createQuery(ModVersion.class);
Root<Mod> root = cq.from(Mod.class);
SetJoin<Mod, ModVersion> join = root.join(Mod_.modsVersionses);
cq.select(
join
);
cq.where(
cb.equal(
join.get(ModVersion_.id), versionId
)
);
List<ModVersion> mods = s.createQuery(cq).getResultList();