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

paulochf picture paulochf · Oct 4, 2013 · Viewed 18k times · Source

Edit: not duplicate but almost

I would like to have my app persistence.xml to be something like

<?xml version="1.0" encoding="UTF-8"?>
<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 
                http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
                version="1.0">
   <persistence-unit name="appName" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <property name="hibernate.dialect" value="${db.dialect'}"/>
            <property name="javax.persistence.jdbc.driver" value="${db.driver}"/>
            <property name="javax.persistence.jdbc.user" value="${db.user}"/>
            <property name="javax.persistence.jdbc.password" value="${db.password}"/>
            <property name="javax.persistence.jdbc.url" value="${db.url}"/>
        </properties>
    </persistence-unit>
</persistence>

getting these placeholder values from a simple text file somewhere in my source folders.

I read about that it's possible when using Spring doing like

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <value>classpath:com/foo/jdbc.properties</value>
    </property>
</bean>

but here we are not using Spring, just Hibernate and some Primefaces.

Is it possible?

Thanks!

Edit: I didn't mention some things, but for reference, I'm also using Shiro Security and Ant to do some stuff. I'll post the solution as an answer. This makes my project have 3 different files with database parameters:

  • persistence.xml (Hibernate)
  • context.xml (Shiro)
  • database.properties (for Flyway tasks in Ant)

Answer

David Levesque picture David Levesque · Oct 4, 2013

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);