Spring @Transactional注释不起作用 [英] Spring @Transactional annotation is not working

查看:127
本文介绍了Spring @Transactional注释不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在以下方法中运行entityManager.merge(myEntity),但似乎@Transactional注释已被忽略.Hibernate配置似乎很好,因为我可以成功地从数据库中获取数据,但无法写入数据库.我正在使用Spring版本3.2.3.为什么编写数据库操作无效?

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?

我无法使用的方法

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

推荐答案

因为它用于私有方法. Spring Docs :

Because it is used on private method. Spring Docs:

方法可见性和@Transactional

Method visibility and @Transactional

使用代理时,应应用@Transactional批注仅适用于具有公众知名度的方法.如果您在受保护的地方添加注释,带有@Transactional批注的私有或包可见方法,不会引发任何错误,但是带注释的方法不会显示配置的交易设置.考虑使用AspectJ(请参阅下面)是否需要注释非公开方法.

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.

当它是私有的时,显然是在同一类中调用的.但是Spring调用需要通过代理才能使其正常工作.因此,该方法将需要从另一个bean调用.

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.

其他选择是使用@Transactional注释类.

Other option is to annotate class with @Transactional.

这篇关于Spring @Transactional注释不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆