MyBatis的学习总结

本文详细介绍了MyBatis的环境搭建,包括主配置文件的设置,如事务管理器、数据源、连接池的选择。讲解了 Dao 对应的配置文件,包括 SQL 映射、动态SQL(if、where、foreach)、多表查询。还涉及了延迟加载的开启与SQL修改,以及MyBatis的一级和二级缓存的配置与使用。内容深入浅出,适合初学者学习。
摘要由CSDN通过智能技术生成


在创建实体类时候最好使用和表中属性一致,为了以后不必要参数封装。idea的database工具给我提供了很好用的实体类生成方法(具体操作请查看该链接): idea的数据库工具

环境搭建

在resources目录下创建个主配置文件名字随便。并添加如下约束:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

具体配置如下:

主配置文件:

  • environments:配置环境
    • environment:配置MySQL的环境

      • transactionManager:配置的事务类型

      • dataSource:配置连接池(数据源)

        • POOLED 采用传统的javax.sql.DataSource规范中的连接池,mybatis中有针对规范的实现
        • UNPOOLED 采用传统的获取连接的方式,虽然也实现Javax.sql.DataSource接口,但是并没有使用池的思想。
        • JNDI 采用服务器提供的JNDI技术实现,来获取DataSource对象,不同的服务器所能拿到DataSource是不一样。
          注意:如果不是web或者maven的war工程,是不能使用的。
          我们课程中使用的是tomcat服务器,采用连接池就是dbcp连接池。
  • properties:可以在标签内部配置连接数据库信息。也可以通过属性引用外部配置文件信息
    • resource属性:
      用于指定配置文件的位置,按照类路径的写法来写,并且必须存在与类路径下
    • url属性:
      Url写法
      http://localhost:8080/mybatisserver/
<properties resource="jdbcConfig.properties">
<!--配置环境-->
<environments default="mysql">
        <environment id="mysql">
            <!-- 配置的事务类型 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置连接池(数据源)           -->
            <dataSource type="POOLED">
                <!-- 配置连接数据库的4个基本信息 -->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
</environments>
  • mappers:指定映射文件的位置,映射配置文件指的是每个dao独立的配置文件
<!--使用xml的方式 -->
         <!--使用xml的方式 -->
        <mapper resource="com/oak/dao/IUserDao.xml"/>
        <!--使用注解的方式-->
        <mapper class="com.oak.dao.IUserDao"/>
        <!-- package标签是用于指定dao接口所在的包,当指定了之后就不需要在写mapper以及resource或者class了 -->
        <package name="com.oak.dao"></package>
  • typeAliases:用于配置别名。type属性指定的是实体类的全限定类名。alias属性指定别名。指定了别名就不在区分大小写了
 <typeAliases>
        <!--typeAlias 用于配置别名。type属性指定的是实体类的全限定类名。alias属性指定别名。指定了别名就不在区分大小写了-->
        <!--        <typeAlias type="com.oak.domain.User" alias="user"></typeAlias>-->
        <!-- package用于指定配置别名的包,当指定之后,该包下的实体类都会注册别名,并且别名就是类名,不在区分大小写-->
        <package name="com.oak.domain"/>
    </typeAliases>

最终配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--mybatis 主配置文件-->
<configuration>
    <!--配置properties
    可以在标签内部配置连接数据库信息。也可以通过属性引用外部配置文件信息
    resource属性:
        用于指定配置文件的位置,按照类路径的写法来写,并且必须存在与类路径下
    url属性:
        Url写法
        http://localhost:8080/mybatisserver/
    -->
    <properties resource="jdbcConfig.properties">

    </properties>
    <typeAliases>
        <!--typeAlias 用于配置别名。type属性指定的是实体类的全限定类名。alias属性指定别名。指定了别名就不在区分大小写了-->
        <!--        <typeAlias type="com.oak.domain.User" alias="user"></typeAlias>-->
        <!-- package用于指定配置别名的包,当指定之后,该包下的实体类都会注册别名,并且别名就是类名,不在区分大小写-->
        <package name="com.oak.domain"/>
    </typeAliases>
    <!--配置环境-->
    <environments default="mysql">
        <environment id="mysql">
            <!-- 配置的事务类型 -->
            <transactionManager type="JDBC"></transactionManager>
            <!-- 配置连接池(数据源)           -->
            <dataSource type="POOLED">
                <!-- 配置连接数据库的4个基本信息 -->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--指定映射文件的位置,映射配置文件指的是每个dao独立的配置文件-->
    <mappers>
        <!--使用xml的方式 -->
        <!--        <mapper resource="com/oak/dao/IUserDao.xml"/>-->
        <!--使用注解的方式-->
        <!--        <mapper class="com.oak.dao.IUserDao"/>-->
        <!-- package标签是用于指定dao接口所在的包,当指定了之后就不需要在写mapper以及resource或者class了 -->
        <package name="com.oak.dao"></package>
    </mappers>
</configuration>

Dao 对应的配置文件

在resources目录下创建和Dao目录一样的目录结构并创建相应的xxx.xml。并添加如下约束:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

在每个dao的配置文件的mapper 标签加上namespace属性,且namespace的值为该类的全限定类名。
mapper 的内部标签就是相应sql语句,且id为该接口相应方法名,内部为相应的SQL语句。例如一个findAll方法对应的写法:

<!--查询所有用户    -->
    <select id="findAll" resultType="user">
        select *
        from user
    </select>
  • resultType :返回值的封装类型
  • parameterType: 参数的类型,且取值时,按照#{},大括号里面是实体类的名称。
    实例如下:
<!--根据id 查询用户-->
    <select id="findById" parameterType="java.lang.Integer" resultType="com.oak.domain.User">
        select *
        from user
        where id = #{id}
    </select>
  • resultMap:配置查询结果的列名和实体类的属性名的对应关系,相应的返回值需要用resultMap来代替resultType。
    实例如下:
 <resultMap id="userMap" type="uSeR">
        <!-- 主键字段的对应 -->
        <id property="userId" column="id"></id>
        <!--非主键字段的对应-->
        <result property="userName" column="username"></result>
        <result property="userAddress" column="address"></result>
        <result property="userSex" column="sex"></result>
        <result property="userBirthday" column="birthday"></result>
    </resultMap>

动态SQL:

  • if :判断
  • where :
    实例如下:
<!--根据条件查询-->
    <select id="findByConditions" parameterType="user" resultType="user">
        select * from user
        <where>
            <if test="username != null">
                and username=#{username}
            </if>
            <if test="id != null">
                and id=#{id}
            </if>
            <if test="birthday != null">
                and birthday=#{birthday}
            </if>
            <if test="address != null">
                and address=#{address}
            </if>
            <if test="sex != null">
                and sex=#{sex}
            </if>
        </where>
    </select>
  • foreach ;集合
    实例如下:
<!--根据QueryVo对象查找用户-->
    <select id="findByIds" parameterType="QueryVo" resultType="user">
        select * from user
        <where>
            <if test="ids != null and ids.size() > 0">
                <foreach collection="ids" open="and id in (" close=")" item="id" separator=",">
                    #{id}
                </foreach>
            </if>
        </where>
    </select>

多表查询

  • 一对一:从表实体类应该包含一个主表的实体类的引用。

该返回类型的封装:

<resultMap id="accountMap" type="account">
		<!--property对应实体类的属性,column对应查询结果的列名-->
        <id property="id" column="aid"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
        <!--一对一的关系映射,配置封装user的内容。
        association的column对应的是通过那个来获取的。
        -->
        <association property="user" column="uid" javaType="user">
            <id property="id" column="id"></id>
            <result property="username" column="username"></result>
            <result property="sex" column="sex"></result>
            <result property="birthday" column="birthday"></result>
            <result property="address" column="address"></result>
        </association>
    </resultMap>
  • 一对多:主表实体包含从表实体引用。

该返回类型的封装:

    <resultMap id="userAccountMap" type="user">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="address" column="address"></result>
        <result property="sex" column="sex"></result>
        <result property="birthday" column="birthday"></result>
        <!-- 配置user对象中accounts集合的映射,ofType表示集合内的类型-->
        <collection property="accounts" ofType="account">
            <id column="aid" property="id"></id>
            <result column="uid" property="uid"></result>
            <result column="money" property="money"></result>
        </collection>
    </resultMap>
  • 多对多:主表实体类包含从表的集合属性。

该返回类型的封装:

<resultMap id="roleMap" type="role">
        <id property="roleId" column="rid"></id>
        <result property="roleName" column="role_name"></result>
        <result property="roleDesc" column="role_desc"></result>
        <collection property="users" ofType="user">
            <id property="id" column="id"></id>
            <result property="username" column="username"></result>
            <result property="sex" column="sex"></result>
            <result property="birthday" column="birthday"></result>
            <result property="address" column="address"></result>
        </collection>
    </resultMap>

最终配置文件如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.oak.dao.IAccountDao">
    <resultMap id="accountMap" type="account">
        <id property="id" column="aid"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
        <!--一对一的关系映射,配置封装user的内容-->
        <association property="user" column="uid" javaType="user">
            <id property="id" column="id"></id>
            <result property="username" column="username"></result>
            <result property="sex" column="sex"></result>
            <result property="birthday" column="birthday"></result>
            <result property="address" column="address"></result>
        </association>
    </resultMap>
    <!-- 配置一对多的关系映射-->
    <resultMap id="userAccountMap" type="user">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="sex" column="sex"></result>
        <result property="birthday" column="birthday"></result>
        <result property="address" column="address"></result>
        <!-- 配置user对象中account集合的映射       -->
        <collection property="accounts" ofType="account">
            <id property="id" column="aid"></id>
            <result property="uid" column="uid"></result>
            <result property="money" column="money"></result>
        </collection>
    </resultMap>
    <!--查询所有账号的用户    -->
    <select id="findAll" resultMap="accountMap">
        select u.*, a.id as aid, a.uid, a.money
        from account a,
             user u
        where u.id = a.uid;
    </select>
    <!--查询所有用户的账号-->
    <select id="findUserAll" resultMap="userAccountMap">
        select u.*, a.id as aid, a.uid, a.money
        from user u
                 left outer join account a
                                 on u.id = a.uid

    </select>
</mapper>

延迟加载

<!--开启Mybatis支持延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>

对应的SQL语句也要做相应的修改:

 <resultMap id="accountMap" type="account">
        <id property="id" column="id"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
        <!--select属性指定的内容:查询用户的唯一标识
        column属性指定的内容:用户根据id查询时,所需要的参数值
        -->
        <association property="user" column="uid" javaType="user" select="com.oak.dao.IUserDao.findById"></association>
    </resultMap>

 <!--查询所有账号的用户    -->
    <select id="findAll" resultMap="accountMap">
        select *
        from account

    </select>

缓存

缓存是存在于内存中的临时数据。

  • 为什么使用缓存
    减少和数据库的交互次数,提高执行效率。

  • 什么样的数据能使用缓存,什么样的数据不能使用

    • 适用于缓存:
      • 经常查询并且不经常改变的。
      • 数据的正确与否对最终结果影响不大的。
    • 不适用于缓存:
      • 经常改变的数据
      • 数据的正确与否对最终结果影响很大的。
        例如:商品的库存,银行的汇率,股市的牌价。
        Mybatis中的一级缓存和二级缓存
  • 一级缓存:它指的是Mybatis中SqlSession对象的缓存。当我们执行查询之后,查询的结果会同时存入到SqlSession为我们提供一块区域中。该区域的结构是一个Map。当我们再次查询同样的数据,mybatis会先去sqlsession中查询是否有,有的话直接拿出来用。当SqlSession对象消失时,mybatis的一级缓存也就消失了。一级缓存默认开启。

  • 二级缓存:它指的是Mybatis中SqlSessionFactory对象的缓存。由同一个SqlSessionFactory对象创建的SqlSession共享其缓存。

    • 二级缓存的使用步骤:
      1. 让Mybatis框架支持二级缓存(在SqlMapConfig.xml中配置)
      2. 让当前的映射文件支持二级缓存(在IUserDao.xml中配置)
      3. 让当前的操作支持二级缓存(在select标签中配置)

在主配置文件中配置如下:

 <settings>
        <!--开启支持二级缓存-->
        <setting name="cacheEnabled" value="true"/>
        <!--开启Mybatis支持延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>

在Dao的配置文件中:

 <!--开启user支持二级缓存-->
    <cache/>
    <!--根据id 查询用户-->
    <select id="findById" parameterType="java.lang.Integer" resultType="user" useCache="true">
        select *
        from user
        where id = #{id}
    </select>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值