简体   繁体   中英

How do I use JpaRepository in a backend thread?

I have an interface as follows:

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

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, by default, use proxies. This mean @Transaction works only when method called from outside of class.

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

我认为你需要在你的方法中添加@Transactional注释

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM