-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path04_java_jpa_L_ids.qmd
More file actions
403 lines (321 loc) · 12.3 KB
/
Copy path04_java_jpa_L_ids.qmd
File metadata and controls
403 lines (321 loc) · 12.3 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
---
title: Les clés primaires avec JPA
description: contrôle fin des identifiants JPA.
categories:
- Java
- I211
- Lecture
- JPA
provide_notes: true
provide_slides: true
jupyter: java
---
{{< include ./_init.qmd >}}
## Concepts fondamentaux
- Clé primaire
- sous-ensemble minimal K d'attributs A = {a₁, a₂, ..., aₙ} d'une relation R qui satisfait simultanément :
1. l'unicité, qui garantit que pour tous tuples t₁, t₂ ∈ R, si t₁ ≠ t₂ alors leurs projections sur K sont différentes (t₁[K] ≠ t₂[K]),
2. la minimalité, qui assure qu'aucun sous-ensemble propre K' ⊂ K ne peut satisfaire la propriété d'unicité,
3. la non-nullité, qui impose que pour tout tuple t ∈ R et tout attribut k ∈ K, la valeur t[k] ne peut pas être nulle (t[k] ≠ null),
- Types supportés: primitifs (`int`, `long`, ...), wrappers (`Integer`, `Long`, ...), `String`, Date (`Date`, `LocalDate`, ...), `UUID`
- Annotation `@Id` sur l'attribut de l'entité
## Génération automatique des Id atomiques
::: {.content-visible when-profile="slides"}
- Annotation `@GeneratedValue`
- Stratégies disponibles
- IDENTITY: auto-increment natif
- SEQUENCE: séquence BD
- TABLE: table de séquences
- AUTO: choix automatique
:::
::: {.content-visible when-profile="notes"}
En théorie des bases de données relationnelles, une clé primaire est définie comme un sous-ensemble minimal K d'attributs A = {a₁, a₂, ..., aₙ} d'une relation R qui satisfait simultanément trois propriétés fondamentales : (1) l'unicité, qui garantit que pour tous tuples t₁, t₂ ∈ R, si t₁ ≠ t₂ alors leurs projections sur K sont différentes (t₁[K] ≠ t₂[K]), (2) la minimalité, qui assure qu'aucun sous-ensemble propre K' ⊂ K ne peut satisfaire la propriété d'unicité, et (3) la non-nullité, qui impose que pour tout tuple t ∈ R et tout attribut k ∈ K, la valeur t[k] ne peut pas être nulle (t[k] ≠ null), ces propriétés garantissant ainsi l'intégrité des entités et l'identification unique des tuples dans la base de données.
La génération automatique des identifiants est une fonctionnalité essentielle de JPA, permettant de déléguer la création des valeurs d'identifiants au framework.
Plusieurs stratégie de génération sont disponibles, chacune adaptée à un contexte particulier.
1. **IDENTITY**
- Utilise l'auto-increment natif de la base
- Optimal pour MySQL/MariaDB
- Pas de batch possible
2. **SEQUENCE**
- Utilise une séquence en base
- Performant avec allocationSize > 1
- Standard pour PostgreSQL/Oracle
3. **TABLE**
- Utilise une table dédiée
- Portable mais moins performant
- Solution de dernier recours
4. **AUTO**
- Choix automatique selon la base
- IDENTITY pour MySQL
- SEQUENCE pour PostgreSQL
5. **UUID**
- Utilise un UUID
- Portable et unique
:::
### Tableau comparatif
| Stratégie | Performance | Portabilité | Batch | Scalabilité | Usage recommandé |
|-----------|-------------|-------------|-------|-------------|------------------|
| IDENTITY | +++ | + | Non | + | MySQL/MariaDB |
| SEQUENCE | ++ | ++ | Oui | ++ | PostgreSQL/Oracle|
| TABLE | + | +++ | Oui | +++ | Multi-bases |
| AUTO | ++ | ++ | Selon | ++ | Développement |
| UUID | + | +++ | Non | ++++ | Systèmes distribués|
Notes sur la scalabilité:
- IDENTITY: problématique en sharding
- SEQUENCE: possible avec sequences par shard
- TABLE: adapté au clustering
- UUID: optimal pour systèmes distribués
### Les générateurs SEQUENCE et IDENTITY
* Les générateurs SEQUENCE et IDENTITY spécifient l'utilisation d'une séquence de base de données ou d'une colonne d'identité (plus performant, mais pas portable). [](https://jakarta.ee/specifications/persistence/3.1/jakarta-persistence-spec-3.1#a16164).
:::: {.columns}
::: {.column}
```{java}
//| output: true
//| echo: false
//| label: fig-class-employee-seqid-PK
//| fig-cap: EmployeePK.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_ids/ex_seqid/Customer.java";
IJava.getKernelInstance().getMagics().applyCellMagic("javasrcClassByName",List.of("Customer"),script);
return null;
```
:::
::: {.column}
```{java}
//| output: true
//| echo: false
//| label: fig-rel-employe-seqid-PK
//| fig-cap: An Employee with a composite Key/Id
//| vscode: {languageId: java}
// PRINT SCHEMA
String script="%";
IJava.getKernelInstance().getMagics().applyCellMagic("rdbmsSchema",
List.of("ex_idseq"),script);
return null;
```
:::
::::
### Sequence et Batch
La génération de clés avec une séquence peut être optimisée en utilisant un `allocationSize` plus grand que 1.
Cela permet de pré-allouer un bloc de valeurs pour les entités, réduisant ainsi le nombre d'appels à la séquence.
```java
// Exemple de configuration optimisée
@Entity
public class Order {
@Id
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "order_seq"
)
@SequenceGenerator(
name = "order_seq",
sequenceName = "ORDER_SEQ",
initialValue = 1,
allocationSize = 50 // Optimisation batch
)
private Long id;
}
```
### générateur TABLE
Le générateur TABLE demande d'attribuer des clés primaires à l'entité en utilisant une table de base de données, c'est le plus portable mais le moins performant.
:::: {.columns}
::: {.column}
```{java}
//| output: true
//| echo: false
//| label: fig-class-employee-tableid-PK
//| filename: null
//| fig-cap: EmployeePK.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_ids/ex_tableid/Customer.java";
IJava.getKernelInstance().getMagics().applyCellMagic("javasrcClassByName",List.of("Customer"),script);
return null;
```
:::
::: {.column}
```{java}
//| output: true
//| echo: false
//| label: fig-rel-employe-composite-idtable
//| fig-cap: An Employee with a composite Key/Id
//| vscode: {languageId: java}
// PRINT SCHEMA
String script="%";
IJava.getKernelInstance().getMagics().applyCellMagic("rdbmsSchema",
List.of("ex_idtable"),script);
return null;
```
:::
::::
### UUIDs
- Les UUIDs sont des identifiants universels uniques, générés aléatoirement.
- Avantages: unicité globale, distribution, sans coordination centrale
- Inconvénients: taille (16 octets), performance index, non séquentiel
- Pour la pagination ajouter un index sur un attribut date de création
- Usage: microservices, systèmes distribués, réplication multi-maîtres
:::: {.columns}
::: {.column}
```{java}
//| output: true
//| echo: false
//| label: fig-class-employee-uuid-PK
//| filename: null
//| fig-cap: EmployeePK.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_uuid/Customer.java";
IJava.getKernelInstance().getMagics().applyCellMagic("javasrcClassByName",List.of("Customer"),script);
return null;
```
:::
::: {.column}
```{java}
//| output: true
//| echo: false
//| label: fig-rel-customer-uuid
//| fig-cap: A Customer with a UUID
//| vscode: {languageId: java}
// PRINT SCHEMA
String script="%";
IJava.getKernelInstance().getMagics().applyCellMagic("rdbmsSchema",
List.of("ex_uuid"),script);
return null;
```
:::
::: {.column}
```{java}
//| output: false
//| echo: false
//| vscode: {languageId: java}
import java.util.stream.Stream;
import net.datafaker.Faker;
import fr.univtln.bruno.demos.jpa.hello.samples.ex_uuid.Customer;
```
```{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}
//| vscode: {languageId: java}
try (EntityManager entityManager = emf.createEntityManager()) {
entityManager.getTransaction().begin();
Faker faker = new Faker();
Stream.generate(() -> {
String fullname = faker.name().fullName();
return Customer.of(fullname);
}).limit(5).forEach(entityManager::persist);
entityManager.getTransaction().commit();
entityManager.createQuery("""
SELECT c
FROM CustomerUUID c""")
.setMaxResults(5)
.getResultStream()
.forEach(System.out::println);
}
```
:::
::::
## Les clés composites
- Types de clés
- **Clé atomique**
- **Natural** (Clé naturelle) : attribut métier unique (email, SIRET)
- **Surrogate** (Clé artificielle) : identifiant technique unique (Long, UUID)
- **Clé composite**
- **Natural** : combinaison d'attributs métier (année + département + matricule)
- **Surrogate** : combinaison d'identifiants techniques (shardId + sequenceId)
- JPA propose deux approches pour gérer les clés composites:
- `@EmbeddedId` : encapsule les attributs dans une classe dédiée
- `@IdClass` : distribue les attributs dans l'entité
### Embedded Id
- Utilisation de l'annotation `@EmbeddedId`
- Encapsulation des attributs de la clé dans une classe dédiée
- La classe embarquée doit être annotée `@Embeddable`
- Doit implémenter Serializable
- Nécessite equals() et hashCode()
```{java}
//| output: true
//| echo: false
//| label: fig-rel-employe-composite-id
//| fig-cap: An Employee with a composite Key/Id
//| tags: [remove-input]
//| vscode: {languageId: java}
// PRINT SCHEMA
String script="%";
IJava.getKernelInstance().getMagics().applyCellMagic("rdbmsSchema",
List.of("ex_embedded_id"),script);
return null;
```
```{java}
//| output: true
//| echo: false
//| label: fig-class-employee-embedded
//| filename: X.java
//| fig-cap: Employee.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_ids/ex_embedded/Employee.java";
IJava.getKernelInstance().getMagics().applyCellMagic("javasrcClassByName",List.of("Employee"),script);
return null;
```
```{java}
//| output: true
//| echo: false
//| label: fig-class-employee-embedded-PK
//| filename: null
//| fig-cap: EmployeePK.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_ids/ex_embedded/EmployeePK.java";
IJava.getKernelInstance().getMagics().applyCellMagic("javasrcClassByName",List.of("EmployeePK"),script);
return null;
```
### Id Class
- Utilisation de l'annotation `@IdClass` dans l'entité.
- Les attributs de la clé sont définis dans l'entité
- Une classe séparée définit la structure de la clé
- Les noms des attributs doivent correspondre
- Plus simple pour les requêtes JPQL
```{java}
//| output: true
//| echo: false
//| label: fig-rel-employe-composite-id-idclass
//| fig-cap: An Employee with a composite Key/Id
//| tags: [remove-input]
//| vscode: {languageId: java}
// PRINT SCHEMA
String script="%";
IJava.getKernelInstance().getMagics().applyCellMagic("rdbmsSchema",
List.of("ex_idclass"),script);
return null;
```
```{java}
//| output: true
//| echo: false
//| label: fig-class-employee-idclass
//| filename: null
//| fig-cap: Employee.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_ids/ex_idclass/Employee.java";
IJava.getKernelInstance().getMagics().applyCellMagic("javasrcClassByName",List.of("Employee"),script);
return null;
```
```{java}
//| output: true
//| echo: false
//| label: fig-class-employee-idclass-PK
//| filename: null
//| fig-cap: EmployeePK.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_ids/ex_idclass/EmployeePK.java";
IJava.getKernelInstance().getMagics().applyCellMagic("javasrcClassByName",List.of("EmployeePK"),script);
return null;
```