Mybatis

此章节为mybatis的学习笔记

Mybatis连接的四要素和日志及驼峰命名的映射开关

XML映射文件

1.映射配置文件名与Mapper接口一致,且放在相同的包下(同包同名)。

2.映射配置文件的namespace属性与Mapper接口的全类名一致。

3.XML映射文件中SQL语句的id与Mapper接口的方法名一致。

Mybatis动态SQL配置xml文件

1.<if>

<if test = '条件表达式'>

        要拼接的sql语句

</if>

用于判断条件是否成立。

使用test属性来进行条件判断,如果条件为true,则拼接SQL语句。

2.<where>

<where> (元素)

        内容(子元素)

</where>

where元素只会在子元素有内容的情况下才会插入where字句。

会自动去除子句的and或者or。

    <select id="list" resultType="com.itheima.pojo.Emp">
        select *
        from emp
        <where>
        <if test="name != null">
            name like concat('%', #{name}, '%')
        </if>
        <if test="gender != null">
            and gender = #{gender}
        </if>
        <if test="begin != null and end != null">
            and entrydate between #{begin} and #{end}
        </if>
        </where>
        order by update_time desc
    </select>

3.<set>

<set> (元素)

        内容(子元素)去除条件的逗号分隔

</set>

(用在update中) set元素只会在子元素有内容的情况下才会插入set字句。

会自动去除子句的[,]逗号。

    <update id="update2">
        update emp
        <set>
            <if test="username != null">username = #{username},</if>
            <if test="name != null">name = #{name},</if>
            where id = #{id}
        </set>
    </update>

4.<foreach> 

collection:遍历出来的集合

item:遍历出来的元素 

separator:分隔符

open:遍历开始时的SQL片段

close:遍历结束时的SQL片段

    <delete id="deleteByIds">
        delete from emp where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>

 5.<sql>

<sql id = "定义名字">

        定义可重复的SQL片段

</sql>

如查询select的字段,我们可以重复抽取代码片段通过<sql>标签整合在用<include>标签进行引用

    <sql id="commonSelect">
        select      id,username,password,name,gender,image,job,entrydate,dept_id,create_time,update_time
        from emp
    </sql>

6.<include>

<include refid = "<sql>标签定义的id名字"/>

通过属性refid 调取之前<sql>的抽取的地方进行引用

指定包含的SQL片段

    <select id="list" resultType="com.itheima.pojo.Emp">
        <include refid="commonSelect"/>
        where
        <if test="name != null">
            name like concat('%', #{name}, '%')
        </if>
        order by update_time desc
    </select>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

尤尔哈丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值