看起来很简单。我认为您缺少的是数据库列中的 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 中值为空的列?.