zoukankan      html  css  js  c++  java
  • Mybatis学习--Mapper.xml映射文件

    • 简介

      Mapper.xml映射文件中定义了操作数据库的sql,每个sql是一个statement,映射文件是mybatis的核心。

      映射文件中有很多属性,常用的就是parameterType(输入类型)、resultType(输出类型)、resultMap()、rparameterMap()。

    • parameterType(输入类型)

      1、#{}与${}

      #{}实现的是向prepareStatement中的预处理语句中设置参数值,sql语句中#{}表示一个占位符即?

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

      使用占位符#{}可以有效防止sql注入,在使用时不需要关心参数值的类型,mybatis会自动进行java类型和jdbc类型的转换。#{}可以接收简单类型值或pojo属性值,如果parameterType传输单个简单类型值,#{}括号中可以是value或其它名称。

      ${}#{}不同,通过${}可以将parameterType 传入的内容拼接在sql中且不进行jdbc类型转换, ${}可以接收简单类型值或pojo属性值,如果parameterType传输单个简单类型值,${}括号中只能是value。使用${}不能防止sql注入,但是有时用${}会非常方便,如下的例子:

      

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

      如果本例子使用#{}则传入的字符串中必须有%号,而%是人为拼接在参数中,显然有点麻烦,如果采用${}sql中拼接为%的方式则在调用mapper接口传递参数就方便很多。

      //如果使用占位符号则必须人为在传参数中加%

      List<User> list = userMapper.selectUserByName("%张三%");

      //如果使用${}原始符号则不用人为在参数中加%

      List<User>list = userMapper.selectUserByName("张三");

      再比如order by排序,如果将列名通过参数传入sql,根据传的列名进行排序,应该写为:

      ORDER BY ${columnName},如果使用#{}将无法实现此功能。

      2、传递简单类型

      传递简单类型只需要注意#{}与${}的使用就可以。

      3、传递pojo对象

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

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

      测试代码:

     1 Public void testFindUserByUser()throws Exception{
     2         //获取session
     3         SqlSession session = sqlSessionFactory.openSession();
     4         //获限mapper接口实例
     5         UserMapper userMapper = session.getMapper(UserMapper.class);
     6         //构造查询条件user对象
     7         User user = new User();
     8         user.setId(1);
     9         user.setUsername("管理员");
    10         //传递user对象查询用户列表
    11         List<User>list = userMapper.findUserByUser(user);
    12         //关闭session
    13         session.close();
    14 }

      如果将username写错后,会报以下异常

    1 org.apache.ibatis.exceptions.PersistenceException: 
    2 ### Error querying database.  Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'dusername' in 'class com.luchao.mybatis.first.po.User'
    3 ### Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'dusername' in 'class com.luchao.mybatis.first.po.User'

      可以看出MyBatis是通过反射来讲java对象映射到查询参数中的。

      4、传递pojo包装对象

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

      (1)、定义包装对象

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

     1 public class QueryVo {
     2     private User user;
     3     //自定义用户扩展类
     4     private UserCustom custom;
     5     public User getUser() {
     6         return user;
     7     }
     8     public void setUser(User user) {
     9         this.user = user;
    10     }
    11     public UserCustom getCustom() {
    12         return custom;
    13     }
    14     public void setCustom(UserCustom custom) {
    15         this.custom = custom;
    16     }
    17 }

      (2)、 mapper.xml映射文件

    1 <select id="findUser" parameterType="com.luchao.mybatis.first.po.QueryVo" resultType="com.luchao.mybatis.first.po.User">
    2         select * from user where username like '%${user.username}%' and sex = #{user.sex}
    3 </select>

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

      5、传递hashmap

      Sql映射文件定义如下:

    1 <select id="findUserByIdMap" parameterType="hashmap" resultType="com.luchao.mybatis.first.po.User">
    2         select * from user where id = #{id}
    3 </select>

      测试代码:

     1 Public void testFindUserByHashmap()throws Exception{
     2         //获取session
     3         SqlSession session = sqlSessionFactory.openSession();
     4         //获限mapper接口实例
     5         UserMapper userMapper = session.getMapper(UserMapper.class);
     6         //构造查询条件Hashmap对象
     7         HashMap<String, Object> map = new HashMap<String, Object>();
     8         map.put("id", 1);        
     9         //传递Hashmap对象查询用户列表
    10         List<User>list = userMapper.findUserByHashmap(map);
    11         //关闭session
    12         session.close();
    13 }

      传递的map中的keysql中解析的key不一致。测试结果没有报错,只是通过key获取值为空。这种用法一般用在POJO与数据库字段不一致的时候。

    • parameterMap和resultMap

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

      下面是在数据库列于POJO不一致的时候,将输入参数映射到数据库列的一种方式 

     1 <resultMap type="Book.dao.Book" id="BookResultMap">
     2   <id column="id" property="id"/>
     3   <result column="name" property="bookName"/>
     4   <result column="price" property="bookPrice"/>
     5  </resultMap>
     6  
     7  <!-- resultMap:resultMap的id ,bookName:resultMap的property,即实体类中的属性 -->
     8  <parameterMap type="Book.dao.Book" id="BookParameterMap">
     9   <parameter property="bookName" resultMap="BookResultMap" />  
    10   <parameter property="bookPrice" resultMap="BookResultMap" />  
    11  </parameterMap>
    12 <!-- 保存一个Book -->
    13  <insert id="saveBook" parameterMap="BookParameterMap">
    14   insert into BOOK_MANAGE
    15    (ID,NAME,PRICE)
    16     values
    17    (Bookmanage_Seq.Nextval,#{bookName},#{bookPrice})
    18  </insert>
    19  
    20  <!-- 根据ID修改Book -->
    21  <update id="updatePersnById" parameterMap="BookParameterMap">
    22   update BOOK_MANAGE 
    23    set 
    24     NAME=#{bookName},
    25     PRICE=#{bookPrice}
    26    WHERE id=#{id}
    27  </update>

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

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

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

      Property:表示person类的属性。

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

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

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

      使用resultType进行输出映射,只有查询出来的列名和pojo中的属性名一致,该列才可以映射成功。如果查询出来的列名和pojo的属性名不一致,通过定义一个resultMap对列名和pojo属性名之间作一个映射关系。

    • resultType(输出类型)

      1、输出简单类型

      映射文件:

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

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

      2、输出pojo对象

      映射文件

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

      3、输出pojo列表

      映射文件:

    1 <!-- 根据名称模糊查询用户信息 -->
    2     <select id="findUserByUsername" parameterType="string" resultType="user">
    3        select * from user where username like '%${value}%'
    4     </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>对象作为方法返回值。

    • 动态SQl

      mybatis核心 对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接、组装。对查询条件进行判断,如果输入参数不为空才进行查询条件拼接。

      1、if

     1 <!-- 传递pojo综合查询用户信息 -->
     2     <select id="findUserList" parameterType="user" resultType="user">
     3         select * from user 
     4         where 1=1 
     5         <if test="id!=null and id!=''">
     6         and id=#{id}
     7         </if>
     8         <if test="username!=null and username!=''">
     9         and username like '%${username}%'
    10         </if>
    11 </select>

      2、Where

      上面的配置也可以按如下来写:

     1 <select id="findUserList" parameterType="user" resultType="user">
     2         select * from user 
     3         <where>
     4         <if test="id!=null and id!=''">
     5         and id=#{id}
     6         </if>
     7         <if test="username!=null and username!=''">
     8         and username like '%${username}%'
     9         </if>
    10         </where>
    11 </select>

      <where />可以自动处理第一个and

      3、foreach

      sql传递数组或Listmybatis使用foreach解析,如下:

      如果我们需要传入多个ID来查询多个用户的信息,这也就可以使用foreach。我们先考虑下如果只写sql语句是如下:

    1 SELECT * FROM USERS WHERE username LIKE '%张%' AND (id =10 OR id =89 OR id=16)
    2 SELECT * FROM USERS WHERE username LIKE '%张%'  id IN (10,89,16)

      index:为数组的下标。

      item:为数组每个元素的名称,名称随意定义

      open:循环开始

      close:循环结束

      separator:中间分隔输出

      通过POJO传入List,映射文件如下:

    1 <if test="ids!=null and ids.size>0">
    2             <foreach collection="ids" open=" and id in(" close=")" item="id" separator="," >
    3                 #{id}
    4             </foreach>
    5 </if>

      或者:

    1 <if test="ids!=null and ids.size>0">
    2             <foreach collection="ids" open=" and (" close=")" item="id" separator="," >
    3                  id = #{id}
    4             </foreach>
    5 </if>

       传递单个List

      传递List类型在编写mapper.xml没有区别,唯一不同的是只有一个List参数时它的参数名为list

      配置文件如下:

    <select id="selectUserByList" parameterType="java.util.List" resultType="user">
            select * from user 
            <where>
            <!-- 传递List,List中是pojo -->
            <if test="list!=null">
            <foreach collection="list" item="item" open="and id in("separator=","close=")">
                #{item.id} 
            </foreach>
            </if>
            </where>
    </select>

      传递单个数组(数组中是POJO)

    <!-- 传递数组综合查询用户信息 -->
        <select id="selectUserByArray" parameterType="Object[]" resultType="user">
            select * from user 
            <where>
            <!-- 传递数组 -->
            <if test="array!=null">
            <foreach collection="array" index="index" item="item" open="and id in("separator=","close=")">
                #{item.id} 
            </foreach>
            </if>
            </where>
    </select>

      sql只接收一个数组参数,这时sql解析参数的名称mybatis固定为array,如果数组是通过一个pojo传递到sql则参数的名称为pojo中的属性名。

      传递单个数组(数组中是简单类型)

      配置文件如下:

     1 <!-- 传递数组综合查询用户信息 -->
     2 <select id="selectUserByArray" parameterType="Object[]" resultType="user">
     3         select * from user 
     4         <where>
     5         <!-- 传递数组 -->
     6         <if test="array!=null">
     7         <foreach collection="array"index="index"item="item"open="and id in("separator=","close=")">
     8             #{item} 
     9         </foreach>
    10         </if>
    11         </where>
    12 </select>

      如果数组中是简单类型则写为#{item},不用再通过ognl获取对象属性值了。

        Sql片段

      Sql中可将重复的sql提取出来,使用时用include引用即可,最终达到sql重用的目的,如下:

      映射文件如下:

     1 <!-- 传递pojo综合查询用户信息 -->
     2     <select id="findUserList" parameterType="user" resultType="user">
     3         select * from user 
     4         <where>
     5         <if test="id!=null and id!=''">
     6         and id=#{id}
     7         </if>
     8         <if test="username!=null and username!=''">
     9         and username like '%${username}%'
    10         </if>
    11         </where>
    12     </select>

      如果有多个statement都使用相同的查询条件,那么就可以把查询条件抽取出来作为单独的Sql片段。

      Sql片段配置:

    1 <sql id="query_user_where">
    2     <if test="id!=null and id!=''">
    3         and id=#{id}
    4     </if>
    5     <if test="username!=null and username!=''">
    6         and username like '%${username}%'
    7     </if>
    8 </sql>

      使用include引用:

    1 <select id="findUserList" parameterType="user" resultType="user">
    2         select * from user 
    3         <where>
    4         <include refid="query_user_where"/>
    5         </where>
    6 </select>

      注意:如果引用其它mapper.xmlsql片段,则在引用时需要加上namespace,如下:<include refid="namespace.sql片段”/>

      Mapper配置文件中常用的基本属性就是这些,如果还有其他的特殊需求可以根据需要来进行修改配置。另外,在我们的设计中,如果已经定义好了基本的POJO在引用的时候可以在定义一个视图查询层的POJO在其中封装基本的POJO和自定义的POJO(继承基本的POJO),这样就可以较容易实现扩展。当数据库需求有变化的时候可以不修改基本POJO,而修改自定义的POJO,这样就可以实现较好的扩展,而不影响其他模块。如果前端需求有变动,可以通过修改前端的POJO来实现较小的改动。如下实现:

      基本的POJO类型:

     1 public class User {
     2     private int id;
     3     private String username;// 用户姓名
     4     private String sex;// 性别
     5     private Date birthday;// 生日
     6     private String address;// 地址
     7     public int getId() {
     8         return id;
     9     }
    10     public void setId(int id) {
    11         this.id = id;
    12     }
    13     public String getUsername() {
    14         return username;
    15     }
    16     public void setUsername(String username) {
    17         this.username = username;
    18     }
    19     public String getSex() {
    20         return sex;
    21     }
    22     public void setSex(String sex) {
    23         this.sex = sex;
    24     }
    25     public Date getBirthday() {
    26         return birthday;
    27     }
    28     public void setBirthday(Date birthday) {
    29         this.birthday = birthday;
    30     }
    31     public String getAddress() {
    32         return address;
    33     }
    34     public void setAddress(String address) {
    35         this.address = address;
    36     }
    37     @Override
    38     public String toString() {
    39         // TODO Auto-generated method stub
    40         return this.id+"-"+this.username+"-"+this.sex+"-"+this.address+"-"+this.birthday.toString();
    41     }
    42     
    43 }

      自定义的POJO继承基本的POJO:

    1 public class UserCustom extends User{
    2 
    3 }

      如果我们的数据库有变动,我们可以在UserCustom添加属性,只满足当前修改。

      前端POJO实现:

     1 public class QueryVo {
     2     private User user;
     3     //自定义用户扩展类
     4     private UserCustom custom;
     5     public User getUser() {
     6         return user;
     7     }
     8     public void setUser(User user) {
     9         this.user = user;
    10     }
    11     public UserCustom getCustom() {
    12         return custom;
    13     }
    14     public void setCustom(UserCustom custom) {
    15         this.custom = custom;
    16     }
    17 }

      可以满足基本的需求,如果我们在查询中需要加入其他查询条件,如:商品、订单等,只需要修改QueryVo,这样就可以实现较好的可扩展性。 

  • 相关阅读:
    Runloop详解
    iOS高效裁剪图片圆角算法
    Runtime详解(下)
    Runtime详解(上)
    iOS UITextfield只允许输入数字和字母,长度限制
    iOS多线程(上)——GCD详解(上)
    @property、@sythesize以及Ivar和@dynamic讲解(下)
    iOS 循环引用讲解(中)
    @property详解,@property修饰符以及各个修饰符区别(上)
    PHP 使用 OSS 批量上传图片
  • 原文地址:https://www.cnblogs.com/lcngu/p/5470695.html
Copyright © 2011-2022 走看看