gpt4 book ai didi

java - 如何通过在 Spring-boot 中使用 JPA + Hibernate 在一个数据库中使用多个模式?

转载 作者:行者123 更新时间:2023-12-03 19:34:55 29 4
gpt4 key购买 nike

我需要它来访问一个数据库(MySQL)中的 2 个不同模式。

我在这里写了两个配置类:

package twodb.webfi.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

@Configuration
@ComponentScan
@EnableTransactionManagement
@EnableJpaRepositories(basePackages={"twodb.webfi","twodb.mc"},
entityManagerFactoryRef = "entityManagerFactory1",
transactionManagerRef = "transactionManager1",
considerNestedRepositories = true)
public class FirstConfig {

@Autowired
private Environment env;

@Bean
public PlatformTransactionManager transactionManager1()
{
EntityManagerFactory factory = entityManagerFactory1().getObject();
return new JpaTransactionManager(factory);
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory1()
{
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();

HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(Boolean.TRUE);
vendorAdapter.setShowSql(Boolean.TRUE);

factory.setDataSource(dataSource1());
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan(new String[] {"twodb.webfi.entities","twodb.mc.model"});
Properties jpaProperties = new Properties();

jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.ddl-auto"));
jpaProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
jpaProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.showSql"));
factory.setJpaProperties(jpaProperties);

factory.afterPropertiesSet();
factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
return factory;
}

@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator()
{
return new HibernateExceptionTranslator();
}


@Bean(destroyMethod = "close")
public HikariDataSource dataSource1() {
System.out.println("<--HikariDataSource1-->");
HikariConfig dataSourceConfig = new HikariConfig();
dataSourceConfig.setDriverClassName(env.getProperty("ui.db.driver"));
dataSourceConfig.setJdbcUrl(env.getProperty("ui.db.url"));
dataSourceConfig.setUsername(env.getProperty("ui.db.username"));
dataSourceConfig.setPassword(env.getProperty("ui.db.password"));

dataSourceConfig.setMaximumPoolSize(env.getProperty("hikari.maximumPoolSize", Integer.class, new Integer(1)));
dataSourceConfig.setMinimumIdle(env.getProperty("hikari.minimumIdle", Integer.class, new Integer(1)));
dataSourceConfig.setIdleTimeout(env.getProperty("hikari.idleTimeout", Long.class, new Long(600000))); // 10 min
dataSourceConfig.setMaxLifetime(env.getProperty("hikari.maxLifetime", Long.class, new Long(1800000))); // 30 min
dataSourceConfig.setPoolName(env.getProperty("hikari.poolName", "upiCp"));

return new HikariDataSource(dataSourceConfig);
}

}

这里的另一个配置类:
package twodb.webfi.config;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

@Configuration
@ComponentScan
@EnableTransactionManagement
@EnableJpaRepositories(basePackages={"twodb.webfi","twodb.mc"},
entityManagerFactoryRef = "entityManagerFactory2",
transactionManagerRef = "transactionManager2",
considerNestedRepositories = true)
public class SecondConfig {

@Autowired
private Environment env;

@Bean
public PlatformTransactionManager transactionManager2()
{
EntityManagerFactory factory = entityManagerFactory2().getObject();
return new JpaTransactionManager(factory);
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory2()
{
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();

HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(Boolean.TRUE);
vendorAdapter.setShowSql(Boolean.TRUE);

factory.setDataSource(dataSource2());
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan(new String[] {"twodb.webfi.entities","twodb.mc.model"});
Properties jpaProperties = new Properties();

jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.ddl-auto"));
jpaProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
jpaProperties.setProperty("hibernate.show_sql", env.getProperty("hibernate.showSql"));
factory.setJpaProperties(jpaProperties);

factory.afterPropertiesSet();
factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
return factory;
}

@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator()
{
return new HibernateExceptionTranslator();
}

@Bean(destroyMethod = "close")
public HikariDataSource dataSource2() {
System.out.println("<--HikariDataSource2-->");
HikariConfig dataSourceConfig = new HikariConfig();
dataSourceConfig.setDriverClassName(env.getProperty("web.db.driver"));
dataSourceConfig.setJdbcUrl(env.getProperty("web.db.url"));
dataSourceConfig.setUsername(env.getProperty("web.db.username"));
dataSourceConfig.setPassword(env.getProperty("web.db.password"));

dataSourceConfig.setMaximumPoolSize(env.getProperty("hikari.maximumPoolSize", Integer.class, new Integer(1)));
dataSourceConfig.setMinimumIdle(env.getProperty("hikari.minimumIdle", Integer.class, new Integer(1)));
dataSourceConfig.setIdleTimeout(env.getProperty("hikari.idleTimeout", Long.class, new Long(600000))); // 10 min
dataSourceConfig.setMaxLifetime(env.getProperty("hikari.maxLifetime", Long.class, new Long(1800000))); // 30 min
dataSourceConfig.setPoolName(env.getProperty("hikari.poolName", "upiCp"));

return new HikariDataSource(dataSourceConfig);
}

}

在这里,我得到了异常(exception),例如
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webCommonDaoImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available: expected single matching bean but found 2: entityManagerFactory1,entityManagerFactory
任何人都可以通过使用 JPA + Hibernate 和 Spring-boot 来指出如何使用多个数据库的正确方向吗?

我是 uiweb模式在 mysql 中。两者都是同一个数据库。

最佳答案

使用限定符和 bean 名称将避免任何冲突。

我在我的应用程序 yaml 文件中创建了不同的数据源配置,如下所示

db-abc:
datasource:
url: ${ABC_DATABASE_URL}
username: ${ABC_DATABASE_USERNAME}
password: ${ABC_DATABASE_PASSWORD}
driverClassName: org.postgresql.Driver
db-xyz:
datasource:
url: ${XYZ_DATABASE_URL}
username: ${XYZ_DATABASE_USERNAME}
password: ${XYZ_DATABASE_PASSWORD}
driverClassName: org.postgresql.Driver
db-batch:
datasource:
url: ${DATABASE_URL}
username: ${DATABASE_USERNAME}
password: ${DATABASE_PASSWORD}
driverClassName: org.postgresql.Driver

并创建了我的数据源配置,如下所示
@Configuration
public class DataSourceConfig {

private final Environment env;

@Autowired
public DataSourceConfig(Environment env) {
this.env = env;
}

@Bean(name = "abcDataSource")
@ConfigurationProperties(prefix = "db-abc.datasource")
public DataSource abcDataSource() {
return DataSourceBuilder
.create()
.url(env.getProperty("db-abc.datasource.url"))
.driverClassName(env.getProperty("db-abc.datasource.driverClassName"))
.username(env.getProperty("db-abc.datasource.username"))
.password(env.getProperty("db-abc.datasource.password"))
.build();
}

@Bean(name = "xyzDataSource")
@ConfigurationProperties(prefix = "db-xyz.datasource")
public DataSource xyzDataSource() {
return DataSourceBuilder
.create()
.url(env.getProperty("db-xyz.datasource.url"))
.driverClassName(env.getProperty("db-xyz.datasource.driverClassName"))
.username(env.getProperty("db-xyz.datasource.username"))
.password(env.getProperty("db-xyz.datasource.password"))
.build();
}

@Primary
@Bean(name = "batchDataSource")
@ConfigurationProperties(prefix = "db-batch.datasource")
public DataSource batchDataSource() {
return DataSourceBuilder
.create()
.url(env.getProperty("db-batch.datasource.url"))
.driverClassName(env.getProperty("db-batch.datasource.driverClassName"))
.username(env.getProperty("db-batch.datasource.username"))
.password(env.getProperty("db-batch.datasource.password"))
.build();
}
}

并使用各自的 bean 来做我想做的事情……使用限定符和 bean 名称将避免任何冲突。

对于单个数据库中的多个架构,您可以使用上述各自的架构
@Table(
schema = "schema1",
name = "TBL_SCHEMA1_TABLE"
)
public class Schema1Entity implements Serializable { @Entity
@Table(
schema = "schema2",
name = "TBL_SCHEMA2_TABLE"
)
public class Schema2Entity implements Serializable {

关于java - 如何通过在 Spring-boot 中使用 JPA + Hibernate 在一个数据库中使用多个模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50760964/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com