我需要在运行时将实体类添加到持久性单元,而不是在 persistence.xml 中指定所有实体类。有人可以帮助我吗?
我知道 Hibernate 有自己的机制来执行相同的操作:
AnnotationConfiguration.addAnnotatedClass(Class)
等 - 您还可以添加休眠配置(*.hbm.xml
) 以编程方式文件。
要求是,在不重新启动应用程序服务器的情况下,我应该能够继续动态地将实体类/它们的配置(映射)文件添加到持久性单元。
但是,在运行时以编程方式将实体类/配置文件添加到持久性单元的解决方案不应特定于 JPA 实现。
JPA 尚不提供此功能。您可以查看以下三个选项:
-
这个解决办法: https://stackoverflow.com/a/8744363/363573
1.生成一个persistence.xml
使用新的持久性单元动态(简单的 XML 文件创建)。
2.动态地将持久性文件添加到类路径(URLCLassLoader
)
3. Ask PersistenceProvider
加载新的持久性单元(createEntityManagerFactory
)
我确实实施了这个解决方法。然而,随着实体数量的增长(100+),它的扩展性不佳。我最终切换到了 JDBC。下面是从 JPA 切换到 JDBC 之前和之后的内存消耗 (-75%) 的捕获。
Nota
如果 JPA 提供者是 Hibernate,从 Hibernate 4.0 开始,可以直接将实体传递给该 JPA 提供者而不声明它们 in the persistence.xml
文件。 Hibernate 将动态处理实体。
以下是 JPA 2.1 + Hibernate 4.3.7.Final 的示例配置,未声明任何实体:
META-INF/persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="my-persistence-unit"
transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<!-- Database Properties -->
<property name="javax.persistence.jdbc.url"
value="jdbc:postgresql://localhost:5432/my-database" />
<property name="javax.persistence.jdbc.user" value="login" />
<property name="javax.persistence.jdbc.password" value="password" />
<!-- Hibernate Properties -->
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.default_schema" value="public" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="true" />
<!-- Connection Pool -->
<property name="hibernate.c3p0.min_size" value="5" />
<property name="hibernate.c3p0.max_size" value="20" />
<property name="hibernate.c3p0.timeout" value="500" />
<property name="hibernate.c3p0.max_statements" value="50" />
<property name="hibernate.c3p0.idle_test_period" value="2000" />
</properties>
</persistence-unit>
</persistence>
参考
- JPA 2.1 规范:8.2 持久性单元包装 http://download.oracle.com/otndocs/jcp/persistence-2_1-fr-eval-spec/index.html
- JPA 2.1 规范:8.2.1.6 映射文件、jar 文件、类、排除未列出的类 http://download.oracle.com/otndocs/jcp/persistence-2_1-fr-eval-spec/index.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)