核心开发接口(一)

1.Configuration

  进行配置信息的管理

  用来产生SessionFactory

  可以在configure方法中指定hibernate配置文件

  只需要关注一个方法即:buildSessionFactory()

2.SessionFactory

  管理连接池

  用来产生Session,没产生一个session,就给它一个数据库连接

  Session session = sessionFactory.openSession();与Session session = sessionFactory.getCurrentSession();的区别

openSession永远是创建新的Session,使用它的时候要用session.close();

getCurrentSession()如果当前环境中有了session,就会拿当前环境的session,在这个session没有提交之前,无论拿多少个,都是同一个,一旦提交,再拿,就是新的了。用途是界定事务边界,事务提交时会自动colse()。什么叫上下文,上下文是在hibernate配置里面指定的current_session_context_class。所以使用这个方法的时候配置文件里要写<!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>看API文档,thread可以换成别的三个值,但thread比较长用。

package hjj.lch.hibernate.model;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class HibernateCoreAPITest {

private static SessionFactory sf = null;
    
    @BeforeClass
    public static void beforeClass(){
        sf = new AnnotationConfiguration().configure().buildSessionFactory();
    }
    
    @Test
    public void testTeacherSave() {
        Teacher t = new Teacher(); 
        t.setId(6);
        t.setName("fkdshf");
        t.setTitle("中级");
        
        Session session1 = sf.getCurrentSession();
        Session session3 = sf.getCurrentSession();
        System.out.println(session1 == session3);
        session1.beginTransaction();
        session1.save(t);
        session1.getTransaction().commit();
        
        Session session2 = sf.getCurrentSession();
        
        System.out.println(session1 == session2);
        session1.close();
    }

    @AfterClass
    public static void afterClass(){
        sf.close();
    }

}

结果为true  false,这种方法拿到的session在commit的时候会自动colse,所以session2又是一个新的了。session 是一个接口,可以实现它的类很多,所以Session session = sessionFactory.openSession();与Session session = sessionFactory.getCurrentSession();很有可能不是同一个实现,不能混用。

原文地址:https://www.cnblogs.com/ligui989/p/3456053.html