2016-11-16 106 views
1

請建議我怎麼能寫的JPA EntityManager,createQuery對於給定的SQL查詢:我怎麼能寫JPA查詢給定的SQL查詢

select 
    sum(case when Status_2 = 'Allocated' then 1 else 0 end) as Allocated, 
    sum(case when Status_2 = 'Bench' then 1 else 0 end) as Bench 
    from userbean where Organizational_Unit = 'SIDG Java' 
    union 
select 
    sum(case when Status_2 = 'Allocated' then 1 else 0 end) as Allocated, 
    sum(case when Status_2 = 'Bench' then 1 else 0 end) as Bench 
    from userbean where Organizational_Unit = 'SIDG Microsoft' 
+0

我想提供的SQL查詢適合em.createQuery(答案) –

+0

我的意思是如何可以得到JPQL查詢EntityManager.createQuery(答案)...提供的SQL查詢以上 –

+0

從bean bean選擇bean where bean.organiz = :java或bean.organiz =:microsoft和bean.status_2 =:分配或bean.status_2。 =:長凳 - >這將返回給你列表的大小將是你的答案,老實說不明白你的意思 –

回答

2

您可以使用原生SQL查詢使用JPA:

Query q = em.createNativeQuery("select 
    sum(case when Status_2 = 'Allocated' then 1 else 0 end) as Allocated, 
    sum(case when Status_2 = 'Bench' then 1 else 0 end) as Bench 
    from userbean where Organizational_Unit = 'SIDG Java' 
    union 
select 
    sum(case when Status_2 = 'Allocated' then 1 else 0 end) as Allocated, 
    sum(case when Status_2 = 'Bench' then 1 else 0 end) as Bench 
    from userbean where Organizational_Unit = 'SIDG Microsoft'"); 

List<Object[]> result= q.getResultList(); 

// for each line retrieved 
for (Object[] currentLine : result) { 
    System.out.println("Allocated=" + currentLine[0] 
        + ", Bench=" + currentLine[1] ; 
} 

無法保證,但您可以測試。

+0

thnx這很有用 –

+0

歡迎您:) – davidxxx