SpringBoot—JPA和Mybatis多数据源配置和使用

JPA多数据源配置

  1. pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.7.9version>
        <relativePath/> 
    parent>
    <groupId>com.liwanggroupId>
    <artifactId>jpamultiartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>jpamultiname>
    <description>Demo project for Spring Bootdescription>
    <properties>
        <java.version>8java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jpaartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>com.mysqlgroupId>
            <artifactId>mysql-connector-jartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

  1. application.properties
spring.datasource.one.username=root
spring.datasource.one.password=root
spring.datasource.one.jdbcUrl=jdbc:mysql:///test

spring.datasource.two.username=root
spring.datasource.two.password=root
spring.datasource.two.jdbcUrl=jdbc:mysql:///test2

# 使用的数据库类型
spring.jpa.database=mysql
spring.jpa.database-platform=mysql
# 显示sql
spring.jpa.show-sql=true
# 当在java实体类中新增了一个字段,在应用重新运行时,会将字段添加到数据库表中的新列,但不会移除先前存在的列或约束
spring.jpa.hibernate.ddl-auto=update
# 配置数据库方言,默认创建数据库表使用的是myisam引擎,指定方言是为了使用innodb引擎
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
  1. 配置数据源DataSourceConfig,主要标识dsOne 为**@Primary**
@Configuration
public class DataSourceConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.one")
    @Primary
    DataSource dsOne() {
        return new HikariDataSource();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.two")
    DataSource dsTwo() {
        return new HikariDataSource();
    }
}
  1. 配置JpaConfigOne,主要配置好entityManagerFactoryRef 和transactionManagerRef
@Configuration
@EnableJpaRepositories(basePackages = "com.liwang.jpamulti.dao1", entityManagerFactoryRef = "localContainerEntityManagerFactoryBean1",
                        transactionManagerRef = "platformTransactionManager1")
public class JpaConfigOne {

    @Autowired
    @Qualifier("dsOne")
    DataSource ds;

    @Autowired
    JpaProperties jpaProperties;

    @Bean
    @Primary
    LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean1(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(ds)
                .packages("com.liwang.jpamulti.model")
                .properties(jpaProperties.getProperties())
                .persistenceUnit("pu1")
                .build();
    }

    @Bean
    PlatformTransactionManager platformTransactionManager1(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(localContainerEntityManagerFactoryBean1(builder).getObject());
    }
}
  1. 配置JpaConfigTwo
@Configuration
@EnableJpaRepositories(basePackages = "com.liwang.jpamulti.dao2", entityManagerFactoryRef = "localContainerEntityManagerFactoryBean2",
                        transactionManagerRef = "platformTransactionManager2")
public class JpaConfigTwo {

    @Autowired
    @Qualifier("dsTwo")
    DataSource ds;

    @Autowired
    JpaProperties jpaProperties;

    @Bean
    LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean2(EntityManagerFactoryBuilder builder) {
        return builder.dataSource(ds)
                .packages("com.liwang.jpamulti.model")
                .properties(jpaProperties.getProperties())
                .persistenceUnit("pu2")
                .build();
    }

    @Bean
    PlatformTransactionManager platformTransactionManager2(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(localContainerEntityManagerFactoryBean2(builder).getObject());
    }
}
  1. 新建实体类User
@Entity(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    private String username;
    private String password;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
  1. 新建UserDao1和UserDao2
public interface UserDao1 extends JpaRepository<User, Integer> {

}

public interface UserDao2 extends JpaRepository<User, Integer> {

}
  1. 测试
@SpringBootTest
class JpamultiApplicationTests {

    @Test
    void contextLoads() {
    }

    @Autowired
    UserDao1 userDao1;

    @Autowired
    UserDao2 userDao2;

    @Test
    void test01() {
        System.out.println("userDao1.findAll() = " + userDao1.findAll());
        System.out.println("userDao2.findAll() = " + userDao2.findAll());
    }

}

在这里插入图片描述

Mybatis多数据源配置

  1. pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.7.3version>
        <relativePath/> 
    parent>
    <groupId>com.liwanggroupId>
    <artifactId>mybatismultiartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>mybatismultiname>
    <description>Demo project for Spring Bootdescription>
    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.2.2version>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.xmlinclude>
                includes>
            resource>
            <resource>
                <directory>src/main/resourcesdirectory>
            resource>
        resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>


  1. application.properties
spring.datasource.one.jdbcUrl=jdbc:mysql:///test?serverTimeZone=Asia/shanghai&userUnicode=true&character=UTF-8
spring.datasource.one.username=root
spring.datasource.one.password=root
spring.datasource.two.jdbcUrl=jdbc:mysql:///test2?serverTimeZone=Asia/shanghai&userUnicode=true&character=UTF-8
spring.datasource.two.username=root
spring.datasource.two.password=root


  1. 配置数据源DataSourceConfig
@Configuration
public class DataSourceConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.one")
    DataSource dsOne() {
        return new HikariDataSource();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.two")
    DataSource dsTwo() {
        return new HikariDataSource();
    }
}
  1. 配置MybatisConfigOne
@Configuration
@MapperScan(basePackages = "com.liwang.mybatismulti.mapper1", sqlSessionFactoryRef = "sqlSessionFactory1",
        sqlSessionTemplateRef = "sqlSessionTemplate1")
public class MybatisConfigOne {

    @Autowired
    @Qualifier(value = "dsOne")
    DataSource ds;

    @Bean
    SqlSessionFactory sqlSessionFactory1() {
        SqlSessionFactory sqlSessionFactory = null;
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(ds);
        try {
            sqlSessionFactory = bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sqlSessionFactory;
    }

    @Bean
    SqlSessionTemplate sqlSessionTemplate1() {
        return new SqlSessionTemplate(sqlSessionFactory1());
    }
}
  1. 配置MybatisConfigTwo
@Configuration
@MapperScan(basePackages = "com.liwang.mybatismulti.mapper2", sqlSessionFactoryRef = "sqlSessionFactory2",
        sqlSessionTemplateRef = "sqlSessionTemplate2")
public class MybatisConfigTwo {

    @Autowired
    @Qualifier(value = "dsTwo")
    DataSource ds;

    @Bean
    SqlSessionFactory sqlSessionFactory2() {
        SqlSessionFactory sqlSessionFactory = null;
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(ds);
        try {
            sqlSessionFactory = bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sqlSessionFactory;
    }

    @Bean
    SqlSessionTemplate sqlSessionTemplate2() {
        return new SqlSessionTemplate(sqlSessionFactory2());
    }
}
  1. 新建实体类User
public class User {
    private Integer id;
    private String username;
    private String password;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
  1. 新建UserMapper1 和 UserMapper1.xml
@Mapper
public interface UserMapper1 {
    List<User> getAllUser();
}

DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.liwang.mybatismulti.mapper1.UserMapper1">

    <select id="getAllUser" resultType="com.liwang.mybatismulti.model.User">
        select * from user
    select>


mapper>

  1. 新建UserMapper2 和 UserMapper2.xml
@Mapper
public interface UserMapper2 {
    List<User> getAllUser();
}

DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.liwang.mybatismulti.mapper2.UserMapper2">

    <select id="getAllUser" resultType="com.liwang.mybatismulti.model.User">
        select * from user
    select>


mapper>

  1. 测试
@SpringBootTest
class MybatismultiApplicationTests {

    @Autowired
    UserMapper1 userMapper1;

    @Autowired
    UserMapper2 userMapper2;

    @Test
    void contextLoads() {
        System.out.println(userMapper1.getAllUser());
        System.out.println(userMapper2.getAllUser());
    }

}

SpringBoot—JPA和Mybatis多数据源配置和使用_第1张图片

可以看看我的个人博客:
网站:https://www.fuzm.wang / https://liwangc.gitee.io
—————————————————————————

作为初学者,很多知识都没有掌握,见谅,如有错误请指出,以期进步,感谢!。后续有新的学习,继续补充上来。

你可能感兴趣的:(【Spring,boot】,spring,boot,多数据源)