Spring Boot配置两个数据源(SpringBoot + Mysql + Jpa)

项目结构:SpringBoot+Mysql+Jpa

1、新建一个Spring Boot项目,在https://start.spring.io/可以新建,如下图:

在这里插入图片描述

选择SpringBoot版本,选择相关依赖添加进项目,Mysql和Jpa

2、生成项目,讲生成的项目导入IDEA,项目结构如下图

在这里插入图片描述

3、编辑application.properties

server.port = 9002


# 本地环境主库
spring.datasource.primary.url = jdbc:mysql://localhost:3306/dyt_website?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
spring.datasource.primary.username = root
spring.datasource.primary.password = 12345678

# 本地环境副库
spring.datasource.secondary.url = jdbc:mysql://localhost:3306/dytkf?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
spring.datasource.secondary.username = root
spring.datasource.secondary.password = 12345678

spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.max-active=20
spring.datasource.max-idle=8
spring.datasource.min-idle=8
spring.datasource.initial-size=10

spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update,validate,none)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

4、entity目录下包含主库的实体类和副库的实体类,dao目录下包含主库的dao和副库的dao

(1)、主库实体类

package com.dyt.website.entity.primary;

import javax.persistence.*;

/**
 * Created by Annan.Wang on 2019/4/18.
 * Description:
 * Coding Changes World :)
 */
@Entity
@Table(name = "t_user")
public class User {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Integer id;
    private String username;
    private String password;
    private String name;

   //get set省略
}

(2)、副库实体类

package com.dyt.website.entity.secondary;

import javax.persistence.*;

/**
 * Created by Annan.Wang on 2019/4/19.
 * Description:平台用户数
 * Coding Changes World :)
 */
@Entity
@Table(name = "api_wechat")
public class Wechat {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    //get set省略
}

(3)、主库DAO

package com.dyt.website.dao.primary;

import com.dyt.website.entity.primary.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

/**
 * Created by Annan.Wang on 2019/4/18.
 * Description:
 * Coding Changes World :)
 */
@Repository
public interface UserDao extends JpaRepository<User, Integer> {

    @Query("select u from User u where u.username=:username")
    User findUserByUsername(@Param("username") String username);
}

(4)、副库DAO

package com.dyt.website.dao.secondary;

import com.dyt.website.entity.secondary.Wechat;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

/**
 * Created by Annan.Wang on 2019/4/19.
 * Description:
 * Coding Changes World :)
 */
@Repository
public interface WechatDao extends JpaRepository<Wechat, Integer> {
}

5、实体类和DAO写好之后,就可以配置主库和副库的数据源配置了,配置代码如下:

(1)、数据源配置

package com.dyt.website;

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 javax.sql.DataSource;


/**
 * Created by Annan.Wang on 2019/4/18.
 * Description:
 * Coding Changes World :)
 */
@Configuration //启动时自动装配
public class DataSourceConfig {
    @Bean(name = "primaryDataSource")
    @Qualifier("primaryDataSource")
    @Primary
    @ConfigurationProperties(prefix="spring.datasource.primary") //读取application.properties中的主库配置信息
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "secondaryDataSource")
    @Qualifier("secondaryDataSource")
    @ConfigurationProperties(prefix="spring.datasource.secondary") //读取application.properties中的副库配置信息
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
}

(2)、主库配置

package com.dyt.website;

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;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactoryPrimary",
        transactionManagerRef="transactionManagerPrimary",
        basePackages= { "com.dyt.website.dao.primary" }) //设置dao所在位置
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.dyt.website.entity.primary") //设置主库实体类所在位置
                .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());
    }

}

(3)、副库配置

package com.dyt.website;

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;

import javax.persistence.EntityManager;
import javax.sql.DataSource;
import java.util.Map;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerFactorySecondary",
        transactionManagerRef="transactionManagerSecondary",
        basePackages= { "com.dyt.website.dao.secondary" }) //设置dao所在位置
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.dyt.website.entity.secondary") //设置副库实体类所在位置
                .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());
    }

}

6、配置完成,写一个测试类

package com.dyt.website;



import com.dyt.website.dao.primary.UserDao;
import com.dyt.website.dao.secondary.WechatDao;
import com.dyt.website.entity.primary.User;
import com.dyt.website.entity.secondary.Wechat;
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.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class WebsiteApplicationTests {

	@Autowired
	private UserDao userDao;

	@Autowired
	private WechatDao wechatDao;




	@Test
	public  void test(){

		User user = new User();
		user.setUsername("test");
		user.setPassword("123456");
		user.setName("TEST");

		userDao.save(user);

		Wechat wechat = wechatDao.getOne(1);



	}

}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值