一、前言

      前一篇博客向大家介绍了Mybatis的添加操作,深入浅出Mybatis(四)——入门程序(查询),咱们继续跟进步伐,完成增删改操作。

二、添加

2.0 添加需求

      在开始做之前呢?我们还是要看一下我们的需求:

  • 添加用户,返回添加的用户信息,包括(id,address,sex,username,birthday)

2.1 在User.xml添加insert的sql语句

      这次我们使用的是添加用户,所以要使用insert标签。

<insert id="insertUser" parameterType="cn.itcast.mybatis.po.User"  >
        <!-- 将插入数据的主键返回,返回到user对象中。 select LAST_INSERT_ID():得到刚insert进行的记录的主键,只适用于自增主键 
            keyProperty:将查询到主键值设置到parameterType指定的对象的哪个属性。 order:select LAST_INSERT_ID()执行顺序,相对insert语句来说他的执行顺序 
            resultType:指定select LAST_INSERT_ID()的返回数据的类型 -->
         <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
            select LAST_INSERT_ID()
        </selectKey> 
        INSERT into user (username ,birthday,sex,address)VALUES (#{username},#{birthday},#{sex},#{address})
    </insert>

      这里有几点是需要我们要留意的:
      1.因为要插入的是用户实体,所以我们的输入格式parameterType=”cn.itcast.mybatis.po.User”;

      2.需求中说返回添加的用户信息,包括(id,address,sex,username,birthday),再怎么数据库中的id字段是自增长的,我们可以通过select LAST_INSERT_ID()语句来得到刚insert进行的记录的主键的值。

      3.在selectKey标签中,keyProperty:将查询到主键值设置到parameterType指定的对象的哪个属性。 order:select LAST_INSERT_ID()执行顺序,相对insert语句来说他的执行顺序 。

      4.插入语句我们使用的是#{}占位符,可以在括号内直接写User的属性值。且不能有‘’,以下两种是错误的写法:

INSERT into user (username ,birthday,sex,address)VALUES (#{User.username},#{User.birthday},#{User.sex},#{User.address})

        INSERT into user (username ,birthday,sex,address)VALUES ('#{username}','#{birthday}','#{sex}','#{address}')

        INSERT into user (username ,birthday,sex,address)VALUES ('#{User.username}','#{User.birthday}','#{User.sex}','#{User.address}')

      当然我们也可以使用${}来拼接字符串,但是可能会遇到数据格式的问题,最常见的就是时间格式问题。

INSERT into user (username ,birthday,sex,address)VALUES ('${username}','${birthday}','${sex}','${address}')

2.2 测试程序

      在UserTest.java测试类中添加测试方法testinsertUser:

//添加用戶
    @Test
    public void testinsertUser() throws ParseException{
        // 数据库会话实例
        SqlSession sqlSession = null;
        try {
            // 创建数据库会话实例sqlSession
            sqlSession = sqlSessionFactory.openSession();
            // 添加用户信息
            User user = new User();
            user.setSex("1");
            user.setAddress("北京北京");
            user.setBirthday(new Date());
            user.setUsername("China Ares");
            sqlSession.insert("test.insertUser", user);
            //提交事务
            sqlSession.commit();
            System.out.println("添加成功");
            System.out.println(user.getId() );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

2.3 执行结果:




【Mybatis】深入浅出Mybatis(五)——入门程序(增删改)_博客


三、删除

3.0 删除的需求

  • 根据id删除用户信息

3.1 在User.xml添加delete的sql语句

<!-- 删除用户 -->
    <delete id="deleteUserById" parameterType="int">
        delete from user where id=#{id}
    </delete>

3.2 测试程序

// 根据id删除用户
    @Test
    public void testDelete() {
        // 数据库会话实例
        SqlSession sqlSession = null;
        try {
            // 创建数据库会话实例sqlSession
            sqlSession = sqlSessionFactory.openSession();
            // 删除用户
            sqlSession.delete("test.deleteUserById",18);
            // 提交事务
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }

3.3 执行结果



【Mybatis】深入浅出Mybatis(五)——入门程序(增删改)_sql_02


四、修改

4.0 修改的需求

  • 根据id修改用户信息

4.1 在User.xml添加update的sql语句

<!-- 更新用户 -->
    <update id="updateUser" parameterType="cn.itcast.mybatis.po.User">
        update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}
    </update>

4.2 测试程序

// 更新用户信息
    @Test
    public void testupdateUser(){
        // 数据库会话实例
        SqlSession sqlSession = null;
        try {
            // 创建数据库会话实例sqlSession
            sqlSession = sqlSessionFactory.openSession();
            // 添加用户信息
            User user = new User();
            user.setId(39);
            user.setSex("2");
            user.setAddress("北京中国");
            user.setBirthday(new Date());
            user.setUsername("BeiJing Ares");

            sqlSession.update("test.updateUser",user);
            // 提交事务
            sqlSession.commit();

            System.out.println(user.getId() );
            System.out.println(user.getAddress() );
            System.out.println(user.getSex() );
            System.out.println(user.getUsername() );
            System.out.println(user.getBirthday() );
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            sqlSession.close();
        }

    }

4.3 执行结果



【Mybatis】深入浅出Mybatis(五)——入门程序(增删改)_mybatis_03


五、小结

      到此为止,增删改查就完成了,这个些功能仅仅是使用了一个映射文件完成的,可以感觉到系统变的非常的灵活,而且使用的也很方面,把封装发挥到了很好的地步。

      下一篇博客将带来“深入浅出Mybatis(五)——mapper代理方法使用”;