需要帮助编写CriteriaQuery“in”谓词

时间:2011-08-28 01:32:53

标签: jpa-2.0

我有一个查询,我一直试图变成CriteraQuery,但我不知道如何编码查询的“IN”术语。

可行的JPA查询如下所示:

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

它所使用的实体看起来像这样:

@Entity
public class User {

    @Id private Integer id;

    @OneToMany private List<UserData> data;

    ... }

引用的实体是

@Entity
public class UserData {

    @Id private Long id;

    private String key;

    private String data;

    ... }

预期的结果(NamedQuery工作)是拉出在其数据属性列表中具有一些匹配的所有用户实体。出于某种原因,CriteraQuery语法逃脱了我的直觉。有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

我认为用户应该是唯一的吗? 那么JP QL版本没有相当旧的时尚IN:

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

同样通过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);