user798719
user798719

Reputation: 9869

How to use JTA to POST an array of objects using Jax-RS?

I have a jax-rs REST service that POSTs an

ArrayList<Book>

objects to the server.

On the server, I loop through each Book, convert it into a BookEntity (I'm using JPA), and then persist each book.

If any BookEntity fails to be persisted, I'd like the entire POST operation to fail and no Book Entities in that submitted ArrayList to be persisted. I want to rollback the entire operation so that it's all or nothing.

Does merely using Container Managed Transactions (which I understand you get for free by just injecting your Entity Manager) do the trick? Or do I need JTA to do this? I'm a bit confused about what part of transaction management is automatically done?

Thank you!

Upvotes: 0

Views: 321

Answers (1)

Perception
Perception

Reputation: 80603

Merely injecting an entity manager does not give you container managed transactions. These are the pre-requisites to enabling CMT for a service:

  1. Service must be an EJB (@Stateless, @Stateful, @MessageDriven)
  2. Service must define @TransactionManagement(CONTAINER). This is the default and as such, the entire annotation may be omitted
  3. Service must use a JTA entity manager for its JPA operations.

If all the pre-requisites are met, then for any given business method on the service the container will automatically manage its transaction. The transaction behavior can be fine-tuned on a method by method basis via use of TransactionAttribute annotations, but the default is that for each method:

  • If no transaction exists, start one
  • When the method completes, commit the transaction
  • If an exception is thrown by the method, rollback the transaction

Upvotes: 1

Related Questions