Key concepts of JPA and Hibernate

Here’s a detailed explanation of JPA (Java Persistence API) and Hibernate without the use of Spring or any other dependency injection framework. These concepts will focus on how to use JPA and Hibernate in a standalone Java application.


Java Persistence API (JPA) – Key Concepts

JPA is a specification that defines a set of rules for working with relational databases in Java. It is used to manage relational data in Java applications by mapping Java objects to database tables. JPA works with an EntityManager to handle CRUD operations, and it abstracts the interaction with the database.

1. Entity

  • An entity represents a persistent object that is mapped to a database table. Each instance of the entity corresponds to a row in the database table.
  • To define an entity, use the @Entity annotation:
    @Entity @Table(name = "employee") public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String role; // Getters and setters }
  • @Entity indicates that this class is a JPA entity.
  • @Table allows you to specify the table name (optional; if omitted, JPA uses the class name as the table name).

2. EntityManager

  • The EntityManager is the core interface used to interact with the persistence context (which tracks entity states).
  • It provides CRUD operations and JPQL (Java Persistence Query Language) querying capabilities.
    • persist(): Saves a new entity.
    • find(): Retrieves an entity by its primary key.
    • merge(): Updates an existing entity.
    • remove(): Deletes an entity.
  • Example:
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("myPersistenceUnit"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); Employee emp = new Employee("John", "Manager"); em.persist(emp); em.getTransaction().commit(); em.close(); emf.close();

3. Persistence Context

  • The Persistence Context is a set of entities that are managed by the EntityManager. This context ensures that entities are tracked and synchronized with the underlying database.
  • Changes made to entities are automatically persisted when the transaction is committed.
  • The context ensures that multiple queries or operations on the same entity are consistent (i.e., an entity is loaded once per session).

4. JPQL (Java Persistence Query Language)

  • JPQL is an object-oriented query language used to query entities, not the database itself. It operates on entity objects instead of database tables.
  • Example:
    TypedQuery<Employee> query = em.createQuery("SELECT e FROM Employee e WHERE e.role = :role", Employee.class); query.setParameter("role", "Manager"); List<Employee> result = query.getResultList();

5. Transactions

  • JPA relies on transactions to ensure data consistency and integrity. Transactions are typically managed through EntityManager.
  • You can manually handle transactions using the begin(), commit(), and rollback() methods.
  • Example of manual transaction management:
    em.getTransaction().begin(); em.persist(employee); em.getTransaction().commit();

6. Relationships

  • JPA supports mapping relationships between entities using annotations:
    • One-to-One: A one-to-one relationship.
    • One-to-Many: A one-to-many relationship.
    • Many-to-One: A many-to-one relationship.
    • Many-to-Many: A many-to-many relationship.
  • Example of a one-to-many relationship:
    @Entity @Table(name = "department") public class Department { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @OneToMany(mappedBy = "department") private List<Employee> employees; }

Hibernate – Key Concepts

Hibernate is an implementation of JPA, but it also provides additional features beyond JPA. It is a powerful ORM framework that simplifies the process of persisting Java objects into relational databases.

1. Session

  • The Session is the main interface for interacting with Hibernate. It provides methods to perform CRUD operations and execute HQL (Hibernate Query Language) queries.
  • It is analogous to the EntityManager in JPA.
  • Example:
    SessionFactory factory = new Configuration().configure("hibernate.cfg.xml") .addAnnotatedClass(Employee.class) .buildSessionFactory(); Session session = factory.getCurrentSession(); session.beginTransaction(); session.save(employee); session.getTransaction().commit(); factory.close();

2. SessionFactory

  • The SessionFactory is a thread-safe object that is responsible for creating Session instances. It is typically created once during the application startup.
  • Example of configuring a SessionFactory:
    SessionFactory factory = new Configuration() .configure("hibernate.cfg.xml") .addAnnotatedClass(Employee.class) .buildSessionFactory();

3. Hibernate Configuration

  • Hibernate configuration is usually done via an XML configuration file (e.g., hibernate.cfg.xml) or programmatically via Configuration objects.
  • Example hibernate.cfg.xml:

    <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/mydb</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">password</property> <property name="hibernate.hbm2ddl.auto">update</property> </session-factory> </hibernate-configuration>

4. Hibernate Query Language (HQL)

  • HQL is a query language similar to JPQL but with some Hibernate-specific features. It is used to query entity objects.
  • Example:
    Query<Employee> query = session.createQuery("FROM Employee WHERE role = :role", Employee.class); query.setParameter("role", "Manager"); List<Employee> employees = query.list();

5. Caching

  • First-Level Cache: Hibernate automatically caches entities within a session. This is called the first-level cache, and it operates at the session level.
  • Second-Level Cache: Hibernate provides an optional second-level cache at the SessionFactory level. This cache can be configured using third-party providers like EhCache or Infinispan.
  • Example of enabling second-level cache:
    <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

6. Hibernate Criteria API

  • The Criteria API provides a programmatic way to create database queries in a type-safe manner, avoiding the use of string-based queries like HQL.
  • Example:
    CriteriaBuilder builder = session.getCriteriaBuilder(); CriteriaQuery<Employee> criteria = builder.createQuery(Employee.class); Root<Employee> root = criteria.from(Employee.class); criteria.select(root).where(builder.equal(root.get("role"), "Manager")); List<Employee> employees = session.createQuery(criteria).getResultList();

7. Transactions

  • Hibernate manages transactions using the Transaction interface. Transactions are typically handled using the begin(), commit(), and rollback() methods.
  • Example of manual transaction management:
    Session session = factory.getCurrentSession(); session.beginTransaction(); session.save(employee); session.getTransaction().commit();

Differences Between JPA and Hibernate (Standalone)

FeatureJPAHibernate
TypeSpecification for ORMORM framework that implements JPA and adds extra features
EntityManager/SessionEntityManager interface (part of JPA)Session interface (additional Hibernate features)
Query LanguageJPQL (Java Persistence Query Language)HQL (Hibernate Query Language)
CachingNo built-in caching (depends on implementation)First-level and second-level caching (built-in support)
ConfigurationConfigured using persistence.xmlConfigured using hibernate.cfg.xml
FeaturesBasic ORM functionalityAdditional features like HQL, Criteria API, and caching
Vendor IndependenceDesigned to be database-agnosticCan be used as a standalone ORM or as a JPA provider

Comments