Reputation: 6073
I am using JSF 2.1, EJB 3.1, JPA 2.0, Glassfish 3.1.1 and NetBeans 7.0.1.
For each entity class I created a separate Facade class, for example, UserFacade and AddressFacade using NetBeans tools. These two entities are not related to each other and are completely independent of each of other. However, I need to put them into database during one transaction and if one fails to be inserted then another one should also be rollbacked. How can I do that? As far as I know EJB container manages transactions itself and doesn't allow to manually control the transaction boundaries.
Upvotes: 2
Views: 5051
Reputation: 2093
It is possible to control transactions yourself. This feature is called Bean-Managed Transactions (BMT). You can read more about them here.
Also you'll need to understand TransactionManagement
thing. Oracle describes it in this article.
Example:
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class MyEJB implements MyEJBLocal {
@Resource
private EJBContext context;
@PersistenceContext
private EntityManager em;
public void doMyAction() {
UserTransaction transaction = context.getUserTransaction();
transaction.begin();
... create myEntity ...
em.persist(myEntity);
transaction.commit();
}
}
Upvotes: 2
Reputation: 6543
The transaction will be rollback everything as long as you "touch" both of your entities in the same persist, update or remove, however, you say that they are not related to each other in anyway and so Im guessing that you have to perform 2 persists and that will not be in the same transaction scope.
Option 1
You could do something easy and ugly for this, there is @PrePersist and @PreUpdate in JPA that you can make sure that everything is with the previous persist. This will make a bad codebase and force unwanted dependencies.
Option 2
You could simply have a relation between User and Address, which is only natural.
Option 3
The third option is to use Bean Managed Transaction
Upvotes: 3
Reputation: 10389
In the very basic case, every public method of an EJB is executed in one transaction that rolled back when an exception is thrown inside the method.
So if you create both entities in the same method, the creations will be wrapped in one transaction.
Upvotes: 2