persistence.xml to import database parameters values from .properties file

别说谁变了你拦得住时间么 提交于 2019-11-30 18:45:33

Instead of defining the properties inside persistence.xml you can define them in a standard properties file (key=value) and pass a Properties object to the createEntityManagerFactory() method, e.g.:

Properties props = new Properties();
props.load(new FileInputStream("/some/path/persistence.properties"));
EntityManagerFactory factory = Persistence.createEntityManagerFactory("appName", props);
Gireesh

If you are using Maven as the build system, you can use Maven filters to replace the values during build time.

Or you can write a simple property placeholder replacement (which is internally used by spring itself)

Reference: https://stackoverflow.com/a/14724719/477435

I edited to mention I'm using Shiro Security, that also needs some database parameters. I made it need just 1 database parameters location doing these stay in context.xml and referencing it in the others.

1) Ant read context.xml

Context.xml having

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <!-- Other stuff... -->

    <!-- Shiro's -->
    <Resource name="jdbc/postgres" auth="Container"
        type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
        url="jdbc:postgresql://url-to-db/database"
        username="user" password="pass" />
</Context>

did using in Ant build.xml

<xmlproperty file="/path/to/context.xml" keepRoot="false" semanticAttributes="true" includeSemanticAttribute="true" />

and then accessing it using

<target name="init-flyway">
    <property name="flyway.url" value="${Resource.url}" />
    <property name="flyway.user" value="${Resource.username}" />
    <property name="flyway.password" value="${Resource.password}" />
    <!-- stuff stuff stuff -->
</target>

2) persistence.xml read context.xml

It is possible to use context's datastore using this

<non-jta-data-source>java:/comp/env/jdbc/postgres</non-jta-data-source>

So, I killed 3 database parameters to just 1.

Thanks for the help!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!