MyBatis-Plus Common Usage
Query
QueryWrapper
QueryWrapper
// usage 1 |
LambdaQueryWrapper
// usage 1 |
Convert QueryWrapper
to LambdaQueryWrapper
LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new QueryWrapper<SysUser>() |
Basic Query
An example
List<SysUser> sysUserList = userService.list( |
from
new QueryWrapper<Entity>() |
select
wrapper.select("column 1", "column 2") |
where
wrapper.eq("type", 1) |
and…or
// where type = 1 or type = 2 |
// find_in_set(?, category_id) or find_in_set(?, category_id) |
// where status = 0 and (type = 1 or (type > 10 and type < 20)) |
order by
wrapper.orderByDesc("id") |
limit
wrapper.last("limit 10") |
Query Conditions
find_in_set
wrapper.apply("find_in_set({0}, type)", type); |
Date functions
date equal
wrapper.apply("date(gmt_create)=date({0})", new Date()) |
Recent 7 days
wrapper.apply("create_time > DATE_SUB(NOW(), INTERVAL 7 DAY)")); |
Page Query
- Request query string parameters
http://xxx.xxx/?current=1&size=10&orders[0].column=pubtime&orders[0].asc=true
- current
- size
- orders[].column
- orders[].asc
- Page Entity
com.baomidou.mybatisplus.extension.plugins.pagination.Page
Fields for Request parameters
long size
long current
List<OrderItem> orders
String column
boolean asc
Fields for response
List<T> records
long total
- Page Query Methods
MyBatis Plus page query method
IPage<T> selectPage(IPage<T> page, Wrapper<T> queryWrapper) |
Custom page query in Mapper XML
IPage<MyResult> myPageQuery(; Page page, MyParam param) |
- Pass
com.baomidou.mybatisplus.extension.plugins.pagination.Page
object as a parameter. - Using the
IPage
class as the return type. - Don’t need to add
limit start, size
in mapper XML. The SQL is query all rows. But MyBatis Plus automatically add limit at the end of SQL. If you want to query all, update toList<MyResult> queryAll(@Param("param") MyParam param);
One Column Query
List<Object> names = baseMapper.selectObjs( |
Aggregation Query
Aggregation Query methods
- selectMaps()
List<Map<String, Object>> mapList = userMapper.selectMaps( |
- selectObjs()
List<Object> mapList = userMapper.selectObjs( |
- selectCount()
userMapper.selectCount(queryWrapper); |
select
queryWrapper.select("count(*) as typeCount"); |
group by
queryWrapper.groupBy("type")); |
having
queryWrapper.having("COUNT(*) > 10")) |
Others
Non-query fields
Use @TableField(exist = false)
|
Use @TableName(excludeProperty={})
|
Using @TableField(condition = SqlCondition.LIKE)
|
Using @TableField(whereStrategy = FieldStrategy.NOT_EMPTY)
IGNORED
: 不判断NOT_NULL
: 非NULL判断NOT_EMPTY
: 非空判断
Using MySQL keyword as a column name
|
Using another entity name
|
DML
update it to null when it value is null
|
logical delete
// Note that the field for logical deletion cannot be modified by update() method |
Update
userService.update(new UpdateWrapper<User>() |
MyBatis Plus Configurations
mybatis-plus: |
More configurations reference MyBatis Plus使用配置