JPQL select query for ElementCollection

Zaw Than oo picture Zaw Than oo · Feb 21, 2014 · Viewed 13.9k times · Source

I have the following entity with enum collection. I would like to search the user with an enum parameter.
The user might have multiple permission. When I search the users with the parameter like Permission.APPROVE, there may be one or more user who have that permission. How can I write JPQL query?

User.java

@Entity
....
public class User implements Serializable {

    @ElementCollection(targetClass = Permission.class)
    @Enumerated(EnumType.STRING)
    @CollectionTable(name = "USER_PERMISSION", joinColumns = @JoinColumn(name = "PERMISSION", referencedColumnName = "ID")) 
    private List<Permission> permisssionList;
}

Permission.java

public enum Permission {
    REGISTER, APPROVE, REJECT, CONFIRM;
}

How to write ?

public List<User> findUserList(Permission permission) { 
    Query q = em.createQuery(.....);
    result = q.getResultList();
}

Answer

Camilo picture Camilo · Feb 21, 2014

@Embeddable and @CollectionTable are just a simple way to map One To Many relationships, they can not be queried directly nor persisted, but certainly can be joined, do it like you would with any One To Many relationship:

"select user from User user join user.permissionList p where p = :permission"

and pass the enum as a regular parameter