一、概述
MyBatis中查询进行select映射,对于SQL语句返回结果的处理通常有两种方式:一种是resultType,另一种是resultMap。
resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,但是resultType跟resultMap不能同时存在。在MyBatis进行查询映射时,其实查询出来的每一个属性都是放在一个对应的Map里面的,其中键是属性名,值则是其对应的值。
1.返回类型是resultType:MyBatis会将Map里面的键值对取出赋给resultType所指定的对象对应的属性。其实MyBatis的每一个查询映射的返回类型都是ResultMap,只是当提供的返回类型属性是resultType的时候,MyBatis会自动的把对应的值赋给resultType所指定对象的属性。
注意:使用resultType进行输出映射,只有查询出来的列名和pojo(实体bean)中的属性名一致,该列才可以映射成功。
如果查询出来的列名和pojo中的属性名全部不一致,没有创建pojo对象。
只要查询出来的列名和pojo中的属性有一个一致,就会创建pojo对象。
(1)需求:
实现城市基本信息的查询(cityCode、cityName、cityType、parentCode、remark)
(2)Mapper.xml
<mapper namespace="com.example.dao.SysCityDao">
<select id="selectAllCity" resultType="com.example.data.SysCity">
<![CDATA[
select city_code,city_name,city_type,parent_code,remark from sys_city
]]>
<where>
<if test="cityCode != null and cityCode != ''">
city_code = #{cityCode}
</if>
<if test="cityName != null and cityName != ''">
AND city_name = #{cityName}
</if>
<if test="cityType != null and cityType != ''">
AND city_type = #{cityType}
</if>
</where>
</select>
</mapper>
(3)Mapper.java
//城市信息的Dao接口
public interface SysCityDao extends BaseMapper<SysCity> {
//查看城市基本信息
public List<SysCity> selectAllCity();
}
运行输出日志:
resultType总结:
输出的pojo不管是单个对象还是一个列表(list中包括pojo),在mapper.xml中resultType指定的类型是一样的。
在mapper.java指定的方法返回值类型不一样:
(1)输出单个pojo对象,方法返回值是单个对象类型
(2)输出pojo对象list,方法返回值是List<实体类>
生成的动态代理对象中是根据mapper方法的返回值类型确定是调用selectOne(返回单个对象调用)还是selectList (返回集合对象调用 )。
2.返回类型是resultMap:因为Map不能很好表示领域模型,就需要再进一步的把它转化为对应的对象,常常应用在复杂查询中。
mybatis中使用resultMap完成高级输出结果映射。
注意:解决字段名(数据库中的列名)和属性名(java里pojo类中的属性)不一致而导致错误冲突。
(1)业务需求:
实现城市基本信息的查询(cityCode、cityName、cityType、parentCode、remark)
(2)Mapper.xml
<mapper namespace="com.example.dao.SysCityDao">
<!-- 定义ResultMap
id:唯一标识符,连接select查询标签内的resultmap。
type:所对应的实体pojo类型 -->
<resultMap id="cityResultMap" type="com.example.data.SysCity">
<!-- id标签:主键标签。
column:查询出的列名(给数据库中的列名定义的别名)
property:对应type所指定的java实体类POJO中的属性名-->
<id column="code" property="cityCode"/>
<!-- 对普通列的映射定义 -->
<result column="name" property="cityName"/>
<result column="type" property="cityType"/>
<result column="pcode" property="parentCode"/>
<result column="rmk" property="remark"/>
</resultMap>
<!-- 使用resultMap进行输出映射
resultMap:指定上面定义的resultMap的id(cityResultMap),如果这个resultMap在其它的mapper文件,前面需要加namespace-->
<select id="selectAllCity" resultMap="cityResultMap">
<![CDATA[
select city_code code,city_name name,city_type type,parent_code pcode,remark rmk from sys_city
]]>
<where>
<if test="code != null and code != ''">
city_code = #{code}
</if>
<if test="name != null and name != ''">
AND city_name = #{name}
</if>
<if test="type != null and type != ''">
AND city_type = #{type}
</if>
</where>
</select>
(3)Mapper.java
//城市信息的Dao接口
public interface SysCityDao extends BaseMapper<SysCity> {
//查看城市基本信息
public List<SysCity> selectAllCity() throws Exception;
}
运行输出日志:
总结:
查询出来的列名和java实体类pojo中的属性名一致用ResultType;
查询出来的列名和java实体类pojo中的属性名不一致,就需要定义一个resultMap对列名和java实体类pojo属性名之间作映射。