Les associations entre entités avec JPA

Contrôles des relations entre entités avec JPA.

Lecture
Containers
Java
JPA
Persistence
ORM
Apprenez à gérer les associations entre entités en utilisant Jakarta Persistence API (JPA) avec des exemples pratiques en Java.
Auteur
Affiliations

Université de Toulon

LIS UMR CNRS 7020

Date de publication

2026-10-14

JPA offre une prise en charge complète pour la gestion des relations entre entités de différents types, que ce soit en mode un-vers-un (OneToOne), un-vers-plusieurs (OneToMany), ou plusieurs-vers-plusieurs (ManyToMany). Ces relations peuvent être configurées de manière unidirectionnelle ou bidirectionnelle.

One To One (1-1)

Dans certaines situations, lors de la modélisation orientée objet, il est nécessaire d’associer deux classes dans une relation un-à-un, mais en gardant une seule relation.

java.io.IOException: Cannot run program "/opt/local/bin/dot": Exec failed, error: 2 (No such file or directory) 
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1112)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1046)
    at net.sourceforge.plantuml.dot.ProcessRunner.run(ProcessRunner.java:71)
    at net.sourceforge.plantuml.dot.ProcessRunner.run(ProcessRunner.java:60)
    at net.sourceforge.plantuml.dot.GraphvizVersionFinder.dotVersion(GraphvizVersionFinder.java:120)
    at net.sourceforge.plantuml.dot.GraphvizVersionFinder.getVersion(GraphvizVersionFinder.java:75)
    at net.sourceforge.plantuml.dot.GraphvizRuntimeEnvironment.getVersion(GraphvizRuntimeEnvironment.java:86)
    at net.sourceforge.plantuml.svek.DotStringFactory.getGraphvizVersionInternal(DotStringFactory.java:278)
    at net.sourceforge.plantuml.svek.DotStringFactory.getGraphvizVersion(DotStringFactory.java:267)
    at net.sourceforge.plantuml.svek.GraphvizImageBuilder.printEntityInternal(GraphvizImageBuilder.java:381)
    at net.sourceforge.plantuml.svek.GraphvizImageBuilder.printEntity(GraphvizImageBuilder.java:363)
    at net.sourceforge.plantuml.svek.GraphvizImageBuilder.printEntities(GraphvizImageBuilder.java:355)
    at net.sourceforge.plantuml.svek.GraphvizImageBuilder.buildImage(GraphvizImageBuilder.java:225)
    at net.sourceforge.plantuml.svek.CucaDiagramFileMakerSvek.createFileInternal(CucaDiagramFileMakerSvek.java:104)
    at net.sourceforge.plantuml.svek.CucaDiagramFileMakerSvek.createFile(CucaDiagramFileMakerSvek.java:70)
    at net.atmp.CucaDiagram.exportDiagramInternal(CucaDiagram.java:489)
    at net.sourceforge.plantuml.classdiagram.ClassDiagram.exportDiagramInternal(ClassDiagram.java:85)
    at net.sourceforge.plantuml.UmlDiagram.exportDiagramNow(UmlDiagram.java:119)
    at net.sourceforge.plantuml.AbstractPSystem.exportDiagram(AbstractPSystem.java:216)
    at net.sourceforge.plantuml.SourceStringReader.outputImage(SourceStringReader.java:189)
    at net.sourceforge.plantuml.SourceStringReader.outputImage(SourceStringReader.java:147)
    at io.github.spencerpark.ijava.magics.JavaPlantUMLMagics.plantUML(JavaPlantUMLMagics.java:53)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
    at java.base/java.lang.reflect.Method.invoke(Method.java:565)
    at io.github.spencerpark.jupyter.kernel.magic.registry.Magics.invoke(Magics.java:89)
    at io.github.spencerpark.jupyter.kernel.magic.registry.Magics$CellReflectionMagicFunction.execute(Magics.java:164)
    at io.github.spencerpark.jupyter.kernel.magic.registry.Magics.applyCellMagic(Magics.java:36)
    at REPL.$JShell$59.do_it$($JShell$59.java:65)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
    at java.base/java.lang.reflect.Method.invoke(Method.java:565)
    at io.github.spencerpark.ijava.execution.IJavaExecutionControl.lambda$execute$0(IJavaExecutionControl.java:95)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:328)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1090)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:614)
    at java.base/java.lang.Thread.run(Thread.java:1474)
Caused by: java.io.IOException: Exec failed, error: 2 (No such file or directory) 
    at java.base/java.lang.ProcessImpl.forkAndExec(Native Method)
    at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:300)
    at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:231)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1078)
    ... 34 more
Figure 1: Un Customer a une Biography
No JDBC connection available. Set system properties 'jdbc.url' (and optionally 'jdbc.user'/'jdbc.password'), or provide a Connection in the kernel environment.
Figure 2

Pour cela JPA propose des annotations spécifiques :

@Embeddable: Cette annotation indique que les membres d’une classe Java peuvent être persistés en tant qu’attributs de la classe qui les utilise. En d’autres termes, elle spécifie qu’une classe peut être utilisée comme composant réutilisable dont les propriétés peuvent être incorporées dans une autre entité.

@Embedded: Utilisée au niveau d’un membre de classe annoté avec @Embeddable, cette annotation indique que le membre annoté doit être intégré dans la relation. Cela signifie que les propriétés de la classe annotée avec @Embeddable seront incluses dans la table de la classe qui les utilise.

Error: failed to read file /home/jovyan/work/examples/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_biography/Biography.java: /home/jovyan/work/examples/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_biography/Biography.java

Figure 3: Embeddable.java

Error: failed to read file /home/jovyan/work/examples/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_biography/Customer.java: /home/jovyan/work/examples/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_biography/Customer.java

Customer.java

On peut donc rendre persistente une instance de Customer associé à une instance de Biography.

Creation et persistence d’un Customer
import fr.univtln.bruno.demos.jpa.hello.samples.ex_biography.Customer;
try (EntityManager entityManager = emf.createEntityManager()) {
   entityManager.getTransaction().begin();

   Customer customer = Customer.of("Jim");
   customer.setBiography(Biography.builder()
      .brief("bla")
      .extended("bla bla")
      .build());
   entityManager.persist(customer);

   entityManager.getTransaction().commit();
}

dans une seule relation

No JDBC connection available. Set system properties 'jdbc.url' (and optionally 'jdbc.user'/'jdbc.password'), or provide a Connection in the kernel environment.
Figure 4

One to Many (1-N)

Figure 5: Une Order a plusieurs Line

Error: failed to read file /home/jovyan/work/examples/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_onetomany_b/Line.java: /home/jovyan/work/examples/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_onetomany_b/Line.java

Error: failed to read file /home/jovyan/work/examples/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_onetomany_b/Order.java: /home/jovyan/work/examples/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_onetomany_b/Order.java

No JDBC connection available. Set system properties 'jdbc.url' (and optionally 'jdbc.user'/'jdbc.password'), or provide a Connection in the kernel environment.
Figure 6

Avec deux entités

Dans le cas général, l’attribut de type Collection<T> est annoté avec @OneToMany.

L’attribut optionnel mappedBy indique le nom de l’attribut correspondant dans le type T si l’on souhaite une relation bi-directionnelle. L’autre entité (de Type T) est alors annotée avace @ManyToOne

Error: failed to read file /home/jovyan/work/examples/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_onetomany_a/Order.java: /home/jovyan/work/examples/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_onetomany_a/Order.java

Error: failed to read file /home/jovyan/work/examples/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_onetomany_a/Line.java: /home/jovyan/work/examples/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_onetomany_a/Line.java

14:52:39.922 [IJava-executor-0] INFO  notebook -- Order(id=1, date=2026-10-14T14:52:39.778850) [Line(id=2, product=Scissor, price=8.0), Line(id=3, product=Pen, price=1.0), Line(id=1, product=Paper, price=5.0)]
No JDBC connection available. Set system properties 'jdbc.url' (and optionally 'jdbc.user'/'jdbc.password'), or provide a Connection in the kernel environment.
Figure 7
No JDBC connection available. Set system properties 'jdbc.url' (and optionally 'jdbc.user'/'jdbc.password'), or provide a Connection in the kernel environment.
Figure 8

Many to Many (N-M)

L’annotation @ManyToMany en Java Persistence API (JPA) est utilisée pour modéliser une relation many-to-many entre deux entités. La table d’association sera alors générée et utilisée implicitement.

Figure 9: Un Customer a plusieurs adresses (qui peuvent être associées à d’autres)
No JDBC connection available. Set system properties 'jdbc.url' (and optionally 'jdbc.user'/'jdbc.password'), or provide a Connection in the kernel environment.
Figure 10

Error: failed to read file /home/jovyan/work/examples/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_manytomany/Customer.java: /home/jovyan/work/examples/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_manytomany/Customer.java

Error: failed to read file /home/jovyan/work/examples/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_manytomany/Address.java: /home/jovyan/work/examples/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_manytomany/Address.java

14:52:41.503 [IJava-executor-0] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=Pn6ALuII739t86uyr1YWDEcnwnjQ1yaGkj8fNd9d3Gg-1791989561.4476976-1.0.1.1-oLmWcI.4hDDCAV.NUkAI9ot.dntRWMAahFmxNy4hfn_yTi0BqR3.L90h82KGzIl5KlIkMID2UmZADfizpYyUZxXkmxeZC0KkbcrAWY_bAWQG5WB5uX3Rd2TbdvDwsBnk; HttpOnly; SameSite=None; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Wed, 14 Oct 2026 15:22:41 GMT". Invalid 'expires' attribute: Wed, 14 Oct 2026 15:22:41 GMT
14:52:41.718 [IJava-executor-0] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=TXYjH20EjhVA5W63LtzMtVwmY2z354k_B3kxoT.kJFw-1791989561.6173618-1.0.1.1-lEHe.FOjIjuKdh7gvew_Crw4noextsugR1vP0ostIUJMCrgjSJsAgtLQ8zUtawtcOsqNuyUqmvcgsde2zyoPQyCn1ZaZ_g0qeC3_8wUWmdV48yVuCtRUalHqsBP8TTRU; HttpOnly; SameSite=None; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Wed, 14 Oct 2026 15:22:41 GMT". Invalid 'expires' attribute: Wed, 14 Oct 2026 15:22:41 GMT
14:52:41.787 [IJava-executor-0] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=C9AMk3y.a_h31PgUeSmhih4YpLqzseJIOUFXAyTJi14-1791989561.7448535-1.0.1.1-qK.i10p19E3r7MbC3Z6gHsj2A1Wa4sxH2YdxYWLcqKVRUppeunhj2.MXe.TSY5TWtAxcL9gEWycsqTgslUEGObErCOplzQEpZtRX5isYzRsxak9w_SJT8Ep57KKzCOSS; HttpOnly; SameSite=None; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Wed, 14 Oct 2026 15:22:41 GMT". Invalid 'expires' attribute: Wed, 14 Oct 2026 15:22:41 GMT
14:52:41.848 [IJava-executor-0] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=4Gl8PVzddnHQ_aR8JctYux_sp69iKlxuR7Dwcu1tpL8-1791989561.8108501-1.0.1.1-Alsb9JYBu1A5VHckouAcjYh7fMVA2RjgyPqkTXEypFSgt47o2_AoJDjmLgfV9qtjB91AJT9Sz6wd1pu_PxCO2iQSH4VW6fvZ_b3R7O0G53SbJXGaTg6PysZMvoGo2LUT; HttpOnly; SameSite=None; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Wed, 14 Oct 2026 15:22:41 GMT". Invalid 'expires' attribute: Wed, 14 Oct 2026 15:22:41 GMT
14:52:41.912 [BasicRepositoryConnector-repo.maven.apache.org-0-0] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=pjDdEAjiN4PSV.S37u17O4xpGM9w8ArfOblXLZ3vW9Q-1791989561.8780048-1.0.1.1-93XfHnzw4zbzAqA8G5h8ca6WDm1zGYpvNKpiYsGdeDU0qQqrLrjfkRTXFuOwpv1Kj71UvuJzCunq3VXDaslJiHerQTRzpbhBL5sHpTwov9mX5Q9k2_EVGF4w74qMaNHs; HttpOnly; SameSite=None; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Wed, 14 Oct 2026 15:22:41 GMT". Invalid 'expires' attribute: Wed, 14 Oct 2026 15:22:41 GMT
14:52:41.957 [BasicRepositoryConnector-repo.maven.apache.org-0-1] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=808xAkgYHbHIfUZuSRM1qShP3PedlJHJrk8fHbfqoQk-1791989561.9274302-1.0.1.1-f7SORyUdzSqZGeNlWs.kU_SFqWO42RMaO5quTmJJ1_hhj6wah5ta2k9ViMDE3oiuM_DYM_5.kEYUw07gCvtfw30gB1A2YsvRoywb6_L6tYy2S2yGIVv8pu2xVKKfsoFN; HttpOnly; SameSite=None; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Wed, 14 Oct 2026 15:22:41 GMT". Invalid 'expires' attribute: Wed, 14 Oct 2026 15:22:41 GMT
14:52:41.976 [BasicRepositoryConnector-repo.maven.apache.org-0-3] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=mpw7U0ugLeQsWzmkY8A32HQbhBbWEwEtv84443QjunQ-1791989561.9305341-1.0.1.1-ov0xXQfwDD4Au20BKCIqR0tBF3Lm52em40He.ttFw6X1JHTZBqPSdgESUJTPZhoNarIpplm8CAq.E_HmyFy8BdBHMql4_PDl3oQiZHteEm06OcmvBt6U9hwP7YEUyK.j; HttpOnly; SameSite=None; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Wed, 14 Oct 2026 15:22:41 GMT". Invalid 'expires' attribute: Wed, 14 Oct 2026 15:22:41 GMT
14:52:41.976 [BasicRepositoryConnector-repo.maven.apache.org-0-2] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=iK98YaIC.FgyQHpfkzTeiLDyMQxYg9U3DoLuf_DDxho-1791989561.9440022-1.0.1.1-FwGhL8zyP46RnVCQc3SNy5zIdqvmyddaEaekyfCYNhGZDJBgdsHmDnin3A1TLs9eoPP6P1tLFMxdxhuMr4aZInhuBH3dVE0MLbE5rlXge51PDZrp_P6QJI.re01k56gG; HttpOnly; SameSite=None; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Wed, 14 Oct 2026 15:22:41 GMT". Invalid 'expires' attribute: Wed, 14 Oct 2026 15:22:41 GMT
No JDBC connection available. Set system properties 'jdbc.url' (and optionally 'jdbc.user'/'jdbc.password'), or provide a Connection in the kernel environment.
Figure 11
No JDBC connection available. Set system properties 'jdbc.url' (and optionally 'jdbc.user'/'jdbc.password'), or provide a Connection in the kernel environment.
Figure 12
No JDBC connection available. Set system properties 'jdbc.url' (and optionally 'jdbc.user'/'jdbc.password'), or provide a Connection in the kernel environment.
Figure 13

Réutilisation