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.
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 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:
-
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 PostgreSQL with Micronaut Test Resources.
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,postgres,serialization-jackson,validation \
--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 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
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:
compileOnly("jakarta.persistence:jakarta.persistence-api")Datasource Configuration
datasources.default.schema-generate=NONE
datasources.default.driver-class-name=org.postgresql.Driver
datasources.default.db-type=postgres
datasources.default.dialect=POSTGRES test-resources.containers.postgres.image-name=postgis/postgis
test-resources.containers.postgres.image-tag=17-3.5
test-resources.containers.postgres.startup-timeout=600sThe 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:
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="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:
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") //
public record DeliveryDriver(
@Id
@GeneratedValue
Long id,
@NotBlank
String name,
@NotNull
Status status, //
@NotNull
@Srid(4326) //
@MappedProperty(definition = "geography not null") //
@Index(columns = "location") //
Point location
) {
public enum Status {
AVAILABLE,
BUSY
}
public DeliveryDriver(String name, Status status, Point location) {
this(null, name, status, location);
}
}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:
Dispatch Service
The repository returns available drivers within 5 km of the order location. The service then selects the nearest candidate:
Create a small response object for the match:
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:
Test
Add a test that verifies the dispatch endpoint:
Testing the Application
To run the tests:
./gradlew testThen 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
Read more about Micronaut Data geospatial support.
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). |