springboot是JAVA最省事的框架,不接受反驳
如何集成Mybatis,只需要简单几步
一、pom文件中添加mybatis,数据库依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
二、配置数据库账号密码之类的配置
PS:本人更偏爱于yml文件风格,所以不使用application.properties文件
将resource下的application.properties文件删除,加入application.yml文件(配置了四个文件方便测试,开发,线上)
PS:其实SpringBoot底层会把application.yml文件解析为application.properties)
application.yml
spring:
profiles:
active: dev
application-dev.yml
server:
port: 8088
spring:
datasource:
username: root
password: 123
url: jdbc:mysql://localhost:3306/ge_data?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
mybatis:
mapper-locations: classpath:mapping/*Mapper.xml
type-aliases-package: com.company.po
#showSql
logging:
level:
com:
example:
mapper : debug
上面列出两个我配置的文件
为什么要配置四个呢?
因为现在一个项目有好多环境,开发环境,测试环境,准生产环境,生产环境,每个环境的参数不同,
所以我们就可以把每个环境的参数配置到yml文件中,
而最终是根据application.yml中选择的哪个文件去加载
例:(spring.profiles.active= dev-->代表是选择加载application-dev.yml这个文件)
PS:在Spring Boot中多环境配置文件名需要满足application-{profile}.yml的格式,其中{profile}对应你的环境标识,比如:
application-dev.yml:开发环境
application-test.yml:测试环境
application-prod.yml:生产环境
至于哪个具体的配置文件会被加载,需要在application.yml文件中通过spring.profiles.active属性来设置,其值对应{profile}值。
PS:还有配置文件中最好不要有中文注释,会报错。并且启动类必须放在java这个目录下?为什么这样?约定大于配置呗
好了,集成完成,测试一下
三、测试
创建数据库,entity类
mapper 类
@Mapper
public interface CardUserMapper {
@Select("select *from t_grade_user limit 0,10")
List<CardUserEntity> getUserList();
}
serivce类
public interface CardUserService {
List<CardUserEntity> getUserList();
}
实现类
@Service("cardUserService")
@Transactional
public class CardUserServiceImpl implements CardUserService {
@Resource
private CardUserMapper cardUserMapper;
@Override
public List<CardUserEntity> getUserList() {
return cardUserMapper.getUserList();
}
}
控制器
@RestController
@RequestMapping("/user")
public class CardUserController {
@Autowired
private CardUserService cardUserService;
@RequestMapping("/userList")
public List<CardUserEntity> getUserList(){
List<CardUserEntity> cardUserEntities=cardUserService.getUserList();
return cardUserEntities;
}
}
启动 postman 访问 localhost:8088/user/userList
![]()

本文详细介绍如何在SpringBoot项目中集成Mybatis框架,包括添加依赖、配置数据库、使用YAML进行多环境配置,以及创建实体类、Mapper、Service和Controller进行数据操作的全过程。
3093

被折叠的 条评论
为什么被折叠?



