skip to Main Content

enter image description hereI’m working on a project where I need to store latitude and longitude in coordinates field in a PostgreSQL database. I’ve decided to use the Point data type in PostgreSQL to represent these coordinates efficiently. However, I’m unsure about the best approach to handle this in Java and how to declare in entity class.

For example:

double lat =17.4343,
double lon =76.4343

Better approach to store the coordinates to store in db and how to take in entity class.

Give me best suggestions to store the coordinates to PostgreSQL db

2

Answers


  1. Read the documentation: The Postgres JDBC driver docs: Geometric data types.

    The key is to use the PGpoint class (there are more ‘geometric’ types, and a java class is available for each of them), from the postgres JDBC driver.

    You can easily retrieve points from queries, as well as set them in queries:

    PreparedStatement ps = ...;
    PGpoint p = new PGpoint(1.5, 2.5);
    ps.setObject(colRef, p);
    
    ResultSet rs = .....;
    PGpoint q = rs.getObject(colRef, PGpoint.class);
    System.out.printf("Coord: [%f, %f]n", q.x, q.y);
    

    NB: The docs suggest you have to cast. You don’t – The 2-args method of getObject is is nicer on the eyes and a bit more standard. But, if you really wanna cast – it’s an option, of course.

    Login or Signup to reply.
  2. Use PostGIS geometry(Point) type instead. The db extension comes bundled with JDBC extension objects.

    The built-in geometry types are fairly primitive and limited in what you can do with them. Although PostGIS is an extension, it’s the de-facto standard for GIS-related operations in Postgres. Compare the list of built-in functions and operators with the PostGIS list to get an idea.

    There’s a small example in the doc, and here’s larger end-to-end example of a working app.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search