Mittwoch, 9. Juli 2008

EJB3: PostGIS and Hibernate

Ever dreamed of container managed persistence for your PostGIS database? Here's one solution.

PostGIS is a spatial extension to the PostgreSQL database which adds support for geographic objects and operations. Because of these new database types special treatment is needed when defining your persistent unit and generating your entity beans.

First of all you have to download the hibernate spatial extension libraries hibernate-spatial-1.0-M1.jar and hibernate-spatial-postgis-1.0-M1.jar from http://www.hibernatespatial.org. Additionally the Java Transaction Service library jts-1.8.jar (http://www.vividsolutions.com) is needed. Put all these JAR-files to your JBoss lib folder.

When defining your persistence unit your have to register the new hibernate dialect org.hibernatespatial.postgis.PostgisDialect, e.g.:

<?xml version="1.0" encoding="UTF-8"?>
<persistence
        version="1.0"
        xmlns="http://java.sun.com/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
                http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd ">
    <persistence-unit name="SpacialDatabasePU" transaction-type="JTA">
        <jta-data-source>java:/SpatialDatabaseJNDIName</jta-data-source>                                                                                                                                                                                                              
        <properties>
            <property name="hibernate.dialect"
                    value="org.hibernatespatial.postgis.PostgisDialect"/>
        </properties>
    </persistence-unit>
</persistence>

After generating your entity beans you will recognize that all of the non-standard database types are mapped to Object and are annotated with @Lob. Replace the Object type by the actual needed spatial type, e.g. com.vividsolutions.jts.geom.Geometry, and annote them with their hibernate spatial pendant, e.g. @Type(type = "org.hibernatespatial.postgis.PGGeometryUserType"). Don't forgett to modify getters and setters accordingly.

... comment