DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Spring Data: Easy MongoDB Migration Using Mongock
  • Spring Boot Application With Spring REST and Spring Data MongoDB
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements

Trending

  • Why Successful Tech Transformation Starts With Clarity
  • Prompt Caching for LLMs, Part 1: Exact-Match Caching in Production
  • The Pipeline Failed, But the Infrastructure Changed
  • Build Production-Ready AI Phone Agents: Infrastructure, Models, and Telephony

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Databases
  4. Using GeoJSON With Spring Data for MongoDB and Spring Boot

Using GeoJSON With Spring Data for MongoDB and Spring Boot

By 
Lieven Doclo
·
Dec. 13, 14 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
23.4K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

In my previous articles I compared 4 frameworks commonly used in communicating with MongoDB from the JVM and found out that in that use-case, Spring Data for MongoDB was the easiest solution. However I did make the remark that it doesn’t use the GeoJSON format to store geolocation coordinates and geometries.

I tried to add GeoJSON support before, but couldn’t get the conversion to work propertly. But after some extensive searching I found out that the reason for it not working was my use of Spring Boot: its autoconfiguration for MongoDB does not support custom conversion out of the box. Luckily, the solution was simple: provide an extra configuration that extends from AbstractMongoConfiguration and import that in the Boot application. In that configuration you can override the customConversions() and add your converters.

When you compare the geo classes in Spring Data and GeoJSON, I noticed that only a subset of GeoJSON geometries can be mapped on Spring Data geo classes: Point and Polygon. Spring Boot does not support LineString, MultiLineString, MultiPolygon or MultiPoint. However, in your mapped domain classes, you won’t use these normally. Creating a converter that adheres to the GeoJSON format is quite straightforward.

import com.mongodb.BasicDBObject
import com.mongodb.DBObject
import org.springframework.core.convert.converter.Converter
import org.springframework.data.convert.ReadingConverter
import org.springframework.data.convert.WritingConverter
import org.springframework.data.geo.Point
import org.springframework.data.geo.Polygon
final class GeoJsonConverters {
    static List<Converter<?, ?>> getConvertersToRegister() {
        return [
                GeoJsonDBObjectToPointConverter.INSTANCE,
                GeoJsonDBObjectToPolygonConverter.INSTANCE,
                GeoJsonPointToDBObjectConverter.INSTANCE,
                GeoJsonPolygonToDBObjectConverter.INSTANCE
        ]
    }
    @WritingConverter
    static enum GeoJsonPointToDBObjectConverter implements Converter<Point, DBObject> {
        INSTANCE;
        @Override
        DBObject convert(Point source) {
            return new BasicDBObject([type: 'Point', coordinates: [source.x, source.y]])
        }
    }
    @ReadingConverter
    static enum GeoJsonDBObjectToPointConverter implements Converter<DBObject, Point> {
        INSTANCE;
        @Override
        Point convert(DBObject source) {
            def coordinates = source.coordinates as double[]
            return new Point(coordinates[0], coordinates[1])
        }
    }
    @WritingConverter
    static enum GeoJsonPolygonToDBObjectConverter implements Converter<Polygon, DBObject> {
        INSTANCE;
        @Override
        DBObject convert(Polygon source) {
            def coordinates = source.points.collect {
                [it.x, it.y]
            }
            return new BasicDBObject([type: 'Polygon', coordinates: coordinates])
        }
    }
    @ReadingConverter
    static enum GeoJsonDBObjectToPolygonConverter implements Converter<DBObject, Polygon> {
        INSTANCE;
        @Override
        Polygon convert(DBObject source) {
            def coordinates = source.coordinates as double[]
            return new Point(coordinates[0], coordinates[1])
        }
    }
}

To add those converters to the Spring context, you’ll have to override some methods in your MongoDB spring configuration class.

import com.mongodb.Mongo
import org.springframework.beans.factory.annotation.*
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.context.annotation.*
import org.springframework.data.mongodb.config.AbstractMongoConfiguration
import org.springframework.data.mongodb.core.convert.*
@EnableAutoConfiguration
@ComponentScan
@Configuration
@Import([MongoComparisonMongoConfiguration])
class MongoComparison
{
    static void main(String[] args) {
        SpringApplication.run(MongoComparison, args);
    }
}
@Configuration
class MongoComparisonMongoConfiguration extends AbstractMongoConfiguration {
    @Autowired
    Mongo mongo;
    @Value("\${spring.data.mongodb.database}")
    String databaseName;
    @Override
    protected String getDatabaseName() {
        return databaseName
    }
    @Override
    Mongo mongo() throws Exception {
        return mongo
    }
    @Override
    CustomConversions customConversions() {
        def customConverters = []
        customConverters << GeoJsonConverters.convertersToRegister
        return new CustomConversions(customConverters.flatten())
    }
}

As Spring Boot already provides the configuration of the Mongo instance and the name of the database, we can reuse these in the MongoDB configuration class. The custom conversions take preference over the existing ones for Point and Polygon.

I’ll be writing a library this weekend to add support for all GeoJSON geometries in Spring Data for MongoDB. However, I already noticed it’ll be very hard to provide support for those in generated query methods in repositories, but with annotated queries being possible, I don’t think this will be a big issue but we’ll see.

Spring Framework Spring Data Spring Boot GeoJSON MongoDB Data (computing)

Published at DZone with permission of Lieven Doclo. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Spring Data: Easy MongoDB Migration Using Mongock
  • Spring Boot Application With Spring REST and Spring Data MongoDB
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook