MongoDB查询含2dsphere索引实体报PersistentEntity错误的解决方法
背景配置
已在MongoDB中创建对应空间索引,实体类内location字段初始定义如下:
@Indexed(name = "2dsphere") private Point location;
MongoDB中该字段的实际存储结构如下:
"location": { "type": "Point", "coordinates": [ 41.035137, 28.98953 ] }
问题现象
调用repository.findById(id).orElse(null)从MongoDB查询目标实体时抛出异常,异常信息如下:
Expected to read Document Document{{type=Point, coordinates=[41.015137, 28.97953]}} into type class com.mongodb.client.model.geojson.Point but didn't find a PersistentEntity for the latter!
故障原因
报错核心是两处配置错误:
- 字段使用的
Point类导包错误,导入了MongoDB驱动原生的com.mongodb.client.model.geojson.Point,Spring Data MongoDB没有为该类注册对应的持久化实体映射,无法完成自动反序列化 - 2dsphere索引注解写法错误,
@Indexed(name = "2dsphere")是将索引名设置为"2dsphere",没有正确声明空间索引类型
修复方案
- 替换location字段的Point类导包,删除原有
com.mongodb.client.model.geojson.Point的导入,改为导入Spring Data MongoDB提供的GeoJSON类型:org.springframework.data.mongodb.core.geo.GeoJsonPoint - 修正空间索引注解,将原有的
@Indexed替换为专门的空间索引注解,正确声明2dsphere索引类型,修正后的字段定义如下:
@GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE) private GeoJsonPoint location;
- 存量MongoDB中存储的GeoJSON结构不需要做任何修改,Spring Data MongoDB会自动完成
GeoJsonPoint与库表存储结构的序列化、反序列化映射,重启应用后再调用findById等Repository查询方法即可正常返回结果,不会再抛出PersistentEntity相关异常。
注意:构造
GeoJsonPoint对象时参数顺序为经度在前、纬度在后,与库中coordinates数组的存储顺序保持一致,避免传参顺序错误导致坐标偏移。
内容的提问来源于stack exchange,提问作者halil baydar
相关产品推荐
相关产品推荐

