M
M
mitaichik2021-11-26 19:09:18
Spring
mitaichik, 2021-11-26 19:09:18

How to execute JPA requests in left threads (ExecutorService)?

Guys, hello everyone.

There is a component, in it ExecutorService. In it, I submit tasks that work with JPA.
When calling JPA, I get an exception No EntityManager with actual transaction available for current thread
Tried to hang everything @Transactional - does not work.
How to be in such a situation? I didn't find any easy solutions. It helps only if you hang @Transactional on the method itself in the repository, but this is clearly not a solution.

If the question arose why ExecutorService - you can’t do without it, there is a complicated story (third-party library)

Here is the code for an example:

@Component
@Transactional
public class TestComponent
{
  @Autowired
  private AccountReposiotry reposiotry;

  private final ExecutorService executor = Executors.newSingleThreadExecutor();

  @Scheduled(fixedDelay = 5000)
  @Transactional
  public void doSome()
  {
    executor.submit(this::delete);
  }

  @Transactional
  public void delete()
  {
    try {
      reposiotry.deleteByUserId(3);
    }
    catch (Throwable t) {
      t.printStackTrace();
    }
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan Hasanli, 2021-11-27
@mitaichik

Good afternoon.
And you did not look by chance here, this answer is a link
By the way, the answer was given by one of the Java Olympiads.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question