1. 添加maven依赖
添加到pom.xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2. 配置MySQL连接
编辑application.properties这个文件,我用的xampp中的MySQL所以root密码为空,我的数据库名字叫"discuss"
spring.datasource.url=jdbc:mysql://localhost/discuss?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
到此为止MyBatis就算是整合进来了,下面我们来测试一下是否成功
验证
在数据库中添加一个user的表
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(100) DEFAULT NULL,
`password` varchar(100) DEFAULT NULL,
`nickname` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
编写一个User的model
public class User {
private Integer id;
private String username;
private String password;
private String nickname;
}
包含了id,username,password,nickname这四个属性,请自行alt+insert生成getter和setter方法
编写一个mapper
@Mapper
public interface UserMapper {
//@Select("SELECT id,username,password,nickname FROM USER")
//User find();
@Insert("INSERT INTO USER (USERNAME,PASSWORD,NICKNAME) VALUES(#{username},#{password},#{nickname})")
void insert(User user);
}
在Controller中添加一个测试方法
首先要注入mapper
@Autowired
UserMapper userMapper;
@RequestMapping("/addUser")
public String add(){
User user = new User();
user.setUsername("admin");
user.setPassword("admin123");
user.setNickname("管理员");
userMapper.insert(user);
return "index";
}
之后浏览器访问:“http://localhost:8080/addUser”
再查看数据库中的user表,如果有数据说明我们MyBatis整合成功
注意点
- 连接MySQL数据库时一定要指定好时区和编码,不然会报错
- 之前开发SSM时习惯于将Controller统一放到包里,但是Spring Boot默认却无法识别提示conflict,只能暂时将controller跟SpringBootApplication放到同一目录