请按以下步骤操作:
在 hibernate.org 下载 Hibernate zip 文件(现在是 Hibernate4.3.0Final),但我用 Hibernate 4.2.8Final 测试OK
将项目A创建为osgi项目:(项目A将包含Hibernate osgi loader和hibernate Library,没有你的Entities类,也没有hibernate.cfg.xml)解压hibernate-release-4.2.8.Final.zip到目录,将\hibernate-release-4.2.8.Final\project\hibernate-osgi\src\main\java中的包源(org....)复制到项目A的src中。
Setup Activator class: (MANIFEST.MF)
Bundle-Activator: org.hibernate.osgi.HibernateBundleActivator
Create directory 'libs/hiber-4.2.8' in project A:
Copy All <DIR>\hibernate-release-4.2.8.Final\lib to your 'libs/hiber-4.2.8',
设置捆绑类路径:(MANIFEST.MF)
Bundle-ClassPath: .,
libs/hiber-4.2.8/jpa/hibernate-entitymanager-4.2.8.Final.jar,
libs/hiber-4.2.8/optional/ehcache/ehcache-core-2.4.3.jar,
libs/hiber-4.2.8/optional/ehcache/slf4j-api-1.6.1.jar,
libs/hiber-4.2.8/required/antlr-2.7.7.jar,
libs/hiber-4.2.8/required/dom4j-1.6.1.jar,
libs/hiber-4.2.8/required/hibernate-commons-annotations-4.0.2.Final.jar,
libs/hiber-4.2.8/required/hibernate-core-4.2.8.Final.jar,
libs/hiber-4.2.8/required/hibernate-jpa-2.0-api-1.0.1.Final.jar,
libs/hiber-4.2.8/required/javassist-3.18.1-GA.jar,
libs/hiber-4.2.8/required/jboss-logging-3.1.0.GA.jar,
libs/hiber-4.2.8/required/jboss-transaction-api_1.1_spec-1.0.1.Final.jar
设置导出包:
Export-Package: javax.persistence,
org.hibernate,
org.hibernate.annotations,
org.hibernate.cfg,
org.hibernate.criterion,
org.hibernate.dialect,
org.hibernate.dialect.function,
org.hibernate.exception,
org.hibernate.internal.util,
org.hibernate.jdbc,
org.hibernate.mapping,
org.hibernate.osgi,
org.hibernate.property,
org.hibernate.service,
org.hibernate.tool.hbm2ddl,
org.hibernate.type
==> 现在准备好项目 A(Osgi 项目)。
创建 Osgi 项目 B,在项目 B 中包含您的实体类、文件 hibernate.cfg.xml 、您可以在 B osgi 中声明的 Jdbc 驱动程序库。
在 B 激活器中:
public void start(BundleContext bundleContext) throws Exception {
Activator.context = bundleContext;
this.loadOsgiHibernateService(bundleContext);
}
private void loadOsgiHibernateService(BundleContext bundleContext) {
ServiceReference<?> ref = context
.getServiceReference(SessionFactory.class.getName());
if (ref != null) {
SessionFactory factory = (SessionFactory) context.getService(ref);
// Ready session factory.
Session session= factory.getCurrentSession();
}
}