您现在的位置是:首页 >技术杂谈 >SpringBoot—JPA和Mybatis多数据源配置和使用网站首页技术杂谈
SpringBoot—JPA和Mybatis多数据源配置和使用
简介SpringBoot—JPA和Mybatis多数据源配置和使用
JPA多数据源配置
- pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.9</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.liwang</groupId>
<artifactId>jpamulti</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jpamulti</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- 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
- 配置数据源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();
}
}
- 配置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());
}
}
- 配置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());
}
}
- 新建实体类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;
}
}
- 新建UserDao1和UserDao2
public interface UserDao1 extends JpaRepository<User, Integer> {
}
public interface UserDao2 extends JpaRepository<User, Integer> {
}
- 测试
@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多数据源配置
- pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.liwang</groupId>
<artifactId>mybatismulti</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatismulti</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- 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
- 配置数据源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();
}
}
- 配置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());
}
}
- 配置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());
}
}
- 新建实体类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;
}
}
- 新建UserMapper1 和 UserMapper1.xml
@Mapper
public interface UserMapper1 {
List<User> getAllUser();
}
<?xml version="1.0" encoding="utf-8" ?>
<!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>
- 新建UserMapper2 和 UserMapper2.xml
@Mapper
public interface UserMapper2 {
List<User> getAllUser();
}
<?xml version="1.0" encoding="utf-8" ?>
<!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>
- 测试
@SpringBootTest
class MybatismultiApplicationTests {
@Autowired
UserMapper1 userMapper1;
@Autowired
UserMapper2 userMapper2;
@Test
void contextLoads() {
System.out.println(userMapper1.getAllUser());
System.out.println(userMapper2.getAllUser());
}
}
可以看看我的个人博客:
网站:https://www.fuzm.wang / https://liwangc.gitee.io
—————————————————————————
作为初学者,很多知识都没有掌握,见谅,如有错误请指出,以期进步,感谢!。后续有新的学习,继续补充上来。
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。