GIS User Types in Hibernate and MySQL

MySQL has OpenGIS Spatial support built in now. We have been working on a project where latitudes, longitudes and distances are of great importance.

We chose MySQL for the OpenGIS support, but had yet to use it. We are using Hibernate (w/ annotations), and wanted to be able to save, retrieve and query against a MySQL GEOMETRY column. Here is a quick run-down as to what we did:

Custom GeometryUserType

We found some code written by Chris Wood, which extends the EnhancedUserType in Hibernate. There was a small error in the equals method, but I have attached our fixed version of the file in its entirety here if anyone wants to look at it.

Define the TypeDef

Again, we are using annotations, so we needed to add the following TypeDef block at the top of the class in which we are using this custom type:

@TypeDefs({
    @TypeDef(name="point", typeClass=GeometryUserType.class)
})

Annotate the Field using the Type

Below is the annotation we used to define our column and type:

@Column(name="centroid", columnDefinition="geometry") @Type(type="point")
    private Point centroid;

The name centroid is of course the name of the column in the database. The type point is the reference to the custom type. Now, we must specify the columnDefinition here, as the java.sql.Type returned by the GeometryUserType is java.sql.Type.BLOB. The columnDefinition of “geometry” is the MySQL column type that denotes the OpenGIS spatial types, and is what the HibernateTool uses to generate the schema.

The Point class is the class that is part of VividSolutions JTS, which is a subclass of Geometry, which GeometryUserType uses.

Querying the MySQL Geometry Column using Hibernate

I’ll throw a bunch of examples in here at some point. Certainly not the day before the long weekend…

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

One thought on “GIS User Types in Hibernate and MySQL

  1. Pingback: Hibernate | i-Proving –

Leave a Reply