javageotools

geotools - Is it possible to skip columns when inserting new SimpleFeature using JDBCDataStore


In our application (Java, Geotools 25, PostGIS) we have forms where the user can input some data which will be used to create a new features. In the database (PostGIS) there are more columns than there are fields so some columns will be empty. For some of these 'empty' columns there are default values defined in the database. Geotools however seems to always insert null for these columns.

In code I have a SimpleFeatureStore and I create a SimpleFeature based on the user input. When I'm inserting new Features (store.addFeatures()) the final SQL that is created by Geotools is an INSERT INTO statement which contains null values for all the columns which are not 'in the form', but again some of these have default values in the DB. Since Geotools explicitly sets the value to null the default value is never used.

Is there a fix or workaround I can try to resolve this issue so I can just let the DB insert default values when no value is supplied?


Solution

  • The DataUtilities class provides a defaultValues(SimpleFeatureType ) method that you can call to get the value defined in the PropertyDescriptor (though by default this is null). You can define the default value for any or all of your attributes in your SimpleFeatureType.

    I would use some code like:

    SimpleFeatureTypeBuilder sftb = new SimpleFeatureTypeBuilder();
    sftb.setName("test");
    sftb.add("id", Integer.class);
    sftb.defaultValue("String");
    sftb.add("desc", String.class);
    SimpleFeatureType schema = sftb.buildFeatureType();
    SimpleFeatureBuilder sfb = new SimpleFeatureBuilder(schema);
    sfb.addAll(DataUtilities.defaultValues(schema));
    sfb.set("id", 23);
    SimpleFeature f = sfb.buildFeature("test.1");
    System.out.println(f);
    

    Which produces a feature like:

    SimpleFeatureImpl:test=[SimpleFeatureImpl.Attribute: id<id id=test.1>=23,
     SimpleFeatureImpl.Attribute: desc<desc id=test.1>=String]