EJB 3.0 is one of the major improvements introduced with Java EE 5.0. It aims at reducing the complexity of older versions of EJB and simplifies Enterprise Java development and deployment. You will notice that to declare a class as a 'Session Bean' you simply have to annotate it. Using annotations eliminates the complexity involved with too many deployment descriptors. Also the only interface an EJB3 Session Bean requires is a business interface that declares all the business methods that must be implemented by the bean.
We will explore the two important source files associated with the Bean implementation in our application: TodoDaoInt.java
and TodoDao.java
.
Business interface: TodoDaoInt.java
We define here the methods that need to be implemented by the bean implementation class. Basically, the business methods that will be used in our application are defined here.
public interface TodoDaoInt { public void persist (Todo todo); public void delete (Todo todo); public void update (Todo todo); public List <Todo> findTodos (); public Todo findTodo (String id); }
Stateless Session Bean: TodoDao.java
The @Stateless
annotation marks the bean as a stateless session bean. In this class, we need to access the Entity bean Todo
defined earlier. For this we need an EntityManager
. The @PersistenceContext
annotation tells the JBoss Server to inject an entity manager during deployment.
@Stateless public class TodoDao implements TodoDaoInt { @PersistenceContext private EntityManager em; public void persist (Todo todo) { em.persist (todo); } public void delete (Todo todo) { Todo t = em.merge (todo); em.remove( t ); } public void update (Todo todo) { em.merge (todo); } public List <Todo> findTodos () { return (List <Todo>) em.createQuery("select t from Todo t") .getResultList(); } public Todo findTodo (String id) { return (Todo) em.find(Todo.class, Long.parseLong(id)); } }