Spring @Transactional wrapping 2 methods

I am new to Spring. I am using @Transactional annotation for my dao methods:

@Transactional public Person getById(long id) { return new Person(jdbcTemplate.queryForMap(...)); } @Transactional public void save(Person person) { jdbcTemplate.update(...); } 

and I created a transaction manager as follows:

 <tx:annotation-driven transaction-manager="txManager" /> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> 

The problem is that when my client code calls dao.save(..) and then dao.getById(4) , this happens in two separate transactions. How can I wrap these 2 calls in a single database transaction? Ideally, not doing this programmatically.

thanks

+4
source share
3 answers
 @Transactional(propagation = REQUIRES_NEW, readOnly = false) public Person saveAndGetById(Person person, long id) { save(person); return getById(id); } @Transactional(propagation = REQUIRED) public Person getById(long id) { return new Person(jdbcTemplate.queryForMap(...)); } @Transactional(propagation = REQUIRED, readOnly = false) public void save(Person person) { jdbcTemplate.update(...); } 

However, it would be best if the "save" method returns an identifier, because it is difficult to know in advance which identifier will ever be saved.

+4
source

Bad practice is to put transaction attributes at the DAO level. Also, I'm not sure why a transaction is needed for the getById method. Even if you want to use a transaction, you need to specify the distribution behavior as REQUIRES_NEW for the save and getById methods.

+5
source

It is good practice to label the service method that calls both of these DAO methods as @Transactional . The case has been clearly discussed here .

+4
source

All Articles