我在应用程序中定义了以下配置
@Bean
@Primary
@ConfigurationProperties(prefix="database1")
public DataSource rameshDS()
{
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "rameshEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean rameshEntityManagerFactory(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(rameshDS())
.packages("com.nandagiri.entities")
.build();
}
@Primary
@Bean(name = "rameshTransactionManager")
public PlatformTransactionManager rameshTransactionManager(
final @Qualifier("rameshEntityManagerFactory") LocalContainerEntityManagerFactoryBean rameshEntityManagerFactory) {
return new JpaTransactionManager(rameshEntityManagerFactory.getObject());
}
如果我尝试通过以下方式将数据插入其中一个表中,则数据不会持久保存。但是,如果我取消注释以明确开始/提交事务的行,那么它就可以正常工作。但是,我想使用声明式的交易方式。如何实现呢?
@Autowired
@Qualifier("rameshEntityManagerFactory")
EntityManagerFactory rameshEntity;
@Override
@Transactional(value = "rameshTransactionManager")
public void storeInfo(Ramesh ramesh)
{
EntityManager em = rameshEntity.createEntityManager();
//em.getTransaction().begin();
em.persist(ramesh);
//em.getTransaction().commit();
}
如果我使用存储库接口持久化实体,则可以正常工作,没有任何问题。请在下面找到代码。
@Repository
public interface RameshRepository extends JpaRepository<Ramesh, String>
{
}
@Transactional(transactionManager = "rameshTransactionManager", propagation = Propagation.REQUIRED)
public void saveRameshs()
{
saveRamesh1();
saveRamesh2();
}
@Transactional
public void saveRamesh1()
{
Ramesh ramesh = new Ramesh();
ramesh.setId("8");
ramesh.setFname("jagadeesh");
ramesh.setLname("K");
repository.save(ramesh);
}
@Transactional
public void saveRamesh2()
{
Ramesh ramesh = new Ramesh();
ramesh.setId("9");
ramesh.setFname("jagadeesh123");
ramesh.setLname("k123");
repository.save(ramesh);
//int x = 5/0;
}