问题
In my company the usage of the Spring framework is discouraged and instead Java EE 6 is promoted. But recently I read about Springs @Transactional
annotation at Using @Transactional and think this could be really useful for our code.
As far as I understand a method annotated with @Transactional
will either reuse an already existing transaction or open up a new transaction if no active transaction exists when calling that method. Is there something analogous (e.g. a similar annotation) available in Java EE 6?
回答1:
EJB components have this transactional control in Java EE. You can set the transaction of a method on the EJB to be Required, RequiresNew, Supports, etc. You would almost always use a Stateless Session Bean (@Stateless
) for the requirements you describe:
> @TransactionAttribute(value=[MANDATORY,
> REQUIRED, REQUIRES_NEW, SUPPORTS,
> NOT_SUPPORTED, NEVER]
Required, the default, will re-use an existing txn if there's one running or create a new one if there is not. Java EE 6 ships with EJB 3.1, so you don't even need the Business Interface and you can package the EJBs in the WAR file if you want. Therefore you are using EJBs, but to the developer they are much easier to integrate if all you want is JTA support.
This is a useful cheat sheet for the EJB annotations and there are numerous guides if you Google for them.
回答2:
Java EE 7 now contains @javax.transactional.Transactional. It acts quite the same as the spring annotation.
回答3:
In Java EE 6, one may annotate the EJB bean class itself, or the individual business methods in an EJB (both session EJBs and MDBs) with the TransactionAttribute annotation. This can be applied only if you use container managed transactions.
Valid values for the annotation are defined in the TransactionAttributeType annotation:
- NOT_SUPPORTED
- SUPPORTS
- REQUIRED
- REQUIRES_NEW
- MANDATORY
- NEVER
The semantics of these values haven't changed from the earlier versions of the EJB specification. These annotations are available since Java EE 5, when annotations were introduced in EJB 3.0. Note that, some of the values are not applicable in certain scenarios - MDBs for instance cannot be annotated with anything but REQUIRED and NOT_SUPPORTED; any other values would not make sense for container managed trasactions for a MDB (after all, the container must either create a transaction or musn't, in this case).
If you want a quick overview of how the transaction attributes compare between the EJB 3.0 and Spring models, I would gladly point you in the direction of Java Transaction Design Strategies. Disclaimer: I'm just a satisfied reader of this book.
回答4:
EJB's (stateless and stateful) are default transactional components, default transactional property is REQUIRED, similar to spring..
来源:https://stackoverflow.com/questions/6424289/is-there-something-analogous-to-springs-transactional-annotation-available-in-j