Únase con la API de criterios JPA 2
Frecuentes
Visto 534 veces
1
I have a basic structure of 2 domain entities:
- Usuario
- 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);
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)?
¿Cómo debería hacerlo?
1 Respuestas
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);
Respondido 28 ago 12, 10:08
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas jpa jpa-2.0 or haz tu propia pregunta.
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