2013-12-13 27 views
0

我們使用jpa/hibernate,但是我們有一些像這樣的本地查詢。將嵌套的sql查詢轉換爲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 cp2 
    WHERE cp1.customerid=cp2.customerid 
    AND cp2.startTime > now() 
) IS NULL 

映射

@Entity 
    @Table(name = "customerbook") 
    public class CustomerBook{ 

@Id 
@Column(name = "id") 
@GeneratedValue(strategy = GenerationType.AUTO) 
private Long id; 

@Column(name = "customerId") 
private long customerId; 

@Column(name = "startTime") 
private Timestamp startTime; 

@Column(name = "endTime") 
private Timestamp endTime; 

@Column(name = "autoRenew") 
private Character autoRenew; 
    } 

    @Entity 
    @Table(name = "customer") 
    public class customer{ 
    @Id 
    @Column(name = "id") 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 
    } 

是否有可能將其轉換爲JPA?

+0

您是否指向JPQL? –

+0

是JPQL。我們可以用jpa使用hql嗎? – redfox26

+0

'JPA'是一個'API'。 'Hibernate'是JPA **實現**之一。 'HQL'是Hibernate特定的語言。 –

回答

0

我猜實體之間的關係的,但可能是這個樣子:

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)