(JSF + JPA) - EJB = Bloat 📎
Without an EJB you will need for every EntityManager interaction at least 4 lines of code:
- tx.begin
- EntityManager interaction
- tx.commit
- consistent error handling + tx.rollback
The creation and management of an EntityManager is not even included. The code will look like this:
public class ManufacturerJpaController {
private EntityManagerFactory emf = null;
public ManufacturerJpaController() {
emf = Persistence.createEntityManagerFactory("WithOrWithoutEJBPU");
}
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Manufacturer manufacturer) throws PreexistingEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(manufacturer); // the only interesting method
em.getTransaction().commit();
} catch (Exception ex) {
if (findManufacturer(manufacturer.getManufacturerId()) != null) {
throw new PreexistingEntityException("Manufacturer " + manufacturer + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
With a single EJB 3 you can eliminate all the bloat - the EntityManager will be properly managed and injected by the container. The same code will look like:
@Stateless
public class ManufacturerFacade {
@PersistenceContext
private EntityManager em;
public void create(Manufacturer manufacturer) {
em.persist(manufacturer);
}
You could even build a generic and reusable CRUD Service. The @Stateless session bean can be directly injected into the backing bean then:
@ManagedBean (name="manufacturerController")
@SessionScoped
public class ManufacturerController {
@EJB private ManufacturerFacade ejbFacade;
}
There is no additional XML, libraries or additional frameworks needed. You can just jar everything in a WAR and you are done. Btw. the whole EJB 3 container in Glassfish v3 is < 1MB. The project WithOrWithoutEJB was pushed into: http://kenai.com/projects/javaee-patterns/. An average, incremental deployment takes < 1 second.
[See Chapter 1 (the basics), page 27, 37, 46 in "Real World Java EE Patterns Rethinking Best Practices" for state / transactions, dependency injection and JPA+EJB synergies]