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

来源:互联网 发布:阿里云ecs传文件 编辑:程序博客网 时间:2024/05/16 09:26

使用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>>() {@Overridepublic 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
原创粉丝点击