Springboot2.0配置JPA多數(shù)據(jù)源連接兩個(gè)mysql數(shù)據(jù)庫(kù)方式
1. 目錄結(jié)構(gòu)及配置
pom.xml(不要亂放太多,會(huì)引起jar沖突,親身體驗(yàn))
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.luoshupeng</groupId> <artifactId>multidatasource</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>SpringBoot2-MultiDataSource</name> <description>Spring Boot 2.0 多數(shù)據(jù)源練習(xí)程序</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.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>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </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> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2. 配置文件
server.port=8080 ##\u7B2C\u4E00\u79CD\u65B9\u6CD5 spring.datasource.primary.name=primaryDB spring.datasource.primary.url=jdbc:mysql://localhost:3306/shiro?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true spring.datasource.primary.username=root spring.datasource.primary.password= spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver ##\u7B2C\u4E8C\u79CD\u65B9\u6CD5 spring.datasource.secondary.name=secondaryDB #spring.datasource.secondary.url=jdbc:h2:mem:test-db2 spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true spring.datasource.secondary.username=root spring.datasource.secondary.password= spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.show-sql=true spring.jpa.properties.hibernate.hbm2ddl.auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
3. DataSourceConfigurer類
(兩種方法,取任何一種都可以,此程序中兩種都有demo)
@Configuration public class DataSourceConfigurer { /** * 第一種方法 * @return */ @Primary @Bean(name = "primaryDataSourceProperties") @ConfigurationProperties(prefix = "spring.datasource.primary") public DataSourceProperties primaryDataSourceProperties() { return new DataSourceProperties(); } @Primary @Bean(name = "primaryDataSource") @ConfigurationProperties(prefix = "spring.datasource.primary") public DataSource primaryDataSource() { return primaryDataSourceProperties().initializeDataSourceBuilder().build(); } /** * 第二種方法 * @return */ @Bean(name = "secondaryDataSource") @ConfigurationProperties(prefix = "spring.datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } }
4. 主數(shù)據(jù)源配置
(需要改兩處,1.注解處basePackages=“****”//此處對(duì)應(yīng)程序dao層 全路徑包名,2. LocalContainerEntityManagerFactoryBean方法下的.packeages(“***”)//pojo類全類名) @Configuration @EnableTransactionManagement @EnableJpaRepositories( entityManagerFactoryRef = "entityManagerFactoryPrimary", transactionManagerRef = "transactionManagerPrimary", basePackages = {"com.luoshupeng.multidatasource.primary"}) public class PrimaryConfigurer { @Resource(name = "primaryDataSource") private DataSource primaryDataSource; @Autowired private JpaProperties jpaProperties; private Map<String, Object> getVendorProperties() { return jpaProperties.getHibernateProperties(new HibernateSettings()); } @Primary @Bean(name = "entityManagerFactoryPrimary") public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary(EntityManagerFactoryBuilder builder) { return builder.dataSource(primaryDataSource).properties(getVendorProperties()) .packages("com.luoshupeng.multidatasource.primary").persistenceUnit("primaryPersistenceUnit") .build(); } @Primary @Bean(name = "entityManagerPrimary") public EntityManager entityManager(EntityManagerFactoryBuilder builder) { return entityManagerFactoryPrimary(builder).getObject().createEntityManager(); } @Primary @Bean(name = "transactionManagerPrimary") public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) { return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject()); } }
5. 從數(shù)據(jù)源配置
(需要改兩處,1.注解處basePackages=“****”//此處對(duì)應(yīng)程序dao層 全路徑包名,2. LocalContainerEntityManagerFactoryBean方法下的.packeages(“***”)//pojo類全類名) @Configuration @EnableTransactionManagement @EnableJpaRepositories( transactionManagerRef = "transactionManagerSecondary", entityManagerFactoryRef = "entityManagerFactorySecondary", basePackages = {"com.luoshupeng.multidatasource.secondary.repository"}) public class SecondaryConfigurer { //@Resource(name = "secondaryDataSource") @Autowired @Qualifier(value = "secondaryDataSource") private DataSource secondaryDataSource; @Autowired private JpaProperties jpaProperties; private Map<String, Object> getVendorProperties() { return jpaProperties.getHibernateProperties(new HibernateSettings()); } @Bean(name = "entityManagerFactorySecondary") public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary(EntityManagerFactoryBuilder builder) { return builder.dataSource(secondaryDataSource).properties(getVendorProperties()) .packages("com.luoshupeng.multidatasource.secondary.repository").persistenceUnit("secondaryPersistenceUnit") .build(); } @Bean(name = "entityManagerSecondary") public EntityManager entityManager(EntityManagerFactoryBuilder builder) { return entityManagerFactorySecondary(builder).getObject().createEntityManager(); } @Bean(name = "transactionManagerSecondary") public PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) { return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject()); } }
6.User實(shí)體類模板
package com.luoshupeng.multidatasource.primary.entity; import javax.persistence.*; /** * Created by luoshupeng on 2018-03-20 10:01 */ @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private Integer age; public User() { } public User(String name, Integer age) { this.name = name; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
7.dao層模板
//注意??!必須繼承JpaRepository import com.luoshupeng.multidatasource.primary.entity.User; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * Created by luoshupeng on 2018-03-20 10:22 */ public interface UserRepository extends JpaRepository<User, Integer> { List<User> findAll(); }
8.service模板
import com.luoshupeng.multidatasource.primary.entity.User; import com.luoshupeng.multidatasource.primary.repository.UserRepository; import com.luoshupeng.multidatasource.baseservice.IBaseService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by luoshupeng on 2018-03-20 10:26 */ @Service public class UserService implements IBaseService<User> { @Autowired UserRepository userRepository; @Override public List<User> list() { return userRepository.findAll(); } }
9.IBaseService接口
import java.util.List; /** * Created by luoshupeng on 2018-03-20 10:25 */ public interface IBaseService<T> { List<T> list(); }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解SpringBoot如何創(chuàng)建自定義Starter
Spring Boot的自動(dòng)配置機(jī)制為開(kāi)發(fā)人員提供了一種輕松集成和配置各種功能的便捷方式,本文將深入探討在Spring Boot中如何創(chuàng)建自定義Starter,為構(gòu)建模塊化且易維護(hù)的應(yīng)用提供有力的支持,需要的朋友可以參考下2024-02-02mybatis-plus的SafetyEncryptProcessor安全加密處理示例解析
這篇文章主要為大家介紹了mybatis-plus的SafetyEncryptProcessor安全加密處理示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08Java實(shí)現(xiàn)多文件壓縮加密并重命名壓縮文件對(duì)象的方法
這篇文章主要介紹了Java實(shí)現(xiàn)多文件壓縮加密并重命名壓縮文件對(duì)象的方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01Java?詳解Collection集合之ArrayList和HashSet
本章具體介紹了ArrayList和HashSet兩種集合的基本使用方法和區(qū)別,圖解穿插代碼實(shí)現(xiàn)。?JAVA成仙路從基礎(chǔ)開(kāi)始講,后續(xù)會(huì)講到JAVA高級(jí),中間會(huì)穿插面試題和項(xiàng)目實(shí)戰(zhàn),希望能給大家?guī)?lái)幫助2022-03-03Java靜態(tài)方法不能調(diào)用非靜態(tài)成員的原因分析
在Java中,靜態(tài)方法是屬于類的方法,而不是屬于對(duì)象的方法,它可以通過(guò)類名直接調(diào)用,無(wú)需創(chuàng)建對(duì)象實(shí)例,非靜態(tài)成員指的是類的實(shí)例變量和實(shí)例方法,它們需要通過(guò)對(duì)象實(shí)例才能訪問(wèn)和調(diào)用,本文小編將和大家一起探討Java靜態(tài)方法為什么不能調(diào)用非靜態(tài)成員2023-10-10Springboot中@Async異步,實(shí)現(xiàn)異步結(jié)果合并統(tǒng)一返回方式
這篇文章主要介紹了Springboot中@Async異步,實(shí)現(xiàn)異步結(jié)果合并統(tǒng)一返回方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09