一、双边的一对多,多对一配置(单边只要去掉一方就可以了) ,班级学生为例
学生类(get set 方法略)
public class Student100 implements java.io.Serializable {
// Fields
private Integer sno;
private Class100 class100;
private String name;
// Constructors
/** default constructor */
public Student100() {
}
/** minimal constructor */
public Student100(Integer sno) {
this.sno = sno;
}
/** full constructor */
public Student100(Integer sno, Class100 class100, String name) {
this.sno = sno;
this.class100 = class100;
this.name = name;
}
}
班级类
public class Class100 implements java.io.Serializable {
// Fields
private Integer id;
private String name;
private Set students = new HashSet();
// Constructors
/** default constructor */
public Class100() {
}
/** minimal constructor */
public Class100(Integer id) {
this.id = id;
}
/** full constructor */
public Class100(Integer id, String name, Set students) {
this.id = id;
this.name = name;
this.students = students;
}
}
配置文件 Student100.hbm.xml
<hibernate-mapping>
<class name="com.sunny.entity100.Student100" table="student100" catalog="test100">
<id name="sno" type="java.lang.Integer">
<column name="sno" />
<generator class="identity"></generator>
</id>
<many-to-one name="class100" class="com.sunny.entity100.Class100">
<column name="class_id" /><!-- Student100表中将会生成一个外键class_id 引用Class100中的id -->
</many-to-one>
<property name="name" type="java.lang.String">
<column name="name" length="20" />
</property>
</class>
</hibernate-mapping>
配置文件 Class100.hbm.xml
<hibernate-mapping>
<class name="com.sunny.entity100.Class100" table="class100" catalog="test100">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity"></generator>
</id>
<property name="name" type="java.lang.String">
<column name="name" length="20" />
</property>
<set name="students" lazy="true" fetch="join" inverse="true"><!-- lazy默认为true既打开延时加载 -->
<key>
<column name="class_id" /><!-- 定义集合所对应的数据库表的外键,class_id位student表的外键 -->
</key>
<one-to-many class="com.sunny.entity100.Student100" />
</set>
</class>
</hibernate-mapping>