Ok, I've searched and at a loss as to why I cannot find anything on how to save a shapefile to PostGIS with Java. Thought GeoTools might be helpful, but doesn't seem to be there either.

So here's the scenario and functionality that I've been looking for.

  1. User uploads a file
  2. Java code (Spring) on the server side get the file and checks to see if it is a .shp file
  3. If it is a .shp file, save it to a PostGIS table

It's step 3 that doesn't seem to be out there and what I'd like to find a solution for. In my case the table will have all necessary fields and a couple of other fields to record who uploaded and when etc..


Basically, you need a ShapefileDatastore to import your shapefile (remember to make sure you have at least 4 files and upto 13 at last count) then you create a PostGISDatastore to write the features from the first store to.

You will need to include gt-shapefile and gt-jdbc-postgis in your pom.xml. Then if you study this tutorial you will see how reading and writing features works.

If you are in a hurry, you can probably cut and paste from this answer.

  • Thank you Ian, I guess it's just not as straight forward as I'd hoped. That's a big help thank you. It looks like I've got some learning to do. I figure this would be a fairly easy thing to do. I guess not so much. Thanks again.
    – eLowe
    Dec 16 '20 at 11:50
  • 1
    That's about as straightforward as anything is with spatial data.
    – Ian Turton
    Dec 16 '20 at 12:30
  • Another quick question. I have this code running, but it creates a table for each shape file that is saved. This seems strange to me, but other similar examples do the same kind of thing. Is there a way to specify a common "geometries" table for storage of all shape/spatial data? Or is this just way too complicated, given the complexity of these?
    – eLowe
    Dec 16 '20 at 12:48
  • depends, are all of your attributes associated with the geometries the same? if so you can stuff the lot into the same table (just skip createSchema)
    – Ian Turton
    Dec 16 '20 at 13:14
  • Thank you Ian, you have been incredibly helpful. I can't be sure that all attributes will be the same, no. I was hoping that there could be a common "geometries" table that held all shape file contents. So if one wanted to save multiple different types of shape files in a database, you would have to create a table for each? That doesn't seem practical or manageable.
    – eLowe
    Dec 16 '20 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.