Hibernate Tutorial «Prev  Next»

Mapping POJO with persistence layer using hibernate mapping document

In modern versions of Hibernate (5.x and 6.x), the use of XML-based mapping documents is still supported, but not commonly used anymore. Instead, Hibernate encourages the use of annotations directly on POJOs (Plain Old Java Objects), which is a more concise and maintainable approach.
βœ… Modern Approach: Annotations
Hibernate leverages Java Persistence API (JPA) annotations, like:
@Entity
@Table(name = "employees")
public class Employee {
    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "first_name")
    private String firstName;

    // other fields, getters, and setters
}
This eliminates the need for a separate XML mapping file.
πŸ—‚οΈ Legacy Approach: Hibernate Mapping Document (XML)
Older Hibernate versions (pre-JPA standardization or if XML was preferred) used `.hbm.xml` files for mapping:
<hibernate-mapping>
    <class name="com.example.Employee" table="employees">
        <id name="id" column="id">
            <generator class="native"/>
        </id>
        <property name="firstName" column="first_name"/>
    </class>
</hibernate-mapping>


This approach is still supported for backward compatibility or complex configurations, but is largely deprecated in real-world use.
Summary
Feature Annotation-based Mapping XML Mapping Document
Recommended in Hibernate 6 βœ… Yes ⚠️ Not preferred
Ease of use βœ… Easier and cleaner ❌ Verbose
Tooling support (IDE) βœ… Strong ⚠️ Limited
Required for basic use ❌ No ❌ No
Use case today 95% of modern apps Legacy systems only

So while Hibernate still supports mapping documents, today’s best practice is to use annotations for POJO-to-database mappings.

Java Persistence API (JPA) Described

The "Java Persistence API (JPA) is the standard ORM (Object-Relational Mapping) specification in Java. It provides a framework for managing relational data in Java applications. Hibernate is one of the most widely used implementations of the JPA specification.
βš™οΈ Basic Theory Behind JPA
At its core, JPA provides a way to map Java objects (POJOs) to relational database tables and to manage these objects' lifecycle through transactions and queries.
πŸ”‘ Core Concepts of JPA
Concept Description
Entity A lightweight, persistent domain object. Annotated with `@Entity`.
Entity Manager The main API to interact with the persistence context. It manages the lifecycle of entities.
Persistence Context A cache or workspace where entities are managed during a transaction.
JPQL (Java Persistence Query Language) Object-oriented query language similar to SQL but operates on entity objects.
Transactions JPA operations are done within transactions, usually managed by the container (like Spring or EJB).

🧠 High-Level Idea
  1. Object Mapping: Java classes are annotated (or XML-mapped) to represent database tables.
  2. State Management: JPA tracks the state of entity objects (e.g., new, managed, detached, removed).
  3. Querying: You use JPQL or Criteria API to query entities (instead of writing SQL directly).
  4. Automatic SQL Generation: JPA translates operations on entities into actual SQL statements behind the scenes.
  5. Portability: Because it’s a standard API, you can switch between implementations (e.g., Hibernate, EclipseLink) with minimal code change.

🧩 Example Flow
@Entity
public class Book {
    @Id
    @GeneratedValue
    private Long id;
    private String title;
}
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();

Book b = new Book();
b.setTitle("Java Persistence with Hibernate");
em.persist(b);

em.getTransaction().commit();
➑️ JPA takes care of generating the necessary SQL to insert the `Book` entity into the database.
πŸš€ Benefits of JPA
  • βœ… Abstracts away SQL
  • βœ… Encourages clean object-oriented design
  • βœ… Reduces boilerplate code
  • βœ… Portable across vendors
  • βœ… Supports caching, lazy loading, and relationships (1:1, 1:N, N:M)


One can also generate Hibernate mapping documents using Hibernate extension toolset. Hibernate mapping documents are straight forward. The <class> element maps a table with corresponding class. The <id> element represents the primary key column, and its associated attribute in the domain object. The <property> elements represent all other attributes available in the domain object.

SEMrush Software