【问题标题】:SEPARATOR keyword not working properly in Hibernate FormulaSEPARATOR 关键字在休眠公式中无法正常工作
【发布时间】:2015-12-17 18:22:54
【问题描述】:

我有以下 Hibernate forumla 查询,我可以在 mysql 工作台中执行。

select group_concat(distinct t.column_1_name SEPARATOR ', ') from table_name t and t.fk_record_id = record_id

在使用 Hibernate 执行此查询时,hibernate 会将父表附加到 SEPRATOR 关键字,如下面的查询所示。

select group_concat(distinct t.column_1_name parent_table.SEPARATOR ', ') from table_name t and t.fk_record_id = record_id

这里 hibernate 不将 SEPRATOR 视为关键字。有人对此有任何想法吗?

【问题讨论】:

    标签: mysql hibernate


    【解决方案1】:

    您可以添加SEPARATOR 作为关键字。实现你自己的DialectResolver 并将关键字小写添加到生成的方言中:

    public class MyDialectResolver implements DialectResolver {
    
        public Dialect resolveDialect(DialectResolutionInfo info) {
            for (Database database : Database.values()) {
                Dialect dialect = database.resolveDialect(info);
                if (dialect != null) {
                    dialect.getKeywords().add("separator");
                    return dialect;
                }
            }
    
            return null;
        }
    }
    

    5.2.13 / 5.3.0 之前的 Hibernate 版本也是如此:

    public class MyDialectResolver extends StandardDialectResolver {
    
        protected Dialect resolveDialectInternal(DatabaseMetaData metaData) throws SQLException {
            Dialect dialect = super.resolveDialectInternal(metaData);
            dialect.getKeywords().add("separator");
            return dialect;
        }
    
    }
    

    然后您必须告诉 Hibernate 使用您的方言解析器。例如,在 JPA 中,您可以在 persistence.xml 中执行此操作:

    <persistence>
      <persistence-unit>
        ...
        <property name="hibernate.dialect_resolvers" value="mypackage.MyDialectResolver"/>
      </persistence-unit>
    </persistence>
    

    这同样适用于其他方言中的聚合函数。例如,在 Oracle 中,WITHIN 关键字缺失。

    还有另一种选择,它更独立于数据库(我更喜欢)。创建以下SQLFunction

    public class ListAggFunction implements SQLFunction {
    
        /**
         * The pattern that describes how the function is build in SQL.
         *
         * Replacements:
         * {path} - is replaced with the path of the list attribute
         * {separator} - is replaced with the separator (defaults to '')
         * {orderByPath} - is replaced by the path that is used for ordering the elements of the list
         */
        private String pattern;
    
        /**
         * Creates a new ListAggFunction definition which uses the ANSI SQL:2016 syntax.
         */
        public ListAggFunction() {
            this("LISTAGG(DISTINCT {path}, {separator}) WITHIN GROUP(ORDER BY {orderByPath})");
        }
    
        /**
         * Creates a new ListAggFunction definition which uses a database specific syntax.
         *
         * @param pattern  The pattern that describes how the function is build in SQL.
         */
        public ListAggFunction(String pattern) {
            this.pattern = pattern;
        }
    
        public Type getReturnType(Type firstArgumentType, Mapping mapping) throws QueryException {
            return StringType.INSTANCE;
        }
    
        public boolean hasArguments() {
            return true;
        }
    
        public boolean hasParenthesesIfNoArguments() {
            return true;
        }
    
        public String render(Type firstArgumentType, List arguments,
                SessionFactoryImplementor factory) throws QueryException {
            if (arguments.isEmpty() || arguments.size() > 3) {
                throw new IllegalArgumentException(
                        "Expected arguments for 'listagg': path [, separator [, order by path]]");
            }
    
            String path = (String) arguments.get(0);
            String separator = arguments.size() < 2 ? "''" : (String) arguments.get(1);
            String orderByPath = arguments.size() <= 2 ? path : (String) arguments.get(2);
    
            return StringUtils.replaceEach(this.pattern, new String[] { "{path}", "{separator}", "{orderByPath}" },
                    new String[] { path, separator, orderByPath });
        }
    
    }
    

    你可以在 DialectResolver 中注册这个函数,方法和上面的关键字一样:

     if ("MySQL".equals(info.getDatabaseName()) || "H2".equals(info.getDatabaseName())) {
       dialect.getFunctions().put("listagg", new ListAggFunction("GROUP_CONCAT(DISTINCT {path} ORDER BY {orderByPath} SEPARATOR {separator})"));
     } else {
       dialect.getFunctions().put("listagg", new ListAggFunction());
     }
    

    现在您可以在 JPQL / HQL / Criteria 查询中使用此功能,而无需考虑方言的语法:

     SELECT e.group, listagg(e.stringProperty, ', ') FROM Entity e GROUP BY e.group
    

    【讨论】:

    • @shadow 不工作是什么意思?我将它用于 Hibernate 4.1 和 5.0。您能否创建一个带有详细解释的新问题?
    • @TobiasLiefke 我尝试过这种方式,但有些方法无法通过,hibernate 仍在为 INTERVAL 关键字添加前缀。
    • 正如我所说:请打开一个新问题,添加您所做的确切内容,包括任何日志消息(例如,您可以在方言解析器中编写日志消息,以检查您是否正确包含它)并添加 exact Hibernate 版本。虽然我认为它与版本无关,但它有助于重现您的问题。
    • @Shadow 我刚才看到你说的是INTERVAL(大写):你需要添加小写的关键字。
    • 在hibernate 5.2.17版本中,StandardDialectResolver没有resolveDialectInternal方法,所以不能覆盖
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多