Les associations entre entités avec JPA

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

Université de Toulon

LIS UMR CNRS 7020

2026-11-19

À propos de ce support

Transparence IA : support rédigé avec l'assistance d'un modèle de langage, relu et validé par l'auteur.

  • Contenu ebpro/notebook-java-jpa · engagement ab77bde, état courant de ce dépôt

  • Configuration partagée _quarto-utils à l'engagement e628793

  • Licence CC BY-NC 4.0 · aucune version stable publiée à ce jour

  • Politique de production

[postgres-ci] starting...
[postgres-ci] OK
[maven] starting...
[maven] OK
[diag] 1/5 classpath du kernel exposée
[diag] 2/5 imports slf4j/logback OK
[diag] 3/5 contexte logback OK
[diag] 4/5 40 jars ajoutés au classpath
[diag] Postgres driver registered OK
[diag] 5/5 imports JPA/DatabaseManager OK
21:13:19.055 [IJava-executor-0] INFO  f.u.b.d.jpa.hello.DatabaseManager -- Database settings: URL=jdbc:postgresql://dind/notebook-db, User=dba
21:13:19.059 [IJava-executor-0] INFO  f.u.b.d.jpa.hello.DatabaseManager -- Starting JPA with URL: jdbc:postgresql://dind/notebook-db and User: dba
21:13:20.248 [IJava-executor-0] INFO  com.zaxxer.hikari.HikariDataSource -- HikariPool-1 - Starting...
21:13:20.457 [IJava-executor-0] INFO  com.zaxxer.hikari.pool.HikariPool -- HikariPool-1 - Added connection org.postgresql.jdbc.PgConnection@2224a356
21:13:20.459 [IJava-executor-0] INFO  com.zaxxer.hikari.HikariDataSource -- HikariPool-1 - Start completed.
--> Connexion JPA réussie (Tentative 1) !
[diag] cell init terminée ✓

Types de relations

  • Prise en charge complète: gestion des relations entre entités de différents types.
  • Types de relations
    • One-to-One (Un-vers-Un)
    • One-to-Many (Un-vers-Plusieurs)
    • Many-to-Many (Plusieurs-vers-Plusieurs)
  • Unidirectionnelle ou bidirectionnelle.

One To One (1-1)

  • 1-1 en Java mais une seule relation
Figure 1: Un Customer a une Biography
Figure 2: L’unique relation CUSTOMER
  • Pour cela, JPA propose :
    • @Embeddable: Indique que les membres d’une classe peuvent être persistés en tant qu’attributs de la classe qui les utilise.
    • @Embedded: Utilisé avec @Embeddable pour intégrer ses propriétés dans une autre entité

Un client a une et une seule biographie

@Builder
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor

@Embeddable
public class Biography {
    @Column(name = "BIO_BRIEF")
    private String brief;

    @Lob
    @Column(name = "BIO_EXTENDED")
    private String extended;
}
Figure 3: Embeddable.java

Le client lié

@Getter
@Setter
@ToString
@RequiredArgsConstructor(staticName = "of")
@NoArgsConstructor(access = AccessLevel.PROTECTED)

@Entity
@Table(name = "CUSTOMER", schema = "ex_biography")
public class Customer {
    @Id
    @GeneratedValue
    private long id;

    @Column(length = 50, nullable = false)
    @NonNull
    private String name;

    @Embedded
    @Column()
    private Biography biography;
}

Customer.java

Persistence de l’association

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

id name bio_brief bio_extended
1 Jim bla 16776
Figure 4: La table CUSTOMER

One to Many (1-N)

Figure 5: Une Order a plusieurs Line
@Getter
@Setter
@ToString
@AllArgsConstructor(staticName = "of")
@NoArgsConstructor(access = AccessLevel.PROTECTED)

@Embeddable
@Table(name = "LINE", schema = "EX_ONE_TO_MANY_B")
public class Line {
    @NonNull
    private String product;

    private double price;
}
@Getter
@Setter
@ToString
@NoArgsConstructor
@Builder
@AllArgsConstructor

@Entity
@Table(name = "EORDER", schema = "EX_ONE_TO_MANY_B")
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long id;

    @Builder.Default
    @Column(nullable = false)
    private LocalDateTime date = LocalDateTime.now();

    @ElementCollection
    @CollectionTable(name = "LINE", schema = "EX_ONE_TO_MANY_B")
    @Singular
    private Set<Line> lines = new HashSet<>();

}
Figure 6: Les relations LINE et EORDER

Avec deux entités

  • Dans le cas général :
    • L’attribut de type Collection<T> est annoté avec @OneToMany.
    • Pour une relation bidirectionnelle, l’autre entité (de type T) est annotée avec @ManyToOne.
    • L’attribut optionnel mappedBy indique le nom de l’attribut correspondant dans le type T si l’on souhaite une relation bidirectionnelle.

1 to N à deux entités (1/3)

@Getter
@Setter
@ToString
@NoArgsConstructor

@Entity
@Table(name = "EORDER", schema = "EX_ONE_TO_MANY_A")
public class Order {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long id;

    private LocalDateTime date = LocalDateTime.now();

    @OneToMany(mappedBy = "order",
            cascade = {CascadeType.PERSIST,
                    CascadeType.REMOVE},
            orphanRemoval = true)
    @ToString.Exclude
    private Set<Line> lines = new HashSet<>();

    public Order addLine(Line line) {
        line.setOrder(this);
        lines.add(line);
        return this;
    }

    public Order removeLine(Line line) {
        line.setOrder(null);
        lines.remove(line);
        return this;
    }
}

1 to N à deux entités (2/3)

@Getter
@Setter
@ToString
@RequiredArgsConstructor(staticName = "of")
@NoArgsConstructor(access = AccessLevel.PROTECTED)

@Entity
@Table(name = "LINE", schema = "EX_ONE_TO_MANY_A")
public class Line {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long id;
    @NonNull
    private String product;

    @NonNull // just for requiredargsconstructor
    private double price;

    @ManyToOne
    @JoinColumn(nullable = false)
    @ToString.Exclude
    private Order order;

    public void setOrder(Order order) {
        if (this.order != null) {
            this.order.getLines().remove(this);
        }
        this.order = order;
        if (order != null) {
            order.getLines().add(this);
        }
    }
}

1 to N à deux entités (3/3)

21:13:26.710 [IJava-executor-0] INFO  notebook -- Order(id=1, date=2026-11-19T21:13:26.553864) [Line(id=3, product=Paper, price=5.0), Line(id=1, product=Pen, price=1.0), Line(id=2, product=Scissor, price=8.0)]

Figure 7: Les relations LINE et EORDER

order_id order_date line_id product price
1 2026-11-19 21:13:26.553864 1 Pen 1.0
1 2026-11-19 21:13:26.553864 2 Scissor 8.0
1 2026-11-19 21:13:26.553864 3 Paper 5.0
2 2026-11-19 21:13:26.564498 4 Moto 8000.0
2 2026-11-19 21:13:26.564498 5 Car 20000.0
Figure 8: SELECT * FROM EORDER INNER JOIN LINE

Many to Many (N-M)

  • @ManyToMany en Java Persistence API (JPA) :
    • Utilisée pour modéliser une relation many-to-many entre deux entités.
    • La table d’association est générée et utilisée implicitement.
Figure 9: Un Customer a plusieurs adresses (qui peuvent être associées à d’autres)
Figure 10: Les relation CUSTOMER, ADDRESS et la relation de d’association

Many to Many (1/2)

@Getter
@Setter
@ToString
@RequiredArgsConstructor(staticName = "of")
@NoArgsConstructor(access = AccessLevel.PROTECTED)

@Entity
@Table(name = "CUSTOMER", schema = "EX_MANY_TO_MANY")
public class Customer {
    @Id
    @GeneratedValue
    private long id;

    @NonNull
    private String name;

    @ManyToMany
    @ToString.Exclude
    @JoinTable(schema = "EX_MANY_TO_MANY")
    private Set<Address> places = new HashSet<>();

    public void addPlace(Address address) {
        this.places.add(address);
        address.getOccupants().add(this);
    }

    public void removePlace(Address address) {
        this.places.remove(address);
        address.getOccupants().remove(this);
    }
}
@Getter
@Setter
@ToString
@RequiredArgsConstructor(staticName = "of")
@NoArgsConstructor(access = AccessLevel.PROTECTED)

@Entity
@Table(name = "ADDRESS", schema = "EX_MANY_TO_MANY")
public class Address {
    @Id
    @GeneratedValue
    private long id;

    @NonNull
    private String addressDetail;

    @ManyToMany(mappedBy = "places")
    @ToString.Exclude
    private Set<Customer> occupants= new HashSet<>();

    public void addOccupant(Customer customer) {
        this.occupants.add(customer);
        customer.getPlaces().add(this);
    }

    public void removeOccupant(Customer customer) {
        this.occupants.remove(customer);
        customer.getPlaces().remove(this);
    }

}
21:13:32.095 [IJava-executor-0] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=Izwx49HcMIS6YS96bhfAXh2WyvdLaAjMYQ_TeMfEZF8-1795122812.06309-1.0.1.1-H1.uNdkfSq6zt_4aZ1oq5JAYwgqSOHcw86Zm307kJD2s2IKjLZNOGn80zg4PCgRmzoEERTQiz.nQZoHxa5zotcooDw70esacsfLBI05O0VEl3KoH16IKknJ2sJQo7cdi; HttpOnly; SameSite=None; Partitioned; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Thu, 19 Nov 2026 21:43:32 GMT". Invalid 'expires' attribute: Thu, 19 Nov 2026 21:43:32 GMT
21:13:32.886 [IJava-executor-0] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=CWONgcmeva4qBhbZh8JJKOiEpIf6a0v7C7te2sdd1RY-1795122812.8621154-1.0.1.1-YNj5fytZHBpPDpZ7LmtSSvV1hpugjSiGdoCZCclvLIvVc0FiSjfO1v8NrovrCFJf1kB.PtoP8ytJLHo7fzAuB2zAmpAXLWXH2c_QhaOQCcdEp6yialmJqDkcC.3Kr_74; HttpOnly; SameSite=None; Partitioned; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Thu, 19 Nov 2026 21:43:32 GMT". Invalid 'expires' attribute: Thu, 19 Nov 2026 21:43:32 GMT
21:13:32.947 [IJava-executor-0] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=bOeGuunLnaXwelzs9jRPISUheqHdC9nI62LnKMEmepM-1795122812.9275243-1.0.1.1-Yk.NKSc1f2NiR4rAHv4yrIxMvZ4s2xPylussTjcfwQrTsGoTEwDCOoUZe6C15ktgzYUgnC8bmEK1n671BeUGEtWoZgZZlwiELS26GhZC_FWTz6ON9fex09eQPEQx4BTQ; HttpOnly; SameSite=None; Partitioned; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Thu, 19 Nov 2026 21:43:32 GMT". Invalid 'expires' attribute: Thu, 19 Nov 2026 21:43:32 GMT
21:13:32.984 [IJava-executor-0] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=M.6__WQJjFzesXxTJWaGH7qdPwxwghnkif1.jh94eWk-1795122812.9665504-1.0.1.1-jstybatMMAIwCPwDr0y4_505krLNBvS_SxYzppzh.w80VU2TpUWQYos8JpCO9Ly62T_IaRZYDtFMv3.oTaNdz4Dd93G9cUNBMbXGAMco6GVuf2jY.nNJd8FD8.n0dPkC; HttpOnly; SameSite=None; Partitioned; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Thu, 19 Nov 2026 21:43:32 GMT". Invalid 'expires' attribute: Thu, 19 Nov 2026 21:43:32 GMT
21:13:33.027 [BasicRepositoryConnector-repo.maven.apache.org-0-1] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=cdKLXEr.6CpCT1Jz.Z_HmKfnUtr7RjwveByBWyx7.l4-1795122813.0061355-1.0.1.1-Fa5LmRxgcIzZFguby_WlU.XsAtwM0.uPwFNsQxFp3JzIIh4UPnvSVnN6cK04.fhGmJI0INQ8RLZ2NsVWX1Ty1W2p9PDQ6lSuxQyAn5aCAwJYLiXYsvypv1_PP6PmqziH; HttpOnly; SameSite=None; Partitioned; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Thu, 19 Nov 2026 21:43:33 GMT". Invalid 'expires' attribute: Thu, 19 Nov 2026 21:43:33 GMT
21:13:36.461 [BasicRepositoryConnector-repo.maven.apache.org-0-2] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=WDUXGQmvb.xYE7k56k58TzY7ji0n7MsYs.9hrgLeUM8-1795122813.0565464-1.0.1.1-R.89ZCQpw3ra8mEjjR7eKzjjstfiTWKVxYqOiPSszVWOvNkdQP3IjR9loYpEFAVkDbwT3oGSgQ_4nhrtDJzwOvJL2nJLUmY5BprQ74xa4Bxl0RPwwU5R8pYGnxBypWTV; HttpOnly; SameSite=None; Partitioned; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Thu, 19 Nov 2026 21:43:33 GMT". Invalid 'expires' attribute: Thu, 19 Nov 2026 21:43:33 GMT
21:13:36.461 [BasicRepositoryConnector-repo.maven.apache.org-0-0] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=simQFWwexUYJ9xeMmtupvdKBmWg501L_fuXnuMD8g9I-1795122813.058096-1.0.1.1-XcVIQpOq9W8WQ4NvFSYpTDJ_c58D5cs7ViQqXv80OZH5R3I4CVGvwxmGHRtMB9.qOKlkvQcxbxMfEXwLU02.zrpPo09BZmN5HNMK5D.Ut25PUMbDaLALh7WlJ0goKyQp; HttpOnly; SameSite=None; Partitioned; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Thu, 19 Nov 2026 21:43:33 GMT". Invalid 'expires' attribute: Thu, 19 Nov 2026 21:43:33 GMT
21:13:36.467 [BasicRepositoryConnector-repo.maven.apache.org-0-3] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=lgoh5XZyYK47y1V3gs0ACTGm6QeMfQ40hFMaCZkdhSk-1795122816.4475715-1.0.1.1-g4HdqrI3KJejAvqnaingecviuZE5YxPUceJmDCNidNzTHZC2H.5wuAcTKZeoNwqtFip8.xMEKuzhDiWnkbCBbAiVLrXivHjGUrSjUVgdBiTtoIyecDbTbc.dRHslFXzB; HttpOnly; SameSite=None; Partitioned; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Thu, 19 Nov 2026 21:43:36 GMT". Invalid 'expires' attribute: Thu, 19 Nov 2026 21:43:36 GMT

Many to Many (2/2)

id name
2 Chase Hegmann III
3 Lavada Effertz
4 Jacques Bauch
5 Indira Champlin
6 Delmar Boyer
Figure 11: La table CUSTOMER
occupants_id places_id
2 1
3 1
4 1
5 1
6 1
5 2
Figure 12: La table de jointure
id addressdetail
1 222 Lindgren Burg, Maireview, VT 49855
2 Suite 568 881 Hegmann Views, West Anastaciahaven, OH 61465
Figure 13: La table ADDRESS

Politique de production

Cette page dit comment ce support est produit. Son existence dans la configuration partagée est la condition d’émission du cartouche « À propos de ce support », et son texte est publié en fin de chaque leçon.

Transparence

Le support est rédigé avec l’assistance d’un modèle de langage, relu et validé par l’auteur.

Traçabilité

Chaque leçon indique en fin de document le dépôt source, la branche ou la version qui a produit la page, le commit de la leçon et l’engagement (commit) de la configuration partagée _quarto-utils. Les références sont des liens cliquables ; une information inconnue au rendu est masquée, jamais inventée.

Dates et erreurs

Aucune date d’enseignement n’est publiée sans saisie de l’auteur. Une démonstration qui échoue se voit ; une démonstration impossible fait rougir la publication plutôt que de publier une page muette.

Auteur : Emmanuel Bruno — Université de Toulon. Licence : CC BY-NC 4.0.