Hibernate 4 composite-id NonUniqueObjectException - java

I have NonUniqueObjectException thrown when upgrading my project from Hibernate 3 to Hibernate 4.
I created minimal Hibernate 4 project for testing purposes, and managed to reproduce this exception by:
having entity House, and another entity Door that has a composite id that contains House entity
<class dynamic-insert="true" dynamic-update="true" name="entity.Door" select-before-update="true" table="DOOR">
<composite-id name="id" class="DoorHousePK">
<key-many-to-one class="entity.House" column="HOUSEID" name="house"/>
<key-property column="DOORID" name="doorId" type="string"/>
</composite-id>
and then in the same transaction fetching a House and then fetching Door by composite id with:
(Door)session.get(Door.class, doorHousePK)
Here is the hbm file for House:
<class dynamic-insert="true" dynamic-update="true" name="entity.House" select-before-update="true" table="HOUSE">
<id column="ID" name="id" type="int"/>
<property column="squarefeet" name="squareFeet" not-null="false" type="int"/>
<property column="address" length="255" name="address" not-null="false" type="string"/>
<property column="color" length="32" name="color" not-null="false" type="string"/>
<property column="description" name="description" not-null="false" type="materialized_clob"/>
</class>
,and the stack trace of the error:
INFO: HHH000327: Error performing load command : org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [entity.House#1]
Exception in thread "main" org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session : [entity.House#1]
at org.hibernate.engine.internal.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:617)
at org.hibernate.event.internal.AbstractReassociateEventListener.reassociate(AbstractReassociateEventListener.java:74)
at org.hibernate.event.internal.DefaultLockEventListener.onLock(DefaultLockEventListener.java:95)
at org.hibernate.internal.SessionImpl.fireLock(SessionImpl.java:774)
at org.hibernate.internal.SessionImpl.fireLock(SessionImpl.java:767)
at org.hibernate.internal.SessionImpl.access$1800(SessionImpl.java:176)
at org.hibernate.internal.SessionImpl$LockRequestImpl.lock(SessionImpl.java:2491)
at org.hibernate.loader.plan.exec.internal.EntityLoadQueryDetails$EntityLoaderRowReader.addKeyManyToOnesToSession(EntityLoadQueryDetails.java:263)
at org.hibernate.loader.plan.exec.internal.EntityLoadQueryDetails$EntityLoaderRowReader.readRow(EntityLoadQueryDetails.java:247)
at org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:129)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:138)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:102)
at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:186)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4126)
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:503)
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:468)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:213)
at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:275)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:151)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1070)
at org.hibernate.internal.SessionImpl.access$2000(SessionImpl.java:176)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2551)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:955)
When reverting this minimal project back to Hibernate 3 the exception is gone, and it all works fine.
What is the difference in composite-id handling between Hibernate 3 and Hibernate 4?
How can I make this work in Hibernate 4?

I recently migrated from hibernate 3 to 4 with two tables with composite ids and related to each other by composite foreign key. Exactly same configuration worked fine in both versions. So there is no difference as far as basic concepts about composite-id functionality are concerned.
You should enable debugging for hibernate APIs i.e. set debug level for org.hibernate.* to DEBUG in log properties file to see which SQLs are being fired. That will help you see if any additional/unexpected SQLs are being fired by hibernate.

Make sure your entities, and the objects that make up your composite primary key, have appropriate implementations of hashCode() and equals(). I seem to remember there being some underlying changes in hash-code usage and/or object equality checking between Hibernate 3 and 4.

Related

Hibernate performs delete cascade in wrong order

My Db is throwing a Constraing violation (FK) because Hibernate performs a cascade delete in the wrong order.
Details:
I delete a Member, that has a Wallet with Wallet transactions (value-type), and the wallet transaction has an association to a product just like the Member contains collection of products (see the Hibernate mapping below).
I delete a Member instance, and want Hibernate to remove both the products and Wallet transactions. It seems that it first removes the product instances (through cascading), such that a FK violation is thrown by the DB, as it's still referenced by a Wallet transaction, that wasn't removed yet (through cascade)
I played around with the cascade setting, like all-delete-orphan (on the products), etc..., but no luck
I also emptied the wallet transactions and flushed the hibernate session in the same removal transaction, but also the same error.
Please some understanding and help to get the order of cascade deletion correct?
The hibernate mapping (I left out the none-important parts like PK and properties):
<class name="Member" table="mem" >
<component name="wallet" class="Wallet">
<set name="transactions" table="wallet_tx" cascade="all">
<cache usage="read-write" />
<key column="idTaxer" not-null="true" />
<composite-element class="WalletTransaction">
<property name="amount" type="big_decimal" column="amount" />
<many-to-one name="product" column="idPrdInst" class="Product" cascade="none" />
</composite-element>
</set>
</component>
<set name="products" cascade="delete" inverse="true">
<key column="idTaxer" not-null="true" />
<one-to-many class="Product" />
</set>
</class>
<class name="Product" table="prd" >
...
<many-to-one name="member" column="idMember" class="Member" cascade="none" />
</class>
The DB error:
ERROR: update or delete on table "prd" violates foreign key constraint "fk_1umej7" on table "wallet_tx"
DETAIL: Key (id)=(75bef42fc4544) is still referenced from table "wallet_tx".
If you empty the wallet transaction and expect it to be deleted you must set delete-orphan on the transactions relationship.
If product is still deleted 1st, you can flush after removing the wallet tx from the transaction set, it will work but it's surely not the state-of-art way.
Otherwise you could try to map the product - transaction oneToMany relationship and set a delete cascade on it (with inverse), the product deletion will so first trigger the transaction deletion.
Instead of:
<set name="transactions" table="wallet_tx" cascade="all">
you should have:
<set name="transactions" table="wallet_tx" cascade="all-delete-orphan">
And simply clear the transactions Set prior to deleting the Member parent entity.

Map hibernate many-to-one with the foreign key in subclass joined table

I'm mapping some entities using Hibernate 3 for my project and simply explained I've got kind of this:
Student entity (tstudent table)
UniversityStudent entity (tuniversitystudent table)
University entity (tuniversity table)
UniversityStudent extends from Student and has its own attributes, like the university itself, which is a foreign key into the tuniversitystudent table. It is also mapped like a subclass into the Student class, using a discriminator field:
<class name="mycompany.Student" table="tstudent" discriminator-value="BASIC">
<id name="id" column="id" type="integer">
<generator class="native" />
</id>
<discriminator column="type" />
<property name="name" column="name" />
<property name="surname" column="surname" />
<property name="phoneNumber" column="phone_number" />
<subclass discriminator-value="UNIVERSITY"
name="mycompany.UniversityStudent">
<join table="tuniversitystudent">
<key column="id_student" />
<many-to-one name="university" class="mycompany.University">
<column name="id_university" />
</many-to-one>
</join>
</subclass>
</class>
Well, now I want to have a Set collection with the UniversityStudent entities for each University. So I map it like that:
<class name="mycompany.University" table="tuniversity">
<id name="id" column="id" type="integer">
<generator class="native" />
</id>
<property name="name" column="name" />
<set name="universityStudents" table="tuniversitystudent">
<key>
<column name="id_university" />
</key>
<one-to-many class="mycompany.UniversityStudent" />
</set>
</class>
My problem comes when I want to load a University object, Hibernate complains that id_university doesn't exist in tstudent table. I checked the generated SQL query and it really tries to load it from tstudent.
Unknown column 'student0_.id_university' in 'field list'
It seems that it's recognizing that it is a subclass of the basic Student and tries to join the collection using a field in the parent table, but however the field is actually in the child table, because only university students can have a University assigned.
I tried another workaround which seems to work but it's not valid for me, that's mapping the UniversityStudent as a joined-subclass instead of a subclass with a join inside:
<joined-subclass name="mycompany.UniversityStudent" table="tuniversitystudent">
<key column="id_student" />
<many-to-one name="university" class="mycompany.University">
<column name="id_university" />
</many-to-one>
</joined-subclass>
However, I'm interested in keeping it as a subclass with a discriminator value. Any idea?
I checked out some resources and finally got into this bug: https://hibernate.atlassian.net/browse/HHH-1015, which looks absolutely compatible with your case. Checkout this old question as well, again very similar to your case.
I firstly read the definition of table per sublass given by Hibernate (I know, it is for version 3.3 but I couldn't find the same source for Hibernate 4): joined-subclass seems (to me) to be a custom implementation of subclass using a discriminator provided by Hibernate and that is a good reason to stay away from its usage. However, from what I know, the mappings table per sublass and table per subclass using a discriminator should be equivalent, that's why I believe the bug I pointed you out is really still open.
If you have time and will, you can try to use another JPA provider and check if you still run in the same issue. JPA 2.0 specifications is a thing, provider implementation is another! I recently run into another bug (related to #IdClass) which forced me to try EclipseLink and the configuration which was not working with Hibernate was right with Eclipse Link
Seems you can use Custom SQL (or HQL) for loading. Haven't tried it myself, but looks like, hmm, at least as a last resort, it provides a decent solution.
Define the query in your HBM:
<sql-query name="universityStudents">
<load-collection alias="unistu" role="University.universityStudents"/>
SELECT unistu.*, student.*
FROM tuniversitystudent unistu
JOIN tstudent student
ON unistu.id_student = student.id
WHERE unistu.id_university = :id
</sql-query>
And then use it inside University:
<set name="universityStudents" inverse="true">
<key/>
<one-to-many class="mycompany.UniversityStudent"/>
<loader query-ref="universityStudents"/>
</set>

Hibernate Mapping of Join Table with Meta Data

I'm trying to figure out how to map the relationship between two tables through a join table that has some meta data in it. In short, the three tables represent the page of a form, and each page can contain any number of elements (questions.) For some reason, the original developer decided that elements could be used on multiple forms. This means that the weight column, used to order the elements on the page, is in the join table.
How the heck do I map this in XML? (Annotations aren't an option.)
For the join table, I guess it's like this:
<class name="com.foo.bar.model.db.ApplicationPageElements"
table="APPLICATION_PAGE_ELEMENTS">
<composite-id name="id" class="com.foo.bar.model.db.ApplicationPageElementsKey">
<key-property name="pageId" column="page_id"/>
<key-property name="elementId" column="element_id"/>
</composite-id>
<property name="weight" type="java.lang.Long">
<column name="WEIGHT" precision="0" />
</property>
</class>
My instincts have me wanting to do something like this from the ApplicationPage side of things:
<set name="applicationElements" table="applicationPageElement">
<key column="page_id"/>
<many-to-many column="element_id" unique="true"
class="com.foo.bar.model.db.ApplicationElements" />
</set>
And that's where I get all slack-jawed, stare at the screen, and sob.
We're using .hbm.xml files to map our database. We also made the decision to not change our database.
Any ideas on how to map this in XML?
Instead of thinking of the relationship between application_page and application_element as many to many, think of it as a one to many relationship from application_page to ApplicationPageElements and a one to many relationship from application_element to ApplicationPageElements.
In your application_page xml mapping add this:
<set name="applicationElements" inverse="true">
<key column="page_id"/>
<one-to-many class="ApplicationPageElements"/>
</set>
page_id forms a part of the primary key of the join table. So, mark the collection as inverse.
Your mapping for the join table is correct. But, with the above change current mapping of your join table you can navigate from application_page to ApplicationPageElements. To navigate from application_page to application_element (via ApplicationPageElements) add a many to one relationship in join table mapping.
<class name="com.foo.bar.model.db.ApplicationPageElements"
table="APPLICATION_PAGE_ELEMENTS">
<composite-id name="id" class="com.foo.bar.model.db.ApplicationPageElementsKey">
<key-property name="pageId" column="page_id"/>
<key-property name="elementId" column="element_id"/>
</composite-id>
<property name="weight" type="java.lang.Long">
<column name="WEIGHT" precision="0" />
</property>
<many-to-one name="elements" class="ApplicationElements"
column="element_id" not-null="true" insert="false" update="false"/>
<many-to-one name="page" class="ApplicationPage"
column="page_id" not-null="true" insert="false" update="false"/>
</class>
Note that in the above many-to-one mapping, insert and update attributes are set to false. This is necessary because the columns are mapped twice, once in the composite key (which is responsible for insertion of the values) and again for the many-to-one associations.
The above use case is mentioned in detail in the book: Java Persistence with Hibernate.

Error generating sequence in HSQLDB with Hibernate using hbm2ddl

I am getting an error while generating a sequence for an id field in HSQLDB. The mapping file is configurated like this:
<hibernate-mapping>
<class name="ddol.rtdb.dto.Configuration" table="RTDB_CONFIGURATION">
<id name="id" type="int">
<column name="CONF_ID" />
<generator class="sequence">
<param name="sequence">CONF_ID_SEQ</param>
</generator>
</id>
<property generated="never" lazy="false" name="configurationDate"
type="java.util.Date">
<column name="CONF_DATE" />
</property>
It works when I use the same mapping with oracle, but does not generate the sequence when used with HSQLDB for testing. Is there anything else I should add to the mapping?
The error I am getting when I try to insert something into the table is:
ERROR org.hibernate.util.JDBCExceptionReporter - user has no privileges or object not found: CONF_ID_SEQ
HSQLDB version is 2.2.8, Hibernate version is 3.6.10
Create the sequence(CONF_ID_SEQ - if it doesn't exists) and make sure that you have "grant" permission for that.
Alternatively, you can create a "synonym" for the sequence and give "grant" permission for all the users or to the specific users you want to. Then it should work.
E.g
Consider, You are creating Sequence as "dbauser". Now, some other "user"(who don't have access) trying to use it,
then u will get "user has no privileges" error.
In that case you can use above strategy.

How to Stop Hibernate From Trying to Update one-to-many Over Join Table

Ok so I'm having bit of a problem with my Hibernate mappings and getting the desired behavior.
Basically what I have is the following Hibernate mapping:
<hibernate-mapping>
<class name="com.package.Person" table="PERSON" schema="MYSCHEMA" lazy="false">
<id name="personId" column="PERSON_ID" type="java.lang.Long">
<generator class="sequence">
<param name="sequence">PERSON_ID_SEQ</param>
</generator>
</id>
<property name="firstName" type="string" column="FIRST_NAME">
<property name="lastName" type="string" column="LAST_NAME">
<property name="age" type="int" column="AGE">
<set name="skills" table="PERSON_SKILL" cascade="all-delete-orphan">
<key>
<column name="PERSON_ID" precision="12" scale="0" not-null="true"/>
</key>
<many-to-many column="SKILL_ID" unique="true" class="com.package.Skill"/>
</set>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="com.package.Skill" table="SKILL" schema="MYSCHEMA">
<id name="skillId" column="SKILL_ID" type="java.lang.Long">
<generator class="sequence">
<param name="sequence">SKILL_ID_SEQ</param>
</generator>
</id>
<property name="description" type="string" column="DESCRIPTION">
</class>
</hibernate-mapping>
So lets assume that I have already populated the Skill table with some skills in it. Now when I create a new Person I want to associate them with a set of skills that already exist in the skill table by just setting the ID of the skill. For example:
Person p = new Person();
p.setFirstName("John");
p.setLastName("Doe");
p.setAge(55);
//Skill with id=2 is already in the skill table
Skill s = new Skill()
s.setSkillId(2L);
p.setSkills(new HashSet<Skill>(Arrays.asList(s)));
PersonDao.saveOrUpdate(p);
If I try to do that however I get an error saying:
WARN (org.slf4j.impl.JCLLoggerAdapter:357) - SQL Error: 1407, SQLState: 72000
ERROR (org.slf4j.impl.JCLLoggerAdapter:454) - ORA-01407: cannot update ("MYSCHEMA"."SKILL"."DESCRIPTION") to NULL
ERROR (org.slf4j.impl.JCLLoggerAdapter:532) - Could not synchronize database state with session
org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update
The reason I am getting this error I think is because Hibernate sees that the Skill with Id 2 has 'updated' its description to null (since I never set it) and tries to update it. But I don't want Hibernate to update this. What I want it to do is insert the new Person p and insert a record into the join table, PERSON_SKILL, that matches p with the skill in the SKILL table with id=2 without touching the SKILL table.
Is there anyway to achieve this behavior?
Instead of creating the Skill object yourself:
//Skill with id=2 is already in the skill table
Skill s = new Skill()
s.setSkillId(2L);
p.setSkills(new HashSet<Skill>(Arrays.asList(s)));
You should be retrieving it from the Hibernate Session:
Skill s = (Skill) session.get(Skill.class, 2L);
p.setSkills(new HashSet<Skill>(Arrays.asList(s)));
This way the Session thinks that the skill contained in p.skills is persistent, and not transient.
This may be possible if you don't cascade all-delete-orphan which is explicitely telling hibernate to cascade the changes.
But the right way would be IMO to load load the desired Skill entity from the database and to add it to the set of skills of the Person.

Categories