mybatis集成
mybatis集成
导入starter依赖
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
官网文档链接
http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
代码参考
纯注解版代码CRUD
-
创建Mapper编写基本增删改查
@Mapper @Repository public interface StudentMapper { @Select("select * from Student ") List<Student> getAllStudent(); @Insert("insert into student(stuId,stuName)values(#{stuId},#{stuName})") int addStudent(Student student); @Update("update student set stuName=#{stuName} where stuId=#{stuId}") int updateStudent(Student student); @Delete("delete from student where stuId=#{stuId}") int delStudent(String stuId); }
-
实体类进行映射
@Data //使用lombok减少get、set、有参无参构造函数、tostring等方法的冗余 @AllArgsConstructor @NoArgsConstructor public class Student { private String stuId; private String stuName; private Integer stuSex; private String stuAddress; private Integer stuAge; }
-
编写Controller进行测试
@RestController @RequestMapping("/test") public class TestController { @Autowired private StudentMapper studentMapper; @GetMapping("/getStudentAll") public List<Student> getStudentAll(){ return studentMapper.getAllStudent(); } @GetMapping("/addStudent") public List<Student> addStudent(){ Student stu=new Student(); stu.setStuId(UUID.randomUUID().toString()); stu.setStuName("测试"); studentMapper.addStudent(stu); return studentMapper.getAllStudent(); } @GetMapping("/updateStudent") public List<Student> updateStudent(){ Student stu=new Student(); stu.setStuId("f2adf775-3cfa-4e25-97bc-ec5676e15594"); stu.setStuName("修改了用户"); studentMapper.updateStudent(stu); return studentMapper.getAllStudent(); } @GetMapping("/delStudent") public List<Student> delStudent(){ String stuId="f2adf775-3cfa-4e25-97bc-ec5676e15594"; studentMapper.delStudent(stuId); return studentMapper.getAllStudent(); } }
通过配置文件进行操作
-
配置application.yml扫描mapper配置文件
mybatis: mapper-locations: classpath:mybatis/*.xml
-
创建mapper文件进行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.lwp.study.dao.StudentMapper"> <select id="getAllStudent" resultType="com.lwp.study.pojo.Student"> select * from student </select> <update id="updateStudent"> update student set stuName=#{stuName} where stuId=#{stuId} </update> <delete id="delStudent"> delete from student where stuId=#{stuId} </delete> <insert id="addStudent"> insert into student(stuId,stuName)values(#{stuId},#{stuName}) </insert> </mapper>
-
添加mapper映射类,和纯注解的mapper类一样,去掉注解即可,实体类也一致
如出现xml文件问题
<!--maven配置资源过滤问题-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>