gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:20:56 26 4
gpt4 key购买 nike

通常,我使用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();

最佳答案

对我来说,这似乎是正确的行为。

当不返回任何行时,将抛出NoResultException,但在您的情况下sum会返回仅一个带有null值的行。根据JPA 2.0规范:

If SUM, AVG, MAX, or MIN is used, and there are no values to which the aggregate function can be applied, the result of the aggregate function is NULL.



如果要获取 0而不是 null,请使用 coalesce:
select coalesce(sum(p.value), 0) ...

关于JPA:TypedQuery有时返回null而不是NoResultException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10295347/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com