查询一个实体类对象
- 查询出来的数据只有一条,
可以用User和User集合来接收
User getUserById(@Param("id") Integer id);
查询一个list集合
- 只能用list集合来接收
List<User> getAllUser();
单行单列的数据
单条数据 Map集合
查询的结果没有一个实体类与他相对应
- mapper接口
Map<String,Object> getUserByIdToMap(@Param("id") Integer id);
- xml
<select id="getUserByIdToMap" resultType="java.util.Map">
select * from t_user where id = #{id}
</select>
- 测试类
@Test
public void testGetUserByIdToMap(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
Map<String, Object> user = mapper.getUserByIdToMap(1);
System.out.println(user);
}
- 结果
{password=123456, sex=男, id=1, age=23, email=12345@qq.com, username=孙少聪}
多条数据 使用List
- mapper接口
/**
* 多条 map集合
*/
List<Map<String,Object>> getAllUserToMap();
- xml
<select id="getAllUserToMap" resultType="java.util.Map">
select * from t_user
</select>
- 测试类
@Test
public void testAllUserToMap(){
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
SelectMapper mapper = sqlSession.getMapper(SelectMapper.class);
List<Map<String, Object>> users = mapper.getAllUserToMap();
users.forEach(user -> System.out.println(user));
}
- 结果
{password=123456, sex=男, id=1, age=23, email=12345@qq.com, username=孙少聪}
{password=123456, sex=女, id=3, age=24, email=123456@qq.com, username=杨赛格}
@MapKey
@MapKey("id")
Map<String,Object> getAllUserToMap();
- 结果
{1={password=123456, sex=男, id=1, age=23, email=12345@qq.com, username=孙少聪}, 3={password=123456, sex=女, id=3, age=24, email=123456@qq.com, username=杨赛格}}