1.导包
<!-- mysql 驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<!--mybatisplus起步依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
2.配置
# datasource spring: datasource: url: jdbc:mysql://111.111.111.111:3306/mp?serverTimezone=UTC username: root password: root driver-class-name: com.mysql.jdbc.Driver mybatis-plus: global-config: db-config: # 表名前缀 实际表名就是前缀 + 类名 table-prefix: tb_ # id生成策略 数据库自增 id-type: auto
启动类
@SpringBootApplication //启动注解
@MapperScan("com.tang.mapper")
public class MybatisPlusSpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusSpringbootApplication.class, args);
}
}
与表对应的类
- @Data
@TableName("tb_user")//对应数据库中的哪个表
public class User {
@TableId(type = IdType.AUTO) //数据库自增
private Long id;
@TableField("user_name") //指定映射关系,名字相同或者 _ 换小驼峰 则会自动识别
private String userName;
private String password;
private String name;
private Integer age;
private String email;
@TableField(exist = false) //忽略这个字段的查询和插入
private String HaHa;
}
分页查询:1.配置拦截器。2.创建page对象
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return mybatisPlusInterceptor;
}
分页查询
@Test
public void test05(){
int page = 1; //当前页数
int size = 4; //每页条数
User user = new User(); //前台传过来的查询套件
user.setUserName("zhangsan");
QueryWrapper<User> queryWrapper =null;
if(user!=null){
//有条件再创建queryWrapper 这里相当于之前的动态sql
queryWrapper = new QueryWrapper<>();
if(StringUtils.isNotBlank(user.getUserName())){ //里面有值
queryWrapper.eq("user_name",user.getUserName());
}
if(StringUtils.isNotBlank(user.getPassword())){ //里面有值
queryWrapper.eq("password",user.getPassword());
}
}
//分页查询
Page<User> userPage = userMapper.selectPage(new Page<>(page, size), queryWrapper);
List<User> records = userPage.getRecords(); //数据
long total = userPage.getTotal(); //一共的条数
long pages = userPage.getPages(); //一共的页数
System.out.println(records);
System.out.println(total);
System.out.println(pages);
}