【MyBatisPlus笔记整理三】CRUD详解

版权声明:本文为 小异常 原创文章,非商用自由转载-保持署名-注明出处,谢谢!
本文网址:https://blog.csdn.net/sun8112133/article/details/106917361







本篇博客是 MyBatis Plus 中的核心内容,将会为大家讲解 CRUD 操作。


一、准备工作

先准备一张表和对应的实体类以及 Mapper。

1、数据表

create table `t_user` (
	`id` int(11) not null auto_increment,
	`name` varchar(255),
	`age` int(11),
	primary key (`id`)
);

-- 随意插入几条记录

2、实体类

@Data
@TableName("t_user")
public class User {
    @TableId(type=IdType.INPUT)
    private Integer id;
    private String name;
    private Integer age;
}

3、Mapper

public interface UserMapper extends BaseMapper<User> {
	
}


二、添加

调用 insert() 方法实现添加效果。

  • int insert(T t):添加方法,返回添加的条数。
@Autowired
private UserMapper mapper;

@Test
void save() {
    User user = new User();
    account.setTitle("张三");
    account.setAge(12);
    mapper.insert(user);
    System.out.println(user);
}


三、删除

1、根据 id 删除

  • int deleteById(Serializable id):根据单个 id 删除,返回删除的条数;
  • int deleteBatchIds(Collection idList):根据多个 id 删除,返回删除的条数。
@Test
void delete() {
	// 根据 id 删除
	mapper.deleteById(1);
	
	// 删除多个,根据多个id
	mapper.deleteBatchIds(Arrays.asList(1, 2));
}

2、根据条件删除

  • int delete(Wrapper wrapper):根据指定条件进行删除,返回删除的条数;
  • int deleteByMap(Map map):根据指定条件进行删除,返回删除的条数。这个条件放到 Map 集合中,Map 中的条件都是以 And 连接的,它只能做等值判断。
@Test
void delete() {		
    // 根据指定条件进行删除
    QueryWrapper<User> wrapper = new QueryWrapper();
    wrapper.eq("age", 1);  // 删除 age 属性为 1 的记录,其中 eq 是等于的意思,类似的还有 lt(小于)、gt(大于)
    mapper.delete(wrapper);

    // 根据条件删除,条件放到 Map 集合中,Map 中的条件都是以 And 连接的
    Map<String, Object> map = new HashMap<>();
    map.put("id", 5);  // 删除 id 为 5 的记录
    mapper.deleteByMap(map);
}


四、修改

  • int updateById(T entity):根据 id 修改,返回修改的条数;
  • int update(T entity, Wrapper wrapper):根据条件修改,返回修改的条数。
@Test
void update() {
    // 根据 id 修改
    User user = mapper.selectById(1);  // 根据 id 从数据库中查询对应的记录
    account.setName("张三");
    mapper.updateById(user);   // 根据 id 修改

    // 根据条件修改
    User user = mapper.selectById(3);
    user.setName("李四");
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    wrapper.eq("id", 3);
    mapper.update(user, wrapper);   // 根据 id 为 3 这个条件进行修改
}


五、查询

1、根据 id 查询

  • T selectById(Serializable id):根据单个 id 查询,返回查询到的实体对象;
  • List selectBatchIds(Collection idList):根据多个 id 查询,返回查询到的实体对象列表。
@Test
void select() {
    // 根据 ID 查询
    mapper.selectById(2);

    // 根据多个 ID 查询
    mapper.selectBatchIds(Arrays.asList(2, 3, 5)).forEach(System.out::println);
}

2、根据条件查询

  • List selectList(Wrapper wrapper):根据指定条件去查询,返回查询到的实体对象;
  • List selectByMap(Map map):根据指定条件去查询,这个条件放到 Map 集合中,它与 selectList() 方法的区别在于 Map 只能做等值判断,逻辑判断需要使用 Wrapper 来处理;
  • List<Map> selectMaps(Wrapper wrapper):根据指定条件去查询,条件使用 Wrapper,它会将结果封装到 Map 中,它与 selectList() 方法的区别在于,一个是以 Map 集合返回,一个是以实体对象返回。
@Test
void select() {
	// selectList() 方法:
	// 不加任何条件,全部查询
	mapper.selectList(null);
    
	// 等于条件查询
	QueryWrapper<Account> wrapper = new QueryWrapper<>();
	wrapper.eq("name", "小红");
	System.out.println(mapper.selectList(wrapper));
    
	// 多条件查询
	QueryWrapper<Account> wrapper = new QueryWrapper<>();
	Map<String, Object> map = new HashMap<>();
	map.put("name", "小明");
	map.put("age", 2);
	wrapper.allEq(map);
	System.out.println(mapper.selectList(wrapper));
	
	// 小于条件查询(小于lt,大于gt,小于等于le,大于等于ge)
	QueryWrapper<Account> wrapper = new QueryWrapper<>();
	wrapper.lt("age", 2);
	System.out.println(mapper.selectList(wrapper));

    // 不等于条件查询
	QueryWrapper<Account> wrapper = new QueryWrapper<>();
	wrapper.ne("age", 2);
	System.out.println(mapper.selectList(wrapper));

	// selectByMap() 方法:
	// 条件查询,类似 wrapper
	// Map 只能做等值判断,逻辑判断需要使用 Wrapper 来处理
	Map<String, Object> map = new HashMap<>();
	map.put("id", "2");
	mapper.selectByMap(map);

	// selectMaps() 方法:
	// 条件查询 与 selectList() 的区别在于,一个是以 Map集合返回的,一个是以 Account 对象返回的。
	// 将查询的结果封装到Map中
	QueryWrapper<Account> wrapper = new QueryWrapper<>();
	wrapper.gt("age", "2");
	mapper.selectMaps(wrapper).forEach(System.out::println);
}

3、分页查询

  • Page selectPage(Page page, Wrapper wrapper):根据条件进行分页查询;
  • Page selectMapsPage(Page page, Wrapper wrapper):根据条件进行分页查询,与 selectPage() 的区别是,一个是以 Map 集合返回的,一个是以实体对象返回的。
@Test
void select() {
	// 分页查询
	Page<User> page = new Page<>(1, 2);
	Page<User> result = mapper.selectPage(page, null);
	System.out.println(result.getSize());   // 每页取2条
	System.out.println(result.getTotal());   // 总记录数
	result.getRecords().forEach(System.out::println);

	// 分页查询,把结果集封装到 Map 集合中
	// 与 selectPage() 的区别是,一个是以 Map 集合返回的,一个是以实体对象返回的
	Page<Map<String, Object>> page = new Page<>(1, 2);
	mapper.selectMapsPage(page, null).getRecords().forEach(System.out::println);
}

注意: 分页查询时需要在 Mybatis Plus 配置类中配置一个分页拦截器(PaginationInterceptor):

@Configuration
public class MyBatisPlusConfig {

	@Bean
	public PaginationInterceptor paginationInterceptor() {
		return new PaginationInterceptor();
	}
	
}

4、查询所有的主键

  • List selectObjs(Wrapper wrapper):根据条件查询主键列表。
@Test
void select() {
	// 查询所有的主键
	mapper.selectObjs(null).forEach(System.out::println);
}	

5、仅查询一条记录

注意: 查询一条记录,结果集必须是一条记录,否则就会报错。

  • T selectOne(Wrapper wrapper):根据条件查询记录,必须保证结果集只有一条记录。
@Test
void select() {
	// 查询一条记录,结果集必须是一条记录,否则就会报错
	QueryWrapper<Account> wrapper = new QueryWrapper<>();
	wrapper.eq("name", "二号");
	mapper.selectOne(wrapper);
}

6、模糊查询

模糊查询 需要在 Wrapper 条件中设置模糊条件,此方法是 Wrapper 的方法。

  • like(String s1, String s2):设置模糊条件;
  • likeLeft(String s1, String s2):设置左模糊条件;
  • likeRight(String s1, String s2):设置右模糊条件。
@Test
void select() {
	// 模糊查询
	QueryWrapper<Account> wrapper = new QueryWrapper<>();
	wrapper.like("name", "小");       // %小%
	wrapper.likeLeft("name", "小");   // %小
	wrapper.likeRight("name", "小");  // 小%
	System.out.println(mapper.selectList(wrapper));
}

7、嵌套查询

嵌套查询 需要在 Wrapper 条件中设置嵌套条件,此方法是 Wrapper 的方法。

  • inSql(String name, String sql):设置嵌套条件。
@Test
void select() {
    // 嵌套查询
	QueryWrapper<Account> wrapper = new QueryWrapper<>();
	wrapper.inSql("id", "select id from user where id < 10");
	wrapper.inSql("age", "select age from user where age > 1");
    
	// 执行的 SQL 语句如下:
	// SELECT ... AND 
	// (id IN (select id from user where id < 10) 
	// AND age IN (select age from user where age > 1)) 
    
	System.out.println(mapper.selectList(wrapper));
}

8、排序查询

排序查询 需要在 Wrapper 条件中设置排序条件,此方法是 Wrapper 的方法。

  • orderByAsc(String name):设置升序排序的字段;
  • orderByDesc(String name):设置降序排序的字段。
@Test
void select() {
	// 排序查询(asc升序,desc降序)
	QueryWrapper<User> wrapper = new QueryWrapper<>();
	wrapper.orderByAsc("age");  // 根据 age 进行升序排序
	System.out.println(mapper.selectList(wrapper));
}


六、自定义 SQL

如果 MP 中提供的方法无法应付你的需求,你也可以 自定义 SQL 语句。这里以多表关联查询为例:

1、准备工作

多表关联查询需要准备两张表和 VO 实体类以及 Mapper。

1)数据表

create table `t_user` (
	`id` int(11) not null auto_increment,
	`name` varchar(255),
	`age` int(11),
	primary key (`id`)
);

create table `t_product` (
	`id` int(11) not null auto_increment,
	`description` varchar(255),
	`count` int(11),
	primary key (`id`)
);

-- 随意插入几条记录

2)VO 实体类

这里我用 VO 来封装实体类。

@Data
public class ProductVO {
    @TableId
    private Integer id;
    private String description;
    private Integer count;
    private Integer userId;
    private String userName;
}

2、Mapper

public interface UserMapper extends BaseMapper<User> {
	@Select("select p.id, p.description, p.count, u.id user_id, u.`name` user_name from t_user u, t_product p where u.id = p.user_id and u.id = #{id}")
	List<ProductVO> productList(Integer id);
}


博客中若有不恰当的地方,请您一定要告诉我。前路崎岖,望我们可以互相帮助,并肩前行!



  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小异常

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值