Spring Boot整合Mybatis通用Mapper插件

  • 項目配置:

    springboot: 2.02

    mysql:8.0.11

    maven:3.5.3

  • 數據源配置:

  • 引入依賴:pom.xml
        mysql、druid連接池
<!--mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.11</version>
</dependency>
<!--druid連接池-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>

  • 對應application.yml:

        注意:url和driver-class-name

        druid官方文檔:點擊打開鏈接

spring:
  #datasource配置
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/spring?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
    username: root
    password: 1995
    #mysql新版驅動
    driver-class-name: com.mysql.cj.jdbc.Driver

    #連接池配置
    druid:
    #初始化大小、最小空閒、最大激活
      initial-size: 5
      min-idle: 5
      max-active: 20
      #配置獲取連接等待超時的時間
      max-wait: 60000
      # 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連接,單位是毫秒
      time-between-eviction-runs-millis: 60000
      # 配置一個連接在池中最小生存的時間,單位是毫秒
      min-evictable-idle-time-millis: 300000
      validation-query: SELECT 1 FROM DUAL
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      # 打開PSCache,並且指定每個連接上PSCache的大小
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      # 配置監控統計攔截的filters,去掉後監控界面sql無法統計,'wall'用於防火牆
      filters: stat,wall,log4j
      # 合併多個DruidDataSource的監控數據
      use-global-data-source-stat: true
      # 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

  • druid對應的bean配置:
@Configuration
public class DruidConfig {

    private Logger logger = LoggerFactory.getLogger(DruidConfig.class);

    @Value("${spring.datasource.url:#{null}}")
    private String dbUrl;
    @Value("${spring.datasource.username: #{null}}")
    private String username;
    @Value("${spring.datasource.password:#{null}}")
    private String password;
    @Value("${spring.datasource.driverClassName:#{null}}")
    private String driverClassName;
    @Value("${spring.datasource.initialSize:#{null}}")
    private Integer initialSize;
    @Value("${spring.datasource.minIdle:#{null}}")
    private Integer minIdle;
    @Value("${spring.datasource.maxActive:#{null}}")
    private Integer maxActive;
    @Value("${spring.datasource.maxWait:#{null}}")
    private Integer maxWait;
    @Value("${spring.datasource.timeBetweenEvictionRunsMillis:#{null}}")
    private Integer timeBetweenEvictionRunsMillis;
    @Value("${spring.datasource.minEvictableIdleTimeMillis:#{null}}")
    private Integer minEvictableIdleTimeMillis;
    @Value("${spring.datasource.validationQuery:#{null}}")
    private String validationQuery;
    @Value("${spring.datasource.testWhileIdle:#{null}}")
    private Boolean testWhileIdle;
    @Value("${spring.datasource.testOnBorrow:#{null}}")
    private Boolean testOnBorrow;
    @Value("${spring.datasource.testOnReturn:#{null}}")
    private Boolean testOnReturn;
    @Value("${spring.datasource.poolPreparedStatements:#{null}}")
    private Boolean poolPreparedStatements;
    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize:#{null}}")
    private Integer maxPoolPreparedStatementPerConnectionSize;
    @Value("${spring.datasource.filters:#{null}}")
    private String filters;
    @Value("{spring.datasource.connectionProperties:#{null}}")
    private String connectionProperties;

    @Bean
    @Primary
    public DataSource dataSource(){
        DruidDataSource datasource = new DruidDataSource();

        datasource.setUrl(this.dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);
        //configuration
        if(initialSize != null) {
            datasource.setInitialSize(initialSize);
        }
        if(minIdle != null) {
            datasource.setMinIdle(minIdle);
        }
        if(maxActive != null) {
            datasource.setMaxActive(maxActive);
        }
        if(maxWait != null) {
            datasource.setMaxWait(maxWait);
        }
        if(timeBetweenEvictionRunsMillis != null) {
            datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        }
        if(minEvictableIdleTimeMillis != null) {
            datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        }
        if(validationQuery!=null) {
            datasource.setValidationQuery(validationQuery);
        }
        if(testWhileIdle != null) {
            datasource.setTestWhileIdle(testWhileIdle);
        }
        if(testOnBorrow != null) {
            datasource.setTestOnBorrow(testOnBorrow);
        }
        if(testOnReturn != null) {
            datasource.setTestOnReturn(testOnReturn);
        }
        if(poolPreparedStatements != null) {
            datasource.setPoolPreparedStatements(poolPreparedStatements);
        }
        if(maxPoolPreparedStatementPerConnectionSize != null) {
            datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        }

        if(connectionProperties != null) {
            datasource.setConnectionProperties(connectionProperties);
        }

        List<Filter> filters = new ArrayList<>();
        filters.add(statFilter());
        filters.add(wallFilter());
        datasource.setProxyFilters(filters);

        return datasource;
    }

    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");

        //控制檯管理用戶,加入下面2行 進入druid後臺就需要登錄
        //servletRegistrationBean.addInitParameter("loginUsername", "admin");
        //servletRegistrationBean.addInitParameter("loginPassword", "admin");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        filterRegistrationBean.addInitParameter("profileEnable", "true");
        return filterRegistrationBean;
    }

    @Bean
    public StatFilter statFilter(){
        StatFilter statFilter = new StatFilter();
        statFilter.setLogSlowSql(true); //slowSqlMillis用來配置SQL慢的標準,執行時間超過slowSqlMillis的就是慢。
        statFilter.setMergeSql(true); //SQL合併配置
        statFilter.setSlowSqlMillis(1000);//slowSqlMillis的缺省值爲3000,也就是3秒。
        return statFilter;
    }

    @Bean
    public WallFilter wallFilter(){
        WallFilter wallFilter = new WallFilter();
        //允許執行多條SQL
        WallConfig config = new WallConfig();
        config.setMultiStatementAllow(true);
        wallFilter.setConfig(config);
        return wallFilter;
    }
}

  • 通用mapper和pagehelper配置:

  • 引入依賴:pom.xml
<!--mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<!--通用Mapper-->
<dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper-spring-boot-starter</artifactId>
    <version>2.0.3</version>
</dependency>
<!--pageHelper分頁-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.5</version>
</dependency>

  • 對應application.yml:
#mybatis相關配置
mybatis:
  #當mybatis的xml文件和mapper接口不在相同包下時
  #需要用mapperLocations屬性指定xml文件的路徑。  
  #*是個通配符,代表所有的文件,**代表所有目錄下
  mapper-locations: classpath:mapper/*.xml
  #指定bean所在包 
  #在mapper.xml中可以使用別名而不使用類的全路徑名
  type-aliases-package: com.ali.demo.domain

#通用mapper配置
mapper:
    #mappers 多個接口時逗號隔開
    mappers: com.ali.demo.utils.MyMapper
    not-empty: false
    identity: MYSQL

#pagehelper分頁插件
pagehelper:
    helper-dialect: mysql
    reasonable: true
    params: count=countSql
    support-methods-arguments: true

  • 通用mapper接口:
        通用Mapper都可以極大的方便開發人員,對單表封裝了許多通用方法,省掉自己寫增刪改查的sql
        通用Mapper插件網址:點擊打開鏈接
        特別注意:該接口不能被掃描到,否則會出錯  
        文件位置:com.ali.demo.utils
package com.ali.demo.utils;

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;

/**
 * @author 
 * @description 通用Mapper
 * @create 2018/7/9 22:31
 */
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
}

  • MyBatis Generator配置:
    Mybatis Geneator 詳解:點擊打開鏈接
    mybatis-generator.xml:位於src/main/resources目錄下
<?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>
    <!--加載配置文件,爲下面讀取數據庫信息準備-->
    <!-- <properties resource="application.yml"/>-->
    <!--classPathEntry:數據庫的JDBC驅動位置 -->
    <!-- <classPathEntry location="D:\Program Files\Maven\Repository\mysql\mysql-connector-java\8.0.11\mysql-connector-java-8.0.11.jar"/>-->
    <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">

        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
            <property name="mappers" value="com.ali.demo.utils.MyMapper" />
            <!--caseSensitive默認false,當數據庫表名區分大小寫時,可以將該屬性設置爲true-->
            <property name="caseSensitive" value="true"/>
            <property name="forceAnnotation" value="true"/>
            <property name="beginningDelimiter" value="`"/>
            <property name="endingDelimiter" value="`"/>
        </plugin>

        <!-- 是否去除自動生成的註釋 true:是 : false:否  -->
        <commentGenerator>
            <property name="javaFileEncoding" value="UTF-8"/>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--數據庫鏈接地址賬號密碼-->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
				connectionURL="jdbc:mysql://127.0.0.1:3306/spring?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"
				userId="root"
				password="1995">
        </jdbcConnection>

        <!-- 默認false,把JDBC DECIMAL 和 NUMERIC 類型解析爲 Integer,
        爲 true時把JDBC DECIMAL 和 NUMERIC 類型解析爲java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <!--生成pojo類存放位置-->
        <javaModelGenerator targetPackage="com.ali.demo.domain" targetProject="src/main/java">
            <!-- enableSubPackages:是否讓schema作爲包的後綴 -->
            <property name="enableSubPackages" value="false"/>
            <!-- 從數據庫返回的值被清理前後的空格 -->
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!--生成mapper.xml映射文件存放位置-->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <!-- enableSubPackages:是否讓schema作爲包的後綴 -->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!--生成Mapper的存放位置-->
        <!-- 客戶端代碼,生成易於使用的針對Model對象和XML配置文件 的代碼
                type="ANNOTATEDMAPPER",生成Java Model 和基於註解的Mapper對象
                type="XMLMAPPER",生成SQLMap XML文件和獨立的Mapper接口
        -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.ali.demo.dao" targetProject="src/main/java">
            <!-- enableSubPackages:是否讓schema作爲包的後綴 -->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!--生成對應表及類名
            去掉Mybatis Generator生成的一堆 example
        -->
        <table tableName="LEARN_RESOURCE" domainObjectName="LearnResource"
               enableCountByExample="false" enableUpdateByExample="false"
               enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
            <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
        </table>
    </context>
</generatorConfiguration>
    其中tk.mybatis.mapper.generator.MapperPlugin通用mapper插件很重要,自動生成的mapper都會繼承其指定的mapper
    
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
    <property name="mappers" value="com.ali.demo.utils.MyMapper" />
    <!--caseSensitive默認false,當數據庫表名區分大小寫時,可以將該屬性設置爲true-->
    <property name="caseSensitive" value="true"/>
    <property name="forceAnnotation" value="true"/>
    <property name="beginningDelimiter" value="`"/>
    <property name="endingDelimiter" value="`"/>
</plugin>
    問題: mybatis-generator.xml加載不了application.yml文件但可以加載application.properties文件
    如果mybatis-generator.xml中引入了application.properties則jdbcConnection部分可如下編寫
<!--數據庫鏈接地址賬號密碼-->
<jdbcConnection driverClass="${spring.datasource.driver-class-name}"
        connectionURL="${spring.datasource.url}"
        userId="${spring.datasource.username}"
        password="${spring.datasource.password}">
</jdbcConnection>
   這裏不配置classPathEntry屬性,在pom.xml中mybatis  generator 自動生成代碼插件引入相關jdbc驅動即可

  • 自動生成插件:
    pom.xml中引入自動生成插件:mapper生成後需註釋該插件
        指定mybatis-generator.xml文件位置
        添加相關依賴:通用mapper、數據庫驅動
<build>
    <plugins>
        <!--maven插件-->
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <!--mybatis  generator 自動生成代碼插件-->
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.7</version>
            <!--自動生成相關配置-->
            <configuration>
            <!--指定配置文件的位置-->
            <configurationFile>src/main/resources/mybatis-generator.xml</configurationFile>
                <!-- 是否覆蓋 -->
                <overwrite>true</overwrite>
                <!--允許移動生成的文件 -->
                <verbose>true</verbose>
            </configuration>
            <!--添加自動生成插件所需依賴-->
            <dependencies>
                <dependency>
                    <groupId>tk.mybatis</groupId>
                    <artifactId>mapper</artifactId>
                    <version>4.0.3</version>
                </dependency>

                <!--mysql驅動-->
                <dependency>
                    <groupId>mysql</groupId>
                    <artifactId>mysql-connector-java</artifactId>
                    <version>8.0.11</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

  • mapper生成:
    

    如果不是IDEA開發環境也可以直接通過命令:mvn mybatis-generator:generate

   注意事項:確保生成的mapper可以被掃描到

            方式一:在生成的每一個mapper上添加@Mapper註解,使得該mapper可以被掃描到

                注入相關mapper時忽略idea提示Could not autowire. No beans of 'xxxx' type found,不受影響

  • 去除idea提示:

            

            方式二:在啓動類上添加@MapperScan註解

@MapperScan(basePackages = "com.ali.demo.dao", markerInterface = MyMapper.class)
basePackage:掃描器開始掃描的基礎包名,支持嵌套掃描
markerInterface:基於接口的過濾器,實現了該接口的dao纔會被掃描器掃描,與basePackage是與的作用

  • 生成的文件:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章