Hibernate - NullPointerException when accessing a child element of one-to-many association - java

There is a Java SE project with Hibernate ORM. I feel that the problem is trivial, but need some help.
There is a code snippet:
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session s = factory.openSession();
int id = 1;
ExperimentSetResult experimentSetResult = (ExperimentSetResult)s.get(ExperimentSetResult.class, id);
System.out.println("size: " + experimentSetResult.getExperimentResults().size());
System.out.println("id[0]: " + experimentSetResult.getExperimentResults().get(0).getId());
I get a NullPointerException for the last string of code (when accessing the 0-th element of a collection associated with an object loaded recently).
There are the hbm files snippets:
ExperimentResult.hbm.xml:
<hibernate-mapping>
<class name="rmocommon.driverreaction.ExperimentResult" table="experiment_results">
<id name="id" type="int">
<generator class="increment"/>
</id>
<many-to-one class="rmocommon.driverreaction.ExperimentSetResult" name="ExperimentSetResult" column="ExperimentSetResultId" not-null="true" />
</class>
</hibernate-mapping>
ExperimentSetResult.hbm.xml:
<hibernate-mapping>
<class name="rmocommon.driverreaction.ExperimentSetResult" table="experiment_set_results">
<id name="id" type="int">
<generator class="increment"/>
</id>
<list name="ExperimentResults" cascade="all-delete-orphan" inverse="true">
<key column="ExperimentSetResultId" not-null="true"/>
<list-index column="Id"/>
<one-to-many class="rmocommon.driverreaction.ExperimentResult"/>
</list>
</class>
</hibernate-mapping>
What's wrong with mapping or with my source code?
UPDATE:
Here is an output and a stack trace:
Hibernate: select experiment0_.id as id4_2_, experiment0_.StartedDate as StartedD2_4_2_, experiment0_.FinishedDate as Finished3_4_2_, experiment0_.DeviceOutput as DeviceOu4_4_2_, person1_.id as id0_0_, person1_.Login as Login0_0_, person1_.LastName as LastName0_0_, person1_.Patronymic as Patronymic0_0_, person1_.FirstName as FirstName0_0_, person1_.Age as Age0_0_, experiment2_.id as id1_1_, experiment2_.TestMode as TestMode1_1_, experiment2_.TransportType as Transpor3_1_1_, experiment2_.TransportStartSpeed as Transpor4_1_1_, experiment2_.RoadType as RoadType1_1_, experiment2_.RoadLength as RoadLength1_1_, experiment2_.DirectionLeft as Directio7_1_1_, experiment2_.RespondToFirstEffort as RespondT8_1_1_, experiment2_.SoundOnFirstEffort as SoundOnF9_1_1_, experiment2_.ScaleObjects as ScaleOb10_1_1_, experiment2_.ShowTransportSpeed as ShowTra11_1_1_, experiment2_.BarrierXMin as Barrier12_1_1_, experiment2_.BarrierXMax as Barrier13_1_1_, experiment2_.ReactionTime as Reactio14_1_1_, experiment2_.SoundOnBarrierAppearance as SoundOn15_1_1_, experiment2_.AllowedCheatCount as Allowed16_1_1_ from experiment_set_results experiment0_ left outer join persons person1_ on experiment0_.id=person1_.id left outer join experiment_set_settings experiment2_ on experiment0_.id=experiment2_.id where experiment0_.id=?
Hibernate: select experiment0_.ExperimentSetResultId as Experim11_4_1_, experiment0_.id as id1_, experiment0_.Id as Id1_, experiment0_.id as id2_0_, experiment0_.Distance as Distance2_0_, experiment0_.Crash as Crash2_0_, experiment0_.BrakingStarted as BrakingS4_2_0_, experiment0_.BrakingStartedTime as BrakingS5_2_0_, experiment0_.BrakingStartedDistance as BrakingS6_2_0_, experiment0_.BarrierX as BarrierX2_0_, experiment0_.Number as Number2_0_, experiment0_.Time as Time2_0_, experiment0_.Valid as Valid2_0_, experiment0_.ExperimentSetResultId as Experim11_2_0_ from experiment_results experiment0_ where experiment0_.ExperimentSetResultId=?
size: 6
Exception in thread "main" java.lang.NullPointerException
at hibernateTest.HibernateTest.main(HibernateTest.java:45)
Java Result: 1

Might be that your mapping is wrong. Your list-index column definetly should not be ID.
If you really need the ordering, you better create a separate column for that, otherwise you will encounter problems.
Another thing I've noticed. You don't have to specify the inverse on the one-to-many relationship.
It's been a while I've seen hbm.xml files, can you use annotations? They are much easier to understand.

Related

How to access joined-subclass's properties in HQL?

Consider the following hibernate mapping (using hibernate 4):
Answer with a DataCollection joined-subclass:
<hibernate-mapping>
<class name="Answer" table="answer">
<many-to-one name="answeredForm" class="AnsweredForm" fetch="select">
<column name="answered_form_id" />
</many-to-one>
<joined-subclass table="data_collection" name="DataCollection" extends="Answer">
<key column="id"></key>
</joined-subclass>
</class>
</hibernate-mapping>
AnsweredForm with a PatientForm joined-subclass:
<hibernate-mapping>
<class name="AnsweredForm" table="answered_form">
<joined-subclass table="patientForm" name="PatientForm" extends="AnsweredForm">
<many-to-one name="patient" class="Patient" fetch="join">
<column name="patient_id" />
</many-to-one>
</joined-subclass>
</class>
</hibernate-mapping>
Question: Using HQL, how can you ask for "all datcollections whose AnsweredForm belongs to patient x"?
SELECT answer FROM DataCollection answer
JOIN answeredForm answeredForm
WHERE answer.answeredForm.patient.code=:patientCode
This HQL yields the error:
ERROR: missing FROM-clause entry for table "answeredfo2_2_"
And rightly so, as the SQL translation of this query is:
SELECT datacollec0_.id AS id1_62_,
datacollec0_1_.free_text AS free_tex2_62_
FROM data_collection datacollec0_
INNER JOIN answer datacollec0_1_
ON datacollec0_.id = datacollec0_1_.id
CROSS JOIN answered_form answeredfo1_
CROSS JOIN answered_form answeredfo2_
CROSS JOIN patient patient3_
WHERE datacollec0_1_.answered_form_id = answeredfo1_.id
AND datacollec0_1_.answered_form_id = answeredfo2_.id
AND answeredfo2_2_.patient_id = patient3_.id
AND CASE
WHEN answeredfo1_4_.id IS NOT NULL THEN 4
WHEN answeredfo1_1_.id IS NOT NULL THEN 1
WHEN answeredfo1_2_.id IS NOT NULL THEN 2
WHEN answeredfo1_3_.id IS NOT NULL THEN 3
WHEN answeredfo1_.id IS NOT NULL THEN 0
END = 2
AND patient3_.code = ?
Try to use the following hql:
SELECT a FROM Answer a
JOIN a.answeredForm af
WHERE af.patient.code=:patientCode
Look at this part of the hibernate documentation for additional explanations and examples.

hibernate deletes list relation when updating other list containing same objects

In my application I have a setup like the following:
class A {
String id;
List<C> list;
}
class B {
String id;
List<C> list;
}
class C {
String id;
}
which is mapped in hibernate like
<class name="A" lazy="false">
<id name="id">
<generator class="org.hibernate.id.UUIDGenerator"/>
</id>
<list name="list" lazy="false" mutable="false">
<key column="listA_id"/>
<list-index column="listA_index"/>
<many-to-many class="C"/>
</list>
</class>
<class name="B" lazy="false">
<id name="id">
<generator class="org.hibernate.id.UUIDGenerator"/>
</id>
<list name="list" lazy="false" mutable="false">
<key column="listB_id"/>
<list-index column="listB_index"/>
<many-to-many class="C"/>
</list>
</class>
<class name="C" lazy="false">
<id name="id">
<generator class="org.hibernate.id.UUIDGenerator"/>
</id>
</class>
All 5 tables (one for each class and 2 for the many-many-relations) are created as expected. The problem appears when I execute some code like the following:
A a = new A();
B b = new B();
C c1 = new C();
C c2 = new C();
C c3 = new C();
<hibernatesession>.save(c1);
<hibernatesession>.save(c2);
<hibernatesession>.save(c3);
a.list.add(c1);
a.list.add(c2);
<hibernatesession>.save(a);
b.list.add(c1);
b.list.add(c3);
<hibernatesession>.save(b);
I followed the resulting SQL in a HSQL-log-file and found everything to be fine up until the last save. Saving b will result in the association between a and c1 being deleted from the many-many-tabel A_list. Fetching the objects a and b anew from the database will result in c1 and c3 being in b.list but only c2 in a.list.
Observations:
* There is no cascading in the game.
* switching the order of saving a/b will result in c1 getting deleted from the list of whoever gets saved first.
* Both lists are mapped with indexes.
* Both lists are mapped with different key/index-column names.
* hibernate deletes exactly those elements common to the lists
Can somebody explain me this behavior of hibernate and knows how to realize a respective mapping correctly?
Thx in advance!!!
Salsolatragus
Try adding a many-to-many mapping to Class C so that it is a bidirectional relationship. Perhaps by being explicit about the "parent" relationships, it will know to keep more than one relationship rather than delete the first one as you have explained.
<class name="C" lazy="false">
<id name="id">
<generator class="org.hibernate.id.UUIDGenerator"/>
</id>
<list name="listA" lazy="false" mutable="false" inverse="true">
<key column="listC_id"/>
<many-to-many class="A"/>
</list>
<list name="listB" lazy="false" mutable="false" inverse="true">
<key column="listC_id"/>
<many-to-many class="B"/>
</list>
</class>
Fixed the bug. Lessons learned: If you have strange correlations between certain Collections in hibernate, check first if you're accidentally using the same Java instance for them... A couple of hours pairDebugging thru hibernate at last led us to the right guess. Tricky thing. Problem solved.
Thx for you hint Brad!

Hibernate is updating instead of inserting, why?

I'm starting my adventure with Hibernate, so please be patient :)
I want to make mapping for two tables, for example A and B. The relation beetwen A and B is one-to-many.
I wrote this hbm.xml file:
<hibernate-mapping package="something">
<class name="A" table="A">
<id name="id" type="int" column="ID">
<generator class="native" />
</id>
<set name="setInA" sort="natural" cascade="all" lazy="false">
<key column="ANOTHER_ID"/>
<one-to-many class="B" />
</set>
</class>
<class name="B" table="B">
<id name="anotherId" type="int" column="ANOTHER_ID">
<generator class="native" />
</id>
</class>
</hibernate-mapping>
Of course I made also POJO classes A and B.
And now, when I try to do:
A a = new A();
Set<B> set = new TreeSet<B>();
set.add(new B());
a.setSetInA(set);
session.save(a);
Hibernate inserts new row to table A, but (what is the worst) is not inserting new row to B table, but only makes SQL Update on not existing row in B.
Can tell me anyone why it is happening? What I made wrong?
You should either persist B's objects firstly, or use Cascade option.
You can use Cascade without using annotations:
<set name="setInA" sort="natural" cascade="all" lazy="false" cascade="all">
<key column="ANOTHER_ID"/>
<one-to-many class="B" />
</set>
This will ensure that collection of B instances is inserted when you insert A.
Found this question while searching for causes of the same symptoms in my system. cascade="all" did not help.
In my case I solved this by adding a mapping to the list element, in this example class B.
Please note that the enclosing class (A in this example) also was versioned. Hibernate might require that versioning (used for optimistic locking) must be enabled for all nested elements. I haven't found any documentation to support this theory.

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.

Legacy mapping with hibernate

For my current project I have to map a legacy database using hibernate, but I'm running into some problems.
The database is setup using one 'entity' table, which contains common properties for all domain objects. Properties include (among others) creation date, owner (user), and a primary key which is subsequently used in the tables for the domain objects.
A simple representation of the context is as such:
table entity
- int id
- varchar owner
table account
- int accountid (references entity.id)
table contact
- int contactid (references entity.id)
- int accountid (references account.accountid)
My problem exhibits itself when I try to add a collection mapping to my account mapping, containing all contacts belonging to the account. My attempts boil down to the following:
<hibernate-mapping>
<class name="Contact" table="entity">
<id name="id" column="id">
<generator class="native" />
</id>
<join table="contact">
<key column="contactid"/>
<!-- more stuff -->
</join>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="Account" table="entity">
<id name="id" column="id">
<generator class="native" />
</id>
<bag name="contacts" table="contact">
<key column="accountid" />
<one-to-many class="Contact"/>
</bag>
<join table="account">
<key column="accountid"/>
<!-- more stuff -->
</join>
</class>
</hibernate-mapping>
However, when I try to fetch the account I get an SQL error, stating that the entity table does not contain a column called accountid. I see why this is happening: the mapping tries to find the accountid column in the entity table, when I want it to look in the contact table. Am I missing something obvious here, or should I approach this problem from another direction?
This looks to me like you actually need to be mapping an inheritance, using the Table Per Subclass paradigm.
Something like this:
<class name="entity" table="entity">
<id name="id" column="id">
...
</id>
<joined-subclass name="contact" table="contact">
<key column="contactid"/>
</joined-subclass>
<joined-subclass name="account" table="account">
<key column="accountid"/>
</joined-subclass>
</class>
That's approximate by the way - it's described in detail in section 9.1.2 of the Hibernate documentation (just in case you can't find it, it's called "Table per subclass").
Cheers
Rich

Categories