2016-11-16 61 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