MyBatis(二)增删改

基于白嫖:【狂神说Java】Mybatis最新完整教程IDEA版通俗易懂

1 增

1.1 创建接口

package dao;

import pojo.Student;

public interface StudentMapper {
    //增加学生
    int addStudent(Student student);
}

dao包下面新建一个StudentMapper接口,接口有一个增加学生的方法addStudent

1.2 配置xml的mapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!--namespace和接口匹配-->
<mapper namespace="dao.StudentMapper">
    <insert id="addStudent" parameterType="pojo.Student">
        insert into Student values (#{id},#{name});<!--对象属性可以直接取到-->
    </insert>
</mapper>

dao包下面新建一个StudentMapper.xml配置文件,把addStudent的sql实现添加进去;

1.3 在mybatis-config.xml注册mapper

<mappers>
        <mapper resource="dao/StudentMapper.xml"/>
    </mappers>

1.4 编写测试方法

package dao;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import pojo.Student;
import utils.MybatisUtils;

public class StudentTest {

    @Test
    public void addTest(){
        try (SqlSession sqlSession = MybatisUtils.getSqlSession()) {
            //getmap方法
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);

            //添加方法
            studentMapper.addStudent(new Student(1,"小明"));
       
            //提交事务
            sqlSession.commit();
        }
    }
}

注意增删改都需要提交事务

2 改

2.1 新增接口方法

//更改学生
int updateStudent(Student student);

2.2 新增接口映射

<update id="updateStudent" parameterType="pojo.Student">
        update Student set name=#{name} where id=#{id};
</update>

注意是根据一个id去修改,根据id修改名字

2.3 测试方法

@Test
public void updateTest(){
    try (SqlSession sqlSession = MybatisUtils.getSqlSession()) {
    //getmap方法
    StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);

    //修改
    studentMapper.updateStudent(new Student(1,"蒋中正"));

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

3 删

3.1 创建接口方法

//删除学生
int deleteStudent(Student student);

3.2 新增接口映射

<delete id="deleteStudent" parameterType="pojo.Student">
        delete from Student where id=#{id};
</delete>

根据id删除项;

3.3 编写测试方法

public void deleteStudentTest(){
        try (SqlSession sqlSession = MybatisUtils.getSqlSession()) {
            //getmap方法
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);

            //修改
            studentMapper.deleteStudent(new Student(1,"不关心"));//根据id删人

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

        }
    }

4 总结

当配置好环境之后,添加功能的通用步骤为:

编写接口方法
编写mapper的SQL语句
测试

注意点:

  • 增、删、改需要提交事务sqlSession.commit();
  • 再往上一级,增加新的实体需要增加新的接口以及新的接口映射配置文件,且配置文件需要去mybatis-config.xml中注册
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值