I’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
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:
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.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.