ORM--继承--Hibernate4.0注解版

类的继承关系在Hibernate中有三种表现方式。

1.每个具体类一张表,简单的说就是每个子类都对应不同的表,分表保存父类的属性与子类的属性

@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)指明了继承映射的策略,如果父类使用abstract进行修饰,将不映射父类。

Flight类与Jet类分别映射到不同的表上。

Flight
id name

Jet
id name type



@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
//public abstract class Flight {
public class Flight {

	private String id;
	
	@Id
	@GeneratedValue(generator = "flight-uuid")
	@GenericGenerator(name = "flight-uuid", strategy = "uuid")
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
}
@Entity
public class Jet extends Flight  {


 private String type;


 public String getType() {
 return type;
 }


 public void setType(String type) {
 this.type = type;
 }
}

2.子类的属性保存到独立的表中,父类的属性,保存到父类的表中。

cat
id name

domesticcats
id type


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

	private String id;
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setId(String id) {
		this.id = id;
	}

	@Id
	@GeneratedValue(generator = "cat-uuid")
	@GenericGenerator(name = "cat-uuid", strategy = "uuid")
	String getId() {
		return id;
	}
}

@Entity
@PrimaryKeyJoinColumn(name="CAT")
public class DomesticCat extends Cat {
	private String catType;

	public String getCatType() {
		return catType;
	}

	public void setCatType(String catType) {
		this.catType = catType;
	}
}

3.单表继承。父类与子类映射到同一张表通过鉴别值来区别子类对象。

@DiscriminatorColumn定义了鉴别值的列属性。@DiscriminatorValue则指明了具体类的鉴别值。

payment
id amount cardtype paymentType


@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
	    name="paymentType",
	    discriminatorType=DiscriminatorType.STRING
)
@DiscriminatorValue("Payment")
public class Payment extends IdEntity {
	
	private BigDecimal amount;

	public BigDecimal getAmount() {
		return amount;
	}

	public void setAmount(BigDecimal amount) {
		this.amount = amount;
	}
}


@Entity
@DiscriminatorValue("CreditPayment")
public class CreditPayment extends Payment {

	private String cardtype;

	public String getCardtype() {
		return cardtype;
	}

	public void setCardtype(String cardtype) {
		this.cardtype = cardtype;
	}

}


你可能感兴趣的:(ORM--继承--Hibernate4.0注解版)