在上一篇博客内容的基础上做了以下修改,即可实现。


注解方式:


package com.bjsxt.hibernate;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.Id;

import javax.persistence.OneToOne;

@Entity

public class Wife {

    private int id;

    private String name;

    ​private Husband husband;

    @OneToOne(mappedBy="wife")//加上后边括号内容可以防止生成多余的键字段,表示husband中的哪个字段已经做了映射,只要和其关联即可。

    public Husband getHusband() {

        return husband;

    }

    public void setHusband(Husband husband) {

        this.husband = husband;

    }

    @Id

    @GeneratedValue

    public int getId() {

        return id;

    }

    public void setId(int id) {

        this.id = id;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }


}


xml方式:


在Student类中也要添加private StuIdCard stuIdCard属性,然后在上一篇博客的基础上修改以下内容

Student.hbm.xml


<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

        "​​http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"​​​​>

<hibernate-mapping>

    <class name="com.bjsxt.hibernate.Student" dynamic-update="true">

        <id name="id">

            <generator class="native"></generator>

        </id>


        <property name="name"></property>

        <property name="age" />

        <property name="sex" />

        <property name="good" type="yes_no"></property>

        ​<one-to-one name="stuIdCard" property-ref="student"></one-to-one>
​    </class>


</hibernate-mapping>