Injecting key Hibernate objects

If you have been through the Hibernate web application carefully, you might advocate that it is not a pure MVC application, as we are accessing the persistence layer from within the servlet.

This approach can be useful for a learner who wants an easy-to-catch example of Hibernate. However, you can create a clean separation of roles between the controller and the model tier, also by introducing an EJB as intermediary.

From inside your Hibernate project, add another stateless session bean named com.packtpub.hibernate.HibernateDAOBean implementing a local interface com.packtpub.hibernate.HibernateDAOLocal.

Following is a code snippet of the bean implementing the saveEmployee method:

@Stateless
@LocalBinding(jndiBinding="HibernateDAO/local")
public class HibernateDAOBean implements HibernateDAO {
 @PersistenceUnit(unitName="hibernateUnit") //[1]
 SessionFactory factory;
  public void saveEmployee(String name,String salary,String departmentId) {
  Session hsession=null;
  try {
   hsession = factory.openSession();
   Query query = hsession.createQuery("from Department d where
   d.departmentId = :departmentId");
   query.setInteger("departmentId", new Integer(departmentId));
   Department dep = (Department) query.uniqueResult();
   Employee emp = new Employee();
   emp.setDepartment(dep);
   emp.setEmployeeName(name);
   emp.setEmployeeSalary(Integer.parseInt(salary));
   hsession.save(emp);
  }
  catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    throw new EJBException(e.getMessage());
  }
  finally {
   if (hsession.isOpen())
   hsession.close();
  }
 }


The most interesting point in this example is that you have injected the Hibernate SessionFactory in your bean by means of the persistence unit named hibernateUnit. Therefore, you have to equip your application with a JPA persistence.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="hibernateUnit" transaction-type="JTA">
 <provider>org.hibernate.ejb.HibernatePersistence</provider>
 <jta-data-source>java:/MySqlDS</jta-data-source>
 <properties>
 <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
 </properties>
</persistence-unit>
</persistence>


We leave as exercise to the reader to complete the EJB with all other methods. On the web tier, you will do a clear cut of all the persistence stuff, just taking care to invoke the EJB with the parameters collected from the request. Look how simple and effective your servlet method saveEmployee has become:

@EJB(mappedName = "HibernateDAO/local")
HibernateDAO hibernateDAO;
 private String saveEmployee(HttpServletRequest request) {
 Session hsession=null;
 String name=request.getParameter("name");
 String salary=request.getParameter("salary");
 String departmentId=request.getParameter("departmentId");
 try {
 hibernateDAO.saveEmployee(name,salary,departmentId);
 }
 catch (Exception e) {
 e.printStackTrace();
 }
 return employeeList(request);
 }

 


A snapshot of the complete Hibernate EJB-driven project follows here:


hibernate jboss example application
As you can see, using Hibernate API works much the same way as the EntityManager interface. This example reveals another difference with our former web application. Here the EJB must not attempt to manage the life cycle of the Hibernate session; this is done internally by the EJB container, which is in charge of commiting or rolling back the transaction, following the EJB container's policies.
Summary

Hibernate is a flexible framework that can be used in any Java application environment. In our excursus, we have showed how to develop a sample application that is geared toward a managed environment.

Article taken from JBoss AS 5 Development

jboss 5 as development book

Develop, deploy, and secure Java applications on this robust, open source application server

  • A complete guide for JBoss developers covering everything from basic installation to creating, debugging, and securing Java EE applications on this popular, award-winning JBoss application server
  • Master the most important areas of Java Enterprise programming including EJB 3.0, web services, the security framework, and more
  • Starts with the basics of JBoss AS and moves on to cover important advanced topics with the help of easy-to-understand practical examples
  • Written in a very simple and readable style, this book includes essential tips and tricks that will help you master JBoss AS development


Read the first part of this article here.

0
0
0
s2smodern