Reputation: 169
I use the spring boot 1.5.2 RELEASE.
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(ptvEntityManagerFactory);
txManager.setDataSource(ds);
txManager.setJpaDialect(hibernateDialect);
//txManager.setNestedTransactionAllowed(true);
so what does this NestedTransactionAllowed really do? I create code like this:
@Transactional
public void testNestTransaction() {
saveToRepository()
saveToJdbcTemplate();
throw new RuntimeException();
}
@Transactional
private void saveToRepository() {
employeeRepository.save(new MyEntity(xxx,xx,xx));
}
private void saveToJdbcTemplate() {
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
// the code in this method executes in a transactional context
protected void doInTransactionWithoutResult(TransactionStatus status) {
String sql = "INSERT INTO task (id,create_by,description) VALUES
(?,?,?)";
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter().....
}
}
Here is the problem. no matter NestedTransactionAllowed is true or false, the runTimeException always rollback both in saveToRepository() and saveToJdbcTemplate(). it default value is false, and there is a chunk of JavaDoc to describ this flag.
But I still do not understand what is the point of the NestedTransactionAllowed?? can you guys helps me with some scenarios to show the difference between this value in true and false? thanks a lot
BTW: the entity manager is hibernate.
// hibernate adapter
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
Upvotes: 2
Views: 2474
Reputation: 4076
Your setNestedTransactionAllowed is not working as nested transaction support is not available for JpaTransaactionManager. Following excerpt from the official doc -
This transaction manager supports nested transactions via JDBC 3.0 Savepoints. The "nestedTransactionAllowed" flag defaults to false though, since nested transactions will just apply to the JDBC Connection, not to the JPA EntityManager and its cached entity objects and related context. You can manually set the flag to true if you want to use nested transactions for JDBC access code which participates in JPA transactions (provided that your JDBC driver supports Savepoints). Note that JPA itself does not support nested transactions! Hence, do not expect JPA access code to semantically participate in a nested transaction.
Upvotes: 2