Necesita ayuda para codificar un predicado CriteriaQuery "in"

I have a query that I have been trying to turn into a CriteraQuery, but I don't get how to code the "IN" term of the query.

The JPA Query that works looks like this:

@NamedQuery(name = "User.fromSearchID",
    query = "SELECT q FROM User q,"
    + " IN (q.data) AS s WHERE s.data LIKE :search"
    + " ORDER BY q.id")

And the entity that it works on looks like this:

@Entity
public class User {

    @Id private Integer id;

    @OneToMany private List<UserData> data;

    ... }

And the referenced entity is

@Entity
public class UserData {

    @Id private Long id;

    private String key;

    private String data;

    ... }

The intended result (the NamedQuery works) is to pull out all User entities that have some match in their list of data attributes. For some reason the CriteraQuery syntax escapes my intuition. Any help?

preguntado el 28 de agosto de 11 a las 01:08

1 Respuestas

I assume users should be unique? Then JP QL version without rather old fashion IN is:

String searchArgument = "data1";
String query = " SELECT DISTINCT(u) " +
               " FROM User u JOIN  u.data ud " +
               " WHERE ud.data LIKE :search ORDER BY u.id";
List<User> result =em.createQuery(query, User.class).
                setParameter("search", searchArgument).getResultList();

And same via Criteria API:

String searchArgument = "data1";
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<User> cq = cb.createQuery(User.class);
Root<User> user = cq.from(User.class);

Predicate dataLike = cb.like(user.join("data").<String>get("data"),
                             cb.parameter(String.class, "search"));
cq.distinct(true).select(user)
    .where(dataLike)
    .orderBy(cb.asc(user.get("id")));

TypedQuery<User> findUniqueUserByUserDataData = em.createQuery(cq);
findUniqueUserByUserDataData.setParameter("search", searchArgument);

Respondido el 19 de Septiembre de 11 a las 19:09

This is a good answer so I will mark it. In the end I used a Map collection and a MapJoin to do this, so the distinct sub-clause wasn't needed. - AlanObject

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