我需要配置hibernate以从karaf上的OSGI包上的自定义位置加载hibernate.cfg.xml。我需要能够编辑配置而无需编辑JAR文件,这似乎是唯一可用的选项。我正在使用下面的类加载Hibernate SessionFactory,如hibernate文档中所述,但似乎没有办法在暴露此服务的Hibernate OSGI模块返回的SessionFactory上配置它。我几天来一直在研究这个问题,但我找不到解决方案。我正在使用Hibernate 4.3.11.Final。非常感谢任何帮助,谢谢
public class 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 :(得分:0)
经过多天的工作并遵循许多不同的线索,我能够解决问题。主要思想是将数据库连接属性存储在hibernate.cfg.xml文件之外,该文件必须位于用于Hibernate OSGI的jar文件中才能找到它。相反,属性文件可以位于您喜欢的任何位置。为此,使用blueprint定义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