0

I need to query an object that contains a list.

@Entity @Table(name = "userAccount") public class UserAccounts implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name = "email", nullable = false, unique = true) private String username; @Column(name = "hash", nullable = false, length = 60) private String hash; @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "userID"), inverseJoinColumns = @JoinColumn(name = "roleID")) private List<Role> roles; @Enumerated(EnumType.ORDINAL) private Status status; //getters and setters } 

I need to get objects that contains role "ROLE_USER". how can I achieve that using CriteriaBuilder?

 CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<UserAccounts> cq = cb.createQuery(UserAccounts.class); Root<UserAccounts> ua = cq.from(UserAccounts.class); 

What Should I put here?

// cq.where(cb.and(cq.equals(ua.get("roles")), // cq.equals(ua.get("status"), Status.ACTIVE))); 

TIA.

1 Answer 1

1

The equivalent JPQL could be like this

SELECT ua FROM UserAccount ua JOIN ua.roles r WHERE r.name = :roleName 

so the Criteria would be something like

Join<UserAccounts, Role> roleRoot = ua.join(UserAccounts_.roles); roleRoot.alias("r"); ParameterExpression<String> param = qb.parameter(String.class); cq.where(roleRoot.get(Role_.name).equals(param)); 
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, using ua.join(UserAccounts_.roles); requires me to change roles to public. i don't think i should change that to public though.
No it doesn't require public. This is the static metamodel class! You can use the equivalent String based getter if you insist on using Strings
Finally got it to work. turns out I was mising Hibernate-metamodel-generator.jar. Thank You So Much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.