MyBaits-Plus
November 30, 2024About 3 min
MyBaits-Plus
Annotations
Annotations
MyBatis-Plus infers table information based on the PO (Persistent Object) entity details to generate SQL. By default:
- MyBatis-Plus converts the PO entity class name from camelCase to snake_case for the table name.
- MyBatis-Plus converts all variable names in the PO entity from camelCase to snake_case for the column names, and infers the column types from the variable types.
- MyBatis-Plus treats a field named
id
as the primary key. However, the default implementation often does not match actual scenarios, so MyBatis-Plus provides several annotations to facilitate the declaration of table information. Annotations: https://baomidou.com/reference/annotation/ Key annotations: @TableName, @TableId, @TableField
Configuration
mybatis-plus:
type-aliases-package: com.xxx.mp.domain.po
global-config:
db-config:
id-type: auto # id auto-increment
https://baomidou.com/reference/
Wrapper and LambdaWrapper
QueryWrapper和UpdateWrapper
@Test
void testQueryWrapper() {
// 1.构建查询条件 where name like "%o%" AND balance >= 1000
QueryWrapper<User> wrapper = new QueryWrapper<User>()
.select("id", "username", "info", "balance")
.like("username", "o")
.ge("balance", 1000);
// 2.查询数据
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
@Test
void testUpdateWrapper() {
List<Long> ids = List.of(1L, 2L, 4L);
// 1.生成SQL
UpdateWrapper<User> wrapper = new UpdateWrapper<User>()
.setSql("balance = balance - 200") // SET balance = balance - 200
.in("id", ids); // WHERE id in (1, 2, 4)
// 2.更新,注意第一个参数可以给null,也就是不填更新字段和数据,
// 而是基于UpdateWrapper中的setSQL来更新
userMapper.update(null, wrapper);
}
To avoid String Hard Code above, we can use LambdaWrapper
e.g.
@Test
void testLambdaQueryWrapper() {
// 1.构建条件 WHERE username LIKE "%o%" AND balance >= 1000
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.lambda()
.select(User::getId, User::getUsername, User::getInfo, User::getBalance)
.like(User::getUsername, "o")
.ge(User::getBalance, 1000);
// 2.查询
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
DIY SQL
We can use Wrapper to generate the condition expression (the condition after WHERE clause), and combine it with mapper.xml
@Test
void testCustomWrapper() {
// 1.准备自定义查询条件
List<Long> ids = List.of(1L, 2L, 4L);
QueryWrapper<User> wrapper = new QueryWrapper<User>().in("id", ids);
// 2.调用mapper的自定义方法,直接传递Wrapper
userMapper.deductBalanceByIds(200, wrapper);
}
public interface UserMapper extends BaseMapper<User> {
@Select("UPDATE user SET balance = balance - #{money} ${ew.customSqlSegment}")
void deductBalanceByIds(@Param("money") int money, @Param("ew") QueryWrapper<User> wrapper);
}
IService and ServiceImpl
save
: Add a single element.saveBatch
: Batch add elements.saveOrUpdate
: Determine by ID, if the data exists, update it; otherwise, add it.saveOrUpdateBatch
: Batch add or update.removeById
: Delete by ID.removeByIds
: Batch delete by IDs.removeByMap
: Delete by key-value pairs in the Map.remove(Wrapper<T>)
: Delete by Wrapper condition.updateById
: Update by ID.update(Wrapper<T>)
: Update by UpdateWrapper, where the Wrapper contains the set and where parts.update(T, Wrapper<T>)
: Update the data matched by Wrapper according to the data in T.updateBatchById
: Batch update by ID.getById
: Query one record by ID.getOne(Wrapper<T>)
: Query one record by Wrapper.getBaseMapper
: Get the BaseMapper implementation within the Service, useful when you need to call custom SQL in the Mapper.listByIds
: Batch query by IDs.list(Wrapper<T>)
: Query multiple records by Wrapper condition.list()
: Query all records.count()
: Count all records.count(Wrapper<T>)
: Count records that meet the Wrapper condition.
public interface IUserService extends IService<User> {
}
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
}
Lambda in IService
@GetMapping("/list")
@ApiOperation("根据id集合查询用户")
public List<UserVO> queryUsers(UserQuery query){
// 1.组织条件
String username = query.getName();
Integer status = query.getStatus();
Integer minBalance = query.getMinBalance();
Integer maxBalance = query.getMaxBalance();
// 2.查询用户
List<User> users = userService.lambdaQuery()
.like(username != null, User::getUsername, username)
.eq(status != null, User::getStatus, status)
.ge(minBalance != null, User::getBalance, minBalance)
.le(maxBalance != null, User::getBalance, maxBalance)
.list();
// 3.处理vo
return BeanUtil.copyToList(users, UserVO.class);
}
- .one(): At most one result.
- .list(): Return a list of results.
- .count(): Return the count of results.
PageHelper
@Configuration
public class MybatisConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
// 初始化核心插件
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 添加分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
@Test
void testPageQuery() {
// 1.分页查询,new Page()的两个参数分别是:页码、每页大小
Page<User> p = userService.page(new Page<>(2, 2));
// 2.总条数
System.out.println("total = " + p.getTotal()); //4
// 3.总页数
System.out.println("pages = " + p.getPages()); //2
// 4.数据
List<User> records = p.getRecords();
records.forEach(System.out::println);
int pageNo = 1, pageSize = 5;
// 分页参数
Page<User> page = Page.of(pageNo, pageSize);
// 排序参数, 通过OrderItem来指定
page.addOrder(new OrderItem("balance", false));
userService.page(page);
}