1.引入依赖
引入mybatis提供的stater,以及druid数据源和mysql驱动器和lombok依赖:
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- druid 数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.17</version>
</dependency>
<!-- mybatis第三方stater -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- lombok插件依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
lombok插件:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
2.在applicaiton.yaml中配置数据源以及mybatis
在application.yaml中配置数据源,以及mybatis:
# 数据源配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/phpdemo?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
# mybatis整合
mybatis:
#config-location: classpath:mybatis/mybatis-config.xml # 指定mybatis-config.xml全局配置文件的位置,可以不写
mapper-locations: mapper/* # 指定mapper.xml配置文件的位置
configuration:
map-underscore-to-camel-case: true # 开启下划线转驼峰命名
通过 mybatis.mapper.locations来指定mapper.xml映射文件的位置,mybatis-config.xml可以不指定位置(也不创建)。
3.创建sql测试表
创建一个Book表:
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for book
-- ----------------------------
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`bookName` varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
`bookPrice` decimal(10, 2) NOT NULL,
`author` varchar(30) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of book
-- ----------------------------
INSERT INTO `book` VALUES (1, '平凡的世界', 59.00, '路遥');
INSERT INTO `book` VALUES (2, '三体', 99.00, '刘慈欣');
INSERT INTO `book` VALUES (3, '人间失格', 44.00, '太宰治');
INSERT INTO `book` VALUES (4, '白夜行', 38.00, '东野圭吾');
SET FOREIGN_KEY_CHECKS = 1;
4.编写mapper接口和mapper.xml文件
4.1 mapper接口
在springboot中,使用@Mapper注解来标识一个接口为mapper接口,也可以通过在主启动程序上使用@MapperScan(“com.robin.boot.mapper”)的方式来扫描指定的包为mapper接口的包。
这里我使用第一种方式,通过@Mapper注解来标识接口:
package com.robin.boot.mapper;
import com.robin.boot.bean.Book;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper // 在springboot中通过 @Mapper注解来标识一个接口为mapper接口
public interface BookMapper {
// 查询所有书籍
public List<Book> queryAllBook();
// 根据id查询单本书
public Book findBookById(Long id);
}
4.2 mapper.xml
在类资源路径下,创建对应的mapper.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">
<mapper namespace="com.robin.boot.mapper.BookMapper">
<!-- public List<Book> queryAllBook(); -->
<select id="queryAllBook" resultType="com.robin.boot.bean.Book">
select * from phpdemo.book
</select>
<!-- public Book findBookById(Long id); -->
<select id="findBookById" resultType="com.robin.boot.bean.Book">
select * from phpdemo.book where id = #{id}
</select>
</mapper>
4.3 mybatisX快速开发插件
推荐安装一个mybatisX插件,这样可以方便的跳转mapper接口和对应的xml配置文件
如下图,当mapper.xml与mapper接口绑定时,会有小鸟图标显示,开发很方便观察
5.创建service层和controller层
5.1 创建service层
mvc三层架构的方式:service层包括sevice接口和对应实现类serviceImpl
service接口:
package com.robin.boot.service;
import com.robin.boot.bean.Book;
import java.util.List;
public interface BookService {
// 查询所有书籍
public List<Book> queryAllBook();
// 根据id查询单本书
public Book findBookById(Long id);
}
serviceImgl实现类:
package com.robin.boot.service.impl;
import com.robin.boot.bean.Book;
import com.robin.boot.mapper.BookMapper;
import com.robin.boot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class BookServiceImpl implements BookService {
@Autowired // 自动注入
BookMapper bookMapper;
@Override
public List<Book> queryAllBook() {
return bookMapper.queryAllBook();
}
@Override
public Book findBookById(Long id) {
return bookMapper.findBookById(id);
}
}
5.2 创建controller层
编写controller以及请求映射,这里为了方便,我就直接通过返回字符串json数据来响应请求,不去编写对应的html页面了
controller:
package com.robin.boot.controller;
import com.robin.boot.bean.Book;
import com.robin.boot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
public class BookController {
@Autowired
BookService bookService;
@ResponseBody // 以json的格式返回数据
@GetMapping("/allBook")
public String queryAllBook(){
// 调用service层来查询所有书籍数据
List<Book> books = bookService.queryAllBook();
// 为了演示,简单的将其返回字符串
return books.toString();
}
@ResponseBody
@GetMapping("/book/{id}")
public String findBookById(@PathVariable("id") Long id){
Book book = bookService.findBookById(id);
return book.toString();
}
}
6.项目结构及运行测试
6.1 项目结构
6.2 运行测试
查询所有书籍 localhost:8080/allBook
查询单本书籍localhost:8080/book/id号
7.小结
在springboot中整合使用mybatis很方便,只要引入对应的stater,然后在application.yaml或者application.properties配置文件中进行配置即可(配置对应的mapper.xml的路径,还有很多配置,可以参考对应的官方文档),注意使用mapper接口时通过@Mapper注解标识,或者通过@MapperScan注解扫描对应的mapper包。