问答详情
源自:2-6 session详解(下)

使用OpenSession每次connection的hashCode是一样的

https://img1.mukewang.com/5b7cffaf0001437e10400864.jpg

@Test
public void testSaveStudentWithOpenSession(){
    //获得配置对象
    Configuration config = new Configuration().configure();
    //获得服务注册对象
    StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder().configure().build();
    SessionFactory sessionFactory = config.buildSessionFactory(standardServiceRegistry);
    Session session = sessionFactory.openSession();
    //开启事务
    Transaction transaction = session.beginTransaction();
    Student student = new Student("张三丰", "女", new Date(), "武当山");
    session.doWork(new Work() {
        public void execute(Connection connection) throws SQLException {
            System.out.println(connection.hashCode());
        }
    });
    session.save(student);
    transaction.commit();
    
    Session session2 = sessionFactory.openSession();
    transaction = session2.beginTransaction();
    session2.doWork(new Work() {
        public void execute(Connection connection) throws SQLException {
            System.out.println(connection.hashCode());
        }
    });
    session2.save(student);
    transaction.commit();
}


提问者:K8sCat 2018-08-22 14:17

个回答

  • 情有独钟
    2018-08-23 17:08:35

    不是不hibernate版本问题,你的事5.x版本吧。看到用了StandardServiceRegistryBuilder