- SpringBoot 整合MyBatis-Plus
- 异常处理
学习内容:
- 整合MyBatis-Plus
- 异常处理
学习时间:
- 2022.07.03
学习产出:
- Spring Boot 整合MyBatis Plus
mysql
mysql-connector-java
com.baomidou
mybatis-plus-boot-starter
3.5.2
com.alibaba
druid
1.2.11
application.yml 相关配置
spring:
#数据源的配置
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.1.5:3306/dd?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=UTC&allowMultiQueries=true
username: root
password: 123456
mybatis:
# 搜索指定包别名
typeAliasesPackage: com.example.**.dto
# 配置mapper的扫描,找到所有的mapper.xml映射文件
mapperLocations: classpath*:mapper*Mapper.xml
# 加载全局的配置文件
configLocation: classpath:mybatis/mybatis-config.xml
mybatis-plus:
configuration:
#控制台输出SQL语句
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapperPackage: com.example.**.mapper
# 对应的 XML 文件位置
mapperLocations: classpath*:mapper*Mapper.xml
项目目录结构
MyBatis Puls 主要代码,基础BaseMapper 就能实现单表通用操作(CRUD)。复杂业务SQL,还是需要Xml的做法。
public interface UserMapper extends BaseMapper{ }
MyBatis Puls 分页实现, 通过selectPage方法返回IPage实现,需要添加MyBatis Puls分页拦截器。
@Configuration
public class MpConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor mpc=new MybatisPlusInterceptor();
mpc.addInnerInterceptor(new PaginationInnerInterceptor());
return mpc;
}
}
表现形式 select * from user limit 5,5
@Override
public IPage pageList(IPage page) {
return userMapper.selectPage(page,null);
}
- 通用异常处理
通过SpringBoot 的Advice实现
可以把Void 改为返回通用对象,处理成前段通用的响应格式。
@RestControllerAdvice
public class ProjectExceptionAdvice {
@ExceptionHandler
public void doException(Exception ex){
//写log
//发通知
//.....
//一定要有这句不然异常会被吃掉
ex.printStackTrace();
}
}



