Spring Boot? 多数据源配置(二):Spring-data-jpa

效果图:

代码区:

package com.wls.integrateplugs.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;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@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();
    }

    @Bean(name = "primaryJdbcTemplate")
    public JdbcTemplate primaryJdbcTemplate(
            @Qualifier("primaryDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
    @Bean(name = "secondaryJdbcTemplate")
    public JdbcTemplate secondaryJdbcTemplate(
            @Qualifier("secondaryDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }
}

  

package com.wls.integrateplugs.jpa.primary.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
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.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    entityManagerFactoryRef="entityManagerFactoryPrimary",
    transactionManagerRef="transactionManagerPrimary",
    basePackages= { "com.wls.integrateplugs.jpa.primary.repository" }) //设置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.wls.integrateplugs.jpa.primary.model") //设置实体类所在位置
            .persistenceUnit("primaryPersistenceUnit")
            .build();
    }

    @Autowired
    private JpaProperties jpaProperties;

    private Map<String, String> getVendorProperties(DataSource dataSource) {
        return jpaProperties.getHibernateProperties(dataSource);
    }

    @Primary
    @Bean(name = "transactionManagerPrimary")
    public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
    }

}

  

package com.wls.integrateplugs.jpa.second.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
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.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    entityManagerFactoryRef="entityManagerFactorySecondary",
    transactionManagerRef="transactionManagerSecondary",
    basePackages= { "com.wls.integrateplugs.jpa.second.reposity" }) //设置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.wls.integrateplugs.jpa.second.model") //设置实体类所在位置
            .persistenceUnit("secondaryPersistenceUnit")
            .build();
    }

    @Autowired
    private JpaProperties jpaProperties;

    private Map<String, String> getVendorProperties(DataSource dataSource) {
        return jpaProperties.getHibernateProperties(dataSource);
    }

    @Bean(name = "transactionManagerSecondary")
    PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
    }

}

  

package com.wls.integrateplugs.jpa.primary.model;

/**
 * Created by wls on 2017/8/24.
 */
import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class User implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    private Long id;
    @Column(nullable = false, unique = true)
    private String userName;
    @Column(nullable = false)
    private String passWord;
    @Column(nullable = false, unique = true)
    private String email;
    @Column(nullable = true, unique = true)
    private String nickName;
    @Column(nullable = false)
    private String regTime;
    @Column(nullable = false)
    private String name;
    @Column(nullable = false)
    private Integer age;

    public User() {
        super();
    }

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public User(String userName, String passWord, String email, String nickName, String regTime, String name, Integer age) {
        this.userName = userName;
        this.passWord = passWord;
        this.email = email;
        this.nickName = nickName;
        this.regTime = regTime;
        this.name = name;
        this.age = age;
    }

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassWord() {
        return passWord;
    }
    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getNickName() {
        return nickName;
    }
    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
    public String getRegTime() {
        return regTime;
    }
    public void setRegTime(String regTime) {
        this.regTime = regTime;
    }

    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;
    }
}

  

package com.wls.integrateplugs.jpa.second.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 * @author 程序猿DD
 * @version 1.0.0
 * @date 16/3/21 下午3:35.
 * @blog http://blog.didispace.com
 */
@Entity
public class Message {

    @Id
    @GeneratedValue
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private String content;

    public Message(){}

    public Message(String name, String content) {
        this.name = name;
        this.content = content;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

}

  

package com.wls.integrateplugs.jpa.primary.repository;

import com.wls.integrateplugs.jpa.primary.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

/**
 * @author 程序猿DD
 * @version 1.0.0
 * @date 16/3/23 下午2:34.
 * @blog http://blog.didispace.com
 */
public interface UserRepository extends JpaRepository<User, Long> {

    User findByName(String name);

    User findByNameAndAge(String name, Integer age);

    @Query("from User u where u.name=:name")
    User findUser(@Param("name") String name);
}

  

package com.wls.integrateplugs.jpa.second.reposity;

import com.wls.integrateplugs.jpa.second.model.Message;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * @author 程序猿DD
 * @version 1.0.0
 * @date 16/3/23 下午2:34.
 * @blog http://blog.didispace.com
 */
public interface MessageRepository extends JpaRepository<Message, Long> {

}

  

package com.wls.test.integrateplugs.jpa;

import com.wls.integrateplugs.jpa.primary.model.User;
import com.wls.integrateplugs.jpa.primary.repository.UserRepository;
import com.wls.integrateplugs.jpa.second.model.Message;
import com.wls.integrateplugs.jpa.second.reposity.MessageRepository;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class JpaTest {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private MessageRepository messageRepository;

    @Before
    public void setUp() {
    }

    @Test
    public void test() throws Exception {

        userRepository.save(new User("aa","aa","aa","aa","aa","aa",12));
        userRepository.save(new User("bb","bb","bb","bb","bb","bb",13));
        userRepository.save(new User("cc","cc","cc","cc","cc","cc",14));

        Assert.assertEquals(3, userRepository.findAll().size());

        messageRepository.save(new Message("o1", "aaaaaaaaaa"));
        messageRepository.save(new Message("o2", "bbbbbbbbbb"));
        messageRepository.save(new Message("o3", "cccccccccc"));

        Assert.assertEquals(3, messageRepository.findAll().size());

    }

}

  

spring:
  datasource:
    primary:
      driver-class-name: com.mysql.jdbc.Driver
  #    url: jdbc:mysql://192.168.159.128:3306/mydb
      url: jdbc:mysql://192.168.223.128:3306/db1
      username: wls
      password: Wls141215!
    secondary:
      driver-class-name: com.mysql.jdbc.Driver
  #    url: jdbc:mysql://192.168.159.128:3306/mydb
      url: jdbc:mysql://192.168.223.128:3306/db2
      username: wls
      password: Wls141215!
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

  

  <!--    jpa     -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

  

时间: 2024-08-24 16:28:46

Spring Boot? 多数据源配置(二):Spring-data-jpa的相关文章

spring boot 多数据源配置(多种数据库)

最近一段时间在使用spring boot开发项目,其中有一个项目用到了多数据源的配置,网上的资料还是不太多,走了好多才找到一个合适的,把自己写的分享一下,做个笔记,以后也许有用,第一次写博客,不好勿喷!! 首先介绍下我的业务场景,此项目用到了两种数据库,一个是mysql,另一个是sqlserver, 首先第一步需要在application.yml中将多数据源的配置信息进行配置, mysql数据源: spring: datasource: driverClassName: com.mysql.jd

Spring Boot 多数据源配置

下面一个Java类是已经写好的根据配置文件动态创建多dataSource的代码,其原理也很简单,就是读取配置文件,根据配置文件中配置的数据源数量,动态创建dataSource并注册到Spring中. 代码如下: package org.springboot.sample.config; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.sql.DataSource; i

Spring Boot多数据源配置与使用

有时候,一个系统的功能,需要两个或两个以上的数据库, 在Spring Boot 中要如何配置? How to? #primary primary.spring.datasource.jdbc-url=jdbc:mysql://localhost:3316/test1 primary.spring.datasource.username=root primary.spring.datasource.password=root primary.spring.datasource.driver-cla

spring 4 + jpa(hibernate 3/4) + spring mvc 多数据源配置(二)+Druid连接池

接上一个博文(http://www.loveweir.com/html/18.html),没有数据库连接池,纯粹用jpa的官方链接. 所以这次要加上连接池本文用Druid连接池来实现多数据源的配置. persistence.xml 这个文件可以省略了,全部配置在applicationContext.xml 里面: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www

spring boot多数据源配置示例

1. application.properties #\u4E3B\u5E93\u914D\u7F6E spring.datasource.primary.url=jdbc:mysql://mysql.test.xxxxx.com:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false spring.datasource.primary.username=root spring.datasource.primary.pas

关于Spring Boot 多数据源的事务管理

自己的一些理解:自从用了Spring Boot 以来,这近乎零配置和“约定大于配置”的设计范式用着确实爽,其实对零配置的理解是:应该说可以是零配置可以跑一个简单的项目,因为Spring Boot 有默认的配置,当默认的配置满足不了你的时候,这时候所谓的零配置只是换了一种方式而已,我们都知道程序员最擅长的就是写代码,相比来说xml文件还是有点蛋疼的: 行啊,Spring Boot说你不是擅长写代码,那我就把配置给你转换为写代码的形式,所以你会发现在Spring Boot 中使用@Configura

Spring Boot 2.0.4整合Spring Data JPA和Druid,双数据源

最近Team开始尝试使用Spring Boot + Spring Data JPA作为数据层的解决方案,在网上逛了几圈之后发现大家并不待见JPA,理由是(1)MyBatis简单直观够用,(2)以Hibernate为底层的Spring Data JPA复杂且性能一般. 但是当我们来到Spring Boot的世界后发现,相较于Spring Data JPA,MyBatis对Spring Boot的支持有限,Spring Data JPA与Spring Boot结合可以让dao变得非常简单,比如(1)

Spring Boot 外部化配置(二) - @ConfigurationProperties 、@EnableConfigurationProperties

目录 3.外部化配置的核心 3.2 @ConfigurationProperties 3.2.1 注册 Properties 配置类 3.2.2 绑定配置属性 3.1.3 ConfigurationPropertiesAutoConfiguration 4.总结 3.外部化配置的核心 ????????接着上一章,<Spring Boot 外部化配置(一)> 3.2 @ConfigurationProperties 众所周知,当 Spring Boot 集成外部组件后,就可在 propertie

spring boot系列(五)spring boot 配置spring data jpa (查询方法)

接着上面spring boot系列(四)spring boot 配置spring data jpa 保存修改方法继续做查询的测试: 1 创建UserInfo实体类,代码和https://www.cnblogs.com/kxm87/p/9273555.html中的一样. 2 创建数据库操作类相当于dao层,主要创建一个接口UserRepository,继承JpaRepository接口即可.本代码中主要都是自定义方法. 使用findXX 或者countXX(这两个不用编写sql,jpa会自动生成)