2017-02-13 115 views
0

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

公共类的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; 
} 
+0

我使用Hibernate 4.3.11.Final –

回答

0

后的工作和下面的许多不同的线索,我能够解决的问题很多天。主要想法是将数据库连接属性存储在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