1. 程式人生 > >Hibernate繼承對映之一_用一張表對映

Hibernate繼承對映之一_用一張表對映

這次給大家發的是hibernate的繼承對映,繼承對映的例項有很多:例如dog、cat都是animal的子類

這裡用的是文章Article、主題Topic和回覆Reply給大家做講解。

主題和回覆都是屬於文章的子類,本文是講解了怎麼用一張表來對映這三個類,並且包括了對映的除錯。

實體類:

Atricle.java

package i_hbm_extends;

import java.util.Date;

public class Article {
	private Integer id;
	private String title;
	private String context;
	private Date postTime;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContext() {
		return context;
	}
	public void setContext(String context) {
		this.context = context;
	}
	public Date getPostTime() {
		return postTime;
	}
	public void setPostTime(Date postTime) {
		this.postTime = postTime;
	}
}


Reply.java

package i_hbm_extends;

public class Reply extends Article{
	private int floor; // 樓層

	public int getFloor() {
		return floor;
	}

	public void setFloor(int floor) {
		this.floor = floor;
	}
	
}


Topic.java

package i_hbm_extends;

public class Topic extends Article{
	private int type; // 精華、置頂...

	public int getType() {
		return type;
	}

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


對映檔案:

Article.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                                   "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- This mapping demonstrates -->
<!-- 告訴hibernate需要找哪個表 -->
<hibernate-mapping package="i_hbm_extends">
	
	<!-- discriminator-value:用於鑑別是哪個類的值,表示值就是這個類,如果不寫,預設為類的全限定名 -->
	<class name="Article" table="t_article" discriminator-value="Article">
		<id name="id">
			<generator class="native"></generator>
		</id>
		
		<!-- 指定一個鑑別器 -->
		<discriminator type="string" column="class_"></discriminator>
		
		<property name="title" />
		<property name="context" type="text" length="20000"/>
		<property name="postTime" type="timestamp"/>
		
		<!-- 
			子類:Topic,每一段裡面,每一個子類只寫自己特有的資訊
			name:指的是子類的型別名稱
		-->
		<subclass name="Topic" discriminator-value="Topic">
			<property name="type"></property>
		</subclass>
		
		
		<!-- 
			子類:Reply,每一段裡面,每一個子類只寫自己特有的資訊
		-->
		<subclass name="Reply" discriminator-value="Reply">
			<property name="floor"></property>
		</subclass>
		
	</class>
</hibernate-mapping>