第一种:与hibernate4.0之前相同,只需要一句
SessionFactory factory = cfg.buildSessionFactory();
第二种:稍微麻烦
StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder().configure().build();
Metadata metadata = new MetadataSources(standardServiceRegistry).getMetadataBuilder()
.applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE).build();
SessionFactory factory = metadata.getSessionFactoryBuilder().build();
第三种:这种在官网下载的hibernate5中有 user-guide文档说明,所以跟着官方写应该不会出错
此为文档目录:\hibernate-release-5.4.4.Final\documentation\userguide\html_single\Hibernate_User_Guide.html
protected void setUp() throws Exception {
// A SessionFactory is set up once for an application!
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
// The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
// so destroy it manually.
StandardServiceRegistryBuilder.destroy( registry );
}
}
以下为上方的精简版:
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
SessionFactory factory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();
最后创建session:Session session = factory.openSession();
三种方法均可实现创建SessionFactory.