lujop
lujop

Reputation: 13873

Managed CDI transaction with long operations

Suppose I've a CDI bean that needs

  1. Load some JPA entities
  2. Do long IO operation with that JPA entities (ie. call Web services)
  3. Update some of the JPA entities with the results of -2-

What is the best pattern if I want to avoid a long transaction while the IO operations run? I know I can use @Transactional(Transactional.TxType.REQUIRES_NEW) in -2- but to my understant the transaction opened in -1- will be only paused.

Until know I used old JBoss 4 with not container managed transactions and I used to do:

  1. Create entityManager without opening a new transaction
  2. Load JPA entities (no transaction opened)
  3. Do IO operations ie (call external Webservice)
  4. Open transaction, update jpa entities, close transaction

I know that pattern can have some data inconcistence because you update data obtained outside a transaction but it can be ok in some cases.

Is there any pattern to imitate old not container managed transaction in managed way. If it's possible without managing detached instances?

EDIT Response from @Alexander Langer is a good option for some cases. But I would also want to know an alternative to do that without jobs if it's possible. Because point -2- (long IO operation) can be only a simple call to external WS needed to serve the request.

Normally there isn't any problem holding a transaction on that. But if for some reason the external WS doesn't work correctly and takes a lot of time to respond then it's a big problem if transactions start to accumulate. In fact it can be a problem the simple fact to mantain the EntityManager openend without transaction and holding a database connection from the pool.

I know that there are timeouts, but in general I want to know a usable pattern to minimize transaction time for simple cases. Or know if it's simple an anti pattern for EE7 if not involving batch jobs.

Upvotes: 0

Views: 472

Answers (1)

Alexander Langer
Alexander Langer

Reputation: 2893

Take a look at Java EE Batch Processing introduced in Java EE 7. Its exactly what you are looking for.

Upvotes: 1

Related Questions