Reputation: 1559
My equals() and hashcode() methods have been overwritten properly. But when I am saving equal objects, they appear in the database. How can I solve this problem? I want to have unique set of elements in the database. Thanks.
Here is the mapping file:
<hibernate-mapping>
<class name="vertical.model.filter.Filter" table="FILTER">
<id name="id" type="long">
<generator class="native"/>
</id>
<discriminator column="TYPE" type="string"/>
<subclass name="vertical.impl.filter.AbstractFilter" abstract="true">
<set name="options" table="FILTER_OPTION" cascade="all">
<key column="FILTER_ID"/>
<many-to-many column="OPTION_ID" class="vertical.model.filter.FilterOption"/>
</set>
<subclass name="vertical.impl.services.filter.GrfFilter"
discriminator-value="rabota">
</subclass>
</subclass>
</class>
</hibernate-mapping>
Upvotes: 1
Views: 1475
Reputation: 11839
It is a classical problem with no theoretical solution but there are practical ways of solving it.
Let me take some lines from the article;
The problem stems from differences between object identity in the virtual machine (VM) and object identity in the database. In the VM you do not get an ID for an object; you simply hold direct references to the object. Behind the scenes, the VM does assign an eight-byte ID, which is what a reference to an object really is. The problems start when you persist an object in a database. Say you create a Person object and save it to a database (person1). Somewhere else in your code you read in the Person data and instantiate a new Person object (person2). You now have two objects in memory that are mapped to the same row in the database. An object reference can only point to one or the other, but we need a way to show that these are really the same entity. This is where object identity comes in.
What you should do is simple, override the equals()
and hashcode()
according to the business functions of the entities.
Here is a suggested solution from the hibernate forum article;
Separating object id and business key To avoid this problem we recommend using the "semi"-unique attributes of your persistent class to implement equals() (and hashCode()). Basically you should think of your database identifier as not having business meaning at all (remember, surrogate identifier attributes and automatically generated vales are recommended anyway). The database identifier property should only be an object identifier, and basically should be used by Hibernate only. Of course, you may also use the database identifier as a convenient read-only handle, e.g. to build links in web applications.
Upvotes: 1