Hibernate5.x创建sessionFactory的方法

private static SessionFactory sessionFactory = null;

static {
    try {
        Configuration conf = new Configuration().configure();
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();
        sessionFactory = conf.buildSessionFactory(serviceRegistry);
    }catch (HibernateException e){
        System.out.println("SessionFactory初始化失败");
        e.printStackTrace();
    }
}

public static SessionFactory getSessionFactory() throws Exception{
    if (sessionFactory != null){
        return sessionFactory;
    }else {
        throw new Exception("sessionFactory为空,请检查配置文件");
    }
}

你可能感兴趣的:(Hibernate)