jpa + hibernate-spatial + postgis实现简单的空间范围查询

2024-04-01 16:12

本文主要是介绍jpa + hibernate-spatial + postgis实现简单的空间范围查询,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

jpa 也能直接写原生sql,原生sql,直接写postgis的函数,不多说

@Query(value = "select t from DemoPointDO t where st_contains(:polygon, t.point) is true", nativeQuery = true)
List<DemoPointDO> containsQuery1(@Param("polygon") Polygon polygon);

现在说两种不写原生sql去调用postgis的函数,这里以一个空间返回查询为例,查询该矩形里面的所有点。
一个最简单的表,id + 名称 + 空间点位

create table demo_point (point_id varchar(36) not null primary key,point_name varchar(32) not null,location geometry
);

spring cloud、alibaba cloud版本和Spring boot版本如下

        <spring-cloud.version>2021.0.5</spring-cloud.version><spring-boot.version>2.7.6</spring-boot.version><alibaba-cloud.version>2021.0.5.0</alibaba-cloud.version>

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>com.lutuo.iot</groupId><artifactId>ltb-iot-equipment</artifactId><version>1.0.0-SNAPSHOT</version></parent><artifactId>demo-spatial</artifactId><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-spatial</artifactId></dependency><dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency><dependency><groupId>com.lutuo.jpa.plugin</groupId><artifactId>lutuo-jpa-plugin</artifactId></dependency><dependency><groupId>com.graphhopper.external</groupId><artifactId>jackson-datatype-jts</artifactId><version>2.14</version></dependency></dependencies></project>

实体类定义,这里这个Point是JTS里面的那个

@Data
@Entity
@Table(name = "demo_point")
public class DemoPointDO {/** uuid-36 */@Id@GenericGenerator(name = "uuid", strategy = "com.lutuo.jpa.plugin.config.CustomerUuidGenerator")@GeneratedValue(generator = "uuid")@Column(length = 36)private String pointId;@Column(length = 32)private String pointName;/*** 注意这里:columnDefinition = "geometry"* 这里指定了jackson的序列化和反序列化器*/@Column(name = "location", columnDefinition = "geometry")@JsonDeserialize(using = GeometryDeserializer.class)@JsonSerialize(using = GeometrySerializer.class)private Point point;
}

repository接口

public interface DemoPointRepository extends JpaRepository<DemoPointDO, String>, JpaSpecificationExecutor<DemoPointDO> {/** 空间返回查询方式一 */@Query("select t from DemoPointDO t where st_contains(:polygon, t.point) is true")List<DemoPointDO> containsQuery(@Param("polygon") Polygon polygon);@Query(value = "select t from demo_point t where st_contains(:polygon, t.location) is true", nativeQuery = true)List<DemoPointDO> containsQuery1(@Param("polygon") Polygon polygon);}

单元测试,demo里面没有加回滚

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpatialApplication.class)
public class DemoPointRepositoryTest {private DemoPointRepository demoPointRepository;@Testpublic void findAllTest() {List<DemoPointDO> list = demoPointRepository.findAll();assertNotNull("查询结果为空", list);}/** 保存一条数据 */@Testpublic void saveTest() {DemoPointDO pointDO = new DemoPointDO();pointDO.setPointName("点位2");GeometryFactory geometryFactory = new GeometryFactory();Point point = geometryFactory.createPoint(new Coordinate(130.40180135416841035156, 33.015156103111531));pointDO.setPoint(point);DemoPointDO save = demoPointRepository.save(pointDO);assertNotNull("保存结果为空", save);}/*** 方式一:repositor直接定义方法,并写@Query(),注意:st_contains返回值本来是bool,理论上可以不加is true,但是这里不加会出现语法错误。* 原生sql,这里返回的是true:SELECT  st_contains(ST_GeomFromText('POLYGON((-180 90, 180 90, 180 -90, -180 -90, -180 90))'),ST_GeomFromText('POINT(132.3416515 32.156135)'));*/@Testpublic void containsQueryTest() throws Exception {GeometryFactory geometryFactory = new GeometryFactory();Coordinate[] coordinates = new Coordinate[5];// -180 90, 180 90, 180 -90, -180 -90, -180 90coordinates[0] = new Coordinate(-180, 90);coordinates[1] = new Coordinate(180, 90);coordinates[2] = new Coordinate(180, -90);coordinates[3] = new Coordinate(-180, -90);coordinates[4] = new Coordinate(-180, 90);Polygon polygon = geometryFactory.createPolygon(coordinates);List<DemoPointDO> list = demoPointRepository.containsQuery(polygon);assertNotNull("查询结果为空", list);ObjectMapper objectMapper = new ObjectMapper();for (DemoPointDO pointDO : list) {System.out.println(objectMapper.writeValueAsString(pointDO));}}/*** 方式二:repository继承JpaSpecificationExecutor,调用List<T> findAll(@Nullable Specification<T> spec);* 这里的重点是如何构建Specification对象,这里用于动态构建sql的情况*/@Testpublic void findAll1Test() throws JsonProcessingException {GeometryFactory geometryFactory = new GeometryFactory();Coordinate[] coordinates = new Coordinate[5];// -180 90, 180 90, 180 -90, -180 -90, -180 90coordinates[0] = new Coordinate(-180, 90);coordinates[1] = new Coordinate(180, 90);coordinates[2] = new Coordinate(180, -90);coordinates[3] = new Coordinate(-180, -90);coordinates[4] = new Coordinate(-180, 90);Polygon polygon = geometryFactory.createPolygon(coordinates);Specification<DemoPointDO> specification = (root, query, criteriaBuilder) -> {return criteriaBuilder.isTrue(criteriaBuilder.function("st_contains", Boolean.class, criteriaBuilder.literal(polygon), root.get("point")));};List<DemoPointDO> list = demoPointRepository.findAll(specification);assertNotNull("查询结果为空", list);ObjectMapper objectMapper = new ObjectMapper();for (DemoPointDO pointDO : list) {System.out.println(objectMapper.writeValueAsString(pointDO));}}@Autowiredpublic void setDemoPointRepository(DemoPointRepository demoPointRepository) {this.demoPointRepository = demoPointRepository;}}

这篇关于jpa + hibernate-spatial + postgis实现简单的空间范围查询的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/867593

相关文章

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

C++11范围for初始化列表auto decltype详解

《C++11范围for初始化列表autodecltype详解》C++11引入auto类型推导、decltype类型推断、统一列表初始化、范围for循环及智能指针,提升代码简洁性、类型安全与资源管理效... 目录C++11新特性1. 自动类型推导auto1.1 基本语法2. decltype3. 列表初始化3

解密SQL查询语句执行的过程

《解密SQL查询语句执行的过程》文章讲解了SQL语句的执行流程,涵盖解析、优化、执行三个核心阶段,并介绍执行计划查看方法EXPLAIN,同时提出性能优化技巧如合理使用索引、避免SELECT*、JOIN... 目录1. SQL语句的基本结构2. SQL语句的执行过程3. SQL语句的执行计划4. 常见的性能优

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、

PyCharm中配置PyQt的实现步骤

《PyCharm中配置PyQt的实现步骤》PyCharm是JetBrains推出的一款强大的PythonIDE,结合PyQt可以进行pythion高效开发桌面GUI应用程序,本文就来介绍一下PyCha... 目录1. 安装China编程PyQt1.PyQt 核心组件2. 基础 PyQt 应用程序结构3. 使用 Q

Linux系统中查询JDK安装目录的几种常用方法

《Linux系统中查询JDK安装目录的几种常用方法》:本文主要介绍Linux系统中查询JDK安装目录的几种常用方法,方法分别是通过update-alternatives、Java命令、环境变量及目... 目录方法 1:通过update-alternatives查询(推荐)方法 2:检查所有已安装的 JDK方