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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Spring Data: Easy MongoDB Migration Using Mongock
  • Spring Data: Data Auditing Using JaVers and MongoDB
  • Spring Boot Application With Spring REST and Spring Data MongoDB
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl

Trending

  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • How to Introduce a New API Quickly Using Micronaut
  • Data Lake vs. Warehouse vs. Lakehouse vs. Mart: Choosing the Right Architecture for Your Business
  • The Perfection Trap: Rethinking Parkinson's Law for Modern Engineering Teams
  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 user avatar
Lieven Doclo
·
Dec. 13, 14 · Interview
Likes (1)
Comment
Save
Tweet
Share
22.6K Views

Join the DZone community and get the full member experience.

Join For Free

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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Spring Data: Easy MongoDB Migration Using Mongock
  • Spring Data: Data Auditing Using JaVers and MongoDB
  • Spring Boot Application With Spring REST and Spring Data MongoDB
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!