jpa異常No entity found for query問題解決
jpa是什么?
JPA全稱Java Persistence API.JPA通過JDK 5.0注解或XML描述對象-關(guān)系表的映射關(guān)系,并將運行期的實體對象持久化到數(shù)據(jù)庫中。
JPA 是 JCP 組織發(fā)布的 Java EE 標(biāo)準(zhǔn)之一,因此任何聲稱符合 JPA 標(biāo)準(zhǔn)的框架都遵循同樣的架構(gòu),提供相同的訪問API,這保證了基于JPA開發(fā)的企業(yè)應(yīng)用能夠經(jīng)過少量的修改就能夠在不同的JPA框架下運行
JPA是需要Provider來實現(xiàn)其功能的,Hibernate就是JPA Provider中很強的一個,應(yīng)該說無人能出其右。從功能上來說,JPA就是Hibernate功能的一個子集。Hibernate 從3.2開始,就開始兼容JPA。Hibernate3.2獲得了Sun TCK的JPA(Java Persistence API) 兼容認證。
出現(xiàn)的問題
工作中使用了jpa來持久化數(shù)據(jù),調(diào)試的時候拋了這樣的異常No entity found for query,找不到查詢的實體,導(dǎo)致這個問題主要是使用了getSingleResult()這個方法返回一個實體,下面我們看下源碼找下原因
getSingleResult實現(xiàn)源碼
@SuppressWarnings({ "unchecked", "RedundantCast" }) public X getSingleResult() { try { final Listresult = query.list(); if ( result.size() == 0 ) { NoResultException nre = new NoResultException( "No entity found for query" ); getEntityManager().handlePersistenceException( nre ); throw nre; } else if ( result.size() > 1 ) { final SetuniqueResult = new HashSet(result); if ( uniqueResult.size() > 1 ) { NonUniqueResultException nure = new NonUniqueResultException( "result returns more than one elements" ); getEntityManager().handlePersistenceException( nure ); throw nure; } else { return uniqueResult.iterator().next(); } } else { return result.get( 0 ); } } catch (QueryExecutionRequestException he) { throw new IllegalStateException(he); } catch( TypeMismatchException e ) { throw new IllegalArgumentException(e); } catch (HibernateException he) { throw getEntityManager().convert( he ); } }
分析解決問題
從源碼實現(xiàn)中的if判斷我們可以看到,如果你使用了getSingleResult()來返回實體,結(jié)果為0或者大于1都會拋出異常。除非你能肯定你查詢的實體存在且只有一個,不然一般返回實體還是建議使用getResultList()取結(jié)果集,然后做相關(guān)處理,如:
Listlist=entityManager().createQuery("SELECT o FROM User o where o.userId=?1", User.class) .setParameter(1, userId) .getResultList(); if(list!=null && list.size()!=0){ return list.get(0); } return null ;
先判斷結(jié)果集大小,根據(jù)結(jié)果集大小再確定是返回null還是取第一條
以上就是jpa異常No entity found for query問題解決的詳細內(nèi)容,更多關(guān)于jpa異常No entity found for query的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Intellij idea下使用不同tomcat編譯maven項目的服務(wù)器路徑方法詳解
今天小編就為大家分享一篇關(guān)于Intellij idea下使用不同tomcat編譯maven項目的服務(wù)器路徑方法詳解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-02-02SpringBoot對靜態(tài)資源的映射規(guī)則詳解解讀
這篇文章主要介紹了SpringBoot對靜態(tài)資源的映射規(guī)則詳解解讀,在Spring Boot中,映射規(guī)則是用來定義URL與控制器方法之間的映射關(guān)系的,通過映射規(guī)則,可以將特定的URL請求映射到相應(yīng)的控制器方法上,從而實現(xiàn)請求的處理和響應(yīng)的返回,需要的朋友可以參考下2023-10-10