I'm using a read only database to get some data in to my project. We use Spring v3 with jpa and hibernate
Will the following annotation have the effect of making all calls to my repository a read only transaction? Or do I need the annotation on the service layer calling the repository
package com.blah.jpa;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
@Transactional(readOnly = true)
public interface ServiceToServerRepository extends JpaRepository<ServiceToServerJPA, String> {
}
So we get all the findOne, findAll for free. But any updates should fail as it is a read only transaction
The usage of the @Repository annotation or @Transactional . @Repository is not needed at all as the interface you declare will be backed by a proxy the Spring Data infrastructure creates and activates exception translation for anyway.
The @Transactional annotation is the metadata that specifies the semantics of the transactions on a method. We have two ways to rollback a transaction: declarative and programmatic. In the declarative approach, we annotate the methods with the @Transactional annotation.
The @Transactional annotation belongs to the Service layer because it is the Service layer's responsibility to define the transaction boundaries.
So when you annotate a method with @Transactional , Spring dynamically creates a proxy that implements the same interface(s) as the class you're annotating. And when clients make calls into your object, the calls are intercepted and the behaviors injected via the proxy mechanism.
That should basically do it. But I usually opt for marking service-layer artifacts with Transactional
annotation. Anyway, please also check this post for more information of using transactionality together with Spring Data: How to use @Transactional with Spring Data?
The readOnly flag only hints that it is sufficient with a read only transaction while calling the method.
If you have a nested transaction from your service layer which is not read only, then it would use that one, and you will effectively disregard this annotation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With