如何使用具有多个连接的SQL查询并使用hibernate进行计数

时间:2017-12-11 12:52:43

标签: java sql postgresql hibernate

我有一个使用Spring MVC的Java hibernate网络应用程序。我正在尝试使用SQL join从多个表中检索数据,并使用单个查询基于少数条件计算行数。我使用的当前SQL如下:

SELECT (s.school_id, u.first_name, u.last_name, u.username, u.email, p.plan_name, s.start_date, s.end_date,(SELECT COUNT(*) FROM c_school_user t WHERE t.user_type = 'TA' and t.school_id = s.school_id), (SELECT COUNT(*) FROM c_school_user t WHERE t.user_type = 'PA' and t.school_id = s.school_id), (SELECT COUNT(*) FROM c_school_user t WHERE t.user_type = 'ST' and t.school_id = s.school_id)) FROM c_school s inner join u_user u on s.user_created = u.user_id inner join c_plan p on s.current_plan = p.plan_Id where s.application_id = 1 and s.site_id = 1;

此查询为我返回所需的结果。我试图在我的方法中使用与SQL Query相同的查询来使用hibernat获得结果,如下所示:

public List<Object[]> getBuyersInformation(int applicationId, int siteId) throws HibernateException 
{

    Session session = getCurrentSession();
    Query query = session.createSQLQuery("SELECT (s.school_id, u.first_name, u.last_name, u.username, u.email, p.plan_name, s.start_date, s.end_date, s.subscription_price, (SELECT COUNT(*) FROM c_school_user t WHERE t.user_type = 'TA' and t.school_id = s.school_id), (SELECT COUNT(*) FROM c_school_user t WHERE t.user_type = 'PA' and t.school_id = s.school_id), (SELECT COUNT(*) FROM c_school_user t WHERE t.user_type = 'ST' and t.school_id = s.school_id)) FROM c_school s inner join u_user u WHERE s.user_created = u.user_id inner join c_plan p WHERE s.current_plan = p.plan_Id where s.application_id = :applicationId and s.site_id = :siteId");
    query.setParameter("applicationId", applicationId);
    query.setParameter("siteId", siteId);
    List<Object[]> results = query.list();
    if(results != null && results.size() > 0)
    {
    return results;
    }
    return null;
}

如果我在没有连接的情况下使用SQL查询,我会得到正确的结果,但是当使用当前查询时,我会得到以下异常:

org.hibernate.MappingException: No Dialect mapping for JDBC type: 1111

我是用户Postgres数据库。有没有什么办法可以将所需的结果作为对象列表或自定义类。我试图使用这个单一的SQL,因为我的数据库可能包含数千行信息,并且拆分此查询将导致如此多的数据库调用,最终会降低系统速度。有没有办法使用hibernate执行具有多个连接和计数的SQL查询。

1 个答案:

答案 0 :(得分:3)

由于列列表周围的括号,您的查询只返回单个列,该列是包含所选列作为字段的匿名记录。

Postgres select (a,b)select a,b不同。表达式(a,b)(也称为“行构造函数”)creates an anonymous record包含两个字段。

删除那些无用的括号,你的查询应该可以正常工作。为列表达式添加别名也是一个好主意:

类似的东西:

SELECT s.school_id, u.first_name, u.last_name, u.username, u.email, p.plan_name, s.start_date, s.end_date,
       (SELECT COUNT(*) FROM c_school_user t WHERE t.user_type = 'TA' and t.school_id = s.school_id) as ta_count, 
       (SELECT COUNT(*) FROM c_school_user t WHERE t.user_type = 'PA' and t.school_id = s.school_id) as pa_count, 
       (SELECT COUNT(*) FROM c_school_user t WHERE t.user_type = 'ST' and t.school_id = s.school_id) as st_count
FROM c_school s 
  inner join u_user u on s.user_created = u.user_id 
  inner join c_plan p on s.current_plan = p.plan_Id 
where s.application_id = 1 and s.site_id = 1;