Hibernate: how to use CONCAT and GROUP_CONCAT

2019-01-14 23:33发布

How can I use CONCAT() and GROUP_CONCAT() in HQL queries?

3条回答
来,给爷笑一个
2楼-- · 2019-01-14 23:41

subclass the dialect

and

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

or use SQLFunctionTemplate

查看更多
smile是对你的礼貌
3楼-- · 2019-01-14 23:50

If you are using createSQLQuery, use addScalar to that column as String.

SQLQuery query = sessionObj.createSQLQuery("select group_concat(column1,column2) as mycolumn from some table group by someThing");
query.addScalar("mycolumn ", Hibernate.STRING);
查看更多
虎瘦雄心在
4楼-- · 2019-01-14 23:59

About concat: it works exactly the same way as it does in MySQL (it concatenates strings, it is not an aggregate function).

You can add group_concat as an sql function to your configuration. This way you assume that the underlaying DB knows this function, and you tie your program to 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()));

You also indicate that the output of the function is a string. Without this when you group_concat numeric fields Hibernate will assume the result also to be numeric and crash.

查看更多
登录 后发表回答