hibernate 一对一外键关联映射

 

Hibernate 一对一外键关联映射需要使用<many-to-one>标签达到目的。关系数据库会在many的一方增加一个关联字段,也就是外键。

 

  • JAVA类:

 

public class Person1 {
	private String id;
	private String personName;
	private String sex;
	private Date birthday;
	private IdentityCard1 identityCard;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPersonName() {
		return personName;
	}
	public void setPersonName(String personName) {
		this.personName = personName;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public IdentityCard1 getIdentityCard() {
		return identityCard;
	}
	public void setIdentityCard(IdentityCard1 identityCard) {
		this.identityCard = identityCard;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	
	@Override
	public String toString(){
		return this.id+"---"+this.getPersonName()+"---"+this.getSex()+"---"+this.getIdentityCard().getCardNum()+"---"+this.getIdentityCard().getEffectiveDate();
	}
}

public class IdentityCard1 {
	private String cardNum;
	private Date effectiveDate;
	private Person1 person;
	public String getCardNum() {
		return cardNum;
	}
	public void setCardNum(String cardNum) {
		this.cardNum = cardNum;
	}
	public Date getEffectiveDate() {
		return effectiveDate;
	}
	public void setEffectiveDate(Date effectiveDate) {
		this.effectiveDate = effectiveDate;
	}
	public Person1 getPerson() {
		return person;
	}
	public void setPerson(Person1 person) {
		this.person = person;
	}
}

 

  • 映射文件:
<hibernate-mapping>
    <class name="com.woo.demo.hibernate.domain.Person1" table="PERSON1">
        <id name="id" type="string">
            <column name="ID" />
        	<generator class="assigned"/>
        </id>
        <property name="personName" column="person_name" type="string" length="128" not-null="true" update="false"/>
        <property name="sex" type="string" column="sex" length="1" not-null="true" update="false"/>
        <property name="birthday" column="birthday" type="date"/>
		<many-to-one name="identityCard" column="identity_card" cascade="save-update" unique="true" lazy="false"/>
    </class>
</hibernate-mapping>


<hibernate-mapping>
    <class name="com.woo.demo.hibernate.domain.IdentityCard1" table="IDENTITYCARD1">
        <id name="cardNum" column="card_num" type="string" length="32">
            <generator class="assigned"/>
        </id>
        <property name="effectiveDate" column="effective_date" type="date"/>
        <one-to-one name="person"/>
    </class>
</hibernate-mapping>

 

外键关联也可以采用单向关联,单向关联时将IdentityCard中的one-to-one标签删掉,这样IdentityCard实体就不会维护映射关系,查询IdentityCard实体,从中获取Person对象时,为null值。

 

  • 数据库结构


hibernate 一对一外键关联映射_第1张图片

你可能感兴趣的:(数据结构,Hibernate)