JPA2.0,标准API,子查询,子查询中

JPA2.0,标准API,子查询,子查询中,jpa,subquery,criteria,Jpa,Subquery,Criteria,我多次尝试用子查询和IN表达式编写查询语句。但我从未成功过 在JPA中构建查询后,我总是得到不正确的结果。我的SQL请求如下: SELECT distinct ss.* FROM table1 ss where ss.active=1 and ss.id not in (select ia.organization_id from table2 ia where ia.is_allow = 'Y') 我的代码使用标准API如下: CriteriaQuery<T

我多次尝试用子查询和IN表达式编写查询语句。但我从未成功过

在JPA中构建查询后,我总是得到不正确的结果。我的SQL请求如下:

SELECT distinct 
  ss.*
FROM
  table1 ss  
where 
  ss.active=1 
and 
  ss.id not in (select ia.organization_id from table2 ia where ia.is_allow = 'Y')
我的代码使用标准API如下:

CriteriaQuery<Table1> cq = qb.createQuery(Table1.class);
Root<Table1> table = cq.from(Table1.class);
cq.select(table);
List<Predicate> predicateList = new ArrayList<Predicate>();

Subquery<Table1> subquery = cq.subquery(Table1.class);
Root<Table2> subroot = subquery.from(Table2.class);
subquery.select(subroot.get(Table2_.table1));
subquery.where(qb.equal(subroot.get(Table2_.isAllow.getName()), Boolean.TRUE));

predicateList.add(qb.not(qb.in(table.get(Table1_.id.getName())).value(subquery)));
if (!predicateList.isEmpty()) {
            Predicate[] array = new Predicate[predicateList.size()];
            cq.where(qb.and(predicateList.toArray(array)));
} 
cq.distinct(true);
TypedQuery<Table1> qry = entityManager.createQuery(cq);
return qry.getResultList();
为什么在该代码中“从表2 t2、表1 t1中选择1”等。。。。我在这里等你


您能帮助我吗?

如果子查询返回just和integer

select ia.organization_id from table2 ia where ia.is_allow = 'Y'
试试这个

Subquery<Integer> subquery = cq.subquery(Integer.class);
Root<Table2> subroot = subquery.from(Table2.class);
subquery.select(subroot.get("organization_id"));
subquery.where(qb.equal(subroot.get("is_allow"), Boolean.TRUE));
Subquery Subquery=cq.Subquery(Integer.class);
Root subroot=subquery.from(表2.class);
subquery.select(subroot.get(“organization_id”);
其中(qb.equal(subroot.get(“is_allow”),Boolean.TRUE));
上面的子查询应该返回将放置在in语句中的整数

那么你的逻辑就可以适用了

CriteriaQuery<Table1> cq = qb.createQuery(Table1.class);
Root<Table1> table = cq.from(Table1.class);
cq.select(table);
cq.distinct(true)
   .where(qb.not(qb.in(root.get("get")).value(subquery))
   .and(cb<Integer>equals(root.get("active"),1))
CriteriaQuery cq=qb.createQuery(表1.class);
根表=cq.from(表1.class);
选择(表);
cq.distinct(真)
.where(qb.not(qb.in(root.get(“get”)).value(子查询))
和(cbequals(root.get(“active”),1))
不确定这是否有效。 TypedQuery qry=entityManager.createQuery(cq); 如果cq“Criteria Query”是Table1.class的类型,那么TypedQuery将是 改为

TypedQuery<Table1> qry = entityManager.createQuery(cq);
TypedQuery qry=entityManager.createQuery(cq);
TypedQuery<Table1> qry = entityManager.createQuery(cq);