Frage

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?

War es hilfreich?

Lösung

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

Andere Tipps

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?

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top