I'm looking for a way to implement some generic way (typemap / any other) that would allow me to map a certain object type into separated attributes when mapping DTO to Entity.
Some basic info - I have an IdName class that looks like this:
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class IdName implements Serializable {
@NonNull private Long id;
@NonNull private String name;
}
Now I have many DTO's, that will have an IdName representation of a certain field - f.ex.
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Book implements Serializable {
private String title;
private IdName author;
}
or:
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Movie implements Serializable {
private String title;
private IdName director;
}
What I'm looking for now is a way to say to model mapper: Every time you want to map any IdName to Long/String - use Id or Name correspondingly (and vice versa). That would allow me to keep my automated mapping using modelMapper to convert between request DTO (only accepting ID's f.ex.), DAO entity (still relying only on ID's), and response DTO (returning both ID and name).
Normally I could introduce a typeMap from IdName to Long/String and vice versa. The problem here is that modelmapper still requires the attributes to be named the same way, whilst in my case there would be a diff - one would be f.ex. authorId
and the IdName object in the response would be author
.
So I'm looking for a nice way to configure modelMapper to always attempt to map IdName attributes to their corresponding attribute name + Id
and attribute name + Name
.
Based on the above example DTO's, let's assume I have also DAO entities like the following:
@Entity
@Table(name = "movies")
@Getter
@Setter
public class MovieEntity {
private String title;
private Long directorId;
}
and
@Entity
@Table(name = "books")
@Getter
@Setter
public class BookEntity {
private String title;
private Long authorId;
}
Each time I request a BookDto
/MovieDto
to be mapped to BookEntity
/MovieEntity
ideally I'd like model mapper to:
- if it's an
IdName
object, get the attribute name and try to map the Id to attribute name + Id (in the example of Books -author
of typeIdName
would try to map id (Long) toauthorId
and name (String) toauthorName
on the target object.
So basically I'm looking for a way to provide a certain TypeMap (in this case IdName<->Long
and IdName<->String
), but in the mean time allowing 'lean' mapping based on the attribute names.
I would be able to introduce some overhead map of possible IdName object like authors, directors, ... so I can predefine to modelmapper which IdName fields should be translatable to flattened Id/Name attributes instead.
I would prefer not to have to define this for each class type separately though, rather have a way of saying f.ex. - for each author
field of type IdName
attempt to perform that mapping, regardless of the class that holds the author
field