Hibernate version:
Hibernate 3.2.2 GA
Hibernate Annotations 3.3.0 GA
Mapping documents:
Using JPA annotations
Code:
@Entity
// Defaults:
// Inheritance strategy = single table
// Discriminator column = DTYPE
// Discriminator type = string
// Discriminator value = class name
public class Base implements Serializable
{
@Id
protected String id;
protected String baseField;
// Getters and Setters omitted
}
@Entity
public class Child extends Base
{
protected String childField;
// Getters and Setters omitted
}
Code between sessionFactory.openSession() and session.close():Using Spring HibernateDaoSupport class
Code:
HibernateTemplate ht = getHibernateTemplate();
Base base = new Base();
base.setId(1);
base.setBaseField("baseValue");
ht.save(base);
Child child = new Child();
child.setId(2);
child.setBaseField("baseValue");
child.setChildField("childValue");
ht.save(child);
DetachedCriteria criteria = DetachedCriteria.forClass(Base.class);
criteria.add(Restrictions.eq("baseField", "baseValue"));
List<Base> result = ht.findByCriteria(criteria);
Name and version of the database you are using:
HSQLDB 1.8.0.8
The generated SQL (show_sql=true):
Hibernate: insert into Base (baseField, DTYPE, id) values (?, 'Base', ?)
Hibernate: insert into Child (baseField, childField, DTYPE, id) values (?, ?, 'Child', ?)
Hibernate: select this_.id as id5_0_, this_.baseField as baseField5_0_, this_.childField as childField5_0_, this_.DTYPE as DTYPE5_0_ from Base this_
I have a Base entity with a Child entity that sublasses it. If I execute the code above, I get two results (the Base instance and the Child instance). How can I do a query that only returns instances of Base and not Child? I tried adding Restrictions.eq("class", "Base") to the criteria, which seems to work, but I get the feeling there is a more sophisticated solution. Thanks in advance for your help.