JPA:TypedQuery有时会返回null而不是NoResultException

时间:2012-04-24 09:39:26

标签: jpa hql jpa-2.0

通常我使用NoResultException返回一个“空”对象,例如一个空的错误列表或新的BigInteger(“0”),如果我没有得到TypedQuery的结果。现在事实证明,这有时不起作用。突然getSingleResult()返回null而不是导致NoResultException,我不明白为什么。看这个例子:

public BigInteger pointsSumByAccountId(long accountId)
{
    try
    {
        TypedQuery<BigInteger> pointsQuery = entityManager.createNamedQuery(Points.SumByAccountId, BigInteger.class);
        pointsQuery.setParameter(Points.AccountIdParameter, accountId);

        return pointsQuery.getSingleResult();
    }
    catch (NoResultException e)
    {
        return new BigInteger("0");
    }
}

实体的重要部分......

@NamedQueries({@NamedQuery(name = "Points.sumByAccountId", query = "select sum(p.value) from Points p where p.validFrom <= current_timestamp() and p.validThru >= current_timestamp() and p.account.id = :accountId")})
public class Points
{
    private static final long serialVersionUID = -15545239875670390L;

    public static final String SumByAccountId = Points.class.getSimpleName() + ".sumByAccountId";
    public static final String AccountIdParameter = "accountId";
.
.
.

如果我使用不会导致结果的accountId,我会得到null而不是NoResultException。任何想法为什么会这样?甚至TypedQuery的Javadoc也说它必须返回NoResultException:

/**
 * Execute a SELECT query that returns a single result.
 *
 * @return the result
 *
 * @throws NoResultException if there is no result
 * @throws NonUniqueResultException if more than one result
 * @throws IllegalStateException if called for a Java
 * Persistence query language UPDATE or DELETE statement
 * @throws QueryTimeoutException if the query execution exceeds
 * the query timeout value set and only the statement is
 * rolled back
 * @throws TransactionRequiredException if a lock mode has
 * been set and there is no transaction
 * @throws PessimisticLockException if pessimistic locking
 * fails and the transaction is rolled back
 * @throws LockTimeoutException if pessimistic locking
 * fails and only the statement is rolled back
 * @throws PersistenceException if the query execution exceeds
 * the query timeout value set and the transaction
 * is rolled back
 */
X getSingleResult();

1 个答案:

答案 0 :(得分:22)

对我来说,这看起来是正确的行为。

如果没有返回任何行,则抛出

NoResultException,但sum在您的情况下只返回一行null的行。从JPA 2.0规范:

  

如果使用SUM,AVG,MAX或MIN,并且没有聚合函数可以使用的值   应用时,聚合函数的结果为NULL。

如果您想获得0而不是null,请使用coalesce

select coalesce(sum(p.value), 0) ...