这个springboot集成druid和tk.mybatis是在之前Idea搭建多模块聚合maven项目的基础上完成的
https://segmentfault.com/a/1190000021385783
1.druid是什么?
Druid首先是一个数据库连接池。Druid是目前最好的数据库连接池,在功能、性能、扩展性方面,都超过其他数据库连接池。

2.tk.mybatis是什么?
通用Mapper,优点是可以缓存,全部针对单表操作,每个实体类都需要继承通用Mapper接口来获得通用方法,目前新版也可以针对多表进行操作,但是就不能使用二级缓存。

3.mybatis-genertor是什么?
是一款mybatis自动代码生成工具,可以通过配置,快速生成mapper和xml文件。

4.springboot集成mybatis-genertor生成dao层的实体和mapper,我把这个集成放到fire-common层
pom.xml

 <!--模块依赖-->
    <dependencies>
            <!--生成mapper所需要的jar-->
            <dependency>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-core</artifactId>
                <version>${mybatis-generator.version}</version>
            </dependency>

            <dependency>
                <groupId>tk.mybatis</groupId>
                <artifactId>mapper</artifactId>
                <version>${tk-mybatis.version}</version>
            </dependency>

            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>${mybatis.version}</version>
            </dependency>

            <dependency>
                <groupId>org.freemarker</groupId>
                <artifactId>freemarker</artifactId>
                <version>${freemarker.version}</version>
            </dependency>
            <!--生成mapper所需要的jar-->

            <!--mysql链接jar-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql-connector-java.version}</version>
            </dependency>
    </dependencies>

genertor.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>
    <context id="MysqlTables" targetRuntime="MyBatis3Simple">
        <property name="javaFileEncoding" value="UTF-8" />
        <property name="javaFileEncoding" value="UTF-8" />
        <property name="useMapperCommentGenerator" value="false" />

        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers"
                      value="tk.mybatis.mapper.common.Mapper" />
            <property name="caseSensitive" value="true" />
            <property name="forceAnnotation" value="true" />
            <property name="beginningDelimiter" value="`" />
            <property name="endingDelimiter" value="`" />
        </plugin>

        <plugin type="tk.mybatis.mapper.generator.TemplateFilePlugin">
            <property name="targetProject"
                      value="E:/IdeaProject/fire/fire-dao/src/main/java" />
            <property name="targetPackage" value="cn.yskcoder.fire.dao" />
            <property name="mapperSuffix" value="Dao" />
            <property name="templatePath" value="generator/mapper.ftl" />
            <property name="fileName"
                      value="${tableClass.shortClassName}${mapperSuffix}.java" />
        </plugin>

        <!--去除注释 -->
        <commentGenerator>
            <property name="suppressDate" value="true" />
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!-- 数据库链接URL、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/fire" userId="root"
                        password="123456">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="useJSR310Types" value="true" />
        </javaTypeResolver>
        <!-- ★★★生成实体类的包名和位置★★★要保证目录存在 -->
        <javaModelGenerator
                targetPackage="cn.yskcoder.fire.model"
                targetProject="E:/IdeaProject/fire/fire-dao/src/main/java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- ★★★生成的映射文件包名和位置★★★要保证目录存在 -->
        <sqlMapGenerator targetPackage="mapper"
                         targetProject="E:/IdeaProject/fire/fire-dao/src/main/resources">
            <property name="enableSubPac kages" value="false" />
        </sqlMapGenerator>

        <!-- 要生成那些表(更改tableName就可以); %为通配符,可以生成全部表 -->
        <!-- <table tableName="B%" enableCountByExample="false" -->
        <table tableName="sys_user" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false" />
    </context>
</generatorConfiguration>

Genertor.java

package cn.yskcoder.fire.generator;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


/**
 * 自动生成Mybatis相关的代码和配置文件
 *
 * @author: yskcoder
 * @createDate: 2019/12/25 18:59
 * @version: 1.0
 */
public class Generator {
    public static void main(String[] args) throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        ConfigurationParser cp = new ConfigurationParser(warnings);
        InputStream stream = Class.class.getResourceAsStream("/mybatis-generator.xml");
        Configuration config =
                cp.parseConfiguration(stream);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
        for (String warning : warnings) {
            System.out.println(warning);
        }
        System.out.println("恭喜你,生成Mybatis相关的代码完成!");
    }
}

5.springboot集成druid和tk.mybatis
pom.xml,这里将spring-boot-starter-web放到了fire-service里面因为要用注解的原因

<!--模块依赖-->
    <dependencies>
        <dependency>
            <groupId>cn.yskcoder.fire</groupId>
            <artifactId>fire-service</artifactId>
            <version>v1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- 阿里巴巴druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis-spring-boot-starter.version}</version>
        </dependency>

        <!--mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>${mapper-spring-boot-tarter.version}</version>
        </dependency>
    </dependencies>

application.yml

##########################################################
##################  Fire项目的配置  #######################
##########################################################


###################  项目启动端口  ########################
server:
  port: 80

###################  spring配置  #########################
spring:
  profiles:
    datasource:
      url: jdbc:mysql://localhost:3306/fire?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true&jdbcCompliantTruncation=false&serverTimezone=GMT%2B8
      username: root
      password: 123456
    resources:
     static-locations: classpath:/webapp/
  mvc:
    static-path-pattern: /static/**
    view:
      prefix: /WEB-INF/view/


###################  tk.mybaties配置  #########################
mybatis:
    type-aliases-package: cn.yskcoder.fire.model
    mapper-locations: classpath*:mapper/*.xml

通过注解的方式配置数据库数据源DruidProperties

Component
@ConfigurationProperties(prefix = "spring.datasource")
public class DruidProperties {

    private String url = "jdbc:mysql://127.0.0.1:3306/fire?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull";

    private String username = "root";

    private String password = "123456";

    private String driverClassName = "com.mysql.cj.jdbc.Driver";

    private Integer initialSize = 4;

    private Integer minIdle = 2;

    private Integer maxActive = 30;

    private Integer maxWait = 60000;

    private Integer timeBetweenEvictionRunsMillis = 60000;

    private Integer minEvictableIdleTimeMillis = 300000;

    private String validationQuery = "SELECT 'x'";

    private Boolean testWhileIdle = true;

    private Boolean testOnBorrow = false;

    private Boolean testOnReturn = false;

    private Boolean poolPreparedStatements = true;

    private Integer maxPoolPreparedStatementPerConnectionSize = 30;

    private String filters = "stat";


    public DataSource config(DruidDataSource dataSource){
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        dataSource.setDriverClassName(driverClassName);
        dataSource.setInitialSize(initialSize);     //定义初始连接数
        dataSource.setMinIdle(minIdle);             //最小空闲
        dataSource.setMaxActive(maxActive);         //定义最大连接数
        dataSource.setMaxWait(maxWait);             //最长等待时间

        // 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);

        // 配置一个连接在池中最小生存的时间,单位是毫秒
        dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        dataSource.setValidationQuery(validationQuery);
        dataSource.setTestWhileIdle(testWhileIdle);
        dataSource.setTestOnBorrow(testOnBorrow);
        dataSource.setTestOnReturn(testOnReturn);

        // 打开PSCache,并且指定每个连接上PSCache的大小
        dataSource.setPoolPreparedStatements(poolPreparedStatements);
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);

        try {
            dataSource.setFilters(filters);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  dataSource;

    }


    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public Integer getInitialSize() {
        return initialSize;
    }

    public void setInitialSize(Integer initialSize) {
        this.initialSize = initialSize;
    }

    public Integer getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(Integer minIdle) {
        this.minIdle = minIdle;
    }

    public Integer getMaxActive() {
        return maxActive;
    }

    public void setMaxActive(Integer maxActive) {
        this.maxActive = maxActive;
    }

    public Integer getMaxWait() {
        return maxWait;
    }

    public void setMaxWait(Integer maxWait) {
        this.maxWait = maxWait;
    }

    public Integer getTimeBetweenEvictionRunsMillis() {
        return timeBetweenEvictionRunsMillis;
    }

    public void setTimeBetweenEvictionRunsMillis(Integer timeBetweenEvictionRunsMillis) {
        this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
    }

    public Integer getMinEvictableIdleTimeMillis() {
        return minEvictableIdleTimeMillis;
    }

    public void setMinEvictableIdleTimeMillis(Integer minEvictableIdleTimeMillis) {
        this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
    }

    public String getValidationQuery() {
        return validationQuery;
    }

    public void setValidationQuery(String validationQuery) {
        this.validationQuery = validationQuery;
    }

    public Boolean getTestWhileIdle() {
        return testWhileIdle;
    }

    public void setTestWhileIdle(Boolean testWhileIdle) {
        this.testWhileIdle = testWhileIdle;
    }

    public Boolean getTestOnBorrow() {
        return testOnBorrow;
    }

    public void setTestOnBorrow(Boolean testOnBorrow) {
        this.testOnBorrow = testOnBorrow;
    }

    public Boolean getTestOnReturn() {
        return testOnReturn;
    }

    public void setTestOnReturn(Boolean testOnReturn) {
        this.testOnReturn = testOnReturn;
    }

    public Boolean getPoolPreparedStatements() {
        return poolPreparedStatements;
    }

    public void setPoolPreparedStatements(Boolean poolPreparedStatements) {
        this.poolPreparedStatements = poolPreparedStatements;
    }

    public Integer getMaxPoolPreparedStatementPerConnectionSize() {
        return maxPoolPreparedStatementPerConnectionSize;
    }

    public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) {
        this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
    }

    public String getFilters() {
        return filters;
    }

    public void setFilters(String filters) {
        this.filters = filters;
    }
}

配置mybatis通过注解类的方式MyBatisConfig

/**
 * mybatisConfig配置类
 *
 * @author:       yskcoder
 * @createDate:   2019/12/25 16:20
 * @version:      1.0
*/
@Configuration
public class MyBatisConfig {
    @Autowired
    DruidProperties druidProperties;


    /**
     * Fire数据源
     */
    private DruidDataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        druidProperties.config(dataSource);
        return dataSource;
    }

    @Bean
    public DruidDataSource datasource() {
        return dataSource();
    }
}

6.具体的代码可以参考Fire
https://github.com/yskcoder/Fire


恒不动
105 声望15 粉丝