Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Transactional on a JpaRepository

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

like image 539
t0mmyw Avatar asked Mar 05 '14 14:03

t0mmyw


People also ask

Can we use @transactional in Repository?

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.

What does @transactional do in JPA?

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.

When should we use @transactional annotation?

The @Transactional annotation belongs to the Service layer because it is the Service layer's responsibility to define the transaction boundaries.

What does @transactional do in Spring boot?

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.


2 Answers

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?

like image 154
Funky coder Avatar answered Oct 04 '22 11:10

Funky coder


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.

like image 28
Niels Bech Nielsen Avatar answered Oct 04 '22 11:10

Niels Bech Nielsen