为了支持复杂的映射,select元素提供了resultMap属性,在说明resultMap时,首先有必要区分一下另外一个属性:resultType
元素 | 说明 |
---|---|
resultType | 定义类的全路径,结果集可以通过java bean的规范映 射;或者定义:int 、double、map等, 注意不能和resultmap同时使用! |
resultMap | 映射集的引用,可以提供自定义映射规则 |
一个简单的select语句:
<select id="getAge" parameterType="int" resultType="int">
select age from user where id=#{id}
</select>
resultType表示该语句的返回的结果类型。也可以是类的全限定名,如:com.lyy.bean.User
如果数据库中对应的的用户表(user),而且其中有个user_name,要与User类中的属性 userName 保持一致,
可以再sql语句中写成
select user_name as userName from user
这样就和User类保持一致了。resultType的一些知识简单介绍了一下,接下来就开始分析resultMap。
<mapper namespace="com.lyy.dao.PoetriesMapper">
<resultMap id="poetriesMapper" type="com.lyy.bean.Poetries">
<id property="id" column="id"/>
<result property="poetId" column="poet_id"/>
<result property="content" column="content"/>
<result property="title" column="title"/>
</resultMap>
<select id="getContent" resultMap="poetriesMapper" parameterType="com.lyy.bean.Poetries">
select pr.id,pr.poet_id,pr.content,pr.title,p.id , p.name from poetries pr
LEFT JOIN poets p on pr.poet_id=p.id
<where>
<if test="poetId!=-1"><!-- 先前默认诗人id为-1,在此处通过对poetId值判断,便于连接 -->
and poet_id=#{poetId}
</if>
<if test="content!=null and !"".equals(content.trim())">
and content like concat('%',#{content},'%')
</if>
</where>
limit 0,20
</select>
</mapper>
其中,resultMap元素中的type代表使用的映射类为,可以使用别名或全限定名(别名需要在主配置文件中设置别名)
<id property="id" column="id"/>
id元素代表sql中的主键,result元素代表属性,property为类对应属性,column为表对应字段,这样就可以完成简单的映射了。