Hibernate / JPA equals () and hashCode () with Lazy loaded business id

I am wondering how to write the correct equals () and hashCode () for Hibernate Entities that have Lazy Loaded ManyToOne related to another object, which is important as a business key. Please note that I already read the Hibernate documentation in this section , and I know that I should / should not use the object identifier.

To clarify, here is an example:

public class BusinessEntity implements Serializable { //for simplicity, here just the important part private String s; @ManyToOne(fetch= FetchType.LAZY ) private ImportantEntity anotherEntity; @Override public boolean equals( Object obj ) { //Here I would like to call something like // (obj.getAnotherEntity.getName.equals(getAnotherEntity.getName) && obj.getS().equals(getS()); return true; } } 

Of course, this is just a simplified example. But I hope I can explain my scenario. Has anyone tried something like this before? I did not find anything regarding this topic.

+6
source share
2 answers

For simplicity, I skipped the zero security code. But the idea is to create an additional property that will retain the name of the object and will not reveal it to the outside world

 public class BusinessEntity implements Serializable { //for simplicity, here just the important part private String s; @ManyToOne(fetch= FetchType.LAZY ) private ImportantEntity anotherEntity; private String anotherEntityName; @Override public boolean equals( Object obj ) { if(BusinessEntity.class.isAssignableFrom(obj.getClasS())){ BusinessEntity other = (BusinessEntity)obj; return other.anotherEntityName. equals(this.anotherEntityName) && other.s.equals(this.s); } return true; } public void setAnotherEntity(ImportantEntity ie){ anotherEntityName= ie.getName(); anotherEntity = ie; } } 
+3
source

Equally, you should use instanceof to compare the types and getters of the properties you want to include.

instanceof is used because of proxy classes that use hibernate, and getters are used to enable lazy loads.

+2
source

Source: https://habr.com/ru/post/890094/


All Articles