1

I have a basic structure of 2 domain entities:

  1. User
  2. 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?

1 Answer 1

0

I can't try it now, but I think you must do something like:

Predicate condition = qb.equal(user.get(User_.userDetails).get(UserDetails_.userName), userName);
3
  • This looks nice, I can try it out but I wonder if this is the best\right way of doing it..
    – forhas
    Aug 28, 2012 at 10:47
  • @YogevLidor: well, I'm pretty sure you must achieve this using "paths". I'm not sure if my syntax is 100% correct.
    – sinuhepop
    Aug 28, 2012 at 10:51
  • I'll take a look into "paths" later, for now it seems to work out just fine. Thanks!
    – forhas
    Aug 28, 2012 at 11:12

Your Answer

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

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