`
Tracylau
  • 浏览: 65072 次
  • 性别: Icon_minigender_2
社区版块
存档分类
最新评论

笔记4hibernate

阅读更多
SessionFactory 负责一个数据库,也只对应一个XML 配置文件(hibernate.cfg.xml)。要确保SessionFactory只创建一次.
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.*;
import java.util.*;
import java.io.File;
public class HibernateUtil {
	private static final SessionFactory sessionFactory;
	static {
		try {
			// Create the SessionFactory
			Configuration config = new Configuration();.configure();;
			sessionFactory =config.buildSessionFactory();;
		} catch (HibernateException ex); {
			throw new RuntimeException(
				"Configuration problem: " + ex.getMessage();,
				ex);;
		}
	}
	public static final ThreadLocal session = new ThreadLocal();;
	public static Session currentSession(); throws HibernateException {
		Session s = (Session); session.get();;
		// Open a new Session, if this Thread has none yet
		if (s == null); {
			s = sessionFactory.openSession();;
			session.set(s);;
		}
		return s;
	}
	public static void closeSession(); throws HibernateException {
		Session s = (Session); session.get();;
		session.set(null);;
		if (s != null);
			s.close();;
	}
}

Session 不是线程安全的,代表与数据库之间的一次操作。Session 通过SessionFactory 打开,在所有的工作完成后,需要关闭.
在Session 中,每个数据库操作都是在一个事务(transaction)中进行的,这样就可以隔离开不同的操作(甚至包括只读操作)。我们使用Hibernate 的Transaction API 来从底层的事务策略中(本例中是JDBC 事务)脱身。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics