Mybatis的xml实用的一些技巧

1.结果映射技巧

    <resultMap id="myMap" type="com.shixin.vo.MyVO">
        <id column="id" property="id" />
        <result column="name" property="name" />
        <result column="type" property="type" />
        <collection property="subList" ofType="com.shixin.vo.SubVO">
            <id column="subId" property="subId" />
            <result column="subName" property="subName" />
            <result column="subType" property="subType" />
        </collection>
    </resultMap>

对应的java类

@Data
public class MyVO {
    private Integer id;
    private String name;
    private String type;
    //三级分类vo List
    private List<SubVO> subList;
}

对应的数据库结果集

这样的结果映射出来就只会有两个MyVO对象,一个是id=11一个是id=12

2.对于一个判断查询善用when

  ( ' )  这个符号有可能会报错,全部换成  (")即可

        ......
        order by
        <choose>
            <when test="params.sort == 'c1' ">
                column1 desc
            </when>
            <when test="params.sort == 'c2' ">
                column2 asc
            </when>
            <otherwise>
                column3 asc
            </otherwise>
        </choose>

3.foreach循环

 ......
 in
 <foreach collection="myList" item="item" index="index" open="("  separator=","  close=")">
            #{item}        
 </foreach>

用于 in (1,2,3)  or  in  ('1','2','3')的场景

collection代表外部传入的参数,实用@Param("myList")即可映射

item代表myList集合中的每一个元素(可以是自定义对象,也可以是基本类型)

如果item是对象那么可以使用 #{item.xx}的形式进行拼接

open代表起始符号,separator代表分隔符,close代表结束符号

最终会成为如下的语句

...... in  ( myList.get(0) , myList.get(1) , myList.get(2) ...... )

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值