升级Hibernate至5.6.15.Final:无数据库连接实例化InFlightMetadataCollectorImpl
Hibernate 5.6.x 无数据库连接构建SessionFactory解决方案
Hibernate 5.x版本起,元数据收集流程默认会尝试连接数据库获取方言等元数据信息,这也是你实例化InFlightMetadataCollectorImpl时遇到警告和错误的核心原因。要在不提供数据库连接的情况下完成构建,需要显式配置以下关键属性:
- 配置无连接提供者:指定
hibernate.connection.provider_class为org.hibernate.connection.NoConnectionProvider,该提供者不会尝试获取数据库连接 - 指定数据库方言:显式设置
hibernate.dialect为对应数据库的方言类(比如Oracle用org.hibernate.dialect.Oracle12cDialect),Hibernate需要方言处理类型映射、HQL转换等逻辑,无需连接数据库也能正常工作 - 禁用自动DDL操作:设置
hibernate.hbm2ddl.auto为none,避免自动执行表创建/更新操作时尝试连接数据库
修改后的代码如下:
private SessionFactory createSessionFactory() { Configuration cfg = new Configuration(); cfg.setProperty("show_sql", "true"); // 新增关键配置 cfg.setProperty("hibernate.connection.provider_class", "org.hibernate.connection.NoConnectionProvider"); cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.Oracle12cDialect"); // 根据你的数据库类型调整 cfg.setProperty("hibernate.hbm2ddl.auto", "none"); StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build(); MetadataBuildingOptionsImpl buildingOptions = new MetadataBuildingOptionsImpl(serviceRegistry); BootstrapContextImpl bootstrapContext = new BootstrapContextImpl(serviceRegistry, buildingOptions); buildingOptions.setBootstrapContext(bootstrapContext); InFlightMetadataCollectorImpl metadataCollector = new InFlightMetadataCollectorImpl(bootstrapContext, buildingOptions); MetadataBuildingContext metadataBuildingContext = new MetadataBuildingContextRootImpl(bootstrapContext, buildingOptions, metadataCollector); /* * Modify metadataCollector here */ MetadataImpl metadataInstance = metadataCollector.buildMetadataInstance(metadataBuildingContext); return metadataInstance.getSessionFactoryBuilder().build(); }
配置完成后,Hibernate会跳过数据库连接步骤,直接基于你提供的方言和配置完成InFlightMetadataCollectorImpl的实例化,进而构建SessionFactory。
内容的提问来源于stack exchange,提问作者Daniel Kargl
相关产品推荐
相关产品推荐

