Mybatis中resultMap和 特殊字符转意 的浅析

Mybatis之ResultMap映射

适用场景:

当查询出来的字段名和对象中的属性名不一致的情况,就没办法使用resultType来默认映射(同名规则)

使用resultMap来映射数据库中的字段到底注入到对象中什么属性中.

具体操作:

<!-- 关联关系 
		所有的column:都是数据库相关的列
		所有的property:都是类里面的属性
	-->
	<resultMap type="com.xinghe.carCon.system.pojo.ASms" id="resultMap">
		<!-- 关联字段需要额外赋值
			select:查询关联关系的sql语句
		 -->
		 <id column="d_id" property="id"/>
		<result column="smsTemplateId" property="smsTemplateId"/>
		
		<association property="smsTemplate" column="smsTemplateId" javaType="com.xinghe.carCon.system.pojo.ASmsTemplate" 
			select="com.xinghe.carCon.system.dao.IASmsTemplateDao.selectById"/>
	</resultMap>

Mybatis 之<![CDATA[ ]]>浅析

在使用mybatis 时我们sql是写在xml 映射文件中,如果写的sql中有一些特殊的字符的话,在解析xml文件的时候会被
转义,但我们不希望他被转义,所以我们要使用<![CDATA[ ]]>来解决。

<![CDATA[ ]]> 是什么,这是XML语法。在CDATA内部的所有内容都会被解析器忽略。

如果文本包含了很多的"<“字符 <=和”&"字符——就象程序代码一样,那么最好把他们都放到CDATA部件中。
但是有个问题那就是 <if test=""> </if> <where> </where> <choose> </choose> <trim> </trim>等这些标签都不会被解
析,所以我们只把有特殊字符的语句放在 <![CDATA[ ]]> 尽量缩小 <![CDATA[ ]]> 的范围。

具体操作:

<select id="findList" resultMap="resultMap">
		select * from a_sms
		<!-- 查询条件 -->
		<where>
			<!-- 关键字搜索;
				其中keyword为parameterType中类型map的键;
				mybatis底层会将map的值赋值给键对应的点位符
			 -->
			<if test="keyword != null and keyword != ''">
				and ( name like #{keyword} or content like #{keyword} )
			</if>
			
			<!-- 按照状态查询 -->
			<if test="status != null and status != ''">
				and status = #{status}
			</if>
			
			<!-- 按照时间范围查询 -->
			<if test="stDate != null and edDate != null">
				<!-- 如果XML中有特殊字符需要转义 -->
				<![CDATA[
					and pubTime > #{stDate} and pubTime < #{edDate}
				]]>
			</if>
		</where>
		<!-- 排序 -->
		<choose>
			<when test="orderBy = 'idDesc'">
				order by id desc 
			</when>			
			<otherwise>
				<!-- 按照发布时间倒序 -->
				order by pubTime desc 
			</otherwise>
		</choose>
	</select>

因为这里有 “>” “<” 特殊字符所以要使用 <![CDATA[ ]]> 来注释,但是有<if>标签,所以把<if>等标签放在<![CDATA[ ]]>外面

发布了15 篇原创文章 · 获赞 8 · 访问量 9450

猜你喜欢

转载自blog.csdn.net/qq_42684504/article/details/89447579