I have a User
and UserRole
model, that looks like this:
User.java
public class User {
@Id
private Long id;
private String name;
@ManyToOne
@JoinColumn(name = "ROLE_ID")
private UserRole role;
//All other properties...
}
UserRole.java
public class UserRole {
@Id
private Long id;
private String name;
//All other properties...
}
I need to be able to fetch all users that have role = 1L
.
I'm able to do this with JPQL, as follows:
TypedQuery<SystemUser> query = entityManager.createQuery("Select u from User u left join u.role r where r.id=?1", User.class);
query.setParameter(1, roleId);
return query.getResultList();
However, for some reason, I would like to know if I can achieve the exact same thing Without JPQL , by simply using the JPA Criteria API.
Can anyone help me out?
Thanks, Sriram Sridharan
Try below code,
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<User> criteriaQuery = builder.createQuery(User.class);
Root<User> root = criteriaQuery.from(User.class);
criteriaQuery.where(builder.equal(root.get("role").get("id"), roleId));
return entityManager.createQuery(criteriaQuery)..getResultList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.