gpt4 book ai didi

java - 如何在不使用 persistence.xml 的情况下在 Wildfly 中部署时设置 hibernate.hbm2ddl.auto

转载 作者:行者123 更新时间:2023-11-30 06:58:23 25 4
gpt4 key购买 nike

我需要为使用 JPA 的 Web 应用程序生成部署架构。服务器是使用 Hibernate 作为 JPA 提供程序的 Wildfly 9。

我可以通过添加

<property name="hibernate.hbm2ddl.auto" value="create" />

到 persistence.xml。

是否有另一种方法可以在 Wildfly 9 中per webappon deployment 设置此属性?我也试过 hibernate.properties,但这没有效果。

最佳答案

没有开箱即用的 webapp 特定部署属性。

但是您可以设置一个您在 persistence.xml 中引用的特定于 webapp 的系统属性:

<persistence-unit >
...
<properties>
<property name="hibernate.hbm2ddl.auto" value="${mywebapp.hibernate.hbm2ddl.auto}" />
</properties>
</persistence-unit>

可以在 standalone.conf(.bat) 或 standalone.xml 中设置系统属性:

<server xmlns="urn:jboss:domain:3.0"> 
<extensions> ... </extensions>
<system-properties>
<property name="mywebapp.hibernate.hbm2ddl.auto" value="create"/>
...
</system-properties>
...
</server>

唯一的缺点:您必须在每个 环境中设置系统属性——没有默认值。

另一种选择是创建一个 Integrator,它在设置中设置值。不幸的是,配置在开始时被读入 Settings 对象,Settings.setAutoCreateSchema() 和其他 hibernate.hbm2ddl.auto 特定属性是包 protected ,但您可以通过反射设置它们:

public class AutoCreateSchemaIntegrator implements Integrator {

@Override
public void integrate(Configuration config, SessionFactoryImplementor factory,
SessionFactoryServiceRegistry registry) {
Settings settings = factory.getSettings();

try {
Method setter = settings.getClass().getDeclaredMethod("setAutoCreateSchema", boolean.class);
setter.setAccessible(true);
setter.invoke(settings, myDeploymentSpecificProperty);
} catch (ReflectiveOperationException | SecurityException e) {
// handle exception
}
}
}

您需要将该集成器的完整限定类名写入META-INF/services/org.hibernate.integrator.spi.Integrator:

com.myproject.AutoCreateSchemaIntegrator

如果您想动态确定 hbm2ddl 设置,这是最佳选择。

关于java - 如何在不使用 persistence.xml 的情况下在 Wildfly 中部署时设置 hibernate.hbm2ddl.auto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32762150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com