本篇文章小编给大家分享一下MyBatisPlus利用Service实现获取数据列表代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
接口说明
接口提供了如下十个 list 方法:
// 查询所有 List list(); // 查询列表 List list(Wrapper queryWrapper); // 查询(根据ID 批量查询) Collection listByIds(Collection<? extends Serializable> idList); // 查询(根据 columnMap 条件) Collection listByMap(Map columnMap); // 查询所有列表 List> listMaps(); // 查询列表 List> listMaps(Wrapper queryWrapper); // 查询全部记录 List listObjs(); // 查询全部记录 List listObjs(Function<? super Object, V> mapper); // 根据 Wrapper 条件,查询全部记录 List listObjs(Wrapper queryWrapper); // 根据 Wrapper 条件,查询全部记录 List listObjs(Wrapper queryWrapper, Function<? super Object, V> mapper);
参数说明
queryWrapper:实体对象封装操作类 QueryWrapper
idList:主键ID列表
columnMap:表字段 map 对象
mapper:转换函数
实例代码
1 不带任何参数的 list() 方法查询数据
import com.hxstrive.mybatis_plus.model.UserBean;
import com.hxstrive.mybatis_plus.service.UserService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
class List1Test {
@Autowired
private UserService userService;
@Test
void contextLoads() {
List userBeanList = userService.list();
System.out.println("size=" + userBeanList.size());
}
}
2 查询用户ID大于 10,小于 20 且性别为“男”的用户列表
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hxstrive.mybatis_plus.model.UserBean;
import com.hxstrive.mybatis_plus.service.UserService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
class List2Test {
@Autowired
private UserService userService;
@Test
void contextLoads() {
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.gt("user_id", 10);
wrapper.lt("user_id", 20);
wrapper.eq("sex", "男");
List userBeanList = userService.list(wrapper);
for(UserBean userBean : userBeanList) {
System.out.println(userBean);
}
}
}
3 注意事项说明
请注意,这里我们所描述的一切方法都是基于 Service 层来说的
请注意,这里我们所描述的一切方法都是不是基于 Mapper 层来说的
SqlAugur 如何用 AST 校验保障 SQL Server MCP 查询安全?
GPT-5.3-Codex 使用 xhigh 时为何会产生大量 Token?
ubuntu终端背景图片怎么设置? ubuntu16.04终端窗口设置背景的教程
GPT-5.3-Codex、GPT-5.2 与 Claude Opus 4.6 在真实重构任务中表现如何?
AI 明明提升了效率,为何人却更疲惫?解析 5 个机制与 9 项自检
GPT-5-Codex、Claude Sonnet 4.5 与 Kimi K2 在真实重构任务中谁更强?