我必须执行一个Spring Boot 1.5版应用程序,它可以这样做:它创建一个对象并尝试持久化到两个数据源(例如:2个数据库名为:test_book_1和Postgresql中的test_book_2)。
我找到了一个可以用于2个不同对象的例子(作者:A,书籍:B),它们可以存储在不同的数据库中(A转到test_book_1,B转到test_book_2)。这是一个很好的例子,但它不是我想要的。 Store separate objects to different data sources
我认为我需要定义2个自定义JPA DatabaseConfigurations,并且需要将它们配置为管理相同的存储库和域类。但是,Spring只使用第二个类作为限定符来注入JPA存储库(我知道当两个配置指向同一个类时,第二个类可以覆盖)。
问题是,如何告诉Spring让它知道什么时候应该从有用的数据源注入正确的Bean(BookRepository)(我想将对象持久化到两个数据源,而不仅仅是第二个。)
以下是上面示例链接中的修改后的代码。
一个application.properties文件被修改为在Postgresql中创建2个数据库,而不是在Postgresql中创建1个,在Mysql中创建1个。
server.port=8082
# -----------------------
# POSTGRESQL DATABASE CONFIGURATION
# -----------------------
spring.postgresql.datasource.url=jdbc:postgresql://localhost:5432/test_book_db
spring.postgresql.datasource.username=petauser
spring.postgresql.datasource.password=petapasswd
spring.postgresql.datasource.driver-class-name=org.postgresql.Driver
# ------------------------------
# POSTGRESQL 1 DATABASE CONFIGURATION
# ------------------------------
spring.mysql.datasource.url=jdbc:postgresql://localhost:5432/test_author_db
spring.mysql.datasource.username=petauser
spring.mysql.datasource.password=petapasswd
spring.mysql.datasource.driver-class-name=org.postgresql.Driver
package:com.roufid.tutorial.configuration class APostgresqlConfiguration
package com.roufid.tutorial.configuration;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
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.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
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 com.roufid.tutorial.entity.postgresql.Book;
/**
* Spring configuration of the "PostgreSQL" database.
*
* @author Radouane ROUFID.
*
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "postgresqlEntityManager",
transactionManagerRef = "postgresqlTransactionManager",
basePackages = "com.roufid.tutorial.dao.postgresql"
)
public class APostgresqlConfiguration {
/**
* PostgreSQL datasource definition.
*
* @return datasource.
*/
@Bean
@Primary
@ConfigurationProperties(prefix = "spring.postgresql.datasource")
public DataSource postgresqlDataSource() {
return DataSourceBuilder
.create()
.build();
}
/**
* Entity manager definition.
*
* @param builder an EntityManagerFactoryBuilder.
* @return LocalContainerEntityManagerFactoryBean.
*/
@Primary
@Bean(name = "postgresqlEntityManager")
public LocalContainerEntityManagerFactoryBean postgresqlEntityManagerFactory(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(postgresqlDataSource())
.properties(hibernateProperties())
.packages(Book.class)
.persistenceUnit("postgresqlPU")
.build();
}
@Primary
@Bean(name = "postgresqlTransactionManager")
public PlatformTransactionManager postgresqlTransactionManager(@Qualifier("postgresqlEntityManager") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
private Map<String, Object> hibernateProperties() {
Resource resource = new ClassPathResource("hibernate.properties");
try {
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
return properties.entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey().toString(),
e -> e.getValue())
);
} catch (IOException e) {
return new HashMap<String, Object>();
}
}
}
package:com.roufid.tutorial.configuration class MysqlConfiguration
package com.roufid.tutorial.configuration;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
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 com.roufid.tutorial.entity.mysql.Author;
import com.roufid.tutorial.entity.postgresql.Book;
/**
* Spring configuration of the "mysql" database.
*
* @author Radouane ROUFID.
*
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "mysqlEntityManager",
transactionManagerRef = "mysqlTransactionManager",
basePackages = "com.roufid.tutorial.dao.postgresql"
)
public class MysqlConfiguration {
/**
* MySQL datasource definition.
*
* @return datasource.
*/
@Bean
@ConfigurationProperties(prefix = "spring.mysql.datasource")
public DataSource mysqlDataSource() {
return DataSourceBuilder
.create()
.build();
}
/**
* Entity manager definition.
*
* @param builder an EntityManagerFactoryBuilder.
* @return LocalContainerEntityManagerFactoryBean.
*/
@Bean(name = "mysqlEntityManager")
public LocalContainerEntityManagerFactoryBean mysqlEntityManagerFactory(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(mysqlDataSource())
.properties(hibernateProperties())
.packages(Book.class)
.persistenceUnit("mysqlPU")
.build();
}
/**
* @param entityManagerFactory
* @return
*/
@Bean(name = "mysqlTransactionManager")
public PlatformTransactionManager mysqlTransactionManager(@Qualifier("mysqlEntityManager") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
private Map<String, Object> hibernateProperties() {
Resource resource = new ClassPathResource("hibernate.properties");
}
} try {
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
return properties.entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey().toString(),
e -> e.getValue())
);
} catch (IOException e) {
return new HashMap<String, Object>();
}
}
}
包com.roufid.tutorial.dao.postgresql class BookRepository
package com.roufid.tutorial.dao.postgresql;
import org.springframework.data.repository.CrudRepository;
import com.roufid.tutorial.entity.postgresql.Book;
/**
* Book repository.
*
* @author Radouane ROUFID.
*
*/
public interface BookRepository extends CrudRepository<Book, Long> {
}
包com.roufid.tutorial.entity.postgresql 班级书
package com.roufid.tutorial.entity.postgresql;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "BOOK")
public class Book implements Serializable {
private static final long serialVersionUID = -9019470250770543773L;
@Id
private Long id;
@Column
private String name;
@Column
private Long authorId;
...
// Setters, Getters
}
一个注入BookRepository的测试类,它只使用MysqlConfiguration类(第二个数据源)。
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTest {
@Autowired
private BookRepository bookRepository;
@Before
public void init() {
Book book = new Book();
book.setId(bookId);
book.setName("Spring Boot Book");
// How can it persist to the first datasource?
bookRepository.save(book);
}
}
答案 0 :(得分:3)
所以我想我自己得到了一个答案(我想坚持使用Spring JPA和Hibernate)。所以这就是我所做的,灵感来自Spring Booth with 2 different data sources
最重要的类是手动创建2个数据源的配置类(Postgresql中有2个数据库)
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "sourceEntityManagerFactory",
basePackages = "application"
)
public class PersistenceConfig {
@Autowired
private JpaVendorAdapter jpaVendorAdapter;
private String databaseUrl = "jdbc:postgresql://localhost:5432/test_book_db";
private String targetDatabaseUrl = "jdbc:postgresql://localhost:5432/test_author_db";
private String username = "petauser";
private String password = "petapasswd";
private String driverClassName = "org.postgresql.Driver";
private String dialect = "org.hibernate.dialect.PostgreSQLDialect";
private String ddlAuto = "update";
@Bean
public EntityManager sourceEntityManager() {
return sourceEntityManagerFactory().createEntityManager();
}
@Bean
public EntityManager targetEntityManager() {
return targetEntityManagerFactory().createEntityManager();
}
@Bean
@Primary
public EntityManagerFactory sourceEntityManagerFactory() {
return createEntityManagerFactory("source", databaseUrl);
}
@Bean
public EntityManagerFactory targetEntityManagerFactory() {
return createEntityManagerFactory("target", targetDatabaseUrl);
}
@Bean(name = "transactionManager")
@Primary
public PlatformTransactionManager sourceTransactionManager() {
return new JpaTransactionManager(sourceEntityManagerFactory());
}
@Bean
public PlatformTransactionManager targetTransactionManager() {
return new JpaTransactionManager(targetEntityManagerFactory());
}
private EntityManagerFactory createEntityManagerFactory(final String persistenceUnitName,
final String databaseUrl) {
final LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
final DriverManagerDataSource dataSource = new DriverManagerDataSource(databaseUrl, username, password);
dataSource.setDriverClassName(driverClassName);
entityManagerFactory.setDataSource(dataSource);
entityManagerFactory.setJpaVendorAdapter(jpaVendorAdapter);
entityManagerFactory.setPackagesToScan("application.domain");
entityManagerFactory.setPersistenceUnitName(persistenceUnitName);
final Properties properties = new Properties();
properties.setProperty("hibernate.dialect", dialect);
properties.setProperty("hibernate.hbm2ddl.auto", ddlAuto);
entityManagerFactory.setJpaProperties(properties);
entityManagerFactory.afterPropertiesSet();
return entityManagerFactory.getObject();
}
}
因为我想将存储的实体从源数据库复制到目标数据库。所以我使用Spring JPA从源数据库中读取对象
public interface StorageEntryRepository extends CrudRepository<StorageEntry, Long> {
}
我创建了一个服务类来检查目标数据库中存在的实体(someValue是否包含子字符串“Book”),然后通过Hibernate将其保存在目标数据库中(这里的StorageEntry是一个域类)链接上面)。
@Service
@Transactional(rollbackFor = Exception.class)
public class StorageEntryService {
@Autowired
private StorageEntryRepository storageEntryRepository;
@PersistenceContext(unitName = "target")
private EntityManager targetEntityManager;
public void save(StorageEntry storageEntry) throws Exception {
// this.storageEntryRepository.save(storageEntry);
// Load an stored entry from the source database
StorageEntry storedEntry = this.storageEntryRepository.findOne(12L);
//this.storageEntryRepository.save(storageEntry);
// Save also to a different database
final Session targetHibernateSession = targetEntityManager.unwrap(Session.class);
Criteria criteria = targetHibernateSession.createCriteria(StorageEntry.class);
criteria.add(Restrictions.like("someValue", "%Book1%"));
List<StorageEntry> storageEntries = criteria.list();
if (storageEntries.isEmpty()) {
targetEntityManager.merge(storedEntry);
// No flush then nodata is saved in the different database
targetHibernateSession.flush();
System.out.println("Stored the new object to target database.");
} else {
System.out.println("Object already existed in target database.");
}
}
}
所以最终我可以使用当前工作应用程序中的两个JPA,只需要使用配置类和服务类创建另一个应用程序来将现有对象迁移到新数据库。
答案 1 :(得分:2)
看起来你需要多租户支持。
有一个基于Spring的解决方案
您需要实现CurrentTenantIdentifierResolver接口
public String resolveCurrentTenantIdentifier()
并扩展
AbstractDataSourceBasedMultiTenantConnectionProviderImpl
返回租户的DataSource
查看更多here