• mybatis学习笔记(三)


    mybatis增删改

    • 概念:
      • 功能:从应用程序角度出发,软件具有哪些功能;
      • 业务:完成功能时的逻辑,对应service的一个方法;
      • 事务:从数据库角度出发,完成业务时需要执行的SQL集合,统称一个事务。
    • mybatis 底层是对 JDBC 的封装
      • JDBC 中 executeUpdate()执行新增,删除,修改的 SQL.返回值 int,表示受影响的行数。
      • 所以mybatis 中<insert><delete><update>标签没有 resultType 属性,默认返回值都是 int。
    • 增加一条信息
      • 使用<insert>标签
        <insert id="ins" parameterType="People">
              insert into people values(default,#{name},#{age})
        </insert>
         1 People people = new People();
         2 people.setName("新增name");
         3 people.setAge(88);
         4 try {
         5    int insert = session.insert("com.bjm.mapper.ins", people);
         6    if (insert>0) {
         7       System.out.println("成功");
         8    }else {
         9       System.out.println("失败");
        10       }
        11   } catch (Exception e) {
        12       session.rollback();
        13       }
        14 session.commit();
        15 session.close();
      • 在 openSession()时 Mybatis 会创建 SqlSession 时同时创建一个Transaction(事务对象),同时 autoCommit 都为 false,这也就是mybatis将JDBC的自动提交关闭,需要session.commit();让session进行提交。
      • 为了避免错误提交,使用session.rollback();事务回滚
    • 删除一条信息
      • 使用<delete>标签
        1 <delete id="del" parameterType="People">
        2       delete from people where id=#{0}
        3 </delete>
         1 try {
         2     int delete = session.delete("com.bjm.mapper.del", 2);
         3     if (delete > 0) {
         4         System.out.println("成功");
         5     }else {
         6     System.out.println("失败");
         7         }
         8     } catch (Exception e) {
         9     session.rollback();
        10 }  
      • 由于删除操作是根据id查找一条数据,所以使用#{0}
    • 修改一条信息
      • 使用<update>标签
        1 <update id="upd" parameterType="People">
        2       update people set name = #{name} where id = #{id}
        3 </update> 
         1 People people = new People();
         2 people.setId(3);
         3 people.setName("王二麻子");
         4 try {
         5     int update = session.update("com.bjm.mapper.upd", people);
         6     if (update > 0) {
         7         System.out.println("成功");
         8     }else {
         9         System.out.println("失败");
        10     }
        11 } catch (Exception e) {
        12     session.rollback();
        13 }
        14 session.commit();
        15 session.close();
  • 相关阅读:
    像调试java一样来调试Redis lua
    微言限流
    性能测试遭遇TPS抖动问题
    你所不知道的堆外缓存
    基于JMH的Benchmark解决方案
    基于FastJson的通用泛型解决方案
    你所不知道的日志异步落库
    mac上配置java开发环境
    你所不知道的库存超限做法
    服务器一般达到多少qps比较好[转]
  • 原文地址:https://www.cnblogs.com/bjm1/p/10267361.html
Copyright © 2020-2023  润新知