Hibernate Spatial H2/GeoDB Grails Plugin
Dependency:
compile "org.grails.plugins:hibernate-spatial-hdb:0.0.4"
Summary
Installation
grails install-plugin hibernate-spatial-hdb
Description
Hibernate Spatial Provider for H2/GeoDB.It's a child plugin of hibernate-spatial.
For better instructions on how to create a spatially enabled database: H2/GeoDB Wiki.
Usage example
Install the plugin
grails install-plugin hibernate-spatial-hdb
Create a spatially enabled database
// BootStrap.groovy def dataSource def init = { servletContext -> try { def sql = new Sql(dataSource) sql.executeUpdate('CREATE ALIAS InitGeoDB for "geodb.GeoDB.InitGeoDB"') sql.executeUpdate('CALL InitGeoDB()') } catch (java.sql.SQLException e) { log.debug('', e) } // (...) }
Configure the corresponding JDBC Driver dependency in BuildConfig.groovy
dependencies { runtime 'com.h2database:h2:1.1.118' }
Change the JDBC URL in DataSource(s).groovy
url = 'jdbc:h2:file:devDB'
In your domain classes, define properties of the type com.vividsolutions.jts.geom.Geometry (or subclasses)
// Place.groovy package testimport com.vividsolutions.jts.geom.Pointclass Place { static mapping = { location /* H2/GeoDB bug or limitation? */ sqlType: 'blob' } String description Point location}
Perform some tests using save, dynamic finders, HQL and Criteria
//import com.vividsolutions.jts.geom.GeometryFactory //import com.vividsolutions.jts.geom.Coordinate //import org.hibernatespatial.criterion.SpatialRestrictions //import com.vividsolutions.jts.io.WKTReader Place.withNewTransaction { Place p = new Place() p.description = 'Desc' p.location = geometryFactory.createPoint(new Coordinate(5d, 5d)) p.save(failOnError: true, flush: true) } Place.withNewTransaction { println(Place.createCriteria() .add(SpatialRestrictions.within("location", reader.read('POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))'))) .list()) def filter = reader.read('POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))') Query q = Place.createQuery("from Place where within(location, ?) = true") q.setParameter(0, filter, GeometryUserType.TYPE) println (q.list()) }
DomainClass.withNewTransaction is available through transaction-handling.