如何将 JPA 2.1 的 CriteriaBuilder.function 与 MySQL 的 "GROUP_CONCAT" 一起使用?

How do I use JPA 2.1's CriteriaBuilder.function with MySQL's "GROUP_CONCAT"?

我正在使用 JPA 2.1、Hibernate 4.3。6.Final 和 MySQL 5.5。我读到 JPA 2.1 支持调用本机 DB 函数,但我无法弄清楚如何调用 MySQL 的“GROUP_CONCAT”。我有以下代码……

final CriteriaBuilder builder = m_entityManager.getCriteriaBuilder();
final CriteriaQuery criteria = StringUtils.equals(orderByCol, "organization") ? builder.createQuery(Tuple.class) : builder.createQuery(User.class);
final Root<User> user = criteria.from(User.class);
    …
final SetJoin<User, Organization> orgsJoin = orderByRoot.join(User_.organizations, JoinType.LEFT);
final Expression groupConcatExpr = builder.function("GROUP_CONCAT", String.class, orgsJoin.get(Organization_.name));
 criteria.select(builder.tuple(user, groupConcatExpr))
                    .groupBy(user);
…           
  orderByExpr = orgsJoin.get(Organization_.name);
  criteria.orderBy(orderByAscending == null || orderByAscending == true ? builder.asc(orderByExpr) : builder.desc(orderByExpr));

但我得到以下异常……

java.lang.IllegalStateException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode 
 \-[METHOD_CALL] MethodNode: 'function (GROUP_CONCAT)'
    +-[METHOD_NAME] IdentNode: 'GROUP_CONCAT' {originalText=GROUP_CONCAT}
    \-[EXPR_LIST] SqlNode: 'exprList'
       \-[DOT] DotNode: 'organizati2_.NAME' {propertyName=name,dereferenceType=PRIMITIVE,getPropertyPath=name,path=generatedAlias1.name,tableAlias=organizati2_,className=org.mainco.subco.organization.domain.Organization,classAlias=generatedAlias1}
      +-[ALIAS_REF] IdentNode: 'organizati2_.id' {alias=generatedAlias1, className=org.mainco.subco.organization.domain.Organization, tableAlias=organizati2_}
      \-[IDENT] IdentNode: 'name' {originalText=name}

    at org.hibernate.hql.internal.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:174)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.useSelectClause(HqlSqlWalker.java:924)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:692)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:665)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:249)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:167)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1800)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:568)
    at org.hibernate.jpa.criteria.CriteriaQueryImpl.buildCompiledQuery(CriteriaQueryImpl.java:336)
    at org.hibernate.jpa.criteria.compile.CriteriaCompiler.compile(CriteriaCompiler.java:147)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:736)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
    at com.sun.proxy.$Proxy68.createQuery(Unknown Source)
    at org.mainco.subco.user.repo.UserDaoImpl.findUsers(UserDaoImpl.java:120)
    at org.mainco.subco.user.repo.UserDao2IT.testFindOrderByOrganizationAsc(UserDao2IT.java:624)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access[=14=]0(ParentRunner.java:42)
    at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:184)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

对于 JPA 中的用户 GROUP_CONCAT,步骤如下:

1.) 创建一个 class "GroupConcatFunction" 如下:

import java.util.List;
import org.hibernate.QueryException;
import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.Type;

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;
    }

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

2.) 我们将创建一个自定义方言,它将包含在方言中注册我们的 group_concat 函数的代码:

import org.hibernate.dialect.MySQL5Dialect;

public class CustomMySql5Dialect extends MySQL5Dialect {

    public CustomMySql5Dialect() {
        super();
        registerFunction("group_concat", new GroupConcatFunction());
    }
}

3.) 用您的自定义方言替换 persistence.xml 中的方言定义:

<property name="hibernate.dialect"    value="<<pkg name>>.CustomMySql5Dialect" />

现在,您将能够在条件查询中使用它。