Mybatis学习总结二

1.传递pojo对象

Mybatis使用ognl表达式解析对象字段的值,如下例子:

 <!—传递pojo对象综合查询用户信息 -->
 <select id="findUserByUser" parameterType="user" resultType="user">
    select * from user where id=#{id} and username like '%${username}%'
 </select>

MyBatis是通过反射来将java对象映射到查询参数中的。


2.传递pojo包装对象

  开发中通过pojo传递查询条件 ,查询条件是综合的查询条件,不仅包括用户查询条件还包括其它的查询条件(比如将用户购买商品信息也作为查询条件),这时可以使用包装对象传递输入参数。

(1)、定义包装对象

定义包装对象将查询条件(pojo)以类组合的方式包装起来。

public class QueryVo {
    private User user;
    //自定义用户扩展类
    private UserCustom custom;
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public UserCustom getCustom() {
        return custom;
    }
    public void setCustom(UserCustom custom) {
        this.custom = custom;
    }
}

(2)、mapper.xml映射文件

<span style="font-size:14px;"><select id="findUser" parameterType="com.luchao.mybatis.first.po.QueryVo" 	resultType="com.luchao.mybatis.first.po.User">
    select * from user where username like '%${user.username}%' and sex = #{user.sex}
</select></span>

说明:mybatis底层通过ognlpojo中获取属性值:#{user.username}user即是传入的包装对象的属性。


3.传递hashmap

Sql映射文件定义如下:

<span style="font-size:14px;"><select id="findUserByIdMap" parameterType="hashmap" resultType="com.luchao.mybatis.first.po.User">
        select * from user where id = #{id}
</select></span>

 

4.resultMap
resultType可以指定pojo将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功。如果sql查询字段名和pojo的属性名不一致,可以通过resultMap将字段名和属性名作一个对应关系 ,resultMap实质上还需要将查询结果映射到pojo对象中。resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojolist实现一对一查询和一对多查询。

当查询的结果与POJO名字不一致的时候,用resultMap来实现映射。

<resultMap type="user" id="userMap">
        <id column="id_" property="id" />
        <result column="username_" property="username" />
</resultMap>
<select id="findUserMapById" parameterType="java.lang.Integer" resultMap="userMap" >
        select id id_,username username_ from user where id = #{id}
</select>

<id />:此属性表示查询结果集的唯一标识,非常重要。如果是多个字段为复合唯一约束则定义多个<id />

Property:表示person类的属性。

Column:表示sql查询出来的字段名。

Columnproperty放在一块儿表示将sql查询出来的字段映射到指定的pojo类属性上。

<result />:普通结果,即pojo的属性。


5.resultType(输出类型)

(1)输出简单类型

映射文件:

<select id="findUserCount" parameterType="user" resultType="int">
     select count(1) from user
</select>

输出简单类型必须查询出来的结果集有一条记录,最终将第一个字段的值转换为输出类型。使用sessionselectOne可查询单条记录。

(2)输出pojo对象

映射文件:

<!-- 根据id查询用户信息 -->
<select id="findUserById" parameterType="int" resultType="user">
     select * from user where id = #{id}
</select>  

(3)输出pojo列表

映射文件:

<!-- 根据名称模糊查询用户信息 -->
<select id="findUserByUsername" parameterType="string" resultType="user">
    select * from user where username like '%${value}%'
</select>

注意:MyBatis会根据Mapper接口方法的返回类型来选择调用selectOne还是selectList方法,如果是List这调用selectList方法,如果是POJO则调用selectOne方法。
(4)输出hashmap

 输出pojo对象可以改用hashmap输出类型,将输出的字段名称作为mapkeyvalue为字段值。

resultType总结:

  输出pojo对象和输出pojo列表在sql中定义的resultType是一样的。返回单个pojo对象要保证sql查询出来的结果集为单条,内部使用session.selectOne方法调用,mapper接口使用pojo对象作为方法返回值。返回pojo列表表示查询出来的结果集可能为多条,内部使用session.selectList方法,mapper接口使用List<pojo>对象作为方法返回值。

 

6.动态Sql

 mybatis 的动态sql语句基于OGNL表达式的。可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类:
 (1). if 语句 (简单的条件判断)
 (2). choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中的choose 很类似.
 (3). trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀)
 (4). where (主要是用来简化sql语句中where条件判断的,能智能的处理 and or ,不必担心多余导致语法错误)
 (5). set (主要用于更新时)
 (6). foreach (在实现 mybatis in 语句查询时特别有用)
下面分别介绍这几种处理方式

(1)if语句处理

  <select id="dynamicIfTest" parameterType="Blog" resultType="Blog">
        select * from t_blog where 1 = 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>

解析

  如果你提供了title参数,那么就要满足title=#{title},同样如果你提供了Content和Owner的时候,它们也需要满足相应的条件,之后就是返回满足这些条件的所有Blog,这是非常有用的一个功能。

  以往我们使用其他类型框架或者直接使用JDBC的时候, 如果我们要达到同样的选择效果的时候,我们就需要拼SQL语句,这是极其麻烦的,比起来,上述的动态SQL就要简单多了。

(2)choose (when,otherwize) ,相当于java 语言中的 switch ,与 jstl 中的choose 很类似

<select id="dynamicChooseTest" parameterType="Blog" resultType="Blog">
        select * from t_blog where 1 = 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>

    when元素表示当when中的条件满足的时候就输出其中的内容,跟JAVA中的switch效果差不多的是按照条件的顺序,当when中有条件满足的时候,就会跳出choose,即所有的when和otherwise条件中,只有一个会输出,当所有的条件都不满足的时候就输出otherwise中的内容。所以上述语句的意思非常简单, 当title!=null的时候就输出and titlte = #{title},不再往下判断条件,当title为空且content!=null的时候就输出and content = #{content},当所有条件都不满足的时候就输出otherwise中的内容。

(3)trim (对包含的内容加上 prefix,或者 suffix 等,前缀,后缀)

<span style="font-size:14px;">  <select id="dynamicTrimTest" parameterType="Blog" resultType="Blog">
        select * from t_blog 
        <trim prefix="where" prefixOverrides="and |or">
            <if test="title != null">
                title = #{title}
            </if>
            <if test="content != null">
                and content = #{content}
            </if>
            <if test="owner != null">
                or owner = #{owner}
            </if>
        </trim>
    </select></span>

trim元素的主要功能是可以在自己包含的内容前加上某些前缀也可以在其后加上某些后缀,与之对应的属性是prefix和suffix;可以把包含内容的首部某些内容覆盖,即忽略,也可以把尾部的某些内容覆盖,对应的属性是prefixOverrides和suffixOverrides;正因为trim有这样的功能,所以我们也可以非常简单的利用trim来代替where元素的功能。

(4) where (主要是用来简化sql语句中where条件判断的,能智能的处理 and or 条件)

  <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>

      where元素的作用是会在写入where元素的地方输出一个where,另外一个好处是你不需要考虑where元素里面的条件输出是什么样子的,MyBatis会智能的帮你处理,如果所有的条件都不满足那么MyBatis就会查出所有的记录,如果输出后是and 开头的,MyBatis会把第一个and忽略,当然如果是or开头的,MyBatis也会把它忽略;此外,在where元素中你不需要考虑空格的问题,MyBatis会智能的帮你加上。像上述例子中,如果title=null, 而content != null,那么输出的整个语句会是select * from t_blog where content = #{content},而不是select * from t_blog where and content = #{content},因为MyBatis会智能的把首个and 或 or 给忽略。

(5)set (主要用于更新时)

<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>

 set元素主要是用在更新操作的时候,它的主要功能和where元素其实是差不多的,主要是在包含的语句前输出一个set,然后如果包含的语句是以逗号结束的话将会把该逗号忽略,如果set包含的内容为空的话则会出错。有了set元素我们就可以动态的更新那些修改了的字段。

(6)foreach (在实现 mybatis in 语句查询时特别有用)
  foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有item,index,collection,open,separator,close。

  • item表示集合中每一个元素进行迭代时的别名
  • index指定一个名字,用于表示在迭代过程中,每次迭代到位置
  • open表示该语句以什么开始
  • separator表示在每次进行迭代之间以什么符号作为分隔符
  • close表示以什么结束

  在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有一下3种情况:

  • 如果传入的是单参数参数类型是一个List的时候,collection属性值为list
  • 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
  • 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在MyBatis里面也是会把它封装成一个Map的,map的key就是参数名,所以这个时候collection属性值就是传入的List或array对象在自己封装的map里面的key

单参数List的类型

  <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>

上述collection的值为list,对应的Mapper是这样的

public List<Blog> dynamicForeachTest(List<Integer> ids); 

数组类型的参数

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

对应mapper

public List<Blog> dynamicForeach2Test(int[] ids);  

 Map 类型的参数

<select id="dynamicForeach3Test" resultType="Blog">
        select * from t_blog where title like "%"#{title}"%" and id in
        <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

mapper 应该是这样的接口:

public List<Blog> dynamicForeach3Test(Map<String, Object> params); 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值