Integrate Hibernate Servlet or Struts2

Integrate Hibernate Servlet or Struts2

Hibernate can be integrated with both Servlet-based web applications and Struts2 web applications to manage database interactions. The integration ensures that Hibernate handles the data access layer while the servlet or Struts2 framework manages the web layer.

Steps for Integration

  • Setup Hibernate Configuration : Define Hibernate configuration in hibernate.cfg.xml.
  • Create Hibernate Utility Class : To manage SessionFactory.
  • Integrate with Servlet or Struts2 : For Servlets: Use the SessionFactory within servlet methods.
  • Struts2: Use SessionFactory within action classes or services.

Integration with Servlets

  Explanation

To integrate Hibernate with servlets, you need to:

1.  Configure Hibernate : Create hibernate.cfg.xml and mapping files.

2.  Create Hibernate Utility Class : Manage SessionFactory and sessions.

3.  Use Hibernate in Servlet : Obtain Session in the servlet to perform CRUD operations.

Hibernate with Servlet or Struts2

Example
  Hibernate Configuration (hibernate.cfg.xml)

xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/yourdb</property>
        <property name="hibernate.connection.username">yourusername</property>
        <property name="hibernate.connection.password">yourpassword</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <mapping class="com.example.model.User"/>
    </session-factory>
</hibernate-configuration>


  Hibernate Utility Class

java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.Session;

public class HibernateUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static Session getSession() {
        return sessionFactory.openSession();
    }
}


  Servlet Example

java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.Transaction;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Session session = HibernateUtil.getSession();
        Transaction tx = session.beginTransaction();

        User user = new User();
        user.setName("John Doe");
        user.setEmail("john.doe@example.com");

        session.save(user);
        tx.commit();
        session.close();

        response.getWriter().println("User saved successfully");
    }
}

Integration with Struts2

  Explanation

To integrate Hibernate with Struts2, you need to:

1.  Configure Hibernate : Create hibernate.cfg.xml and mapping files.

2.  Create Hibernate Utility Class : Manage SessionFactory and sessions.

3.  Use Hibernate in Action Classes : Obtain Session in Struts2 action classes to perform CRUD operations.

Example
Hibernate Configuration (hibernate.cfg.xml)

(Same as above)

  Hibernate Utility Class

(Same as above)

  Struts2 Action Class

java
import com.opensymphony.xwork2.ActionSupport;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class UserAction extends ActionSupport {
    private static final long serialVersionUID = 1L;
    private String name;
    private String email;

    public String execute() {
        Session session = HibernateUtil.getSession();
        Transaction tx = session.beginTransaction();

        User user = new User();
        user.setName(name);
        user.setEmail(email);

        session.save(user);
        tx.commit();
        session.close();

        return SUCCESS;
    }

    // Getters and Setters for name and email
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}


  Struts2 Configuration (struts.xml)

xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="default" extends="struts-default">
        <action name="saveUser" class="com.example.action.UserAction">
            <result name="success">/success.jsp</result>
        </action>
    </package>
</struts>

Conclusion

Integrate Hibernate Servlet or Struts2 web applications involves configuring Hibernate, creating a utility class to manage SessionFactory, and using Hibernate within servlet methods or Struts2 action classes to perform database operations. This setup ensures a clean separation of concerns and efficient database management.

Homepage

Readmore