使用hibernate查询product的结果为Object, 并且不能转为Product

使用hibernate查询product的结果为Object, 并且不能转为Product。

版本:hibernater-5.2.6

错误代码:

public List<Product> findByPage(Integer cid, Integer begin, Integer countInPage) {
		List<Product> products = (List<Product>) this.getHibernateTemplate().execute(new HibernateCallback<List<Product>>() {

			@Override
			public List<Product> doInHibernate(Session session) throws HibernateException {
				Query query = session
						.createQuery("from Product p join p.categorySecond cs join cs.category c where c.cid=?");
				query.setFirstResult(begin);
				query.setMaxResults(countInPage);
				query.setParameter(0, cid);
				return query.getResultList();
			}
		});
		return products;
	}
若改为
Query<Product> query = session.createQuery("from Product p join p.categorySecond cs join cs.category c where c.cid=?"
,Product.class);

则报错:Cannot create TypedQuery for query with more than one return
stackoverflow中查得如下答案:

Without goind into details about how Media and Book should be modeled, I will at least explain why you get this exception.

You're doing:

em.createQuery(someJPQL, Media.class);

This means: create a query using someJPQL, and this query will return instances of theMedia entity.

But your JPQL is:

SELECT m.title, b.isbn, b.authors ...

So the query does not return entities of type Media. It returns three fields, from two different entities. There is no way your JPA engine could magically create instances of Media from these 3 columns. A query would return instances of Media if it looked like this:

select m from Media m ...

最后将代码改为如下,解决问题。

Query<Product> query = session.createQuery("select p from Product p join p.categorySecond cs join cs.category c where c.cid=?"
,Product.class);
//或 
Query<Product> query = session.createQuery("select p from Product p join p.categorySecond cs join cs.category c where c.cid=?");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值