微服務系列之-Mybatisplus集成

一.Mybatisplus介紹

這款插件跟我之前用過的beetlsql插件很類似,都是插件替你完成底層代碼的編寫工作你不用在耗費大量精力去寫底層SQL語句啥的,它內置的接口幾乎可以滿足所有的增刪改查要求,十分強大,也十分容易上手。

如需要詳細介紹信息,就參考官網官方解釋:

MyBatis-Plus官方網站
在這裏插入圖片描述

二.關鍵配置

  1. 依賴包
        <dependency>
            <groupId>com.xiaoleilu</groupId>
            <artifactId>hutool-all</artifactId>
            <version>${hutool.version}</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>${mybatisplus.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>HikariCP</artifactId>
                    <groupId>com.zaxxer</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>${mybatisplus.version}</version>
        </dependency>
  1. 數據連接池
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>2.7.4</version>
        </dependency>
  1. 初始化配置
@Slf4j
@Configuration
@MapperScan(basePackages = {"org.qy.mybatisplus.client"}, sqlSessionTemplateRef = "mysqlSqlSessionTemplate")
@EnableConfigurationProperties(HikariProperties.class)
@ConditionalOnClass(HikariProperties.class)
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
public class DataSourceConfig
{
    @Autowired
    private HikariProperties properties;

    @Value("${mybatis-plus.mapperLocations}")
    private String mapperLocations;

    @Autowired
    PaginationInterceptor paginationInterceptor;

    @RefreshScope
    @Bean(name = "mysqlDataSource", destroyMethod = "close")
    @Primary
    public DataSource mysqlDataSource()
    {
        log.info("MySqlDataSourceConfig|mysqlDataSource() >>> {}", properties);
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setJdbcUrl(properties.getJdbcUrl());
        hikariConfig.setUsername(properties.getUsername());
        hikariConfig.setPassword(properties.getPassword());
        hikariConfig.setDriverClassName(properties.getDriverClassName());
        hikariConfig.addDataSourceProperty("dataSource.cachePrepStmts", properties.getCachePrepStmts());
        hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSize", properties.getPrepStmtCacheSize());
        hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSqlLimit", properties.getPrepStmtCacheSqlLimit());
        hikariConfig.addDataSourceProperty("dataSource.useServerPrepStmts", "true");
        hikariConfig.addDataSourceProperty("useLocalSessionState", properties.getUseLocalSessionState());
        hikariConfig.addDataSourceProperty("useLocalTransactionState", properties.getUseLocalTransactionState());
        hikariConfig.addDataSourceProperty("rewriteBatchedStatements", properties.getRewriteBatchedStatements());
        hikariConfig.addDataSourceProperty("cacheResultSetMetadata", properties.getCacheResultSetMetadata());
        hikariConfig.addDataSourceProperty("cacheServerConfiguration", properties.getCacheServerConfiguration());
        hikariConfig.addDataSourceProperty("elideSetAutoCommits", properties.getElideSetAutoCommits());
        hikariConfig.addDataSourceProperty("maintainTimeStats", properties.getMaintainTimeStats());
        hikariConfig.addDataSourceProperty("logAbandoned", properties.getLogAbandoned());
        hikariConfig.addDataSourceProperty("removeAbandonedTimeout", properties.getRemoveAbandonedTimeout());
        hikariConfig.setConnectionTestQuery(properties.getConnectionTestQuery());
        hikariConfig.setPoolName(properties.getPoolName());
        hikariConfig.setMaximumPoolSize(properties.getMaxActive());
        hikariConfig.setMaxLifetime(properties.getMaxLifetime());
        hikariConfig.setIdleTimeout(properties.getIdleTimeout());
        hikariConfig.setConnectionTimeout(properties.getConnectionTimeout());
        hikariConfig.setReadOnly(properties.getReadOnly());
        return new HikariDataSource(hikariConfig);
    }
    
    /**
	 * 分頁插件
	 */
	@Bean
	public PaginationInterceptor paginationInterceptor()
    {
        log.info("MySqlDataSourceConfig|paginationInterceptor() >>> ");
		return new PaginationInterceptor();
	}

    @Bean(name = "mysqlSqlSessionFactory")
    @Primary
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mysqlDataSource") DataSource dataSource) throws Exception
    {
        log.info("MySqlDataSourceConfig|mysqlSqlSessionFactory() >>> ");
        MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        mybatisSqlSessionFactoryBean.setDataSource(dataSource);
	    MybatisConfiguration configuration = new MybatisConfiguration();
        mybatisSqlSessionFactoryBean.setConfiguration(configuration);
        mybatisSqlSessionFactoryBean.setPlugins(new Interceptor[]{paginationInterceptor, new PerformanceInterceptor()});
        mybatisSqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        return mybatisSqlSessionFactoryBean.getObject();
    }

    @Bean(name = "mysqlTransactionManager")
    @Primary
    public DataSourceTransactionManager mysqlTransactionManager(@Qualifier("mysqlDataSource") DataSource dataSource)
    {
        log.info("MySqlDataSourceConfig|mysqlTransactionManager() >>> ");
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "mysqlSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate mysqlSqlSessionTemplate(@Qualifier("mysqlSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception
    {
        log.info("MySqlDataSourceConfig|mysqlSqlSessionTemplate() >>> ");
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
@RefreshScope
@ConfigurationProperties(prefix = "spring.datasource.mysql")
@Data
public class HikariProperties
{
	private String jdbcUrl;
	private String username;
	private String password;
	private String driverClassName;

	/**
	 * 是否自定義配置,爲true時下面兩個參數才生效
	 * 同一個SQL語句發生了兩次預編譯,這不是我們想要的效果,要想對同一SQL語句多次執行不是每次都預編譯,就要使用
	 */
	private Boolean cachePrepStmts;

	/**
	 * 連接池大小默認25,官方推薦250-500
	 */
	private Integer prepStmtCacheSize;
	/**
	 * 單條語句最大長度默認256,官方推薦2048
	 * 準備SQL的最大長度.聲明驅動程序將緩存.MySQL默認值爲256.在我們經驗
	 * 特別是像Hibernate這樣的ORM框架默認值遠遠低於生成語句長度的閾值,官方推薦的設置是2048.
	 */
	private Integer prepStmtCacheSqlLimit;
	/**
	 * 新版本MySQL支持服務器端準備,開啓能夠得到顯著性能提升
	 * 使用預處理 只有爲true才能開啓Mysql的預編譯
	 */
	private Boolean useServerPrepStmts;

	private Boolean useLocalSessionState;
	private Boolean useLocalTransactionState;
	private Boolean rewriteBatchedStatements;
	private Boolean cacheResultSetMetadata;
	private Boolean cacheServerConfiguration;
	private Boolean elideSetAutoCommits;
	private Boolean maintainTimeStats;

	/**
	 * 連接數據庫測試sql
	 */
	private String connectionTestQuery;
	/**
	 * 連接池名字
	 */
	private String poolName;
	/**
	 * 最少空閒連接數
	 */
	private Integer minIdle;
	/**
	 * 最大連接數
	 */
	private Integer maxActive;
	/**
	 * 連接允許在池中閒置的最長時間,單位:毫秒,默認爲10秒
	 */
	private Integer idleTimeout;
	/**
	 * 等待來自池的連接的最大毫秒數
	 */
	private Integer connectionTimeout;
	/**
	 * 一個連接的生命時長(毫秒),超時而且沒被使用則被釋放(retired),缺省:30分鐘.
	 * 建議設置比數據庫超時時長少30秒,參考MySQL wait_timeout參數(show variables like '%timeout%';)
	 * 單位:毫秒
	 */
	private Integer maxLifetime;
	/**
	 * 從池中獲取的連接是否默認處於只讀模式,默認爲false
	 */
	private Boolean readOnly;
	/**
	 * removeAbandoned多久回收,單位秒
	 */
	private Integer removeAbandonedTimeout;
	/**
	 * 關閉abanded連接時輸出錯誤日誌
	 */
	private Boolean logAbandoned;
}
  1. 配置文件
mybatis-plus:
  mapperLocations: classpath:org/qy/mybatisplus/client/dao/mapper/*Dao.xml
  # 實體掃描,多個package用逗號或者分號分隔
  typeAliasesPackage: org.qy.mybatisplus.client.domain.entity
  global-config:
    # 數據庫相關配置
    db-config:
      # 主鍵類型  AUTO:"數據庫ID自增", INPUT:"用戶輸入ID",ID_WORKER:"全局唯一ID (數字類型唯一ID)", UUID:"全局唯一ID UUID";
      idType: ID_WORKER
      # 字段策略 IGNORED:"忽略判斷",NOT_NULL:"非 NULL 判斷"),NOT_EMPTY:"非空判斷"
      fieldStrategy: NOT_EMPTY
      # 駝峯下劃線轉換
      columnUnderline: true
      # 數據庫大寫下劃線轉換
      #capital-mode: true
      # 邏輯刪除配置
      logicDeleteValue: 1
      logicNotDeleteValue: 0
      dbType: mysql
    # 刷新mapper 調試神器
    refresh: false
  # 原生配置
  configuration:
    mapUnderscoreToCamelCase: true
    cacheEnabled: false
spring:
  datasource:
    mysql:
      jdbcUrl: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false
      username: root
      password:
      driverClassName: com.mysql.jdbc.Driver
      cachePrepStmts: true
      prepStmtCacheSize: 250
      prepStmtCacheSqlLimit: 2048
      useServerPrepStmts: true
      useLocalSessionState: true
      useLocalTransactionState: true
      rewriteBatchedStatements: true
      cacheResultSetMetadata: true
      cacheServerConfiguration: true
      elideSetAutoCommits: true
      maintainTimeStats: false
      connectionTestQuery: SELECT 1
      poolName: HikariCP
      minIdle: 5
      maxActive: 100
      idleTimeout: 600000
      connectionTimeout: 30000
      maxLifetime: 1770000
      readOnly: false
      logAbandoned: true
      removeAbandonedTimeout: 1800
  1. 關鍵步驟總結
    業務層實現機制
    在這裏插入圖片描述持久層實現機制
    在這裏插入圖片描述

  2. 實現CURD
    在這裏插入圖片描述
    在這裏插入圖片描述
    數據已經成功入庫。
    在這裏插入圖片描述
    我這裏寫的博文只保證連通性,具體更多的操作請查看官方文檔。

項目地址:微服務集成-謙奕爸爸

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