Search code examples
javahibernateoopormhibernate-mapping

Hibernate query on superclass property


First of all, please forgive my ignorance in both Java and Hibernate, I'm studying different ORM solutions and am not a Java programmer.

1) Is it possible to map the following class hierarchy to a database table, with Person.name and Employee.name pointing to different columns?

abstract public class Person {
        private String name;
}

public class Employee extends Person {
        private String name;
}

2) Supposing that the answer to 1) is Yes, is there a way to create a HQL or Criteria query which would ask Hibernate to return Employee objects, with a criterion on Person.name?

Something like that:

SELECT e FROM Employee e WHERE e.super.name = "test";

Solution

  • 1) Yes. This can be accomplished via a MappedSuperclass, and annotating your columns

    @MappedSuperclass
    abstract public class Person { 
      @Column(name="PERSON_NAME")
      private String name; 
    }
    @Entity
    public class Employee extends Person {
            @Column(name="EMPLOYEE_NAME")
            private String name;
    }
    

    2) No. Not without changing the attribute names of one of either Person or Employee. You could however query for all person objects with that name and cast the results to Employees. Another option would be to use Native SQL to query the column you want, again probably not ideal.

    SELECT p FROM Person p WHERE p.name = "test";