MyBatis学习

MyBatis是一个支持普通SQL查询,存储过程和高级映射的优秀持久层框架。

MyBatis常用SQL标签

1. 基本标签 执行CRUD操作

select insert update delete

2. 动态标签 在SQL语句中实现某些逻辑

(1) 条件判断 

where:简化SQL语句中where中的条件判断

<select id="dynamicWhereTest" parameterType="Blog" resultType="Blog">  
    select * from t_blog   
    <where>  
        <if test="title != null">  
            title = #{title}  
        </if>  
        <if test="content != null">  
            and content = #{content}  
        </if>  
        <if test="owner != null">  
            and owner = #{owner}  
        </if>  
    </where>  
</select>

if:条件判断,利用if语句可以实现某些简单的条件选择

<select id="dynamicIfTest" parameterType="Blog" resultType="Blog">  
    select * from t_blog where 11 = 1  
    <if test="title != null">  
        and title = #{title}  
    </if>  
    <if test="content != null">  
        and content = #{content}  
    </if>  
    <if test="owner != null">  
        and owner = #{owner}  
    </if>  
</select> 

choose(when otherwise):相当于JAVA中的switch语句,基本上跟JSTL中的choose的作用和用法是一样的,通常与when和otherwise搭配

<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">  
    select * from t_blog where 11 = 1   
    <choose>  
        <when test="title != null">  
            and title = #{title}  
        </when>  
        <when test="content != null">  
            and content = #{content}  
        </when>  
        <otherwise>  
            and owner = "owner1"  
        </otherwise>  
    </choose>  
</select>

(2) 设置标签 

set:主要用在更新操作的时候,主要功能和where元素差不多

<update id="dynamicSetTest" parameterType="Blog">  
    update t_blog  
    <set>  
        <if test="title != null">  
            title = #{title},  
        </if>  
        <if test="content != null">  
            content = #{content},  
        </if>  
        <if test="owner != null">  
            owner = #{owner}  
        </if>  
    </set>  
    where id = #{id}  
</update> 

(3) 循环标签 

foreach:主要用在构建in条件中,它可以在SQL语句中迭代一个集合

<select id="dynamicForeachTest" resultType="Blog">  
    select * from t_blog where id in  
    <foreach collection="list" index="index" item="item" open="(" separator="," close=")">  
        #{item}  
    </foreach>  
</select>

参考资料:

1. MyBatis的动态SQL详解

MyBatis中#与$的区别

(1) #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号,#方式能够很大程度防止sql注入
(2) $将传入的数据直接显示生成在sql中,$方式无法防止Sql注入

MyBatis学习总结(四)——解决字段名与实体类属性名不相同的冲突

Mapped Statements collection does not contain value for ...

Mapped Statements collection does not contain value for ... 的错误原因有几种: 
(1) mapper.xml中没有加入namespace 
(2) mapper.xml中的方法和接口mapper的方法不对应 
(3) mapper.xml没有加入到mybatis-config.xml中(即总的配置文件),例外:配置了mapper文件的包路径的除外 
(4) mapper.xml文件名和所写的mapper名称不相同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值