I am facing a strange problem and am unable to find a solution. I am trying to load a set of objects in Java using Hibernate from MySQl db.
These is a simplified version of my hibernate mappings and code:
<class name="org.Foo.Class1" table="class_profile" >
<cache usage="read-write"/>
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="amount" column="amount"/>
</class>
<class name="org.Foo.Class2" table="class_profile" >
<cache usage="read-write"/>
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="amount" column="amount"/>
</class>
This is my code to access, the objects:
public List<Class1> loadProfiles(final List<Integer> pIds)
{
return (List<Class1>)getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
return session.createQuery("from Class1 il where il.id in (:idList)")
.setParameterList("idList", pIds)
.list();
}
});
}
Now, when I run my code
List<Class1> profiles = fooService.loadProfiles(Arrays.asList(3,4));
I get FOUR objects (instead of 2) in the list profiles – TWO Class1 objects and TWO Class2 objects. Where are the TWO Class2 objects coming from?
When you have inheritance between two entities, Hibernate needs to be able to tell which class a particular database row is supposed to represent. You do this by adding a discriminator class to the table that tells it which class to build to represent the row.
Class2 needs to be declared using a
<subclass/>element nested inside Class1 that specifies what value of what column is used to tell them apart.Detials here: http://docs.jboss.org/hibernate/orm/3.5/reference/en/html/inheritance.html#inheritance-tableperclass