How to Embed PostgreSQL in Your Java Application: A Guide

Dec 13, 2021 | Programming

If you’re a developer looking to effectively unit test your Java application with a PostgreSQL database without putting the hassle on end-users to set up a database cluster, you’re in the right place! This article will guide you through embedding PostgreSQL into your Java code using Docker containers, while taking a closer look at the exciting new features and recent changes in the OpenTable Embedded PostgreSQL component.

What You Need

  • Java 11 or higher (Note: Flyway 10 requires Java 17).
  • Docker installed on your machine.
  • A basic understanding of JUnit for testing.

Why Switch to Docker-based PostgreSQL?

The latest release marks a significant shift from the previous embedded tarball method to a Docker-based approach. Why the switch? Let’s break it down:

  • Multi-Architecture Support: With the rise of devices like Mac M1 and various Linux ARM architectures, supporting multiple platforms is paramount.
  • Consistency Across OS: The same PostgreSQL container can run on Mac, Windows, or Linux, minimizing compatibility issues.
  • Easier Maintenance: No more dependency on specific Linux distributions to ship universal binaries—update your Docker image instead.
  • Better Security: You can pull trusted Docker images rather than relying on tarballs that run in your security context.

However, this transition comes with a few caveats:

  • Performance may be slower (2-5x slower), especially with extensive testing.
  • Some API compatibility changes have occurred.

Basic Usage

Let’s get started with the basic setup! Here’s a simple example of how to integrate Embedded PostgreSQL into your JUnit 5 tests:

Add the following line to manage an instance of Embedded PostgreSQL:

@Rule
public SingleInstancePostgresRule pg = EmbeddedPostgresRules.singleInstance();

With this setup, JUnit will handle starting and stopping the PostgreSQL instance automatically. You can access the DataSource using:

pg.getEmbeddedPostgres().getPostgresDatabase();

Here’s a brief analogy to make this clearer: Think of your embedded PostgreSQL instance like a coffee machine in your home. Once you set it up (just like initializing with JUnit), it can brew coffee (provide a DataSource) whenever you need it. You don’t have to worry about running out to a café (setting up an actual database) each time you want a cup. Just brew your coffee at home!

Sample Usage of Embedded PostgreSQL

If you need to run a test using Embedded PostgreSQL, here’s how you can do it:

public void testDatabaseName() throws IOException, SQLException {
    EmbeddedPostgres db = EmbeddedPostgres.builder().start();
    DataSource dataSource = db.getPostgresDatabase();
    // Use the datasource...
    db.close();
}

The builder allows for various configurations, including options to set the image, tag, and database name.

Integration with Migrators (Flyway and Liquibase)

You can integrate easy schema migrations using Flyway or Liquibase:

  • For Flyway:
    @Rule
    public PreparedDbRule db = EmbeddedPostgresRules.preparedDatabase(
        FlywayPreparer.forClasspathLocation("db/my-db-schema"));
    
  • For Liquibase:
    @Rule
    public PreparedDbRule db = EmbeddedPostgresRules.preparedDatabase(
        LiquibasePreparer.forClasspathLocation("liquimaster.xml"));
    

Troubleshooting Tips

If you run into issues while running Docker or setting up your PostgreSQL environment, consider the following troubleshooting steps:

  • Double-check your Docker installation to ensure it’s functioning correctly.
  • If using an alternative to Docker (like Podman), remember that not all features may work the same—specifically the Docker socket API.
  • For better performance, consider adjusting your test lifecycle or isolation strategies.
  • Keep in mind that no further PRs or tickets will be accepted for pre 1.0.0 releases unless community support arises; base PRs against the legacy branch.

For more insights, updates, or to collaborate on AI development projects, stay connected with fxis.ai.

Conclusion

Using the Embedded PostgreSQL component opens up new avenues for seamless and effective database testing in Java applications. With the transition to Docker containers, you can take advantage of the promises of security, compatibility, and maintainability.

At fxis.ai, we believe that such advancements are crucial for the future of AI, as they enable more comprehensive and effective solutions. Our team is continually exploring new methodologies to push the envelope in artificial intelligence, ensuring that our clients benefit from the latest technological innovations.

Stay Informed with the Newest F(x) Insights and Blogs

Tech News and Blog Highlights, Straight to Your Inbox