简体   繁体   English

JPA-将实体的字段映射到数据库功能结果

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

I'm using JPA 2.0. 我正在使用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. 注意:这与PostGIS有关。 Since there is no native support for Geometry types in JPA/EclipseLink, I might do something like this: 由于JPA / EclipseLink中没有对Geometry类型的本机支持,因此我可以这样做:

@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... 换句话说,我可以将几何图形存储为Java中的字符串,但是当EclipseLink将其写入数据库时​​,它应该首先调用数据库函数ST_FromKml并提供字符串,该字符串会将其转换为数据库中的几何类型。 。

I know it's a stretch, but figured I would ask... 我知道这很麻烦,但我想问一下...

I actually found a workaround with help from this post: 实际上,我在这篇文章的帮助下找到了一种解决方法:

Are JPA (EclipseLink) custom types possible? JPA(EclipseLink)定制类型是否可能?

In Postgres, I create an implicit cast from String to Geometry: 在Postgres中,我创建了一个从String到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. 现在在Java中,我只是将Entity成员变量保留为WKT格式的字符串。 When Postgres see's the INSERT, it will recognize the avaiable implicit cast and not complain. 当Postgres看到INSERT时,它将识别可用的隐式强制类型转换而不会抱怨。

Note - I store WKT in my Entity class, but I could theoretically store KML and then update my function to call ST_GeomFromKml instead... 注意-我将WKT存储在我的Entity类中,但是理论上我可以存储KML,然后更新我的函数以调用ST_GeomFromKml ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM