Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @Transactional annotation is not working

I'm trying to run entityManager.merge(myEntity) within the following method but it seems that the @Transactional annotation is ignored. The Hibernate configuration seems to be fine because I can successfully fetch data from the db but it's not possible to write to the db. I'm using Spring version 3.2.3. Why are the writing db operations not working?

my method that does not work

package  com.reflections.importer.bls;
...

@Service
class BlsGovImporter {

...

    @Transactional
    private void importSeries(String externalId) {
        // This works. The dao is using EntityManager too
        Series series = seriesDao.findByExternalId(externalId);

        series.getValues().addAll(fetchNewValues());

        // This does not work and no exception is thrown 
        entityManager.merge(series);
    }
like image 586
eztam Avatar asked Dec 04 '22 02:12

eztam


2 Answers

Because it is used on private method. Spring Docs:

Method visibility and @Transactional

When using proxies, you should apply the @Transactional annotation only to methods with public visibility. If you do annotate protected, private or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings. Consider the use of AspectJ (see below) if you need to annotate non-public methods.

When its private, it is obviously called from within the same class. But Spring call needs to go through proxy in order to make it working. So the method will need to be called from another bean.

Other option is to annotate class with @Transactional.

like image 68
luboskrnac Avatar answered Dec 06 '22 18:12

luboskrnac


luboskrnac actualy answered it exactly for me, but just adding this to Spring newbie who might be confused on using proxy or not.

Please refer to this page explaining the case where even if you call an @Transactional method within the same class, since you call it without the same class, it will not be called via proxy.

https://www.logicbig.com/tutorials/spring-framework/spring-data-access-with-jdbc/correct-use-of-declarative-transaction.html

like image 44
Nap Avatar answered Dec 06 '22 19:12

Nap