0

无法从 NamedQuery 中取回整数???

@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 Aggregat 得到一个实体,而不是一个 Long 或 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();

有人有想法吗?

4

1 回答 1

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

于 2013-12-08T15:59:16.740 回答