Groovy / Gradle

Find Nearby Delivery Drivers with Micronaut Data JDBC and SQL Server Geospatial

Learn how to use Micronaut Data JDBC and SQL Server 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 Groovy.

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 SQL Server geography 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. SQL Server geography applies the 5 km spatial predicate in meters for SRID 4326 distance calculations.

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,sqlserver,serialization-jackson,validation \
    --build=gradle \
    --lang=groovy \
    --test=spock
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, sqlserver, 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.

SQL Server Driver

Add also the SQL Server Driver

build.gradle
runtimeOnly("com.microsoft.sqlserver:mssql-jdbc")

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=com.microsoft.sqlserver.jdbc.SQLServerDriver 
datasources.default.db-type=mssql 
datasources.default.dialect=SQL_SERVER 
src/main/resources/application.properties
test-resources.containers.mssql.accept-license=true
test-resources.containers.mssql.startup-timeout=600s

The SQL Server 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">
    <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">
        <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 a SQL Server geography 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:

groovy/src/main/groovy/example/micronaut/DeliveryDriver.groovy
package example.micronaut

import groovy.transform.CompileStatic
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 io.micronaut.data.model.runtime.convert.GeometryWktConverter

import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.NotNull

@CompileStatic
@MappedEntity('delivery_driver') // 
class DeliveryDriver {

    enum Status {
        AVAILABLE,
        BUSY
    }

    @Id
    @GeneratedValue
    Long id

    @NotBlank
    String name

    @NotNull
    Status status // 

    @NotNull
    @Srid(4326) // 
    @MappedProperty(converter = GeometryWktConverter.class, definition = 'geography not null') // 
    @Index(columns = 'location') // 
    Point location

    DeliveryDriver() {
    }

    DeliveryDriver(String name, Status status, Point location) {
        this.name = name
        this.status = status
        this.location = location
    }
}

SQL Server does not provide a built-in GeoJSON conversion function, so the entity uses Micronaut Data’s WKT converter and maps the column as geography. SQL Server stores the value in the geography 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 Use Micronaut Data’s WKT converter and map the property to a SQL Server geography column.
5 Mark the location column as spatially indexed in the Micronaut Data model.

Repository

Create a repository that declares the SQL Server dialect:

groovy/src/main/groovy/example/micronaut/DeliveryDriverRepository.groovy

Dispatch Service

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

groovy/src/main/groovy/example/micronaut/DispatchService.groovy

Create a small response object for the match:

groovy/src/main/groovy/example/micronaut/DriverMatch.groovy
package example.micronaut

import groovy.transform.CompileStatic
import io.micronaut.serde.annotation.Serdeable

@CompileStatic
@Serdeable
class DriverMatch {

    final Long driverId
    final String name
    final double distanceMeters

    DriverMatch(Long driverId, String name, double distanceMeters) {
        this.driverId = driverId
        this.name = name
        this.distanceMeters = distanceMeters
    }
}

Controller

Expose the dispatch operation through an HTTP endpoint:

groovy/src/main/groovy/example/micronaut/DeliveryDispatchController.groovy

Test

Add a test that verifies the dispatch endpoint:

groovy/src/test/groovy/example/micronaut/DeliveryDispatchControllerSpec.groovy

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 SQL Server container, accepts the container license, 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).