MyBatis学习

来源:互联网 发布:淘宝评价添加小视频 编辑:程序博客网 时间:2024/06/09 13:56

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名称不相同。

0 0
原创粉丝点击