Springboot集成JPA多Hibernate数据源

2023-12-20 18:36:45

项目环境

1.Springboot版本:3.1.5
2.JDK版本:21
3.MySQL版本:8.0.33

1. yaml文件代码

spring:
  application:
    name: xxx #应用名称
  # 多数据源配置步骤1
  datasource:
  	# 数据源1
    goag2:
      jdbc-url: jdbc:mysql://localhost:3306/xxx?createDatabaseIfNotExist=true
      username: xxx
      password: xxx
    # 数据源2
    flowable:
      jdbc-url: jdbc:mysql://localhost:3306/xxx?createDatabaseIfNotExist=true
      username: xxx
      password: xxx
  jpa:
    # 指定数据库类型
    database: mysql
    hibernate:
      #每次运行程序不会删除表,只会更新表
      ddl-auto: update 
      #每次运行程序会删除表重新创建表
      #ddl-auto: create-drop
	#打印sql文
    show-sql: true 
    #请求结束后,关闭session
    open-in-view: true 
    properties:
      #在没有事务的情况下允许懒加载
      enable_lazy_load_no_trans: true
      hibernate:
        connection:
          pool_size: 100
        cache:
#          use_query_cache: true
          use_second_level_cache: true #应用缓存
          region:
            factory_class: jcache #org.hibernate.cache.jcache.JCacheRegionFactory
#        generate_statistics: true
        javax:
          cache:
            uri: classpath:ehcache.xml
            provider: org.ehcache.jsr107.EhcacheCachingProvider
        # Format queries
#        format_sql: true


#  cache:
#    jcache:
#      config: classpath:ehcache.xml
#      provider: org.ehcache.jsr107.EhcacheCachingProvider
springdoc:
  api-docs:
    path: /api-docs
#  swagger-ui:
#    path: /swagger-ui-custom.html
#    operationsSorter: method

logging:
  level:
#    root: off
    com.glad.goag2: debug
  file:
    path: .
    name: goag2.log
    
token:
  signing:
    key: A269B4094077B57E1448FE7FBC87A5B5AC1A9DB66497C0B46A36CD88AC732D32

2. DatasourceConfiguration.java

package com.glad.goag2.config;

import javax.sql.DataSource;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

// 多数据源配置步骤2
@Configuration
public class DatasourceConfiguration {
	
	// 多数据源配置步骤2
	// 主数据源配置
	@Primary
    @Bean(name = "goag2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.goag2")
    public DataSource goag2DataSource() {
        return DataSourceBuilder.create().build();
    }
	
	// 多数据源配置步骤2
	// 非主数据源配置
    @Bean(name = "flowableDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.flowable")
    public DataSource flowableDataSource() {
        return DataSourceBuilder.create().build();
    }
}

3. Goag2JpaConfiguration.java 主数据JPA配置

package com.glad.goag2.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
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 jakarta.annotation.Resource;
import jakarta.persistence.EntityManager;

//多数据源配置步骤3
@Configuration
@EnableTransactionManagement
//basePackages指定repository(dao)
@EnableJpaRepositories(basePackages = {
		"com.glad.goag2.repository" }, entityManagerFactoryRef = "goag2EntityManagerFactory", transactionManagerRef = "goag2TransactionManager")
public class Goag2JpaConfiguration {
	@Resource
	@Qualifier("goag2DataSource")
	private DataSource goag2DataSource;

	@Primary
	@Bean(name = "goag2EntityManager")
	public EntityManager goag2EntityManager(EntityManagerFactoryBuilder builder) {
		return goag2EntityManagerFactory(builder).getObject().createEntityManager();
	}

	@Resource
	private JpaProperties jpaProperties;

	@Resource
	private HibernateProperties properties;

	/**
	 * 设置实体类所在位置
	 */
	@Primary
	@Bean(name = "goag2EntityManagerFactory")
	public LocalContainerEntityManagerFactoryBean goag2EntityManagerFactory(EntityManagerFactoryBuilder builder) {
		LocalContainerEntityManagerFactoryBean entityManagerFactory = builder.dataSource(goag2DataSource)
				// .packages(classes)
				// 设置实体类所在位置
				.packages("com.glad.goag2.entity")
				// 定义unitName
				.persistenceUnit("goag2PersistenceUnit")
				// .properties(jpaProperties.getProperties()) 此处自动建表失效 
				//  此处注解自动建表生效
				.properties(
						properties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings()))
				.build();
		return entityManagerFactory;
	}

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

4. FlowableJpaConfiguration.java 非主数据JPA配置

package com.glad.goag2.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
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 jakarta.annotation.Resource;
import jakarta.persistence.EntityManager;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = {
		"com.glad.goag2.flowable.repository" }, entityManagerFactoryRef = "flowableEntityManagerFactory", transactionManagerRef = "flowableTransactionManager")
public class FlowableJpaConfiguration {
	@Resource
	@Qualifier("flowableDataSource")
	private DataSource flowableDataSource;

	@Bean(name = "flowableEntityManager")
	public EntityManager flowableEntityManager(EntityManagerFactoryBuilder builder) {
		return flowableEntityManagerFactory(builder).getObject().createEntityManager();
	}

	@Resource
	private JpaProperties jpaProperties;

	@Resource
	private HibernateProperties properties;

	/**
	 * 设置实体类所在位置
	 */
	@Bean(name = "flowableEntityManagerFactory")
	public LocalContainerEntityManagerFactoryBean flowableEntityManagerFactory(EntityManagerFactoryBuilder builder) {
		LocalContainerEntityManagerFactoryBean entityManagerFactory = builder.dataSource(flowableDataSource)
				// .packages(classes)
				// 设置实体类所在位置
				.packages("com.glad.goag2.flowable.entity")
				// 定义unitName
				.persistenceUnit("flowablePersistenceUnit")
				// .properties(jpaProperties.getProperties())
				.properties(
						properties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings()))
				.build();
		return entityManagerFactory;
	}

	@Bean(name = "flowableTransactionManager")
	public PlatformTransactionManager flowableTransactionManager(EntityManagerFactoryBuilder builder) {
		return new JpaTransactionManager(flowableEntityManagerFactory(builder).getObject());
	}

}

总结

1.这样就可以实现数据库的映射更新
2.不同的Repository使用不同的数据源
3.博客参考 https://blog.csdn.net/tianyaleixiaowu/article/details/96977099

文章来源:https://blog.csdn.net/qq_40765784/article/details/135111606
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。