问题:
在Student中添属性SC(SC表示课程表);
Student student = new Student();
SC sc = new SC();
student.setSC(sc);
在hibernate配置文件中设置cascade=true,
getHibernateTemplate.save(student);
更新与插入类试;
getHibernateTemplate.update(student);
解决方案:
-
- 学生Student.hbm.xml:
- <hibernate-mapping>
- <class name="com.ssh.Student" table="student" schema="dbo" catalog="sshcourse">
- <id name="stuId" type="integer">
- <column name="stu_id" />
- <generator class="native" />
- </id>
- <property name="stuName" type="string">
- <column name="stu_name" length="50" />
- </property>
- <property name="stuPwd" type="string">
- <column name="stu_pwd" length="50" />
- </property>
- <set name="courses"
- table="course_student_table"
- cascade="save-update"
- inverse="false"
- lazy="false">
- <key column="stu_id"></key>
- <many-to-many class="com.ssh.Course" column="cou_id"></many-to-many>
- </set>
- </class>
- </hibernate-mapping>
- 课程Course.hbm.xml:
- <hibernate-mapping>
- <class name="com.ssh.Course" table="course" schema="dbo" catalog="sshcourse">
- <id name="couId" type="integer">
- <column name="cou_id" />
- <generator class="native" />
- </id>
- <property name="couName" type="string">
- <column name="cou_name" length="50" />
- </property>
- <property name="couDis" type="string">
- <column name="cou_dis" length="50" />
- </property>
- <set name="students"
- table="course_student_table"
- cascade="save-update"
- inverse="true">
- <key column="cou_id"></key>
- <many-to-many class="com.ssh.Student" column="stu_id"></many-to-many>
- </set>
- </class>
- </hibernate-mapping>
- cascade=true表设置级联,即插入学生信息同时也插入选课信息。
- <set name="courses"
- table="course_student_table"
- cascade="save-update"
- inverse="false"
- lazy="false">
- <key column="stu_id"></key>
- <many-to-many class="com.ssh.Course" column="cou_id"></many-to-many>
- </set>
- <set name="students"
- table="course_student_table"
- cascade="save-update"
- inverse="true">
- <key column="cou_id"></key>
- <many-to-many class="com.ssh.Student" column="stu_id"></many-to-many>
- </set>
实例:
- inverse="false" 表示为主控方,主控方负责维护关联关系,一般在一对多关系中,把多的一方设置为inverse="false"。lazy="false表示是延迟加载,当为true时,启动延迟加载,如两个关联a,b不延迟加载时可能加载a时候,也把b加载了,但你可能没用b,只用a了,这就造成了浪费,延迟加载时表示用到b时才加载。
- 删除例子
- public ActionForward execute(ActionMapping mapping, ActionForm form,
- HttpServletRequest request, HttpServletResponse response) {
- // TODO Auto-generated method stub
- CourseID courseid=(CourseID)form;
- Student student=studao.findById((Integer)(request.getSession().getAttribute("stuid")));
- if(courseid.getCourses().length>0)
- {
- for(int i=0;i<courseid.getCourses().length;i++)
- {
- Integer cid=new Integer(courseid.getCourses()[i]);
- Course course=coudao.findById(cid);
- student.getCourses().remove(course);
- System.out.println("this is test1 sdfsdfg");
- System.out.println(cid);
- }
- }
- else
- {
- System.out.println("null");
- }
- studao.delete(student);
- return mapping.findForward("success");
- }