【问题标题】:Use maven properties in persistence.xml在 persistence.xml 中使用 Maven 属性
【发布时间】:2020-01-15 11:52:11
【问题描述】:

我想在我的 persistence.xml 中使用我的 pom.xml 中定义的属性(对于不同的配置文件具有不同的值)。

更准确地说,我希望持久性中使用的 SQL 方言根据我构建应用程序的配置文件进行调整。所以我必须像这样注入一个存储在配置文件中的值:

<profile>
  <id>profileName</id>
  <properties>
    <SqlDialect>Oracle</SqlDialect>
  </properties>
</profile>

进入persistence.xml:

<property name="hibernate.dialect" value="{maven property goes here}" />

这可能吗?如果没有,是否有另一种优雅的解决方案(即另一种解决方案,而不是为不同的方言使用多个持久性文件)?

【问题讨论】:

    标签: maven jpa pom.xml persistence.xml


    【解决方案1】:

    您的persistence.xml 是一种资源,对吧?

    然后您可以将其配置为 POM 中的过滤资源,并使用 ${some-property} 从 POM 中引用该属性。

    https://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html

    【讨论】:

      【解决方案2】:

      将以下行添加到您的 pom 中,以便 maven 知道应该在哪里进行替换:

      <build>
          <resources>
              <resource>
                  <directory>path to your persistence.xml</directory>
                  <filtering>true</filtering>
              </resource>
          </resources>
       ...
      </build>
      

      在你的 pom 中为属性定义一个变量:

      <properties>
          <hibernate.dialect>the dialect you want to use</hibernate.dialect>
      </properties>
      

      在一个值处添加变量:

      <property name="hibernate.dialect" value="${hibernate.dialect}" />
      

      但请注意:“您的 persistence.xml 的路径”中的所有文件都将被分析。所以二进制文件可能会被损坏。

      因此,如果目录中有二进制文件,则必须使用排除和包含:

      <build>
          <resources>
              <resource>
                  <directory>path to your persistence.xml</directory>
                  <excludes>
                      <exclude>define the binary files</exclude>
                  </excludes>
                  <filtering>true</filtering>
              </resource>
              <resource>
                  <directory>path to your persistence.xml</directory>
                  <includes>
                      <includes>define the binary files</includes>
                  </includes>
              </resource>
      
          </resources>
       ...
      </build>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-26
        • 1970-01-01
        • 2012-06-07
        • 2015-05-17
        • 2012-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多