我在mysql中使用group_concat编写了一个查询,如
SELECT c1,group_concat(c2) FROM table1 where sno in(1,4,8,10) group by c1;给出了我的预期结果。
现在,我想使用hibernate条件编写相同的查询。
发布于 2014-10-07 11:29:34
简单的答案是No
为什么?
Hibernate只支持多个数据库中使用的通用函数/语法。Microsoft中没有任何group_concat函数,也可能在其他数据库中。
解决方案:
您必须将其作为简单的SQL查询执行。
发布于 2020-02-13 03:13:20
您有两个选项(取决于您的hibernate版本)。
覆盖方言类任何hibernate版本
您需要对您的方言进行子类以添加group_concat()
在应用程序中的某个位置创建以下类(例如util包)
package com.myapp.util;
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.type.StandardBasicTypes;
public class MySQLCustomDialect extends MySQL5Dialect {
public MySQLCustomDialect() {
super();
registerFunction("group_concat",
new StandardSQLFunction("group_concat",
StandardBasicTypes.STRING));
}
}将下列属性添加到application.properities中
spring.jpa.properties.hibernate.dialect = com.myapp.util.MySQLCustomDialect
只使用JPA元数据生成器Contributor hibernate 5.2.18或更高版本
创建以下类,记住添加包&解析导入。
public class SqlFunctions implements MetadataBuilderContributor {
@Override
public void contribute(MetadataBuilder metadataBuilder) {
metadataBuilder.applySqlFunction( "group_concat",
new StandardSQLFunction( "group_concat",
StandardBasicTypes.STRING ) ); }
}保持原样的方言属性
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.metadata_builder_contributor = com.myapp.util.SqlFunctions发布于 2014-10-06 05:47:12
请参阅以下代码片段
Criteria cr = session.createCriteria(table1.class);
cr.add(Restrictions.in("sno",snoarray));
criteria.setProjection("c1");
criteria.setProjection(Projections.groupProperty("c1"));https://stackoverflow.com/questions/26210036
复制相似问题