Hibernate Tutorial
Core Hibernate
Hibernate Mapping
Hibernate Annotations
Hibernate with Spring Framework
Hibernate with Database
Hibernate Log4j
Inheritance Mapping
Hibernate is a powerful framework for persisting data in a relational database system. Let's break down the CRUD (Create, Read, Update, Delete) operations using Hibernate.
Follow the setup mentioned in the previous tutorial to create a Maven project, include Hibernate and database driver dependencies, and set up a Hibernate configuration file (hibernate.cfg.xml
).
Let's assume you have a simple entity Student
:
package com.example; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Student { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String firstName; private String lastName; private String email; // Default constructor, parameterized constructor, getters, and setters }
To insert a new student into the database:
Session session = factory.getCurrentSession(); try { Student student = new Student("John", "Doe", "john.doe@example.com"); session.beginTransaction(); session.save(student); session.getTransaction().commit(); } finally { session.close(); }
Retrieve a student based on the primary key:
Session session = factory.getCurrentSession(); try { session.beginTransaction(); int studentId = 1; // assuming a student with this id exists Student myStudent = session.get(Student.class, studentId); System.out.println("Retrieved student: " + myStudent); session.getTransaction().commit(); } finally { session.close(); }
Modify student data:
Session session = factory.getCurrentSession(); try { int studentId = 1; session.beginTransaction(); Student myStudent = session.get(Student.class, studentId); myStudent.setFirstName("UpdatedName"); session.getTransaction().commit(); } finally { session.close(); }
Remove a student from the database:
Session session = factory.getCurrentSession(); try { int studentId = 1; session.beginTransaction(); Student myStudent = session.get(Student.class, studentId); if(myStudent != null) { session.delete(myStudent); } session.getTransaction().commit(); } finally { session.close(); }
You can place each of these operations in separate methods or in separate classes based on your requirements, and then run them to perform the specific CRUD operation.
SessionFactory: Always remember to create a SessionFactory
once and reuse it throughout your application. This is a heavyweight object and is thread-safe.
Session: A new session should be created for every database operation or transaction. It's a lightweight object and is not thread-safe.
Transactions: Always use transactions, even for read operations. This ensures that your persistence code maintains ACID properties.
Closing: Always close the session once you're done with the database operations to release the resources.
Hibernate provides many more features and optimizations that you can use based on your needs. This tutorial provides a basic understanding and approach to using Hibernate for CRUD operations. As you delve deeper into Hibernate, you'll come across concepts like caching, HQL (Hibernate Query Language), Criteria API, and more.
Hibernate CRUD operations example:
Basic CRUD operations involve creating, reading, updating, and deleting records.
// Entity class @Entity public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private double price; // Getters and setters } // Example CRUD operations public class ProductDAO { public void create(Product product) { // Hibernate save operation Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); session.save(product); transaction.commit(); session.close(); } public Product read(Long id) { // Hibernate read operation Session session = HibernateUtil.getSessionFactory().openSession(); Product product = session.get(Product.class, id); session.close(); return product; } public void update(Product product) { // Hibernate update operation Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); session.update(product); transaction.commit(); session.close(); } public void delete(Long id) { // Hibernate delete operation Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); Product product = session.get(Product.class, id); if (product != null) { session.delete(product); } transaction.commit(); session.close(); } }
Hibernate save, update, delete operations:
Save, update, and delete operations are fundamental CRUD operations in Hibernate.
// Example of save, update, and delete operations ProductDAO productDAO = new ProductDAO(); // Create Product newProduct = new Product(); newProduct.setName("New Product"); newProduct.setPrice(99.99); productDAO.create(newProduct); // Read Product existingProduct = productDAO.read(newProduct.getId()); // Update existingProduct.setPrice(109.99); productDAO.update(existingProduct); // Delete productDAO.delete(existingProduct.getId());
Hibernate read operation with examples:
The read operation retrieves a record from the database based on its identifier.
// Example of Hibernate read operation ProductDAO productDAO = new ProductDAO(); // Read Product existingProduct = productDAO.read(1L); System.out.println("Product Name: " + existingProduct.getName());
Updating records in Hibernate:
The update operation modifies the state of a persistent object and synchronizes it with the database.
// Example of Hibernate update operation ProductDAO productDAO = new ProductDAO(); // Read Product existingProduct = productDAO.read(1L); // Update existingProduct.setPrice(109.99); productDAO.update(existingProduct);
Deleting records using Hibernate:
The delete operation removes a record from the database.
// Example of Hibernate delete operation ProductDAO productDAO = new ProductDAO(); // Delete productDAO.delete(1L);
Hibernate CRUD operations with annotations:
Hibernate annotations simplify the mapping of entities to database tables.
// Entity class with annotations @Entity @Table(name = "products") public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "product_id") private Long id; @Column(name = "product_name") private String name; @Column(name = "product_price") private double price; // Getters and setters }
Criteria API for CRUD in Hibernate:
The Criteria API provides a programmatic and type-safe way to perform queries in Hibernate.
// Example of Hibernate Criteria API CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder(); CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class); Root<Product> root = criteriaQuery.from(Product.class); criteriaQuery.select(root); criteriaQuery.where(criteriaBuilder.equal(root.get("name"), "Laptop")); List<Product> products = session.createQuery(criteriaQuery).getResultList();
Hibernate HQL for CRUD operations:
Hibernate Query Language (HQL) allows you to express queries using entity and property names.
// Example of Hibernate HQL String hql = "FROM Product WHERE name = :productName"; List<Product> products = session.createQuery(hql, Product.class) .setParameter("productName", "Laptop") .getResultList();