转载

SpringBoot 2.0 + Mybatis + Mybatis Generator + IDEA 制作多数据源

SpringBoot 2.0 + Mybatis + Mybatis Generator + 多数据源 + IDEA

吐槽

昨天网上找了个“完整”版的使用 SpringBoot 2.0 + Mybatis 实现多数据源,结果其实是缺少部分代码的,被害得很惨,浪费了太多时间,找了N多教程后最终集成成功,赶紧文章整理出来。

开发环境、技术栈

使用IDEA,集成了下面的功能点:SpringBoot 2.0 + Mybatis + Mybatis Generator + XML

以XML的形式和数据库交互,而不是使用注解的方式,项目之后遇到复杂的SQL语句还是XML形式方便

项目制作步骤

  1. 使用 IDEA 创建 SpringBoot 2.0 项目的过程略过
  2. pom.xml 的全部代码:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.8.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.xdf</groupId>
        <artifactId>multd</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>multd</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jdbc</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.0</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
    
                <plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <configuration>
                        <verbose>true</verbose>
                        <overwrite>true</overwrite>
                    </configuration>
                </plugin>
    
    
            </plugins>
        </build>
    
    </project>
  3. 解释项目结构

    本来想在图片中标注每个包、文件的作用,看看太多了,还是文字表达吧。controller 存放控制器类,com.xdf.multd.dao.test1 和 com.xdf.multd.dao.test2 分别存放两个数据库对应的 dao 类,com.xdf.multd.datasource 存放两个数据库对应的数据库连接,将两个数据库表对应的ORM类的都存放在包com.xdf.multd.model 中,com.xdf.multd.service 自然是服务层了。

    下面讲解 resources 目录下的文件:

    mapper 是 Mybatis Generator 生成的 mapper 文件存放的位置,生成后要对应的拷贝到 mappers.test1 或者 mappers.test2 中,下面的3个文件 application.yml、application-dev.yml、application-mult.yml 是多环境配置,generatorConfig.xml 是 Mybatis Generator 的相关参数,mybatis-config.xml 是映射ORM时数据类型的对应关系,最后一个 mysql-connector-java-5.1.34.jar 是 Mybatis Generator 链接数据库时要用到的驱动。

  4. application.yml 的全部代码:

    spring:
      profiles:
        active: mult

    application-mult.yml 的全部代码:

    server:
      port: 8083
    
    # mybatis generator 的配置
    mybatis:
      config-location: classpath:mybatis-config.xml
      mapper-locations: classpath:mapper/*.xml
      type-aliases-package: com.xdf.multd.model
    
    
    spring:
      datasource:
        test1:
          driver-class-name: com.mysql.cj.jdbc.Driver
          jdbc-url: jdbc:mysql://localhost:3306/femis?userUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
          username: root
          password: chanchaw
        test2:
          driver-class-name: com.mysql.cj.jdbc.Driver
          jdbc-url: jdbc:mysql://localhost:3306/femisimg?userUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
          username: root
          password: chanchaw
  5. mybatis-config.xml 的全部代码:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <settings>
            <setting name="callSettersOnNulls" value="true"/>
            <setting name="cacheEnabled" value="true"/>
            <setting name="lazyLoadingEnabled" value="true"/>
            <setting name="aggressiveLazyLoading" value="true"/>
            <setting name="multipleResultSetsEnabled" value="true"/>
            <setting name="useColumnLabel" value="true"/>
            <setting name="useGeneratedKeys" value="false"/>
            <setting name="autoMappingBehavior" value="PARTIAL"/>
            <setting name="defaultExecutorType" value="SIMPLE"/>
            <setting name="mapUnderscoreToCamelCase" value="true"/>
            <setting name="localCacheScope" value="SESSION"/>
            <setting name="jdbcTypeForNull" value="NULL"/>
        </settings>
        <typeAliases>
            <typeAlias alias="Integer" type="java.lang.Integer" />
            <typeAlias alias="Long" type="java.lang.Long" />
            <typeAlias alias="HashMap" type="java.util.HashMap" />
            <typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
            <typeAlias alias="ArrayList" type="java.util.ArrayList" />
            <typeAlias alias="LinkedList" type="java.util.LinkedList" />
        </typeAliases>
    </configuration>

    generatorConfig.xml 的全部代码:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
            "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
    <!-- 配置生成器 -->
    <generatorConfiguration>
    
        <!--classPathEntry:数据库的JDBC驱动,换成你自己的驱动位置 可选 -->
        <!--<classPathEntry location="E:/IdeaProjects/mysql-connector-java-5.1.47.jar"/>-->
        <classPathEntry location="D:/Java/ideaProject/multd/src/main/resources/mysql-connector-java-5.1.34.jar"/>
    
        <!-- 一个数据库一个context,defaultModelType="flat" 大数据字段,不分表 -->
        <context id="MysqlTables" targetRuntime="MyBatis3Simple" defaultModelType="flat">
    
            <!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 -->
            <property name="autoDelimitKeywords" value="true"/>
    
            <!-- 生成的Java文件的编码 -->
            <property name="javaFileEncoding" value="utf-8"/>
    
            <!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
            <property name="beginningDelimiter" value="`"/>
            <property name="endingDelimiter" value="`"/>
    
            <!-- 格式化java代码 -->
            <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
    
            <!-- 格式化XML代码 -->
            <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
            <plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
            <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
    
            <!-- 注释 -->
            <commentGenerator>
                <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
                <property name="suppressDate" value="false"/> <!-- 是否生成注释代时间戳-->
            </commentGenerator>
    
            <!-- jdbc连接-->
            <!--<jdbcConnection driverClass="com.mysql.jdbc.Driver"-->
                            <!--connectionURL="jdbc:mysql://localhost:3306/femis?serverTimezone=UTC" userId="root"-->
                            <!--password="chanchaw"/>-->
            <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                            connectionURL="jdbc:mysql://localhost:3306/femisimg?serverTimezone=UTC" userId="root"
                            password="chanchaw"/>
    
            <!-- 类型转换 -->
            <javaTypeResolver>
                <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
                <property name="forceBigDecimals" value="false"/>
            </javaTypeResolver>
    
            <!-- 生成实体类地址 -->
            <javaModelGenerator targetPackage="com.xdf.multd.model" targetProject="src/main/java">
                <!-- 是否让schema作为包的后缀 -->
                <property name="enableSubPackages" value="false"/>
                <!-- 从数据库返回的值去掉前后空格 -->
                <property name="trimStrings" value="true"/>
            </javaModelGenerator>
    
            <!-- 生成map.xml文件存放地址 -->
            <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
                <property name="enableSubPackages" value="false"/>
            </sqlMapGenerator>
    
            <!-- 生成接口dao -->
            <javaClientGenerator targetPackage="com.xdf.multd.dao" targetProject="src/main/java" type="XMLMAPPER">
                <property name="enableSubPackages" value="false"/>
            </javaClientGenerator>
    
            <!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 enableSelectByPrimaryKey相应的配置表示是否生成相应的接口 -->
            <table tableName="orderimg" enableCountByExample="false" enableUpdateByExample="false"
                   enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"
                   enableSelectByPrimaryKey="true" enableUpdateByPrimaryKey="true"
                   enableDeleteByPrimaryKey="true">
                <property name="useActualColumnNames" value="true"/>
            </table>
    
        </context>
    </generatorConfiguration>
  6. 为两个数据库创建对应的数据源,两个文件都放在 com.xdf.multd.datasource 下,其中 DataSource1Config 对的全部代码如下:

    package com.xdf.multd.datasource;
    
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.mybatis.spring.SqlSessionTemplate;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.jdbc.DataSourceBuilder;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
    import org.springframework.core.io.support.ResourcePatternResolver;
    import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    
    import javax.sql.DataSource;
    
    @Configuration
    @MapperScan(basePackages = "com.xdf.multd.dao.test1", sqlSessionTemplateRef  = "test1SqlSessionTemplate")
    public class DataSource1Config {
    
        @Bean(name = "test1DataSource")
        @ConfigurationProperties(prefix = "spring.datasource.test1")
        @Primary
        public DataSource testDataSource() {
            return DataSourceBuilder.create().build();
        }
    
        @Bean(name = "test1SqlSessionFactory")
        @Primary
        public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            //添加XML目录
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            try {
                bean.setMapperLocations(resolver.getResources("classpath*:mappers/test1/*.xml"));
                return bean.getObject();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
    
        }
    
        @Bean(name = "test1TransactionManager")
        @Primary
        public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }
    
        @Bean(name = "test1SqlSessionTemplate")
        @Primary
        public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    
    }

    DataSource2Config 的全部代码如下:

    package com.xdf.multd.datasource;
    
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionFactoryBean;
    import org.mybatis.spring.SqlSessionTemplate;
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.jdbc.DataSourceBuilder;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
    import org.springframework.core.io.support.ResourcePatternResolver;
    import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    
    import javax.sql.DataSource;
    
    @Configuration
    @MapperScan(basePackages = "com.xdf.multd.dao.test2", sqlSessionTemplateRef  = "test2SqlSessionTemplate")
    public class DataSource2Config {
    
        @Bean(name = "test2DataSource")
        @ConfigurationProperties(prefix = "spring.datasource.test2")
        public DataSource testDataSource() {
            return DataSourceBuilder.create().build();
        }
    
        @Bean(name = "test2SqlSessionFactory")
        public SqlSessionFactory testSqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource) throws Exception {
            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            try {
                bean.setMapperLocations(resolver.getResources("classpath*:mappers/test2/*.xml"));
                return bean.getObject();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    
        @Bean(name = "test2TransactionManager")
        public DataSourceTransactionManager testTransactionManager(@Qualifier("test2DataSource") DataSource dataSource) {
            return new DataSourceTransactionManager(dataSource);
        }
    
        @Bean(name = "test2SqlSessionTemplate")
        public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
            return new SqlSessionTemplate(sqlSessionFactory);
        }
    
    }
  7. 剩下的工作就是使用 Mybatis Generator 生成 ORM 类并且拷贝到对应的目录下,自己手动制作服务类和控制器用来测试
原文  https://segmentfault.com/a/1190000020348756
正文到此结束
Loading...