类与类之间的继承关系,hibernate提供了三种映射策略。
InheritanceType.SINGE_TABLE :单表继承(在数据库中用同一张表存储具有继承关系的实体对象,通过不同的类型来区分父类与子类之间的关系)
InheritanceType.JOINED: 连接子类策略(在数据库中表示为用外键关联)
InheritanceType.TABLE_PER_CLASS: (每个子类对应一张数据库表模型)
(该篇只针对单表继承策略)
首先建表模型:
CREATE TABLE PERSION
(ID NUMBER(18),
NAME VARCHAR2(255),
SEX NUMBER(2),
TYPE NUMBER(2)
);
对应的实体模型:
父类:
package cn.com.httpclient;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
* 孩子,这是人类
* @author xiaomingtongxie
*
*/
@Entity
@Table(name = "PERSION")
@SequenceGenerator(name = "S_PERSION", sequenceName = "S_PERSION", allocationSize = 1)
//类继承方式,单表继承
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
//辨别者列,用于区分对应的实体
@DiscriminatorColumn(name = "type" ,discriminatorType = DiscriminatorType.INTEGER)
public class YPersion {
@Id
@GeneratedValue(generator = "S_PERSION", strategy = GenerationType.SEQUENCE)
private Long id;
/** 名字 */
private String name;
/** 性别 */
private Integer sex;
// /**类型*/
// private Byte type;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
// 人的类型
/** 工人 */
public static int TYPE_GR = 0;
/** 好人 */
public static int TYPE_GOOD = 1;
/** 坏人 */
public static int TYPE_BAD = 2;
}
子类:
package cn.com.httpclient;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* 人类的子类,好人
* @author xiaomingtongxie
*
*/
@Entity
@Table(name = "PERSION")
//辨别者列值,好人
@DiscriminatorValue("1")
public class YGoodPersion extends YPersion{
}
(回头再写,麻蛋,饿死了,去吃东西了)