@@ -364,64 +364,23 @@ class Book {
364
364
But this approach comes with a problem: what object can we use to identify a `Book` and pass to methods like `find()` which accept an identifier?
365
365
366
366
The solution is to write a separate class with fields that match the identifier attributes of the entity.
367
- The `@IdClass` annotation of the `Book` entity identifies the id class to use for that entity:
367
+ Every such id class must override `equals()` and `hashCode()`.
368
+ Of course, the easiest way to satisfy these requirements is to declare the id class as a `record`.
368
369
369
370
[source,java]
370
371
----
371
- class BookId {
372
-
373
- String isbn;
374
- int printing;
375
-
376
- BookId() {}
377
-
378
- BookId(String isbn, int printing) {
379
- this.isbn = isbn;
380
- this.printing = printing;
381
- }
382
-
383
- @Override
384
- public boolean equals(Object other) {
385
- if (other instanceof BookId) {
386
- BookId bookId = (BookId) other;
387
- return bookId.isbn.equals(isbn)
388
- && bookId.printing == printing;
389
- }
390
- else {
391
- return false;
392
- }
393
- }
394
-
395
- @Override
396
- public int hashCode() {
397
- return isbn.hashCode();
398
- }
399
- }
372
+ record BookId(String isbn, int printing) {}
400
373
----
401
374
402
- Every id class should override `equals()` and `hashCode()` .
375
+ The `@IdClass` annotation of the `Book` entity identifies `BookId` as the id class to use for that entity .
403
376
404
377
This is not our preferred approach.
405
378
Instead, we recommend that the `BookId` class be declared as an `@Embeddable` type:
406
379
407
380
[source,java]
408
381
----
409
382
@Embeddable
410
- class BookId {
411
-
412
- String isbn;
413
-
414
- int printing;
415
-
416
- BookId() {}
417
-
418
- BookId(String isbn, int printing) {
419
- this.isbn = isbn;
420
- this.printing = printing;
421
- }
422
-
423
- ...
424
- }
383
+ record BookId(String isbn, int printing) {}
425
384
----
426
385
427
386
We'll learn more about <<embeddable-objects>> below.
@@ -881,11 +840,6 @@ record Name(String firstName, String middleName, String lastName) {}
881
840
882
841
In this case, the requirement for a constructor with no parameters is relaxed.
883
842
884
- [NOTE]
885
- ====
886
- Unfortunately, as of May 2023, Java `record` types still cannot be used as ``@EmbeddedId``s.
887
- ====
888
-
889
843
We may now use our `Name` class (or record) as the type of an entity attribute:
890
844
891
845
[source,java]
0 commit comments