前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >No entity found for query异常之jpa

No entity found for query异常之jpa

作者头像
kl博主
发布2023-11-18 09:19:04
1560
发布2023-11-18 09:19:04
举报
文章被收录于专栏:kl的专栏kl的专栏

jpa是什么?

JPA全称Java Persistence API.JPA通过JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。

JPA 是 JCP 组织发布的 Java EE 标准之一,因此任何声称符合 JPA 标准的框架都遵循同样的架构,提供相同的访问API,这保证了基于JPA开发的企业应用能够经过少量的修改就能够在不同的JPA框架下运行

JPA是需要Provider来实现其功能的,Hibernate就是JPA Provider中很强的一个,应该说无人能出其右。从功能上来说,JPA就是Hibernate功能的一个子集。Hibernate 从3.2开始,就开始兼容JPA。Hibernate3.2获得了Sun TCK的JPA(Java Persistence API) 兼容认证。

出现的问题

工作中使用了jpa来持久化数据,调试的时候抛了这样的异常No entity found for query,找不到查询的实体,导致这个问题主要是使用了getSingleResult()这个方法返回一个实体,下面我们看下源码找下原因

下面是getSingleResult实现源码

代码语言:javascript
复制
	@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 );
		}
	}

分析解决问题

从源码实现中的if判断我们可以看到,如果你使用了getSingleResult()来返回实体,结果为0或者大于1都会抛出异常。除非你能肯定你查询的实体存在且只有一个,不然一般返回实体还是建议使用getResultList()取结果集,然后做相关处理,如:

代码语言:javascript
复制
 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 ;

先判断结果集大小,根据结果集大小再确定是返回null还是取第一条

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-04-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档