Hibernate Tutorial
Core Hibernate
Hibernate Mapping
Hibernate Annotations
Hibernate with Spring Framework
Hibernate with Database
Hibernate Log4j
Inheritance Mapping
Building a Hibernate-based web application involves integrating Hibernate with a web framework. In this tutorial, we'll create a simple web application using Hibernate for ORM (Object-Relational Mapping) and Servlets for handling web requests.
<!-- Hibernate ORM --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.30.Final</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.23</version> </dependency> <!-- Servlet API --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency>
hibernate.cfg.xml
):Place this XML file in the src/main/resources
directory:
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property> <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testdb</property> <property name="hibernate.connection.username">username</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <!-- Add annotated class reference here --> </session-factory> </hibernate-configuration>
@Entity @Table(name="users") public class User { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private int id; @Column(name="name") private String name; // Constructors, getters, setters... }
@WebServlet("/add") public class AddUserServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userName = request.getParameter("name"); User user = new User(); user.setName(userName); // Saving user using Hibernate SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(user); session.getTransaction().commit(); response.sendRedirect("list"); // Redirect to listing page } }
@WebServlet("/list") public class ListUsersServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); List<User> users = session.createQuery("FROM User", User.class).list(); request.setAttribute("users", users); request.getRequestDispatcher("/list-users.jsp").forward(request, response); } }
<form action="add" method="post"> Name: <input type="text" name="name" required> <input type="submit" value="Add User"> </form>
<table> <tr> <th>ID</th> <th>Name</th> </tr> <c:forEach items="${users}" var="user"> <tr> <td>${user.id}</td> <td>${user.name}</td> </tr> </c:forEach> </table>
http://localhost:8080/YourAppName/
.This is a basic example to demonstrate how you can integrate Hibernate with Servlets to build a web application. In real-world applications, you might want to consider using established frameworks like Spring MVC, which offer seamless integration with Hibernate and provide many utilities for building robust web applications.
Integrating Hibernate with Servlets and JSP:
// Servlet public class MyServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Hibernate operations } }
<!-- JSP --> <html> <body> <% // Display data retrieved from Hibernate %> </body> </html>
Building a CRUD web application with Hibernate:
// Servlet or Controller public class ProductController extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Perform CRUD operations using Hibernate } }
Spring MVC and Hibernate integration example:
// Spring MVC Controller @Controller public class ProductController { @Autowired private ProductService productService; @RequestMapping("/products") public String listProducts(Model model) { // Use productService to fetch and display products return "products"; } }
Configuring Hibernate in a Java web application:
hibernate.cfg.xml
or programmatically.<!-- hibernate.cfg.xml --> <hibernate-configuration> <session-factory> <!-- Hibernate configuration --> </session-factory> </hibernate-configuration>
// HibernateUtil.java public class HibernateUtil { public static SessionFactory getSessionFactory() { // Build and return Hibernate SessionFactory } }
Using Hibernate with Struts framework in a web app:
// Struts Action public class ProductAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Use Hibernate for data operations return mapping.findForward("success"); } }
Managing transactions in Hibernate web applications:
// Servlet or Controller public class ProductController extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Transaction transaction = null; try { // Begin transaction transaction = HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction(); // Perform database operations // Commit transaction transaction.commit(); } catch (Exception e) { // Rollback transaction on exception if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } } }
Hibernate and JPA in a Spring Boot web application:
// JPA Entity @Entity public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; // Other fields and methods }
// Spring Data JPA Repository public interface ProductRepository extends JpaRepository<Product, Long> { // Custom queries if needed }
Handling concurrency in Hibernate web applications:
// JPA Entity with Versioning @Entity public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Version private Long version; // Other fields and methods }