Upsert Oracle AI Database
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.
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 Oracle AI Database.
What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
A decent text editor or IDE (e.g. IntelliJ IDEA)
-
JDK 21 or greater installed with
JAVA_HOMEconfigured appropriately -
Docker installed to run Oracle and to run tests using Testcontainers.
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.
-
Download and unzip the source
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,oracle,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, oracle, 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:
annotationProcessor("io.micronaut.data:micronaut-data-processor")
implementation("io.micronaut.data:micronaut-data-jdbc")
implementation("io.micronaut.sql:micronaut-jdbc-hikari")Oracle Driver
Add also the Oracle Driver
runtimeOnly("com.oracle.database.jdbc:ojdbc11")Data Source configuration
Define the datasource in 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:
implementation("io.micronaut.liquibase:micronaut-liquibase")Configure the database migrations directory for Liquibase in application.properties.
liquibase.datasources.default.change-log=classpath\:db/liquibase-changelog.xmlCreate the following files with the database schema creation:
<?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><?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" dbms="oracle">
<createTable tableName="book">
<column name="id" type="NUMBER(19,0)">
<constraints primaryKey="true" primaryKeyName="pk_book" nullable="false"/>
</column>
<column name="title" type="VARCHAR2(255)">
<constraints nullable="false"/>
</column>
<column name="pages" type="NUMBER(10,0)">
<constraints nullable="true"/>
</column>
</createTable>
</changeSet>
</databaseChangeLog>The id column is the table’s primary key. Oracle’s MERGE statement matches rows with its ON condition, and the primary key on that same column keeps the upsert reliable under concurrent writes.
Entity
Create a Book entity:
|
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:
For the ORACLE dialect, Micronaut Data generates a MERGE statement at compilation time. For the Book entity, the generated SQL is similar to:
MERGE INTO "BOOK" target
USING (SELECT ? c0,? c1,? c2 FROM DUAL) source
ON (target."ID"=source.c0)
WHEN MATCHED THEN UPDATE SET target."TITLE"=source.c1,target."PAGES"=source.c2
WHEN NOT MATCHED THEN INSERT ("ID","TITLE","PAGES") VALUES (source.c0,source.c1,source.c2)The bound values are selected from DUAL as a single-row source. If no row with the given id exists, the WHEN NOT MATCHED branch inserts a new row. Otherwise, the WHEN MATCHED branch updates the title and pages columns of the existing row.
|
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:
Tests
Create an abstract test class that starts an Oracle Database container with Testcontainers and points the default datasource to it:
Create a test which sends a POST request to create a book and then a PUT request with the same id to update it:
Testing the Application
To run the tests:
./gradlew testThen 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 nativeTestThen 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). |