05_Spring Boot 多数据源配置:Spring-data-jpa

1、pom.xml配置

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

4.0.0

com.linjb

springboot-multi-source-jpa

war

0.0.1-SNAPSHOT

springboot-multi-source-jpa Maven Webapp

http://maven.apache.org

org.springframework.boot

spring-boot-starter-parent

1.3.3.RELEASE

org.springframework.boot

spring-boot-starter

org.springframework.boot

spring-boot-starter-web

mysql

mysql-connector-java

org.springframework.boot

spring-boot-starter-data-jpa

springboot-multi-source-jpa

org.springframework.boot

spring-boot-maven-plugin

 

org.apache.maven.plugins

maven-compiler-plugin

1.8

1.8

UTF-8

2、application.properties 配置

## 数据源配置

spring.datasource.primary.url=jdbc:mysql://127.0.0.1:3306/test_base_1?useUnicode=true&characterEncoding=utf-8

spring.datasource.primary.username=root

spring.datasource.primary.password=bgsn

spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver

 

spring.datasource.secondary.url=jdbc:mysql://127.0.0.1:3306/test_user_1?useUnicode=true&characterEncoding=utf-8

spring.datasource.secondary.username=root

spring.datasource.secondary.password=bgsn

spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver

3、数据源配置类:

1)、DataSourceConfig

package com.linjb.config;

 

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;

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;

 

@Configuration

public class DataSourceConfig {

 

@Bean(name = "primaryDataSource")

@Qualifier("primaryDataSource")

@ConfigurationProperties(prefix="spring.datasource.primary")

public DataSource primaryDataSource() {

return DataSourceBuilder.create().build();

}

 

@Bean(name = "secondaryDataSource")

@Qualifier("secondaryDataSource")

@Primary

@ConfigurationProperties(prefix="spring.datasource.secondary")

public DataSource secondaryDataSource() {

return DataSourceBuilder.create().build();

}

 

}

 

定义两个DataSource用来读取application.properties中的不同配置。如上例子中,主数据源配置为spring.datasource.primary开头的配置,第二数据源配置为spring.datasource.secondary开头的配置。

 

新增对第一数据源的JPA配置,注意两处注释的地方,用于指定数据源对应的Entity实体和Repository定义位置,用@Primary区分主数据源。

package com.linjb.config;

 

import java.util.Map;

import javax.persistence.EntityManager;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;

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;

 

@Configuration

@EnableTransactionManagement

@EnableJpaRepositories(

entityManagerFactoryRef="entityManagerFactoryPrimary",

transactionManagerRef="transactionManagerPrimary",

basePackages= { "com.linjb.model.p" }) //设置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.linjb.model.p") //设置实体类所在位置

.persistenceUnit("primaryPersistenceUnit")

.build();

}

 

@Autowired

private JpaProperties jpaProperties;

 

private Map getVendorProperties(DataSource dataSource) {

return jpaProperties.getHibernateProperties(dataSource);

}

 

@Primary

@Bean(name = "transactionManagerPrimary")

public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {

return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());

}

}

 

新增对第二数据源的JPA配置,内容与第一数据源类似,具体如下:

package com.linjb.config;

 

import java.util.Map;

import javax.persistence.EntityManager;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;

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;

 

@Configuration

@EnableTransactionManagement

@EnableJpaRepositories(

entityManagerFactoryRef="entityManagerFactorySecondary",

transactionManagerRef="transactionManagerSecondary",

basePackages= { "com.linjb.model.s" }) //设置Repository所在位置

public class SecondaryConfig {

 

@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.linjb.model.s") //设置实体类所在位置

.persistenceUnit("secondaryPersistenceUnit")

.build();

}

 

@Autowired

private JpaProperties jpaProperties;

 

private Map getVendorProperties(DataSource dataSource) {

return jpaProperties.getHibernateProperties(dataSource);

}

 

@Bean(name = "transactionManagerSecondary")

PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {

return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());

}

}

 

4、Model层

完成了以上配置之后,主数据源的实体和数据访问对象位于:com.linjb.model.p,次数据源的实体和数据访问接口位于:com.linjb.model.s。

分别在这两个package下创建各自的实体和数据访问接口

 

package com.linjb.model.p;

 

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

 

@Entity

public class College {

 

@Id

@GeneratedValue

private Integer collegeId;

@Column(nullable = false)

private String collegeName;

public Integer getCollegeId() {

return collegeId;

}

public void setCollegeId(Integer collegeId) {

this.collegeId = collegeId;

}

public String getCollegeName() {

return collegeName;

}

public void setCollegeName(String collegeName) {

this.collegeName = collegeName;

}

}

 

package com.linjb.model.p;

 

import org.springframework.data.jpa.repository.JpaRepository;

 

public interface CollegeRepository extends JpaRepository{

 

}

 

package com.linjb.model.s;

 

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

 

@Entity

public class UserLogin {

 

@Id

@GeneratedValue

private Integer userId;

@Column(nullable = false)

private String username;

@Column(nullable = false)

private String pwd;

public Integer getUserId() {

return userId;

}

public void setUserId(Integer userId) {

this.userId = userId;

}

public String getUsername() {

return username;

}

public void setUsername(String username) {

this.username = username;

}

public String getPwd() {

return pwd;

}

public void setPwd(String pwd) {

this.pwd = pwd;

}

}

 

package com.linjb.model.s;

 

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

 

public interface UserLoginRepository extends JpaRepository{

 

List findByUsername(String username);

}

5、Controller层

package com.linjb.controller;

 

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

import com.linjb.model.p.College;

import com.linjb.model.p.CollegeRepository;

 

@RestController

@RequestMapping(value = "/college")

public class CollegeController {

 

@Autowired

private CollegeRepository collegeRepository;

@RequestMapping(value="/findAll", method=RequestMethod.POST)

public List findAll(){

return collegeRepository.findAll();

}

}

 

package com.linjb.controller;

 

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

import com.linjb.model.s.UserLogin;

import com.linjb.model.s.UserLoginRepository;

 

@RestController

@RequestMapping(value = "/userLogin")

public class UserLoginController {

 

@Autowired

private UserLoginRepository userLoginRepository ;

@RequestMapping(value="/login", method=RequestMethod.POST)

public String login(@RequestBody UserLogin userLogin){

List list=userLoginRepository.findByUsername(userLogin.getUsername());

if(null != list){

if(list.get(0).getPwd().equals(userLogin.getPwd())){

return "success";

}

}

return "false";

}

}

 

 

6、Application启动类

package com.linjb;

 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

 

/**

* Spring Boot应用启动类

* @Copyright Copyright (C) 2019 linjb

* @author linjb

* @version 1.0

* @CreateDate 2019年1月31日下午10:25:16

*/

@SpringBootApplication

public class Application /*extends SpringBootServletInitializer*/{

 

public static void main(String[] args) {

SpringApplication.run(Application.class,args);

}

// @Override

// protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {

//

// return builder.sources(Application.class);

// }

}

你可能感兴趣的:(搬砖之,SpringBoot,专栏)