Table des matières
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
Maison Java javaDidacticiel Java Persistance avec JPA et Hibernate: un tutoriel complet

Java Persistance avec JPA et Hibernate: un tutoriel complet

Jul 26, 2025 am 05:13 AM
java

JPA 是 Java Persistence API 的缩写,是一种用于将 Java 对象映射到数据库表的标准规范,而 Hibernate 是其最流行的实现之一,提供了对象关系映射(ORM)功能,能够简化数据库操作。1. JPA 定义了实体映射和 CRUD 操作的标准,使开发者可以使用面向对象的方式操作数据库,避免编写大量 JDBC 代码。2. Hibernate 作为 JPA 的实现,不仅支持 JPA 规范,还提供缓存、懒加载、事务管理等高级特性。3. 使用 Maven 添加 hibernate-core 和数据库驱动(如 H2)依赖,并在 src/main/resources/META-INF/persistence.xml 中配置数据库连接和 Hibernate 属性,如 hbm2ddl.auto 控制表结构的生成策略。4. 通过 @Entity、@Table、@Id、@GeneratedValue、@Column 等注解定义实体类与数据库表的映射关系。5. 使用 EntityManager 进行 CRUD 操作,所有操作需在事务中进行,persist() 保存新实体,merge() 更新已有实体,find() 根据主键查询,remove() 删除实体。6. 支持实体间关系映射,如 @OneToMany 和 @ManyToOne 实现一对多关联,并通过 cascade 配置级联操作,确保关联数据同步保存或删除。7. 最佳实践包括:及时关闭 EntityManager 和 EntityManagerFactory 防止内存泄漏,重写 equals() 和 hashCode() 方法,优先使用 FetchType.LAZY 避免性能问题,使用 DTO 而非实体类暴露 API,避免 LazyInitializationException。8. 在 Spring Boot 项目中,推荐使用 Spring Data JPA,通过继承 JpaRepository 接口自动获得 CRUD 功能,由 Spring 管理配置、事务和依赖注入。9. 可通过 JPQL 查询如 SELECT u FROM User u LEFT JOIN FETCH u.posts 预加载关联数据,避免懒加载异常。10. 实际开发中应从小功能开始,逐步增加实体、关系和查询,结合实践深入掌握 JPA 与 Hibernate 的使用。你现在已经掌握了 JPA 和 Hibernate 的核心知识,能够构建高效的数据持久化 Java 应用。

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='" + name + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

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 — try adding more entities, queries, and constraints to deepen your understanding.

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

Video Face Swap

Video Face Swap

Échangez les visages dans n'importe quelle vidéo sans effort grâce à notre outil d'échange de visage AI entièrement gratuit !

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Sujets chauds

Tutoriel PHP
1535
276
Excel trouver et remplacer ne fonctionne pas Excel trouver et remplacer ne fonctionne pas Aug 13, 2025 pm 04:49 PM

CheckkSearchSettings like "MatchEnteRireCellContents" et "MatchCase" ByExpandingOptionsInFindanDreplace, garantissant "lookin" issettominuesand »dans" TOCORRECTSCOPE; 2.LOORHFORHIDDENCHARACTER

Comment déployer une application Java Comment déployer une application Java Aug 17, 2025 am 12:56 AM

Préparez-vous en application par rapport à Mavenorgradletobuildajarorwarfile, externalisationConfiguration.2.ChoOSEADPLOYENDIRONMENT: Runonbaremetal / vmwithjava-jarandsystemd, deploywarontomcat, compeneriserisewithdocker, orusecloudplatformslikelise.

Comment configurer la journalisation dans une application Java? Comment configurer la journalisation dans une application Java? Aug 15, 2025 am 11:50 AM

L'utilisation de SLF4J combinée avec la journalisation ou le log4j2 est le moyen recommandé de configurer les journaux dans les applications Java. Il introduit des bibliothèques API et implémentation en ajoutant des dépendances Maven correspondantes; 2. Obtenez l'enregistreur via le loggerfactory de SLF4J dans le code et écrivez le code journal découplé et efficace à l'aide de méthodes de journalisation paramétrée; 3. Définir le format de sortie du journal, le niveau, la cible (console, le fichier) et le contrôle du journal du package via Logback.xml ou les fichiers de configuration log4j2.xml; 4. Activer éventuellement la fonction de balayage de fichiers de configuration pour atteindre un ajustement dynamique du niveau de journal, et Springboot peut également être géré via des points de terminaison de l'actionneur; 5. Suivez les meilleures pratiques, y compris

Liaison des données XML avec Castor en Java Liaison des données XML avec Castor en Java Aug 15, 2025 am 03:43 AM

CASTORENablesxml-to-javaObjectMappingViadefaultConverionsOrexplicitMappingFiles; 1) DefinejavaclasseswithGetters / seters; 2) useUnmarShallertOConvertXmltoObjects; 3)

JS Ajouter un élément au début du tableau JS Ajouter un élément au début du tableau Aug 14, 2025 am 11:51 AM

Dans JavaScript, la méthode la plus courante pour ajouter des éléments au début d'un tableau est d'utiliser la méthode Unsich (); 1. En utilisant unsith () modifiera directement le tableau d'origine, vous pouvez ajouter un ou plusieurs éléments pour retourner la nouvelle longueur du tableau ajouté; 2. Si vous ne souhaitez pas modifier le tableau d'origine, il est recommandé d'utiliser l'opérateur d'extension (tel que [Newelement, ... Arr]) pour créer un nouveau tableau; 3. Vous pouvez également utiliser la méthode CONCAT () pour combiner le nouveau tableau d'éléments avec le numéro d'origine, renvoyez le nouveau tableau sans modifier le tableau d'origine; En résumé, utilisez Unsich () lors de la modification du tableau d'origine et recommandez l'opérateur d'extension lorsque vous gardez le tableau d'origine inchangé.

Comparaison des performances: Java Vs. GO pour les services backend Comparaison des performances: Java Vs. GO pour les services backend Aug 14, 2025 pm 03:32 PM

GOTYPICAL OFFERSBETTERRUNTIMEPERFORMANCE AVEC LA MAINTRÉE DE PUTHROUGHTANDLOWERLATENCE, ENTERTFORI / O-HEAVYSERVICES, DUETOITSLIGHT LONDEGOROUTINESANDERFICENTSCHEDULL

Comment travailler avec JSON à Java Comment travailler avec JSON à Java Aug 14, 2025 pm 03:40 PM

ToworkwithJSONinJava,useathird-partylibrarylikeJackson,Gson,orJSON-B,asJavalacksbuilt-insupport;2.Fordeserialization,mapJSONtoJavaobjectsusingObjectMapperinJacksonorGson.fromJson;3.Forserialization,convertJavaobjectstoJSONstringsviawriteValueAsString

Quel est le mot-clé Assert en Java? Quel est le mot-clé Assert en Java? Aug 17, 2025 am 12:52 AM

TheassertKeywordInjavaisUsedTovalIdateShandshandingsDuringDevelopment, ThrowinganAssertionErroriftheconditionisfalse.2.ithastwoforms: AssertCondition; AndSersertCondition: Message; avecthelatterProvidActureCustomerMessage.3.

See all articles