I have a basic structure of 2 domain entities:
- User
- UserDetails
Where a User holds (has a) UserDetails, and UseDetails has String userName.
Using JPA criteria API I would like to commit a simple query which loads a User by a given user-name.
In code, I would like it to look more or less like this:
public User findByUsername(String userName) {
CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<User> c = qb.createQuery(User.class);
Root<User> user = c.from(User.class);
Predicate condition = qb.equal(user.get(User_.userDetails.getuserName()), userName);
c.where(condition);
TypedQuery<User> q = entityManager.createQuery(c);
List<User> result = q.getResultList();
if (result.isEmpty()) {
return null;
}
return result.get(0);
}
But this doesn't work since getuserName() cannot be found under User_.userDetails. I guess this is not the way to do that, maybe I need to implement a Join between those tables (User and UserDetails)?
How should I do it?