0%

MyBatis的各种查询功能

  • 查询一个实体类对象
  • 查询一个list集合
  • 查询单个数据
  • 查询一条数据为map的集合
1
2
3
4
5
6
7
@Test
public void testMybatis() throws IOException {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper parameterMapper = sqlSession.getMapper(ParameterMapper.class);
Map<String, Object> result = parameterMapper. getUserByIdToMap(2);
System.out.println(result);
}
1
2
3
4
<!--Map<String, Object> getUserByIdToMap(@Param("id") int id)-->
<select id="getUserByIdToMap" resultType="java.util.Map">
select * from t_user where id = #{id}
</select>
  • 查询多条数据为map的集合
1
2
3
4
5
6
7
@Test
public void testMybatis() throws IOException {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper parameterMapper = sqlSession.getMapper(ParameterMapper.class);
List<Map<String, Object>> result = parameterMapper. getUserByIdToMap();
result.forEach(mp -> System.out.println(mp));
}
1
2
3
4
<!--List<Map<String, Object>> getUserByIdToMap()-->
<select id="getUserByIdToMap" resultType="Map">
select * from t_user
</select>
使用@MapKey注解,定义唯一键,将每条数据转换的map集合作为值
1
2
3
4
5
6
7
@Test
public void testMybatis() throws IOException {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper parameterMapper = sqlSession.getMapper(ParameterMapper.class);
Map<Integer, Object> result = parameterMapper. getUserByIdToMap();
result.forEach((id, obj) -> System.out.println(obj));
}
1
2
@MapKey("id")
Map<Integer, Object> getUserByIdToMap();
1
2
3
4
<!--Map<Integer, Object> getUserByIdToMap()-->
<select id="getUserByIdToMap" resultType="Map">
select * from t_user
</select>
------ THEEND ------

欢迎关注我的其它发布渠道