昨晚初学Hibernate时,本来想做一些简单的查询,但是报了如下一些错误,找了好久才知道原因
在网上找了一大推,基本都是说<mapping resource=""/>
这个没有配置,但是看了我自己的确实配置好了,第二天在找的时候,发现了一遍博文,主要讲的时Hibernate4和Hibernate5的区别,看完之后改了一下代码就搞定了,博文链接如下,有兴趣的可以自己看看请点击这里
大概讲的就是SessionFactory的构建步骤不同,才会导致发生上面的错误
如果你使用的时Hibernate4版本的jar包,应该使用如下代码 //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);
如果使用的是Hibernate5版本的jar包,就应该使用如下代码构建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();