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实现终端清屏的几种方式详解

《Python实现终端清屏的几种方式详解》在使用Python进行终端交互式编程时,我们经常需要清空当前终端屏幕的内容,本文为大家整理了几种常见的实现方法,有需要的小伙伴可以参考下... 目录方法一:使用 `os` 模块调用系统命令方法二:使用 `subprocess` 模块执行命令方法三:打印多个换行符模拟

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF

Python实现MQTT通信的示例代码

《Python实现MQTT通信的示例代码》本文主要介绍了Python实现MQTT通信的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 安装paho-mqtt库‌2. 搭建MQTT代理服务器(Broker)‌‌3. pytho

使用zip4j实现Java中的ZIP文件加密压缩的操作方法

《使用zip4j实现Java中的ZIP文件加密压缩的操作方法》本文介绍如何通过Maven集成zip4j1.3.2库创建带密码保护的ZIP文件,涵盖依赖配置、代码示例及加密原理,确保数据安全性,感兴趣的... 目录1. zip4j库介绍和版本1.1 zip4j库概述1.2 zip4j的版本演变1.3 zip4

python生成随机唯一id的几种实现方法

《python生成随机唯一id的几种实现方法》在Python中生成随机唯一ID有多种方法,根据不同的需求场景可以选择最适合的方案,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习... 目录方法 1:使用 UUID 模块(推荐)方法 2:使用 Secrets 模块(安全敏感场景)方法

MyBatis-Plus通用中等、大量数据分批查询和处理方法

《MyBatis-Plus通用中等、大量数据分批查询和处理方法》文章介绍MyBatis-Plus分页查询处理,通过函数式接口与Lambda表达式实现通用逻辑,方法抽象但功能强大,建议扩展分批处理及流式... 目录函数式接口获取分页数据接口数据处理接口通用逻辑工具类使用方法简单查询自定义查询方法总结函数式接口

MySql基本查询之表的增删查改+聚合函数案例详解

《MySql基本查询之表的增删查改+聚合函数案例详解》本文详解SQL的CURD操作INSERT用于数据插入(单行/多行及冲突处理),SELECT实现数据检索(列选择、条件过滤、排序分页),UPDATE... 目录一、Create1.1 单行数据 + 全列插入1.2 多行数据 + 指定列插入1.3 插入否则更

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.