Hibernate:如何使用CONCAT和GROUP_CONCAT

如何在HQL查询中使用CONCAT()GROUP_CONCAT()

关于concat :它与MySQL中的工作方式完全相同(它连接字符串,它不是聚合函数)。

您可以将group_concat作为sql函数添加到您的配置中。 这样你就可以假设底层数据库知道这个函数,并且你将程序绑定到MySQL

 import org.hibernate.cfg.Configuration; import org.hibernate.dialect.function.StandardSQLFunction; import org.hibernate.type.StringType; // ... myConf.addSqlFunction("group_concat", new StandardSQLFunction("group_concat", new StringType())); 

您还指出函数的输出是一个字符串。 如果没有这个,当你group_concat数字字段时,Hibernate会假设结果也是数字和崩溃。

方言的子类

 registerFunction("group_concat", new StandardSQLFunction("group_concat", Hibernate.STRING)); 

或使用SQLFunctionTemplate

如果您使用的是createSQLQuery,请将该列的addScalar用作String。

 SQLQuery query = sessionObj.createSQLQuery("select group_concat(column1,column2) as mycolumn from some table group by someThing"); query.addScalar("mycolumn ", Hibernate.STRING);