MyBatis实现增删改查

145 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第10天,点击查看活动详情

CRUD增删改查

1 有条件查询

这里我们做一个小例子就是:按id查询

  1. 接口添加方法 直接在StudentMapper接口里添加一个按id查找的方法返回值是student 添加的代码
	Student findStudentByID(int id);
  1. mapper文件添加语句 然后在student-mapper.xml中添加查询语句
    <select id="findStudentByID" parameterType="int" resultType="com.shea.pojo.Student">
       SELECT * from student WHERE id = #{id}
   </select>

idresultType在上面的时候讲过了 。 parameterType:这个例子中是按照id来查找,id的是int类型的数组,我们需要把这个值传入,这个标签就是传入值的类型,也是传参的。

  1. 编写测试用例
    @Test
    public void testFindStudentByID(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        Student student = studentMapper.findStudentByID(1);

        System.out.println(student);
        
        sqlSession.close();
    }

2 插入数据

和上面一样

  1. 添加接口方法
	void insertStudent(Student student);
  1. 编写mapper
    <insert id="insertStudent" parameterType="com.shea.pojo.Student">
        INSERT INTO student(id,name,score,age,gender) VALUES (#{id},#{name},#{score},#{age},#{gender})
    </insert>
  1. 编测试文件
	@Test
    public void testInsertStudent(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();

        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        studentMapper.insertStudent(new Student(3,"naoao",100,18,1));

        //事务提交
        sqlSession.commit();
        sqlSession.close();
    }

**注意:**这里和查询不一样,是需要提交事务的,可以运行,当然很显然,这里的student的id可以不写但是需要改变代码,大家自己思考自己动手写一下

3 修改

这个案例我在实体类中多写了一个构造方法,这样我就不用写那么多其他东西了

	//实体类中多加的构造方法
	public Student(int id, int score) {
        this.id = id;
        this.score = score;
    }
  1. 接口添加方法
    void updateStudent(Student student);
  1. 在mapper中编写sql
    <update id="updateStudent" parameterType="com.shea.pojo.Student">
        UPDATE student SET score = #{score} WHERE id = #{id}
    </update>
  1. 编写测试文件
    @Test
    public void testUpdateStudent(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();

        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        studentMapper.updateStudent(new Student(3,80));

        sqlSession.commit();
        sqlSession.close();
    }

4 删除

如果你是看这个教程学习的同学,可以先留十分钟给自己写一下这个案例,使用id删除一个学生

  1. 添加一个接口方法
    void deleteStudent(int id);
  1. 在mapper中添加sql
    <delete id="deleteStudent" parameterType="int">
        DELETE  FROM student WHERE id = #{id};
    </delete>
  1. 编写测试文件
    @Test
    public void testDeleteStudent(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();

        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        studentMapper.deleteStudent(3);

        sqlSession.commit();
        sqlSession.close();
    }

5 总结

当我们第一次使用mybatis的时候配置十分的繁琐,但是等你配置完再去修改代码,那你基本上需要认真写的就只有sql语句了,这个代码量很少,而且很快,比JDBC更便捷。 万事开头难结束了就是比较轻松的