本文主要是介绍Hibernate之openSession和getCurrentSession,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在Hibernate之基础配置测试用例中已经用到了openSession;
开启hibernate会话的方式:
//读取hibernate.cfg.xml文件
//Configuration方法默认加载hibernate.properties;configure方法默认加载hibernate.cfg.xml
Configuration cfg = new Configuration().configure();
//建立SessionFactory
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Hibernate4开启会话工厂方法
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry=new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Hibernate5.0Final之后用StandarServiceRegistryBuilder取代了ServiceRegistryBuilder;
会话工厂获取会话的两种方式:
1.openSession方式:
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
SessionFactory sessionFactory=new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
Session session = null;
try{session = sessionFactory.openSession();session.beginTransaction();User user = new User("陈三","1");session.save(user);session.getTransaction().commit();
}catch(Exception e) {e.printStackTrace();//回滚事务session.getTransaction().rollback();
}finally {if (session != null) {if (session.isOpen()) {//关闭sessionsession.close();}}
}
需要手动关闭session;除了查询,增删改都需要开启事务;
2.getCurrentSession
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
SessionFactory sessionFactory=new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();Session session = null;
try{session = sessionFactory.getCurrentSession();session.beginTransaction();User user = new User("陈三","1");session.save(user);session.getTransaction().commit();
}catch(Exception e) {e.printStackTrace();//回滚事务session.getTransaction().rollback();
}
运行报错:
Exception in thread "main" org.hibernate.HibernateException: No CurrentSessionContext configured!
需要在hibernate.cfg.xml配置事务管理
<property name="current_session_context_class">thread</property>
或者
<property name="current_session_context_class">jta</property>
请参考:http://www.cnblogs.com/lihaoyang/p/4853897.html?tvd
增删改查都需要开启session;参考:http://liusu.iteye.com/blog/380397
这篇关于Hibernate之openSession和getCurrentSession的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!