Monday, January 2, 2012

Inheritance Mapping

Basically there are 3 types of inheritance mapping. We may use those methods suitably.
  • SINGLE_TABLE (default)
  • JOINED
  • TABLE_PER_CLASS
Model


  • Single Table inheritance (default strategy) 
Classes
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;


@Entity
public class Project {

 private int projectID;
 private String projectName;

 @Id
 @GeneratedValue
 public int getProjectID() {
  return projectID;
 }

 public void setProjectID(int projectID) {
  this.projectID = projectID;
 }

 public String getProjectName() {
  return projectName;
 }

 public void setProjectName(String projectName) {
  this.projectName = projectName;
 }

}
Classes
import javax.persistence.Entity;


@Entity
public class Module extends Project {

 private String moduleName;

 public String getModuleName() {
  return moduleName;
 }

 public void setModuleName(String moduleName) {
  this.moduleName = moduleName;
 }

}
Classes
import javax.persistence.Entity;


@Entity
public class Task extends Module {

 private String taskName;

 public String getTaskName() {
  return taskName;
 }

 public void setTaskName(String taskName) {
  this.taskName = taskName;
 }

}
Result
  • Joined inheritance
in this strategy we need to use special annotation called @Inheritance
@Inheritance(strategy=InheritanceType.JOINED)
We have to put this annotation for the top class in the inheritance hierarchy.

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public class Project {

 private int projectID;
 private String projectName;

 @Id
 @GeneratedValue
 public int getProjectID() {
  return projectID;
 }
................
................
................

Result :

  •  TABLE_PER_CLASS Strategy


0 comments:

Post a Comment

© kani.stack.notez 2012 | Blogger Template by Enny Law - Ngetik Dot Com - Nulis