文档详情

jsp程序设计入门沈泽刚、秦玉平编著的javaweb第二版第11章Hibernate框架基础剖析.ppt

发布:2017-03-15约2.46万字共188页下载文档
文本预览下载声明
2. 外键关联 一对一的外键关联是指两个实体各自有自己的主键,但其中一个实体用外键引用另一个实体。例如,Student实体对应表的主键是id,Card实体对应表的主键是id,设在card表中还有一个studentId属性,它引用student表的id列,在card表中studentId就是外键。 一对一关联实际是多对一关联的特例,因此在外键所在的实体的映射文件中使用many-to-one元素来建立关联。 2. 外键关联 若仍建立双向关联,则Student.hbm.xml无需修改,修改后的Card.hbm.xml如下: hibernate-mapping package=com.hibernate class name=Card table=card lazy=true id name=id column=id generator class=identity !-- 这里不再是foreign了 -- param name=propertystudent/param /generator /id property name=cardNo type=long column=cardNo / property name=major type=string column=major / property name=balance type=double column=balance / 2. 外键关联 many-to-one name=student class=com.hibernate.Student column=studentId unique=true / /class /hibernate-mapping 11.7.6 多对多关联映射 学生(Student)实体和课程(Course)实体是最典型的多对多关联。可以设置单向的多对多关联,也可以设置双向的多对多关联。 本节主要讲解设置双向的多对多关联。在映射多对多关联时,需要另外使用一个连接表,如图11.5所示。 11.7.6 多对多关联映射 Student - id:Long - studentNo: String - studentName:String - sage:int - major:String - courses:SetCourse Course - id:Long - courseName: String - credit:int - balance:double - students:SetStudent student-course - student_id:Long - course_id: Long - grade:int 11.7.6 多对多关联映射 下面是连接表的定义: CREATE TABLE student_course ( student_id bigint NOT NULL, course_id bigint NOT NULL, grade integer DEFAULT 0, CONSTRAINT sc_pkey PRIMARY KEY (student_id, course_id) ) 11.7.6 多对多关联映射 对于双向的多对多关联,要求关联的双方实体类都使用Set集合属性,两端都增加集合属性的setter和getter方法。 11.7.6 多对多关联映射 在Student类中增加的代码如下。 private SetCourse courses= new HashSetCourse(); public void setCourses(SetCourse courses){ this.courses = courses; } public SetCourse getCourses(){ return courses; } 11.7.6 多对多关联映射 下面是课程类Course的定义。 public class Course{ ????private Long id; ????private String courseName; ????private double ccredit;? private SetStudent students = new HashSetStudent(); 11.7.6 多对多关联映射 对于双向多对多关联,需要在两端实体类的映射文件中都使用set元素定义集合属性并在其中使用many-to-many元素进行多对多映射。 在Student.hbm.xml文件中添加下面代码。 set name=courses table=stud
显示全部
相似文档