Hi Support
I have a problem to use transaction.
I created a bean for manage update operation with sql command on additional database db1.
In @SpringBootApplication java file I created this function
@Bean
TransactionTemplate db1TransactionTemplate(
@Qualifier("db1TransactionManager")
PlatformTransactionManager transactionManager) {
return new TransactionTemplate(transactionManager);
}
In my bean I declare Entity Manager and TransactionTemplate
@PersistenceContext(unitName = "db1") // store name
private EntityManager entityManager;
@Autowired
@Qualifier("db1TransactionTemplate")
private TransactionTemplate db1TransactionTemplate;
// creates new transaction
@Transactional("db1TransactionManager")
public TransactionTemplate getRequiresNewTransactionTemplate() {
TransactionTemplate tt = new TransactionTemplate(transactionManager);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
return tt;
}
My method is this:
@Transactional("db1TransactionManager")
private boolean nativeQuery(String nativeQuery) {
int result = -1;
List<Object > result1 = null;
TransactionTemplate tx = getRequiresNewTransactionTemplate();
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("db1");
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
try {
Query query = entityManager.createNativeQuery(nativeQuery);
result = query.executeUpdate();
entityManager.getTransaction().commit();
} catch (Exception e ){
e.printStackTrace();
log.error(e.getMessage());
entityManager.getTransaction().rollback();
}finally {
entityManager.close();
}
return (result == 0) ? true : false;
}
on execute I receive this error:
jakarta.persistence.TransactionRequiredException: Exception Description: No transaction is currently active
What did I do wrong?
Thank you for response