我想知道如何在JPA中进行查询,其中的内容不在第三个表格中#34;负责与许多人建立关系。
示例:
SELECT id FROM A WHERE id NOT IN (SELECT id FROM A_B WHERE idB = @id)
在这种情况下,我有表A,表B和relationShip manytomany A_B
我尝试使用CriteriaQuery和子查询,但它没有用。实际上,它没有返回任何结果。
有人对此案有任何例子吗?
答案 0 :(得分:0)
我得到了我的解决方案!
我不知道它是否完全正确,所以,如果有人看到错误,请告诉我。
由JPA创建的结束查询变为:
select maingroup0_.GroupId as GroupId1_, maingroup0_.idGroupAttendanceType as idGroupA2_1_, maingroup0_.name as name1_ from TUnPbxGroup maingroup0_ where maingroup0_.GroupId not in (select maingroup1_.GroupId from TUnPbxGroup maingroup1_ inner join THolidayGroup listholida2_ on maingroup1_.GroupId=listholida2_.GroupId inner join THoliday holiday3_ on listholida2_.IdHoliday=holiday3_.IdHoliday where holiday3_.IdHoliday=2)
代码:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<MainGroup> query = cb.createQuery(MainGroup.class);
Root<MainGroup> root = query.from(MainGroup.class);
query.select(root);
Subquery<Long> subquery = query.subquery(Long.class);
Root<MainGroup> subRoot = subquery.from(MainGroup.class);
subquery.select(subRoot.<Long>get("id"));
Join<Holiday, Holiday> maingroups = subRoot.join("listHolidays");
subquery.where(cb.equal(maingroups.get("id"), holidayId));
query.where(cb.not(cb.in(root.get("id")).value(subquery)));
TypedQuery<MainGroup> typedQuery = em.createQuery(query);
List<MainGroup> result = typedQuery.getResultList();