I wanted to know how to change the configuration of the persistence.xml file from an external file. I'm using JSF + JPA. I want to do this not to leave this setting stuck in the source code.
Does anyone give me a help?
I wanted to know how to change the configuration of the persistence.xml file from an external file. I'm using JSF + JPA. I want to do this not to leave this setting stuck in the source code.
Does anyone give me a help?
I believe the best solution is to tell your connection settings in Tomcat, not the project. Following Tomcat 7 documentation :
Within Context
of your application, create Resource
(attention to name: jdbc/TestDB
):
<Context>
<Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/javatest"/>
</Context>
On your web.xml
:
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<description>MySQL Test App</description>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
On your persistence.xml
:
<persistence-unit name="TestUnit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/TestDB</jta-data-source>
<!-- Demais configurações pertinentes -->
</persistence-unit>
In this way, your project will always be the same. What will change is the configuration of your server / container.
The Persistence.createEntityManagerFactory
method has an overload that you can pass a Map with the settings of persistence.xml, there you load them from wherever you like (eg a configuration file);
Map properties = new HashMap();
properties.put("javax.persistence.jdbc.driver", "oracle.jdbc.OracleDriver");
properties.put("javax.persistence.jdbc.url", "jdbc:oracle:thin:@localhost:1521:ORCL");
properties.put("javax.persistence.jdbc.user", "user-name");
properties.put("javax.persistence.jdbc.password", "password");
Persistence.createEntityManagerFactory("unit-name", properties);