gpt4 book ai didi

java - KARAF OSGI bundle 上的自定义 hibernate.cfg.xml 位置

转载 作者:行者123 更新时间:2023-11-30 06:53:44 25 4
gpt4 key购买 nike

我需要配置 hibernate 以从 karaf 上 OSGI 包的自定义位置加载 hibernate.cfg.xml。我需要能够在不编辑 JAR 文件的情况下编辑配置,这似乎是唯一可用的选项。我正在使用以下类来加载 Hibernate SessionFactory,如 hibernate 文档中所述,但似乎无法在公开此服务的 Hibernate OSGI 模块返回的 SessionFactory 上配置它。我已经研究这个问题好几天了,但找不到解决方案。我正在使用 Hibernate 4.3.11.Final。非常感谢任何帮助,谢谢

公共(public)类 HibernateUtil {

private static SessionFactory sf;

public static Session getSession() {
return getSessionFactory().openSession();
}

private static SessionFactory getSessionFactory() {
if ( sf == null ) {
Bundle thisBundle = FrameworkUtil.getBundle( HibernateUtil.class );

BundleContext context = thisBundle.getBundleContext();

ServiceReference sr = context.getServiceReference( SessionFactory.class.getName() );
sf = (SessionFactory) context.getService( sr );
}
return sf;
}

最佳答案

经过许多天的工作并遵循许多不同的线索,我终于解决了这个问题。主要思想是将数据库连接属性存储在 hibernate.cfg.xml 文件之外,该文件必须位于 jar 文件内,以便 Hibernate OSGI 找到它。相反,属性文件可以位于您喜欢的任何位置。要完成此任务,请使用蓝图定义 JNDI 服务,然后使用以下标记在 hibernate.cfg.xml 上配置 JNDI 服务:

<property name="connection.datasource">osgi:service/jdbc/mysqlds</property>

使用蓝图定义JNDI服务的代码如下:

<bean id="dataSource" 
class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
<property name="driverClass" value="${db.driverClass}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</bean>


<service interface="javax.sql.DataSource" ref="dataSource">
<service-properties>
<entry key="osgi.jndi.service.name" value="jdbc/mysqlds"/>
<entry key="datasource.name" value="MySqlDS"/>
</service-properties>
</service>

值得一提的是,我尝试使用许多不同的 DataSource 类,这些类通常会因 classnotfound 错误而失败。唯一对我有用的是 SimpleDriverDataSource

关于java - KARAF OSGI bundle 上的自定义 hibernate.cfg.xml 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42209493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com