Day64-MyBatis深入


title: Day64-MyBatis深入
date: 2021-04-01 16:28:25
author: Liu_zimo


Mybatis连接池与事务

  • 连接池特性
    • 我们在实际开发中都会使用连接池,因为它可以减少我们获取连接所消耗的时间。
    • 连接池就是用于存储连接的一个容器
    • 容器其实就是—个集合对象,该集合必须是线程安全的,不能两个线程拿到同一连接
    • 该集合还必须实现队列的特性:先进先出
连接池的使用及分析
  • mybatis连接池提供了三种配置方式:
    • 配置的位置:
      • 主配置文件SqlMapConfig.xml中的dataSource标签,type属性就是表示采用何种连接池方式
        • type属性取值
          • POOLED:采用传统的javax.sql.DataSource规范中的连接池,mybatis中有针对规范的实现
          • UNPOOLED:采用传统的获取连接的方式,虽然也实现Javax.sql.DataSource接口,但是并没有使用池的思想。
          • JNDI:采用服务器提供的JNDI技术实现,来获取DataSource对象,不同的服务器所能拿到DataSource是不一样
            • 注意:如果不是web或者maven的war工程,是不能使用的。
            • 我们使用的是tomcat服务器,采用连接池就是dbcp连接池。

POOLED从连接池中取出连接对象,执行结束后归还,而UNPOOLED不使用是连接池技术,直接创建连接,用完就销毁

  • 基类:javax.sql.DataSource

  • UnpooledDataSource

    1. public class UnpooledDataSource implements DataSource {}
    2. public Connection getConnection() throws SQLException {
           return this.doGetConnection(this.username, this.password);
       }
    3. Properties props = new Properties();
       ......
       return this.doGetConnection(props);
    4. this.initializeDriver();
       Connection connection = DriverManager.getConnection(this.url, properties);
       return connection;
    5. private synchronized void initializeDriver() throws SQLException {
           driverType = Class.forName(this.driver, true, this.driverClassLoader);
       }
    
  • PooledDataSource

    1. public class PooledDataSource implements DataSource {}
    2. public Connection getConnection() throws SQLException {
            return this.popConnection(this.dataSource.getUsername(), this.dataSource.getPassword()).getProxyConnection();
        }
    3. private PooledConnection popConnection(String username, String password) throws SQLException {
            while(conn == null) {
                synchronized(this.state) {	// 连接池线程安全
                    if(空闲连接还有){
                        conn = (PooledConnection)this.state.idleConnections.remove(0);
                    }else{
                        if(活动的连接池数量 < 设定的最大值){
                            conn = new PooledConnection(this.dataSource.getConnection(), this);
                        }else{
                            // 获取活动连接池中最老的一个连接出来
                            PooledConnection oldestActiveConnection = (PooledConnection)this.state.activeConnections.get(0);
                        }
                    }
                }
            } 
       }
    
    • 空闲池:如果空闲池还有连接,直接拿出来用
    • 活动池:若空闲池中没有连接,看活动池中是否到达最大数量
      • 若活动池未满,则创建一个连接
      • 若活动池满:返回最早进来的连接
事务控制及分析
  • 事务是指的是一个业务上的最小不可再分单元,通常一个事务对应了一个完整的业务,而一个完整的业务需要批量的DML语句共同联合完成。
  • 事务四大特性:ACID
    • 原子性(atomicity)
    • 一致性(consistency)
    • 隔离性(isolation)
    • 持久性(durability)
  • 不考虑隔离性会产生的三个问题
  • 解决办法:四种隔离界别
  • 它是通过sqlsession对象的commit方法和rollback方法实现事务的提交和回滚
  • 自动提交事务:sqlSession = factory.openSession(true);

Mybatis映射文件的SQL深入

基于XML配置的动态SQL语句使用

mappers配置文件中的几个标签

  • if
<select id="findUserByCondition" resultType="com.zimo.domain.User" parameterType="user">
    select * from user where 1=1
    <if test="username != null">
        and username = #{username}
    </if>
    <if test="sex != null">
        and sex = #{sex}
    </if>
</select>
  • where
<select id="findUserByCondition" resultType="com.zimo.domain.User" parameterType="user">
    select * from user
    <where>
        <if test="username != null">
            and username = #{username}
        </if>
        <if test="sex != null">
            and sex = #{sex}
        </if>
    </where>
</select>
  • foreach
<select id="findUserInIds" resultType="com.zimo.domain.User" parameterType="ids">
    select * from user 
    <where>
        <if test="ids != null and ids.size() > 0">
            <foreach collection="ids" open="and id in(" close = ")" item = "uid" separator=",">
                #{uid}
            </foreach>
        </if>
    </where>
</select>
  • sql
<!-- 抽取重复的sql语句:若后面还有sql拼接,则不要加; -->
<sql id = "defaultUser">
    select * from user
</sql>

<select id="findAll" resultType="com.zimo.domain.User">
    <include refid="defaultUser"></include>
</select>

<select id="findUserByCondition" resultType="com.zimo.domain.User" parameterType="user">
    <include refid="defaultUser"></include>
    <where>
        <if test="username != null">
            and username = #{username}
        </if>
        <if test="sex != null">
            and sex = #{sex}
        </if>
    </where>
</select>

Mybatis的多表关联查询

  • 一对多:用户和订单关系

  • 多对一:订单和用户

  • 一对一:人和身份证

  • 多对多:老师和学生

  • 特例:如果拿出每一个订单,他都只能属于一个用户。所以Mybatis就把多对一看成了一对一

  • 示例:用户和账户
    一个用户可以有多个账户,一个账户只能属于一个用户(多个账户也可以属于同一个用户)

  • 步骤:

    1. 建立两张表:用户表,账户表

      让用户表和账户表之间具备一对多的关系:需要使用外键在账户表中添加

    2. 建立两个实体类:用户实体类和账户实体类

      让用户和账户的实体类能体现出来一对多的关系

    3. 建立两个配置文件
      用户的配置文件、账户的配置文件

    4. 实现配置
      当我们查询用户时,可以同时得到用户下所包含的账户信息
      当我们查询账户时,可以同时得到账户的所属用户信息

  • 示例:用户和角色

    一个用户可以有多个角色

    一个角色可以赋予多个用户

  • 步骤:

    1. 建立两张表:用户表,角色表

      让用户表和角色表具有多对多的关系。需要使用中间表,中间表中包含各自的主键,在中间表中是外键

    2. 建立两个实体类:用户实体类和角色实体类

      让用户和角色的实体类能体现出来多对多的关系
      各自包含对方一个集合引用

    3. 建立两个配置文件
      用户的配置文件、角色的配置文件

    4. 实现配置
      当我们查询用户时,可以同时得到用户所包含的角色信息
      当我们查询角色时,可以同时得到角色的所赋予的用户信息

CREATE TABLE `account`(
	`ID` 			int(11) NOT NULL COMMENT '编号',
	`UID`			int(11) default NULL COMMENT '用户编号',
	`MONEYT` 	double 	default NULL COMMENT '金额',
	PRIMARY KEY (`ID`),
	KEY `FK_Reference_8` (UID),
	CONSTRAINT `FK_Reference_8` FOREIGN KEY (`UID`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

insert into account`( ID`, UID`, MONEY ) values (1,46,1000)(2,45,1000)(3,46,2000);
  • 多表关联查询
<select id="findAllAccount" resultType="com.zimo.domain.AccountUser">
    select a.*, u.username, u.address from account a, user u where u.id = a.uid;
</select>
package com.zimo.domain;
/**
 * @author Liu_zimo
 * @version v0.1 by 2021/4/2 10:40
 */
public class AccountUser extends Account{
    private String username;
    private String address;
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
    public String getAddress() { return address; }
    public void setAddress(String address) { this.address = address; }
    @Override
    public String toString() { return super.toString() + "AccountUser{" +  "username='" + username + '\'' + ", address='" + address + '\'' + '}'; }
}
------------------------------------------------------------------------------
public interface IAccountDao {
    List<Account> findAll();
    List<AccountUser> findAllAccount();
}

JNDI概述和原理

类似于windows的注册表,它实际上是一个Map存储数据,key:存储路径 + 名称,value:是一个Object

MyBatis延迟加载策略

  • 在一对多中,当我们有一个用户,它有100个账户。

    • 在查询用户的时候,要不要把关联的账户查出来?

      在查询用户时,用户下的账户信息应该是,什么时候使用,什么时候查询的。(延迟加载/按需加载/懒加载)

    • 在查询账户的时候,要不要把关联的用户查出来?

      在查询账户时,账户的所属用户信息应该是随着账户查询时一起查询出来。(立即加载)

  • 延迟加载

    在真正使用数据时才发起查询,不用的时候不查询。按需加载(懒加载)

    • 一对,多对:通常情况下我们都是采用延迟加载。
  • 立即加载

    不管用不用,只要一调用方法,马上发起查询。

    • 多对,一对:通常情况下我们都是采用立即加载。
  • 使用Assocation 实现延迟加载

    • 第一步:只查询账户信息的DAO接口
    • 第二步:AccountDao.xml映射文件
    • 第三步:UserDao接口及UserDao.xml映射文件
    • 第四步:开启Mybatis的延迟加载策略
      • 进入Mybaits的官方文档,找到settings的说明信息
      • lazyLoadingEnabled
      • aggressivelazyLoading
    • 第五步:测试加载账户信息同时加载用户信息
<resultMap id="accountUserMap" type="account">
    <id property="id" colume="id"></id>
    <result property="uid" colume="uid"></result>
    <result property="money" colume="money"></result>
    <!-- 一对一的关系映射:配置封装user的内容
	select属性指定的内容:查询用户的唯一标识:
	column属性指定的内容:用户根据id查询时,所需要的参数的值
	-->
    <association property ="user" column="uid" javaType="user" select="com.zimo.dao.IUsenDao.findBylId"></association>

</resultMap>
<!--查询所有-->
<select id="findAll" resultMap="userAccountMap">
    select * from user u left outer join account a on u.id = a.uid
</select>
<!--根据id查询用户 -->
<select id="findById" parameterType="INT"resultType="user">
    select * from user where id = #{uid}
</select>
--------------------------------------------------------------------------
<settings>
    <!--打开延迟加载的开关-->
    <setting name="LazyLoadingEnabled" value="true"/>
    
    <!--将积极加载改为消息加载即按需加载-->
    <setting name="aggressiveLazyLoading" value="false" />
<settings>
  • 一对一配置:使用<resultMap>做配置
  • 一对多配置:使用<resultMap> + <collection>做配置
  • 多对多配置:使用<resultMap> + <collection>做配置(比一对多,多一张中间表)

MyBatis缓存

  • 什么是缓存

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

  • 为什么使用缓存

    减少和数据库的交互次数,提高执行效率。

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

    • 适用于缓存:

      经常查询并且不经常改变的

      数据的正确与否对最终结果影响不大的

    • 不适用于缓存:

      经常改变的数据

      数据的正确与否对最终结果影响很大的。

      例如:商品的库存,银行的汇率,股市的牌价。

  • Mybatis中的一级缓存和二级缓存

    一级缓存是sqlSession范围的缓存,当调用sqlSession的修改,添加,删除,commit(),close()等方法时,就会清空一级缓存。

    • 一级缓存:

      它指的是Mybatis中SqlSession对象的缓存(SqlSession.clearCache()清空缓存时,会再次执行查询)

      当我们执行查询之后,查询的结果会同时存入到SqlSession为我们提供一块区域中

      该区域的结构是一个Map,当我们再次查询同样的数据,mybatis会先去sqlsession中查询是否有,有的话直接拿出来用

      当SqlSession对象消失时,mybatis的一级缓存也就消失了

    • 二级缓存:

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

      • 二级缓存的使用步骤:

        • 第一步:让Mybatis框架支持二级缓存(在SqlMapConfig.xml中配置)

          <settings>
              <setting name="cacheEnabled" value="true"/>
          </settings>
          
        • 第二步:让当前的映射文件支持二级缓存(在IUserDao.xml中配置)

          <!--开启user支持二级缓存-->
          <cache/>
          
        • 第三步:让当前的操作支持二级缓存(在select标签中配置)

          <!--根据id查询用户 -->
          <select id="findById" parameterType="INT"resultType="user" useCache="true">
              select * from user where id = #{uid}
          </select>
          

Mybaits二级缓存

MyBatis注解开发

  • @lnsert:实现新增
  • @Update:实现更新
  • @Delete:实现删除
  • @Select:实现查询
  • @Result:实现结果集封装
  • @Results:可以与@Result一起使用,封装多个结果集
  • @One:实现一对一结果集封装
  • @Many:实现一对多结果集封装
<!--加载映射关系-->
<mappers>
    <package name="com.zimo.dao"></package>
</mappers>
  • 单表注解查询
package com.zimo.dao;
import com.zimo.domain.User;
import com.zimo.mybatis.annotations.Select;
import java.util.List;
/**
 * 用户持久层接口
 * @author Liu_zimo
 * @version v0.1 by 2021/3/30 18:09
 */
public interface IUserDao {
    // 查询所有
    @Select("select * from user")
    List<User> findAll();
    // 保存
    @Insert("insert into user(username,address,sex,birthday)values(#{(username},#{address},#{sex},#{birthday})")
    void saveUser(User user);
    // 更新
    @Update("update user set username=#{username},sex=#{sex},address=#{address},birthday=#{birthday} where id=#{id}")
    void updateUser(User user);
    // 删除
    @Delete("delete from user where id=#{id}")
    void deleteUser(int id);
    // 查询单个用户
    @select("select * from user where id=#{id}")
    User findById(String id);
    // 模糊查询
    @Select("select * from user where username like #{username} ")
    List<User> findUserByName(String username);
    // 查询总用户数量
    @Select("select count(*)from user")
    int findTotalUser();
}
  • 注解映射关系
// 查询所有
@Select("select * from user")
@Results(id="userMap",value={
    @Result(id=true, column="id",property="userId"),
    @Result(column="sex",property="userSex"),
    @Result(column="address",property="userAddress"),
    @Result(column="username",property="userName"),
})
List<User> findAll();

// 保存
@Insert("insert into user(username,address,sex,birthday)values(#{(username},#{address},#{sex},#{birthday})")
@ResultMap(value={"userMap"})
void saveUser(User user);
  • 注解配置

    • 一对一
    @Select("select * from user")
    @Results(id="userMap",value={
        @Result(id=true, column="id",property="userId"),
        @Result(column="sex",property="userSex"),
        @Result(column="address",property="userAddress"),
        @Result(column="username",property="userName"),
        @Result(property="user" column="uid" one=@One(select="com.itheima.dao.IUserDao.findById", fetchType=FetchType.EAGER))
    })
    List<User> findAll();
    
    • 一对多
    @Select("select * from user")
    @Results(id="userMap",value={
        @Result(id=true, column="id",property="userId"),
        @Result(column="sex",property="userSex"),
        @Result(column="address",property="userAddress"),
        @Result(column="username",property="userName"),
        @Result(property="accounts", column="id", 
                many=@Many(select="com.itheima.dao.IAccountDao.findAccountByUid",fetchType=FetchType.LAZY))
    })
    List<User> findAll();
    
    • 一级缓存无需配置
    • 二级缓存
<!--配置开启二级缓存-->
<settings>
    <setting name="cacheEnabled" value="true" />
</settings>
import com.zimo.domain.AccountUser;
import java.util.List;
@CacheNamespace(blocking=true)
public interface IAccountDao {
    List<Account> findAll();
    List<AccountUser> findAllAccount();
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柳子陌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值