我是Spring和Spring Boot的新手.如何配置和使用两个数据源.
例如,这是第一个数据源的内容.
application.properties
#first db
spring.datasource.url = [url]
spring.datasource.username = [username]
spring.datasource.password = [password]
spring.datasource.driverClassName = oracle.jdbc.OracleDriver
#second db ...
Run Code Online (Sandbox Code Playgroud)
应用类
@SpringBootApplication
public class SampleApplication
{
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
如何修改application.properties以添加其他数据源?如何将其自动装配以供其他仓库使用?
我的主要工作只是读取操作而另一个人写了一些但MyISAM engine忽略了事务,所以我不需要事务支持.如何配置Spring Batch拥有自己的数据源JobRepository,与持有业务数据的数据源分开?最初的一个数据源配置如下所示:
@Configuration
public class StandaloneInfrastructureConfiguration {
@Autowired
Environment env;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.podcastpedia.batch.*" });
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalJpaProperties());
return em;
}
Properties additionalJpaProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "none");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
properties.setProperty("hibernate.show_sql", "true");
return properties;
}
@Bean
public DataSource dataSource(){
return DataSourceBuilder.create()
.url(env.getProperty("db.url"))
.driverClassName(env.getProperty("db.driver"))
.username(env.getProperty("db.username"))
.password(env.getProperty("db.password"))
.build();
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
JpaTransactionManager transactionManager = …Run Code Online (Sandbox Code Playgroud) 作为一个事务的一部分,我必须更新两个数据源。那是 -
如果DB2中的更新失败,我想回滚DB1和DB2来回滚。可以使用@Transactional完成此操作吗?
这是一个示例代码-
@Transactional(value="db01TransactionManager")
public void updateDb01() {
Entity01 entity01 = repository01.findOne(1234);
entity01.setName("Name");
repository01.save(entity01);
//Calling method to update DB02
updateDb02();
}
@Transactional(value="db02TransactionManager")
public void updateDb02() {
Entity02 entity02 = repository02.findOne(1234);
entity02.setName("Name");
repository02.save(entity02);
//Added this to force a roll back for testing
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,updateDb02中的setRollbackOnly()仅回滚Db01事务。
spring hibernate transactions transactionmanager spring-data-jpa