MyBatis-Plus用法

本文深入解析MyBatis-Plus在service层的高级应用技巧,包括复杂查询如多条件筛选、字段为空的查询,以及通过UpdateWrapper进行字段修改的操作细节。同时,详述了各种注解的使用场景,如@TableField、@NotNull、@NotEmpty、@NotBlank、@TableLogic和@EnumValue,帮助开发者更高效地进行数据库操作。

MyBatis-Plus用法

service层

1、查询多个
wrapper.in(BizWorker::getId, workerIds);
in和=相似,只是一个可以查询多个结果,一个只能查询一个
2、查询某一个字段为空
wrapper.isNull(Shop::getParentId);//查询这个字段为空
3、将某个字段修改为空
for(Shop shops : shopList){
UpdateWrapper up = new UpdateWrapper<>();
up.set(“parent_id”,null);
up.eq(“id”,shops.getId());
this.update(shops,up);
}

注解

1、@TableField(exist = false) 注解加载bean属性上,表示当前属性不是数据库的字段,但在项目中必须使用,
这样在新增等使用bean的时候,mybatis-plus就会忽略这个,不会报错
2、@NotNull:不能为null,但可以为empty
3、@NotEmpty:不能为null,而且长度必须大于0
4、@NotBlank:只能作用在String上,不能为null,而且调用trim()后,长度必须大于0
5、@TableLogic逻辑删除,在实体类中加
6、@EnumValue枚举类注解(注解在枚举字段上)

Mybatis-plusMybatis 的增强工具,在 Mybatis 的基础上,提供了更加便捷的 CRUD 操作、分页、代码生成等功能。使用 Mybatis-plus 可以大大提高开发效率,以下是 Mybatis-plus用法: 1. 引入 Mybatis-plus 依赖 在 Maven 项目中,可以在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3.1</version> </dependency> ``` 2. 配置 Mybatis-plus 在 Spring Boot 项目中,可以在 application.yml 或 application.properties 文件中添加以下配置: ```yaml mybatis-plus: mapper-locations: classpath*:mapper/**/*.xml # mapper 文件的位置 type-aliases-package: com.example.entity # 实体类的包名 ``` 3. 编写实体类 ```java @Data public class User { private Long id; private String name; private Integer age; private String email; } ``` 4. 编写 Mapper 接口 ```java public interface UserMapper extends BaseMapper<User> { } ``` 5. 使用 Mybatis-plus 进行 CRUD 操作 ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User getById(Long id) { return userMapper.selectById(id); } @Override public List<User> list() { return userMapper.selectList(null); } @Override public int save(User user) { return userMapper.insert(user); } @Override public int update(User user) { return userMapper.updateById(user); } @Override public int deleteById(Long id) { return userMapper.deleteById(id); } } ``` 以上就是 Mybatis-plus 的基本用法,更多高级用法可以参考官方文档。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值