I actually map a very similar, simple inheritance hierarchy in one of the Hibernate3 tutorials on my website. Fortunately, I us JPA as well. Here's the scenario Java classes:
The mappings looked like this:
Ancestor without Mapping Strategy
Code:
package com.examscam.mappings;
import javax.persistence.*;
@Entity
public class Ancestor {
private Long id;
private String nationality;
@Id
@GeneratedValue
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
public String getNationality() {return nationality;}
public void setNationality(String nationality) {
this.nationality = nationality;
}
}
Parent Java Class
Code:
package com.examscam.mappings;
import javax.persistence.*;
@Entity
public class Parentextends Ancestor{
private String lastName;
public String getLastName() {return lastName;}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Child Java ClassCode:
package com.examscam.mappings;
import javax.persistence.*;
@Entity
public class Parentextends Ancestor{
private String lastName;
public String getLastName() {return lastName;}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Then I just added the following to the ancestor class:
Code:
@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public class Ancestor { }
Running the code in a main method looked like this:
Code:
public static void main(String args[]) {
Ancestor a = new Ancestor();
a.setNationality("Korean");
Parent p = new Parent();
p.setNationality("Jewish"); p.setLastName("Steinberg");
Child c = new Child();
c.setNationality("Irish");
c.setLastName("McKenzie");
c.setFirstName("Cameron");
Session session = HibernateUtil.beginTransaction();
session.save(a); session.save(p); session.save(c);
HibernateUtil.commitTransaction();
}
And when it was done, here was the tables and results:
And of course, the SQL:
Code:
Hibernate:
insert into Ancestor (nationality, DTYPE) values (?, 'Ancestor')
Hibernate:
insert into Ancestor (nationality, lastName, DTYPE) values (?, ?, 'Parent')
Hibernate:
insert into Ancestor (nationality, lastName, firstName, DTYPE) values (?, ?, ?, 'Child')