Kotlin / Gradle

Find Nearby Delivery Drivers with Micronaut Data JDBC and PostGIS

Learn how to use Micronaut Data JDBC and PostgreSQL spatial queries to find the closest available delivery driver within 5 km of a food delivery order.

Milenko Supic
On this guide
In this section

Getting Started

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

In this guide, you will build the dispatch part of a food delivery application. When a customer places an order, the application stores driver positions in PostgreSQL GEOGRAPHY(POINT,4326) columns and asks Micronaut Data JDBC for available drivers within 5 km of the order location. The dispatch service then chooses the closest returned candidate.

The sample uses WGS 84 coordinates (SRID 4326), the coordinate system commonly used by GPS. The sample maps the column as PostGIS geography, so ST_DWithin applies the 5 km spatial predicate and interprets the 5,000 value as meters for SRID 4326 data.

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,validation \
    --build=gradle \
    --lang=kotlin \
    --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 validation 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.

PostgreSQL Driver

Add also the PostgreSQL Driver

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

Micronaut Data builds repository queries at compilation time. Add the Jakarta Persistence API as a compile-only dependency so the compile-time query model has the Criteria API types available:

build.gradle
compileOnly("jakarta.persistence:jakarta.persistence-api")

Datasource Configuration

src/main/resources/application.properties
datasources.default.schema-generate=NONE
datasources.default.driver-class-name=org.postgresql.Driver 
datasources.default.db-type=postgres 
datasources.default.dialect=POSTGRES 
src/main/resources/application.properties
test-resources.containers.postgres.image-name=postgis/postgis
test-resources.containers.postgres.image-tag=17-3.5
test-resources.containers.postgres.startup-timeout=600s

The PostgreSQL container image can take a while to download and initialize the first time. The container startup timeout and generated build’s Test Resources client timeout give Micronaut Test Resources enough time to pull the image and start the container.

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="micronaut-guides">
    <sql>
      CREATE EXTENSION IF NOT EXISTS postgis
    </sql>

    <createTable tableName="delivery_driver">
      <column name="id" type="BIGINT" autoIncrement="true">
        <constraints primaryKey="true" primaryKeyName="pk_delivery_driver" nullable="false"/>
      </column>
      <column name="name" type="VARCHAR(255)">
        <constraints nullable="false"/>
      </column>
      <column name="status" type="VARCHAR(32)">
        <constraints nullable="false"/>
      </column>
      <column name="location" type="GEOGRAPHY(POINT,4326)">
        <constraints nullable="false"/>
      </column>
    </createTable>

    <sql>
      CREATE INDEX idx_delivery_driver_location ON delivery_driver USING GIST (location)
    </sql>
  </changeSet>
</databaseChangeLog>

The migration enables PostGIS, creates the delivery_driver table with a GEOGRAPHY(POINT,4326) column, and creates a GiST spatial index. In production, keep the spatial column and index statements in your migration tool instead of relying on test-only schema generation.

Domain Model

Create a DeliveryDriver entity:

kotlin/src/main/kotlin/example/micronaut/DeliveryDriver.kt
package example.micronaut

import io.micronaut.data.annotation.GeneratedValue
import io.micronaut.data.annotation.Id
import io.micronaut.data.annotation.Index
import io.micronaut.data.annotation.MappedEntity
import io.micronaut.data.annotation.MappedProperty
import io.micronaut.data.annotation.Srid
import io.micronaut.data.model.geo.Point
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.NotNull

@MappedEntity("delivery_driver") // 
data class DeliveryDriver(
    @field:NotBlank
    var name: String,

    @field:NotNull
    var status: Status, // 

    @field:NotNull
    @field:Srid(4326) // 
    @field:MappedProperty(definition = "geography not null") // 
    @field:Index(columns = ["location"]) // 
    var location: Point,

    @field:Id
    @field:GeneratedValue
    var id: Long? = null
) {

    enum class Status {
        AVAILABLE,
        BUSY
    }
}

Micronaut Data geospatial model types use GeoJSON conversion by default. The entity maps the column as PostGIS geography, and PostgreSQL stores the value in the GEOGRAPHY(POINT,4326) column declared in the Liquibase migration.

1 Map the entity to the delivery_driver table created by Liquibase.
2 Represent whether a driver is available or busy so dispatch queries can filter drivers before applying the spatial predicate.
3 Use SRID 4326 for GPS-style longitude and latitude coordinates.
4 Map the property to a geography column so PostGIS distance predicates use meters with WGS 84 data.
5 Mark the location column as spatially indexed in the Micronaut Data model.

Repository

Create a repository that declares the PostgreSQL dialect:

kotlin/src/main/kotlin/example/micronaut/DeliveryDriverRepository.kt

Dispatch Service

The repository returns available drivers within 5 km of the order location. The service then selects the nearest candidate:

kotlin/src/main/kotlin/example/micronaut/DispatchService.kt

Create a small response object for the match:

kotlin/src/main/kotlin/example/micronaut/DriverMatch.kt
package example.micronaut

import io.micronaut.serde.annotation.Serdeable

@Serdeable
data class DriverMatch(
    val driverId: Long?,
    val name: String,
    val distanceMeters: Double
)

Controller

Expose the dispatch operation through an HTTP endpoint:

kotlin/src/main/kotlin/example/micronaut/DeliveryDispatchController.kt

Test

Add a test that verifies the dispatch endpoint:

kotlin/src/test/kotlin/example/micronaut/DeliveryDispatchControllerTest.kt

Testing the Application

To run the tests:

./gradlew test

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

When you run the test, Micronaut Test Resources starts a PostGIS-enabled PostgreSQL container and configures the JDBC datasource automatically.

Next Steps

Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.

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).