hibernate 查询时报错: No entity found for query

先贴上代码:

	public Account getAccountByName(String name) {
		// TODO Auto-generated method stub
		String hql = "select a from Account a where name =?";
		Query query = null;
		query = entityManager.createQuery(hql);
		Account account = (Account) query.setParameter(1, name)
				.getSingleResult();
		return account;
	}


错误的原因:使用了getSingleResult()方法,当查询时,如果数据库中确实有数据,不会报错;但是 当数据库中没有数据时,则无法getSingleResult,所以会报:

No entity found for query 这个错。在网上查到资料介绍:getSingleResult的源码里有这样一句: @throws EntityNotFoundException if there is no result;

解决方法:用其他方式代替getSingleResult()

原文地址:https://www.cnblogs.com/wyang0126/p/5039961.html