JPA Criteria API group_concat usage

戏子无情 提交于 2019-11-28 01:35:28

I figured out how to do this with Hibernate-jpa-mysql:

1.) created a GroupConcatFunction class extending org.hibernate.dialect.function.SQLFunction (this is for single column group_concat for now)

public class GroupConcatFunction implements SQLFunction {

@Override
public boolean hasArguments() {
    return true;
}

@Override
public boolean hasParenthesesIfNoArguments() {
    return true;
}

@Override
public Type getReturnType(Type firstArgumentType, Mapping mapping)
        throws QueryException {
    return StandardBasicTypes.STRING;
}

@Override
public String render(Type firstArgumentType, List arguments,
        SessionFactoryImplementor factory) throws QueryException {
    if (arguments.size() != 1) {
        throw new QueryException(new IllegalArgumentException(
                "group_concat shoudl have one arg"));
    }
    return "group_concat(" + arguments.get(0) + ")";
}

}


2.) i created the CustomMySql5Dialect class extending org.hibernate.dialect.MySQL5Dialect and registered the group_concat class created in step 1
3.) On the app context, i updated the jpaVendorAdapter to use the CustomMySql5Dialect as the databasePlatform
4.) Finally to use it

criteriaBuilder.function("group_concat", String.class,
        sampleRoot.get("sampleColumnName"))

Simple solution: instead of creating the whole class, just use SQLFunctionTemplate.

new SQLFunctionTemplate(StandardBasicTypes.STRING, "group_concat(?1)")

and then register this function in your own SQL dialect (eg. in constructor)

public class MyOwnSQLDialect extends MySQL5Dialect {

  public MyOwnSQLDialect() {
    super();
    this.registerFunction("group_concat", new SQLFunctionTemplate(StandardBasicTypes.STRING, "group_concat(?1)"));
  }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!