Java / Maven

Find Nearby Delivery Drivers with Micronaut Data JDBC and H2GIS

Learn how to use Micronaut Data JDBC and H2 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 Java.

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 H2 GEOMETRY 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. Srid.CrsType.GEOGRAPHIC tells Micronaut Data to use the H2GIS spherical distance function for the 5 km spatial predicate.

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,h2,h2gis,serialization-jackson,validation \
    --build=maven \
    --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, h2, h2gis, 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.

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:

pom.xml
<dependency>
    <groupId>jakarta.persistence</groupId>
    <artifactId>jakarta.persistence-api</artifactId>
    <scope>provided</scope>
</dependency>

Datasource Configuration

src/main/resources/application.properties
datasources.default.schema-generate=NONE
datasources.default.url=jdbc:h2:mem:devDb;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE;INIT=CREATE ALIAS IF NOT EXISTS H2GIS_SPATIAL FOR "org.h2gis.functions.factory.H2GISFunctions.load"\\;CALL H2GIS_SPATIAL()
datasources.default.username=sa
datasources.default.password=
datasources.default.driver-class-name=org.h2.Driver 
datasources.default.db-type=h2 
datasources.default.dialect=H2 

The H2 JDBC URL initializes H2GIS before Liquibase runs, so the in-memory database has the spatial SQL functions used by Micronaut Data.

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:

pom.xml
<dependency>
    <groupId>io.micronaut.liquibase</groupId>
    <artifactId>micronaut-liquibase</artifactId>
    <scope>compile</scope>
</dependency>

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">
    <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="GEOMETRY">
        <constraints nullable="false"/>
      </column>
    </createTable>

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

The migration creates the delivery_driver table with an H2 GEOMETRY column and a 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:

java/src/main/java/example/micronaut/DeliveryDriver.java
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.Srid;
import io.micronaut.data.model.geo.Point;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;

@MappedEntity("delivery_driver") // 
public record DeliveryDriver(
    @Id
    @GeneratedValue
    Long id,

    @NotBlank
    String name,

    @NotNull
    Status status, // 

    @NotNull
    @Srid(value = 4326, type = Srid.CrsType.GEOGRAPHIC) // 
    @Index(columns = "location") // 
    Point location
) {

    public enum Status {
        AVAILABLE,
        BUSY
    }

    public DeliveryDriver(String name, Status status, Point location) {
        this(null, name, status, location);
    }
}

H2 stores the value in the GEOMETRY column declared in the Liquibase migration. The JDBC URL initializes H2GIS before Liquibase runs so the geospatial SQL functions are available.

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 with Srid.CrsType.GEOGRAPHIC for GPS-style longitude and latitude coordinates.
4 Mark the location column as spatially indexed in the Micronaut Data model.

Repository

Create a repository that declares the H2 dialect:

java/src/main/java/example/micronaut/DeliveryDriverRepository.java

Dispatch Service

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

java/src/main/java/example/micronaut/DispatchService.java

Create a small response object for the match:

java/src/main/java/example/micronaut/DriverMatch.java
package example.micronaut;

import io.micronaut.serde.annotation.Serdeable;

@Serdeable
public record DriverMatch(Long driverId, String name, double distanceMeters) {
}

Controller

Expose the dispatch operation through an HTTP endpoint:

java/src/main/java/example/micronaut/DeliveryDispatchController.java

Test

Add a test that verifies the dispatch endpoint:

java/src/test/java/example/micronaut/DeliveryDispatchControllerTest.java

Testing the Application

To run the tests:

./mvnw test

The test uses the in-memory H2 database and initializes H2GIS from the JDBC URL.

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