如何使用hibernate创建连接两个表的查询

时间:2015-07-10 05:54:33

标签: java hibernate postgresql

我有以下两个名为wc_content_definitionsimple_web_content的表,以及与这些表对应的两个pojos,即WebContentDefinitionSimpleWebContent。我使用的数据库是PostgreSQL。现在我正在尝试编写一个连接两个表的查询,只有simple_web_content表中的一个字段和wc_content_definition表中的所有字段。 我现在使用的查询是:

select wc.*,swc.content_data from wc_content_definition wc, simple_web_content swc where swc.web_content_definition_id = wc.web_content_definition_id and wc.web_content_definition_id = 491 and wc.site_id = 9 order by swc.version_number desc ;

我正在尝试实现一个hibernate查询而不是这个。与pojo中的content_data列对应的字段名称为simpleWebContentData。我目前的实施如下:

public Object[] getDocLibContentByContentId(int contentId, int siteId) throws HibernateException
{
    Session session = getCurrentSession();
    String sql = "select wc.*,swc.content_data from wc_content_definition wc, simple_web_content swc where swc.web_content_definition_id = wc.web_content_definition_id and wc.web_content_definition_id = :contentId and wc.site_id = :siteId order by swc.version_number desc ";
    SQLQuery query = session.createSQLQuery(sql);
    query.setParameter("contentId", contentId);
    query.setParameter("siteId", siteId);
    List<Object[]> results = query.list();
    if (results != null && !results.isEmpty())
    {
        return results.get(0);
    }
return null;
}

我创建了一个名为SimpleWebContentHB的新类,它有两个字段simpleWebContentDataWebContentDefinition。有什么方法可以运行正确的hibernate查询并将返回类型作为SimpleWebContentHB

1 个答案:

答案 0 :(得分:0)

一个好主意是创建HQL查询而不是SQL查询。 它允许您检索对象而不是所有列的简单值。

String hql = "select w, s.simpleWebContentData 
    from WebContentDefinition w, SimpleWebContent s 
    where ...";
Query query = session.createQuery(hql);
query.setParameter("contentId", contentId);
query.setParameter("siteId", siteId);
List<Object[]> results = query.list();
if (results != null && !results.isEmpty()) {
    WebContentDefinition w = (WebContentDefinition)results[0];
    String data = (String)results[1];
}
相关问题