【MyBatis】 MyBatis修煉之六 MyBatis XML方式的基本用法(UPDATE肚豺、DELETE)

MyBatis參考文檔:

中文版:http://www.mybatis.org/mybatis-3/zh/index.html
英文版:http://www.mybatis.org/mybatis-3/

工具

JDK 1.6及以上版本
MyBatis 3.30版本
MySQL 6.3版本
Eclipse4 及以上版本
Apache Maven 構(gòu)建工具


項目源碼下載地址:https://github.com/JFAlex/MyBatis/tree/master/MyBatis_No.3/alex


update用法

一個簡單的通過主鍵更新數(shù)據(jù)的UPDATE的列子:
在UserMapper接口中添加一個修改的方法:

public int updateById(SysUser sysUser);

這里的sysUser就是新的數(shù)據(jù)對象,然后在XML文件中添加響應(yīng)的映射數(shù)據(jù):

    <update id="updateById">
        update sys_user set user_name = #{userName},
        user_password = #{userPassword},
        user_email = #{userEmail}, user_info =
        #{userInfo}, head_img = #{headImg
        , jdbcType=BLOB}, create_time =
        #{createTime,jdbcType=TIMESTAMP}
        where id = #{id}
    </update>

下面再在UserMapperTest測試類中添加一個測試方法:

    @Test
    public void testUpateById(){
        // 獲取SqlSession
                SqlSession sqlSession = getSqlSession();

                // 獲取UserMapper接口
                try {
                    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
                    
                    //根據(jù)數(shù)據(jù)庫中的用戶的ID,查詢出用戶數(shù)據(jù)
                    SysUser user = userMapper.selectById(3L);
                    
                    System.out.println("修改前數(shù)據(jù)為:" + user);
                    
                    //修改用戶數(shù)據(jù)
                    user.setUserName("update");
                    user.setUserPassword("12345678");
                    user.setUserEmail("mybatis@my.test");
                    user.setUserInfo("update data");
                    //正常情況下應(yīng)該存入一張圖片
                    user.setHeadImg(new byte[]{1,2,3});
                    user.setCreateTime(new Date());
                    
                    //將新建的對象插入數(shù)據(jù)庫中,特別注意這里的返回值result是執(zhí)行的SQL影響的行數(shù)
                    int result = userMapper.updateById(user);
                    System.out.println("修改成功數(shù)據(jù)條數(shù)為:" + result);
                    
                    //修改后再次獲取用戶數(shù)據(jù)
                    SysUser user2 = userMapper.selectById(3L);
                    System.out.println("修改后數(shù)據(jù)為:" + user2);
                }catch(Exception e){
                    e.printStackTrace();
                } finally {
                    //為了不對其他的測試造成影響,此處進行數(shù)據(jù)回滾
                    //由于默認的sqlSessionFactory.openSession()是不會自動提交的舌涨,因此如果不手動進行commit操作,數(shù)據(jù)也不會寫入數(shù)據(jù)庫
                    sqlSession.rollback();
                    // 關(guān)閉SqlSession
                    sqlSession.close();
                }
    }

測試方法首先從數(shù)據(jù)庫中根據(jù)id獲取出一個已經(jīng)存在的用戶的信息扔字,然后對查詢出來的數(shù)據(jù)進行修改囊嘉,當然不能修改主鍵id的值,然后調(diào)用修改的接口革为,將修改后的數(shù)據(jù)更新扭粱,最后在執(zhí)行一個根據(jù)id獲取用戶信息,即為修改后的用戶信息震檩。

右鍵單擊測試類焊刹,在Run As選項中選擇JUnit Test執(zhí)行測試。測試通過恳蹲,控制臺將會打印如下日志:

DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 1665404403.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@63440df3]
DEBUG [main] - ==>  Preparing: select * from sys_user where id = ? 
DEBUG [main] - ==> Parameters: 3(Long)
TRACE [main] - <==    Columns: id, user_name, user_password, user_email, user_info, head_img, create_time
TRACE [main] - <==        Row: 3, insert, 123456, mybatis@my.test, <<BLOB>>, <<BLOB>>, 2017-08-15 10:01:41.0
DEBUG [main] - <==      Total: 1
修改前數(shù)據(jù)為:SysUser [id=3, userName=insert, userPassword=123456, userEmail=mybatis@my.test, userInfo=insert data, headImg=[1, 2, 3], createTime=Tue Aug 15 10:01:41 CST 2017]
DEBUG [main] - ==>  Preparing: update sys_user set user_name = ?, user_password = ?, user_email = ?, user_info = ?, head_img = ?, create_time = ? where id = ? 
DEBUG [main] - ==> Parameters: update(String), 12345678(String), mybatis@my.test(String), update data(String), java.io.ByteArrayInputStream@51c8530f(ByteArrayInputStream), 2017-08-15 14:44:13.635(Timestamp), 3(Long)
DEBUG [main] - <==    Updates: 1
修改成功數(shù)據(jù)條數(shù)為:1
DEBUG [main] - ==>  Preparing: select * from sys_user where id = ? 
DEBUG [main] - ==> Parameters: 3(Long)
TRACE [main] - <==    Columns: id, user_name, user_password, user_email, user_info, head_img, create_time
TRACE [main] - <==        Row: 3, update, 12345678, mybatis@my.test, <<BLOB>>, <<BLOB>>, 2017-08-15 14:44:14.0
DEBUG [main] - <==      Total: 1
修改后數(shù)據(jù)為:SysUser [id=3, userName=update, userPassword=12345678, userEmail=mybatis@my.test, userInfo=update data, headImg=[1, 2, 3], createTime=Tue Aug 15 14:44:14 CST 2017]
DEBUG [main] - Rolling back JDBC Connection [com.mysql.jdbc.JDBC4Connection@63440df3]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@63440df3]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@63440df3]
DEBUG [main] - Returned connection 1665404403 to pool.

我們還可以通過設(shè)置UPDATE語句中的WHERE條件虐块,來修改一條或者多條數(shù)據(jù),基本的UPDATE用法就這么簡單嘉蕾。

delete用法

delete同update相似贺奠,我們通過主鍵來完成刪除數(shù)據(jù)。
在UserMapper接口中添加方法:

public int deleteById(Long id);

根據(jù)主鍵刪除數(shù)據(jù)時错忱,如果主鍵只有一個字段儡率,那么就可以像這個方法一樣使用一個參數(shù),這個方法對應(yīng)的UserMapper.xml中的代入如:

    <update id="updateById">
        update sys_user set user_name = #{userName},
        user_password = #{userPassword},
        user_email = #{userEmail}, user_info =
        #{userInfo}, head_img = #{headImg
        , jdbcType=BLOB}, create_time =
        #{createTime,jdbcType=TIMESTAMP}
        where id = #{id}
    </update>

如果我們修改UserMapper接口中方法中傳遞的參數(shù)以清,如下:

public int deleteById(SysUser sysUser);

我們XML中的代碼不需要進行任何修改儿普,也是可以正確執(zhí)行的。
然后在測試類UserMapperTest中添加一個測試方法:

@Test
    public void testDeleteById(){
        // 獲取SqlSession
        SqlSession sqlSession = getSqlSession();

        // 獲取UserMapper接口
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            
            //根據(jù)數(shù)據(jù)庫中的用戶的ID,查詢出用戶數(shù)據(jù)
            SysUser user1 = userMapper.selectById(1L);
            SysUser user2 = userMapper.selectById(2L);
            //此時還能夠查詢出數(shù)據(jù)
            System.out.println("執(zhí)行刪除前:"+user1);
            System.out.println("執(zhí)行刪除前:"+user2);
            
            //執(zhí)行刪除
            int result1 = userMapper.deleteById(1L);
            
            int result2 = userMapper.deleteById(user2);
            
            System.out.println("刪除id=1數(shù)據(jù)條數(shù):" + result1);
            System.out.println("刪除id=2數(shù)據(jù)條數(shù):" + result2);
            
            SysUser user11 = userMapper.selectById(1L);
            SysUser user22 = userMapper.selectById(2L);
            //此時還能夠查詢出數(shù)據(jù)
            System.out.println("執(zhí)行刪除后:"+user11);
            System.out.println("執(zhí)行刪除后:"+user22);
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            //為了不對其他的測試造成影響掷倔,此處進行數(shù)據(jù)回滾
            //由于默認的sqlSessionFactory.openSession()是不會自動提交的眉孩,因此如果不手動進行commit操作,數(shù)據(jù)也不會寫入數(shù)據(jù)庫
            sqlSession.rollback();
            // 關(guān)閉SqlSession
            sqlSession.close();
        }
    }

右鍵單擊測試類,在Run As選項中選擇JUnit Test執(zhí)行測試浪汪。測試通過巴柿,控制臺將會打印如下日志:

DEBUG [main] - Opening JDBC Connection
DEBUG [main] - Created connection 1665404403.
DEBUG [main] - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@63440df3]
DEBUG [main] - ==>  Preparing: select * from sys_user where id = ? 
DEBUG [main] - ==> Parameters: 1(Long)
TRACE [main] - <==    Columns: id, user_name, user_password, user_email, user_info, head_img, create_time
TRACE [main] - <==        Row: 1, admin, 123456, admin@mybais.alex, <<BLOB>>, <<BLOB>>, 2017-08-09 15:26:52.0
DEBUG [main] - <==      Total: 1
DEBUG [main] - ==>  Preparing: select * from sys_user where id = ? 
DEBUG [main] - ==> Parameters: 2(Long)
TRACE [main] - <==    Columns: id, user_name, user_password, user_email, user_info, head_img, create_time
TRACE [main] - <==        Row: 2, test, 123456, test@mybais.alex, <<BLOB>>, <<BLOB>>, 2017-08-09 15:27:30.0
DEBUG [main] - <==      Total: 1
執(zhí)行刪除前:SysUser [id=1, userName=admin, userPassword=123456, userEmail=admin@mybais.alex, userInfo=管理員, headImg=null, createTime=Wed Aug 09 15:26:52 CST 2017]
執(zhí)行刪除前:SysUser [id=2, userName=test, userPassword=123456, userEmail=test@mybais.alex, userInfo=測試用戶, headImg=null, createTime=Wed Aug 09 15:27:30 CST 2017]
DEBUG [main] - ==>  Preparing: delete from sys_user where id = ? 
DEBUG [main] - ==> Parameters: 1(Long)
DEBUG [main] - <==    Updates: 1
DEBUG [main] - ==>  Preparing: delete from sys_user where id = ? 
DEBUG [main] - ==> Parameters: 2(Long)
DEBUG [main] - <==    Updates: 1
刪除id=1數(shù)據(jù)條數(shù):1
刪除id=2數(shù)據(jù)條數(shù):1
DEBUG [main] - ==>  Preparing: select * from sys_user where id = ? 
DEBUG [main] - ==> Parameters: 1(Long)
DEBUG [main] - <==      Total: 0
DEBUG [main] - ==>  Preparing: select * from sys_user where id = ? 
DEBUG [main] - ==> Parameters: 2(Long)
DEBUG [main] - <==      Total: 0
執(zhí)行刪除后:null
執(zhí)行刪除后:null
DEBUG [main] - Rolling back JDBC Connection [com.mysql.jdbc.JDBC4Connection@63440df3]
DEBUG [main] - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@63440df3]
DEBUG [main] - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@63440df3]
DEBUG [main] - Returned connection 1665404403 to pool.

項目源碼下載地址:https://github.com/JFAlex/MyBatis/tree/master/MyBatis_No.3/alex


上一篇: 【MyBatis】 MyBatis修煉之五 MyBatis XML方式的基本用法(INSERT)

下一篇: 【MyBatis】 MyBatis修煉之七 MyBatis XML方式的基本用法(多個接口參數(shù))

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市死遭,隨后出現(xiàn)的幾起案子广恢,更是在濱河造成了極大的恐慌,老刑警劉巖呀潭,帶你破解...
    沈念sama閱讀 218,682評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件钉迷,死亡現(xiàn)場離奇詭異,居然都是意外死亡钠署,警方通過查閱死者的電腦和手機篷牌,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,277評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來踏幻,“玉大人,你說我怎么就攤上這事戳杀「妹妫” “怎么了?”我有些...
    開封第一講書人閱讀 165,083評論 0 355
  • 文/不壞的土叔 我叫張陵信卡,是天一觀的道長隔缀。 經(jīng)常有香客問我,道長傍菇,這世上最難降的妖魔是什么猾瘸? 我笑而不...
    開封第一講書人閱讀 58,763評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮丢习,結(jié)果婚禮上牵触,老公的妹妹穿的比我還像新娘。我一直安慰自己咐低,他們只是感情好揽思,可當我...
    茶點故事閱讀 67,785評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著见擦,像睡著了一般钉汗。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上鲤屡,一...
    開封第一講書人閱讀 51,624評論 1 305
  • 那天损痰,我揣著相機與錄音,去河邊找鬼酒来。 笑死卢未,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的堰汉。 我是一名探鬼主播尝丐,決...
    沈念sama閱讀 40,358評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼显拜,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了爹袁?” 一聲冷哼從身側(cè)響起远荠,我...
    開封第一講書人閱讀 39,261評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎失息,沒想到半個月后譬淳,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,722評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡盹兢,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年邻梆,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片绎秒。...
    茶點故事閱讀 40,030評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡浦妄,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出见芹,到底是詐尸還是另有隱情剂娄,我是刑警寧澤,帶...
    沈念sama閱讀 35,737評論 5 346
  • 正文 年R本政府宣布玄呛,位于F島的核電站阅懦,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏徘铝。R本人自食惡果不足惜耳胎,卻給世界環(huán)境...
    茶點故事閱讀 41,360評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望惕它。 院中可真熱鬧怕午,春花似錦、人聲如沸淹魄。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,941評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽揭北。三九已至扳炬,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間搔体,已是汗流浹背恨樟。 一陣腳步聲響...
    開封第一講書人閱讀 33,057評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留疚俱,地道東北人劝术。 一個月前我還...
    沈念sama閱讀 48,237評論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親养晋。 傳聞我的和親對象是個殘疾皇子衬吆,可洞房花燭夜當晚...
    茶點故事閱讀 44,976評論 2 355

推薦閱讀更多精彩內(nèi)容