springBoot+Hibernate(Jpa)多数据源配置与使⽤
在学习的过程中,⼤多时候项⽬与数据库都在本机上,使⽤hibernate或者mybatits加上简单的配置就能够打通程序到数据库路径,让程序能够访问到数据库。然⽽在⼀些情况下,我们不仅需要访问本机的数据库,还需要访问到另外⼀个数据库中的资源。本⽂书写的⽬的便在于解决访问多资源库的问题,更多的是为了交流与学习。学习,源码是很重要的。⽂末给出了我的Github中的源码链接,感兴趣的可以下载阅览。
⼀、项⽬创建与资源⽂件配置
建⽴⼀个初始的spring项⽬的⽅式在我的另⼀篇⽂章已经详细介绍了,在这⾥就不多赘述。当然,⽹上也有很多详细的教程,你也可以⾃⾏搜索阅览。新建好的项⽬的l⽂件中已经集成了必要的依赖包。本⽂所⽤到的l⽂件如下。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>thymeleaf用法
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.40</version>
</dependency>
<dependency>
<groupId>kohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
<!--部署热启动依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.7.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration><!--热启动配置-->
<fork>true</fork>
<addResources>true</addResources>
</configuration>
</plugin>
</plugins>
</build>
当初始化好⼀个项⽬后,⾸先要进⾏的便是各类资源⽂件的配置,这时springboot的强⼤便体现的淋漓尽致,仅需要少量的信息配置就能
替代spring⼤量的xml⽂件配置。在springboot中甚⾄都不需要配置l,仅需要在⾃带的application.properties⽂件中进⾏数据库
等信息配置。
对于本⽂的⼯程Demo资源⽂件配置,⾸先,需要数据库吧,还是两个,所以两个数据库源都得配置吧。其次,⽤到了hibernate,也需要
配置⼀下。⾄此必要的配置就结束了,就这么简单。
spring.datasource.primary.url=jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true spring.datasource.primary.username=root
spring.datasource.primary.password=xxxxx
spring.datasource.primary.sql.jdbc.Driver
spring.datasource.max-active=10
spring.datasource.primary.max-idle=5
spring.datasource.primary.min-idle=0
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true spring.datasource.secondary.username=root
spring.datasource.secondary.password=xxxxx
spring.datasource.secondary.sql.jdbc.Driver
spring.datasource.secondary.max-active=10
spring.datasource.secondary.max-idle=5
spring.datasource.secondary.min-idle=0
#新设置访问接⼝,默认为8080
server.port=80
#hibernate配置
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
#前端html的配置,解除严格语法检查,前端才⽤到
spring.thymeleaf.cache=false
de=LEGACYHTML5
⼆、多资源库配置
细⼼的你或许发现了多资源库时的资源⽂件配置与单资源库时的配置不⼀样,默认时的配置为
spring.datasource.url=jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
spring.datasource.username=root
spring.datasource.password=xxxxx
spring.datasource.sql.jdbc.Driver
spring.datasource.max-active=10
spring.datasource.max-idle=5
spring.datasource.min-idle=0
⽽本⽂的配置为
spring.datasource.primary.url=jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true spring.datasource.primary.username=root
spring.datasource.primary.password=xxxxx
spring.datasource.primary.sql.jdbc.Driver
spring.datasource.max-active=10
spring.datasource.primary.max-idle=5
spring.datasource.primary.min-idle=0
数据库字段做了⼀些更改,⼀点变动貌似看起来没啥关系,但是变了之后springboot就不认识这东西,不知道它是数据库的信息配置,因此我们需要重新定义。
⾸先,定义数据源,并且注明⼀个主数据源,⼀个从数据源。直接在java⽬录下,你所定义的项⽬⽂件包(假如为)下,新建⼀个DataSourceConfig.java⽂件。
@Configuration
public class DataSourcesConfig {
@Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
@Primary
@ConfigurationProperties(prefix="spring.datasource.primary")
public DataSource primaryDataSource() {
System.out.println("primary db built");
ate().build();
}
@Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.secondary")
public DataSource secondaryDataSource() {
System.out.println("secondary db built");
ate().build();
}
}
这样就相当于告诉程序,程序要⽤到两个数据库,于是程序就去连接这两个数据库。怎么连接呢,默认的连接已经⾏不通了,因此,对于每个数据库还需要有⼀个定义⽂件告诉程序如何去连接它。
同样,我们在包下新建两个数据库定义⽂件PrimaryConfig.java与SecondaryConfig.java,分别定义主数据库与从数据库。
PrimaryConfig.java
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactoryPrimary",
transactionManagerRef="transactionManagerPrimary",
basePackages= { "com.springboot.pository.user" }) //设置Repository所在位置
public class PrimaryConfig {
@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(primaryDataSource))
.packages("com.springboot.ity.user") //设置实体类所在位置
.persistenceUnit("primaryPersistenceUnit")
.build();
}
@Autowired(required=false)
private JpaProperties jpaProperties;
private Map<String, String> getVendorProperties(DataSource dataSource) {
HibernateProperties(dataSource);
}
@Primary
@Bean(name = "transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}
SecondaryConfig.java
package com.springboot.multi_resources;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jpa.JpaProperties;
import org.jpa.EntityManagerFactoryBuilder;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.fig.EnableJpaRepositories;
import jpa.JpaTransactionManager;
import jpa.LocalContainerEntityManagerFactoryBean;
import ansaction.PlatformTransactionManager;
import ansaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactorySecondary",
transactionManagerRef="transactionManagerSecondary",
basePackages= { "com.springboot.pository.work" }) //设置Repository所在位置
public class SecondaryConfig {
@Autowired
private JpaProperties jpaProperties;
@Autowired@Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;
@Bean(name = "entityManagerSecondary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactorySecondary(builder).getObject().createEntityManager();
}
@Bean(name = "entityManagerFactorySecondary")
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder) {
return builder
.dataSource(secondaryDataSource)
.properties(getVendorProperties(secondaryDataSource))
.packages("com.springboot.ity.work") //设置实体类所在位置
.persistenceUnit("secondaryPersistenceUnit")
.build();
}
private Map<String, String> getVendorProperties(DataSource dataSource) {
HibernateProperties(dataSource);
}
@Bean(name = "transactionManagerSecondary")
PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
}
}
3、功能实现
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论