Programming Tutorials

A sample Hibernate Web Application using Servlets

By: Felix in Hibernate Tutorials on 2023-05-08  

Complete step by step Hibernate web application using servlets with the Student entity:

  1. Create a Student entity class with annotations:
    package com.example.hibernate;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "students")
    public class Student {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private int id;
    
        private String name;
    
        private int age;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    }
    
  2. Create a HibernateUtil class to configure Hibernate and obtain the session factory:
    package com.example.hibernate;
    
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    
    public class HibernateUtil {
    
        private static SessionFactory sessionFactory;
    
        static {
            try {
                Configuration configuration = new Configuration();
                configuration.configure();
                sessionFactory = configuration.buildSessionFactory();
            } catch (Throwable ex) {
                System.err.println("Initial SessionFactory creation failed." + ex);
                throw new ExceptionInInitializerError(ex);
            }
        }
    
        public static SessionFactory getSessionFactory() {
            return sessionFactory;
        }
    }
    
  3. Create a StudentDAO class to perform CRUD operations on the Student entity:
    package com.example.hibernate;
    
    import java.util.List;
    
    import org.hibernate.Session;
    import org.hibernate.Transaction;
    
    public class StudentDAO {
    
        public void save(Student student) {
            Transaction transaction = null;
            try (Session session = HibernateUtil.getSessionFactory().openSession()) {
                transaction = session.beginTransaction();
                session.save(student);
                transaction.commit();
            } catch (Exception e) {
                if (transaction != null) {
                    transaction.rollback();
                }
                e.printStackTrace();
            }
        }
    
        public void update(Student student) {
            Transaction transaction = null;
            try (Session session = HibernateUtil.getSessionFactory().openSession()) {
                transaction = session.beginTransaction();
                session.update(student);
                transaction.commit();
            } catch (Exception e) {
                if (transaction != null) {
                    transaction.rollback();
                }
                e.printStackTrace();
            }
        }
    
        public void delete(int studentId) {
            Transaction transaction = null;
            try (Session session = HibernateUtil.getSessionFactory().openSession()) {
                transaction = session.beginTransaction();
                Student student = session.get(Student.class, studentId);
                if (student != null) {
                    session.delete(student);
                }
                transaction.commit();
            } catch (Exception e) {
                if (transaction != null) {
                    transaction.rollback();
                }
                e.printStackTrace();
            }
        }
    
        public Student get(int studentId) {
            try (Session session = HibernateUtil.getSessionFactory().openSession()) {
                Student student = session.get(Student.class, studentId);
                return student;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    
        public List<Student> getAll() {
            try (Session session = HibernateUtil.getSessionFactory().openSession()) {
                List<Student> students = session.createQuery("from Student", Student.class).list();
                return students;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }
    
  4. Create a servlet to handle HTTP requests and use the StudentDAO class to perform CRUD operations on the Student entity:
    package com.example.web;
    
    import com.example.dao.StudentDAO;
    import com.example.model.Student;
    
    import java.io.IOException;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @WebServlet("/students")
    public class StudentServlet extends HttpServlet {
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            
            StudentDAO studentDAO = new StudentDAO();
            List<Student> students = studentDAO.getAllStudents();
            request.setAttribute("students", students);
            request.getRequestDispatcher("students.jsp").forward(request, response);
        }
    }
    

    n the above code, we have created an instance of the StudentDAO class and used its getAllStudents() method to fetch all the student records from the database. We then set the list of Student objects as a request attribute with the name "students" and forward the request to a JSP page called students.jsp for rendering.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Hibernate )

Latest Articles (in Hibernate)