如何在Spring JPA中读取PostGIS数据库的CIRCULARSTRING?
Spring JPA读取PostGIS中CIRCULARSTRING几何对象失败及插入超时问题
背景
在PostGIS数据库中存在一个CIRCULARSTRING(EWKT类型)几何对象,通过以下SQL语句插入:
INSERT INTO objectwithgeometries (id,geometry,remarks) VALUES ( 41, ST_SetSRID( ST_GeomFromEWKT( 'CIRCULARSTRING(29.8925 41.36667,29.628611 41.015000,29.27528 41.31667)'), 4326), 'remark-3');
插入后该几何对象在数据库中可正常可视化显示。
尝试1:Spring Data JPA Repository读取
调用postgisRepo.findAll()读取对象时,报错:
org.geolatte.geom.codec.WkbDecodeException: Unsupported WKB type code:8
查看WktDialect类发现仅支持标准7种WKB类型,不包含CircularString。
尝试2:JDBC直接读取
通过JDBC模板执行查询:
List<Map<String, Object>> objects = jdbcTemplate.queryForList( String.format( "select id,geometry,remarks from objectwithgeometries where id = %d", id)); objects.forEach( r -> { WKBReader wkbReader = new WKBReader(); PGobject geometryObject = (PGobject) r.get( "geometry"); byte[] geom = WKBReader.hexToBytes( geometryObject.getValue() ); try { log.info( "Geometry: {}", wkbReader.read(geom)); } catch (ParseException e) { throw new RuntimeException(e); } });
同样抛出异常:
org.locationtech.jts.io.ParseException: Unknown WKB type 8
Spring Boot 2/3版本(搭配Hibernate 5/6)均存在该问题。
尝试3:使用postgis-jdbc依赖的PGobject/PGGeometry
引入依赖:
<dependency> <groupId>net.postgis</groupId> <artifactId>postgis-jdbc</artifactId> <version>2023.1.0</version> </dependency>
但执行jdbcTemplate.queryForList()时仍报错:
Unknown Geometry Type: 8
尝试4:原生JDBC连接示例
编写独立JDBC连接代码:
Class.forName("org.postgresql.Driver"); String url = "jdbc:postgresql://localhost:5433/postgis"; conn = DriverManager.getConnection(url, "xyz", "abc"); ((org.postgresql.PGConnection)conn).addDataType("geometry", (Class<? extends PGobject>) Class.forName("net.postgis.jdbc.PGgeometry")); Statement s = conn.createStatement(); ResultSet r = s.executeQuery("select id,geometry,remarks from objectwithgeometries where id = 43"); while( r.next() ) { PGgeometry geom = (PGgeometry)r.getObject(2); int id = r.getInt(1); System.out.println("Row " + id + ":"); System.out.println(geom.toString()); } s.close(); conn.close();
依旧报错:
Unknown Geometry Type: 8
问题
- 如何在Spring JPA中读取该CIRCULARSTRING类型的几何对象?当前使用
org.hibernate.spatial.dialect.postgis.PostgisDialect处理几何数据。 - 通过Spring JPA执行上述插入语句时常出现连接超时问题,该如何解决?
内容的提问来源于stack exchange,提问作者tm1701
相关产品推荐
相关产品推荐

