美文网首页
MyBatis入门(二)

MyBatis入门(二)

作者: 長得太帥忚四種檌 | 来源:发表于2017-12-25 18:12 被阅读13次

    Configuration.xml中配置的内容和顺序如下:

    以下内容可以有, 也可以没有, 但是有的时候, 顺序必须是这样的:

    • properties(属性)
    • settings(全局配置参数)
    • typeAliases(类型别名)
    • typeHandlers(类型处理器)
    • objectFactory(对象工厂)
    • plugins(插件)
    • environments(环境集合属性对象)
      • environment(环境子属性对象)
        • transactionManager(事务管理)
        • dataSource(数据源)
    • mappers(映射器)

    properties属性的配置

    • 可以直接在properties节点里面定义属性:
    <properties>
        <property name="jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="jdbc.url" value="jdbc:mysql://localhost:3306/mybatis"/>
    </properties>
    
    
    • 也可以在classpath路径下创建一个properties文件, 加载到properties属性中

    1.创建db.properties文件

    jdbc.url=jdbc:mysql://localhost:3306/mybatis
    jdbc.driver=com.mysql.jdbc.Driver
    jdbc.username=root
    jdbc.password=root
    

    2.在properties节点中加载

    <properties resource="db.properties"></properties>
    

    3.加载属性文件的同时, 还可以在properties节点中定义属性, 当两者中有相同名字的属性时, 使用的是属性文件中的内容!

    typeAliases节点配置: 给pojo类型起一个别名, 方便使用!

    • 给指定的一个类型起别名, 使用时不区分大小写
    <typeAliases>
        <!-- 给指定的一个类型起别名, 使用时不区分大小写 -->
        <typeAlias type="com.gongxm.bean.Book" alias="book"/>
    </typeAliases>
    
    • 给指定的包下的所有类型起别名,别名就是类名, 使用时不区分大小写
    <typeAliases>
        <!-- 给指定的包下的所有类型起别名,别名就是类名, 使用时不区分大小写 -->
        <package name="com.gongxm.bean"/>
    </typeAliases>
    
    • 默认已支持的别名:
    别名 映射的类型
    _byte byte
    _long long
    _short short
    _int int
    _integer int
    _double double
    _float float
    _boolean boolean
    string String
    byte Byte
    long Long
    short Short
    int Integer
    integer Integer
    double Double
    float Float
    boolean Boolean
    date Date
    decimal BigDecimal
    bigdecimal BigDecimal
    map Map

    mappers(映射器)

    Mapper配置的几种方法:

    • 使用相对于classpath的资源
      如:
    <mapper resource="sqlmap/User.xml" />
    
    • 使用mapper接口类路径
      如:
    <mapper class="com.gongxm.mybatis.mapper.UserMapper"/>
    

    注意:此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中。

    • 注册指定包下的所有mapper接口
      如:
    <package name="com.gongxm.mybatis.mapper"/>
    

    注意:此种方法要求mapper接口名称和mapper映射文件名称相同,且放在同一个目录中。

    resultMap

    如果sql查询字段名和pojo的属性名不一致,可以通过resultMap将字段名和属性名作一个对应关系 ,resultMap实质上还需要将查询结果映射到pojo对象中。

    • 在mapper.xml文件中:
    <!-- resultMap定义
        type:返回结果映射的pojo,可以使用别名
     -->
    <resultMap type="orders" id="order_list_result_map">
        <!-- id主键的映射, property时候pojo中主键的属性,column:返回结果中主键的列-->
        <id property="id" column="id"/>
        <!-- 普通列使用result映射 -->
        <result property="userId" column="user_id"/>
        <result property="number" column="number"/>
        <result property="createtime" column="createtime"/>
        <result property="note" column="note"/>
    </resultMap>
    <select id="getOrderListResultMap" resultMap="order_list_result_map">
        select id,user_id,number,createtime,note from orders
    </select>
    
    • 说明
    <id />:此属性表示查询结果集的唯一标识,非常重要。如果是多个字段为复合唯一约束则定义多个<id />。
    Property:表示User类的属性。
    Column:表示sql查询出来的字段名。
    Column和property放在一块儿表示将sql查询出来的字段映射到指定的pojo类属性上。
    <result />:普通结果,即pojo的属性。
    

    动态SQL语句

    • if语句: 满足条件的时候拼接sql语句
    <sql id="find_user_list_where">
      select * from user
      where 1=1
      <if test="id!=null">
        and id=#{id}
      </if>
      <if test="username != null and username != ''">
        and username like '%${username}%'
      </if>
    </sql>
    
    • where语句: 删除多余的and
    <sql id="find_user_list_where">
      select * from user
     <where>
        <if test="id!=null">
          and id=#{id}
        </if>
        <if test="username != null and username != ''">
          and username like '%${username}%'
        </if>
     </where>
    </sql>
    
    • foreach: 循环
      ids是一个id的集合:
    <if test="ids!=null and ids.size>0">
      <foreach collection="ids" open=" and id in(" close=")" item="id" separator="," >
        #{id}
      </foreach>
    </if>
    

    说明:
    collection: 指定要遍历的集合
    open: 要生成的语句以什么内容开始
    close:要生成的语句以什么内容结束
    item: 遍历到集合中的元素
    separator: 每个元素之间的分隔符

    • SQL片段: 提取公共SQL语句, 方便复用
        <sql id="select">
            select * from books
        </sql>
        
        <select id="findBookById" parameterType="string" resultType="com.gongxm.bean.Book">
            <include refid="select"/> where id = #{id}
        </select>
        
        <select id="findBooksByName" parameterType="string" resultType="com.gongxm.bean.Book">
            <include refid="select"/> where book_name like #{name}
        </select>
    

    resultMap定义一对一, 一对多关系

    • 一对一
        <!-- 查询订单关联用户信息使用resultmap -->
        <resultMap type="Orders" id="orderUserResultMap">
            <id column="id" property="id"/>
            <result column="user_id" property="userId"/>
            <result column="number" property="number"/>
            <result column="createtime" property="createtime"/>
            <result column="note" property="note"/>
            <!-- 一对一关联映射 -->
            <!-- 
            property:Orders对象的user属性
            javaType:user属性对应 的类型
             -->
            <association property="user" javaType="com.gongxm.mybatis.po.User">
                <!-- column:user表的主键对应的列  property:user对象中id属性-->
                <id column="user_id" property="id"/>
                <result column="username" property="username"/>
                <result column="address" property="address"/>
            </association>
        </resultMap>
        <select id="findOrdersWithUserResultMap" resultMap="orderUserResultMap">
            SELECT
                o.id,
                o.user_id,
                o.number,
                o.createtime,
                o.note,
                u.username,
                u.address
            FROM
                orders o
            JOIN `user` u ON u.id = o.user_id
        </select>
    

    说明

    association:表示进行关联查询单条记录
    property:表示关联查询的结果存储在com.gongxm.mybatis.po.Orders的user属性中
    javaType:表示关联查询的结果类型
    <id property="id" column="user_id"/>:查询结果的user_id列对应关联对象的id属性,这里是<id />表示user_id是关联查询对象的唯一标识。
    <result property="username" column="username"/>:查询结果的username列对应关联对象的username属性。
    
    • 一对多
      <resultMap type="user" id="userOrderResultMap">
            <!-- 用户信息映射 -->
            <id property="id" column="id"/>
            <result property="username" column="username"/>
            <result property="birthday" column="birthday"/>
            <result property="sex" column="sex"/>
            <result property="address" column="address"/>
            <!-- 一对多关联映射 -->
            <collection property="orders" ofType="orders">
                <id property="id" column="oid"/>    
                  <!--用户id已经在user对象中存在,此处可以不设置-->
                <!-- <result property="userId" column="id"/> -->
                <result property="number" column="number"/>
                <result property="createtime" column="createtime"/>
                <result property="note" column="note"/>
            </collection>
        </resultMap>
        <select id="getUserOrderList" resultMap="userOrderResultMap">
            SELECT
            u.*, o.id oid,
            o.number,
            o.createtime,
            o.note
            FROM
            `user` u
            LEFT JOIN orders o ON u.id = o.user_id
        </select>
    

    说明

    collection部分定义了用户关联的订单信息。表示关联查询结果集
    property="orders":关联查询的结果集存储在User对象的上哪个属性。
    ofType="orders":指定关联查询的结果集中的对象类型即List中的对象类型。此处可以使用别名,也可以使用全限定名。
    <id />及<result/>的意义同一对一查询。
    

    相关文章

      网友评论

          本文标题:MyBatis入门(二)

          本文链接:https://www.haomeiwen.com/subject/dnylgxtx.html