Skip to content

Commit a869ce1

Browse files
committed
document that records can now be used as @IdClasses and @EmbeddableIds
Signed-off-by: Gavin King <[email protected]>
1 parent 647f689 commit a869ce1

File tree

1 file changed

+5
-51
lines changed

1 file changed

+5
-51
lines changed

documentation/src/main/asciidoc/introduction/Entities.adoc

+5-51
Original file line numberDiff line numberDiff line change
@@ -364,64 +364,23 @@ class Book {
364364
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?
365365

366366
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`.
368369

369370
[source,java]
370371
----
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) {}
400373
----
401374

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.
403376

404377
This is not our preferred approach.
405378
Instead, we recommend that the `BookId` class be declared as an `@Embeddable` type:
406379

407380
[source,java]
408381
----
409382
@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) {}
425384
----
426385

427386
We'll learn more about <<embeddable-objects>> below.
@@ -881,11 +840,6 @@ record Name(String firstName, String middleName, String lastName) {}
881840

882841
In this case, the requirement for a constructor with no parameters is relaxed.
883842

884-
[NOTE]
885-
====
886-
Unfortunately, as of May 2023, Java `record` types still cannot be used as ``@EmbeddedId``s.
887-
====
888-
889843
We may now use our `Name` class (or record) as the type of an entity attribute:
890844

891845
[source,java]

0 commit comments

Comments
 (0)