hibernate中继承层次的小结

   hibernate中的继承关系的处理手法有三种,下面小结之,外加上ejb3的这方面的描述.

  比如有个动物类animal,假设有如下属性
    private int id;
 private String sex;

  而它的子类比如bird鸟类,有另外的属性hight,

    它的子类比如pig类,有另外的属性weight,

那么三类办法来处理,在hibernate中
   1) 每个子类对应一张表

   bird类 有id,sex,hight属性

   pig 类有 id,sex,weight属性

     它们有各自的xxx.hbm.xml了

 

2)  table per subclass
     这个其实就是把公共属性放到父类中去,各子类只保留其子类特有的属性,并且通过id等进行关联,比如
  animal类里,还是有id,sex属性
  bird类里,有id,hight属性
  pig类里,有id,weight属性
      而animal.hbm.xml中的设置为
    <joined-subclass name="pig" table="pig>
       <key column="id>
      <prperty name="weight"/>

    <joined-subclass name="bird" table="pig>
       <key column="id>
      <prperty name="height"/>

  

3) 冗余分类
      比如animal表如下
       id    sex height  weight

      好明显这里是有冗余的哦,但可以加个标志来区分,比如p为pig类,b为bird类
    下面看anmimal.hbm.xml
     ...........

     <discriminator column="type" type="string">
   

      <subclass name="pig" discriminator-value="P">
         <prperty name="weight"/>

</subclass>

   <subclass name="bird" discriminator-value="b">
         <prperty name="height"/>

</subclass>

 

  再看在ejb3里如何玩:
   animal.java
  

import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="animalType")
@DiscriminatorValue("A")
public class Animal {
 
 @Id
 private int id;
 private String sex;
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getSex() {
  return sex;
 }
 public void setSex(String sex) {
  this.sex = sex;
 }
}

 

   bird.java
 

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

@Entity
@DiscriminatorValue("B")
public class Bird extends Animal{
 private int height;

 public int getHeight() {
  return height;
 }

 public void setHeight(int height) {
  this.height = height;
 }
}

 

pig.java
 

@Entity
@DiscriminatorValue("P")
public class Pig extends Animal{
 private int weight;

 public int getWeight() {
  return weight;
 }

 public void setWeight(int weight) {
  this.weight = weight;
 }
}

   

   

你可能感兴趣的:(Hibernate,xml)