NRaf
NRaf

Reputation: 7559

Spring Data Mongo - Embed entities at the top-level

I have the following class (simplified example):

@Entity
public class Person {
  private PersonName personName;

  ...
}

@Embeddable
public class PersonName {
  private String name;
  ...
}

PersonName contains some validation and other information.

When I save Person to Mongo, PersonName is saved as:

{ 
  ... 
  "personName": { "name": "John Smith" },
  ...
}

Whilst I understand this behaviour makes sense in most cases, in this case, I'd prefer that it simply saved the name, ideally as "personName": "John Smith", rather than nesting the inner object.

Is there any way to achieve this (hopefully by adding an annotation)?

Upvotes: 0

Views: 138

Answers (1)

Christoph Strobl
Christoph Strobl

Reputation: 6736

You can always register custom converters for a specific type. Something like:

@WritingConverter
class PersonNameToStringConverter implements Converter<PersonName, String> {

    @Override
    public String convert(PersonName source) {
        return source.name;
    }
}

@ReadingConverter
class StringToPersonNameConverter implements Converter<String, PersonName> {

    @Override
    public PersonName convert(String source) {
        return new PersonName(source);
    }
}

Upvotes: 1

Related Questions