前言
之前我们做过jpa访问mysql的案例,那么jpa如何设置多数据源访问呢?本节我们就来做jpa多数据源的案例
创建空项目
IDEA创建一个空依赖springboot项目
添加依赖
pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
添加配置
application.yml:
spring:
datasource:
master:
username: root
password: 123456
url: jdbc:mysql://192.168.145.131:3306/test
driver-class-name: com.mysql.cj.jdbc.Driver
slave:
username: root
password: 123456
url: jdbc:mysql://192.168.145.131:3306/test2
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
properties:
hibernate:
hbm2ddl:
auto: update
master/slave可以自己任意命名,数据源可以随意增加多个
建库
我们新增test/test2数据库 test新建表
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL,
`age` int(11) NOT NULL,
`grade` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `student` VALUES ('1', '1', '1', '1');
test2新建表:
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher` (
`id` int(11) NOT NULL,
`age` varchar(255) DEFAULT NULL,
`course` varchar(255) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `teacher` VALUES ('1', '1', '1', '1');
完善
目录结构
我们先完善配置包类 config/DataSourceConfig:
package com.mrcoder.sbjpamultidb.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
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 DataSourceConfig {
//master库
@Primary
@Bean(name = "masterDataSourceProperties")
@Qualifier("masterDataSourceProperties")
@ConfigurationProperties(prefix = "spring.datasource.master")
public DataSourceProperties masterDataSourceProperties() {
return new DataSourceProperties();
}
@Primary
@Bean(name = "masterDataSource")
@Qualifier("masterDataSource")
@ConfigurationProperties(prefix = "spring.datasource.master")
public DataSource masterDataSource(@Qualifier("masterDataSourceProperties") DataSourceProperties dataSourceProperties) {
return dataSourceProperties.initializeDataSourceBuilder().build();
}
//slave库
@Bean(name = "slaveDataSourceProperties")
@Qualifier("slaveDataSourceProperties")
@ConfigurationProperties(prefix = "spring.datasource.slave")
public DataSourceProperties slaveDataSourceProperties() {
return new DataSourceProperties();
}
@Bean(name = "slaveDataSource")
@Qualifier("slaveDataSource")
@ConfigurationProperties(prefix = "spring.datasource.slave")
public DataSource slaveDataSource(@Qualifier("slaveDataSourceProperties") DataSourceProperties dataSourceProperties) {
return dataSourceProperties.initializeDataSourceBuilder().build();
}
}
```
config/MasterConfig:
```
package com.mrcoder.sbjpamultidb.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "masterEntityManagerFactory",
transactionManagerRef = "masterTransactionManager",
basePackages = {"com.mrcoder.sbjpamultidb.entity.master"})
public class MasterConfig {
@Autowired
private HibernateProperties hibernateProperties;
@Resource
@Qualifier("masterDataSource")
private DataSource masterDataSource;
@Primary
@Bean(name = "masterEntityManager")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return masterEntityManagerFactory(builder).getObject().createEntityManager();
}
@Resource
private JpaProperties jpaProperties;
// private Map<String, Object> getVendorProperties() {
// return jpaProperties.getHibernateProperties(new HibernateSettings());
// }
/**
* 设置实体类所在位置
*/
@Primary
@Bean(name = "masterEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean masterEntityManagerFactory(EntityManagerFactoryBuilder builder) {
Map<String, Object> properties = hibernateProperties.determineHibernateProperties(
jpaProperties.getProperties(), new HibernateSettings());
return builder
.dataSource(masterDataSource)
.packages("com.mrcoder.sbjpamultidb.entity.master")
.persistenceUnit("masterPersistenceUnit")
.properties(properties)
.build();
}
@Primary
@Bean(name = "masterTransactionManager")
public PlatformTransactionManager masterTransactionManager(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(masterEntityManagerFactory(builder).getObject());
}
}
```
config/SlaveConfig:
```
package com.mrcoder.sbjpamultidb.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "slaveEntityManagerFactory",
transactionManagerRef = "slaveTransactionManager",
basePackages = {"com.mrcoder.sbjpamultidb.entity.slave"})//repository的目录
public class SlaveConfig {
@Autowired
@Qualifier("slaveDataSource")
private DataSource slaveDataSource;
@Autowired
private HibernateProperties hibernateProperties;
@Bean(name = "slaveEntityManager")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return slaveEntityManagerFactory(builder).getObject().createEntityManager();
}
@Resource
private JpaProperties jpaProperties;
// private Map<String, Object> getVendorProperties() {
// return jpaProperties.getHibernateProperties(new HibernateSettings());
// }
@Bean(name = "slaveEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean slaveEntityManagerFactory(EntityManagerFactoryBuilder builder) {
Map<String, Object> properties = hibernateProperties.determineHibernateProperties(
jpaProperties.getProperties(), new HibernateSettings());
return builder
.dataSource(slaveDataSource)
.packages("com.mrcoder.sbjpamultidb.entity.slave")//实体类的目录
.persistenceUnit("slavePersistenceUnit")
.properties(properties)
.build();
}
@Bean(name = "slaveTransactionManager")
PlatformTransactionManager slaveTransactionManager(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(slaveEntityManagerFactory(builder).getObject());
}
}
```
controller/JpaMultidbController:
```
package com.mrcoder.sbjpamultidb.controller;
import com.mrcoder.sbjpamultidb.entity.master.StudentDao;
import com.mrcoder.sbjpamultidb.entity.slave.TeacherDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class JpaMultidbController {
@Autowired
private StudentDao studentDao;
@Autowired
private TeacherDao teacherDao;
@RequestMapping("/list")
public void list() {
System.out.println(studentDao.findAll());
System.out.println(teacherDao.findAll());
}
}
```
entity/master/Student:
```
package com.mrcoder.sbjpamultidb.entity.master;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Student {
@Id
@GeneratedValue
private int id;
private String name;
private int age;
private int grade;
public Student() {
}
public Student(String name, int age, int grade) {
this.name = name;
this.age = age;
this.grade = grade;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", grade=" + grade +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
```
entity/master/StudentDao:
```
package com.mrcoder.sbjpamultidb.entity.master;
import org.springframework.data.jpa.repository.JpaRepository;
public interface StudentDao extends JpaRepository<Student, Integer> {
}
```
entity/slave/Teacher:
```
package com.mrcoder.sbjpamultidb.entity.slave;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Teacher {
@Id
@GeneratedValue
private int id;
private String name;
private String age;
private String course;
public Teacher() {
}
public Teacher(String name, String age, String course) {
this.name = name;
this.age = age;
this.course = course;
}
@Override
public String toString() {
return "Teacher{" +
"id=" + id +
", name='" + name + '\'' +
", age='" + age + '\'' +
", course='" + course + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
```
entity/slave/TeacherDao:
```
package com.mrcoder.sbjpamultidb.entity.slave;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TeacherDao extends JpaRepository<Teacher,Integer> {
}
```
## 运行
![5.png](https://upload-images.jianshu.io/upload_images/16747124-fdc5d3cc3908b343.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
## 项目地址
https://github.com/MrCoderStack/SpringBootDemo/tree/master/sb-jpa-multidb
https://gitee.com/MrCoderStack/SpringBootDemo/tree/master/sb-jpa-multidb
## 请关注我的订阅号
![订阅号.png](https://upload-images.jianshu.io/upload_images/16747124-b89acf15e2272701.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)