MyBatis 的各种查询功能
1.查询一个实体类对象
/**
* 查询单个实体类对象
* @param id
*/
User getUserById(@Param("id") Integer id);
<!--User getUserById(@Param("id") Integer id);-->
<select id="getUserById" resultType="user">
select * from user where id=#{id}
</select>
@Test
public void testGetUserById() {
User user = mapper.getUserById(4);
}
2.查询一个list集合
/**
* 查询多个或单个实体类对象
*/
List<User> getAllUser();
<!--List<User> getAllUser();-->
<select id="getAllUser" resultType="user">
select * from user
</select>
@Test
public void testGetAllUser() {
List<User> users = mapper.getAllUser();
for (User user : users) {
System.out.println(user);
}
}
3.查询数量
MyBatis中为Java常用的类型设置了类型别名
- Integer:integer,int
- int: _int, _integer
- Map:map
- String:string
/**
*查询数据总数
*/
Integer getCount();
<!--Integer getCount();-->
<select id="getCount" resultType="int">
SELECT COUNT(*) FROM user
</select>
@Test
public void testGetUserByIdToMap() {
mapper.getCount();
}
4.查询一条数据为Map集合
/**
* 根据id查询用户信息为map的集合
* @param id
* @return
*/
Map<String, Object> getUserByIdToMap(@Param("id") Integer id);
<!--Map<String, Object> getUserByIdToMap(@Param("id") Integer id);-->
<select id="getUserByIdToMap" resultType="map">
select * from user where id=#{id}
</select>
@Test
public void testGetUserByIdToMap() {
Map<String, Object> map = mapper.getUserByIdToMap(9);
System.out.println(map);
}
查询结果
(不使用map的话,查询结果为)
5.查询多条数据为Map集合
5.1 将map数据放入list集合中的方式
将表中的数据以map集合的方式查询,一条数据对应一个map;如果有多条数据,就会产生多个map集合,此时可以将这些map放在一个list集合中获取
/**
* 查询所有用户信息为map集合,采用将map数据放入list集合中的方式
*/
List<Map<String, Object>> getAllUserToMap();
<!--List<Map<String, Object>> getAllUserToMap();-->
<select id="getAllUserToMap" resultType="map">
select * from user
</select>
@Test
public void testGetAllUserToMap() {
List<Map<String, Object>> list = mapper.getAllUserToMap();
System.out.println(list);
}
查询结果
5.2 采用@MapKey()
注解方式
如果有多条数据,可以将每条数据转换的map集合放在一个大的map集合中,但是必须要通过@MapKey注解来完成。将查询的某个字段的值作为大的Map集合的键(key),由于key是唯一的,所以@MapKey(key)中的key必须是数据库中没有重复值的字段,否者查询到的重复数据会被覆盖直到,最终有重复key字段的只会显示一条。
把每一条查询到的数据整体当成一个value,放到新的key中
/**
* 查询所有用户信息为map集合,采用@MapKey()注解方式
*/
@MapKey("id")
Map<String, Object> getAllUserToMap2();
<!--Map<String, Object> getAllUserToMap2();-->
<select id="getAllUserToMap2" resultType="map">
select * from user
</select>
@Test
public void testGetAllUserToMap2() {
Map<String, Object> map2 = mapper.getAllUserToMap2();
System.out.println(map2);
}
查询结果
以id作为key,查询到的数据作为value
以age作为key,查询到的age重复的数据只会显示最后一条
因此,尽量使用不会重复的值作为key进行查询