springboot整合mybatis

it2023-09-03  67

整合包

org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.1 创建一个新的springboot项目 选中web,jdbc,mysql驱动依赖 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20201020195604303.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzMTgyODI3,size_16,color_FFFFFF,t_70#pic_center) 在pom.xml中导入依赖 org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.1

配置数据源 连接数据库 建立对应的实体类

public class Student { private Integer id; private String name; private int age; public Student(){ } public Student(Integer id, String name, int age) { this.id = id; this.name = name; this.age = age; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }

写一个mapper接口

//这个注解表示这是一个mybatis的mapper类 @Mapper @Repository //交给spring托管 public interface StudentMapper { public int addStudent(Student student); public int delStudent(Integer id); public int updStudent(Student student); public List<Student> selStudent(); public Student selStudentById(Integer id); }

在resources下对应的xml文件

在application.yaml中配置属性 classpath代表resources文件夹

#整合mybatis mybatis: type-aliases-package: com.briup.pojo mapper-locations: classpath:mybatis/mapper/*.xml

写Student.xml文件,写sql

<?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"> <mapper namespace="com.briup.mapper.StudentMapper"> <insert id="addStudent" parameterType="Student" > insert into student(id,name,age) values (#{id},#{name},#{age}); </insert> <delete id="delStudent" parameterType="int"> delete from student where id =#{id}; </delete> <update id="updStudent" parameterType="Student"> update student set name=#{name},age=#{age} where id=#{id}; </update> <select id="selStudent" resultType="Student"> select * from student; </select> <select id="selStudentById" resultType="Student"> select * from student where id =#{id}; </select> </mapper>

写一个controller测试一下

@RestController public class StudentController { @Autowired private StudentMapper studentMapper; @GetMapping("/selStudent") public List<Student> selStudent(){ return studentMapper.selStudent(); } }

成功

最新回复(0)