【hibernate框架】一对一双向外键关联(XML实现)

前端之家收集整理的这篇文章主要介绍了【hibernate框架】一对一双向外键关联(XML实现)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以Student与StuIDCard一对一双向关联为例,说一下用XML实现两者的一对一双向关联。

学生与学生证之间的关联关系。
Student.java:
package cn.edu.hpu.model;


public class Student {
	private int id;
	private String name;


	private int age;
	
	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;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}



StudentIdCard.java:
package cn.edu.hpu.model;


public class StuIDCard {
	private int id;
	private String num;
	private Student student;//与学生实体类单向关联


	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getNum() {
		return num;
	}
	public void setNum(String num) {
		this.num = num;
	}
	public Student getStudent() {
		return student;
	}
	public void setStudent(Student student) {
		this.student = student;
	}
}


Student.hbm.xml:
<pre name="code" class="html"><?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">


<hibernate-mapping package="cn.edu.hpu.model">
    <class name="Student" table="student" dynamic-update="true">
	<id name="id" column="id">
		<generator class="native"></generator>  
	</id>  
        <property name="name"></property>
        <property name="age"></property>
        <one-to-one name="stuIDCard" property-ref="student"></one-to-one>
    </class>
</hibernate-mapping>
 


StuIDCard.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">


<hibernate-mapping>
    <class name="cn.edu.hpu.model.StuIDCard">
        <id name="id">
            <generator class="native"></generator>
        </id>


        <property name="num"/>
        <!-- 站在当前类的立场考虑,设外键关联的时候设置的 many-to-one-->
        <!-- many-to-one多个学生证对应一个学生 unique="true"唯一为true,必须保证id唯一,就变成了一对一-->
        <!--column定义哪个字段做为外键关联类字段-->
        <many-to-one name="student" column="id" unique="true"></many-to-one>


    </class>
</hibernate-mapping>


转载请注明出处:http://blog.csdn.net/acmman

原文链接:https://www.f2er.com/xml/297242.html

猜你在找的XML相关文章