Springboot集成JPA多Hibernate数据源

项目环境

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

相关推荐

  1. Springboot集成JPAHibernate数据

    2023-12-21 11:10:03       35 阅读
  2. Springboot JPA实现数据配置

    2023-12-21 11:10:03       31 阅读
  3. Springboot 集成 Dynamic-Datasource 数据组件

    2023-12-21 11:10:03       33 阅读
  4. SpringBoot集成JPA及基本使用

    2023-12-21 11:10:03       19 阅读
  5. 【Spring Boot 3】【数据】自定义JPA数据

    2023-12-21 11:10:03       42 阅读
  6. Spring Data JPA + Hibernate + Mysql

    2023-12-21 11:10:03       12 阅读
  7. springboot实现数据

    2023-12-21 11:10:03       33 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-21 11:10:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-21 11:10:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-21 11:10:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-21 11:10:03       20 阅读

热门阅读

  1. display:grid

    2023-12-21 11:10:03       49 阅读
  2. 使用IntelliJ IDEA进行Python开发配置

    2023-12-21 11:10:03       41 阅读
  3. 进程间通讯-信号量

    2023-12-21 11:10:03       37 阅读
  4. stable diffusion 极简入门 核心 概念介绍 使用

    2023-12-21 11:10:03       32 阅读
  5. Boost.Python与BOOST_TEST_EQ宏的示例编程

    2023-12-21 11:10:03       37 阅读
  6. 使用 Layui 的 template 模块来动态加载select选项

    2023-12-21 11:10:03       34 阅读
  7. Qt 软件界面点击QCombBox控件,造成整个界面移位

    2023-12-21 11:10:03       28 阅读