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

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...