Java 将嵌套sql查询转换为jpa/hibernate
我们使用jpa/hibernate,但是我们有一些像这样的本地查询Java 将嵌套sql查询转换为jpa/hibernate,java,mysql,sql,hibernate,jpa,Java,Mysql,Sql,Hibernate,Jpa,我们使用jpa/hibernate,但是我们有一些像这样的本地查询 SELECT cp1.id AS customerbookid FROM customerbook cp1 INNER JOIN customer cu ON cu.id = cp1.customerid WHERE cp1.autoRenew='Y' AND cp1.endTime < now() AND (SELECT cp2.customerid FROM customerbook c
SELECT cp1.id AS customerbookid
FROM customerbook cp1
INNER JOIN customer cu ON cu.id = cp1.customerid
WHERE cp1.autoRenew='Y'
AND cp1.endTime < now()
AND
(SELECT cp2.customerid
FROM customerbook cp2
WHERE cp1.customerid=cp2.customerid
AND cp2.startTime > now()
) IS NULL
是否可以将其转换为jpa?我猜您的实体之间的关系可能是这样的:
EntityManager em;
Query q = em.createQuery("select cp1 FROM customerbook as cp1
where cp1.customerid in (select cu.id from customer as cu)
and cp1.autoRenew='Y'
and cp1.endTime < :now
and cp1.customerid not in (
select cp2.customerid FROM customerbook cp2 where cp2.startTime > :now
)");
q.setParameter("now", Calendar.getInstance().getTime());
// return List<CustomerBook>
q = em.createQuery("select cp1.id FROM customerbook as cp1
where cp1.customerid in (select cu.id from customer as cu)
and cp1.autoRenew='Y'
and cp1.endTime < :now
and cp1.customerid not in (
select cp2.customerid FROM customerbook cp2 where cp2.startTime > :now
)");
q.setParameter("now", Calendar.getInstance().getTime());
// return List<Long>
100%在对象中重新考虑查询是很重要的。SQL旨在设计表、列/字段,但使用JPQL,您认为从数据库实体或POJO中获取对象是为了实现JPQL吗?是的,JPQL。我们可以将hql与jpa一起使用吗?jpa是一种API。Hibernate是JPA实现之一。HQL是特定于Hibernate的语言。您需要提供类和表之间的映射。
EntityManager em;
Query q = em.createQuery("select cp1 FROM customerbook as cp1
where cp1.customerid in (select cu.id from customer as cu)
and cp1.autoRenew='Y'
and cp1.endTime < :now
and cp1.customerid not in (
select cp2.customerid FROM customerbook cp2 where cp2.startTime > :now
)");
q.setParameter("now", Calendar.getInstance().getTime());
// return List<CustomerBook>
q = em.createQuery("select cp1.id FROM customerbook as cp1
where cp1.customerid in (select cu.id from customer as cu)
and cp1.autoRenew='Y'
and cp1.endTime < :now
and cp1.customerid not in (
select cp2.customerid FROM customerbook cp2 where cp2.startTime > :now
)");
q.setParameter("now", Calendar.getInstance().getTime());
// return List<Long>