准备
介绍
springboot整合mybatis,配置方式:
- 注解+配置文件,sql写在xml中。适合传统大项目
- 全注解,sql写在注解中。适合简单快速开发
在测试时,需要实现controller、service、mybatis相关类、相关配置文件,以及使用druid数据库连接池,比较复杂,稍有不慎,就会报错
本文使用 注解+配置文件,sql写在xml中
准备mysql表
CREATE TABLE `book` (
`id` VARCHAR(32) NOT NULL COMMENT '主键' COLLATE 'utf8mb4_unicode_ci',
`title` VARCHAR(64) NULL DEFAULT NULL COMMENT '书名' COLLATE 'utf8mb4_unicode_ci',
`author` VARCHAR(64) NULL DEFAULT NULL COMMENT '作者' COLLATE 'utf8mb4_unicode_ci',
PRIMARY KEY (`id`)
)
COLLATE='utf8mb4_unicode_ci'
ENGINE=InnoDB
;
druid数据库连接池
略
springboot使用druid连mysql5.7(mysql5驱动)
springboot使用druid连mysql5.7(mysql8驱动)
mybatis依赖
找到mybatis依赖
在 https://mvnrepository.com/ 搜索 mybatis,找到MyBatis Spring Boot Starter
添加依赖
将上图中的红框处粘贴到pom.xml文件中
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
已经包含 spring-boot-starter-jdbc
注意:必须是 2.0.1 以上,否则没有下面用到的 @MapperScan 注解
实体类
package top.malaoshi.entity
public class Book {
private String id;
private String title;
private String author;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
mapper接口
package top.malaoshi.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.example.entity.Book;
@Mapper
public interface BookMapper {
public int save(Book book);
public int deleteById(String id);
public int updateById(Book book);
public Book getById(String id);
}
让 mapper 接口生效
springboot+mybatis,有2种方式让 mapper 接口生效:
mapper接口由
@Mapper注解修饰mapper接口由
@Repository注解修饰
主启动类由@MapperScan("top.malaoshi.mapper")修饰,扫描top.malaoshi.mapper包下的类,使其生效
mapper.xml文件
保存位置
BookMapper.xml 内容
<?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="top.malaoshi.mapper.BookMapper">
<insert id="save" parameterType="org.example.entity.Book">
insert into book (id,title,author) values (#{id},#{title},#{author})
</insert>
<delete id="deleteById">
delete from book where id=#{id}
</delete>
<update id="updateById" parameterType="org.example.entity.Book">
update book set title=#{title},author=#{author} where id=#{id}
</update>
<select id="getById" resultType="org.example.entity.Book">
select id,title,author from book where id=#{id}
</select>
</mapper>
注意:
<mapper namespace="top.malaoshi.mapper.BookMapper">必须是BookMapper全路径
mybatis总配置文件
保存位置
在 resources/mybatis 目录下,如下图:
mybatis-config.xml 内容
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>
注意: <package name="top.malaoshi.entity"/>必须是上面 实体类的包路径
修改springboot配置文件
整合mybatis
application.yml
增加下面部分
# 整合mybatis
mybatis:
config-location: classpath:mybatis/mybatis-config.xml #mybatis总配置文件
mapperLocations: classpath:mybatis/mapper/*.xml # xxxMapper.xml配置文件
application.properties
增加下面部分
# 整合mybatis
#mybatis总配置文件
mybatis.config-location: classpath:mybatis/mybatis-config.xml
# xxxMapper.xml配置文件
mybatis.mapperLocations: classpath:mybatis/mapper/*.xml
注意
classpath指src/main/resources路径,
classpath:mybatis/mybatis-config.xml指src/main/resources/mybatis/mybatis-config.xmlclasspath:mybatis/mapper/*.xml指src/main/resources/mybatis/mapper/mybatis-config.xml
创建service接口
package top.malaoshi.service;
import org.example.entity.Book;
public interface IBookService {
public int save(Book book);
public int deleteById(String id);
public int updateById(Book book);
public Book getById(String id);
}
创建service接口实现类
package top.malaoshi.service.impl;
import top.malaoshi.entity.Book;
import top.malaoshi.mapper.BookMapper;
import top.malaoshi.service.IBookService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.UUID;
@Service
public class BookSrvImpl implements IBookService {
@Resource
private BookMapper bookMapper;
@Override
public int save(Book book) {
String uuid= UUID.randomUUID().toString().replace("-","");
book.setId(uuid);
int i=bookMapper.save(book);
return i;
}
@Override
public int deleteById(String id) {
return bookMapper.deleteById(id);
}
@Override
public int updateById(Book book) {
return bookMapper.updateById(book);
}
@Override
public Book getById(String id) {
return bookMapper.getById(id);
}
}
JsonResult
package top.malaoshi.vo;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class JsonResult <T> {
private int code;
private String msg;
private T data;
public JsonResult() {
}
public JsonResult(int code, String msg) {
this.code = code;
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
创建Controller
package top.malaoshi.controller;
import org.springframework.web.bind.annotation.*;
import top.malaoshi.entities.Book;
import top.malaoshi.vo.JsonResult;
import top.malaoshi.service.IBookService;
import javax.annotation.Resource;
import javax.annotation.Resource;
@RestController
public class BookCtrl {
@Resource
private IBookService bookService;
//restful风格
@PostMapping("/book")
public JsonResult save(String title,String author){
Book book=new Book();
book.setTitle(title);
book.setAuthor(author);
bookService.save(book);
return new JsonResult(0,"success");
}
@DeleteMapping("/book/{id}")
public JsonResult deleteById( @PathVariable String id){
JsonResult jr=new JsonResult(0,"success");
int num=bookService.deleteById(id);
if(num==0){
jr.setCode(100);
jr.setMsg("没有该条记录,无法删除!");
}
return jr;
}
@PutMapping("/book")
public JsonResult updateById(String id,String title,String author){
JsonResult jr=new JsonResult(0,"success");
Book book=new Book();
book.setId(id);
book.setTitle(title);
book.setAuthor(author);
int num=bookService.updateById(book);
if(num==0){
jr.setCode(100);
jr.setMsg("没有该条记录,无法更新");
}
return jr;
}
@GetMapping("/book/{id}")
public JsonResult getById(@PathVariable String id){
JsonResult<Book> jr=new JsonResult(0,"success");
Book book=bookService.getById(id);
jr.setData(book);
return jr;
}
}
修改主启动类
mapper 接口使用 @Repository 注解修饰时,需要在主启动类增加下面注解:
@MapperScan("org.example.mapper")
扫描 top.malaoshi.mapper 包下的类,使其生效
注意: 如果 mapper 接口使用 @Mapper 注解修饰,则 不需要修改主启动类(加上也不报错)
例子
@SpringBootApplication
@MapperScan("top.malaoshi.mapper")
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class,args);
}
}
为什么增加此注解?
见下面链接:
https://www.malaoshi.top/show_1EF6RCe0gjUK.html
mapper
https://www.cnblogs.com/ityouknow/p/6037431.html
dao
https://segmentfault.com/a/1190000017211657


