2

I am new on backend side and I want to use modelmapper on my project. I know how can I use modelmapper on basic level.

There is my Entity classes:

public class Content {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false, unique = true)
    private int id;

    @ManyToOne
    @JsonIgnore
    @JoinColumn(name = "userId",
            referencedColumnName = "userId",
            foreignKey = @ForeignKey(name = "fk_content_userId"))
    private User user;
    
    @Column(name = "title")
    private String title;
    
    @Column(name = "createdDate")
    private Double createdDate;
}
public class User {
    @Id
    @Column(name = "userId", nullable = false, unique = true)
    private String userId;

    @Column(name = "name")
    private String name;
    
    @Column(name = "phoneNumber")
    private String phoneNumber;
    
    @Column(name = "email")
    private String email;
}

And there is my response class:

public class Response {
    private String title;
    private Double createdDate;
    private String userId;
}

So what I want?

There is API's body:

response: {
    "title": "title",
    "createdDate": "1616758604",
    "userId": "101010"
}

I want to convert this response to following:

Content: {
    "title": "title",
    "createdDate": "1616758604",
    "User" : {
        "userId" : "101010"
        "name" : "",
        "phoneNumber" : "",
        "email" : ""
    }
}

NOTE: I wrote "Content" in JSON format in the end. But I need it in JAVA.

Gokhan
  • 41
  • 4

1 Answers1

1

If I understood your question right, your problem is to convert the userId to the respective user and want to use the ModelMapper Library. Therefore you can use the provided converter class. I used your example, added getters/setters and created a ModelMapper instance that converts the Response to a Content object (see below).

// First some sample data
User user = new User();
user.userId = "abc";
user.name = "name";
user.email = "mail";

var response = new Response();
response.createdDate = 112390582.;
response.title = "titel";
response.userId = "abc";

// Mock user db
Map<String, User> users = Map.of(user.userId, user);

// The ModelMapper
var mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
Converter<String, User> conv = (in) -> in.getSource() == null ? null : users.get(in.getSource());

mapper.createTypeMap(Response.class, Content.class)
            .addMappings(mapping -> mapping.using(conv).map(Response::getUserId, Content::setUser));

// Mapping
Content content = mapper.map(response, Content.class);