- 因为遵循着约定优于配置的规范,所以在快速开发的时候非常方便
- MyBatis 是 SSM 项目中的 M,主要负责人项目与数据库之间的相关操作,在项目中作用体现在持久层(有的也称为数据层)
- 此处我使用的是 ALiBaBa 的国内源:https://start.aliyun.com/
- 指定项目的基本信息
- 添加相关的依赖
- 连接数据库,生成对应的实体对象
- 生成数据表对应的实体类
package com.lagou.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Comment implements Serializable {
private static final long serialVersionUID = -20796280730949307L;
private Integer id;
private String content;
private String author;
private Integer aId;
}
- 编写对应的mapper接口
package com.lagou.dao;
import com.lagou.entity.Comment;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CommentDao {
// 根据 id 查询对应的记录
public Comment findById(Integer id);
}
- 编写对应的 mapper 映射文件
select * from t_comment where id = #{id}
- 编写 配置文件
# 端口
server:
port: 8888
# 应用名称
spring:
application:
name: springboot-mybatis
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.159.133:3306/springbootdata?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: liuyunfei
password: Lyf123456!
# MyBatis 配置
mybatis:
configuration:
# 驼峰命名法
map-underscore-to-camel-case: true
# 指定映射文件
mapper-locations: classpath:mapper
@RestController
@RequestMapping("/comment")
public class CommentController {
@Autowired
private CommentDao commentDao;
@RequestMapping("/{id}")
public Comment getCommentById(@PathVariable("id") Integer id){
Comment comment = commentDao.findById(id);
return comment;
}
}
-
首先启动项目
-
浏览器进行接口的访问:http://127.0.0.1:8888/comment/1
以上就是 SpringBoot 结合 MyBatis 使用的案例,虽然简单,但是基本功能都已经实现了,希望可以帮助到大家



