mybatis update標籤
一、update標籤
MyBatis update 標籤用於定義更新語句,執行更新操作。當 MyBatis 執行完一條更新語句後,會返回一個整數,表示受影響的資料庫記錄的行數。
如以下xml檔案中的語句
update 標籤常用屬性
注意:update 標籤中沒有 resultType 屬性,只有查詢操作才需要對返回結果型別進行相應的指定。
二、傳遞引數
Mybatis提供以下 3 種方式,來實現給對映器傳遞多個引數:
- 使用 Map 傳遞引數
- 使用註解傳遞引數
- 使用 JavaBean 傳遞引數
2.1使用 Map 傳遞引數
1》複製【mybatis嚐鮮】這節中的專案程式碼mybatisDemoA2,生成專案mybatisDemoA5,開啟net.biancheng.mapper包下的WebsiteMapper介面類,新增以下方法:
public int updateWebsiteByMap(Map<String, Object> params);
2》開啟net.biancheng.mapper包下的WebsiteMapper.xml 中,新增以下配置內容,注意原來內容不要動:
<!--更新語句接收 Map 傳遞的引數-->
<update id="updateWebsiteByMap" parameterType="map">
update website set name = #{name},url= #{url} where id = #{id}
</update>
3》在net.biancheng.test包新增testMap類,程式碼如下:
package net.biancheng.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 testMap {
public static void main(String[] args) {
InputStream config;
try {
// 讀取配置檔案
config = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory ssf = new SqlSessionFactoryBuilder()
.build(config);
// 建立sqlsession物件
SqlSession ss = ssf.openSession();
// 獲取指定物件
WebsiteMapper websiteMapper = ss.getMapper(WebsiteMapper.class);
System.out.println("更新前:");
// 呼叫物件方法
Website websitelist0 = websiteMapper.selectAllWebsite().get(0);
System.out.println(websitelist0.show());
// 使用 Map 向 update 標籤傳遞引數
Map<String, Object> params = new HashMap<>();
params.put("id", 3);
params.put("name", "菜鳥果");
params.put("url", "www.cai.net");
int i = websiteMapper.updateWebsiteByMap(params);
if (i > 0) {
System.out.println("通過 Map 傳遞引數,共更新了 " + i + " 條記錄");
}
System.out.println("更新後:");
// 呼叫物件方法
Website websitelist1 = websiteMapper.selectAllWebsite().get(0);
System.out.println(websitelist1.show());
ss.commit();
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
更新前資料庫記錄如下:
程式執行結果如下:
更新後資料庫記錄如下:
id為3的記錄發生了更新,執行成功.