溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

SpringBoot整合MybatisPlus配置多數(shù)據(jù)源增強(qiáng)插件的方法是什么

發(fā)布時(shí)間:2021-11-04 14:45:07 來(lái)源:億速云 閱讀:153 作者:iii 欄目:編程語(yǔ)言

本篇內(nèi)容介紹了“SpringBoot整合MybatisPlus配置多數(shù)據(jù)源增強(qiáng)插件的方法是什么”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

一、項(xiàng)目案例簡(jiǎn)介

1、多數(shù)據(jù)簡(jiǎn)介

實(shí)際的項(xiàng)目中,經(jīng)常會(huì)用到不同的數(shù)據(jù)庫(kù)以滿(mǎn)足項(xiàng)目的實(shí)際需求。隨著業(yè)務(wù)的并發(fā)量的不斷增加,一個(gè)項(xiàng)目使用多個(gè)數(shù)據(jù)庫(kù):主從復(fù)制、讀寫(xiě)分離、分布式數(shù)據(jù)庫(kù)等方式,越來(lái)越常見(jiàn)。

2、MybatisPlus簡(jiǎn)介

MyBatis-Plus(簡(jiǎn)稱(chēng) MP)是一個(gè)MyBatis的增強(qiáng)工具,在MyBatis的基礎(chǔ)上只做增強(qiáng)不做改變,為簡(jiǎn)化開(kāi)發(fā)、提高效率而生。

插件特點(diǎn)

無(wú)代碼侵入:只做增強(qiáng)不做改變,引入它不會(huì)對(duì)現(xiàn)有工程產(chǎn)生影響。
強(qiáng)大的 CRUD 操作:通過(guò)少量配置即可實(shí)現(xiàn)單表大部分 CRUD 操作滿(mǎn)足各類(lèi)使用需求。
支持 Lambda 形式調(diào)用:通過(guò) Lambda 表達(dá)式,方便的編寫(xiě)各類(lèi)查詢(xún)條件。
支持主鍵自動(dòng)生成:可自由配置,解決主鍵問(wèn)題。
內(nèi)置代碼生成工具:采用代碼或者 Maven 插件可快速生成各層代碼。
內(nèi)置分頁(yè)插件:基于 MyBatis 物理分頁(yè),開(kāi)發(fā)者無(wú)需關(guān)心具體操作。
內(nèi)置性能分析插件:可輸出 Sql 語(yǔ)句以及其執(zhí)行時(shí)間。

二、多數(shù)據(jù)源案例

1、項(xiàng)目結(jié)構(gòu)

SpringBoot整合MybatisPlus配置多數(shù)據(jù)源增強(qiáng)插件的方法是什么

注意:mapper層和mapper.xml層分別放在不同目錄下,以便mybatis掃描加載。

2、多數(shù)據(jù)源配置

spring:
  # 數(shù)據(jù)源配置
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    admin-data:
      driverClassName: com.mysql.jdbc.Driver
      dbUrl: jdbc:mysql://127.0.0.1:3306/cloud-admin-data?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false
      username: root
      password: 123
      initialSize: 20
      maxActive: 100
      minIdle: 20
      maxWait: 60000
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 30
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 30000
      maxEvictableIdleTimeMillis: 60000
      validationQuery: SELECT 1 FROM DUAL
      testOnBorrow: false
      testOnReturn: false
      testWhileIdle: true
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      filters: stat,wall
    user-data:
      driverClassName: com.mysql.jdbc.Driver
      dbUrl: jdbc:mysql://127.0.0.1:3306/cloud-user-data?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false
      username: root
      password: 123
      initialSize: 20
      maxActive: 100
      minIdle: 20
      maxWait: 60000
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 30
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 30000
      maxEvictableIdleTimeMillis: 60000
      validationQuery: SELECT 1 FROM DUAL
      testOnBorrow: false
      testOnReturn: false
      testWhileIdle: true
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      filters: stat,wall

這里參數(shù)的形式是多樣的,只需要配置參數(shù)掃描即可。

3、參數(shù)掃描類(lèi)

@Component
@ConfigurationProperties(prefix = "spring.datasource.admin-data")
public class DruidOneParam {
    private String dbUrl;
    private String username;
    private String password;
    private String driverClassName;
    private int initialSize;
    private int maxActive;
    private int minIdle;
    private int maxWait;
    private boolean poolPreparedStatements;
    private int maxPoolPreparedStatementPerConnectionSize;
    private int timeBetweenEvictionRunsMillis;
    private int minEvictableIdleTimeMillis;
    private int maxEvictableIdleTimeMillis;
    private String validationQuery;
    private boolean testWhileIdle;
    private boolean testOnBorrow;
    private boolean testOnReturn;
    private String filters;
    private String connectionProperties;
    // 省略 GET 和 SET
}

4、配置Druid連接池

@Configuration
@MapperScan(basePackages = {"com.data.source.mapper.one"},sqlSessionTemplateRef = "sqlSessionTemplateOne")
public class DruidOneConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(DruidOneConfig.class) ;
    @Resource
    private DruidOneParam druidOneParam ;
    @Bean("dataSourceOne")
    public DataSource dataSourceOne () {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(druidOneParam.getDbUrl());
        datasource.setUsername(druidOneParam.getUsername());
        datasource.setPassword(druidOneParam.getPassword());
        datasource.setDriverClassName(druidOneParam.getDriverClassName());
        datasource.setInitialSize(druidOneParam.getInitialSize());
        datasource.setMinIdle(druidOneParam.getMinIdle());
        datasource.setMaxActive(druidOneParam.getMaxActive());
        datasource.setMaxWait(druidOneParam.getMaxWait());
        datasource.setTimeBetweenEvictionRunsMillis(druidOneParam.getTimeBetweenEvictionRunsMillis());
        datasource.setMinEvictableIdleTimeMillis(druidOneParam.getMinEvictableIdleTimeMillis());
        datasource.setMaxEvictableIdleTimeMillis(druidOneParam.getMaxEvictableIdleTimeMillis());
        datasource.setValidationQuery(druidOneParam.getValidationQuery());
        datasource.setTestWhileIdle(druidOneParam.isTestWhileIdle());
        datasource.setTestOnBorrow(druidOneParam.isTestOnBorrow());
        datasource.setTestOnReturn(druidOneParam.isTestOnReturn());
        datasource.setPoolPreparedStatements(druidOneParam.isPoolPreparedStatements());
        datasource.setMaxPoolPreparedStatementPerConnectionSize(druidOneParam.getMaxPoolPreparedStatementPerConnectionSize());
        try {
            datasource.setFilters(druidOneParam.getFilters());
        } catch (Exception e) {
            LOGGER.error("druid configuration initialization filter", e);
        }
        datasource.setConnectionProperties(druidOneParam.getConnectionProperties());
        return datasource;
    }
    @Bean
    public SqlSessionFactory sqlSessionFactoryOne() throws Exception{
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factory.setDataSource(dataSourceOne());
        factory.setMapperLocations(resolver.getResources("classpath*:/dataOneMapper/*.xml"));
        return factory.getObject();
    }
    @Bean(name="transactionManagerOne")
    public DataSourceTransactionManager transactionManagerOne(){
        return  new DataSourceTransactionManager(dataSourceOne());
    }
    @Bean(name = "sqlSessionTemplateOne")
    public SqlSessionTemplate sqlSessionTemplateOne() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryOne());
    }
}

注意事項(xiàng)

  • MapperScan 在指定數(shù)據(jù)源上配置;

  • SqlSessionFactory 配置掃描的Mapper.xml地址 ;

  • DataSourceTransactionManager 配置該數(shù)據(jù)源的事務(wù);

  • 兩個(gè)數(shù)據(jù)源的配置手法相同,不贅述 ;

5、操作案例

  • 數(shù)據(jù)源一:簡(jiǎn)單查詢(xún)

    @Service
    public class AdminUserServiceImpl implements AdminUserService {
      
    @Resource
      private AdminUserMapper adminUserMapper ;
      
    @Override
      public AdminUser selectByPrimaryKey (Integer id) {
          return adminUserMapper.selectByPrimaryKey(id) ;
      }
    }
  • 數(shù)據(jù)源二:事務(wù)操作

    @Service
    public class UserBaseServiceImpl implements UserBaseService {
      
    @Resource
      private UserBaseMapper userBaseMapper ;
      
    @Override
      public UserBase selectByPrimaryKey(Integer id) {
          return userBaseMapper.selectByPrimaryKey(id);
      }
      // 使用指定數(shù)據(jù)源的事務(wù)
      
    @Transactional(value = "transactionManagerTwo")
      
    @Override
      public void insert(UserBase record) {
          // 這里數(shù)據(jù)寫(xiě)入失敗
          userBaseMapper.insert(record) ;
          // int i = 1/0 ;
      }
    }

    注意:這里的需要指定該數(shù)據(jù)源配置的事務(wù)管理器。

三、MybatisPlus案例

1、核心依賴(lài)

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.0.7.1</version>
    <exclusions>
        <exclusion>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>3.0.7.1</version>
</dependency>

2、配置文件

mybatis-plus:
  mapper-locations: classpath*:/mapper/*.xml
  typeAliasesPackage: com.digital.market.*.entity
  global-config:
    db-config:
      id-type: AUTO
      field-strategy: NOT_NULL
      logic-delete-value: -1
      logic-not-delete-value: 0
    banner: false
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: true
    cache-enabled: false
    call-setters-on-nulls: true
    jdbc-type-for-null: 'null'

3、分層配置

mapper層
UserBaseMapper extends BaseMapper<UserBase>
實(shí)現(xiàn)層
UserBaseServiceImpl extends ServiceImpl<UserBaseMapper,UserBase> implements UserBaseService
接口層
UserBaseService extends IService<UserBase>

4、mapper.xml文件

<mapper namespace="com.plus.batis.mapper.UserBaseMapper" >
  <resultMap id="BaseResultMap" type="com.plus.batis.entity.UserBase" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="user_name" property="userName" jdbcType="VARCHAR" />
    <result column="pass_word" property="passWord" jdbcType="VARCHAR" />
    <result column="phone" property="phone" jdbcType="VARCHAR" />
    <result column="email" property="email" jdbcType="VARCHAR" />
    <result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
    <result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
    <result column="state" property="state" jdbcType="INTEGER" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, user_name, pass_word, phone, email, create_time, update_time, state
  </sql>
  <select id="selectByParam" parameterType="com.plus.batis.entity.QueryParam" resultMap="BaseResultMap">
    select * from hc_user_base
  </select>
</mapper>

注意事項(xiàng)

BaseMapper中的方法都已默認(rèn)實(shí)現(xiàn);這里也可以自定義實(shí)現(xiàn)一些自己的方法。

5、演示接口

@RestController
@RequestMapping("/user")
public class UserBaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserBaseController.class) ;
    @Resource
    private UserBaseService userBaseService ;
    @RequestMapping("/info")
    public UserBase getUserBase (){
        return userBaseService.getById(1) ;
    }
    @RequestMapping("/queryInfo")
    public String queryInfo (){
        UserBase userBase1 = userBaseService.getOne(new QueryWrapper<UserBase>().orderByDesc("create_time")) ;
        LOGGER.info("倒敘取值:{}",userBase1.getUserName());
        Integer count = userBaseService.count() ;
        LOGGER.info("查詢(xún)總數(shù):{}",count);
        UserBase userBase2 = new UserBase() ;
        userBase2.setId(1);
        userBase2.setUserName("spring");
        boolean resFlag = userBaseService.saveOrUpdate(userBase2) ;
        LOGGER.info("保存更新:{}",resFlag);
        Map<String, Object> listByMap = new HashMap<>() ;
        listByMap.put("state","0") ;
        Collection<UserBase> listMap = userBaseService.listByMap(listByMap) ;
        LOGGER.info("ListByMap查詢(xún):{}",listMap);
        boolean removeFlag = userBaseService.removeById(3) ;
        LOGGER.info("刪除數(shù)據(jù):{}",removeFlag);
        return "success" ;
    }
    @RequestMapping("/queryPage")
    public IPage<UserBase> queryPage (){
        QueryParam param = new QueryParam() ;
        param.setPage(1);
        param.setPageSize(10);
        param.setUserName("cicada");
        param.setState(0);
        return userBaseService.queryPage(param) ;
    }
    @RequestMapping("/pageHelper")
    public PageInfo<UserBase> pageHelper (){
        return userBaseService.pageHelper(new QueryParam()) ;
    }
}

這里pageHelper方法是使用PageHelper插件自定義的方法。

“SpringBoot整合MybatisPlus配置多數(shù)據(jù)源增強(qiáng)插件的方法是什么”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI