您的位置:首页 > 移动开发 > Objective-C

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

2017-01-15 14:59 483 查看

使用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 the
Media
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=?");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐