如何在后端线程中使用JpaRepository? [英] How do I use JpaRepository in a backend thread?

查看:394
本文介绍了如何在后端线程中使用JpaRepository?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的界面如下:

public interface PackageRepository extends JpaRepository<DocPackage, String> {
}

现在,通过使用以下命令,我可以在REST服务中使用它而不会出现任何问题:

Now I'm able to use this without any problem from my REST services by using:

@Resource
PackageRepository repo;

我可以毫无问题地对其进行交易调用.

I can make transactional calls on it with no problem.

但是,当我尝试从辅助线程中加载它时:

However when I try to load this from a worker thread:

public class MyWorker implements Runnable {
    @Resource
    PackageRepository repo;

    @Transactional
    private void doSomething() {
        DocPackage pck = repo.findOne("key");
        pck.setStatus(2);
        repo.saveAndFlush(pck);
    }

    public void run() {
        //stuff
        doSomething();
        //other stuff
    }
}

new Thread(new MyWorker()).start();

我可以对此仓库进行读取,但是每当我保存并刷新时,都会出现异常:

I'm able to do reads on this repo just fine, but whenever I save and flush I get the exception:

javax.persistence.TransactionRequiredException: no transaction is in progress

有什么方法可以正确完成此操作吗?

Is there any way to get this done correctly?

推荐答案

Spring默认情况下使用代理.这意味着@Transaction仅在从类外部调用方法时有效.

Spring, by default, use proxies. This mean @Transaction works only when method called from outside of class.

要修复此问题,请提取要使用的方法.将服务插入MyWorker并调用它.

To fix it extract you method to service. Inject your service in MyWorker and call it.

这篇关于如何在后端线程中使用JpaRepository?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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