标签:
sessionfactory的目的:产生session,维护数据库连接池
测试文件里的sessionfactory创建数据库连接,所以sessionFactory通过配置文件里的配置信息产生一个数据库连接池, 从中取出一个数据库连接.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
configure用于调用数据库信息, configure()里面可以指定hibernate.cfg.xml的名字
用getCurrentSession产生一个session:
@Test
public void testTeacherSave() {
Teacher t = new Teacher();
t.setName("t1");
t.setTitle("middle");
t.setBirthDate(new Date());
//Session session = sessionFactory.openSession();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(t);
Session session2 = sessionFactory.getCurrentSession();
System.out.println(session == session2);
session.getTransaction().commit();
Session session3 = sessionFactory.getCurrentSession();
System.out.println(session == session3);
}
openSession() 永远是创建一个新的session, 此session需要close, 而getCurrentSession()如果环境中有session就拿环境中的, 不需要close.
hibernate--coreapi--configuration sessionfactory--getcurrentsession--opensession
标签:
原文地址:http://www.cnblogs.com/wujixing/p/5414109.html