JPA getSingleResult() 错误处理NoResultException:No entity found for query NonUniqueResultException

叙述

javax.persistence.Query getSingleResult(),只能返回单个值,但是最近在在使用的时候它总是报错:NoResultException:No entity found for query或者NonUniqueResultException!一开始遇到这个问题的时候很是郁闷!

报错原因:

1、没有查询到结果
2、查询到了多条结果

解决思路:

/**
     * Execute a SELECT query that returns a single untyped 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 other than
     *         <code>NONE</code> has been set and there is no transaction
     *         or the persistence context has not been joined to the 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 
     */
    Object getSingleResult();

看了上面的代码我相信大家就都明白了吧,(学好英语很重要哟)

如何进行错误处理:

**1、当确定有且只有一条记录的时候才使用它
2、对getSingleResult()进行异常处理**

try{
            Integer reserveCount = query.getSingleResult();
            return reserveCount;
        } catch (NoResultException nre) {
            return 0;
        } catch (NonUniqueResultException nure) {
            return 0;
        }

小结

其实有时候在使用某一个方法的时候我们应该先去了解它的实现
感谢您的阅读~~

评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值