Mybatis Mapper.xml零碎知识点

sql操作参数

  • parameterType:指定输入参数的类型
  • resultType:指定输出结果的类型,在select中如果查询结果是集合,那么也表示集合中每个元素的类型
  • #{}:表示占位符,用来接收输入参数,类型可以是简单类型,pojo,HashMap等等
    • 如果接收简单类型,#{}可以写成 value 或者其他名称
    • 如果接收 pojo 对象值,通过 OGNL 读取对象中的属性值,即属性.属性的方式获取属性值
  • ${}:表示一个拼接符,会引起 sql 注入,不建议使用
    • 用来接收输入参数,类型可以是简单类型,pojo,HashMap等等
    • 如果接收简单类型,${}里面只能是 value
    • 如果接收 pojo 对象值,通过 OGNL 读取对象中的属性值,即属性.属性 的方式获取属性值

Mybaties中的默认支持的别名

这里写图片描述

这里写图片描述

resultMap和resultType的区别

返回类型可以用resultType,也可以用resultMap,resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,但是resultType跟resultMap不能同时存在。

    在MyBatis进行查询映射的时候,其实查询出来的每一个属性都是放在一个对应的Map里面的,其中键是属性名,值则是其对应的值。当提供的返回类型属性是resultType的时候,MyBatis会将Map里面的键值对取出赋给
    resultType所指定的对象对应的属性。所以其实MyBatis的每一个查询映射的返回类型都ResultMap,只是当我们提供的返回类型属性是resultType的时候,MyBatis对自动的给我们把对应的值赋给resultType所指定对象的属性,而当我们提供的返回类型是resultMap的时候,因为Map不能很好表示领域模型,我们就需要自己再进一步的把它转化为对应的对象,这常常在复杂查询中很有作用。

resultType

<select id="count" parameterType="AreaDto" resultType="java.lang.Integer">  
        SELECT id FROM USER  
</select>  

或者是:

<typeAlias type=”com.someapp.model.User” alias=”User”/>  

<select id="count" parameterType="AreaDto" resultType="User">  
        SELECT * FROM USER  
</select>   

resultMap

<resultMap type="com.liulanghan.Blog" id="BlogResult">    
    <id column="id" property="id"/>    
    <result column="title" property="title"/>    
    <result column="content" property="content"/>    
    <result column="owner" property="owner"/>    
</resultMap>   

<select id="selectBlog" parameterType="int" resultMap="BlogResult">    
      select * from t_blog where id = #{id}    
</select>  

动态SQL

if+where 语句

<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
    select * from user
    <where>
        <if test="username != null">
           username=#{username}
        </if>

        <if test="username != null">
           and sex=#{sex}
        </if>
    </where>
</select>

  这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。

if+set 语句

!-- 根据 id 更新 user 表的数据 -->
<update id="updateUserById" parameterType="com.ys.po.User">
    update user u
        <set>
            <if test="username != null and username != ''">
                u.username = #{username},
            </if>
            <if test="sex != null and sex != ''">
                u.sex = #{sex}
            </if>
        </set>

     where id=#{id}
</update>

如果第一个条件 username 为空,那么 sql 语句为:
  update user u set u.sex=? where id=?
如果第一个条件不为空,那么 sql 语句为:
  update user u set u.username = ? ,u.sex = ? where id=?

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值