文章目录
- 一、返回一条信息
- 二、返回List集合
- 三、返回Map集合
- 四、返回多个Map集合
- 五、返回List集合
一、返回一条信息
Student selectById(Long id);
不再赘述
二、返回List集合
List< Student> selectAll();
不再赘述
三、返回Map集合
用map集合去接收返回来的结果
字段名叫做key,字段值叫做value
接口:
/*** 根据id获取student信息,将学生信息放在map集合中* @param id* @return*/Map<String,Object> selectByIdReturnMap(Long id);
mapper.xml
<select id="selectByIdReturnMap" resultType="map">select * from t_student where id=#{id}</select>
测试:
@Testpublic void testSelectByIdReturnMap() throws IOException, ParseException {SqlSession session = SqlSessionUtil.openSession();StudentMapper mapper = session.getMapper(StudentMapper.class);Map<String, Object> studentMap = mapper.selectByIdReturnMap(1L);System.out.println(studentMap);session.close();}
运行结果:
四、返回多个Map集合
List< Map > 等同于List< Student>
返回多个map,可以list集合套map
接口:
List<Map<String,Object>> selectAll();
mapper.xml:
注意:resultType不是student不是list 还是map!!!
<select id="selectAll" resultType="map">select * from t_student</select>
测试:
@Testpublic void testSelectAll() throws IOException, ParseException {SqlSession session = SqlSessionUtil.openSession();StudentMapper mapper = session.getMapper(StudentMapper.class);List<Map<String, Object>> maps = mapper.selectAll();maps.forEach(studentmap->{System.out.println(studentmap);});session.close();}
运行结果:
五、返回List集合
在第四种方式的基础上,如果想要获取id为3的学生就需要对List集合中的每一个元素进行遍历,再遍历map集合的id属性。查询起来较为麻烦。
搞一个更大的Map<String,Map >集合由key和value组成。
student的id值作为这个大map集合的key,第四种方式下的小map集合作为大map集合的value值
拿student的id做key,以后取出对应的map集合时较为方便
通过 @MapKey(“id”) 注解将查询结果的id值作为大map集合的key
接口:
/*** 查询所有的Student,返回一个大Map集合* Map集合的key是每条记录的主键值* Map集合的value是每条记录* 通过MapKey这个注解来指定map集合的key* @return*/@MapKey("id") //将查询结果的id值作为大map集合的keyMap<Long,Map<String,Object>> selectAllReturnBigMap();
mapper.xml:
注意:这里的resultType依然是Map
<select id="selectAllReturnBigMap" resultType="map">select * from t_student</select>
测试:
@Testpublic void testSelectAllReturnBigMap() throws IOException, ParseException {SqlSession session = SqlSessionUtil.openSession();StudentMapper mapper = session.getMapper(StudentMapper.class);Map<Long, Map<String, Object>> studentMapMap = mapper.selectAllReturnBigMap();System.out.println(studentMapMap);session.close();}
运行结果:
大Map集合
{
1={sex=男, name=阿白, birth=1999-10-04, id=1, age=23, height=1.58},
2={sex=女, name=阿川, birth=1999-09-30, id=2, age=23, height=1.75},
3={sex=女, name=小小川, birth=1998-09-29, id=3, age=24, height=1.78}
}