【问题标题】:How to use custom data base dialect in spring data?spring data中如何使用自定义数据库方言?
【发布时间】:2019-05-28 05:40:42
【问题描述】:

我需要避免休眠中的 db2 方言中的一些错误。 我使用 spring data + gradle (几个模块) + kotlin 我创建了我的自定义方言

DB2zOSDialect : DB2Dialect() 

并尝试将其添加到 application.properties

spring:
  jpa:
    properties:
      hibernate:
        dialect: com.my.config.DB2zOSDialect 

但是使用 DB2Dialect 实现数据连续性

我尝试了相同的代码,但使用了 java + maven + 相同的 spring 数据,它的工作原理。

所以,我不知道为什么 spring 数据没有使用我的自定义方言。

有没有办法给spring数据添加方言?

【问题讨论】:

    标签: java kotlin spring-data-jpa spring-data


    【解决方案1】:

    所以,我自己解决了问题,但我仍然不知道为什么行为不同。

    我设置

    spring.jpa.database = default
    

    并添加

    spring.jpa.properties.hibernate.dialect_resolvers = com.my.config.CustomDialectResolver
    

    并写了简单的解析器

    class CustomDialectResolver : DialectResolver {
    
        override fun resolveDialect(info: DialectResolutionInfo?): Dialect {
            return DB2zOSDialect()
        }
    }
    

    【讨论】:

      【解决方案2】:
      public class CustomDialectResolver implements DialectResolver {
          private static final Map<String, Class<? extends Dialect>> DIALECT_BY_NAME = new HashMap<>();
      
          static {
              DIALECT_BY_NAME.put("Oracle", Oracle10gDialect.class);
              DIALECT_BY_NAME.put("PostgreSQL", PostgreSQL10Dialect.class);
              DIALECT_BY_NAME.put("HSQL Database Engine", HSQLDialect.class);
              DIALECT_BY_NAME.put("H2", H2Dialect.class);
          }
      
          @Override
          public Dialect resolveDialect(DialectResolutionInfo dialectResolutionInfo) {
              final String name = dialectResolutionInfo.getDatabaseName();
              return lookupDialect(name);
          }
      
          private Dialect lookupDialect(String databaseName) {
              Class<? extends Dialect> dialectClass = DIALECT_BY_NAME.get(databaseName);
              if (dialectClass == null) {
                  log.warn("Could not find dialect for database name {}", databaseName);
                  return null;
              }
              try {
                  return dialectClass.getDeclaredConstructor().newInstance();
              } catch (Exception e) {
                  log.error("Error while init dialect for database name {} - {}", databaseName, e.getLocalizedMessage());
                  return null;
              }
          }
      }
      

      接下来

      spring.jpa.properties.hibernate.dialect_resolvers=CustomDialectResolver
      

      【讨论】:

      • 这个答案可以通过解释整体方法/代码在做什么来改进。
      猜你喜欢
      • 2017-06-18
      • 1970-01-01
      • 2018-02-01
      • 2015-05-10
      • 2016-10-20
      • 1970-01-01
      • 2013-08-09
      • 2018-10-06
      • 2017-09-19
      相关资源
      最近更新 更多