添加
使用方法insert
相关注解
表名和类名不一致时 为我们可以使用以下注解完成映射
-
@TableName 解决表名与实体类名不一致的问题
作用:指定类为哪个表的实体类
位置:类上方
-
@TableId
作用:指定实体类的属性为主键
位置:属性上方
属性: value:主键字段名 type:主键策略
- @TableField
作用:在属性和列名不同的情况下,指定映射关系
@TableField("sname")
private String name;
位置:非主键属性上方
修改
@Test
public void testUpdate() {
//创建实体类对象
Student student = new Student();
//设置需要更新的属性
student.setName("百战程序员");
//设置需要修改的数据id
student.setId(1);
//根据主键进行更新,没有设置的值则忽略
studentMapper.updateById(student);
}
删除
- 根据id删除 deleteById
- 批量删除 deleteBatchIds
- 根据字段条件删除 deleteByMap
// 根据id删除
@Test
public void testDeleteById(){
studentMapper.deleteById(7);
}
// 批量删除
@Test
public void testDeleteBatch(){
ArrayList<Integer> ids = new ArrayList();
ids.add(2);
ids.add(3);
studentMapper.deleteBatchIds(ids);
}
// 根据字段条件删除
@Test
public void testDeleteMap(){
Map<String,Object> map = new HashMap();
// 键为数据库列名,而不是对象属性名
map.put("sname","小王");
map.put("gender","m");
// 删除name为小王且gender为m的数据
studentMapper.deleteByMap(map);
}
查询
- 根据id查询 selectById
- 根据id批量查询 selectBatchIds
- 根据字段条件查询 selectByMap
// 根据id查询
@Test
public void testFindById() {
Student student = studentMapper.selectById(1);
System.out.println(student);
}
// 根据id批量查询
@Test
public void testFindBatch() {
//创建主键集合
List<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);
List<Student> students = studentMapper.selectBatchIds(ids);
students.forEach(System.out::println);
}
// 根据字段条件查询
@Test
public void testFindMap() {
Map<String,Object> map = new HashMap<>();
map.put("sname","baizhan");
map.put("gender","m");
//查询name为baizhan,gender为m的数据
List<Student> students =studentMapper.selectByMap(map);
students.forEach(System.out::println);
}
条件构造器
Mybatis-Plus通过QueryWrapper对象让用户自由的构建SQL条件,简单便捷,没有额外的负担,能够有效提高开发效率。
具体代码示例见文档
分页查询
在配置类或启动类配置分页插件
// 注册插件
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
测试分页查询
// 分页查询
@Test
public void testFindPage() {
//创建分页条件,从第0条数据开始,获取两条数据
Page page = new Page(2,2);
// 分页查询
IPage<Student> iPage =studentMapper.selectPage(page, null);
// 打印分页数据
System.out.println("结果集:"+iPage.getRecords());
System.out.println("总页数:"+iPage.getPages());
System.out.println("总条数:"+iPage.getTotal());
System.out.println("当前页:"+iPage.getCurrent());
System.out.println("每页条数:"+iPage.getSize());
}
全局配置
假如数据库的所有表都以 tb_ 开头,主键都是自增的。如果针对每一个实体类都要添加相关注解比较麻烦,可以在SpringBoot配置文件中进行全局配置,该配置在所有的实体类中都生效。
mybatis-plus:
# 全局配置
global-config:
db-config:
#主键类型
id-type: AUTO
# 设置表名前缀
table-prefix: tb_
# 是否使用驼峰转下划线命名,默认开启
table-underline: true