Java / Gradle

Upsert PostgreSQL

An upsert is a database operation that will update an existing row if a specified value already exists in a table, and insert a new row if the specified value doesn’t already exist.

Sergio del Amo
On this guide
In this section

Getting Started

In this guide, we will create a Micronaut application written in Java.

An upsert is a native database operation that inserts a row when no matching row exists, or updates the existing row when a match is found. Doing this in a single statement, instead of a "find, then insert or update" sequence, avoids a race condition: two concurrent requests cannot both decide the row is missing and both attempt an insert.

In this guide, you will declare an upsert method in a Micronaut Data JDBC repository and use it from an HTTP controller backed by PostgreSQL.

What you will need

To complete this guide, you will need the following:

Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide \
    --features=data-jdbc,liquibase,postgres,serialization-jackson,testcontainers \
    --build=gradle \
    --lang=java \
    --test=junit
Note
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

If you use Micronaut Launch, select Micronaut Application as application type and add data-jdbc, liquibase, postgres, serialization-jackson, and testcontainers features.

Note
If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features, and apply those changes to your application.

Micronaut Data JDBC

Add Micronaut Data JDBC dependencies to the project:

build.gradle
annotationProcessor("io.micronaut.data:micronaut-data-processor")
implementation("io.micronaut.data:micronaut-data-jdbc")
implementation("io.micronaut.sql:micronaut-jdbc-hikari")

PostgreSQL Driver

Add also the PostgreSQL Driver

build.gradle
runtimeOnly("org.postgresql:postgresql")

Data Source configuration

Define the datasource in src/main/resources/application.properties.

src/main/resources/application.properties

Database Migration with Liquibase

We need a way to create the database schema. For that, we use Micronaut integration with Liquibase.

Add the following snippet to include the necessary dependencies:

build.gradle
implementation("io.micronaut.liquibase:micronaut-liquibase")

Configure the database migrations directory for Liquibase in application.properties.

src/main/resources/application.properties
liquibase.datasources.default.change-log=classpath\:db/liquibase-changelog.xml

Create the following files with the database schema creation:

src/main/resources/db/liquibase-changelog.xml
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
  xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
         http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
  <include file="changelog/01-schema.xml" relativeToChangelogFile="true"/>
</databaseChangeLog>
src/main/resources/db/changelog/01-schema.xml
<?xml version="1.0" encoding="UTF-8"?>

<databaseChangeLog
  xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
         http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">
  <changeSet id="01" author="username">
    <createTable tableName="book">
      <column name="id" type="BIGINT">
        <constraints primaryKey="true" nullable="false"/>
      </column>
      <column name="title" type="VARCHAR(255)">
        <constraints nullable="false"/>
      </column>
      <column name="pages" type="INT">
        <constraints nullable="true"/>
      </column>
    </createTable>
  </changeSet>
</databaseChangeLog>

The id column is the table’s primary key. PostgreSQL requires a primary key or unique constraint that matches the conflict target of an upsert.

Entity

Create a Book entity:

src/main/java/example/micronaut/Book.java
Note
The id is not annotated with @GeneratedValue. By default, Micronaut Data uses the entity identity as the upsert conflict target, so the caller must supply the identity value. Upserts that rely on the default identity conflict target reject entities with generated identities.

Repository

Create a repository and declare an upsert method:

java/src/main/java/example/micronaut/BookRepository.java

For the POSTGRES dialect, Micronaut Data generates an INSERT …​ ON CONFLICT …​ DO UPDATE statement at compilation time. For the Book entity, the generated SQL is similar to:

INSERT INTO "book" ("id","title","pages") VALUES (?,?,?)
ON CONFLICT ("id") DO UPDATE SET "title"=EXCLUDED."title","pages"=EXCLUDED."pages"

If no row with the given id exists, PostgreSQL inserts a new row. Otherwise, it updates the title and pages columns of the existing row with the values proposed for insertion, which PostgreSQL exposes through the special EXCLUDED table.

Tip
Use the @Upsert annotation to give an upsert method a custom name, or its conflictsOn member to use another unique property, such as an ISBN, as the conflict target instead of the identity.

Controller

Create a controller which uses the upsert method both to create and to update a book:

src/main/java/example/micronaut/BookController.java

Tests

Create an abstract test class that starts a PostgreSQL container with Testcontainers and points the default datasource to it:

java/src/test/java/example/micronaut/AbstractTest.java

Create a test which sends a POST request to create a book and then a PUT request with the same id to update it:

src/test/java/example/micronaut/BookControllerTest.java

Testing the Application

To run the tests:

./gradlew test

Then open build/reports/tests/test/index.html in a browser to see the results.

Native Tests

The io.micronaut.application Micronaut Gradle Plugin automatically integrates with GraalVM by applying the Gradle plugin for GraalVM Native Image building.

This plugin supports running tests on the JUnit Platform as native images. This means that tests will be compiled and executed as native code.

To execute the tests, execute:

./gradlew nativeTest

Then open build/reports/tests/test/index.html in a browser to see the results.

INFO: A test may be disabled within a GraalVM native image via the @DisabledInNativeImage annotation.

Next Steps

Explore more features with Micronaut Guides.

Read more about Upserts in the Micronaut Data documentation, including conflict targets, batch upserts, supported dialects, and lifecycle event behavior.

License

Note
All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images).