Cloud-Ready Configuration for JPA-Integration Tests 📎
persistence.xml containing all JDBC-connection settings:
<?xml version="1.0" encoding="UTF-8"?>
<persistence>
<persistence-unit name="integration-test" transaction-type="RESOURCE_LOCAL">
<class>com.airhacks.workshops.entity.Workshop</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<validation-mode>NONE</validation-mode>
<properties>
<property name="javax.persistence.jdbc.user" value="air"/>
<property name="javax.persistence.jdbc.password" value="hacks"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
The persistence.xml above does not contain the mandatory javax.persistence.jdbc.url property -- the database
host is fetched from the environment and directly passed to the createEntityManagerFactory
method at runtime:
public class WorkshopIT {
private EntityManager em;
private EntityTransaction tx;
static String getDatabaseHost() {
return System.getenv().getOrDefault("db.host", System.getProperty("db.host", "localhost"));
}
@BeforeEach
public void init() {
String dbURL = String.format("jdbc:postgresql://%s:5432/airhacksDB", getDatabaseHost());
Map<String, String> configuration = new HashMap();
configuration.put("javax.persistence.jdbc.url", dbURL);
this.em = Persistence.
createEntityManagerFactory("integration-test", configuration).
createEntityManager();
this.tx = this.em.getTransaction();
}
}
Now the integration test can be configured to use a local database at the developer machine and a different database in the CI/CD pipeline. In Kubernetes-based environments like e.g. OpenShift the configuration can be provided with deployment configuration (DC) or Jenkins build parameters.
See you at Web, MicroProfile and Java EE Workshops at MUC Airport, particularly at the Java EE CI/CD, Testing and Quality workshop