美文网首页MyBatis修炼MyBatis我爱编程
【MyBatis】 MyBatis修炼之六 MyBatis

【MyBatis】 MyBatis修炼之六 MyBatis

作者: 开心跳蚤 | 来源:发表于2017-08-15 15:19 被阅读88次

    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 构建工具


    项目源码下载地址:https://github.com/JFAlex/MyBatis/tree/master/MyBatis_No.3/alex


    update用法

    一个简单的通过主键更新数据的UPDATE的列子:
    在UserMapper接口中添加一个修改的方法:

    public int updateById(SysUser sysUser);
    

    这里的sysUser就是新的数据对象,然后在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>
    

    下面再在UserMapperTest测试类中添加一个测试方法:

        @Test
        public void testUpateById(){
            // 获取SqlSession
                    SqlSession sqlSession = getSqlSession();
    
                    // 获取UserMapper接口
                    try {
                        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
                        
                        //根据数据库中的用户的ID,查询出用户数据
                        SysUser user = userMapper.selectById(3L);
                        
                        System.out.println("修改前数据为:" + user);
                        
                        //修改用户数据
                        user.setUserName("update");
                        user.setUserPassword("12345678");
                        user.setUserEmail("mybatis@my.test");
                        user.setUserInfo("update data");
                        //正常情况下应该存入一张图片
                        user.setHeadImg(new byte[]{1,2,3});
                        user.setCreateTime(new Date());
                        
                        //将新建的对象插入数据库中,特别注意这里的返回值result是执行的SQL影响的行数
                        int result = userMapper.updateById(user);
                        System.out.println("修改成功数据条数为:" + result);
                        
                        //修改后再次获取用户数据
                        SysUser user2 = userMapper.selectById(3L);
                        System.out.println("修改后数据为:" + user2);
                    }catch(Exception e){
                        e.printStackTrace();
                    } finally {
                        //为了不对其他的测试造成影响,此处进行数据回滚
                        //由于默认的sqlSessionFactory.openSession()是不会自动提交的,因此如果不手动进行commit操作,数据也不会写入数据库
                        sqlSession.rollback();
                        // 关闭SqlSession
                        sqlSession.close();
                    }
        }
    

    测试方法首先从数据库中根据id获取出一个已经存在的用户的信息,然后对查询出来的数据进行修改,当然不能修改主键id的值,然后调用修改的接口,将修改后的数据更新,最后在执行一个根据id获取用户信息,即为修改后的用户信息。

    右键单击测试类,在Run As选项中选择JUnit Test执行测试。测试通过,控制台将会打印如下日志:

    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
    修改前数据为: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
    修改成功数据条数为: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
    修改后数据为: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.
    

    我们还可以通过设置UPDATE语句中的WHERE条件,来修改一条或者多条数据,基本的UPDATE用法就这么简单。

    delete用法

    delete同update相似,我们通过主键来完成删除数据。
    在UserMapper接口中添加方法:

    public int deleteById(Long id);
    

    根据主键删除数据时,如果主键只有一个字段,那么就可以像这个方法一样使用一个参数,这个方法对应的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接口中方法中传递的参数,如下:

    public int deleteById(SysUser sysUser);
    

    我们XML中的代码不需要进行任何修改,也是可以正确执行的。
    然后在测试类UserMapperTest中添加一个测试方法:

    @Test
        public void testDeleteById(){
            // 获取SqlSession
            SqlSession sqlSession = getSqlSession();
    
            // 获取UserMapper接口
            try {
                UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
                
                //根据数据库中的用户的ID,查询出用户数据
                SysUser user1 = userMapper.selectById(1L);
                SysUser user2 = userMapper.selectById(2L);
                //此时还能够查询出数据
                System.out.println("执行删除前:"+user1);
                System.out.println("执行删除前:"+user2);
                
                //执行删除
                int result1 = userMapper.deleteById(1L);
                
                int result2 = userMapper.deleteById(user2);
                
                System.out.println("删除id=1数据条数:" + result1);
                System.out.println("删除id=2数据条数:" + result2);
                
                SysUser user11 = userMapper.selectById(1L);
                SysUser user22 = userMapper.selectById(2L);
                //此时还能够查询出数据
                System.out.println("执行删除后:"+user11);
                System.out.println("执行删除后:"+user22);
            }catch(Exception e){
                e.printStackTrace();
            } finally {
                //为了不对其他的测试造成影响,此处进行数据回滚
                //由于默认的sqlSessionFactory.openSession()是不会自动提交的,因此如果不手动进行commit操作,数据也不会写入数据库
                sqlSession.rollback();
                // 关闭SqlSession
                sqlSession.close();
            }
        }
    

    右键单击测试类,在Run As选项中选择JUnit Test执行测试。测试通过,控制台将会打印如下日志:

    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
    执行删除前:SysUser [id=1, userName=admin, userPassword=123456, userEmail=admin@mybais.alex, userInfo=管理员, headImg=null, createTime=Wed Aug 09 15:26:52 CST 2017]
    执行删除前: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数据条数:1
    删除id=2数据条数: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
    执行删除后:null
    执行删除后: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方式的基本用法(多个接口参数)

    相关文章

      网友评论

      本文标题:【MyBatis】 MyBatis修炼之六 MyBatis

      本文链接:https://www.haomeiwen.com/subject/fysurxtx.html