项目搭建—搭建数据库环境
- 添pom
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
</dependency>
- 改yml
spring:
#数据库配置
datasource:
# mysql5.x的没有cj
driver-class-name: com.mysql.cj.jdbc.Driver
# driver-class-name: com.mysql.jdbc.Driver
#记得先创建数据库
url: jdbc:mysql://localhost:3306/fruitvegetable?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false
username: root
password: xxxxxxx
mybatis-plus:
mapper-locations: classpath*:com/zhku/fruitsandvegetables/*/mapper/xml/*.xml # 这里配置的是你的 .xml文件路径
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
global-config:
db-config:
id-type: auto
- 创建 MybatisPlusConfig 的配置文件
@Configuration
@MapperScan("com.zhku.fruitsandvegetables.*.mapper")
public class MybatisPlusConfig {
//注册乐观锁插件
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
//获取MybatisPlusInterceptor对象
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
//添加内部拦截器(参数为创建一个OptimisticLockerInterceptor(乐观锁拦截器))
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
//将mybatisPlusInterceptor进行返回
return mybatisPlusInterceptor;
}
//分页插件
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor2() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL));
return interceptor;
}
}
- 引入util工具 — 做分页功能需要用到的
public class PageUtil {
public static int[] getPageParam(Integer pageNum,Integer pageSize) {
if (pageNum == null || pageNum < 1) {
pageNum = 1;
}
if (pageSize == null || pageSize < 1) {
pageSize = 10;
}
return new int[]{(pageNum - 1) * pageSize,pageSize};
}
}
补充几个注解 :
- @TableName(“xxx”) 用于 数据库表名 和 实体类名字 不一致的情况,MybatisPlus默认是实体类名字作为查询的数据库表名
- @TableId 这个注解比较关键的是,当你的数据库中设置了主键的情况下,这个注解必须在你实体类上添加,否则mp报错
- @TableLogic 这个注解是用于标注哪个字段是逻辑删除的字段,mp在自动生成sql的时候就会帮你加个逻辑删除的判断
- @TableField(exist = false) 这个注解是用于,你的实体类里面的属性不是数据库表中的字段的时候使用的,如List集合…
- @TableField(value = “username”) 这个注解也可以用来应对实体类属性和数据库字段不一致的问题
- @Param(“userId”) 这个注解也非常的关键,在XXXMapper接口中,传参数到XXXMapper.xml的时候用,#{}获取参数值