mybatis连接池和多表操作实现分析3

mybatis连接池实现分析

mybatis数据源分类
 <!-- 配置连接数据库的信息:用的是数据源(连接池) -->
            <dataSource type="POOLED">
                <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>
  • 可以看出 Mybatis 将它自己的数据源分为三类:
    • type=”POOLED”:MyBatis 会创建 PooledDataSource 实例(使用连接池的数据源,创建新连接的时候使用的就是UnpooledDataSource)
    • type=”UNPOOLED” : MyBatis 会创建UnpooledDataSource 实例POOLED (不使用连接池的数据源,有连接就创建一个新连接)
    • JNDI 使用 JNDI 实现的数据源
      如下图
      在这里插入图片描述
PooledDataSource分析

mybatis连接池源码逻辑在PooledDataSource类中的popConnection
方法
代码如下

// 从连接池中获取连接
  private PooledConnection popConnection(String username, String password) throws SQLException {
    // 等待的个数
    boolean countedWait = false;
    // PooledConnection 对象
    PooledConnection conn = null;
    long t = System.currentTimeMillis();
    // 无效的连接个数
    int localBadConnectionCount = 0;

    while (conn == null) {
      synchronized (state) {
        // 检测是否还有空闲的连接
        if (!state.idleConnections.isEmpty()) {
          // 连接池中还有空闲的连接,则直接获取连接返回
          conn = state.idleConnections.remove(0);
        } else {
          // 连接池中已经没有空闲连接了
          if (state.activeConnections.size() < poolMaximumActiveConnections) {
            // 活跃的连接数没有达到最大值,则创建一个新的数据库连接
            conn = new PooledConnection(dataSource.getConnection(), this);
          } else {
            // 如果活跃的连接数已经达到允许的最大值了,则不能创建新的数据库连接
            // 获取最先创建的那个活跃的连接
            PooledConnection oldestActiveConnection = state.activeConnections.get(0);
            long longestCheckoutTime = oldestActiveConnection.getCheckoutTime();
            // 检测该连接是否超时
            if (longestCheckoutTime > poolMaximumCheckoutTime) {
              // 如果该连接超时,则进行相应的统计
              state.claimedOverdueConnectionCount++;
              state.accumulatedCheckoutTimeOfOverdueConnections += longestCheckoutTime;
              state.accumulatedCheckoutTime += longestCheckoutTime;
              // 将超时连接移出 activeConnections 集合
              state.activeConnections.remove(oldestActiveConnection);
              if (!oldestActiveConnection.getRealConnection().getAutoCommit()) {
                  // 如果超时未提交,则自动回滚
                  oldestActiveConnection.getRealConnection().rollback();
              }
              // 创建新的 PooledConnection 对象,但是真正的数据库连接并没有创建
              conn = new PooledConnection(oldestActiveConnection.getRealConnection(), this);
              conn.setCreatedTimestamp(oldestActiveConnection.getCreatedTimestamp());
              conn.setLastUsedTimestamp(oldestActiveConnection.getLastUsedTimestamp());
              // 设置该超时的连接为无效
              oldestActiveConnection.invalidate();
            } else {
               // 如果无空闲连接,无法创建新的连接且无超时连接,则只能阻塞等待
              // Must wait
              try {
                if (!countedWait) {
                  state.hadToWaitCount++; // 等待次数
                  countedWait = true;
                }
                long wt = System.currentTimeMillis();
                // 阻塞等待
                state.wait(poolTimeToWait);
                state.accumulatedWaitTime += System.currentTimeMillis() - wt;
              } catch (InterruptedException e) {
                break;
              }
            }
          }
        }
        // 已经获取到连接
        if (conn != null) {
          if (conn.isValid()) {
            // 如果连连接有效,事务未提交则回滚
            if (!conn.getRealConnection().getAutoCommit()) {
              conn.getRealConnection().rollback();
            }
            // 设置 PooledConnection 相关属性
            conn.setConnectionTypeCode(assembleConnectionTypeCode(dataSource.getUrl(), username, password));
            conn.setCheckoutTimestamp(System.currentTimeMillis());
            conn.setLastUsedTimestamp(System.currentTimeMillis());
            // 把连接加入到活跃集合中去
            state.activeConnections.add(conn);
            state.requestCount++;
            state.accumulatedRequestTime += System.currentTimeMillis() - t;
          } else {
            // 无效连接
            state.badConnectionCount++;
            localBadConnectionCount++;
            conn = null;
          }
        }
      }
    }
    return conn;
  }

代码分析如下图
在这里插入图片描述
图片分析如下:

  1. 判断连接池是否还有空闲的连接
    1. 如果连接池中还有空闲的连接,则直接获取连接返回

    2. 如果没有则判断活跃的连接数有没有达到最大值

      3.1 如果没有则创建一个新的数据库连接,如果新建的连接无效则抛出异常,有效则放进连接池中

      3.2 如果有的话不能创建连接了这时候则获取最先创建的那个活跃的连接判断该连接是否超时,
      3.2.1. 如果超时则移出连接后继续3.1步骤(创建新连接)
      3.2.2. 如果无空闲连接,无法创建新的连接且无超时连接,则只能阻塞等

Mybatis的动态SQL语句

我们根据实体类的不同取值,使用不同的 SQL 语句来进行查询。比如在 id 如果不为空时可以根据 id 查询,如果 username 不同空时还要加入用户名作为条件。这种情况在我们的多条件组合查询中经常会碰到

  1. 动态 SQL 之 if 标签
    IUserDao.java
    List<User> findByUser(User user);

IUserDao.xml

    <select id="findByUser" resultType="org.example.User" parameterType="org.example.User">
        select * from user where 1=1
        <if test="username!=null and username != '' ">
            and username like #{username}
        </if>
        <if test="address != null">
             and address like #{address}
        </if>

    </select>

或者用where标签代替where 1=1

 	<select id="findByUser" resultType="org.example.User" parameterType="org.example.User">
        select * from user
        <where>
            <if test="username!=null and username != '' ">
                and username like #{username}
            </if>
            <if test="address != null">
                and address like #{address}
            </if>
        </where>
    </select>

注意:标签的 test 属性中写的是对象的属性名,如果是包装类的对象要使用 OGNL 表达式的写法。
另外要注意 where 1=1 的作用

测试

 @Test
    public void testFindByUser()throws Exception {
        User userTemp=new User();
        userTemp.setUsername("%王%");
        userTemp.setAddress("%燕%");
        //6.使用代理对象执行查询所有方法
        List<User> users= iUserDao.findByUser(userTemp);
        for (User user:users){
            System.out.println(user);
        }

    }
  1. 动态 SQL 之foreach 标签

查询条件QueryVo .java

package org.example;

import java.io.Serializable;
import java.util.List;

public class QueryVo implements Serializable {
    private List<Integer> ids;

    public List<Integer> getIds() {
        return ids;
    }

    public void setIds(List<Integer> ids) {
        this.ids = ids;
    }


}

IUserDao.java

List<User> findInIds(QueryVo vo);

持久层 Dao 映射配置IUserDao.xml

    <!-- 抽取重复的sql语句-->
    <sql id="defaultSql">
        select * from user
    </sql>

    <select id="findInIds" resultType="org.example.User" parameterType="org.example.QueryVo">
    <!-- select * from user where id in (x,x,x,x); -->
        <include refid="defaultSql"></include>
        <where>
           <foreach collection="ids" open="id in(" close=")" item="uid" separator=",">
               #{uid}
           </foreach>
        </where>
    </select>
    SQL 语句:
    select 字段 from user where id in (?)
    <foreach>标签用于遍历集合,它的属性:
    collection:代表要遍历的集合元素,注意编写时不要写#{}
    open:代表语句的开始部分
    close:代表结束部分
    item:代表遍历集合的每个元素,生成的变量名
    sperator:代表分隔符

测试

public void testFindInIds()throws Exception {
        QueryVo queryVo=new QueryVo();
        List<Integer> ids=new ArrayList<Integer>();
        ids.add(45);
        ids.add(46);
        ids.add(48);
        queryVo.setIds(ids);
        //6.使用代理对象执行查询所有方法
        List<User> users= iUserDao.findInIds(queryVo);
        for (User user:users){
            System.out.println(user);
        }

    }

Mybatis的多表查询

1对1查询

查询所有账户信息,关联查询下单用户信息

方式一:
定义Account实体类

package org.example;

import java.io.Serializable;

public class Account implements Serializable {
    private Integer id;
    private Integer uid;
    private Double money;
    //从表实体应该包含一个主表实体的对象引用
    private User myUser;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    public User getMyUser() {
        return myUser;
    }

    public void setMyUser(User myUser) {
        this.myUser = myUser;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", uid=" + uid +
                ", money=" + money +
                ", username=" + myUser.getUsername() +
                ", address=" + myUser.getAddress() +
                '}';
    }
}

定义接口IAccountDao.java

package dao;

import org.example.Account;
import org.example.AccountUser;

import java.util.List;

public interface IAccountDao {
    //List<AccountUser> findAll();
    List<Account> findAllAccount();
}

定义 AccountDao.xml 文件中的查询配置信息
因为我配置了别名所以在AccountDao.xml 不需要写全限定类名

    <!-- 建立对应关系 -->
    <resultMap type="Account" id="accountMap">
        <id column="aid" property="id"/>
        <result column="uid" property="uid"/>
        <result column="money" property="money"/>
        <!-- 它是用于指定从表方的引用实体属性的 property是Account实体类型中对应的属性 -->
        <association property="myUser" javaType="User">
            <id column="id" property="id"/>
            <result column="username" property="username"/>
            <result column="sex" property="sex"/>
            <result column="birthday" property="birthday"/>
            <result column="address" property="address"/>
        </association>
    </resultMap>

    <!-- 配置查询所有操作-->
    <select id="findAllAccount" resultMap="accountMap">
        select u.*,a.id as aid,a.uid,a.money from account a,user u where a.uid =u.id;
    </select>

测试类

@Test
    public void testFindAllAccount()throws Exception {
        List<Account> accountUsers=iAccountDao.findAllAccount();
        for (Account accountUser:accountUsers){
            System.out.println(accountUser);
        }

    }

方式二:
定义一个实体类AccountUser来对应你需要查询的两张表需要的字段

package org.example;

import java.io.Serializable;

public class AccountUser extends Account implements Serializable {
    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<AccountUser> findAll();
   
}

重新定义 AccountDao.xml 文件

<!-- 配置查询所有操作-->
    <select id="findAll" resultType="AccountUser">
        select a.*,u.username,u.address from account a,user u where a.uid =u.id;
    </select>

测试

 @Test
    public void testFindAll()throws Exception {
        List<AccountUser> accountUsers=iAccountDao.findAll();
        for (AccountUser accountUser:accountUsers){
            System.out.println(accountUser);
        }
    }
1对多查询

查询所有用户信息及用户关联的账户信息

 User 类 加入 List<Account>
 package org.example;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

public class User implements Serializable {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    private List<Account> accounts;

    public List<Account> getAccounts() {
        return accounts;
    }

    public void setAccounts(List<Account> accounts) {
        this.accounts = accounts;
    }



    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }

}

用户持久层 Dao 接口 中加入查询方法

public interface IUserDao {
    /**
     * 查询所有用户
     */
    List<User> findAll();
}

用户持久层 Dao 映射文件 配置

collection
部分定义了用户关联的账户信息。表示关联查询结果集
property="accList" :
关联查询的结果集存储在 User 对象的上哪个属性。
ofType="account" :
指定关联查询的结果集中的对象类型即List中的对象类型。此处可以使用别名,也可以使用全限定名

 <resultMap type="User" id="userMap">
        <id column="id" property="id"></id>
        <result column="username" property="username"/>
        <result column="address" property="address"/>
        <result column="sex" property="sex"/>
        <result column="birthday" property="birthday"/>
        <!-- collection 是用于建立一对多中集合属性的对应关系
        ofType 用于指定集合元素的数据类型
        -->
        <collection property="accounts" ofType="account">
            <id column="aid" property="id"/>
            <result column="uid" property="uid"/>
            <result column="money" property="money"/>
        </collection>
    </resultMap>

    <!-- 配置查询所有操作 -->
    <select id="findAll" resultMap="userMap">
        select u.*,a.id as aid ,a.uid,a.money from user u left outer join account
        a on u.id =a.uid
    </select>

测试方法

@Test
    public void testFindAll()throws Exception {
        List<User> users=iUserDao.findAll();
       for (User user:users){
           System.out.println("-------每个用户的信息---------");
           System.out.println(user);
           System.out.println(user.getAccounts());

       }

    }
Mybatis 多 表查询之 多 对多

编写角色实体类Role

package org.example;

import java.io.Serializable;
import java.util.List;

public class Role implements Serializable {

    private Integer roleId;
    private String roleName;
    private String roleDesc;

    //多对多的关系映射:一个角色可以赋予多个用户
    private List<User> users;

    public Integer getRoleId() {
        return roleId;
    }

    public void setRoleId(Integer roleId) {
        this.roleId = roleId;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public List<User> getUsers() {
        return users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    public String getRoleDesc() {
        return roleDesc;
    }

    public void setRoleDesc(String roleDesc) {
        this.roleDesc = roleDesc;
    }

    @Override
    public String toString() {
        return "Role{" +
                "roleId=" + roleId +
                ", roleName='" + roleName + '\'' +
                ", roleDesc='" + roleDesc + '\'' +
                '}';
    }

}

编写 Role 持久层 接口

package dao;

import org.example.Role;

import java.util.List;

public interface IRoleDao {
    List<Role> findAll();
}

编写映射文件

<?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="dao.IRoleDao">
    <!--定义 role 表的 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 column="id" property="id"></id>
            <result column="username" property="username"></result>
            <result column="address" property="address"></result>
            <result column="sex" property="sex"></result>
            <result column="birthday" property="birthday"></result>
        </collection>
    </resultMap>

    <!--查询所有-->
    <select id="findAll" resultMap="roleMap">
        select u.*,r.id as rid,r.role_name,r.role_desc from role r
        left outer join user_role ur on r.id = ur.rid
        left outer join user u on u.id = ur.uid
    </select>
</mapper>

测试

@Test
    public void testFindAll()throws Exception {
        List<Role> roles=iRoleDao.findAll();
       for (Role role:roles){
           System.out.println("-------每个角色的信息---------");
           System.out.println(role);
           System.out.println(role.getUsers());
       }

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值