Table of Contents
What Is JPA and Why Use Hibernate?
Setting Up JPA with Hibernate
Creating Your First Entity
Performing CRUD Operations
Relationships: One-to-Many Example
Best Practices and Common Pitfalls
Going Further: Spring Boot Integration
Home Java javaTutorial Java Persistence with JPA and Hibernate: A Complete Tutorial

Java Persistence with JPA and Hibernate: A Complete Tutorial

Jul 26, 2025 am 05:13 AM
java

JPA is the abbreviation of the Java Persistence API, a standard specification for mapping Java objects to database tables, and Hibernate is one of its most popular implementations, providing object-relational mapping (ORM) capabilities that simplify database operations. 1. JPA defines standards for entity mapping and CRUD operations, allowing developers to operate databases in an object-oriented way, avoiding writing a large amount of JDBC code. 2. Hibernate, as an implementation of JPA, not only supports JPA specifications, but also provides advanced features such as caching, lazy loading, and transaction management. 3. Use Maven to add hibernate-core and database driver (such as H2) dependencies, and configure database connections and Hibernate properties in src/main/resources/META-INF/persistence.xml, such as hbm2ddl.auto to control the generation strategy of the table structure. 4. Define the mapping relationship between entity class and database table through @Entity, @Table, @Id, @GeneratedValue, @Column and other annotations. 5. Use EntityManager to perform CRUD operations. All operations need to be performed in a transaction. Persist() saves the new entity, merge() updates the existing entity, find() query according to the primary key, remove() deletes the entity. 6. Support inter-entity relationship mapping, such as @OneToMany and @ManyToOne to implement one-to-many association, and configure cascade operations through cascade to ensure that the associated data is saved or deleted simultaneously. 7. Best practices include: timely shutting down EntityManager and EntityManagerFactory to prevent memory leaks, rewriting equals() and hashCode() methods, prioritizing FetchType.LAZY to avoid performance problems, using DTO instead of entity classes to expose APIs, and avoiding LazyInitializationException. 8. In Spring Boot project, it is recommended to use Spring Data JPA, which automatically obtains CRUD functions by inheriting the JpaRepository interface, and is managed by Spring management configuration, transactions and dependency injection. 9. You can preload the associated data through JPQL queries such as SELECT u FROM User u LEFT JOIN FETCH u.posts to avoid lazy loading exceptions. 10. In actual development, we should start with small functions, gradually increase entities, relationships and queries, and combine practice to deeply understand the use of JPA and Hibernate. You have now mastered the core knowledge of JPA and Hibernate and are able to build efficient data persistent Java applications.

Java Persistence with JPA and Hibernate: A Complete Tutorial

Java Persistence with JPA and Hibernate is a go-to combination for managing relational data in Java applications. Whether you're building a Spring Boot app or a standalone Java project, understanding how to persist data effectively is essential. This tutorial walks you through the fundamentals of JPA (Java Persistence API) and Hibernate — one of its most popular implementations — with practical examples and best practices.

Java Persistence with JPA and Hibernate: A Complete Tutorial

What Is JPA and Why Use Hibernate?

JPA (Java Persistence API) is a specification, not a concrete implementation. It defines how Java objects can be mapped to database tables, and how to perform CRUD (Create, Read, Update, Delete) operations using object-oriented syntax instead of raw SQL.

Hibernate is a full-featured, open-source ORM (Object-Relational Mapping) framework that implements the JPA specification. It adds extra features beyond JPA and handles the heavy lifting of translating Java objects to database records and vice versa.

Java Persistence with JPA and Hibernate: A Complete Tutorial

✅ Why use them together?

  • Write less boilerplate JDBC code
  • Work with Java objects instead of SQL queries
  • Leverage annotations for easy mapping
  • Support for advanced features like caching, lazy loading, and transactions

Setting Up JPA with Hibernate

To get started, you'll need the right dependencies. Here's how to set it up in a Maven project:

Java Persistence with JPA and Hibernate: A Complete Tutorial
 <dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>6.4.4.Final</version>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>2.2.224</version>
    </dependency>
</dependencies>

We're using H2 as an in-memory database for simplicity, but Hibernate supports MySQL, PostgreSQL, Oracle, and more.

Next, create a persistence.xml file in src/main/resources/META-INF/ :

 <?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="3.0">
    <persistence-unit name="my-persistence-unit">
        <properties>
            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:testdb"/>
            <property name="javax.persistence.jdbc.user" value="sa"/>
            <property name="javax.persistence.jdbc.password" value=""/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.show_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>

Key property:

  • hibernate.hbm2ddl.auto : update automatically creates or updates tables based on your entity classes. Use none , validate , or create-drop in production as needed.

Creating Your First Entity

An entity is a Java class mapped to a database table. Use JPA annotations to define the mapping.

 import jakarta.persistence.*;

@Entity
@Table(name = "users")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(unique = true)
    private String email;

    // Constructors
    public User() {}

    public User(String name, String email) {
        this.name = name;
        this.email = email;
    }

    // Getters and setters
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }

    @Override
    public String toString() {
        return "User{"  
                "id=" id  
                ", name=&#39;" name &#39;\&#39;&#39;  
                ", email=&#39;" email &#39;\&#39;&#39;  
                &#39;}&#39;;
    }
}

Annotations explained:

  • @Entity : Marks the class as a JPA entity.
  • @Table : Optional; customizes the table name.
  • @Id : Specifies the primary key.
  • @GeneratedValue : Tells Hibernate to auto-generate the ID.
  • @Column : Customize column definition (nullability, uniqueness, etc.).

Performing CRUD Operations

Use EntityManager to interact with the persistence context.

 import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
import jakarta.persistence.Persistence;

public class Main {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        EntityManager em = emf.createEntityManager();

        // Create
        em.getTransaction().begin();
        User user = new User("Alice", "alice@example.com");
        em.persist(user);
        em.getTransaction().commit();

        // Read
        User found = em.find(User.class, 1L);
        System.out.println("Found: " found);

        // Update
        em.getTransaction().begin();
        found.setName("Alicia");
        em.merge(found);
        em.getTransaction().commit();

        // Delete
        em.getTransaction().begin();
        em.remove(found);
        em.getTransaction().commit();

        em.close();
        emf.close();
    }
}

? Note:

  • Always wrap database operations in transactions.
  • persist() saves a new entity; merge() updates a detached one.
  • find() retrieves an entity by ID.

Relationships: One-to-Many Example

Most real-world apps involve relationships. Let's add Post entities linked to User .

 @Entity
public class Post {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;

    @ManyToOne
    @JoinColumn(name = "user_id")
    private User user;

    // constructors, getters, setters...
}

Now, a User can have multiple posts:

 @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Post> posts = new ArrayList<>();

When you save a user with posts (and cascade is enabled), Hibernate saves the posts automatically.

 User user = new User("Bob", "bob@example.com");
Post post1 = new Post("First Post");
Post post2 = new Post("Second Post");

post1.setUser(user);
post2.setUser(user);
user.getPosts().add(post1);
user.getPosts().add(post2);

em.getTransaction().begin();
em.persist(user);
em.getTransaction().commit();

This creates the user and both posts in a single transaction.


Best Practices and Common Pitfalls

Here are key tips to avoid common issues:

  • Always close EntityManager and EntityManagerFactory to prevent memory leaks.
  • Use equals() and hashCode() in entities — especially when using collections.
  • Avoid FetchType.EAGER by default; prefer FetchType.LAZY to prevent loading unnecessary data.
  • Don't expose entities directly in APIs — use DTOs (Data Transfer Objects) instead.
  • Be cautious with cascade = CascadeType.ALL — it can accidentally delete related data.
  • Initialize lazy collections inside the transaction (before closing EntityManager ), or use JOIN FETCH in queries.

Example of a JPQL query to fetch user with posts:

 String jpql = "SELECT u FROM User u LEFT JOIN FETCH u.posts WHERE u.id = :id";
User user = em.createQuery(jpql, User.class)
              .setParameter("id", 1L)
              .getSingleResult();

This avoids the "LazyInitializationException".


Going Further: Spring Boot Integration

In real projects, especially with Spring Boot, you won't use EntityManagerFactory directly. Instead:

  • Use Spring Data JPA for repository abstraction
  • Annotate your main class with @SpringBootApplication
  • Define repositories like:
 public interface UserRepository extends JpaRepository<User, Long> {
}

Spring handles the rest — configuration, transactions, and dependency injection.


That's it. You now have a solid foundation in JPA and Hibernate. From defining entities and relationships to performing CRUD and managing transactions, you're ready to build robust data-driven Java applications. The key is practice — trying adding more entities, queries, and constraints to deepen your understanding.

Basically, just start small, let Hibernate do the work, and learn as you go.

The above is the detailed content of Java Persistence with JPA and Hibernate: A Complete Tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1504
276
Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Comparing Java Frameworks: Spring Boot vs Quarkus vs Micronaut Aug 04, 2025 pm 12:48 PM

Pre-formanceTartuptimeMoryusage, Quarkusandmicronautleadduetocompile-Timeprocessingandgraalvsupport, Withquarkusoftenperforminglightbetterine ServerLess scenarios.2.Thyvelopecosyste,

Volume keys on keyboard not working Volume keys on keyboard not working Aug 05, 2025 pm 01:54 PM

First,checkiftheFnkeysettingisinterferingbytryingboththevolumekeyaloneandFn volumekey,thentoggleFnLockwithFn Escifavailable.2.EnterBIOS/UEFIduringbootandenablefunctionkeysordisableHotkeyModetoensurevolumekeysarerecognized.3.Updateorreinstallaudiodriv

How to compare two strings in Java? How to compare two strings in Java? Aug 04, 2025 am 11:03 AM

Use the .equals() method to compare string content, because == only compare object references rather than content; 1. Use .equals() to compare string values equally; 2. Use .equalsIgnoreCase() to compare case ignoring; 3. Use .compareTo() to compare strings in dictionary order, returning 0, negative or positive numbers; 4. Use .compareToIgnoreCase() to compare case ignoring; 5. Use Objects.equals() or safe call method to process null strings to avoid null pointer exceptions. In short, you should avoid using == for string content comparisons unless it is explicitly necessary to check whether the object is in phase.

How to join an array of strings in Java? How to join an array of strings in Java? Aug 04, 2025 pm 12:55 PM

Using String.join() (Java8) is the easiest recommended method for connecting string arrays, just specify the separator directly; 2. For old versions of Java or when more control is needed, you can use StringBuilder to manually traverse and splice; 3. StringJoiner is suitable for scenarios that require more flexible formats such as prefixes and suffixes; 4. Using Arrays.stream() combined with Collectors.joining() is suitable for filtering or converting the array before joining; To sum up, if Java8 and above is used, the String.join() method should be preferred in most cases, which is concise and easy to read, but for complex logic, it is recommended.

python logging to file example python logging to file example Aug 04, 2025 pm 01:37 PM

Python's logging module can write logs to files through FileHandler. First, call the basicConfig configuration file processor and format, such as setting the level to INFO, using FileHandler to write app.log; secondly, add StreamHandler to achieve output to the console at the same time; Advanced scenarios can use TimedRotatingFileHandler to divide logs by time, for example, setting when='midnight' to generate new files every day and keep 7 days of backup, and make sure that the log directory exists; it is recommended to use getLogger(__name__) to create named loggers, and produce

python pandas styling dataframe example python pandas styling dataframe example Aug 04, 2025 pm 01:43 PM

Using PandasStyling in JupyterNotebook can achieve the beautiful display of DataFrame. 1. Use highlight_max and highlight_min to highlight the maximum value (green) and minimum value (red) of each column; 2. Add gradient background color (such as Blues or Reds) to the numeric column through background_gradient to visually display the data size; 3. Custom function color_score combined with applymap to set text colors for different fractional intervals (≥90 green, 80~89 orange, 60~79 red,

Computed properties vs methods in Vue Computed properties vs methods in Vue Aug 05, 2025 am 05:21 AM

Computed has a cache, and multiple accesses are not recalculated when the dependency remains unchanged, while methods are executed every time they are called; 2.computed is suitable for calculations based on responsive data. Methods are suitable for scenarios where parameters are required or frequent calls but the result does not depend on responsive data; 3.computed supports getters and setters, which can realize two-way synchronization of data, but methods are not supported; 4. Summary: Use computed first to improve performance, and use methods when passing parameters, performing operations or avoiding cache, following the principle of "if you can use computed, you don't use methods".

Advanced Conditional Types in TypeScript Advanced Conditional Types in TypeScript Aug 04, 2025 am 06:32 AM

TypeScript's advanced condition types implement logical judgment between types through TextendsU?X:Y syntax. Its core capabilities are reflected in the distributed condition types, infer type inference and the construction of complex type tools. 1. The conditional type is distributed in the bare type parameters and can automatically split the joint type, such as ToArray to obtain string[]|number[]. 2. Use distribution to build filtering and extraction tools: Exclude excludes types through TextendsU?never:T, Extract extracts commonalities through TextendsU?T:Never, and NonNullable filters null/undefined. 3

See all articles