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

📄 hibernate2session.java

📁 关于HEBERNATE使用的一个简单例子
💻 JAVA
字号:
package dbdemo;

import java.sql.Connection;
import java.sql.SQLException;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;

import org.apache.log4j.Logger;

/**
 * @author MEagle
 * 
 * This is for Hibernate version 2.x
 *
 * Hibernate is designed to be useable in any kind of Java application, 
 * including applications that make extensive use of multithreading. So, 
 * unlike the ODMG API, Hibernate's native API does not use the current 
 * thread to maintain associations between Session and Transaction or 
 * between Session and application thread. This can be inconvenient for 
 * J2EE applications where access to a Session instance is always from 
 * a particular thread. It is particularly inconvenient when using a DAO 
 * pattern, when the different DAO classes need to obtain the (same) 
 * current session.
 * 
 * 
 * A thread-local variable effectively provides a separate copy of its 
 * value for each thread that uses it. Each thread can see only the value 
 * associated with that thread, and is unaware that other threads may be 
 * using or modifying their own copies.
 */
public class Hibernate2Session {

	// Add a Log4J logger
	static Logger log = Logger.getLogger(Hibernate2Session.class.getName());

	static Configuration cfg = null;
	static SessionFactory sf = null;

	static {
		try {
			init();
		} catch (Exception e) {
			log.error("could not init " + e.getMessage());
		}
	}

	/**
	 * Make this class a singleton
	 */
	private Hibernate2Session() {
		super();
	}

	public static final ThreadLocal local = new ThreadLocal();

	/**
	 * Retrieve the current Hibernate Session object via the ThreadLocal
	 * class.
	 * 
	 * @return Session
	 * @throws PortalException
	 * 
	 */
	public static Session currentSession() throws Exception {

		Session session = (Session) local.get();
		if (session == null) {

			Connection con = null;

			// create a datasource object
			if (sf == null) {
				init();
			}

			try {
				// Get a connnection from a pool
				// Provide your own implemenation for DatasourceFactory
				// to get a connection
				con = DatasourceFactory.getConnection();

				// create a session object to the database
				session = sf.openSession(con);

			} catch (SQLException sqle) {
				log.error("SQLException: " + sqle.getMessage());
				throw new Exception("SQLException: " + sqle.getMessage());
			}
			local.set(session);
		}

		return session;
	}

	/**
	 * Close the Hibernate Session and any underlying Connection
	 * for further cleanup
	 * 
	 * @param uc - the user's container object stored in the session
	 * @return String - the hashcode of the session object that was closed
	 * 					for debug purposes		
	 * @throws HibernateException, SQLException
	 */
	public static String closeSession()
		throws HibernateException, SQLException {
		Connection con = null;

		Session session = (Session) local.get();

		String sessionHashCode = session.toString();

		local.set(null);
		if (session != null) {
			con = session.close();
		}

		if (con != null) {
			con.close();
		}

		return sessionHashCode;
	}

	private static synchronized void init() throws Exception {

		if (sf != null) {
			// check again because more than 1 user might be
			// trying to do this at the same time.  just return.
			return;
		}

		cfg = null;

		try {

			cfg =
				new Configuration()
					.addClass(User.class)
					.addClass(Contact.class)
					.addClass(Book.class)
					.addClass(Address.class);

			sf = cfg.buildSessionFactory();
			log.info("HibernateSession Initialized SessionFactory=" + sf);
		} catch (Exception e) {
			log.error(
				"Could not intialize Hibernate session factory. "
					+ e.getMessage());
			throw new Exception(
				"Could not intialize Hibernate session factory. "
					+ e.getMessage());
		}
	}
}

⌨️ 快捷键说明

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