转自:
set标签的功能简介
set标签主要用于结合update语句动态更新列信息,
使用set标签可避免条件末尾多余的逗号
例 使用 id 修改名称或备注
UserInfoMapper.xml
UPDATE UserInfo WHERE id=#{id} name=#{name} notes=#{notes}
UserInfoMapper 类
package com.java265.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.java265.po.UserInfo; public interface UserInfoMapper { public ListselectUserInfo(UserInfo site); public int updateUserInfo(UserInfo site); }
测试类
package com.java265.test; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.java265.mapper.UserInfoMapper; import com.java265.po.UserInfo; public class Test { public static void main(String[] args) throws IOException { InputStream config = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config); SqlSession ss = ssf.openSession(); UserInfo userInfo = new UserInfo(); userInfo.setId(1); userInfo.setNotes("java爱好者"); // 执行update语句前 ListuserList = ss.getMapper(UserInfoMapper.class).selectUserInfo(userInfo); for (UserInfo t : userList) { System.out.println(t); } int num = ss.getMapper(UserInfoMapper.class).updateUserInfo(userInfo); System.out.println("影响数据库行数" + num); // 执行update语句后 List userList2 = ss.getMapper(UserInfoMapper.class).selectUserInfo(userInfo); for (UserInfo t : userList2) { System.out.println(t); } ss.commit(); ss.close(); } }
输出结果
DEBUG [main] - ==> Preparing: SELECT * FROM UserInfo WHERE id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
UserInfo[id=1,name=王二,notes=java爱好者]
DEBUG [main] - ==> Preparing: UPDATE UserInfo SET notes=? where id=?
DEBUG [main] - ==> Parameters: java爱好者(String), 1(Integer)
DEBUG [main] - <== Updates: 1
影响数据库行数1
DEBUG [main] - ==> Preparing: SELECT * FROM UserInfo WHERE id=?
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <== Total: 1
UserInfo[id=1,name=王二,notes=java爱好者]