简体   繁体   中英

hibernate joined strategy inheritance and polymorphism

In hibernate, when I use the joined strategy. does hibernate support polymorphism?

    for example:

        @Entity
        @Table(name = "PERSON")
        @Inheritance(strategy=InheritanceType.JOINED)
        public class Person {

            @Id
            @GeneratedValue
            @Column(name = "PERSON_ID")
            private Long personId;

            @Column(name = "FIRSTNAME")
            private String Fullname;

            public Person() {

            }
            public Person(String fullname) {
                this.Fullname= fullname
            }
        }

and the derived class:

    @Entity
    @Table(name="EMPLOYEE")
    @PrimaryKeyJoinColumn(name="PERSON_ID")
    public class Employee extends Person {

        @Column(name="department_name")
        private String departmentName;

        public Employee() {
        }

        public Employee(String fullname, String departmentName,) {
            super(fullname);       
            this.departmentName = departmentName;
        }
    }

also all the fields include the getter and setters.
so in my main, when I'll do this:

session.beginTransaction();
person e = new Employee();
e.setFullname("james");
e.setdepartmentName("R&D");
session.getTransaction().commit();

I know for a fact that if e was of Employee type, hibernate would have created a row for both Employee and Person tables. but for this example will hibernate generate queries for person and employee? in other words, will hibernate support the polymorphic behavior?

When I understand you question correctly than you want to know if hibernate does in that case automtically return Employees when you query for all Persons. Additionally if it inserts an Employee when the object is declared as Person p = new Employee().

Short answer to both yes. More detailed. The insert operation is based on the actual type of the object and not on exactly the type written in your sourcecode. Related to querying of Persons. Hibernate does left outer join all subtypes so you will get also Employess back when you do the following:

Query query = session.createQuery("From Person ");
List<Person> persons = query.getResultList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM