2

I have Entity (Course) and DTO (CourseDto) with spring boot as API server, backend as mongo

@Document(collection = "courses")
public class Course {
     @Id private ObjectId id;
     ....
}

public class CourseDto {
  private String id; 
  ....
}

I am using modelmapper to convert from CourseDto to Course and vise-versa. From Course id (ObjectId) to CourseDto id (String) conversion happens correctly (similar to course.getId().toHexString()). It gives me hexstring. But when I try to convert from CourseDto to Course (String id to ObjectId) then completely new ObjectId gets generated.

I know I can use converter but this is applicable thought out all my 50+ entity classes + also for deep nested objects. E.g. Course contains list of topics and each topic contains list of article Ids (List of ObjectId). According to my knowledge I can attach converted to specific model mapper (in this case to course model mapper)

I am mainly looking for generic solution where proper conversion from String to ObjectId would happen (new ObjectId(myString) ) and new ObjectId will not get created.

Thanks in advance

user2869612
  • 607
  • 2
  • 10
  • 32

1 Answers1

1

You have to use Converter because default it generate new Objectid instance.

Converter<String, ObjectId> toObjectId = new AbstractConverter<String, ObjectId>() {
    protected ObjectId convert(String source) {
        return source == null ? null : new ObjectId(source);
    }
};

This your converter and you should use typemap. Crete modelmapper bean like below.

@Bean
    public ModelMapper modelMapper() {

        Converter<String, ObjectId> toObjectId = new AbstractConverter<String, ObjectId>() {
            protected ObjectId convert(String source) {
                return source == null ? null : new ObjectId(source);
            }
        };

        TypeMap<EventMessageModel, Message> typeMap1 = modelMapper.createTypeMap(EventMessageModel.class, Message.class);
        typeMap1.addMappings(mapper -> {
             mapper.using(toObjectId)
            .map(EventMessageModel::getToUserId, Message::setToUserId);

             mapper.using(toObjectId)
            .map(EventMessageModel::getFromUserId, Message::setFromUserId);

        });

        return modelMapper;
    }

This is my implemantation. You should write by your implementation.

If in class all strings should map Objectid you can directly use like below

TypeMap<EventMessageModel, Message> typeMap1 = modelMapper.createTypeMap(EventMessageModel.class, Message.class);

typeMap1.setPropertyConverter(toObjectId);

This convert all string to Object id in class.

güven seckin
  • 99
  • 1
  • 4