seba.wagner
seba.wagner

Reputation: 3870

can there be multiple instances of the same (Open)JPA entity in an application? Equals does not work for Entity Instances?

Our stack: Tomcat 7, Spring 3.1.1, OpenJPA 2.2.0

I came accross an issue, the root was a comparisson:

server1.equals(server2);

server1 and server2 are both instances of the Entity "Server":

@Entity
public class Server implements Serializable {
   private long id;
   // getters and setters
}

I had to change the comparisson to:

server1.getId().equals(server2.getId());

That one worked, the above one returns false, even if the id of the servers are the same. I also checked the hashCodes of the two instances, the two instances had indeed a different hashCode.

Why are there two instances of the same entity in our application?

How can that happen? There is only one entity of the "Server" in the database.

Thanks!
Sebastian

Upvotes: 0

Views: 1583

Answers (3)

Parvez
Parvez

Reputation: 641

You will have multiple instance of Entiry if it is different session or outside session. In your case you are doing comparison in ClientListHashMapStore that is not part of transaction. That means there is no session and you will have multiple instances of Entity. Ideally one should override equals method if comparison of two instances is required.

Upvotes: 0

Ralph
Ralph

Reputation: 120851

There will be different instances if you load them with different entity managers or different transactions for example.

Upvotes: 4

Mark Bramnik
Mark Bramnik

Reputation: 42541

The first thing that comes to mind is that you have 2 (at least) class loaders in your application. One loads Entity and then instance server1 is created and the second loads server2. Usually these are managed internally by your technology stack

This is correct in general in java and not only in your particular application. Now the tricky part is where are these class loaders are coming from.

First of all in order to ensure that this is the case you can try to print out the class loaders, something like this:

print before comparison: server1.getClass().getClassLoader()
print before comparison: server2.getClass().getClassLoader()

This can give you an idea of what happens there. It may come from different deployment units for example.

Hope this helps

Upvotes: 0

Related Questions