2013-12-13 5 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)에서 객체를 가져 오는 것으로 생각합니다.