Java 如何在Hibernate4.3Integrator中获取JDBC连接?
在为hibernate 4.3实现Java 如何在Hibernate4.3Integrator中获取JDBC连接?,java,hibernate,jdbc,orm,multi-tenant,Java,Hibernate,Jdbc,Orm,Multi Tenant,在为hibernate 4.3实现org.hibernate.integrator.spi.integrator时,将获得配置、SessionFactoryImplementor和SessionFactoryServiceRegistry对象 获取元数据的一种方法是获取连接提供程序: sessionFactory.getJdbcServices().getConnectionProvider() 但是getConnectionProvider()已被弃用,不适用于多租户设置 Javadocs说
org.hibernate.integrator.spi.integrator
时,将获得配置
、SessionFactoryImplementor
和SessionFactoryServiceRegistry
对象
获取元数据的一种方法是获取连接提供程序:
sessionFactory.getJdbcServices().getConnectionProvider()
但是getConnectionProvider()
已被弃用,不适用于多租户设置
Javadocs说
只要可能,通过org.hibernate.engine.jdbc.spi.JdbcConnectionAccess
访问连接应优先于通过ConnectionProvider
访问
但我的问题是,我没有找到获得JdbcConnectionAccess
的方法。可以使用给定的SessionFactoryServiceRegistry
并从SessionFactoryImpl\buildLocalConnectionAccess()
复制代码,但这不是一个好的解决方案
在集成器中获取连接的推荐方法是什么?您可以从集成器实现中执行以下操作:
SessionImplementor sessionImplementor = (SessionImplementor) sessionFactory.getCurrentSession();
Connection conn = sessionImplementor.getJdbcConnectionAccess().obtainConnection();
这里的sessionFactory是您从实现的方法中收到的SessionFactoryImplementor。我对不推荐的方法“sessionFactory.getJdbcServices().getConnectionProvider()”也有类似的问题。我使用此函数获取FlywayIntegrator的数据源。我在这个例子中使用了它们: 如果没有getConnectionProvider(),我找不到一个解决方案来获取与数据库连接所需的属性 作为一种解决方法,我将这些属性放在jboss配置的standalone.xml文件中,如下所示:
<system-properties>
<property name="com.mycomp.myapp.servername" value="localhost"/>
<property name="com.mycomp.myapp.databasename" value="xxx"/>
<property name="com.mycomp.myapp.databaseuser" value="yyy"/>
<property name="com.mycomp.myapp.databasepassword" value="zzz"/>
</system-properties>
也许这有助于…在Integrator中获取连接。Hibernate 5中的integrate()方法可以通过以下方式完成:
final DataSource ds = (DataSource) sessionFactory.getProperties().get("hibernate.connection.datasource");
final Connection conn = ds.getConnection();
在integrator中没有当前会话,因此会出现
HibernateException
,并显示消息no CurrentSessionContext configured代码>被抛出。Oups。。。你使用HibernateUtil模式吗?如果改用sessionFactory.openSession(),从HibernateUtil.getSessionFactory()的方法参数中获取的会话工厂,是否可以工作?不,我不使用HibernateUtil模式。我在JPA环境中使用hibernate,并使用库扩展支持的基本类型。该库集成到hibernate中,实现了一个集成器。但是在运行时,无法使用sessionFactory.openTemporarySession()
获取SessionImplementor
。您找到解决此问题的方法了吗?没有,我直到现在才找到解决方案。感谢您的努力,但我需要连接
来获取有关连接的元数据(例如API级别)。因此,配置细节是没有选择的。这是一个很好的、最简单的解决方案,没有提供任何额外的参数(如Gatschet的Solutionion)。谢谢
final DataSource ds = (DataSource) sessionFactory.getProperties().get("hibernate.connection.datasource");
final Connection conn = ds.getConnection();