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-18

[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
19:09:31.064 [IJava-executor-0] INFO  f.u.b.d.jpa.hello.DatabaseManager -- Database settings: URL=jdbc:postgresql://dind/notebook-db, User=dba
19:09:31.071 [IJava-executor-0] INFO  f.u.b.d.jpa.hello.DatabaseManager -- Starting JPA with URL: jdbc:postgresql://dind/notebook-db and User: dba
19:09:32.146 [IJava-executor-0] INFO  com.zaxxer.hikari.HikariDataSource -- HikariPool-1 - Starting...
19:09:32.380 [IJava-executor-0] INFO  com.zaxxer.hikari.pool.HikariPool -- HikariPool-1 - Added connection org.postgresql.jdbc.PgConnection@2224a356
19:09:32.382 [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
@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)

19:09:38.478 [IJava-executor-0] INFO  notebook -- Order(id=1, date=2026-11-18T19:09:38.335414) [Line(id=2, product=Pen, price=1.0), Line(id=3, product=Scissor, price=8.0), Line(id=1, product=Paper, price=5.0)]

Figure 7: Les relations LINE et EORDER

order_id order_date line_id product price
1 2026-11-18 19:09:38.335414 1 Paper 5.0
1 2026-11-18 19:09:38.335414 2 Pen 1.0
1 2026-11-18 19:09:38.335414 3 Scissor 8.0
2 2026-11-18 19:09:38.345858 4 Moto 8000.0
2 2026-11-18 19:09:38.345858 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);
    }

}
19:09:43.825 [IJava-executor-0] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=VRcPl2j2X18G59xniAawSsdZdKxFH4OLVZjXVDb3KPY-1795028983.790381-1.0.1.1-K7ua3kQWl1oa11MXkwKMok8mFJYyHee4eF3Z8qfgqK3CgwufmJUpHK4ceMbTKNRssvRoCGX5A7Ztm.ztWX0gRwI0WtNR5Ys9b0GiF7C8mbarBR5esGRFkxFYuqGgKmXq; HttpOnly; SameSite=None; Partitioned; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Wed, 18 Nov 2026 19:39:43 GMT". Invalid 'expires' attribute: Wed, 18 Nov 2026 19:39:43 GMT
19:09:43.935 [IJava-executor-0] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=QW2wsMaerWujm8He8vv.FhACRMfNXYbkfe2tG7TG4vE-1795028983.9119542-1.0.1.1-jSF6W.VvfubTQ4rZ8BrmRZT6wpy5ipfTUJcFgkmw23sEAxG2GLovlCY6W81uS6gxbHQYqTDFBMjWejR9aZpnoaUDc8PZ0GWDsfy1AKUlklaRxr29IY_T4H9VH3qzadsk; HttpOnly; SameSite=None; Partitioned; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Wed, 18 Nov 2026 19:39:43 GMT". Invalid 'expires' attribute: Wed, 18 Nov 2026 19:39:43 GMT
19:09:43.979 [IJava-executor-0] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=bqaSJ1DwO.jNcZskdVl2Bqh6B.D.y7nCXvVZLdNP6S8-1795028983.955404-1.0.1.1-dN15WSDQhBKx6KJ3KFouAWUnnbnAEgTGiOjNeymfH.tTidUZqpNtBhIz8Ju2L_roEyFbRNnrmjThyytPzBjOLMOSQRi7RGlrC5EbKO8vd8dX7S1v0qT6Lvn3_yJYGKOU; HttpOnly; SameSite=None; Partitioned; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Wed, 18 Nov 2026 19:39:43 GMT". Invalid 'expires' attribute: Wed, 18 Nov 2026 19:39:43 GMT
19:09:44.036 [IJava-executor-0] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=Hy7u_PQJiv2reCp9rSlwhliY4v1dI0K2SRD2dncYWes-1795028984.0164185-1.0.1.1-xXs0Js6wYVxUbrDfHi5uHbiql9cD7okwqIcdmfUGORjTU4lOu4AAvrgugf0IMmDbhfhGyomRNdZJzrP4smqVHeh1ETU09SrpVowkFq1wBgjsBGExoQzV78J0_y3cD5ZD; HttpOnly; SameSite=None; Partitioned; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Wed, 18 Nov 2026 19:39:44 GMT". Invalid 'expires' attribute: Wed, 18 Nov 2026 19:39:44 GMT
19:09:44.081 [BasicRepositoryConnector-repo.maven.apache.org-0-1] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=YMvZdCWOHTufpSkVVDqQZR9DHX.HAFnLMYfBHtyknoA-1795028984.0596623-1.0.1.1-dyunDvO4wyTZ6oCDi6o5wxrzasDdCgfSb6GvcXtJ5i9Iop5akYIJJcrdkDHzkIypUFKJlrCf2VdrESrunl2YVqEJzZ8C8arlLBxf7rUhy.59SY1YjguLVOkBiMBLA9po; HttpOnly; SameSite=None; Partitioned; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Wed, 18 Nov 2026 19:39:44 GMT". Invalid 'expires' attribute: Wed, 18 Nov 2026 19:39:44 GMT
19:09:47.507 [BasicRepositoryConnector-repo.maven.apache.org-0-0] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=i3PX8HO9pRLNXk8vGIgR.4IKyMSeBdgL8NvdSAkQhBk-1795028984.1054842-1.0.1.1-VeVJwhblspV7K4yYJr1Yr0G9kVr2D5GuS3l60_Qr0o5QJD9iKuOBbqb4pRjkb7Vol7v3vw7wTngLGL38WdbAXiqZxn.mNn3ohGjlsFy.OSRhgQPf6rOAdVwld_X.4Q7a; HttpOnly; SameSite=None; Partitioned; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Wed, 18 Nov 2026 19:39:44 GMT". Invalid 'expires' attribute: Wed, 18 Nov 2026 19:39:44 GMT
19:09:47.511 [BasicRepositoryConnector-repo.maven.apache.org-0-2] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=Px9L2W0yWRXPifC2O_wFe4gBN8xozTNFEjv0dHa6qIg-1795028987.4872022-1.0.1.1-Evavrv_SM6MTNFO7RzyEGF35uhTmriydLTbO4SnwXr_ubZXkaJiX8x97OjeTFvKNeWzuXWYuCQPB5Nady424N1xWqd9Lqc7NTz1Qz2rIOowldfRc1qzpNDqi3gbtnuXj; HttpOnly; SameSite=None; Partitioned; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Wed, 18 Nov 2026 19:39:47 GMT". Invalid 'expires' attribute: Wed, 18 Nov 2026 19:39:47 GMT
19:09:47.561 [BasicRepositoryConnector-repo.maven.apache.org-0-3] WARN  o.a.h.c.p.ResponseProcessCookies -- Invalid cookie header: "set-cookie: __cf_bm=wdSC9QO03h4Ha.A3dHYmcRdR_PnWndNEL5p.2n_R7tc-1795028984.1106126-1.0.1.1-aTZYTI7FWPuDaEuSlxyOhU5CMoSitLuB3NM4lo3rsU899TrK5yBDl_LU7wmNgnTcORVso4GfmRIee3NW2s2Ff1QZ.CIcK_iYkBVOybQFlijD8QW3j_UZRFuMqgrhiVDP; HttpOnly; SameSite=None; Partitioned; Secure; Path=/; Domain=repo.maven.apache.org; Expires=Wed, 18 Nov 2026 19:39:44 GMT". Invalid 'expires' attribute: Wed, 18 Nov 2026 19:39:44 GMT

Many to Many (2/2)

id name
2 Latoya Marks
3 Miss Blossom Metz
4 Carolynn Miller
5 Miss Frederic Huels
6 Lou Rowe
Figure 11: La table CUSTOMER
occupants_id places_id
2 1
3 1
4 1
5 1
6 1
2 2
5 2
Figure 12: La table de jointure
id addressdetail
1 Suite 138 244 Eleanore Streets, Lake Kimberg, ME 07224
2 3187 Lueilwitz Freeway, North Damianbury, MA 23246
Figure 13: La table ADDRESS