Abdullah Jibaly
Abdullah Jibaly

Reputation: 54790

Hibernate query by abstract class inconsistent

I've run into a strange inconsistency between the behavior of Criteria and HQL queries. Simplified domain model:

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@Table("TITLES")
public abstract class ParentGroup {}

// no JPA annotations
public abstract class ParentTitle extends ParentGroup {}

@Entity
@DiscriminatorValue("SUB_CHILD")
public class SubTitle extends ParentTitle {}

Here's the test that shows the strange behavior:

@Test
public void testQueryByAbstractSuperClass() {
    List<ParentTitle> list = session.createCriteria(ParentTitle.class).list();
    assertEquals(1, list.size()); //passes

    list = session.createQuery("from ParentTitle").list(); //exception thrown
    assertEquals(1, list.size());
}

With the following exception:

org.hibernate.hql.ast.QuerySyntaxException: ParentTitle is not mapped [from ParentTitle]

Why does the HQL query not work?

Upvotes: 2

Views: 2238

Answers (1)

Mikko Maunu
Mikko Maunu

Reputation: 42094

Criteria solves exact type of the class from the ParentTitle.class. It doesn't matter is it entity or other class.

Also for HQL in the case of entities full path is not needed, because there can be only entity named ParentTitle.

But what HQL query cannot solve is which non-entity class you mean with "from ParentTitle", because you could have more than one ParentTitle classes which are extended by different entities. Thats why for non-entity class you have to provide also package:

list = session.createQuery("from something.somewhere.ParentTitle").list();

Upvotes: 1

Related Questions