微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – 什么时候可以抛出NoSuchResult

我继承了一个系统,其中有一个相当奇怪的错误,可能每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;博士,我是否想念noresultException以及在什么具体情况下可以抛出它?此外,如果没有与查询匹配的行.

解决方法:

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐