前言
项目中经常会遇到使用多个数据源的情况。这里是基于 JPA 来配置多个数据源。此配置是给予java1.8,闲话少说,一起来看看文章内容吧。
1.引入maven依赖
<dependencies>
<!--****spring data jpa ****-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--**** web-services ****-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<!--**** lombok ****-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--**** 阿里的数据源 ****-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!--**** mysql ****-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--**** test ****-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
2.配置数据库和jpa一些简易配置
spring:
datasource:
primary:
driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/primary?useUnicode=true&characterEncoding=UTF-8&useOldAliasMetadataBehavior=true&serverTimezone=Asia/Shanghai
username: root
password: root
second:
driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/second?useUnicode=true&characterEncoding=UTF-8&useOldAliasMetadataBehavior=true&serverTimezone=Asia/Shanghai
username: root
password: root
jpa:
show-sql: false
hibernate:
format_sql: true
primary-dialect: org.hibernate.dialect.MySQL55Dialect
second-dialect: org.hibernate.dialect.MySQL55Dialect
3.多数据源配置
DataSourceConfig
@Configuration
public class DataSourceConfig {
/**
* 第一个数据连接,默认优先级最高
* @return
*/
@Primary
@Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.primary")
public DataSource PrimaryDataSource() {
return DataSourceBuilder.create().type(DruidDataSource.class).build();
}
/**
* 第二个数据源
* @return
*/
@Bean(name = "secondDataSource")
@Qualifier("secondDataSource")
@ConfigurationProperties(prefix="spring.datasource.second")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().type(DruidDataSource.class).build();
}
}
PrimaryConfig
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactoryPrimary",
transactionManagerRef="transactionManagerPrimary",
basePackages= { "xin.zhuyao.springbootjapdatasource.repository.primary" })
public class PrimaryConfig {
@Autowired
private Environment env;
@Autowired
@Qualifier("primaryDataSource")
private DataSource primaryDataSource;
@Primary
@Bean(name = "entityManagerPrimary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
@Primary
@Bean(name = "entityManagerFactoryPrimary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
return builder
.dataSource(primaryDataSource)
.properties(getVendorProperties())
.packages("xin.zhuyao.springbootjapdatasource.domain.primary")
.persistenceUnit("primaryPersistenceUnit")
.build();
}
private Map<String, String> getVendorProperties() {
Map<String, String> jpaProperties = new HashMap<>(16);
jpaProperties.put("hibernate.hbm2ddl.auto", "update");
jpaProperties.put("hibernate.show_sql", env.getProperty("spring.jpa.show-sql"));
jpaProperties.put("hibernate.format_sql", env.getProperty("spring.jpa.hibernate.format_sql"));
jpaProperties.put("hibernate.dialect", env.getProperty("spring.jpa.hibernate.primary-dialect"));
jpaProperties.put("hibernate.current_session_context_class", "org.springframework.orm.hibernate5.SpringSessionContext");
return jpaProperties;
}
@Primary
@Bean(name = "transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}
SecondConfig
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
//实体管理
entityManagerFactoryRef="entityManagerFactorySecond",
//事务管理
transactionManagerRef="transactionManagerSecond",
//实体扫描,设置Repository所在位置
basePackages= { "xin.zhuyao.springbootjapdatasource.repository.second" })
public class SecondConfig {
@Autowired
@Qualifier("secondDataSource")
private DataSource secondDataSource;
@Autowired
private Environment env;
@Bean(name = "entityManagerSecond")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactorySecond(builder).getObject().createEntityManager();
}
@Bean(name = "entityManagerFactorySecond")
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecond (EntityManagerFactoryBuilder builder) {
return builder
.dataSource(secondDataSource)
.properties(getVendorProperties())
.packages("xin.zhuyao.springbootjapdatasource.domain.second")
.persistenceUnit("secondPersistenceUnit")
.build();
}
private Map<String, String> getVendorProperties() {
Map<String, String> jpaProperties = new HashMap<>(16);
jpaProperties.put("hibernate.hbm2ddl.auto", "update");
jpaProperties.put("hibernate.show_sql", env.getProperty("spring.jpa.show-sql"));
jpaProperties.put("hibernate.dialect", env.getProperty("spring.jpa.hibernate.Second-dialect"));
jpaProperties.put("hibernate.format_sql", env.getProperty("spring.jpa.hibernate.format_sql"));
jpaProperties.put("hibernate.current_session_context_class", "org.springframework.orm.hibernate5.SpringSessionContext");
return jpaProperties;
}
@Bean(name = "transactionManagerSecond")
PlatformTransactionManager transactionManagerSecond(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactorySecond(builder).getObject());
}
}
这样整体就结束了,配置就结束了,可以写测试了。
4.测试
UserPrimaryEntity
@Data
@Entity
@NoArgsConstructor
@Table(name = "t_user")
@FieldDefaults(level = AccessLevel.PRIVATE)
public class UserPrimaryEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
/**
* 名称
*/
String name;
/**
* 性别
*/
String sex;
}
UserSecondEntity
@Data
@Entity
@NoArgsConstructor
@Table(name = "t_user")
@FieldDefaults(level = AccessLevel.PRIVATE)
public class UserSecondEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
/**
* 名称
*/
String name;
/**
* 性别
*/
String sex;
}
UserPrimaryRepository
@Repository
public interface UserPrimaryRepository extends JpaRepository<UserPrimaryEntity, Long> {
}
UserSecondRepository
@Repository
public interface UserSecondRepository extends JpaRepository<UserSecondEntity, Long> {
}
SpringbootJapDatasourceApplicationTests
@SpringBootTest
class SpringbootJapDatasourceApplicationTests {
@Autowired
private UserPrimaryRepository userPrimaryRepository;
@Autowired
private UserSecondRepository userSecondRepository;
@Test
void contextLoads() {
System.out.println(userPrimaryRepository.findAll());
System.out.println(userSecondRepository.findAll());
}
}
测试结果:
[UserPrimaryEntity(id=1, name=zy, sex=男)]
[UserSecondEntity(id=1, name=wl, sex=女)]