HIBERNATE一对多配置实例
1. 环境:假定班级和学生是一对多的关系,班级是一,学生是多,对应表格分别是:zlass ,student
2. 创建Zlass和Student对象
班级实体类:
//Zlass对象--------------------------------------------------------- public class Zlass{ private String class_id; private String class_name; private java.util.Set students; public void setId(String id){ this.class_id = id; } public void setClassName(String className){ this.class_name = className; } public void setStudents(java.util.Set students){ this.students = students; } public String getId(){ return class_id; } public String getClassName(){ return class_name; } public java.util.Set getStudents(){ return students; } }
学生对象实体类:
//学生对象 public class Student{ private String student_id; private String name; private Address address; private java.util.Set events; private java.util.Set lessons; private Zlass zlass; public Zlass getZlass(){ return zlass; } public String getStudentId(){ return student_id; } public String getName(){ return name; } public Address getAddress(){ return address; } public java.util.Set getEvents(){ return events; } public java.util.Set getLessons(){ return lessons; } public void setZlass(Zlass zlass){ this.zlass = zlass; } public void setStudentId(String studentId){ this.student_id = studentId; } public void setName(String name){ this.name = name; } public void setAddress(Address address){ this.address = address; } public void setEvents(java.util.Set events){ this.events =events; } public void setLessons(java.util.Set lessons){ this.lessons = lessons; } }
配置文件:
班级映射文件:
//----------Zlass.hbm.xml--------------- <hibernate-mapping package="com.softWork.school"> <class name="Zlass" table="class"> <id name="id" column="id" type="string" length="20"> <generator class="assigned"/> </id> <property name="className" column="class_name" type="string" length="200"/> <set name="students" inverse="false" cascade="all"> <key column="class_id"/> <one-to-many class="Student"/> </set> </class> </hibernate-mapping>
学生实体映射文件:
//-------------Student.hbm.xml--------------- <hibernate-mapping package="com.softWork.school"> <class name="Student" table="student"> <id name="studentId" column="student_id" type="string" length="20"> <generator class="assigned"/> </id> <property name="name" type="string" length="20"/> <component name="address" class="Address"> <property name="state" column="state" type="string"></property> <property name="city" column="city" type="string"></property> <property name="street" column="street" type="string"></property> </component> <set name="events" inverse="false" cascade="all"> <key column="student_id"></key> <one-to-many class="Event"></one-to-many> </set> <set name="lessons" table="student_lesson"> <key column="student_id"/> <many-to-many class="Lesson" column="lesson_id" /> </set> <many-to-one name="zlass" column="class_id" class="Zlass"/> </class> </hibernate-mapping>
以上使用的是班级一端维护关系,并级连操作
3. 使用级连操作数据
1) 新增班级