可以用Student和StuIdCard来举例:
1、Student.java类:
package com.bjsxt.hibernate; public class Student { private int id; private String name; private int age; private String sex; private boolean good; public boolean isGood() { return good; } public void setGood(boolean good) { this.good = good; } 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; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
2.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> </class> </hibernate-mapping>
3、建StuIdCard.java
package com.bjsxt.hibernate; 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; } }
4、建相应的xml文件:StuIdCard.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.StuIdCard"> <id name="id"> <generator class="native"></generator> </id> <property name="num"/> <many-to-one name="student" column="studentId" unique="true"></many-to-one> </class> </hibernate-mapping>
5、<many-to-one name="student" column="studentId" unique="true"></many-to-one>
这句话意思为多对一,如果站在StuIdCard的方面,many-to-one意味多个学生证对应一个学生,因不是一对一,所以后面加了个unique="true"即保证IdCard的唯一,这样就变成一对一的单向关联了,column="studentId"即用column来定义用哪个字段作为外键关联 的字段。
6、在hibernate.cfg.xml中加入:
<mapping resource="com/bjsxt/hibernate/Student.hbm.xml"/> <mapping resource="com/bjsxt/hibernate/StuIdCard.hbm.xml"/>原文链接:https://www.f2er.com/xml/298222.html