MyBatis查询数据时:
1、若查询出的数据只有一条,可以通过实体类对象 list集合 或 map集合 来接收
2、若查询处的数据有多条,一定不能通过实体类对象来接收,此时会抛出TooManyResultsException
目录
查询一条数据为map集合
如果没有实体类对象,就把它映射成map集合
从数据库中查询数据,将其映射为map集合
例如把它传到网页端,就映射成json对象,所以转成map很常用
SelectMapper接口:
public interface SelectMapper {
/**
* 根据id查询用户信息为一个map集合
*/
Map<String, Object> getUserByIdToMap(Integer id);
}
配置文件:
<!-- Map<String, Object> getUserByIdToMap(Integer id);-->
<select id="getUserByIdToMap" resultType="map">
select * from t_user where id = #{id}
</select>
查询多条数据为map集合
SelectMapper接口:
public interface SelectMapper {
/**
* 查询所有用户信息为map集合,每一条记录是一个map
*/
方式一:
// List<Map<String, Object>> getAllUserToMap();
方式二:
@MapKey("id")
Map<String, Object> getAllUserToMap();
}
配置文件:
<!-- Map<String, Object> getAllUserToMap();-->
<select id="getAllUserToMap" resultType="map">
select * from t_user
</select>
常用类型别名: