jeudi 22 juillet 2021

Change configurations depending on the environment in Spring

For years I programmed with the awesome Grails framework. One of it's elegant features is the possibility to define environment-specific configurations in your application.yml.

Example application.yml:

Moving to Spring Boot I was missing this feature until I found out how to do it in the documentation ( section 59.6) using Spring profiles.

Example application.yml:

vendredi 16 juillet 2021

Resolving NoClassDefException

In module A, an integration test was passing, in module B a similar test would fail with a NoClassDefException. Module A had a dependency on a module that B hadn't. Adding the missing dependency on module B fixed the issue.

mardi 13 juillet 2021

Configuring h2 with GIS

Using the H2 gis, I could make my integration tests work with h2, creating spatial queries with jpa.

  • Use the hiberante dialect org.hibernate.spatial.dialect.h2geodb.GeoDBDialect
  • Initialise the database by executing CREATE ALIAS IF NOT EXISTS H2GIS_SPATIAL FOR "org.h2gis.functions.factory.H2GISFunctions.load"; CALL H2GIS_SPATIAL(); You can wrap the query in a sql script and use @Sql(scripts = "/sql/h2_gis_initialization.sql") to execute it on your test class.
  • in maven, import h2 gis. Be aware that each version requires a specific version of h2

<!-- https://mvnrepository.com/artifact/org.orbisgis/h2gis -->
<dependency>
  <groupId>org.orbisgis</groupId>
  <artifactId>h2gis</artifactId>
  <version>${h2.gis.version}</version>
</dependency>
  • in your liquibase script, create the column with the GEOMETRY type:

<changeSet author="hschoonjans" id="create_table_localization_t">
  <createTable tableName="LOCALIZATION_T">
    <column name="ID" type="BIGINT">
      <constraints primaryKey="true"/>
    </column>
    <column name="geometry" type="GEOMETRY"/>
  </createTable>
</changeSet>
Run integration test:

    @Test
    void it_can_search_within_geometry() {
        final Polygon polygon = new GeometryFactory().createPolygon();
        List<Localization> results = repository.findAll(within(polygon));

        Assertions.assertEquals(0, results.size());
    }

    public static Specification<Localization> within(Geometry geometry) {
        return (root, query, builder) -> JTSSpatialPredicates.within(builder, root.get(Localization_.geometry), geometry);
    }