MyBatis und MyBatis-plus konfigurieren mehrere Datenquellen und betreiben mehrere Datenbanken

1. Lernen Sie MyBatis und MyBatis-plus:

mybatis: Offizielle Website-Dokumentation: mybatis – MyBatis 3 | Einführung

mybatis-plus: Offizielle Website-Dokumentation: MyBatis-Plus

Zweitens wird MyBatis verwendet, um eine Abfrage mit mehreren Datenquellen zu implementieren:

Format der Konfigurationsdatei:

spring:
  datasource: 
    db1:
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useUnicode=true&timeZone=UTC
      username: root
      password: root
    db2:
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://localhost:3306/test1?characterEncoding=utf8&useUnicode=true&timeZone=UTC
      username: root
      password: root

Hinweis: Ändern Sie die URL in der Datenbankkonfiguration in jdbc-url, da sonst nicht mehrere Datenquellen konfiguriert werden können.


Konfigurieren Sie die Datenquelle in config:

Erstellen Sie zwei verschiedene Datenkonfigurationsressourcen:

Erste:
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.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.czf.connect.mapper.db1", sqlSessionTemplateRef  = "db1SqlSessionTemplate")
//此处的basePackages指向的是你存放数据库db1的mapper的包
public class DataSource1Config {

    @Bean(name = "db1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db1")//指向yml配置文件中的数据库配置
    @Primary    //主库加这个注解,修改优先权,表示发现相同类型bean,优先使用该方法。
    public DataSource dbDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "db1SqlSessionFactory")
    @Primary
    public SqlSessionFactory dbSqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*xml"));
        //这个的getResources指向的是你的mapper.xml文件,相当于在yml中配置的mapper-locations,此处配置了yml中就不用配置,或者说不会读取yml中的该配置。
        return bean.getObject();
    }

    @Bean(name = "db1TransactionManager")
    @Primary
    public DataSourceTransactionManager dbTransactionManager(@Qualifier("db1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "db1SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate dbSqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

der Zweite:
@Configuration
@MapperScan(basePackages = "com.czf.connect.mapper.db2", sqlSessionTemplateRef  = "db2SqlSessionTemplate")
public class DataSource2Config {

    @Bean(name = "db2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource dbDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "db2SqlSessionFactory")
    public SqlSessionFactory dbSqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*xml"));
        return bean.getObject();
    }

    @Bean(name = "db2TransactionManager")
    public DataSourceTransactionManager dbTransactionManager(@Qualifier("db2DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "db2SqlSessionTemplate")
    public SqlSessionTemplate dbSqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

Zu diesem Zeitpunkt müssen Sie lediglich die entsprechende Mapper-Klasse im entsprechenden com///mapper/db-Paket erstellen oder eine bestimmte SQL-Anweisung schreiben, welche Datenbank geändert oder abgefragt werden muss.


Drittens wird MyBatis-plus verwendet, um eine Abfrage mehrerer Datenquellen zu implementieren:


1. Konfigurationsdatei:

spring:
  datasource:
    dynamic:
      primary: teacher #设置默认的数据源或者数据源组,默认值即为master
      strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
      datasource:
        teacher:
          url: jdbc:mysql://localhost:3306/test1?characterEncoding=utf8&useUnicode=true&timeZone=UTC
          driver-class-name: com.mysql.jdbc.Driver
          username: root
          password: root
        student:
          url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useUnicode=true&timeZone=UTC
          driver-class-name: com.mysql.jdbc.Driver
          username: root
          password: root

2. Abhängigkeitspakete importieren:

<!--     多数据源   -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.5.0</version>
        </dependency>

3.Verwendung:

package com.example.multidatasource.generator.mapper;


import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.multidatasource.generator.domain.Teacher;
import org.apache.ibatis.annotations.Mapper;

/**
* @author 29291
* @description 针对表【teacher】的数据库操作Mapper
* @createDate 2023-08-07 23:25:22
* @Entity generator.domain.Teacher
*/

@Mapper
@DS("slave")
public interface TeacherMapper extends BaseMapper<Teacher> {

}




 

Acho que você gosta

Origin blog.csdn.net/m0_55699184/article/details/132182702
Recomendado
Clasificación