Hibernate4继承映射

Hibernate 支持三种基本的继承映射策略:

1、单表继承:每棵类继承树使用一个表
2、具体表继承:每个子类一个表
3、类表继承:每个具体类一个表(有一些限制)


三种方式的比较:
1、所有类映射成一张表会产生数据冗余(不过这是通常采用的方法)
2、每个类映射成一张表会有效率问题,比如是三层或四层结构时,对于查询或更新会发出很多sql语句
3、具体类映射成表的缺点是主键不能自增

结论:使用第一种方式

/** 动物 */
public class Animal {

	private Integer id;
	private String name;
	private String type;

	//getter and setter
}
/** 猪 */
public class Pig extends Animal {

	private Double weight;
	
	//getter and setter
}
/** 鸟 */
public class Bird extends Animal{

	private String color;
	
	//getter and setter
}
<hibernate-mapping package="org.monday.hibernate4.domain">
	<class name="Animal" table="tbl_animal">
		<id name="id">
			<generator class="identity" />
		</id>
		<!-- 辨别者列 -->
		<discriminator column="type" type="string" />
		<property name="name" />
		<!-- 子类 -->
		<subclass name="Pig" discriminator-value="p">
			<property name="weight" />
		</subclass>
		<!-- 子类 -->
		<subclass name="Bird" discriminator-value="b">
			<property name="color" />
		</subclass>
	</class>
</hibernate-mapping>

 下面是基于注解的

/** 动物 */
@Entity
@Table(name = "tbl_animal")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
@DiscriminatorValue("a")
public class Animal {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;

	private String name;

	// getter and setter
}
/** 猪 */
@Entity
@DiscriminatorValue("p")
public class Pig extends Animal {

	private Double weight;
	
	//getter and setter
}
/** 鸟 */
@Entity
@DiscriminatorValue("b")
public class Bird extends Animal {

	private String color;

	// getter and setter
}

猜你喜欢

转载自1194867672-qq-com.iteye.com/blog/1730876