問題:
在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");
- }