⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 jdbccontext.java

📁  EasyDBO是一个超轻量级对象-关系映射(Object/Relation Mapping
💻 JAVA
字号:
package com.easyjf.dbo;

import java.sql.*;
import javax.sql.*;
import org.apache.log4j.*;


/**
 * @author wangliang138840
 *
 */
public class JDBCContext{
	private static Logger logger = Logger.getLogger(JDBCContext.class);
	private DataSource ds;
	protected Connection connection;
	private boolean isValid = true;
	private static ThreadLocal jdbcContext;
	/**
	 * @param ds
	 */
	private JDBCContext(DataSource ds){
		this.ds = ds;
		createConnection();		
	}
	public static JDBCContext getJdbcContext(javax.sql.DataSource ds)
	{		
		if(jdbcContext==null)jdbcContext=new JDBCContextThreadLocal(ds);
		JDBCContext context = (JDBCContext) jdbcContext.get();
		if (context == null) {
			context = new JDBCContext(ds);
		}
		return context;
	}
	/**
	 * 
	 */
	private void createConnection(){
		try{
			if(connection == null || connection.isClosed() == true){
				logger.debug("Create a connection");
				if(ds != null){
					connection = ds.getConnection();
					isValid = true;
				}
				else{
					logger.error("DataSource is invalid");
					isValid = false;
					return;
				}
			}else{
				logger.debug("The current connection is valid.");
			}
		}catch(SQLException e){
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 释放当前连接;
	 */
	public void releaseConnection(){
		try{
			if(connection != null && connection.isClosed() == false){
				connection.close();
				isValid = false;
				logger.debug("The connection is closed.");
			}
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
	
	/**
	 * @return
	 */
	public Connection getConnection(){
		logger.debug("Get a Connection!");
		try{
		if(connection==null || connection.isClosed())createConnection();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return connection;
	}
	/**
	 * @return
	 */
	public boolean isValid(){
		return isValid;
	}
	private static class JDBCContextThreadLocal extends ThreadLocal {
		public javax.sql.DataSource ds;
		public JDBCContextThreadLocal(javax.sql.DataSource ds)
		{
			this.ds=ds;
		}
		protected synchronized Object initialValue() {
			return new JDBCContext(ds);
		}
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -