在 Mybatis 中,update 語句可以使用 set 標(biāo)簽動態(tài)更新列。set 標(biāo)簽可以為 SQL 語句動態(tài)的添加 set 關(guān)鍵字,剔除追加到條件末尾多余的逗號。
要求:根據(jù) id 修改網(wǎng)站名稱或網(wǎng)址(本節(jié)示例基于《第一個MyBatis程序》一節(jié)的代碼實現(xiàn))。
WebsiteMapper.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="net.biancheng.mapper.WebsiteMapper"> <select id="selectWebsite" resultType="net.biancheng.po.Website"> SELECT * FROM website <where> <if test="id!=null and id!=''"> id=#{id} </if> </where> </select> <!--使用set元素動態(tài)修改一個網(wǎng)站記錄 --> <update id="updateWebsite" parameterType="net.biancheng.po.Website"> UPDATE website <set> <if test="name!=null">name=#{name}</if> <if test="url!=null">url=#{url}</if> </set> WHERE id=#{id} </update> </mapper>
WebsiteMapper 類中方法如下。
package net.biancheng.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import net.biancheng.po.Website; public interface WebsiteMapper { public List<Website> selectWebsite(Website site); public int updateWebsite(Website site); }
測試類代碼如下。
package net.biancheng.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 net.biancheng.mapper.WebsiteMapper; import net.biancheng.po.Website; 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(); Website site = new Website(); site.setId(1); site.setUrl("www.biancheng.net"); // 執(zhí)行update語句前 List<Website> siteList = ss.getMapper(WebsiteMapper.class).selectWebsite(site); for (Website st : siteList) { System.out.println(st); } int num = ss.getMapper(WebsiteMapper.class).updateWebsite(site); System.out.println("影響數(shù)據(jù)庫行數(shù)" + num); // 執(zhí)行update語句后 List<Website> siteList2 = ss.getMapper(WebsiteMapper.class).selectWebsite(site); for (Website st : siteList2) { System.out.println(st); } ss.commit(); ss.close(); } }
輸出結(jié)果如下。
DEBUG [main] - ==> Preparing: SELECT * FROM website WHERE id=? DEBUG [main] - ==> Parameters: 1(Integer) DEBUG [main] - <== Total: 1 Website[id=1,name=編程幫,url=http://www.soo66.com/,age=10,country=CN] DEBUG [main] - ==> Preparing: UPDATE website SET url=? where id=? DEBUG [main] - ==> Parameters: www.soo66.com(String), 1(Integer) DEBUG [main] - <== Updates: 1 影響數(shù)據(jù)庫行數(shù)1 DEBUG [main] - ==> Preparing: SELECT * FROM website WHERE id=? DEBUG [main] - ==> Parameters: 1(Integer) DEBUG [main] - <== Total: 1 Website[id=1,name=編程幫,url=www.soo66.com,age=10,country=CN]