I have an issue while mapping a dto to an entity with nested objects. Basically a "DayEntry" cotains many "SingleEntry" and each "SingleEntry" has a "Category". Here are my entities :
@Entity
public @Data class SingleEntry {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id ;
private float value ;
private boolean isInEntry= true;
@ManyToOne
@JoinColumn(nullable=false)
private Category category;
@ManyToOne
@JoinColumn(nullable=false)
private DayEntry dayEntry;
}
@Entity
public @Data class Category {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;
@Column(unique = true)
private String name;
private String color ="cc8282";
@OneToMany(mappedBy = "category")
//@JsonManagedReference
private List<SingleEntry> singleEntryList;
}
@Entity
public @Data class DayEntry {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;
@Column(nullable = false)
private LocalDate date;
@OneToMany(mappedBy = "dayEntry", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<SingleEntry> singleEntryList;
}
And this is the Dto i'm using :
public @Data class SingleEntryForCreationDto {
private float value ;
private boolean isInEntry;
private int categoryId;
private int dayEntryId;
}
I'm trying to create a new "SingleEntity" so that's why i have no "id" in the dto as it's going to be generated, but when i use model mapper :
modelMapper.map(singleEntryForCreationDto, SingleEntry.class)
it maps the "categoryId" to the "id" field of the entity "SingleEntry" like you can see in this example of logs :
********* dto == SingleEntryForCreationDto(value=50.0, isInEntry=false, categoryId=2, dayEntryId=1)
********* mapped dto == SingleEntry(id=2, value=50.0, isInEntry=false, category=Category(id=2, name=null, color=cc8282, singleEntryList=null), dayEntry=DayEntry(id=1, date=null, singleEntryList=null))
I looked at the documentation of Modelmapper and tried to change the NamingConventions and Transormation configuration but it didn't help. I must be missing something and i surely don't understand how Modelmapper really works as i couldn't fix it on my own.
I'd appreciate any help or suggestions.
******EDIT : I still don't understand why it mapped categoryId (SingleEntryForCreationDto) to id (SingleEntry). I resolved it this way for now
modelMapper.typeMap(SingleEntryForCreationDto.class,SingleEntry.class).addMappings(mapper -> mapper.skip(SingleEntry::setId));
I couldn't find why your configuration set the value of SingleEntry's id 2, but I think you'd better use explicit mapping.
You can skip any field in destination with PropertyMap configuration.
Explicit mappings example: no skipping but map() https://github.com/modelmapper/modelmapper/blob/master/examples/src/main/java/org/modelmapper/flattening/example2/FlatteningExample2.java
You can find how to use skip() in 'Skipping Properties' section in this link. http://modelmapper.org/javadoc/org/modelmapper/PropertyMap.html