Java Tutorial/EJB3/Transaction
Bean Managed Transaction
File: EmployeeBean.java
import javax.annotation.Resource;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class EmployeeBean implements EmployeeServiceLocal, EmployeeServiceRemote {
@PersistenceContext(unitName = "EmployeeService")
private EntityManager manager;
@Resource UserTransaction tx;
public void doAction() {
try {
try {
tx.begin();
// do the work...
System.out.println("Processing...");
} finally {
tx.rumit();
}
} catch (Exception e) {
// handle all the tx.begin()/commit() exceptions
throw new EJBException(e);
}
}
}
Container Managed Transaction Attribute Type: REQUIRED
File: EmployeeBean.java
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@Stateless
public class EmployeeBean implements EmployeeServiceLocal, EmployeeServiceRemote {
@PersistenceContext(unitName = "EmployeeService")
private EntityManager manager;
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void doAction() {
Customer cust = new Customer();
cust.setFirstName("Joe");
manager.persist(cust);
System.out.println("Saved");
cust = manager.find(Customer.class,cust.getSsn());
System.out.println(cust.getFirstName());
cust.setFirstName("new Name");
manager.merge(cust);
cust = manager.find(Customer.class,cust.getSsn());
System.out.println(cust.getFirstName());
}
}
Transaction Attribute Type: REQUIRES_NEW
File: Customer.java
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.Id;
import javax.persistence.PostRemove;
@Entity
public class Customer implements java.io.Serializable {
private String firstName;
private String lastName;
@Id
private long ssn;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public long getSsn() {
return ssn;
}
public void setSsn(long ssn) {
this.ssn = ssn;
}
}