栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

008.MyBatis实现多数据源

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

008.MyBatis实现多数据源

1.创建两个数据库

 

 

2.配置文件新增多数据源配置

 

server.port=8080
#单数据源
#spring.datasource.url=jdbc:postgresql://localhost:5432/javacore
#spring.datasource.username=postgres
#spring.datasource.password=asdf-1234
#spring.datasource.driver-class-name=org.postgresql.Driver

#多数据源
spring.datasource.primary.jdbc-url=jdbc:postgresql://localhost:5432/javacore
spring.datasource.primary.username=postgres
spring.datasource.primary.password=asdf-1234
spring.datasource.primary.driver-class-name=org.postgresql.Driver

spring.datasource.secondary.jdbc-url=jdbc:postgresql://localhost:5432/postgres
spring.datasource.secondary.username=postgres
spring.datasource.secondary.password=asdf-1234
spring.datasource.secondary.driver-class-name=org.postgresql.Driver

#mybatis.mapper-locations=classpath:mapper/*.xml

3.创建一个多数据源配置类

 

package com.javacore;

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 javax.sql.DataSource;

@Configuration
public class DataSourceConfiguration {

    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }

}

 

4.创建数据库1的配置

package com.javacore;


import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(
        //扫描entity类和mapper类
        basePackages = "com.javacore.mybatis.p.mapper",
        sqlSessionFactoryRef = "sqlSessionFactoryPrimary",
        sqlSessionTemplateRef = "sqlSessionTemplatePrimary")
public class DataSourcePrimaryConfig {

    private DataSource primaryDataSource;

    public DataSourcePrimaryConfig(@Qualifier("primaryDataSource") DataSource primaryDataSource) {
        this.primaryDataSource = primaryDataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryPrimary() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(primaryDataSource);
        // 设置mybatis的xml所在位置
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/p/*.xml")
        );

        return bean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplatePrimary() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactoryPrimary());
    }

}

 

5.创建数据库2的配置

package com.javacore;

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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(
        //扫描entity类和mapper类
        basePackages = "com.javacore.mybatis.s.mapper",
        sqlSessionFactoryRef = "sqlSessionFactorySecondary",
        sqlSessionTemplateRef = "sqlSessionTemplateSecondary")
public class DataSourceSecondaryConfig {
    private DataSource secondaryDataSource;

    public DataSourceSecondaryConfig(@Qualifier("secondaryDataSource") DataSource secondaryDataSource) {
        this.secondaryDataSource = secondaryDataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactorySecondary() throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(secondaryDataSource);
        // 设置mybatis的xml所在位置
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/s/*.xml")
        );
        return bean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplateSecondary() throws Exception {
        return new SqlSessionTemplate(sqlSessionFactorySecondary());
    }

}

6.创建对应的Mapper和实体-不同库创建不同的Mapper和实体,

 

 

package com.javacore.mybatis.p.mapper;


import com.javacore.mybatis.p.model.PUser;
import org.apache.ibatis.annotations.*;

@Mapper
public interface PUserMapper {

    //@Select("SELECT * FROM "User" WHERe name = #{name}")
    PUser findByName(@Param("name") String name);

    //@Insert("INSERT INTO "User"(name, age) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);

    //@Update("UPDATE "User" SET age=#{age} WHERe name=#{name}")
    void update(PUser user);

    //@Delete("DELETE FROM "User" WHERe id =#{id}")
    void delete(Long id);
}

package com.javacore.mybatis.p.model;

import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class PUser {
    private Long id;

    private String name;
    private Integer age;

    public PUser(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}
package com.javacore.mybatis.s.mapper;

import com.javacore.mybatis.s.model.SUser;
import org.apache.ibatis.annotations.*;

@Mapper
public interface SUserMapper {

    //@Select("SELECT * FROM "User" WHERe name = #{name}")
    SUser findByName(@Param("name") String name);

    //@Insert("INSERT INTO "User"(name, age) VALUES(#{name}, #{age})")
    int insert(@Param("name") String name, @Param("age") Integer age);

    //@Update("UPDATE "User" SET age=#{age} WHERe name=#{name}")
    void update(SUser user);

    //@Delete("DELETE FROM "User" WHERe id =#{id}")
    void delete(Long id);
}

package com.javacore.mybatis.s.model;

import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class SUser {
    private Long id;

    private String name;
    private Integer age;

    public SUser(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

7.配置MapperXML




    
        SELECT * FROM "User" WHERe NAME = #{name}
    

    
        INSERT INTO "User"(NAME, AGE) VALUES(#{name}, #{age})
    

    
        UPDATE "User" SET age=#{age} WHERe name=#{name}
    

    
        DELETE FROM "User" WHERe id =#{id}
    

8.测试

@SpringBootTest
class CoreApplicationTests {

    @Autowired
    private PUserMapper userMapperPrimary;
    @Autowired
    private SUserMapper userMapperSecondary;

    @Test
    public void testUserController() throws Exception {
        var up = userMapperPrimary.findByName("来源数据库1");


        var us = userMapperSecondary.findByName("来源数据库2");
      
}

 

9.使用到的POM.XML



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.2
         
    
    com.java
    core
    0.0.1-SNAPSHOT
    core
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            com.github.ulisesbocchio
            jasypt-spring-boot-starter
            3.0.3
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.projectlombok
            lombok
        
        
            io.springfox
            springfox-swagger2
            2.9.2
        
        
            io.springfox
            springfox-swagger-ui
            2.9.2
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.1.1
        
        
            org.postgresql
            postgresql
            runtime
        
        
            com.github.xiaoymin
            knife4j-spring-boot-starter
            2.0.4
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
                com.github.ulisesbocchio
                jasypt-maven-plugin
                3.0.3
            
        
    


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/704014.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号