注意:本教程使用的数据库脚本、数据模型和环境信息请参考 “MyBatis Plus环境准备” 章节,点击下载示例源码。
在 IService 接口中提供了很多 list 开头的方法,这些方法将根据查询条件获取多条数据。这些方法的定义如下:
// 查询所有 List<T> list(); // 查询列表 List<T> list(Wrapper<T> queryWrapper); // 查询(根据ID 批量查询) Collection<T> listByIds(Collection<? extends Serializable> idList); // 查询(根据 columnMap 条件) Collection<T> listByMap(Map<String, Object> columnMap); // 查询所有列表 List<Map<String, Object>> listMaps(); // 查询列表 List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper); // 查询全部记录 List<Object> listObjs(); // 查询全部记录 <V> List<V> listObjs(Function<? super Object, V> mapper); // 根据 Wrapper 条件,查询全部记录 List<Object> listObjs(Wrapper<T> queryWrapper); // 根据 Wrapper 条件,查询全部记录 <V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);
参数说明:
queryWrapper:实体对象封装操作类 QueryWrapper
idList:主键ID列表
columnMap:表字段 map 对象
mapper:转换函数
(1)使用不带任何参数的 list() 方法查询数据表所有记录,代码如下:
package com.hxstrive.mybatis_plus.simple_service.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<UserBean> userBeanList = userService.list();
System.out.println("size=" + userBeanList.size());
}
}(2)下面示例将查询用户ID大于 10,小于 20 且性别为“男”的用户列表,代码如下:
package com.hxstrive.mybatis_plus.simple_service.list;
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<UserBean> wrapper = new QueryWrapper<>();
wrapper.gt("user_id", 10);
wrapper.lt("user_id", 20);
wrapper.eq("sex", "男");
List<UserBean> userBeanList = userService.list(wrapper);
for(UserBean userBean : userBeanList) {
System.out.println(userBean);
}
}
}