0

我有下表:

在此处输入图像描述

我想用以下规则形成一个查询:获取 product1,其中 Type 不是 type1 也不是 type2,Flavor 不是 flavor1。

类型可以是 type1、type 2 或 null。

我形成了这样的查询:

    CriteriaBuilder cb = this.getEntityManager().getCriteriaBuilder();
    CriteriaQuery<Product> searchQuery = cb.createQuery(Product.class);
    Root<Product> u = searchQuery.from(Product.class);

    List<Predicate> predicates = new ArrayList<Predicate>();

    predicates.add(cb.and(cb.equal(u.get("product"),"product1"),cb.isNull(u.get("type")),cb.notEqual(u.get("flavor"), "flavor1")));

问题是这个查询什么也没返回……我错过了什么吗?请注意,我的问题是指逻辑而不是语法,因为语法是通过形成返回一些虚拟结果的更简单查询来检查的。谢谢!

4

2 回答 2

1

尝试删除顶级AND谓词。将每个谓词添加到它们并从中predicates创建where

predicates.add(cb.equal(u.get("product"),"product1"))
predicates.add(cb.isNull(u.get("type")));
predicates.add(cb.notEqual(u.get("flavor"), "flavor1")); // and so on

接着

searchQuery.where(predicates.toArray(new Predicate[predicates.size()]));

最重要的是,确保您的数据库内容与您的查询匹配,因此确实应该返回一些内容:)

正如我在你的“表”中看到的那样,“类型”列中没有空值。数据库中此列中是否有任何空值?也许它在数据库中不为空,只有空字符串(这是一个很大的区别)

于 2016-03-29T11:47:24.403 回答
1

看起来很简单。我认为您缺少的是数据库列中的 NULL 不匹配任何内容,除非您准确指定它。换句话说,如果您说type not in ('type1', 'type2')没有隐含地获取空列。如果你想要他们,你必须要求他们:

使用 JPQL 查询:

List<User> c1 = em.createQuery("select u from User u where (type not in ('type1', 'type2') or type = null) and flavor != 'flavor1'", User.class).getResultList();
System.out.println(c1);

使用 CriteriaQuery:

// and with CriteriaQuery
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<User> q = cb.createQuery(User.class);
Root<User> u = q.from(User.class);
List<String> typeFilter = Arrays.asList("type1", "type2");
String flavor = "flavor1";
List<User> rs = em.createQuery(q.select(u).where( cb.or(cb.not(u.get("type").in(typeFilter)), cb.isNull(u.get("type"))), cb.notEqual(u.get("flavor"), flavor) ) ).getResultList();

这给了我以下输出:

Hibernate: select user0_.id as id1_0_, user0_.flavor as flavor2_0_, user0_.product as product3_0_, user0_.type as type4_0_ from User user0_ where (user0_.type not in  ('type1' , 'type2') or user0_.type is null) and user0_.flavor<>'flavor1'
[model.User@30263191]
Hibernate: select user0_.id as id1_0_, user0_.flavor as flavor2_0_, user0_.product as product3_0_, user0_.type as type4_0_ from User user0_ where (user0_.type not in  (? , ?) or user0_.type is null) and user0_.flavor<>?
[model.User@30263191]

有用的链接:如何查询 JPA 中值为空的列?.

于 2016-03-29T16:36:32.100 回答