使用INNER JOIN、LEFT JOIN、GROUP_CONCAT和DISTINCT的Hibernate条件查询

qxgroojn  于 2023-10-23  发布在  其他
关注(0)|答案(1)|浏览(107)

最近几个月我一直在使用Hibernate CRITERIA,我通常会从SQL中进行研发和创建CRITERIA查询。但这次我真的很困惑下面的查询。从我开始的地方我不能理解。

表Map:

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

我做了什么:

Map的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));

剩余内容:

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

von4xj4u1#

在Hibernate中,Joins非常简单,使用jungle和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();

相关问题