Browse Source

反序列化忽略多余字段,修改多数据源配置方式,移除了单数据源时多余文件,统一配置factory

NorthLan 7 years ago
parent
commit
b15327917c

+ 9 - 52
zen-orm/src/main/kotlin/com/gxzc/zen/orm/config/MultipleDataSourceConfig.kt

@@ -1,14 +1,14 @@
 package com.gxzc.zen.orm.config
 
 import com.alibaba.druid.pool.xa.DruidXADataSource
-import com.atomikos.icatch.jta.UserTransactionImp
-import com.atomikos.icatch.jta.UserTransactionManager
 import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean
 import com.baomidou.mybatisplus.spring.boot.starter.MybatisPlusProperties
 import com.baomidou.mybatisplus.spring.boot.starter.SpringBootVFS
 import com.gxzc.zen.orm.DynamicMultipleDataSource
 import com.gxzc.zen.orm.contants.DSKey
+import org.apache.ibatis.plugin.Interceptor
 import org.slf4j.LoggerFactory
+import org.springframework.beans.factory.ObjectProvider
 import org.springframework.beans.factory.annotation.Autowired
 import org.springframework.beans.factory.annotation.Qualifier
 import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
@@ -19,8 +19,6 @@ import org.springframework.context.annotation.Bean
 import org.springframework.context.annotation.Configuration
 import org.springframework.context.annotation.DependsOn
 import org.springframework.context.annotation.Primary
-import org.springframework.transaction.PlatformTransactionManager
-import org.springframework.transaction.jta.JtaTransactionManager
 import javax.sql.DataSource
 import javax.sql.XADataSource
 
@@ -30,20 +28,16 @@ import javax.sql.XADataSource
  * @author NorthLan at 2018/1/29
  */
 @Configuration
-@EnableConfigurationProperties(MybatisPlusProperties::class)
-@ConditionalOnProperty(prefix = "orm", name = ["multi-datasource-enable"], havingValue = "true", matchIfMissing = true)
+// @ConditionalOnProperty(prefix = "orm", name = ["multi-datasource-enable"], havingValue = "true", matchIfMissing = true)
 class MultipleDataSourceConfig {
     companion object {
         private val logger = LoggerFactory.getLogger(MultipleDataSourceConfig::class.java)
     }
 
-    init{
+    init {
         logger.info("MultipleDataSourceConfig initializing...")
     }
 
-    @Autowired
-    private lateinit var properties: MybatisPlusProperties
-
     @Bean(DSKey.DSKEY_SYS + "druid")
     @ConfigurationProperties(prefix = "datasource.sys")
     fun dataSourceSysDruid(): XADataSource {
@@ -76,48 +70,11 @@ class MultipleDataSourceConfig {
     @Bean
     fun multipleDataSource(@Qualifier(DSKey.DSKEY_SYS) dataSourceSys: DataSource,
                            @Qualifier(DSKey.DSKEY_BUSINESS) dataSourceBus: DataSource): DynamicMultipleDataSource {
-        return DynamicMultipleDataSource().also {
-            it.setTargetDataSources(mapOf(
-                    Pair(DSKey.DSKEY_SYS, dataSourceSys),
-                    Pair(DSKey.DSKEY_BUSINESS, dataSourceBus)))
-            it.setDefaultTargetDataSource(dataSourceSys)
-        }
-    }
-
-//    @Bean("tx1")
-//    fun platformTransactionManager(): PlatformTransactionManager {
-//        return JtaTransactionManager().also {
-//            it.userTransaction = UserTransactionImp()
-//            it.transactionManager = UserTransactionManager()
-//        }
-//    }
-
-//    @Bean
-//    fun transactionManager(dynamicMultipleDataSource: DynamicMultipleDataSource): DataSourceTransactionManager {
-//        return DataSourceTransactionManager(dynamicMultipleDataSource)
-//    }
-
-    @Bean
-    @Primary
-    fun mybatisSqlSessionFactoryBean(dynamicMultipleDataSource: DynamicMultipleDataSource): MybatisSqlSessionFactoryBean {
-        return MybatisSqlSessionFactoryBean().also {
-            it.setDataSource(dynamicMultipleDataSource)
-            it.vfs = SpringBootVFS::class.java
-            it.setConfiguration(properties.configuration)
-            it.setGlobalConfig(properties.globalConfig?.convertGlobalConfiguration())
-            it.setMapperLocations(properties.resolveMapperLocations())
+        return DynamicMultipleDataSource().apply {
+            setTargetDataSources(mapOf(
+                    DSKey.DSKEY_SYS to dataSourceSys,
+                    DSKey.DSKEY_BUSINESS to dataSourceBus))
+            setDefaultTargetDataSource(dataSourceSys)
         }
     }
-
-//    override fun annotationDrivenTransactionManager(): PlatformTransactionManager {
-//        return transactionManager()
-//    }
-
-//    @Bean
-//    fun sqlSessionFactory(dynamicMultipleDataSource: DynamicMultipleDataSource): SqlSessionFactory {
-//        return SqlSessionFactoryBean().let {
-//            it.setDataSource(dynamicMultipleDataSource)
-//            it.`object`
-//        }
-//    }
 }

+ 2 - 2
zen-orm/src/main/kotlin/com/gxzc/zen/orm/config/MybatisPlusConfig.kt

@@ -14,8 +14,8 @@ import org.springframework.transaction.annotation.EnableTransactionManagement
  * @author NorthLan at 2018/1/30
  */
 @Configuration
-@MapperScan("com.gxzc.zen.api.*.mapper")
-@EnableTransactionManagement(order = 2)
+@MapperScan("com.gxzc.zen.api.*.mapper*")
+@EnableTransactionManagement
 class MybatisPlusConfig {
 
 //    /**

+ 133 - 0
zen-orm/src/main/kotlin/com/gxzc/zen/orm/config/MybatisPlusFactoryConfig.kt

@@ -0,0 +1,133 @@
+package com.gxzc.zen.orm.config
+
+import com.baomidou.mybatisplus.MybatisConfiguration
+import com.baomidou.mybatisplus.MybatisXMLLanguageDriver
+import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean
+import com.baomidou.mybatisplus.spring.boot.starter.ConfigurationCustomizer
+import com.baomidou.mybatisplus.spring.boot.starter.MybatisPlusProperties
+import com.baomidou.mybatisplus.spring.boot.starter.SpringBootVFS
+import com.gxzc.zen.orm.DynamicMultipleDataSource
+import com.gxzc.zen.orm.contants.DSKey
+import org.apache.ibatis.mapping.DatabaseIdProvider
+import org.apache.ibatis.plugin.Interceptor
+import org.slf4j.LoggerFactory
+import org.springframework.beans.factory.ObjectProvider
+import org.springframework.beans.factory.annotation.Qualifier
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
+import org.springframework.boot.context.properties.EnableConfigurationProperties
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+import org.springframework.context.annotation.Primary
+import org.springframework.core.io.ResourceLoader
+import org.springframework.util.Assert
+import org.springframework.util.CollectionUtils
+import org.springframework.util.ObjectUtils
+import org.springframework.util.StringUtils
+import javax.annotation.PostConstruct
+import javax.sql.DataSource
+
+/**
+ * Mybatis bean工厂配置
+ * @author NorthLan
+ * @date 2018/3/27
+ * @url https://noahlan.com
+ */
+@Configuration
+@EnableConfigurationProperties(MybatisPlusProperties::class)
+class MybatisPlusFactoryConfig {
+    companion object {
+        private val logger = LoggerFactory.getLogger(MybatisPlusFactoryConfig::class.java)
+    }
+
+    private var interceptors: Array<Interceptor>? = null
+    private var properties: MybatisPlusProperties? = null
+    private var resourceLoader: ResourceLoader? = null
+    private var databaseIdProvider: DatabaseIdProvider? = null
+    private var configurationCustomizers: List<ConfigurationCustomizer>? = null
+
+    init {
+        logger.info("MybatisPlusFactoryConfig initializing...")
+    }
+
+    constructor(properties: MybatisPlusProperties,
+                interceptorsProvider: ObjectProvider<Array<Interceptor>>,
+                resourceLoader: ResourceLoader,
+                databaseIdProvider: ObjectProvider<DatabaseIdProvider>,
+                configurationCustomizersProvider: ObjectProvider<List<ConfigurationCustomizer>>) {
+        this.properties = properties
+        this.interceptors = interceptorsProvider.ifAvailable
+        this.resourceLoader = resourceLoader
+        this.databaseIdProvider = databaseIdProvider.ifAvailable
+        this.configurationCustomizers = configurationCustomizersProvider.ifAvailable
+    }
+
+    @PostConstruct
+    fun checkConfigFileExists() {
+        Assert.state(properties != null, "MybatisPlusProperties is null.")
+        if (this.properties!!.isCheckConfigLocation && StringUtils.hasText(this.properties?.configLocation)) {
+            val resource = this.resourceLoader?.getResource(this.properties?.configLocation)
+            Assert.state(resource != null && resource.exists(), "Cannot find config location: " + resource
+                    + " (please add config file or check your Mybatis configuration)")
+        }
+    }
+
+    @Bean
+    @Primary
+    @ConditionalOnProperty(prefix = "orm", name = ["multi-datasource-enable"], havingValue = "true", matchIfMissing = true)
+    fun dynamic(dataSource: DynamicMultipleDataSource): MybatisSqlSessionFactoryBean {
+        return setFactoryBean(dataSource)
+    }
+
+    @Bean
+    @ConditionalOnProperty(prefix = "orm", name = ["multi-datasource-enable"], havingValue = "false", matchIfMissing = true)
+    fun single(@Qualifier(DSKey.DSKEY_SYS) dataSource: DataSource): MybatisSqlSessionFactoryBean {
+        return setFactoryBean(dataSource)
+    }
+
+    private fun setFactoryBean(dataSource: DataSource): MybatisSqlSessionFactoryBean {
+        return MybatisSqlSessionFactoryBean().apply {
+            setDataSource(dataSource)
+            vfs = SpringBootVFS::class.java
+            if (StringUtils.hasText(properties?.configLocation)) {
+                setConfigLocation(resourceLoader?.getResource(properties?.configLocation))
+            }
+            var configuration = properties?.configuration
+            if (configuration == null && !StringUtils.hasText(properties?.configLocation)) {
+                configuration = MybatisConfiguration()
+            }
+            if (configuration != null && !CollectionUtils.isEmpty(configurationCustomizers)) {
+                configurationCustomizers?.forEach {
+                    it.customize(configuration)
+                }
+            }
+            configuration?.setDefaultScriptingLanguage(MybatisXMLLanguageDriver::class.java)
+            setConfiguration(properties?.configuration)
+            if (properties?.configurationProperties != null) {
+                setConfigurationProperties(properties?.configurationProperties)
+            }
+            if (!ObjectUtils.isEmpty(interceptors)) {
+                setPlugins(interceptors)
+            }
+            if (databaseIdProvider != null) {
+                this.databaseIdProvider = databaseIdProvider
+            }
+            if (StringUtils.hasLength(properties?.typeAliasesPackage)) {
+                setTypeAliasesPackage(properties?.typeAliasesPackage)
+            }
+            // 自定义枚举
+            if (StringUtils.hasLength(properties?.typeEnumsPackage)) {
+                setTypeEnumsPackage(properties?.typeEnumsPackage)
+            }
+            if (StringUtils.hasLength(properties?.typeHandlersPackage)) {
+                setTypeHandlersPackage(properties?.typeHandlersPackage)
+            }
+            if (!ObjectUtils.isEmpty(properties?.resolveMapperLocations())) {
+                setMapperLocations(properties?.resolveMapperLocations())
+            }
+            if (!ObjectUtils.isEmpty(properties?.globalConfig)) {
+                setGlobalConfig(properties?.globalConfig?.convertGlobalConfiguration())
+            }
+        }
+    }
+
+}

+ 0 - 69
zen-orm/src/main/kotlin/com/gxzc/zen/orm/config/SingleDataSourceConfig.kt

@@ -1,69 +0,0 @@
-package com.gxzc.zen.orm.config
-
-import com.alibaba.druid.pool.xa.DruidXADataSource
-import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean
-import com.baomidou.mybatisplus.spring.boot.starter.MybatisPlusProperties
-import com.baomidou.mybatisplus.spring.boot.starter.SpringBootVFS
-import com.gxzc.zen.orm.contants.DSKey
-import org.slf4j.LoggerFactory
-import org.springframework.beans.factory.annotation.Autowired
-import org.springframework.beans.factory.annotation.Qualifier
-import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
-import org.springframework.boot.context.properties.ConfigurationProperties
-import org.springframework.boot.context.properties.EnableConfigurationProperties
-import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean
-import org.springframework.context.annotation.Bean
-import org.springframework.context.annotation.Configuration
-import org.springframework.context.annotation.DependsOn
-import org.springframework.context.annotation.Primary
-import javax.sql.DataSource
-import javax.sql.XADataSource
-
-/**
- *
- * @author NorthLan
- * @date 2018/3/24
- * @url https://noahlan.com
- */
-@Configuration
-@EnableConfigurationProperties(MybatisPlusProperties::class)
-@ConditionalOnProperty(prefix = "orm", name = ["multi-datasource-enable"], havingValue = "false")
-class SingleDataSourceConfig {
-    companion object {
-        private val logger = LoggerFactory.getLogger(MultipleDataSourceConfig::class.java)
-    }
-
-    init {
-        logger.info("SingleDataSourceConfig initializing...")
-    }
-
-    @Autowired
-    private lateinit var properties: MybatisPlusProperties
-
-    @Bean(DSKey.DSKEY_SYS + "druid")
-    @ConfigurationProperties(prefix = "datasource.sys")
-    fun dataSourceSysDruid(): XADataSource {
-        return DruidXADataSource()
-    }
-
-    @Bean(DSKey.DSKEY_SYS)
-    @DependsOn(DSKey.DSKEY_SYS + "druid")
-    @Primary
-    fun dataSourceSys(): DataSource {
-        return AtomikosDataSourceBean().also {
-            it.xaDataSource = dataSourceSysDruid()
-        }
-    }
-
-    @Bean
-    @Primary
-    fun mybatisSqlSessionFactoryBean(@Qualifier(DSKey.DSKEY_SYS) dataSource: DataSource): MybatisSqlSessionFactoryBean {
-        return MybatisSqlSessionFactoryBean().also {
-            it.setDataSource(dataSource)
-            it.vfs = SpringBootVFS::class.java
-            it.setConfiguration(properties.configuration)
-            it.setGlobalConfig(properties.globalConfig?.convertGlobalConfiguration())
-            it.setMapperLocations(properties.resolveMapperLocations())
-        }
-    }
-}

+ 2 - 19
zen-web/src/main/resources/application-orm-local.yml

@@ -11,30 +11,13 @@ spring:
         login-username: root
         login-password: root
         reset-enable: false
-      ############ 以下是关闭多数据源时使用的默认数据源 ############
-#      username: root
-#      password: root
-#      url: jdbc:mysql://127.0.0.1:3306/archives_sys?useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
-#      driver-class-name: com.mysql.jdbc.Driver
-#      test-on-borrow: false
-#      test-on-return: false
-#      test-while-idle: true
-#      validation-query: SELECT 1
-#      async-init: false
-#      name: system
-#      filters: log4j,wall,mergeStat
-#      keep-alive: false
-#      initial-size: 5
-#      min-idle: 5
-#      max-active: 20
-#      time-between-eviction-runs-millis: 60000
-#      min-evictable-idle-time-millis: 30000
   jta:
     atomikos:
       properties:
         serial-jta-transactions: false
 
 ################## 数据源 配置 ##################
+######## 单数据源使用sys作为默认数据源 ############
 datasource:
   sys:
     name: system
@@ -90,7 +73,7 @@ mybatis-plus:
     cache-enabled: true #配置的缓存的全局开关
     lazyLoadingEnabled: true #延时加载的开关
     multipleResultSetsEnabled: true #延时加载一个属性时会加载该对象全部属性,否则按需加载属性
-    interceptors: com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor
+    interceptors: com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor, com.baomidou.mybatisplus.plugins.PaginationInterceptor
     # log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印sql语句,调试用
 
 

+ 3 - 20
zen-web/src/main/resources/application-orm.yml

@@ -1,5 +1,5 @@
 orm:
-  multi-datasource-enable: false # 多数据源开关
+  multi-datasource-enable: true # 多数据源开关
 
 
 
@@ -13,24 +13,6 @@ spring:
         login-username: root
         login-password: root
         reset-enable: false
-      ############ 以下是关闭多数据源时使用的默认数据源 ############
-#      username: archives
-#      password: archives
-#      url: jdbc:mysql://192.168.1.124:3307/archives_sys?pinGlobalTxToPhysicalConnection=true&useUnicode=true&characterEncoding=utf-8&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
-#      driver-class-name: com.mysql.jdbc.Driver
-#      test-on-borrow: false
-#      test-on-return: false
-#      test-while-idle: true
-#      validation-query: SELECT 1
-#      async-init: false
-#      name: system
-#      filters: log4j,wall,mergeStat
-#      keep-alive: false
-#      initial-size: 5
-#      min-idle: 5
-#      max-active: 20
-#      time-between-eviction-runs-millis: 60000
-#      min-evictable-idle-time-millis: 30000
   jta:
     atomikos:
       properties:
@@ -38,6 +20,7 @@ spring:
 
 
 ################## 数据源 配置 ##################
+######## 单数据源使用sys作为默认数据源 ############
 datasource:
   sys:
     name: system
@@ -93,7 +76,7 @@ mybatis-plus:
     cache-enabled: true #配置的缓存的全局开关
     lazyLoadingEnabled: true #延时加载的开关
     multipleResultSetsEnabled: true #延时加载一个属性时会加载该对象全部属性,否则按需加载属性
-    interceptors: com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor
+    interceptors: com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor, com.baomidou.mybatisplus.plugins.PaginationInterceptor
     # log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #打印sql语句,调试用
 
 

+ 2 - 1
zen-web/src/main/resources/application.yml

@@ -27,11 +27,12 @@ spring:
     auto: true
   jackson:
     deserialization:
-      fail-on-unknown-properties: true # 多余字段反序列化过滤
+      fail-on-unknown-properties: false # 多余字段反序列化过滤
 logging:
   level:
     root: info
     com.gxzc.zen: debug
+    com.atomikos: warn
   path: logs/
   file: zen.log