基于白嫖:【狂神说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 总结
当配置好环境之后,添加功能的通用步骤为:
注意点:
- 增、删、改需要提交事务
sqlSession.commit();
; - 再往上一级,增加新的实体需要增加新的接口以及新的接口映射配置文件,且配置文件需要去
mybatis-config.xml
中注册;