折腾好几天,趟了几个坑,终于搞成了。废话不多说,直接上结果。
一、为了支持postgis,把Grails3默认的hibernate4改成hibernate5,添加jts支持地理信息,添加postgres-jdbc。这里不需要postgis的jdbc,这个搞了我好几天,最后发现去掉postgis的jdbc就OK了。
修改build.gradle
buildscript {
...
dependencies {
...
// classpath "org.grails.plugins:hibernate4:5.0.4"
classpath "org.grails.plugins:hibernate5:5.0.5"
}
}
dependencies {
...
// compile "org.grails.plugins:hibernate4"
// compile "org.hibernate:hibernate-ehcache"
compile "org.grails.plugins:hibernate5"
compile "org.hibernate:hibernate-core:5.1.0.Final"
compile "org.hibernate:hibernate-ehcache:5.1.0.Final"
compile 'org.hibernate:hibernate-entitymanager:5.1.0.Final'
compile 'org.hibernate:hibernate-spatial:5.1.0.Final'
compile 'com.vividsolutions:jts:1.12'
// runtime "com.h2database:h2"
runtime "org.postgresql:postgresql:9.4-1201-jdbc41"
}
修改application.yml
dataSource:
pooled: true
jmxExport: true
driverClassName: org.postgresql.Driver
dialect: org.hibernate.spatial.dialect.postgis.PostgisDialect
username: postgres
password:
environments:
development:
dataSource:
dbCreate: create-drop
url: jdbc:postgresql://localhost:5432/geoapi
修改driverClassName,添加dialect,修改dateSource.url
二、创建一个含有地理类的domain
package com.emg.api
import grails.rest.*
import org.grails.databinding.BindUsing
import com.vividsolutions.jts.geom.Point
import com.vividsolutions.jts.io.WKTReader
@Resource()
class Tbpoint {
String poiname
@BindUsing({obj, source ->
new WKTReader().read(source['poi'])
})
Point poi
static mapping = {
version false
}
}
@BindUsing是为了Data binding的时候能够正确处理jts类。还可以用其他方式,详见http://docs.grails.org/latest/guide/single.html#dataBinding
三、创建controller
package com.emg.api
import grails.rest.*
import static org.springframework.http.HttpStatus.*
class TbpointController extends RestfulController {
static responseFormats = ['json']
TbpointController() {
super(Tbpoint)
}
}
controller是默认的,只是去掉了xml的输出。
四、修改gson,以适应jts地理类的输出。
在目录grails-app/views/tbpoint/下写如下几个gson文件
1、_tbpoint.gson
import com.emg.api.Tbpoint
model {
Tbpoint tbpoint
}
json {
id tbpoint.id
poiname tbpoint.poiname
poi tbpoint.poi.toText()
}
主要是把地理类toText()输出
2、index.gson
import com.emg.api.Tbpoint
model {
Iterable<Tbpoint> tbpointList
}
json tmpl.tbpoint(tbpointList ?: [])
3、show.gson
import com.emg.api.Tbpoint
model {
Tbpoint tbpoint
}
json tmpl.tbpoint(tbpoint)
至此,Grails RESTful就可以使用postgis增删改查地理信息了。写的比较简略,主要用于记录。

本文介绍如何在Grails3应用中集成PostGIS进行地理信息处理,包括配置Hibernate5支持PostGIS、创建地理信息域类及控制器,并调整GSON以适配地理类输出。
837

被折叠的 条评论
为什么被折叠?



