Find Nearby Delivery Drivers with Micronaut Data JDBC and MySQL Geospatial
Learn how to use Micronaut Data JDBC and MySQL 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 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 an SRID-restricted MySQL POINT column 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 MySQL spherical distance function for the 5 km spatial predicate.
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 MySQL 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,mysql,serialization-jackson,validation \
--build=maven \
--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, mysql, 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. |
MySQL Driver
Add also the MySQL Driver
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>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:
<dependency>
<groupId>jakarta.persistence</groupId>
<artifactId>jakarta.persistence-api</artifactId>
<scope>provided</scope>
</dependency>Database Configuration
And the database configuration:
test-resources.containers.mysql.startup-timeout=600sThe MySQL 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:
<dependency>
<groupId>io.micronaut.liquibase</groupId>
<artifactId>micronaut-liquibase</artifactId>
<scope>compile</scope>
</dependency>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 TABLE delivery_driver (
id BIGINT NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
status VARCHAR(32) NOT NULL,
location POINT NOT NULL SRID 4326,
CONSTRAINT pk_delivery_driver PRIMARY KEY (id)
)
</sql>
<sql>
CREATE SPATIAL INDEX idx_delivery_driver_location ON delivery_driver(location)
</sql>
</changeSet>
</databaseChangeLog>The migration creates the delivery_driver table with a MySQL POINT NOT NULL SRID 4326 column and a spatial index. The SRID attribute restricts the column to WGS 84 coordinates and lets MySQL’s query optimizer use the 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 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.Srid
import io.micronaut.data.model.geo.Point
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(value = 4326, type = Srid.CrsType.GEOGRAPHIC) //
@Index(columns = 'location') //
Point location
DeliveryDriver() {
}
DeliveryDriver(String name, Status status, Point location) {
this.name = name
this.status = status
this.location = location
}
}Micronaut Data geospatial model types use GeoJSON conversion by default. MySQL stores the value in the POINT NOT NULL SRID 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 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 MySQL 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 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:
Test
Add a test that verifies the dispatch endpoint:
Testing the Application
To run the tests:
./mvnw testWhen you run the test, Micronaut Test Resources starts a MySQL 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). |