Mybatis框架基础入门(五)--输入映射和输出映射

1.parameterType(输入类型)

1.1 传递简单类型

使用#{}占位符,或者${}进行sql拼接。

<select id="caseCountByQueryCaseVo" parameterType="String" resultType="Integer">
select count(1) total from  testcase where systemName like "%"#{systemName}"%" 
</select>


#{systemName}中的systemName可以随意取名,不过建议保持与前面字段名              一致。

 systemName like '%${value}%'   //如果传入的是基本类型,那么${}中的变量名必须是value,如果传入的参数是pojo类型,那么         ${}中的变量名称必须是pojo中的属性名
 注意:使用拼接符有可能造成sql注入

 

1.2 传递pojo对象

#{}或者${}括号中的值为pojo的属性名称

<select id="caseCountByQueryCaseVo" parameterType="QueryCaseVo" resultType="Integer">
  select count(1) total from testcase where systemName like "%"#{systemName}"%"
​​​​​​​</select>

1.3  传递pojo包装对象

<select id="findTestCaseByPojoVo" parameterType="TestCaseVo" resultType="Integer">

   select count(1) total from testcase where systemName like "%"#{testcase.systemName}"%"

</select>

2 resultType(输出类型)

2.1 输出简单类型

<select id="findTestCaseByPojoVo" parameterType="TestCaseVo" resultType="Integer">

   select count(1) total from testcase where systemName like "%"#{testcase.systemName}"%"

</select>

2.2 输出pojo对象

<select id="findTestCaseById" parameterType="Integer" resultType="TestCase">

   select *  from testcase where caseId = #{caseId}

</select>

2.3 输出pojo列表

<select id="selectCaseListByCaseQueryVo" parameterType="QueryCaseVo"
		resultType="Testcase">
		select * from testcase
		<where>
			<if test="systemName != null and systemName != ''">
				systemName like "%"#{systemName}"%"
			</if>
			<if test="caseId != null and caseId != ''">
				and	caseId like "%"#{caseId}"%"
			</if>
			<if test="caseName != null and caseName != ''">
				and caseName like "%"#{caseName}"%"
			</if>
			<if test="isPass != null and isPass != ''">
				and isPass = #{isPass}
			</if>
		</where>
		limit #{startRow},#{size}
	</select>

3.resultMap类型

        resultType可以指定将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功。

        如果sql查询字段名和pojo的属性名不一致,可以通过resultMap将字段名和属性名作一个对应关系 ,resultMap实质上还需要将查询结果映射到pojo对象中。

        resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list,实现一对一查询和一对多查询。

<!-- resultMap最终还是要将结果映射到pojo上,type就是指定映射到哪一个pojo -->
	<!-- id:设置ResultMap的id -->
	<resultMap type="order" id="orderResultMap">
		<!-- 定义主键 ,非常重要。如果是多个字段,则定义多个id -->
		<!-- property:主键在pojo中的属性名 -->
		<!-- column:主键在数据库中的列名 -->
		<id property="id" column="id" />

		<!-- 定义普通属性 -->
		<result property="userId" column="user_id" />
		<result property="number" column="number" />
		<result property="createtime" column="createtime" />
		<result property="note" column="note" />
	</resultMap>

	<!-- 查询所有的订单数据 -->
	<select id="queryOrderAll" resultMap="orderResultMap">
		SELECT id, user_id,
		number,
		createtime, note FROM `order`
	</select>

 

原文地址:https://www.cnblogs.com/Aaron-007/p/12814605.html