mybatis与数据库访问相关的配置以及设计

<p style="text-align: center"><span style="font-size: 16px">mybatis与数据库访问相关的配置以及设计


<p style="text-align: left"><span style="font-size: 16px">mybatis不管如何NB,总是要与数据库进行打交道。通过提问的方式,逐步深入

                                                       

    2.对于有连接池的数据源,和无连接池的数据源,我们自己会如何设计?

      流程上的区别

                                                

     职责上区别

                                  

    现在解开谜底:看实际Mybatis设计如何?

      非池化类:

                      

看下最关键的,获得数据库连接,和我们自己写的没啥区别。简单粗暴

Connection doGetConnection(Properties properties) =

    

    池化类:

    

    池化工作分配  :

                

  至此,MYBABTIS对于数据源的创建以及管理结束!看下代码,池化获得连接的代码

Connection getConnection()

<div class="cnblogs_code">

 (conn == ) { 
            </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt;只有有连接还回来,再走这里</span>
    <span style="color: #0000ff"&gt;if</span> (!<span style="color: #000000"&gt;state.idleConnections.isEmpty()) {
      </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; Pool has available connection</span>
      conn = state.idleConnections.remove(0<span style="color: #000000"&gt;);
      </span><span style="color: #0000ff"&gt;if</span><span style="color: #000000"&gt; (log.isDebugEnabled()) {
        log.debug(</span>"Checked out connection " + conn.getRealHashCode() + " from pool."<span style="color: #000000"&gt;);
      }
    } </span><span style="color: #0000ff"&gt;else</span><span style="color: #000000"&gt; {

    </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt;有两种可能:1种,都在使用中,池子没满,再新建
      </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; Pool does not have available connection</span>
      <span style="color: #0000ff"&gt;if</span> (state.activeConnections.size() <<span style="color: #000000"&gt; poolMaximumActiveConnections) {
        </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; Can create new connection

        </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt;新建连接</span>
        conn = <span style="color: #0000ff"&gt;new</span> PooledConnection(dataSource.getConnection(),<span style="color: #0000ff"&gt;this</span><span style="color: #000000"&gt;);
        </span><span style="color: #0000ff"&gt;if</span><span style="color: #000000"&gt; (log.isDebugEnabled()) {
          log.debug(</span>"Created connection " + conn.getRealHashCode() + "."<span style="color: #000000"&gt;);
        }
      } </span><span style="color: #0000ff"&gt;else</span><span style="color: #000000"&gt; {
        </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; Cannot create new connection

        </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt;找一个最老的,用的ArrayList,老的在ArrayList数组的前面</span>
        PooledConnection oldestActiveConnection = state.activeConnections.get(0<span style="color: #000000"&gt;);
        </span><span style="color: #0000ff"&gt;long</span> longestCheckoutTime =<span style="color: #000000"&gt; oldestActiveConnection.getCheckoutTime();

        </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt;借出超时,不让他做了,直接rollback。。。暴力</span>
        <span style="color: #0000ff"&gt;if</span> (longestCheckoutTime ><span style="color: #000000"&gt; poolMaximumCheckoutTime) {
          </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; Can claim overdue connection</span>
          state.claimedOverdueConnectionCount++<span style="color: #000000"&gt;;
          state.accumulatedCheckoutTimeOfOverdueConnections </span>+=<span style="color: #000000"&gt; longestCheckoutTime;
          state.accumulatedCheckoutTime </span>+=<span style="color: #000000"&gt; longestCheckoutTime;
          state.activeConnections.remove(oldestActiveConnection);
          </span><span style="color: #0000ff"&gt;if</span> (!<span style="color: #000000"&gt;oldestActiveConnection.getRealConnection().getAutoCommit()) {
            </span><span style="color: #0000ff"&gt;try</span><span style="color: #000000"&gt; {
              oldestActiveConnection.getRealConnection().rollback();
            } </span><span style="color: #0000ff"&gt;catch</span><span style="color: #000000"&gt; (SQLException e) {
              </span><span style="color: #008000"&gt;/*</span><span style="color: #008000"&gt;
                 Just log a message for debug and continue to execute the following
                 statement like nothing happend.
                 Wrap the bad connection with a new PooledConnection,this will help
                 to not intterupt current executing thread and give current thread a
                 chance to join the next competion for another valid/good database
                 connection. At the end of this loop,bad {@link @conn} will be set as null.
               </span><span style="color: #008000"&gt;*/</span><span style="color: #000000"&gt;
              log.debug(</span>"Bad connection. Could not roll back"<span style="color: #000000"&gt;);
            }  
          }

          </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt;拿回来后,不再放到原有的PooledConnection,新建立一个。从新开始.老的REAL connection还被oldestActiveConnection引用,不会内存溢出?</span>
          conn = <span style="color: #0000ff"&gt;new</span> PooledConnection(oldestActiveConnection.getRealConnection(),<span style="color: #0000ff"&gt;this</span><span style="color: #000000"&gt;);
          conn.setCreatedTimestamp(oldestActiveConnection.getCreatedTimestamp());
          conn.setLastUsedTimestamp(oldestActiveConnection.getLastUsedTimestamp());

          oldestActiveConnection.invalidate();
          </span><span style="color: #0000ff"&gt;if</span><span style="color: #000000"&gt; (log.isDebugEnabled()) {
            log.debug(</span>"Claimed overdue connection " + conn.getRealHashCode() + "."<span style="color: #000000"&gt;);
          }
        } </span><span style="color: #0000ff"&gt;else</span><span style="color: #000000"&gt; {
          </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; Must wait

            </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt;大家都在用着,你只能等着了。</span>
          <span style="color: #0000ff"&gt;try</span><span style="color: #000000"&gt; {
            </span><span style="color: #0000ff"&gt;if</span> (!<span style="color: #000000"&gt;countedWait) {
              state.hadToWaitCount</span>++<span style="color: #000000"&gt;;
              countedWait </span>= <span style="color: #0000ff"&gt;true</span><span style="color: #000000"&gt;;
            }
            </span><span style="color: #0000ff"&gt;if</span><span style="color: #000000"&gt; (log.isDebugEnabled()) {
              log.debug(</span>"Waiting as long as " + poolTimeToWait + " milliseconds for connection."<span style="color: #000000"&gt;);
            }
            </span><span style="color: #0000ff"&gt;long</span> wt =<span style="color: #000000"&gt; System.currentTimeMillis();
            state.wait(poolTimeToWait);
            state.accumulatedWaitTime </span>+= System.currentTimeMillis() -<span style="color: #000000"&gt; wt;
          } </span><span style="color: #0000ff"&gt;catch</span><span style="color: #000000"&gt; (InterruptedException e) {
            </span><span style="color: #0000ff"&gt;break</span><span style="color: #000000"&gt;;
          }
        }
      }
    }
    </span><span style="color: #0000ff"&gt;if</span> (conn != <span style="color: #0000ff"&gt;null</span><span style="color: #000000"&gt;) {
      </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt; ping to server and check the connection is valid or not</span>
      <span style="color: #0000ff"&gt;if</span><span style="color: #000000"&gt; (conn.isValid()) {
        </span><span style="color: #0000ff"&gt;if</span> (!<span style="color: #000000"&gt;conn.getRealConnection().getAutoCommit()) {
          conn.getRealConnection().rollback();
        }
        conn.setConnectionTypeCode(assembleConnectionTypeCode(dataSource.getUrl(),username,password));
        conn.setCheckoutTimestamp(System.currentTimeMillis());
        conn.setLastUsedTimestamp(System.currentTimeMillis());
        state.activeConnections.add(conn);
        state.requestCount</span>++<span style="color: #000000"&gt;;
        state.accumulatedRequestTime </span>+= System.currentTimeMillis() -<span style="color: #000000"&gt; t;
      } </span><span style="color: #0000ff"&gt;else</span><span style="color: #000000"&gt; {
        </span><span style="color: #0000ff"&gt;if</span><span style="color: #000000"&gt; (log.isDebugEnabled()) {
          log.debug(</span>"A bad connection (" + conn.getRealHashCode() + ") was returned from the pool,getting another connection."<span style="color: #000000"&gt;);
        }
        state.badConnectionCount</span>++<span style="color: #000000"&gt;;
        localBadConnectionCount</span>++<span style="color: #000000"&gt;;
        conn </span>= <span style="color: #0000ff"&gt;null</span><span style="color: #000000"&gt;;

        </span><span style="color: #008000"&gt;//</span><span style="color: #008000"&gt;如果累计有这些个链接失效了,则报个异常.</span>
        <span style="color: #0000ff"&gt;if</span> (localBadConnectionCount > (poolMaximumIdleConnections +<span style="color: #000000"&gt; poolMaximumLocalBadConnectionTolerance)) {
          </span><span style="color: #0000ff"&gt;if</span><span style="color: #000000"&gt; (log.isDebugEnabled()) {
            log.debug(</span>"PooledDataSource: Could not get a good connection to the database."<span style="color: #000000"&gt;);
          }
          </span><span style="color: #0000ff"&gt;throw</span> <span style="color: #0000ff"&gt;new</span> SQLException("PooledDataSource: Could not get a good connection to the database."<span style="color: #000000"&gt;);
        }
      }
    }
  }

}</span></pre>

<p style="text-align: left">        


<p style="text-align: left">    

  

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


1.pom.xml引入依赖 &lt;dependency&gt; &lt;groupId&gt;com.github.pagehelper&lt;/groupId&gt; &lt;artifactId&gt;pagehelper&lt;/artifactId&gt; &lt;version&gt;5
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt; &lt;!DOCTYPE configuration PUBLIC &quot;-//mybatis.org//DTD Config 3.0//EN&quot; &qu
准备工作 ① 创建数据库&amp;数据表 ## 创建数据库 CREATE DATABASE `dbtest1`; ## 创建数据表 CREATE TABLE `t_user` ( `id` INT NOT NULL AUTO_INCREMENT, `username` VARCHAR(20) DEF
MyBatis逆向工程是指根据数据库表结构自动生成对应的实体类、Mapper接口以及SQL映射文件的过程。这个过程可以通过MyBatis提供的逆向工程工具来完成,极大地方便了开发人员,避免了重复的代码编写,提高了开发效率。 创建逆向工程的步骤 1、添加依赖&amp;插件 &lt;!-- 控制Mave
MyBatis获取参数值的两种方式:${}和#{} ${}的本质就是字符串拼接,#{}的本质就是占位符赋值。 ${}使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号;但是#{}使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,可以自
resultMap作用是处理数据表中字段与java实体类中属性的映射关系。 准备工作 ① 创建数据库&amp;数据表 CREATE DATABASE `dbtest1`; CREATE TABLE `t_emp` ( `emp_id` int NOT NULL AUTO_INCREMENT, `em
EHCache缓存针对于MyBatis的二级缓存。 MyBatis默认二级缓存是SqlSessionFactory级别的。 添加依赖 &lt;!-- MyBatis-EHCache整合包 --&gt; &lt;dependency&gt; &lt;groupId&gt;org.mybatis.cac
MyBatis 提供了一级缓存和二级缓存的支持,用于提高数据库查询的性能,减少不必要的数据库访问。 一级缓存(SqlSession 级别的缓存) 一级缓存是 MyBatis 中最细粒度的缓存,也称为本地缓存。它存在于每个 SqlSession 的生命周期中,当 SqlSession 被关闭或清空时,
动态SQL是 MyBatis 中非常强大且灵活的功能,允许你根据不同的条件构建SQL查询。 这主要通过 &lt;if&gt;、&lt;choose&gt;、&lt;when&gt;、&lt;otherwise&gt;、&lt;foreach&gt;等标签实现。 查询场景 /** * 根据条件查询员工
本教程操作系统:windows10系统、DELL G3电脑。 MyBatis 是一个优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。在 MyBatis 中,配置数据库连接是非常重要的第一步。下面将详细介绍如何配置 MyBatis 的
今天小编给大家分享的是MyBatis批量查询、插入、更新、删除如何实现,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧。
今天小编给大家分享的是Mybatis操作多数据源实现的方法,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧。一定会有所收获...
本篇文章和大家了解一下mybatis集成到spring的方式有哪些。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。1 前言1.1 集成spring前使用mybat...
今天小编给大家分享的是mybatis-plus分页查询的3种方法,相信很多人都不太了解,为了让大家更加了解,所以给大家总结了以下内容,一起往下看吧。一定会有所收获...
本篇内容主要讲解“mybatis之BaseTypeHandler怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“mybatis...
这篇文章主要介绍了mybatisforeach怎么传两个参数的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇mybatisforeach怎...
这篇“MyBatis映射文件中parameterType与resultType怎么使用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的...
这篇文章主要介绍“MyBatis怎么获取自动生成的键值”,在日常操作中,相信很多人在MyBatis怎么获取自动生成的键值问题上存在疑惑,小编查阅了各式资料,整理出
这篇文章主要讲解了“怎么去掉IntelliJIDEA中mybatis对应的xml文件警告”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入...
这篇文章主要介绍“MybatisPlus使用@TableId主键id自增长无效如何解决”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这...