You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Describe the bug
I had a bug in my project where equals used .id instead of .getId() when comparing the IDs of an Object. The .id just returned null while .getId returned the correct value. I believe that for surrogate key equals, the getters should be enforced.
To Reproduce
Code that triggers the behavior
Equals Method:
@Overridepublicbooleanequals(Objecto) {
if (this == o) {
returntrue;
}
if (!(oinstanceofMyEntitythat)) {
returnfalse;
}
returnid != null && id.equals(that.id);
}
The test should make sure to use return id != null && id.equals(that.**getId()**); instead
Am I correct in assuming you're referring to the "Using a Generated Primary Key" section of that blog post, where the id is generated by Hibernate and is only available once the entity is persisted?
Can you describe the circumstances when entity's id field is null, but getId() isn't? When exactly does that happen?
Hey jqno,
we do have the Problem, if the Entity is "lazy" loaded and a HibernateProxyElement got created. The easiest way to create this is calling the getReferenceById() Method by Spring Boot.
When doing this JPA acts the same way then reference a relationship described here: https://jqno.nl/equalsverifier/errormessages/jpa-direct-reference-instead-of-getter/
Hope this helps already...
Describe the bug
I had a bug in my project where equals used
.id
instead of.getId()
when comparing the IDs of an Object. The.id
just returnednull
while.getId
returned the correct value. I believe that for surrogate key equals, the getters should be enforced.To Reproduce
Code that triggers the behavior
Equals Method:
The test should make sure to use
return id != null && id.equals(that.**getId()**); instead
Test that passed:
Remember, you have the problem right in front of you. I have to try and reproduce it in my spare time. Please help me, so that I can help you!
Error message
The test is passing so no error message. Also no warning.
Expected behavior
I would expect the test to fail. But it did not.
Version
3.15.4
Additional context
According to this blog post, the equals should also be implemented using
getId()
: https://thorben-janssen.com/ultimate-guide-to-implementing-equals-and-hashcode-with-hibernate/The text was updated successfully, but these errors were encountered: