MyBatis-Plus是一个MyBatis的增强工具类库,提供了许多实用的查询工具类。下面是一个示例的MyBatis-Plus查询工具类:
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.StringUtils;
import java.util.Map;
public class MybatisPlusQueryUtils {
public static <T> QueryWrapper<T> buildQueryWrapper(Map<String, Object> params) {
QueryWrapper<T> queryWrapper = new QueryWrapper<>();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, Object> entry : params.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
if (value != null && StringUtils.hasText(value.toString())) {
queryWrapper.eq(key, value);
}
}
}
return queryWrapper;
}
public static <T> IPage<T> buildPage(Map<String, Object> params) {
int current = 1;
int size = 10;
if (params != null && !params.isEmpty()) {
Object currentObj = params.get("current");
Object sizeObj = params.get("size");
if (currentObj instanceof String && StringUtils.hasText((String) currentObj)) {
current = Integer.parseInt((String) currentObj);
}
if (sizeObj instanceof String && StringUtils.hasText((String) sizeObj)) {
size = Integer.parseInt((String) sizeObj);
}
}
return new Page<>(current, size);
}
}
这个工具类中的buildQueryWrapper方法用于根据传入的参数构建QueryWrapper对象,buildPage方法用于构建Page对象,可以用于分页查询。
使用示例:
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public IPage<User> queryUsers(Map<String, Object> params) {
IPage<User> page = MybatisPlusQueryUtils.buildPage(params);
QueryWrapper<User> queryWrapper = MybatisPlusQueryUtils.buildQueryWrapper(params);
return userMapper.selectPage(page, queryWrapper);
}
}
在上面的示例中,queryUsers方法使用了MybatisPlusQueryUtils工具类来构建查询条件和分页参数,然后调用userMapper.selectPage方法进行分页查询。