首页 技术 正文
技术 2022年11月8日
0 收藏 974 点赞 1,881 浏览 1427 个字

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>
       People people = new People();
      people.setName("新增name");
      people.setAge(88);
      try {
      int insert = session.insert("com.bjm.mapper.ins", people);
      if (insert>0) {
      System.out.println("成功");
      }else {
      System.out.println("失败");
      }
      } catch (Exception e) {
      session.rollback();
      }
      session.commit();
      session.close();
    • 在 openSession()时 Mybatis 会创建 SqlSession 时同时创建一个Transaction(事务对象),同时 autoCommit 都为 false,这也就是mybatis将JDBC的自动提交关闭,需要session.commit();让session进行提交。
    • 为了避免错误提交,使用session.rollback();事务回滚
  • 删除一条信息
    • 使用<delete>标签

       <delete id="del" parameterType="People">
      delete from people where id=#{0}
      </delete>
       try {
      int delete = session.delete("com.bjm.mapper.del", 2);
      if (delete > 0) {
      System.out.println("成功");
      }else {
      System.out.println("失败");
      }
      } catch (Exception e) {
      session.rollback();
      }
    • 由于删除操作是根据id查找一条数据,所以使用#{0}
  • 修改一条信息
    • 使用<update>标签

       <update id="upd" parameterType="People">
      update people set name = #{name} where id = #{id}
      </update>
       People people = new People();
      people.setId(3);
      people.setName("王二麻子");
      try {
      int update = session.update("com.bjm.mapper.upd", people);
      if (update > 0) {
      System.out.println("成功");
      }else {
      System.out.println("失败");
      }
      } catch (Exception e) {
      session.rollback();
      }
      session.commit();
      session.close();
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,489
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,904
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,737
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,490
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,128
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,291