Map Recursive Link Between Two Objects

13 views
Skip to first unread message

Collin Molnar

unread,
Oct 4, 2024, 5:52:53 PM10/4/24
to modelmapper
I'm trying to map a DTO to an Entity with a link to a list of parameters that links back to the entity. 

However, it creates a new Foo object in the FooParameter as the variable foo instead of setting foo to the same object that contains the List of FooParameters. 

I have tried, but this didn't do anything. 
ModelMapper fooMapper = new ModelMapper();
fooMapper.typeMap(FooDto.class, Foo.class).addMappings(map -> {
map.map(FooDto::getFooParameters, Foo::setParameters);
});

I think I have to use streams to point each parameter to the Foo object that holds them, but I'm not sure how to do this. 

Here is a simplified example of the two entity classes and DTOs. 

@Entity
public class Foo {
  @Id
  private Integer id;
  @OneToMany(fetch = FetchType.LAZY, mappedBy = "foo", cascade = CascadeType.ALL)
  private List<FooParameter> params;
}

@Entity
public class FooParameter {
  @EmbeddedId
  private FooParameterId cid;
  @ManyToOne(fetch = FetchType.LAZY, optional = false)
  private Foo foo;
  private String value; 
}

The DTOs are as follows

public class FooDto {
  private Integer id;
  private List<FooParameterDto> params;
}

public class FooParameterDto {
  private Integer fooId;
  private String value;
}
Reply all
Reply to author
Forward
0 new messages