mybaits<set>标签的使用

使用set标签可以将动态的配置SET 关键字,和剔除追加到条件末尾的任何不相关的逗号

1.在接口中创建方法

public void updateEmp(Employee employee);

2在映射文件中配置

<!--public void updateEmp(Employee employee); -->
<update id="updateEmp">
<!-- Set标签的使用 -->
update tbl_employee
<set>
<if test="lastName!=null">
last_name=#{lastName},
</if>
<if test="email!=null">
email=#{email},
</if>
<if test="gender!=null">
gender=#{gender}
</if>
</set>
where id=#{id}
<!--
Trim:更新拼串
update tbl_employee
<trim prefix="set" suffixOverrides=",">
<if test="lastName!=null">
last_name=#{lastName},
</if>
<if test="email!=null">
email=#{email},
</if>
<if test="gender!=null">
gender=#{gender}
</if>
</trim>
where id=#{id} -->
</update>

3进行测试

@Test
public void testDynamicSql() throws IOException{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try{
EmployeeMapperDynamicSQL mapper = openSession.getMapper(EmployeeMapperDynamicSQL.class);
Employee employee = new Employee(1, null, null, "3");
//测试set标签
mapper.updateEmp(employee);
openSession.commit();

}finally{
openSession.close();
}
}

原文地址:https://www.cnblogs.com/zhangzhiqin/p/8565934.html