我最近几个月一直在使用休眠CRITERIA,通常我会进行研发并通过SQL创建CRITERIA查询。但是这一次我真的与下面的查询混淆。从我的起点开始,我无法理解。
表映射:
<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9ZYzNGRi5wbmcifQ==” alt =“在此处输入图像描述”>
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
我做了什么:
用条件映射templates
和template_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_values
和template_code_mapping
在查询LEFT JOIN
和GROUP BY
中添加更多表2。联接在休眠中非常简单,请使用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();