Spring @Transactional annotation is not working

风流意气都作罢 提交于 2020-01-05 03:08:06

问题


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);
    }

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/32156652/spring-transactional-annotation-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!