[SOLVED] org.springframework.data.mapping.MappingException: Ambiguous field mapping detected

Issue

This Content is from Stack Overflow. Question asked by NeverSleeps

Due to the fact that I’m using an abstract class, I get such error:

org.springframework.data.mapping.MappingException: Ambiguous field mapping detected! 
Both private final com.life.book.domain.event.EventType com.life.book.domain.command.ObjectCommand.eventType 
and private final com.life.book.domain.event.EventType com.life.book.domain.command.UpdateObjectCommand.eventType 
map to the same field name eventType! Disambiguate using @Field annotation!

My classes:

abstract class ObjectCommand(
    open var eventType: EventType?
)

@Document(collection = "COMMAND")
data class UpdateObjectCommand(
    val description: String?,
    override var eventType: EventType?
) : ObjectCommand(eventType)

enum class EventType {
    CREATED, UPDATED
}

The solution might be to use a different name instead of the eventType name in the UpdateObjectCommand class. But then the database will have two fields with the same purpose. Maybe there is another way?

There is Disambiguate using @Field annotation in the description of the error, but I don’t understand how to use it.



Solution

It’s been a sec since I have delt with what looks like Mongo DB and Spring Boot (I could be off base here). The @Field annotation is applied to fields in your class that have the @Document annotation.

You can add information to the @Field annotation like the serialized name of the field, or if its written when null. @Field in most cases does not need to be applied to a field unless you are dealing with enums. Mongo does not know how to store an enum, so you must add the @Field annotation to specify that it needs to be stored as a string.

https://blog.tericcabrel.com/using-mongodb-with-spring-boot-project-part-1/

From tericcabrel.com:

@Field is used to enhance the property by changing the type; like our case, MongoDB doesn’t support Enum, so we need to tell Mongo to store this property’s value as a string. When retrieving the data from the collection, the value will be returned back as an Enum. You can also provide a different name for the property in MongoDB.


This Question was asked in StackOverflow by NeverSleeps and Answered by Tyler It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?