-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path02_java_jpa_L_associations.qmd
More file actions
627 lines (494 loc) · 17 KB
/
Copy path02_java_jpa_L_associations.qmd
File metadata and controls
627 lines (494 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
---
title: Les associations entre entités avec JPA
subtitle: Contrôles des relations entre entités avec JPA.
description: Apprenez à gérer les associations entre entités en utilisant Jakarta Persistence API (JPA) avec des exemples pratiques en Java.
image: _quarto-utils/MyMedia/images/optimized/taiki-ishikawa-PUXFKuVf_84-unsplash_java-400.webp
jupyter: java
tools:
- docker
- java
- maven
programs:
- M1-InfoMath [DEV-ADV]
- CNAM-I [PO43]
categories:
- Lecture
- Containers
- Java
- JPA
- Persistence
- ORM
provide_notes: true
provide_slides: true
execute:
echo: false
output: true
---
{{< include ./_init.qmd >}}
::: {.content-visible when-profile="notes"}
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.
:::
::: {.content-visible when-profile="slides"}
## 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)
::: {.content-visible when-profile="notes"}
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.
:::
::: {.content-visible when-profile="slides"}
- 1-1 en Java mais une seule relation
:::
:::: {.columns}
::: {.column width="50%"}
```{java}
//| output: true
//| echo: false
//| label: fig-uml-onetoone
//| fig-cap: Un Customer a une Biography
//| vscode: {languageId: java}
// PRINT SCHEMA
String script="""
@startuml
class Biography {
- brief: String
- extended: String
}
class Customer {
- id: long
- name: String
}
Customer "1" *-right- "1" Biography
@enduml""";
IJava.getKernelInstance().getMagics().applyCellMagic("plantUML",List.of(),script);
return null;
```
:::
::: {.column width="50%"}
```{java}
//| output: true
//| echo: false
//| label: fig-rel-onetoone
//| fig-cap: L'unique relation CUSTOMER
//| vscode: {languageId: java}
// PRINT SCHEMA
String script="%";
IJava.getKernelInstance().getMagics().applyCellMagic("rdbmsSchema",
List.of("ex_biography"),script);
return null;
```
:::
::::
::: {.content-visible when-profile="notes"}
Pour cela JPA propose des annotations spécifiques :
[\@Embeddable](https://jakarta.ee/specifications/persistence/3.1/apidocs/jakarta.persistence/jakarta/persistence/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](https://jakarta.ee/specifications/persistence/3.1/apidocs/jakarta.persistence/jakarta/persistence/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.
:::
::: {.content-visible when-profile="slides"}
- Pour cela, JPA propose :
- [\@Embeddable](https://jakarta.ee/specifications/persistence/3.1/apidocs/jakarta.persistence/jakarta/persistence/embeddable): Indique que les membres d'une classe peuvent être persistés en tant qu'attributs de la classe qui les utilise.
- [\@Embedded](https://jakarta.ee/specifications/persistence/3.1/apidocs/jakarta.persistence/jakarta/persistence/embedded): Utilisé avec `@Embeddable` pour intégrer ses propriétés dans une autre entité
:::
::: {.content-visible when-profile="slides"}
## Un client a une et une seule biographie {.smaller}
:::
:::: {.columns}
::: {.column width="50%"}
```{java}
//| output: true
//| echo: false
//| label: fig-class-embeddable
//| filename: null
//| fig-cap: Embeddable.java
//| fig-link: /code-server/?folder=/home/jovyan/work/src/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_biography/Biography.java
//| vscode: {languageId: java}
// PRINT CLASS
String script="/home/jovyan/work/src/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_biography/Biography.java";
IJava.getKernelInstance().getMagics().applyCellMagic("javasrcClassByName",List.of("Biography"),script);
return null;
```
:::
::: {.column width="50%"}
```{java}
//| output: true
//| echo: false
//| jupyter: {source_hidden: true}
//| vscode: {languageId: java}
//| fig-cap: Customer.java
// PRINT CLASS
String script="/home/jovyan/work/src/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_biography/Customer.java";
IJava.getKernelInstance().getMagics().applyCellMagic("javasrcClassByName",List.of("Customer"),script);
return null;
```
:::
::::
```{java}
//| output: false
//| echo: false
//| vscode: {languageId: java}
import fr.univtln.bruno.demos.jpa.hello.samples.ex_biography.*;
EntityManagerFactory emf = DatabaseManager.getEntityManagerFactory();
```
::: {.content-visible when-profile="notes"}
On peut donc rendre persistente une instance de `Customer` associé à une instance de `Biography`.
:::
::: {.content-visible when-profile="slides"}
## Persistence de l'association
:::
```{java}
//| output: true
//| echo: true
//| code-fold: true
//| code-summary: Creation et persistence d'un Customer
//| tags: []
//| vscode: {languageId: java}
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
```{java}
//| output: true
//| echo: false
//| label: fig-table-onetoone
//| fig-cap: La table CUSTOMER
//| vscode: {languageId: java}
// PRINT RELATION
String script="SELECT * FROM ex_biography.CUSTOMER";
IJava.getKernelInstance().getMagics().applyCellMagic("sqlAsTable",List.of(),script);
return null;
```
## One to Many (1-N)
```{java}
//| output: true
//| echo: false
//| label: fig-uml-onetomany
//| fig-cap: Une Order a plusieurs Line
//| vscode: {languageId: java}
// PRINT SCHEMA
String script="""
@startuml
class Order {
- id: long
- date: LocalDateTime
}
class Line {
- id: long
- product: String
- price: double
}er "1" *-r- "1..*" Line :" "
@enduml""";
IJava.getKernelInstance().getMagics().applyCellMagic("plantUML",List.of(),script);
return null;
```
:::: {.columns}
::: {.column width="50%"}
```{java}
//| output: true
//| echo: false
//| vscode: {languageId: java}
// PRINT CLASS
String script="/home/jovyan/work/src/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_onetomany_b/Line.java";
IJava.getKernelInstance().getMagics().applyCellMagic("javasrcClassByName",List.of("Line"),script);
return null;
```
:::
::: {.column width="50%"}
```{java}
//| output: true
//| echo: false
//| vscode: {languageId: java}
// PRINT CLASS
String script="/home/jovyan/work/src/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_onetomany_b/Order.java";
IJava.getKernelInstance().getMagics().applyCellMagic("javasrcClassByName",List.of("Order"),script);
return null;
```
:::
::::
```{java}
//| output: true
//| echo: false
//| label: fig-rel-onetomanyb
//| fig-cap: Les relations LINE et EORDER
//| tags: [remove-input]
//| vscode: {languageId: java}
// PRINT SCHEMA
String script="%";
IJava.getKernelInstance().getMagics().applyCellMagic("rdbmsSchema",
List.of("ex_one_to_many_b"),script);
return null;
```
::: {.content-visible when-profile="notes"}
### 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`
:::
::: {.content-visible when-profile="slides"}
## 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.
:::
::: {.content-visible when-profile="slides"}
## 1 to N à deux entités (1/3)
:::
```{java}
//| output: true
//| echo: false
//| vscode: {languageId: java}
// PRINT CLASS
String script="/home/jovyan/work/src/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_onetomany_a/Order.java";
IJava.getKernelInstance().getMagics().applyCellMagic("javasrcClassByName",List.of("Order"),script);
return null;
```
::: {.content-visible when-profile="slides"}
## 1 to N à deux entités (2/3)
:::
```{java}
//| output: true
//| echo: false
//| vscode: {languageId: java}
// PRINT CLASS
String script="/home/jovyan/work/src/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_onetomany_a/Line.java";
IJava.getKernelInstance().getMagics().applyCellMagic("javasrcClassByName",List.of("Line"),script);
return null;
```
::: {.content-visible when-profile="slides"}
## 1 to N à deux entités (3/3)
:::
```{java}
//| output: false
//| echo: false
//| tags: []
//| vscode: {languageId: java}
import fr.univtln.bruno.demos.jpa.hello.samples.ex_associations.ex_onetomany_a.*;
EntityManagerFactory emf = DatabaseManager.getEntityManagerFactory();
final Logger log = LoggerFactory.getLogger("notebook");
```
```{java}
//| code-fold: true
//| code-summary: Creation et persistence d'une commande et de ses lignes.
//| tags: []
//| vscode: {languageId: java}
Order order1 = new Order()
.addLine(Line.of("Pen", 1.0))
.addLine(Line.of("Paper", 5.0))
.addLine(Line.of("Scissor", 8.0));
Order order2 = new Order()
.addLine(Line.of("Car", 20000))
.addLine(Line.of("Moto", 8000));
try (EntityManager entityManager = emf.createEntityManager()) {
entityManager.getTransaction().begin();
entityManager.persist(order1);
entityManager.persist(order2);
entityManager.getTransaction().commit();
}
try (EntityManager entityManager = emf.createEntityManager()) {
Order order=entityManager.find(Order.class, 1L);
log.info("{} {}",order, order.getLines());
}
```
```{java}
//| output: true
//| echo: false
//| label: fig-rel-onetomanya
//| fig-cap: Les relations LINE et EORDER
//| tags: [remove-input]
//| vscode: {languageId: java}
// PRINT SCHEMA
String script="%";
IJava.getKernelInstance().getMagics().applyCellMagic("rdbmsSchema",
List.of("ex_one_to_many_a"),script);
return null;
```
```{java}
//| output: true
//| echo: false
//| label: fig-rel-onetomanya-query
//| fig-cap: SELECT * FROM EORDER INNER JOIN LINE
//| vscode: {languageId: java}
// PRINT RELATION
String script="""
SELECT EORDER.id AS order_id,
EORDER.date AS order_date,
LINE.id AS line_id,
LINE.product,
LINE.price
FROM EX_ONE_TO_MANY_A.EORDER AS EORDER
INNER JOIN EX_ONE_TO_MANY_A.LINE AS LINE
ON EORDER.id = LINE.order_id
ORDER BY EORDER.id,LINE.id""";
IJava.getKernelInstance().getMagics().applyCellMagic("sqlAsTable",
List.of(),script);
return null;
```
## Many to Many (N-M)
::: {.content-visible when-profile="notes"}
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.
:::
::: {.content-visible when-profile="slides"}
- \@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.
:::
```{java}
//| output: true
//| echo: false
//| label: fig-uml-manytomany
//| fig-cap: Un Customer a plusieurs adresses (qui peuvent être associées à d'autres)
//| vscode: {languageId: java}
// PRINT SCHEMA
String script="""
@startuml
class Customer {
- id: long
- name: String
}
class Address {
- id: long
- adress: String
}
Customer "*" -right- "*" Address :" "
@enduml""";
IJava.getKernelInstance().getMagics().applyCellMagic("plantUML",List.of(),script);
return null;
```
```{java}
//| output: true
//| echo: false
//| label: fig-rel-manytomany
//| fig-cap: Les relation CUSTOMER, ADDRESS et la relation de d'association
//| tags: [remove-input]
//| vscode: {languageId: java}
// PRINT SCHEMA
String script="%";
IJava.getKernelInstance().getMagics().applyCellMagic("rdbmsSchema",
List.of("ex_many_to_many"),script);
return null;
```
::: {.content-visible when-profile="slides"}
## Many to Many (1/2)
:::
:::: {.columns}
::: {.column width="50%"}
```{java}
//| output: true
//| echo: false
//| vscode: {languageId: java}
// PRINT CLASS
String script="/home/jovyan/work/src/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_manytomany/Customer.java";
IJava.getKernelInstance().getMagics().applyCellMagic("javasrcClassByName",List.of("Customer"),script);
return null;
```
:::
::: {.column width="50%"}
```{java}
//| output: true
//| echo: false
//| jupyter: {source_hidden: true}
//| vscode: {languageId: java}
// PRINT CLASS
String script="/home/jovyan/work/src/github/ebpro/sample-hellojpa/src/main/java/fr/univtln/bruno/demos/jpa/hello/samples/ex_associations/ex_manytomany/Address.java";
IJava.getKernelInstance().getMagics().applyCellMagic("javasrcClassByName",List.of("Address"),script);
return null;
```
:::
::::
```{java}
//| vscode: {languageId: java}
%maven net.datafaker:datafaker:2.0.2
import net.datafaker.Faker;
import java.util.stream.Stream;
import fr.univtln.bruno.demos.jpa.hello.samples.ex_associations.ex_manytomany.Address;
import fr.univtln.bruno.demos.jpa.hello.samples.ex_associations.ex_manytomany.Customer;
```
::: {.content-visible when-profile="slides"}
## Many to Many (2/2)
:::
```{java}
//| code-fold: true
//| code-summary: Creation et persistence de Customers et d'Addresses.
//| vscode: {languageId: java}
Faker faker = new Faker();
int nbAddresses = 2;
int nbCustomers = 5;
try (EntityManager entityManager = emf.createEntityManager()) {
entityManager.getTransaction().begin();
Stream.generate(faker.address()::fullAddress)
.map(Address::of)
.limit(nbAddresses)
.forEach(entityManager::persist);
TypedQuery<Address> query = entityManager.createQuery("""
SELECT a
FROM Address a
ORDER BY random()""", Address.class);
Stream.generate(faker.name()::fullName)
.map(Customer::of)
.limit(nbCustomers)
.forEach(c -> query.setMaxResults(ThreadLocalRandom.current().nextInt(2) + 1)
.getResultList()
.stream()
.map(a -> {
c.getPlaces().add(a);
return c;
})
.forEach(entityManager::persist));
entityManager.getTransaction().commit();
}
```
:::: {.columns}
::: {.column width="50%"}
```{java}
//| output: true
//| echo: false
//| label: fig-table-onetoone1
//| fig-cap: La table CUSTOMER
//| vscode: {languageId: java}
// PRINT RELATION
String script="SELECT * FROM EX_MANY_TO_MANY.CUSTOMER";
IJava.getKernelInstance().getMagics().applyCellMagic("sqlAsTable",
List.of(),script);
return null;
```
:::
::: {.column width="50%"}
```{java}
//| output: true
//| echo: false
//| label: fig-table-onetoone-3
//| fig-cap: La table de jointure
//| vscode: {languageId: java}
// PRINT RELATION
String script="SELECT * FROM EX_MANY_TO_MANY.CUSTOMER_ADDRESS ORDER BY places_id, occupants_id";
IJava.getKernelInstance().getMagics().applyCellMagic("sqlAsTable",
List.of(),script);
return null;
```
:::
::::
```{java}
//| output: true
//| echo: false
//| label: fig-table-onetoone-2
//| fig-cap: La table ADDRESS
//| vscode: {languageId: java}
// PRINT RELATION
String script="SELECT * FROM EX_MANY_TO_MANY.ADDRESS";
IJava.getKernelInstance().getMagics().applyCellMagic("sqlAsTable",
List.of(),script);
return null;
```