我一直在尝试构建具有多个数据库支持的应用程序,例如:(psql&mysql),其他人也应该关注。
我有2套套票
com.foo.mysql
entities
UserEntity
RegisterEntity
com.foo.psql
entities
UserEntity
RegisterEntity
和实体经理
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "dbEntityManager",
transactionManagerRef = "dbTransactionManager",
basePackages = {"com.foo.dao.repositories"}
)
public class EntityManagerConfiguration {
@Value("${bar.app.data-source}")
private DatabaseTypes dataSource;
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource customDataSource() {
return DataSourceBuilder
.create()
.build();
}
@Primary
@Bean(name = "dbEntityManager")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
Map<String, Object> properties = new HashMap<String, Object>();
if (dataSource.equals(DatabaseTypes.postgresql)) {
properties.put("spring.jpa.properties.hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
} else if (dataSource.equals(DatabaseTypes.mysql)) {
properties.put("spring.jpa.properties.hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect");
}
properties.put("spring.jpa.hibernate.ddl-auto", "create-drop");
properties.put("hibernate.hbm2ddl.auto", "create-drop");
properties.put("spring.jpa.properties.hibernate.enable_lazy_load_no_trans", "true");
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
LocalContainerEntityManagerFactoryBean build = builder
.dataSource(customDataSource())
.packages("com.identy.dao."+dataSource.name().toLowerCase()+".entities")
.persistenceUnit(dataSource.name().toLowerCase()+"PU")
.properties(properties)
.build();
build.afterPropertiesSet();
build.setJpaVendorAdapter(vendorAdapter);
return build;
}
@Primary
@Bean(name = "dbTransactionManager")
public PlatformTransactionManager transactionManager(@Qualifier("dbEntityManager") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
问题在于如何建立存储库,以便可以在两个实体之间透明地使用它们。
A或B将在运行时激活。
我的问题是,
1)是否有更好的方法来支持多种数据库类型?
2)如何使存储库通用,以便我可以在其中使用任何一个实体?
public interface UserEntityRepository extends JpaRepository<UserEntityMySql OR UserEntityPSQl, Long> {}
谢谢