如何使用postgis和hibernate-spatial正确映射多边形类型?

Bra*_*avo 4 java postgresql hibernate postgis hibernate-spatial

假设我有下表

CREATE TABLE foo (
  id BIGSERIAL PRIMARY KEY, 
  polygon GEOMETRY(POLYGON)
);
Run Code Online (Sandbox Code Playgroud)

和实体类

@Table
@Entity
public class Foo {

   @Id
   @GeneratedValue(strategy = IDENTITY)
   private Long id;

   private Polygon polygon;

}
Run Code Online (Sandbox Code Playgroud)

我设法保存了一个Foo实体,但是,我无法从数据库中选择它们.我得到这个例外:

java.lang.NumberFormatException: For input string: "PO"
Run Code Online (Sandbox Code Playgroud)

然后,我在polygon字段顶部添加了以下注释:

@Type(type = "org.hibernate.spatial.JTSGeometryType")
Run Code Online (Sandbox Code Playgroud)

但它抛出另一个异常,说这种类型无法实例化:

org.hibernate.MappingException: Could not instantiate Type: org.hibernate.spatial.JTSGeometryType
Run Code Online (Sandbox Code Playgroud)

请注意,我使用5.1.0.Final版本用于hibernate和hibernate-spatial.

谢谢

Say*_*eji 7

它似乎hibernate-spartial 5.x知道如何本机处理JTS几何类型,因此不需要类型注释.这是我的工作配置.

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-spatial</artifactId>
  <version>5.2.3.Final</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

MySQL表...

CREATE TABLE `stuff` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `coordinates` point NOT NULL,
  PRIMARY KEY (`id`),
  SPATIAL KEY `coordinates` (`coordinates`)
)
Run Code Online (Sandbox Code Playgroud)

JPA实体......

import com.vividsolutions.jts.geom.Point;
...

@Basic(optional = false)
@NotNull
@Column(nullable = false, columnDefinition = "point")
private Point coordinates;
Run Code Online (Sandbox Code Playgroud)

Hibernate方言......

<property name="hibernate.dialect" value="org.hibernate.spatial.dialect.mysql.MySQLSpatialDialect"/>
Run Code Online (Sandbox Code Playgroud)

这就是请注意,我的应用程序在WildFly 10中运行,它提供了额外的运行时依赖性,如MySQL驱动程序.


Mr.*_*. P 1

您还应该尝试给出列名称

@Entity<br/>
@Table(name = "table_name")<br/>
public class Foo {<br/>

@Id
@GeneratedValue(strategy = IDENTITY)
private Long id;

@Type(type = "org.hibernate.spatial.GeometryType")
@Column(name = "the_geom", nullable = true,columnDefinition="Geometry")
 private Geometry geom;

@Type(type = "org.hibernate.spatial.GeometryType",columnDefinition="Geometry")
private Polygon polygon;
}
Run Code Online (Sandbox Code Playgroud)

您还应该注意,从 Hibernate Spatial 4.0-M1 开始,只有 Geometry 类型被指定给 Hibernate,因此 @Column 注释必须设置columnDefinition="Geometry",而不是 Point 或其他任何类型。这可能会在未来得到修复。

通过这一系列的修改,我终于可以将 Point 写入数据库了!正确的属性规范是:

 @Column(columnDefinition="Geometry")
 @Type(type = "org.hibernate.spatial.GeometryType")
 private Point centerPoint;
Run Code Online (Sandbox Code Playgroud)

还要检查hibernate.cfg.xml中的方言

将以下行添加到hibernate.cfg.xml

<property name="dialect">org.hibernate.spatial.dialect.postgis.PostgisDialect</property>
Run Code Online (Sandbox Code Playgroud)