SpringBoot-Web-整合Mybatis

1. IDEA连接数据库

在这里插入图片描述

2. 建立pojo层和实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    
    
  private int id;
  private String name;
  private String pwd;
}

3. 建立mapper层,CRUD接口和接口映射文件

@Mapper
@Repository
public interface StudentMapper {
    
    
    List<Student> queryStudentList();

    Student queryStudentById(@Param("id") int id);

    int addStudent(Student student);

    int deleteStudentById(@Param("id") int id);

    int updateStudentById(Student student);

}

<?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=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.qk.mapper.StudentMapper">
    <select id="queryStudentList" resultType="student">
        select * from student;
    </select>

    <select id="queryStudentById" resultType="student">
        select * from student where id = #{id};
    </select>

    <insert id="addStudent" parameterType="student">
        insert into student (id,name,pwd) value (#{id},#{name},#{pwd});
    </insert>

    <delete id="deleteStudentById" parameterType="Integer">
        delete from mybatis.student where id = #{id};
    </delete>

    <update id="updateStudentById" parameterType="student">
        update student set name=#{name},pwd=#{pwd} where id=#{id}
    </update>
</mapper>

4. 编写配置文件,mybatis连接数据库,整合mybatis:设置别名和绑定映射文件

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver

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

5. 建立controller层,调用mapper接口的方法返回查询结果


@RestController
public class StudentController {
    
    
    @Autowired
    private StudentMapper studentMapper;


    @GetMapping("/allStudent")
    public List<Student> student01(){
    
    
        List<Student> studentList = studentMapper.queryStudentList();
        return studentList;
    }
    @RequestMapping("/aStudent")
    public Student student02(){
    
    
        Student student = studentMapper.queryStudentById(9);
        return student;
    }
    @RequestMapping("/addStudent")
    public void stdent03(){
    
    
        studentMapper.addStudent(new Student(007,"zz","123"));
    }
    @RequestMapping("/delStudent")
    public void student04(){
    
    
        studentMapper.deleteStudentById(1);
    }

    @RequestMapping("/updStudent")
    public void test05(){
    
    
        studentMapper.updateStudentById(new Student(9,"vv","vvv"));
    }
}


6. 测试

在这里插入图片描述


回顾:

在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40429067/article/details/113728058