Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use PostGIS geography point with hibernate spatial 5 in spring boot

Apparently with Hibernate 5, the geography type is supported. I've searched a lot, but found close to nothing related to the geography points.

What I want to do is the following:

  1. Save Long/Lat Points in the database table, e.g. ST_GeomFromText('POINT(6.463471 52.484832)', 4326)

  2. Perform queues to check if the Point is in a Long/Lat rectangle like :

    WHERE point && ST_MakeEnvelope (5.440433, 39.480434, 8.464680, 55.486190, 4326)

I'm using PostgreSQL and PostGIS.

I just cannot find which type of column annotation for hibernate I have to use to get Long/Lat Points, and also how to perform above query.

@Type(type="org.hibernate.spatial.GeometryType")

Is not a point regarding Long/Lat

Is there any documentation regarding this (note: not geometry points).

like image 231
Tim Johnson Avatar asked Nov 17 '22 02:11

Tim Johnson


1 Answers

I'm using hibernate version 5.4.30

Regarding your question 1, You don't want to use any type of annotations to mark the field as Point type. Specifying the datatype as Point in your entity model is enough

@Entity
public class UserLocation {

    //other fields   
    private Point location;
    
    //constructors, getters & setters

Just make sure, you import Point from

import org.locationtech.jts.geom.Point;

To convert Latitude and longitude to Point, I use a Utility function

public class GeometryUtil {
    
    public static final int SRID = 4326; //LatLng
    private static WKTReader wktReader = new WKTReader();
    
    private static Geometry wktToGeometry(String wellKnownText) {
        Geometry geometry = null;
        
        try {
            geometry = wktReader.read(wellKnownText);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println("###geometry :"+geometry);
        return geometry;
    }
     public static Point parseLocation(double x,double y) {
        Geometry geometry = GeometryUtil.wktToGeometry(String.format("POINT (%s %s)",x,y));
         Point p =(Point)geometry;
         p.setSRID(4326); 
         return p;
     }
}    

To create a point from latitude and longitude using

MySQL

Point p = GeometryUtil.parseLocation(latitude,longitude);

PostGIS

Point p = GeometryUtil.parseLocation(longitude,latitude);

like image 107
Saravanan Avatar answered Mar 13 '23 00:03

Saravanan