mybatis-plus

常用注解

@TableName(“employee”) //当实体类名与数据库表名不一致时,进行关系映射
@TableId(type = IdType.AUTO) //使用数据库id自增
@TableField(“name”) //当实体类属性和数据库中字段不一致时,进行关系映射
@TableField(exist = false) //数据库中不存在该字段,解除字段与列映射
@TableName(“employee”) //当实体类名与数据库表名不一致时,进行关系映射

public class Employee {
    @TableId(type = IdType.AUTO)   //使用数据库id自增
    private Long id;
    @TableField("name")    //当实体类属性和数据库中字段不一致时,进行关系映射
    private String name;
    private String password;
    private String email;
    private int age;
    @TableField(exist = false)  //数据库中不存在该字段,解除字段与列映射
    private int admin;
    private Long deptId;
}

自动封装的方法

1、employeeMapper.updateById(employee); 会将实体类中属性为 null 的字段忽略,不为 null 的字段拼接 update sql 语句。

实体类中使用 int 类型不赋值时默认是 0 ,更新时会将 0 更新到数据库中,而使用 integer 类型不赋值时默认是 null,就不会拼接sql 语句而更新。
解决方法:

  1. 将实体类中 int 类型改为 integer 封装类型
  2. 使用 updateWrapper 条件构建
UpdateWrapper<Employee> wrapper = new UpdateWrapper<>();
wrapper.eq("id",1L);
wrapper.set("name","dada");
employeeMapper.update(null,wrapper);

分页查询

1.配置 mybatisPlus 分页拦截器

//配置mybatisPlus 分页拦截器
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
    MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
    PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(DbType.MYSQL);
    interceptor.addInnerInterceptor(paginationInnerInterceptor);
    return interceptor;
}

2.编写分页查询代码

@Test
public void test(){
    QueryWrapper<Employee> wrapper = new QueryWrapper<>();
    //查询第一页十条数据
    Page<Employee> page = new Page<>(1,10);
    //查询到的数据封装到 page 对象中
    employeeMapper.selectPage(page,wrapper);
    System.out.println(page.getRecords()); //输出查询到的数据
}

条件构造器

在这里插入图片描述

UpdateWrapper :

eq 表示 update sql 语句 where 后面条件, set 表示更新的字段(第一个参数 boolean 类型表示是否拼接改字段,可以实现动态 sql)
在这里插入图片描述


LambdaUpdateWrapper:

与updateWrapper 相比,列名使用方法引用,防止自己列明写错
在这里插入图片描述


QueryWrapper:

在这里插入图片描述


LambdaQueryWrapper:

列名使用方法引用,防止自己列明写错
在这里插入图片描述


wrappers 工具类

wrappers 工具类可以创建各种类型的 wrapper

高级查询

select

在这里插入图片描述

# 1.挑选要查询的列
QueryWrapper<Employee> wrapper = Wrappers.query();
wrapper.select("id","name");    // id 和 name 是需要查询的列

order by

在这里插入图片描述
在这里插入图片描述


group by

在这里插入图片描述


having

在这里插入图片描述
在这里插入图片描述


条件语句

在这里插入图片描述

通用 Service 接口
mapper 接口(继承 BaseMapper<实体类名> 接口)

public interface EmployeeMapper extends BaseMapper<Employee> {
    List<Employee> getAllEmployee();
}

service 接口(继承 IService<实体类名> 接口)

public interface IEmployeeService extends IService<Employee> {

}

service 实现类(继承 ServiceImpl<xxxMapper,实体类名> 类)

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper,Employee> implements IEmployeeService {
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值