Make spatial4j Serializable
gmantele opened this issue · 3 comments
I am using spatial4j-0.6 in order to have spherical geometry capability in an H2 database. I have done that easily thanks to a simple short class.
It works fine when I have to build (and eventually to store into the database) shapes (e.g. point, circle) and to apply constraints (e.g. intersects, contains) on them. The only problem I have is when trying to read a such shape (i.e. org.locationtech.spatial4j.shape.Shape
) though a JDBC driver using a SELECT
clause. I immediately get the following exception:
Serialization failed, cause: "java.io.NotSerializableException: org.locationtech.spatial4j.shape.impl.PointImpl"
I successfully fixed this issue by making the following classes/interfaces implementing java.io.Serializable
:
- org.locationtech.spatial4j.context.SpatialContext
- org.locationtech.spatial4j.distance.DistanceCalculator
- org.locationtech.spatial4j.io.BinaryCodec
- org.locationtech.spatial4j.io.ShapeIO
- org.locationtech.spatial4j.io.SupportedFormats
- org.locationtech.spatial4j.shape.Shape
- org.locationtech.spatial4j.shape.ShapeFactory
Note: After some experimentations it turns out that not only org.locationtech.spatial4j.shape.Shape
must be Serializable
; hence all these above classes/interfaces.
So, now I have my own version of spatial4j which is the only one able to work with H2, and that is quite a problem if anybody else wants to use H2+spatial4j. In order to prevent that, would it be possible to apply these harmless modifications to the official spatial4j? (I can submit a Pull Request if needed)
I think it's fine for Shape to be serializable. But SpatialContext and all that's attached to it... I dunno; that part seems weird. But I see why you're asking -- Shape references the context. If there was a setter for the SpatialContext instead, plus serializable code that doesn't save the context, would that work/make-sense?
Did you consider using a codec (e.g. binary, GeoJSON, or WKT etc.) instead of serializability?
Yes, it seems a better solution. Especially since I unearth a solution of mine to this serialization issue. It turns out that I also serialized the Shape
as an Object[]
; and it works as a charm.
At that time, I did not know about codecs in spatial4j. So, I think that now I will use a BinaryCodec
combined with the JavaObjectSerializer
of H2. And if it does not work, I still have my home-made serialization solution, but I doubt it will be needed.
Thank you for your advice :) and sorry to have bothered you with this meaningless issue.
Using BinaryCodec definitely seems like the right path. It's no trouble to bother me/us here ;-P this is why GH issues exist.