在hibernate中表之间存在一对一,一对多等关系,怎样配置这些属性的,下面来介绍一下这些知识
一对多关系:比如一个班级对用多个学生
班级实体类:
package entity;
import java.util.Set;
public class Clazz {
//实现1对多一个班级对应多个学生
private int id;
private String name;
private entity.Student Student=new Student();
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 entity.Student getStudent() {
return Student;
}
public void setStudent(entity.Student student) {
Student = student;
}
}
学生实体类:
package entity;
public class Student {
private int id;
private String name;
private float score;
private Clazz clazz;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public Clazz getClazz() {
return clazz;
}
public void setClazz(Clazz clazz) {
this.clazz = clazz;
}
public void setName(String name) {
this.name = name;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
}
班级对应的配置
<hibernate-mapping>
<class name="entity.Clazz" table="clazz">
<id name="id">
<generator class="native" />
</id>
<property name="name" column="clazz_name" type="string"/>
<set name="student" inverse="true">
<key>
<column name="cid"/>
</key>
<one-to-many class="entity.Student"/>
</set>
</class>
</hibernate-mapping>
学生对应的配置:
<hibernate-mapping>
<class name="entity.Student" table="student">
<id name="id">
<generator class="native" />
</id>
<property name="name" column="user_name" type="string"/>
<property name="score" column="user_score" type="float"/>
<many-to-one name="clazz" class="entity.Clazz" cascade="all">
<column name="cid"/>
</many-to-one>
</class>
</hibernate-mapping>
需要注意的是再班级和学生配置过程中属性的name要与实体之间对应。