【问题标题】:How to use Spatial Type in Grails4 / GORM7?如何在 Grails 4 / GORM 7 中使用空间类型?
【发布时间】:2020-06-12 08:38:04
【问题描述】:

如何在 GORM7 中对空间类型属性进行建模,以及如何像其他普通类型(如字符串/日期/数字等)一样查询这些空间属性。

Hibernate support spatial types 通过引入特定的方言和类如“MySQLSpatialDialect”和“com.vividsolutions.jts.geom.Point”。

我为 grails-v1/v2 找到了一些 plugins,但它不适用于 grails4。

如果我必须编写一个插件来执行此操作,我该如何启动它?

【问题讨论】:

    标签: grails grails-orm spatial


    【解决方案1】:

    都在盒子里面,但是你需要配置一下!

    创建您的定义表。请注意,如果您自动创建,mysql 可能不会为该位置选择正确的数据类型。

    create table book (id bigint auto_increment primary key, version bigint, title varchar(255), location point)
    

    在你的application.yml中,你需要添加正确的方言:

    dataSource:
        dialect: org.hibernate.spatial.dialect.mysql.MySQLSpatialDialect
        ...etc
    

    到你的 build.gradle(注意,vividsolutions 改名为 locationtech):

        compile "org.locationtech.jts:jts-core:1.18.1"
        runtime "org.hibernate:hibernate-spatial:5.5.2.Final"
        runtime 'mysql:mysql-connector-java:8.0.18'
    

    使用几何字段创建域类:

    import org.locationtech.jts.geom.Point
    class Book {
    
      String title 
      Point location
    
    }
    

    为您的图书创建服务:

    import grails.gorm.services.Service
    import org.locationtech.jts.geom.Point
    @Service(Book)
    interface BookService {
        Book save(String title, Point location)
    }
    

    创建一些虚拟数据:

    import org.locationtech.jts.io.WKTReader
    import org.locationtech.jts.geom.Point
    
    Book book = bookService.save('Test', (Point)new WKTReader().read("POINT (0 1)"))
    

    根据某个多边形测试您的图书位置:

    
    import org.locationtech.jts.io.WKTReader
    
    class Controller {
    
        def sessionFactory
    
        @ReadOnly
        def index() {
            
        def q = new WKTReader()
        def filter = q.read('POLYGON ((0 0, 0 10, 10 10, 10 0, 0 0))')
    
        def session2 = sessionFactory.currentSession
        def queryParams = [:]
        queryParams.loc = filter
    
        List<Book> results = new ArrayList<>()
       
        def query =
        """
        select b from Book b 
        where st_within(b.location, :loc) = true  
        """
    
        results = Book.executeQuery(query, queryParams)
        println(results)
        }
    
    }
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      • 2015-01-16
      相关资源
      最近更新 更多