关于Hibernate 5 和 Hibernate 4 在创建SessionFactory的不同点分析(解决 org.hibernate.MappingException: Unknown entity: xx类报错问题)

Hibernate4版本的SessionFactory实例构建的步骤是这样的(也是很多学习资料的通用范本):

//Configuration就是代表着hibernate的那个xml配置文件对象,如果configure方法中没有参数的话,默认是就是hibernate.cfg.xml。

Configuration conf = new Configuration().configure();

//服务注册,这是使用创建者模式,根据配置文件中的配置字段来构建注册服务(这应该是hibernate架构中注册服务的通用流程)。

ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().
applySettings(conf.getProperties()).build();

//使用实例化好了的注册服务,使用Configuration中的工厂模式实例化了SessionFactory
SessionFactory sf = conf.buildSessionFactory(serviceRegistry);

如果你用的是Hibernate4的版本,这样做完全OK的,运行的时候不会报MappingException。

但是如果你使用Hibernate5的版本,就会报错。那么Hibernate5应该怎样构建SessionFactory呢,如下:

//和V4版本比,V5版本看不到configure对象了。直接使用创建者模式构建出了标准服务注册对象

StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().configure().build();

//这个对象metadata对象应该扮演了一个万金油的角色,使用以上的注册对象作为入参构建这个对象

Metadata metadata = new MetadataSources(standardRegistry).getMetadataBuilder()
.applyImplicitNamingStrategy(ImplicitNamingStrategyComponentPathImpl.INSTANCE).build();


//最后由这个metadata使用构建出sessionFactory
SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build();

比较一下两种方式,V4的构建中思路,主要还是configure对象中用工厂模式来构建,很传统的模式。V5全部修改为创建者模式,3条语句,3个创建,

3个穿行的步骤。构建的思路明显清晰很多。

其实换句话来说,V4的构建也没什么不好的,非得改成V5的方式,不改工作还不正常了。这一点我觉得体验不太好。这大概就是程序员的完美主义在作祟吧。

原文地址:https://www.cnblogs.com/wangxiaoha/p/6231888.html