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

Bev*_*vor 8 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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

@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";
.
.
.
Run Code Online (Sandbox Code Playgroud)

如果我使用不会导致结果的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();
Run Code Online (Sandbox Code Playgroud)

axt*_*avt 23

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

NoResultException在没有返回任何行时抛出,但在您的情况下sum返回一行具有null值的行.从JPA 2.0规范:

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

如果你想0取而代之null,请使用coalesce:

select coalesce(sum(p.value), 0) ...
Run Code Online (Sandbox Code Playgroud)