I have defined the following configuration in my application
@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());
}
If I try to insert data into one of the tables in the following way, the data is not persisted. But if I uncomment the lines to explicitly begin/commit transactions then it is working fine. But, I wanted to use declarative way of transactions. How to achieve that?
@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();
}
If I persist the entities with repository interface it is working absolutely fine without any issues. please find the code below.
@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;
}