zoukankan      html  css  js  c++  java
  • spring-获取连接的工具类

     1 package learnFromBilibili.util;
     2 
     3 import javax.sql.DataSource;
     4 import java.sql.Connection;
     5 import java.sql.SQLException;
     6 
     7 /**
     8  * 连接的工具类,用于从数据源中获取一个连接,并且实现和线程的绑定
     9  * @author tony fan
    10  */
    11 public class ConnectionUtils {
    12 
    13     private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
    14 
    15     private DataSource dataSource;
    16 
    17     public void setDataSource(DataSource dataSource) {
    18         this.dataSource = dataSource;
    19     }
    20 
    21     /**
    22      * 获取当前线程上的连接
    23      */
    24     public Connection getThreadConnection(){
    25         try {
    26             // 1、先从ThreadLocal上获取
    27             Connection conn = threadLocal.get();
    28             // 2、判断当前线程上是否有连接
    29             if(conn == null){
    30                 // 3、从数据源中获取一个连接,并且存入ThreadLocal中
    31                 conn = dataSource.getConnection();
    32                 threadLocal.set(conn);
    33             }
    34             // 4、返回当前线程上的连接
    35             return conn;
    36         } catch (SQLException e) {
    37             throw new RuntimeException();
    38         }
    39     }
    40 
    41     /**
    42      * 把连接和线程解绑
    43      */
    44     public void removeConnection(){
    45         threadLocal.remove();
    46     }
    47     
    48 }
  • 相关阅读:
    lntelliJ IDEA 皮肤设置
    Maven安装与配置
    lntelliJ IDEA 使用 Maven 与 每次新建项目都需要重新配置的解决方案
    Spring Boot 扫描机制说明
    Spring Boot Filter 使用指南
    Gradle构建CAS4.2.7爬坑指南
    Java的垃圾回收
    final与static
    angular directive自定义指令
    ui-router
  • 原文地址:https://www.cnblogs.com/fxw-learning/p/13618543.html
Copyright © 2011-2022 走看看