【问题标题】:When can NoSuchResult be thrown什么时候可以抛出 NoSuchResult
【发布时间】:2018-07-04 20:24:36
【问题描述】:

我继承的系统有一个相当奇怪的错误,可能每 6 个月发生一次,应用程序突然失去对数据库数据的跟踪。

系统有 2 台服务器冗余,这些服务器计划同时运行相同的功能。它们都向函数获取相同的输入数据,并且都与相同的 postgres 数据库通信,但是两台机器上的行为不同。

正在执行的函数正在调用数据库并检查是否存在具有输入参数提供的指定 id 的行,如果存在则执行A(),否则执行B()

问题是一台服务器执行A(),另一台服务器执行B()。我到处搜索,没有代码写入该表或从中删除。因此,出于所有原因,我认为它们都应该执行相同的代码。

这是从数据库中获取的代码:

@PersistenceContext(unitName = "backend-persistence")
private EntityManager em;
public Optional<OfferEntity> getOfferFromOfferId(final long offerId, final String countryAlias, final String langauageAlias) {

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<OfferEntity> cq = cb.createQuery(OfferEntity.class);
    Root<OfferEntity> from = cq.from(OfferEntity.class);
    cq.select(from);
    cq.where(cb.and(cb.equal(from.get(OfferEntity_.offerId), offerId),
            cb.equal(from.get(OfferEntity_.country), countryAlias),
            cb.equal(from.get(OfferEntity_.language), langauageAlias)));

    try {

        return Optional.of(em.createQuery(cq).getSingleResult());
    } catch (NoResultException nre) {

        return Optional.empty();
    }
}

我从其中一个服务器中得到一个空的可选选项,而不是另一个。

所以我想作为一个 tl;dr,我是否误解了 NoResultException 以及在什么具体情况下可以抛出它?此外,如果没有与查询匹配的行。

【问题讨论】:

  • @DN1 我非常清楚,但定义“如果没有结果”。我认为这很模棱两可,因为我可能是“没有与查询匹配的行”或“数据库抛出错误,所以没有结果”或其他可能的东西
  • 没有任何含糊之处。 JPA 将来自 getSingleResult 的缺失结果视为异常情况这一事实源于这样一个事实,即它意味着与必然产生恰好一个结果的查询一起使用(例如聚合查询)。 “根据我的业务逻辑可能永远不会有多个结果”的查询不适合 getSingleResult,您应该真正使用 getResultList。
  • 我假设在这种情况下应该使用getResultList,因为它可能返回一个或零个结果?
  • 是的。话虽这么说,NoResultException 当然并不代表数据库抛出异常的情况。您遇到的可能是 Postgres 的 JDBC 驱动程序的错误,或者可能(我认为不太可能)缓存配置错误。

标签: java postgresql hibernate jpa


【解决方案1】:

只有当你确定你会得到一个结果时,你才能使用 getSingleResult()。在所有其他情况下,您必须使用 getResultList()

来自 javax.persistence.Query getSingleResult() 的 API 文档:

java.lang.Object getSingleResult()

Execute a SELECT query that returns a single untyped result.

Returns:
the result

Throws:
NoResultException - if there is no result
NonUniqueResultException - if more than one result
IllegalStateException - if called for a Java Persistence query language UPDATE or DELETE statement
QueryTimeoutException - if the query execution exceeds the query timeout value set and only the statement is rolled back
TransactionRequiredException - if a lock mode has been set and there is no transaction
PessimisticLockException - if pessimistic locking fails and the transaction is rolled back
LockTimeoutException - if pessimistic locking fails and only the statement is rolled back
PersistenceException - if the query execution exceeds the query timeout value set and the transaction is rolled back

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-17
    • 2015-05-25
    • 2011-03-22
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 2021-09-05
    相关资源
    最近更新 更多