使用JPA标准API在select子句中进行子查询
正如在标题中一样,我正在尝试在select子句中插入一个子查询,如以下简单SQL: 从项目中选择id、名称、从项目中选择计数* 这显然只是一个模拟查询,只是为了说明我的观点。关键是获取查询返回的每个项目的最后一张发票 我试过这个: CriteriaBuilder cb=em.getCriteriaBuilder; CriteriaQuery c=cb.createTupleQuery; 根项=c.fromItem.class; Subquery scont=c.subqueryLong.class; 根sarticolo=scont.fromItem.class; scont.selectcb.countsitem; c、 multiselectitem.getid、item.getnome、Scont; 查询q=em.createQueryc; q、 setMaxResults100; 列表结果=q.getResultList; 四重t:结果{ System.out.printlnt.get0+,+t.get1+,+t.get2; } 但我只得到: java.lang.IllegalStateException: 子查询不能出现在select子句中使用JPA标准API在select子句中进行子查询,jpa,select,subquery,criteria,Jpa,Select,Subquery,Criteria,正如在标题中一样,我正在尝试在select子句中插入一个子查询,如以下简单SQL: 从项目中选择id、名称、从项目中选择计数* 这显然只是一个模拟查询,只是为了说明我的观点。关键是获取查询返回的每个项目的最后一张发票 我试过这个: CriteriaBuilder cb=em.getCriteriaBuilder; CriteriaQuery c=cb.createTupleQuery; 根项=c.fromItem.class; Subquery scont=c.subqueryLong.clas
我怎样才能得到类似的结果 JPA不支持select子句中的子查询
您需要更改查询以便不使用select子句中的子查询、执行多个查询或使用本机SQL查询。JPA现在支持select子句中的子查询 编辑:
JPA2.1 JPQL BNF支持select子句中的子查询,即使它不是必需的。据我所知,Eclipselink支持这一点,Hibernate也在5.1中进行了测试。它在JPA2.1和Hibernate 5.0中得到了支持。您只需在主查询的multiselect中将getSelection添加到子查询参数中
c.multiselect(item.get("id"),item.get("nome"), scount.getSelection());
看看这个工作示例:
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<NotificationInfo> cq = builder.createQuery(NotificationInfo.class); //wrapper class
Root<Notification> n = cq.from(Notification.class); //root entity
//Subquery
Subquery<Long> sqSent = cq.subquery(Long.class);
Root<NotificationUser> sqSentNU = sqSent.from(NotificationUser.class);
sqSent.select(builder.count(sqSentNU));
sqSent.where(
builder.equal(sqSentNU.get(NotificationUser_.notification), n), //join subquery with main query
builder.isNotNull(sqSentNU.get(NotificationUser_.sendDate))
);
cq.select(
builder.construct(
NotificationInfo.class,
n.get(Notification_.idNotification),
n.get(Notification_.creationDate),
n.get(Notification_.suspendedDate),
n.get(Notification_.type),
n.get(Notification_.title),
n.get(Notification_.description),
sqSent.getSelection()
)
);
em.createQuery(cq).getResultList();
您需要合并子查询结果:
Expression<ResultType> expression = criterioaBuilder.coalesce(subquery, criteriaBuilder.literal((ResultType) defaultResult);
query.select(expression);
你的答案中“now”一词的确切含义是什么版本的JPA规范?now的确切含义是JPA的最新版本,即2.1这是一个非常有用的技巧。我在别的地方都没找到。在任何文档或教程中是否也提到了这一点?我相信您的答案是正确的,但是您能否写出NotficationInfo和NotificationUser之间的关系,以及它所完成的SQL语句是什么?它看起来不像:选择id、creationDate、suspendedDate、type、title、description、SELECT countcase(当我不从通知中跟踪通知时)