一、输入parametertype输出resulttype类型
(resulttype:列名和pojo中的属性名要一致)
mybatis使用ognl表达式解析对象字段的值,#{}或者${}括号中的值为pojo属性名称,
其中,#{}:占位符号,相对于?,${}:sql拼接符号,相对于string
select * from user where name = #{name}; 会被动态解析为 select * from user where name = ?;
select * from user where name = ${name}; 当我们传递参数"mark"时,会被解析 select * from user where name = "mark"; <!-- 1、resulttype:如果要返回数据集合,只需设定为每一个元素的数据类型
2、 包装的pojo取值通过 "."来获取
-->
<select id="getuserbyqueryvo" parametertype="queryvo" resulttype="com.mark.pojo.user">
<!-- select * from user where username like #{name} -->
select * from user where username like '%${user.username}%'
</select>二、输出resultmap(列名和pojo中的属性名不一致)
resultmap包含元素
<!--column不做限制,可以为任意表的字段,而property须为type 定义的pojo属性-->
<resultmap id="唯一的标识" type="映射的pojo对象">
<id column="表的主键字段,或者可以为查询语句中的别名字段" jdbctype="字段类型" property="映射pojo对象的主键属性" />
<result column="表的一个字段(可以为任意表的一个字段)" jdbctype="字段类型" property="映射到pojo对象的一个属性(须为type定义的pojo对象中的一个属性)"/>
<!-- 一对一关联-->
<association property="pojo的一个对象属性" javatype="pojo关联的pojo对象">
<id column="关联pojo对象对应表的主键字段" jdbctype="字段类型" property="关联pojo对象的主席属性"/>
<result column="任意表的字段" jdbctype="字段类型" property="关联pojo对象的属性"/>
</association>
<!-- 一对多关联-->
<!-- 集合中的property须为oftype定义的pojo对象的属性-->
<collection property="pojo的集合属性" oftype="集合中的pojo对象">
<id column="集合中pojo对象对应的表的主键字段" jdbctype="字段类型" property="集合中pojo对象的主键属性" />
<result column="可以为任意表的字段" jdbctype="字段类型" property="集合中的pojo对象的属性" />
</collection>
</resultmap>如果collection标签是使用嵌套查询,<collection>标签中的column:要传递给select查询语句的参数,如果传递多个参数,格式为column= {参数名1=表字段1,参数名2=表字段2} ;
格式如下:
<collection column="传递给嵌套查询语句的字段参数" property="pojo对象中集合属性" oftype="集合属性中的pojo对象" select="嵌套的查询语句" > </collection>
usermapper实例
<mapper namespace="com.mark.mapper.usermapper">
<!--
定义resultmap
type:resultmap最终映射的java对象类型,可以使用别名
id:对resultmap的唯一标识
-->
<resultmap type="user" id="userresultmap">
<!--
column:查询出来的列名
property:type指定的pojo类型中的属性名
最终resultmap对column和property作一个映射关系(对应关系)
-->
<!-- 主键用id -->
<id column="id" property="id"/>
<!-- 普通字段用result -->
<!-- 单表查询可以不写全,关联查询必须写全所有字段 -->
<result column="user_name" property="username"/>
</resultmap>
<!-- 这里的resultmap要和<resultmap type="user" id="userresultmap">id一致 -->
<select id="finduserbyresultmap" parametertype="com.mark.po.userqueryvo" resultmap="userresultmap">
select id, user_name from user where user.username=#{usercustom.username}
</select>
</mapper>总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论