Hello,
I use Spring Data JPA and it works like a charm for me, reducing the amount of code significantly. Now I have a question about transactions and the default transactional behaviour of the CRUD methods of a CrudRepository.
Please, have a look at this example service class:
I think it is good practice to have a "@Transactional( readOnly = true )" at service classes. This means all methods are read-only-transactions by default. To define a write-transaction, I just have to use the @Transactional annotation again on a method to "override" the "readOnly" flag.Code:@Service @Transactional( readOnly = true ) public class CustomerServiceImpl implements CustomerService { @Resource private CustomerRepository customerRepository; // is a CrudRepository public void doSomethingWithCustomer() { Customer customer = new Customer(); customer.doSomeThing(...) customerRepository.save( customer ); } public void anotherServiceMethod() { // ... } }
In the above example, the method "doSomethingWithCustomer()" uses a "customerRepository" to actually WRITE an object to the database. I thought that I can omit the "@Transactional" on that method, because the CRUD-methods of Spring Data's CrudRepository ("customerRepository") already have the "@Transactional" annotation attached for the ".save"-Method.
Bus this does not work - the customer does not get written to the databse. It only works when I add a "@Transactional" annotation to the "doSomethingWithCustomer()" method.
To cut a long story short: I would like to understand why I still have to use the "@Transactional" annotation on the method "doSomethingWithCustomer()" - can someone help?
Thanks a lot!


Reply With Quote