HasCode & Equals

Implémenter les méthodes hascode() et equals(Object o) dans le cas on on veut

  • stocker les instances persistantes dans un Set (@ManyToMany ou @OneToMany)
  • rattacher les instances detached dans une liste

Dans le cas de la relation @OneToMany sur un Set, il est important de redéfinir les méthodes hasCode et equals
La meilleur approche serait d’utiliser natural-id ou business-key

@Entity(name = "Library")
public static class Library {

	@Id
	private Long id;

	private String name;

	@OneToMany(cascade = CascadeType.ALL)
	@JoinColumn(name = "book_id")
	private Set<Book> books = new HashSet<>();

	//Getters and setters are omitted for brevity
}

@Entity(name = "Book")
public static class Book {

	@Id
	@GeneratedValue
	private Long id;

	private String title;

	private String author;

	@NaturalId
	private String isbn;

	//Getters and setters are omitted for brevity

	@Override
	public boolean equals(Object o) {
		if ( this == o ) {
			return true;
		}
		if ( o == null || getClass() != o.getClass() ) {
			return false;
		}
		Book book = (Book) o;
		return Objects.equals( isbn, book.isbn );
	}

	@Override
	public int hashCode() {
		return Objects.hash( isbn );
	}
}Langage du code : PHP (php)

Exemple de test

Book book1 = new Book();
book1.setTitle( "High-Performance Java Persistence" );
book1.setIsbn( "978-9730228236" );

Library library = doInJPA( this::entityManagerFactory, entityManager -> {
	Library _library = entityManager.find( Library.class, 1L );

	_library.getBooks().add( book1 );

	return _library;
} );

assertTrue( library.getBooks().contains( book1 ) );Langage du code : JavaScript (javascript)

Parfois, on a juste besoin de comparer deux objets par rapport à leur identifiant unique, dans ce cas,

  • on définit une valeur constante à hasCode de façon à ce que le hasCode ne change pas avant et après un flush sur l’entity
  • On ne compare l’égalité uniquement que sur les entities non-transcient