【hibernate框架】关系映射之一对一单向外键关联(XML实现)

前端之家收集整理的这篇文章主要介绍了【hibernate框架】关系映射之一对一单向外键关联(XML实现)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在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;
	}
}




StudentIdCard.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>



Student.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 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>
    </class>
</hibernate-mapping>



转载请注明出处: http://blog.csdn.net/acmman 原文链接:https://www.f2er.com/xml/297246.html

猜你在找的XML相关文章