문제

I have three data models: Profile, User and UserGroup. Profile has @ManyToOne relation with User (which created this Profile), User has @ManyToMany with List. I need to get Profiles created by any user of the same groups that user created this profile is part of. In JPQL it looks like that and it seems to work properly:

SELECT p FROM Profile p
LEFT JOIN p.user u
LEFT JOIN u.groups g
WHERE g.id in :groups

What I need to do is implement the same functionality but by CriteriaQuery.

CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Profile> criteria = builder.createQuery(Profile.class);
Root<Profile> root = criteria.from(Profile.class);
Join<Profile, Group> joinGroup = root.join("user").join("groups");

criteria.select(root).where(joinGroup.in(groups))
// groups is a method parameter with a type of List<Group>

How to write a correct Join in this scenario?

도움이 되었습니까?

해결책

Join<Profile, Group> joinGroup = root.join("user", JoinType.LEFT)
    .join("groups", JoinType.LEFT);

다른 팁

Better to use alias in create criteria like

Criteria plan= dbSession.createCriteria(Profile.class,"<aliasname>")                                            .createAlias("<aliasname>.<columnName>", "<aliasname1>")
.createAlias("<aliasname1>.<columnName>", "<aliasname2>")                                           .add(Restrictions.eq("<aliasname2>.cloumn", groups object));

For reference -hibernate - createCriteria or createAlias?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top