【问题标题】:How to handle table column of type that is not known in Java (Spring Data)?如何处理Java(Spring Data)中未知类型的表列?
【发布时间】:2020-04-17 18:05:32
【问题描述】:

我有一个表,其中有一列类型为 geography(Point,4326)(使用 PostGIS)。 我只需要在查询表时在 WHERE 条件中使用该列。例如。在下面的查询中,geog 是该列的名称。

@Query(value = "SELECT pois.*\n" +
        "FROM pois,\n" +
        "(select ST_MakePoint(:lat,:lon)::geography as poi) as poi\n" +
        "WHERE ST_DWithin(geog, poi, 400)\n" +
        "ORDER BY ST_Distance(geog, poi)", nativeQuery = true)
public List<PointOfInterest> getPOIsAroundLocation(@Param("lat") double lat,
                                                   @Param("lon") double lon);

但是,在实体类PointOfInterest 中,我不知道如何映射该列,因为我没有与geography(Point,4326) 数据库类型等效的Java 类型。

如果我在课堂上根本不提该列,则不会在数据库中创建它(我有spring.jpa.hibernate.ddl-auto=create),并且查询会失败。

我能做什么?有没有办法创建一个 java 类型的列(可能是Object?),然后用一些注释将它映射到 db 类型?或者有没有办法告诉 Spring Data 关于 db 列而不实际添加我不会在类中使用的字段?

这是PointOfInterest 类:

@Data
@Entity(name = "pois")
public abstract class PointOfInterest {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private final double latitude;
    private final double longitude;
    private final PoiType poiType;

    public PointOfInterest() {
        this.latitude = this.longitude = 0;
        poiType = null;
    }

    public PointOfInterest(double latitude, double longitude, PoiType poiType) {
        this.latitude = latitude;
        this.longitude = longitude;
        this.poiType = poiType;
    }
}

【问题讨论】:

标签: java jpa spring-data-jpa postgis


【解决方案1】:

在我从@Pilosa 的评论中了解到 hibernate-spatial 之后,我添加了一些依赖项:

<dependency>
    <groupId>org.locationtech.jts</groupId>
    <artifactId>jts-core</artifactId>
    <version>1.16.1</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-spatial</artifactId>
    <version>5.4.10.Final</version>
</dependency>

我在 Entity 类中添加了一个org.locationtech.jts.geom.Point 字段来映射地理列。

@JsonIgnore
@Column(columnDefinition = "geography(Point,4326)")
private Point geog;

@JsonIgnore 注释是因为 jackson 在尝试反序列化字段时通过了堆栈溢出异常(参见相关的question)。这个解决方案对我有用,因为我只使用点进行查询,不需要它的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 2020-02-10
    • 2019-09-29
    相关资源
    最近更新 更多