How to correctly map a polygon type with postgis and hibernate-spatial?

Bravo picture Bravo · Jun 3, 2016 · Viewed 7.2k times · Source

Assume I have the following table

CREATE TABLE foo (
  id BIGSERIAL PRIMARY KEY, 
  polygon GEOMETRY(POLYGON)
);

and entity class

@Table
@Entity
public class Foo {

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

   private Polygon polygon;

}

I managed to save a Foo entity, however, I can't select it them from the database. I get this exception:

java.lang.NumberFormatException: For input string: "PO"

Then, I added the following annotation on top of polygon field:

@Type(type = "org.hibernate.spatial.JTSGeometryType")

but it throws another exception saying that this type cannot be instantiated:

org.hibernate.MappingException: Could not instantiate Type: org.hibernate.spatial.JTSGeometryType

Please note that I use 5.1.0.Final version for hibernate and hibernate-spatial.

Thank you

Answer

Sayo Oladeji picture Sayo Oladeji · Oct 21, 2016

It seems hibernate-spartial 5.x knows how to handle JTS geometrical types natively so no type annotation required. Here is my working configuration.

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-spatial</artifactId>
  <version>5.2.3.Final</version>
</dependency>

MySQL table...

CREATE TABLE `stuff` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `coordinates` point NOT NULL,
  PRIMARY KEY (`id`),
  SPATIAL KEY `coordinates` (`coordinates`)
)

JPA entity...

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

@Basic(optional = false)
@NotNull
@Column(nullable = false, columnDefinition = "point")
private Point coordinates;

Hibernate dialect...

<property name="hibernate.dialect" value="org.hibernate.spatial.dialect.mysql.MySQLSpatialDialect"/>

That's all but please note that my application runs within WildFly 10 which supplies additional runtime dependencies like the MySQL driver.