Jmoney38
Jmoney38

Reputation: 3294

JPA - Mapping an Entity's field to a database function result

I'm using JPA 2.0. Is it possible to map an Entity's attribute (column) to the result of a function and then control the way it's persisted too?

Note: This is related to PostGIS. Since there is no native support for Geometry types in JPA/EclipseLink, I might do something like this:

@Entity
public class Foo {

   @Column(name="geom", appendBeforeChange( ST_FromKml ))
   public String kmlString;
}

In other words, I could store the geometry as a String in Java, but when EclipseLink writes it to the database, it should first call the database function ST_FromKml and provide the String, which will convert it to the Geometry type in the database...

I know it's a stretch, but figured I would ask...

Upvotes: 1

Views: 1728

Answers (1)

Jmoney38
Jmoney38

Reputation: 3294

I actually found a workaround with help from this post:

Are JPA (EclipseLink) custom types possible?

In Postgres, I create an implicit cast from String to Geometry:

CREATE OR REPLACE FUNCTION geom_in_text(varchar) RETURNS geometry AS $$
  SELECT ST_GeomFromText($1::varchar); 
$$ LANGUAGE SQL IMMUTABLE;

CREATE CAST (varchar AS geometry) WITH FUNCTION geom_in_text(varchar) AS IMPLICIT;

And now in Java, I just keep my Entity member variable as a String in WKT format. When Postgres see's the INSERT, it will recognize the avaiable implicit cast and not complain.

Note - I store WKT in my Entity class, but I could theoretically store KML and then update my function to call ST_GeomFromKml instead...

Upvotes: 2

Related Questions