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));
3
  • Hi, using ua.join(UserAccounts_.roles); requires me to change roles to public. i don't think i should change that to public though.
    – pat3ck029
    Commented Jan 10, 2016 at 9:10
  • 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 Commented Jan 10, 2016 at 9:18
  • Finally got it to work. turns out I was mising Hibernate-metamodel-generator.jar. Thank You So Much!
    – pat3ck029
    Commented Jan 10, 2016 at 9:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.