SpringBoot 与Mybatis结合比较的简单,我们是在SpringBoot中去整合Mybatis。首先我们需要准备两个Maven项目,一个是SpringBoot的,另一个是Mybatis的。
SpringBootMaven项目详细介绍在企业级智能软件开发(一)———Spring Boot
Mybatis项目详细介绍在企业级智能软件开发(二)——Mybatis
整合方法利用官方提供的Spring Boot启动器,就能自动完成绝大部分配置。
步骤:
- 在SpringBoot项目的 pom.xml 加入依赖
org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.2 mysql mysql-connector-java 5.1.49
- 配置数据库连接信息
创建配置文件application.properties加入配置
#数据库相关配置 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/user?useSSL=FALSE&serverTimezone=GMT%2B8
- 指定Mapper扫描的包名
在Application.java加入一行
@MapperScan("com.test.dao")
4. 将Mybatis项目的java包com.test.bean跟com.test.dao一起移到SpringBoot项目中
5. 编写控制器类UserController.java的代码
package com.test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.test.bean.User;
import com.test.dao.UserDao;
@RestController
@RequestMapping("/User")
public class UserController {
@Autowired
private UserDao userDao;
@PostMapping("/info")
public User Us(Integer id) {
User user = userDao.getUserById(id);
return user;
}
}
运行SpringBoot项目
在POSTman中查看结果:



