使用INNER JOIN,LEFT JOIN,GROUP_CONCAT和DISTINCT进行Hibernate条件查询

时间:2014-12-05 05:49:48

标签: sql hibernate join criteria-api hibernate-criteria

我在最近几个月与hibernate CRITERIA合作,我通常做R& D并从SQL创建CRITERIA查询。但这次我真的与下面的查询混淆了。从我开始的地方开始,我无法理解。

TABLE映射:

enter image description here

SQL查询:

SELECT templates.TEMPLATE_ID,
       templates.TEMPLATE_NAME,
       template_categories.CATEGORY_DESC,
       GROUP_CONCAT(DISTINCT template_code_values.Code_Value) as Code_Valuess
  FROM (client1408.templates templates
       LEFT JOIN
        client1408.template_code_mapping template_code_mapping
           ON (template_code_mapping.Template_ID = templates.TEMPLATE_ID))
       LEFT JOIN client1408.template_code_values template_code_values
          ON (template_code_mapping.Template_Code_Value_ID = template_code_values.ID)
       INNER JOIN client1408.template_categories template_categories
            ON (templates.CATEGORY_ID = template_categories.CATEGORY_ID)   
GROUP BY templates.TEMPLATE_ID

我做了什么:

使用条件

映射templatestemplate_categories
Criteria templateSearchCriteria = session.createCriteria(Templates.class).createAlias("Category", "category")
                                     .setProjection(Projections.projectionList()
                                     .add(Projections.property("Id"), "Id")
                                     .add(Projections.property("TemplateName"), "TemplateName")
                                     .add(Projections.property("Category"), "Category")
                                     .setResultTransformer(Transformers.aliasToBean(Templates.class));

剩余的内容:

  • 使用template_code_valuestemplate_code_mapping在查询LEFT JOINGROUP BY中添加更多2个表格。
  • GROUP_CONCAT,DISTINCT为额外列添加

1 个答案:

答案 0 :(得分:0)

连接在hibernate中非常简单,使用createAlias和JoinType。对于区别和分组,我们必须使用预测。请查看以下示例:

    Criteria criteria = getHibernateSession().createCriteria(A.class);
    criteria.createAlias("b", "b", JoinType.INNER_JOIN);
    criteria.createAlias("b.r", "b.r", JoinType.INNER_JOIN);
    criteria.createAlias("b.c", "b.c", JoinType.LEFT_OUTER_JOIN);
    ProjectionList projectionList = Projections.projectionList();
    // THE BELOW LINE WILL MAKE SURE COULMN a IS DISTINCT
    projectionList.add(Projections.distinct(Projections.property("a")), "a");
    // THE BELOW LINKE WILL GROUP IT BY COLUMN c
    projectionList.add(Projections.groupProperty("c"));
    // ADD all the fields that u want in projection
    criteria.setProjection(projectionList);
    criteria.setResultTransformer(Transformers.aliasToBean(A.class));
    return criteria.list();