MyBatis 如何使用set标签呢?
set标签的功能简介
set标签主要用于结合update语句动态更新列信息,使用set标签可避免条件末尾多余的逗号
例 使用 id 修改名称或备注
UserInfoMapper.xml
<?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.java265.mapper.UserInfoMapper"> <select id="selectUserInfo" resultType="com.java265.po.UserInfo"> SELECT id,name,notes FROM UserInfo <where> <if test="id!=null and id!=''"> id=#{id} </if> </where> </select> <!--使用set元素动态修改一个网站记录 --> <update id="updateUserInfo" parameterType="com.java265.po.UserInfo"> UPDATE UserInfo <set> <if test="name!=null">name=#{name}</if> <if test="notes!=null">notes=#{notes}</if> </set> WHERE id=#{id} </update> </mapper>UserInfoMapper 类
package com.java265.mapper; import java.util.list; import org.apache.ibatis.annotations.Param; import com.java265.po.UserInfo; public interface UserInfoMapper { public List<UserInfo> selectUserInfo(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语句前 List<UserInfo> userList = 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<UserInfo> 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爱好者]
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。