在 OSGi 中的 Hibernate 中创建 EntityManagerFactory

Creating a EntityManagerFactory in Hibernate in OSGi

我正在让 Hibernate 与 OSGi 一起工作,所以这个项目的基础是 org.hibernate.osgi

我创建了以下 persistence.xml:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_2_1.xsd"
    version="1.0">
    <persistence-unit name="DemoUnit" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>

        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
            <property name="hibernate.connection.driver_class" value="org.h2.Driver" />
            <property name="hibernate.connection.username" value="sa" />
            <property name="hibernate.connection.password" value="" />
            <property name="hibernate.connection.url" value="jdbc:h2:mem:test;DB_CLOSE_DELAY=-1" />

            <property name="hibernate.hbm2ddl.auto" value="update" />
            <property name="org.hibernate.FlushMode" value="commit" />
            <property name="hibernate.current_session_context_class" value="thread" />
            <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider" />
            <property name="hibernate.show_sql" value="true" />
        </properties>
    </persistence-unit>
</persistence>

然后我尝试使用以下代码访问它:

    BundleContext context = FrameworkUtil.getBundle(getClass()).getBundleContext();
    ServiceReference serviceReference = context.getServiceReference(PersistenceProvider.class.getName());
    PersistenceProvider persistenceProvider = (PersistenceProvider) context.getService(serviceReference);
    EntityManagerFactory emf = persistenceProvider.createEntityManagerFactory("DemoUnit", null);

之后,EntityManagerFactory为空。没有异常,没有日志,什么都没有。

我知道的:

谁能帮我找到问题的根源?

PersistenceProvider 与您的持久性 类 和 persistence.xml 位于不同的包中。所以它看不到这些。

将 ContextClassLoader 设置为包的类加载器可能会有所帮助。

使用hibernate比较好的方法是在中间使用Aries JPA。它以 OSGi 安全的方式为您创建 EntityManagerFactory 并将 EMF 作为 OSGi 服务提供。

参见Aries JPA examples

还支持使用 pax-jdbc-config.

从配置中将数据源创建为服务

答案很简单:提供商错误(或过时?)。如果 Hibernate 打印日志会更容易找到:

<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>