I'm fairly new to Spring but I want to give it a try on this project. I have a MongoDB database populated with quite complexe documents. I want to use Spring data Mongo to query (no other CRUD operations) the database.
I already described my document entity using POJOs but some of them are abstract (see GeometryGeoJSON
is used to accept all type of GeoJson geometry, or Contact
that can be a Person
or an Organisation
. The link to the GitHub repo is provided below).
Having a test with that entity definition, a java.lang.InstantiationError
is thrown which fair since no Contructor are defined in those abstract classes.
Here is GitHub repository in case you need to have a look.
I feel a bit lost with all this but I'll have a more careful look at the documentation.
How would you face this issue ?
I'll answer my own question. As mentioned in the comments, the solution is to use
Converter
.Here is an example of what I intended to achieve with my class model :
A
Contact
can be either aPerson
or anOrganisation
.If you are using spring-data-mongodb MongoRepository to write data in your database according to your entity model, a
_class
field will be added to document roots and to complex property types (see this section). This fields store the fully qualified name of the Java class and it allows disambiguation when mapping from MongoDb Document to Spring data model.If your app just read document from the database (no
_class
fields), you need to tell Spring data which class to instantiate when mapping aContact
. Spring-data allows you to customize default type mapping behaviour usingConverter
. Using explicitConverter
override default mapping for the class. you need to explicitly map your entire class. Here is an example of my ContactReadConverter:Then, newly defined converters need to be registered:
Hope it helps.