Únase con la API de criterios JPA 2

I have a basic structure of 2 domain entities:

  1. Usuario
  2. Detalles de usuario

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);
    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)?

¿Cómo debería hacerlo?

preguntado el 28 de agosto de 12 a las 10:08

1 Respuestas

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);

Respondido 28 ago 12, 10:08

This looks nice, I can try it out but I wonder if this is the best\right way of doing it.. - porhas

@YogevLidor: well, I'm pretty sure you must achieve this using "paths". I'm not sure if my syntax is 100% correct. - sinuhepop

I'll take a look into "paths" later, for now it seems to work out just fine. Thanks! - porhas

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.