叙述
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;
}
小结
其实有时候在使用某一个方法的时候我们应该先去了解它的实现
感谢您的阅读~~