1

I have a implementation of Object->equals like this i know not maybe the best implementation of it but this is our legacy method.

@Override
public boolean equals(final Object obj){
    if(this == obj){
        return true;
    }
    if(obj == null){
        return false;
    }             
    if(!getClass().isAssignableFrom(obj.getClass())){//this maybe buggy i know
        return false;  
    }
    final IdClass other = (IdClass)obj;
    return Objects.equals(this.id,other.id);
} 

IdClass is a abstract class

public abstract class IdClass 
{
    private Integer id;
    public IdClass(){}
    public IdClass(Integer id){super();this.id = id;}   
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "ID", unique = true, nullable = false,updatable=false)
    public Integer getId(){return this.id;}
    public void setId(Integer id){this.id = id;}        
}

All the models extends of it. I have two questions

1). How this is called? I mean i have seen that in the equals object and i think also in the compareTo method i can access the fields even when is private something like this

return Objects.equals(this.id,other.id);

I can access other.id method even when is private of course when is not the same class i mean other besides IdClass i cant but how this behavior call does have a name?

2). We are facing a bug with our code that i dont understand when i have something like this

final School school = new School(13);
final Student student = loadStudentWithCriteria();
final School proxySchool = student.getSchool();//generates N+1 Hibernate i mean generates a select to retrieve it proxySchool is in fact a proxy.
System.out.println(proxySchool.getId());//returns 13.

And we test the objects like this

final boolean equals = proxySchool.equals(school);//return true.
final boolean notEquals = school.equals(proxySchool);//return false;

Of course this breaks with the contract with equals because they are not symmetry.

But i debug the code and i see that the proxy in this line of the code returns null.

return Objects.equals(this.id,other.id);//other.id returns null.

Is strange even Netbeans build that code.

But this returns the value 13 in the example

return Objects.equals(this.id,other.getId());//other.getId() returns 13.

And now the equals method is symmetry.

But my question is why other.id returns null when other.getId() returns 13 it works ok when the school object is retrieve directly in db or is fetched with student using or createCriteria or createAlias or setFetchMode but when is retrieved in Hibernate n+1 is null.

chiperortiz
  • 4,751
  • 9
  • 45
  • 79
  • Proxy intercepts getter but can't intercept private field. if you call other.getId() then other.id is initialized and **Objects.equals(this.id,other.id)** is true – StanislavL Oct 12 '16 at 14:13

0 Answers0