需求:使用set标签修改用户信息
如将数据库中user表中id为32高萍的sex修改为2,address修改为江苏无锡
1.UserMapper接口:
public int updateUser(User user);
2.UserMapper.xml中的sql如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sea.crm.mapper.UserMapper">
<update id="updateUser" parameterType="User">
update user
<set>
<if test="username!=null and username!=''">
username=#{username},
</if>
<if test="birthday!=null">
birthday=#{birthday},
</if>
<if test="sex!=0">
sex=#{sex},
</if>
<if test="address!=null">
address=#{address}
</if>
</set>
where id=#{id}
</update>
</mapper>
Tips:每一个修改属性的语句的后面不要忘记”,”(逗号),最后一个不需要写。
3.单元测试如下:
public class MyBatisTest {
SqlSessionFactory factory = null;
private UserMapper userMapper = null;
@Before
public void testInit() {
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
InputStream in = MyBatisTest.class.getResourceAsStream("/SqlMapConfig.xml");
factory = builder.build(in);
}
@Test
public void testupdateUser() {
SqlSession sqlSession = factory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = new User();
user.setId(32);
user.setSex(2);
user.setAddress("江苏无锡");
int updateUser = mapper.updateUser(user);
System.out.println(updateUser);
sqlSession.commit();
sqlSession.close();
}
}
4.效果: