2013-08-30 137 views
0

無法從NamedQuery獲取整數?JPA Eclipselink NamedQuery vs查詢COUNT

@NamedQuery( name = Comm.COUNTLIKEVALUEINHOLDER, 
     query = "SELECT COUNT(c.id) " + 
      "FROM Comm c " + 
      "JOIN c.element e " + 
      "WHERE c.search1 LIKE :search1 " + 
      "AND c.search2 = :search2 " + 
      "AND c.type = :type " + 
      "AND e.holderelement = :holder" 
    ) 

Object q = em.createNamedQuery(Comm.COUNTLIKEVALUEINHOLDER) 
    .setParameter("search1", "bla%") 
    .setParameter("search2", "bla2") 
    .setParameter("type", t) 
    .setParameter("holder", h) 
    .getSingleResult(); 

我從一個COUNT聚集中得到一個實體,而不是一個Long或Integer。

但是我在這裏得到了一個Integer。這完全是同一個查詢。

Object i = em.createQuery("SELECT COUNT(c.id) " + 
    "FROM Comm c " + 
    "JOIN c.element e " + 
    "WHERE c.search1 LIKE :search1 " + 
    "AND c.search2 = :search2 " + 
    "AND c.type = :type " + 
    "AND e.holderelement = :holder") 
    .setParameter("search1", "bla%") 
    .setParameter("search2", "bla2") 
    .setParameter("type", t) 
    .setParameter("holder", h) 
    .getSingleResult(); 

有沒有人有想法?

回答

1

簡短回答:

em.createQuery用於創建動態查詢。返回類型由QL語言的返回類型(上例中的「SELECT COUNT(c.id)」)確定。

em.createNamedQuery用於創建靜態查詢。返回類型可以鑄造類型,例如:

Object q = em.createNamedQuery(Comm.COUNTLIKEVALUEINHOLDER) 
    .setParameter("search1", "bla%") 
    .setParameter("search2", "bla2") 
    .setParameter("type", t) 
    .setParameter("holder", h) 
    .getSingleResult(); 

Integer count = (Integer) q; 

` 還看到:http://www.objectdb.com/java/jpa/query/api