在含有外键的表中,要保存一个值到这个外键时:
逻辑思路:
需要先将jsp页面的值传到相应的action中,在这个action中需要引入这个外键的实体层和DAO层(DAO层只需set方法),在执行函数中对于外键的传值,应该先根据外键DAO层的方法来将这个外键传给外键的对象,然后将这个对象通过此表中的实体类中的方法保存到该表中。
jsp:
<div class="form-group has-warning"> <label class="control-label" for="inputWarning">请输入班级编号</label> <input name="studentclass" type="text" class="form-control" id="inputWarning"> </div>
action:
//变量(与外键相关的) private String studentclass = ""; private Classunit classunit; private ClassunitDAO classunitDAO; //函数 public String getStudentclass() { return studentclass; } public void setStudentclass(String studentclass) { this.studentclass = studentclass; } public Classunit getClassunit() { return classunit; } public void setClassunit(Classunit classunit) { this.classunit = classunit; } public void setClassunitDAO(ClassunitDAO classunitDAO) { this.classunitDAO = classunitDAO; } public String execute() throws Exception { System.out.println("执行add的action"); if(studentService.checkStudentnumber(getStudentnumber())) { return ERROR; } else { System.out.println(studentclass); studentex = new Student(); studentex.setStudentNumber(studentnumber); studentex.setStudentName(studentname); studentex.setStudentGender(studentgender); studentex.setStudentBirth(studentbirth); studentex.setStudentPassword(studentpassword); studentex.setStudentPhone(studentphone); studentex.setStudentAddress(studentaddress); classunit = classunitDAO.findclassunitnumber(studentclass); studentex.setClassunit(classunit); studentService.addStudent(studentex); } return SUCCESS; }
配置:
在spring的事务管理配置中需要将这个表需要注入的DAO和外键需要注入的DAO都配置上。
<!-- 新建学生 --> <bean id="StudentAddAction" class="com.zdr.action.StudentAddAction"> <property name="studentService" ref="StudentServiceImpl"/> <property name="classunitDAO" ref="ClassunitDAO"/> </bean>
否则会因为事务逻辑问题引起的无法识别action的500错误。