I am having problems with JPA2/Hibernate 4.2/MySQL 5.1/Java 6
I have the following class, User, which has an attribute, Set<Role>
, where Role is an enum. Here is the class:
@Entity
public class User
{
private static final long serialVersionUID = 1L;
@ElementCollection(fetch=FetchType.EAGER)
@Enumerated(value=EnumType.STRING)
protected Set<Role> roles;
// .. other stuff
}
public enum Role { ADMIN, OPERATOR, ... }
I have tried creating both a CriteriaQuery and a JPQL query for this but for some reason both are returning an empty list each time, even if the role is present.
Here is my code for the criteria query:
CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<User> query = builder.createQuery(User.class);
Root<User> root = query.from(User.class);
query.where(builder.isMember( Role.ADMIN, root.<Set<Role>>get( "roles" ) ) );
List<User> result = getEntityManager().createQuery(query).getResultList();
Here is the JPQL I am creating:
String jpql = "SELECT * FROM com.mypackage.user.User WHERE (:roles1 MEMBER OF roles))";
Query query = em.createQuery(jpql);
query.setParameter( "roles1", Role.ADMIN );
List result = em.getResultList();
The users table contains a single user with all roles, but neither of these are returning any results. I need to have both the JPA and JPQL versions for the work I am doing. Please help!