GeoTools : How to use a PostGISDataStore

The DataStore interface is general to all of the implemented DataStores. The Data access basic described how to use a DataStore, using a ShapefileDataStore as an example. The following document extends this to using a PostGISDataStore created with a DataStoreFinder.

Creating a PostGISDataStore

While the Data access basic uses the ShapefileDataStore constructor to create a DataStore, a more general method is to use the DataStoreFinder. The DataStoreFinder uses the interface for pluggable DataStores, allowing you to use different DataStores just by changing a few parameters. See DataStoreFinder Parameters for a list of available parameters for other DataStores. The following code shows how to use the DataStoreFinder to create a PostGISDataStore.

import java.util.HashMap;
import java.util.Map;



Map params = new HashMap();
params.put("dbtype", "postgis");        //must be postgis
params.put("host", "localhost");        //the name or ip address of the machine running PostGIS
params.put("port", new Integer(5432));  //the port that PostGIS is running on (generally 5432)
params.put("database", "spatial");      //the name of the database to connect to.
params.put("user", "postgres");         //the user to connect with
params.put("passwd", "");               //the password of the user.

DataStore pgDatastore = DataStoreFinder.getDataStore(params);
FeatureSource fsBC = pgDatastore.getFeatureSource("bc");

System.out.println("bc count: " + fsBC.getCount(Query.ALL));

Once the PostGISDataStore is created, you can use it like any other DataStore.

SpearfishSample using PostGIS

The attached file is a modified version of the Maps and styles's that uses data from a PostGIS database. The attached file contains all of the sample data as zipped SQL insert statements.

To create the PostGIS database with the spearfish data, use the following commands. These create the database 'spearfish,' owned by 'postgres.'

$ createdb -U postgres spearfish
$ createlang -U postgres plpgsql spearfish
$ psql -U postgres -f <path/to/file/>postgis.sql -d spearfish
$ psql -U postgres -f spearfish_data_pg.sql -d spearfish
$ vacuumdb -z spearfish 

To run and compile SpearfishPostGIS, you will need the following jars on your classpath:

  • gt2-main.jar
  • gt2-postgis.jar
  • JTS-1.4.jar
  • geoapi-1.1.0alpha.jar
  • vecmath-1.2.1.jar - also part of java 3D
  • a recent postgresql jdbc driver from

This code was tested and works with the geotools b5 release and geotools trunk (requires wkb4j-1.0-RC1.jar and vecmath-1.3.jar).