pom文件
<!-- 数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- lombok 简化set get toString --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!-- mybatis-plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3.1</version> </dependency>
连接数据库yaml代码
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai username: root password: 123456
创建pojo类
@Data @AllArgsConstructor #有参构造器 @NoArgsConstructor #无参构造器 public class User { @TableId(type = IdType.ASSIGN_ID,value = "id")//枚举注解,使用ID_WORKER策略,全局唯一ID,数据库设置自增也没用 private Long id; private String name; private Integer age; private String email; }
分页查询
1.配置拦截器
public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor(); mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());//创建乐观锁拦截器 OptimisticLockerInnerInterceptor mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return mybatisPlusInterceptor; } }
/**源码 * 分页构造函数 * * @param current 当前页 * @param size 每页显示条数 */ public Page(long current, long size) { this(current, size, 0); }