Language: Java
Data
Hibernate was created to solve the problem of manual JDBC code and boilerplate SQL queries. It provides a high-level abstraction for database operations, supports caching, lazy loading, and transaction management, making Java applications more maintainable and scalable.
Hibernate is a powerful Object-Relational Mapping (ORM) framework for Java that simplifies database interactions by mapping Java objects to relational database tables.
Add hibernate-core dependency in pom.xmlAdd implementation 'org.hibernate:hibernate-core:5.6.15.Final' in build.gradleHibernate allows developers to interact with databases using Java objects rather than SQL. It provides features like automatic table generation, HQL (Hibernate Query Language), transaction management, and caching.
// User.java
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
@Entity
public class User {
@Id
private Long id;
private String name;
private String email;
// getters and setters
}Defines a simple `User` entity that maps to a database table using JPA annotations.
// HibernateUtil.java
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory =
new Configuration().configure().buildSessionFactory();
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}Creates a singleton `SessionFactory` which is used to open sessions for database operations.
import org.hibernate.Session;
import org.hibernate.Transaction;
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
User user = new User();
user.setId(1L);
user.setName("Alice");
session.save(user);
tx.commit();
session.close();Demonstrates saving a `User` entity to the database using Hibernate session and transaction.
Session session = HibernateUtil.getSessionFactory().openSession();
List<User> users = session.createQuery("FROM User WHERE name = :name", User.class)
.setParameter("name", "Alice")
.list();
session.close();Uses Hibernate Query Language (HQL) to fetch users with a specific name.
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
User user = session.get(User.class, 1L);
user.setEmail("alice@example.com");
session.update(user);
tx.commit();
session.close();Updates an existing user entity in the database.
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
User user = session.get(User.class, 1L);
session.delete(user);
tx.commit();
session.close();Deletes a user entity from the database.
Use JPA annotations for entity mapping for portability.
Always manage transactions explicitly for consistency.
Close sessions to release database connections.
Use caching (first-level and second-level) to improve performance.
Prefer parameterized queries or HQL to prevent SQL injection.