Mybatis框架(三)Mybatis的CRUD操作

在上一篇Mybatis框架(二)Mybatis的入门程序中实现了Mybatis的查找操作,本文章主要实现其余的几种操作,这里不再创建项目,将接着上篇继续操作:

一、我们只需要更该接口StuMapper与Mapper的配置文件中的内容,其余不需要做变动。
编写接口:

     Stu getStuById(int id);   //根据学生的id查找学生信息
     int addStu(Stu stu);  //插入一个学生信息
     int updateStu(Stu stu);  //修改学生的信息
     int deleteStu(int id);   //删除学生的信息

编写对应的mapper中的sql语句:

  <!--根据学生id查找学生的全部信息-->
    <select id="getStuById" resultType="com.wst.pojo.Stu" parameterType="int">
       /*定义sql*/
       select * from stu where id = #{id};
   </select>

     <!--插入信息-->
    <insert id="addStu" parameterType="com.wst.pojo.Stu">
        insert into stu (id,name,age,address) values (#{id},#{name},#{age},#{address});
    </insert>

<!--&lt;!&ndash;修改信息&ndash;&gt;-->
    <update id="updateStu" parameterType="com.wst.pojo.Stu">
        update stu set name = #{name},age=#{age},address=#{address} where id=#{id} ;
    </update>
<!--删除信息-->
    <delete id="deleteStu" parameterType="int">
        delete from stu where id = #{id};
    </delete>

注:在上面的配置中主要涉及到的映射器:
在这里插入图片描述
二、启动,进行测试。
首先我们需要增加测试函数:

 //查询操作
       @Test
      public void selectStuId(){
            SqlSession sqlSession = MyBatisUtils.getSqlSession();
            StuMapper mapper = sqlSession.getMapper(StuMapper.class);
            System.out.println("根据学生的id查找学生的信息:");
            Stu stu=mapper.getStuById(2);
            System.out.println(stu);
            //关闭sqlsession
            sqlSession.close();
        }
        //插入操作
    @Test
    public void insertStu(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        StuMapper mapper = sqlSession.getMapper(StuMapper.class);
        System.out.println("插入学生信息:");
      int m=  mapper.addStu(new Stu(10,"XX",12,"XX"));
      if (m>0) {
            System.out.println("插入成功!");
        }
        sqlSession.commit();
        sqlSession.close();
    }
//更新操作
    @Test
    public void  updateStu(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        StuMapper mapper = sqlSession.getMapper(StuMapper.class);
        System.out.println("更新学生信息:");
        mapper.updateStu(new Stu(1,"XX",10,"XX"));
        sqlSession.commit();
        System.out.println("更新成功!");
        sqlSession.close();
    }
    //删除操作
    @Test
    public void deleteStu(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        StuMapper mapper = sqlSession.getMapper(StuMapper.class);
        System.out.println("删除学生信息:");
       mapper.deleteStu(2);
        sqlSession.commit();
        System.out.println("删除成功!!!");
        sqlSession.close();
    }

注:
在这里插入图片描述

发布了105 篇原创文章 · 获赞 30 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43759352/article/details/104517020