抱歉我的英文。开始处理javaee并且不太了解如何进行一些操作。我有2个表类别和帖子。在帖子中有字段 id , namecat 和索引。在帖子中,字段 id , namePost ,文字, idCat 。如果表格类别索引= 1.那么属于此类别的所有帖子都必须带到主页。在请求中,它看起来像这样:
id = select * from category where index=1 //Here we learn how to id category i want displayed.
select * from post where idcat=id //and here all put
但我无法弄清楚如何在代码中执行此操作。在那里:
public Collection getPostFromCatId() {
List<Category> category= null;
Session session = null;
try{
session = HibernateUtil.getSessionFactory().openSession();
SQLQuery q = (SQLQuery) session.createSQLQuery("
select * from category where index=1"); //get all category i want displayed. How to get here id and paste the following query?
q.addEntity(Category.class);
category= q.list();
} catch(Exception e) { outputError(e);
} finally{ closeSession(session); }
return category;
}
答案 0 :(得分:1)
首先,我建议您在一个查询而不是两个查询中检索数据,如下所示:
select p.* from post p
join category c on c.id=p.idCat and c.index=1
然后在hibernate请求中你应该使用Post实体,因为你要查询帖子,而不是类别
q.addEntity(Post.class);