Marco
Marco

Reputation: 179

JPA and EJB - When do I need to use transaction?

I'm learning persistence in Java following some tutorial.

I'm using Java EE 7 and Payara server.

I noticed that each uses a different method for persistence.

Examples:

When and why do I have to use the last one?

Is it necessary to use em.close() at the end of each method?

What are the good practices?

Upvotes: 2

Views: 4281

Answers (1)

BalusC
BalusC

Reputation: 1108557

The first one, an EJB method without all that manual flush and transaction fuzz, is the canonical approach. A single EJB method call counts by default already as a single full transaction. The EJB container will transparently begin the transaction before the method is invoked and commit the transaction when the method returns (or rollback when an application exception is thrown from the method).

The manual flush in second example is unnecessary. Generally, you want to use em.flush() only when you're modifying an entity (i.e. making it "dirty") and want afterwards (indirectly) perform a SELECT on it within the very same transaction. It's rare, but there are real world use cases for it, generally when you'd like to SELECT a parent whose the dirty entity is a child of.

The manual transaction management in third example is totally unnecessary. You should already realize that after having read the first paragraph. Manual transaction management is only necessary when you aren't using JTA, but RESOURCE_LOCAL (usually, in Java SE not Java EE).

See also:

Upvotes: 5

Related Questions