Ultimate Guide to Implementing Equals & HashCode with Hibernate & JPA

preview_player
Показать описание
In today’s video, I will show you how to implement the equals and hashcode mehods of your entities. You will learn how to implement these methods so that they fulfil the requirements of the Java language, the JPA specification and Hibernate. I will also show you which attributes you should never include in your equals method.

My consulting clients and people in my workshops and conference talks ask me all the time about these two methods. So, let’s answer these questions once and for all in this video.
But before we start, if this is your first time here, and you want to learn how to create your entity mappings with ease, build incredible efficient persistence layers with Hibernate and all types of other Java persistence related stuff, start now by subscribing and clicking the bell, so you don't miss anything.
OK, let’s get into today’s topic.
The implementation of the equals() and hashCode() methods for entity classes is an often discussed question.
Do you really need them? There are lots of applications that work perfectly fine using Java’s default methods provided by the Object class.
And if you need to implement them, how should you do that? Should you use all attributes or just the primary keys?

If you like this video, please give me your thumbs up and share it with your friends and co-workers.

Like my channel? Subscribe!

Join the free Member Library:

Want to connect with me?

#hashcode #equals #JPA #hibernate
Рекомендации по теме
Комментарии
Автор

Das Video ist immens wichtig, wenn man Test Entities erzeugt, die zunächst detached sind und per HashSet verwendet werden. Der Primary Key ist dann völlig untauglich für hash und equals. Danke Thorben für die ausführliche Erklärung. Da es ein sehr komplizierter Zusammenhang ist, wäre das Video evtl. in einer Deutschen Fassung hilfreich.

frankipanki
Автор

Great video as always.
How about this one-liner as an equals implementation for an entity class named MyEntity with a unique key ID?
public boolean equals(Object obj) { return obj instanceof MyEntity && Objects.equals(id, obj.getId()); }
Is that sufficient or am I missing something?
Note: "obj instanceof MyEntity" already has a Null Pointer check.

ThePianoman--