部门dept的修改
会使用到mybatis的动态标签,if
,choose
if标签
- 根据值编写条件,如果条件成立,拼接sql否则不拼接
- if标签的test属性必填,一般只用true或false作为结果。
- 判断条件property != null或 property == null,适用于任何类型的字段,用于判断属性值是否为空。
- 当有多个判断条件时,使用and或or
- 使用案例
<if test="userName != null and userName != ''">
AND user_name =#{userName}
</if>
<if test="userEmail != null and userEmail != ''">
AND user_email = #{userEmail}
</if>
choose标签
- 相当于switch语句
- 使用案例
<choose>
<when test="id != null">
AND id = #{id}
</when>
<when test="userName != null and userName != ''">
AND user_name = #{userName}
</when>
<otherwise>
AND 1 = 2
</otherwise>
</choose>
修改部门的代码
TestDeptService
@Test
public void test05(){
String deptId="100101";
Dept dept=service.findById(deptId);
dept.setDeptName("董事会");
dept.setCompanyName("吉首大学");
dept.setCompanyId("1");
Dept parent=new Dept();
parent.setDeptId("100");
dept.setParent(parent);
dept.setState(0);
service.updateDept(dept);
l.info("dept==" +dept);
}
IDeptService
void updateDept(Dept dept);
DeptServiceImpl
@Override
public void updateDept(Dept dept) {
dao.update(dept);
}
IDeptDao
void update(Dept dept);
IDeptDao.xml
<update id="update" parameterType="dept">
update pe_dept set
dept_name = #{deptName } ,
parent_id = #{parent.deptId} ,
state = #{state } ,
company_id = #{companyId } ,
company_name = #{companyName }
where dept_id= #{deptId}
</update>
在所有的修改页面数据中,id都不能进行修改
DeptController
@RequestMapping(path = "/update",method = {RequestMethod.GET, RequestMethod.POST})
public String update(Dept dept,String parentId){
l.info("dept=="+dept);
l.info("parentId=="+parentId);
dept.setCompanyName("吉首大学");
dept.setCompanyId("1");
Dept parent=new Dept();//下拉选择菜单
parent.setDeptId(parentId);
dept.setParent(parent);
l.info("dept=="+dept);
service.updateDept(dept);
return "redirect:/system/dept/toList.do";
}
dept-update.jsp
<form id="editForm" action="${path}/system/dept/update.do" method="post">
测试出现bug
修复bug1
在下拉选择菜单中,自己可以把自己作为上级部门
使用if标签来修复bug
<c:forEach items="${list}" var="item">
//正在编辑的数据,不能选择自己作为上级部门
<c:if test="${dept.deptId != item.deptId}">
<option ${dept.parent.deptId == item.deptId ?'selected':''} value="${item.deptId}">${item.deptName}</option>
</c:if>
</c:forEach>
修复bug2
当部门为顶级部门时,没有上级部门
在映射文件中使用mybatis动态标签if
和choose
- 方式一
使用if标签
<update id="update" parameterType="dept">
update pe_dept set
dept_name = #{deptName } ,
<if test="parent.deptId==null or parent.deptId==''">
parent_id= NULL,
</if>
<if test="parent.deptId!=null and parent.deptId!=''">
parent_id = #{parent.deptId} ,
</if>
state = #{state } ,
company_id = #{companyId } ,
company_name = #{companyName }
where dept_id= #{deptId}
</update>
- 方式二
使用choose标签
<update id="update" parameterType="dept">
update pe_dept set
dept_name = #{deptName } ,
<choose>
<when test="parent.deptId==null or parent.deptId==''">
parent_id= NULL,
</when>
<otherwise>
parent_id = #{parent.deptId} ,
</otherwise>
</choose>
state = #{state } ,
company_id = #{companyId } ,
company_name = #{companyName }
where dept_id= #{deptId}
</update>