mybatis02.动态sql

动态sql

通过mybatis提供的各种标签方法实现动态拼接sql

if标签:

<if test="判断条件">

拼接内容

</if>

where标签

<!-- where标签  自动去掉where后的第一个and -->

<where>

<if test="sex!=null and sex!=''">

and sex=#{sex}

</if>

</where>

sql片段:

可将重复的sql提取出来,使用时用include引用即可,可以让sql重复利用

<sql id="select">sql语句</sql>

foreach标签:

<foreach collection="ids" item="id" separator="," open="(" close=")">

#{id}

</foreach>

collection:遍历的集合,这里是QueryVo的ids属性

item:遍历的项目,可以随便写,但是和后面的#{}里面要一致

open:在前面添加的sql片段

close:在结尾处添加的sql片段

separator:指定遍历的元素之间使用的分隔符

多表查询:

 

resultMap

mapper.xmlsql查询列(user_id)Order类属性(userId)不一致,所以查询结果不能映射到pojo中。

需要定义resultMap,把orderResultMapsql查询列(user_id)Order类属性(userId)对应起来

<resultMap  id=””  type=”自定义类”>//如果是单表不用映射,多表需要:

<id  column=”id”  property=”id”/>

<result  column=”字段名”  property=”属性名”/>//普通字段

......

一对一映射:

<association  property=”属性名”  javaType=”类名”>

<id  column=”id”  property=”对应类中的属性名”/>

<result  column=”字段名”  property=”属性名”/>//普通字段

......

</association>

一对多查询:

<collection  property=”属性名”  ofType=”泛型”>

<id  column=”id”  property=”对应类中的属性名”/>

<result  column=”字段名”  property=”属性名”/>//普通字段

......

</collection>

</resultMap>

<select  id=””  resultMap=”resultMapid一样”>

sql语句

</select>

原文地址:https://www.cnblogs.com/hhthtt/p/10891541.html