I am using Mapstruct (1.2.0.Final) to map dto objects where I'd like to extract an attribute of an object to its own object instance.
Here is a simplified example:
#Data
public class ExternalResult {
#JsonProperty("items")
List<Item> items;
}
#Data
public class MyItem {
String name;
}
Now I'd like to extract the items from ExternalResult and have them mapped to a list of MyItems. Here is my Mapper and I don't know what to use in as target:
#Mapper(componentModel = "spring")
public interface GraphhopperMapper {
#Mappings({
#Mapping(target = "??", source="items")
})
List<MyItem> mapItems(ExternalResult externalResult);
}
How can this be achieved? Or is there a more convenient way to get rid of the (useless) object with only one attribute?
Thanks in advance.
It's one of the cases where I'd recommend to just implement the method yourself (e.g. by making the mapper an abstract class) instead of trying to let MapStruct do it for you:
List<MyItem> mapItems(ExternalResult externalResult) {
return externalResult.getItems()
.stream()
.map(i -> new MyItem(i.getName())
.collect(Collectors.toList());
}
MapStruct idea is to help you automate the 90% of trivial mappings but let you hand-write the remaining more special cases like this.
Related
I would like MapStruct to map every property of my Object, except for one particular one for which I would like to provide a custom mapping.
So far, I implemented the whole mapper myself, but every time I add a new property to my Entity, I forget to update the mapper.
#Mapper(componentModel = "cdi")
public interface MyMapper {
MyMapper INSTANCE = Mappers.getMapper(MyMapper.class);
default MyDto toDTO(MyEntity myEntity){
MyDto dto = new MyDto();
dto.field1 = myEntity.field1;
// [...]
dto.fieldN = myEntity.fieldN;
// Custom mapping here resulting in a Map<> map
dto.fieldRequiringCustomMapping = map;
}
}
Is there a way to outsource the mapping for my field fieldRequiringCustomMapping and tell MapStruct to map all the other ones like usual? 🤔
MapStruct has a way to use custom mapping between some fields. So in your case you can do someting like:
#Mapper(componentModel = "cdi")
public interface MyMapper {
#Mapping(target = "fieldRequiringCustomMapping", qualifiedByName = "customFieldMapping")
MyDto toDTO(MyEntity myEntity);
// The #(org.mapstruct.)Named is only needed if the Return and Target type are not unique
#Named("customFieldMapping")
default FieldRequiringCustomMapping customMapping(SourceForFieldRequiringCustomMapping source) {
// Custom mapping here resulting in a Map<> map
return map
}
}
I do not know from what your fieldRequiringCustomMapping needs to be mapped, the example assumes that you have such a field in MyEntity as well, if that is not the case you'll need to add source to the #Mapping.
Side Note: When using a non default componentModel in your case cdi it is not recommended to use the Mappers factory. It will not perform the injection of other mappers in case you use them in a mapper.
I recently started using the MapStruct mapping tool in a project. In the past, for mapping DTO -> Entity and vice versa I used custom mapper like:
public static CustomerDto toDto(Customer customer) {
return isNull(customer)
? null
: CustomerDto.builder()
.id(customer.getId())
.name(customer.getName())
.surname(customer.getSurname())
.phoneNumber(customer.getPhoneNumber())
.email(customer.getEmail())
.customerStatus(customer.getCustomerStatus())
.username(customer.getUsername())
.NIP(customer.getNIP())
.build();
}
In case when I was trying to get one single Optional object after all I was able to map my entity to dto in the following way:
public Optional<CustomerDto> findOneById(final long id) {
return customerRepository.findById(id).map(CustomerMapper::toDto);
}
Currently, as I mentioned before I am using mapStruct and the problem is that my mapper it's, not class, it's the interface like:
#Mapper
public interface CommentMapper {
#Mappings({
#Mapping(target = "content", source = "entity.content"),
#Mapping(target = "user", source = "entity.user")
})
CommentDto commentToCommentDto(Comment entity);
#Mappings({
#Mapping(target = "content", source = "dto.content"),
#Mapping(target = "user", source = "dto.user")
})
Comment commentDtoToComment(CommentDto dto);
}
I want to know if it possible to use somehow this interface method in stream gentle to map my value without wrapping values like:
public Optional<CommentDto> findCommentById(final long id) {
Optional<Comment> commentById = commentRepository.findById(id);
return Optional.ofNullable(commentMapper.commentToCommentDto(commentById.get()));
}
Thanks for any help.
Access the mapper like:
private static final YourMapper MAPPER = Mappers.getMapper(YourMapper.class);
final Optional<YourEntity> optEntity = entityRepo.findById(id);
return optEntity.map(MAPPER::toDto).orElse(null);
Basically we do a similar thing with enumerations
#Mapping(target = "type", expression = "java(EnumerationType.valueOf(entity.getType()))")
you can define java expressions in your #Mapping annotation
#Mapping(target = "comment", expression = "java(commentMapper.commentToCommentDto(commentRepository.findById(entity.commentId).orElse(null)))"
Otherwise you should be able to make use of a
class CommentMapper { ... }
which you automatically can refer with
#Mapper(uses = {CommentMapper.class})
your implementation will detect the commentEntity and Dto and will automatically use the CommentMapper.
A MapStruct mapper is workling like: Shit in Shit out, so remember your entity needs the commentEntity so the dto can has the commentDto.
EDIT
2nd solution could be using:
#BeforeMapping
default void beforeMappingToDTO(Entity source, #MappingTarget Dto target) {
target.setComment(commentMapper.commentToCommentDto(commentRepository.findById(entity.commentId).orElse(null)));
}
#Spektakulatius answer solved a problem.
To reach a goal I made a few steps:
First of all, I created an object of my mapper to use it in a java stream:
private CommentMapper commentMapper = Mappers.getMapper(CommentMapper.class);
In the last step I used my object commentMapper like:
public Optional<CommentDto> findCommentById(final long id) {
return commentRepository.findById(id).map(CommentMapper.MAPPER::commentToCommentDto);
}
After all that completely gave me a possibility to use my custom MapStruct mapper in stream.
I am trying to use Mapstruct to map source object to a target list. What should be a clean mapstruct way of doing this?
Below are my DTO's.
Source DTO
#Data
class Source
{
String a;
String b;
String C;
}
Target DTO
#Data
class Target
{
String name;
List<Child> customList;
}
#Data
class Child
{
String attr1;
boolean attr2;
}
I am facing issues with Mapper Class. Trying to achieve something like below.
public interface CustomMapper
{
#Mapper(target="customList" expression="java(new Child(a,false))"
#Mapper(target="customList" expression="java(new Child(b,true))"
#Mapper(target="customList" expression="java(new Child(c,false))"
Target sourceToTarget(Source source);
}
I don't want to use qualifiedBy function like below to achieve this, as all conversion needs to be coded for each element.
List<Child> toList(Source source)
{
List<Child> customList = new ArrayList<Child>();
customList.add(new Child(source.getA(),false));
customList.add(new Child(source.getB(),true));
customList.add(new Child(source.getC(),false));
return customList;
}
I have used an expression to solve this problem. The expression is to perform the mapping (for objects, straightforward for Strings), and then convert it to a list.
#Mapping(target = "names", expression = "java(Arrays.asList(map(source.getName())))")
TargetObject map(SourceObject source);
TargetName map(SourceName source)
You need to import "Arrays" class in the #Mapper definition as below.
#Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = "spring", imports = {Arrays.class})
I had similar use case where i want to convert and Single Object to List of objects.
As these are very custom requirements, will be hard for mapstruct to provide some API for use cases like this.
I ended up implementing using default method like this
#Mapper(componentModel = "spring")
interface MyMapper {
default List<SomeObject> from(SourceObject sourceObject) {
//Add Mappig logic here
//return the list
}
}
//If you want to use some mapper for mapping
#Mapper(componentModel = "spring")
public abstract class SomeArrayMapper {
#Autowired
SomeMapper mapper;
public SomeUser[] from(SingleObject singleObject) {
SomeUsers[] Users = new SomeUser[1];
Users[0] = mapper.toUser(singleObject);;
return Users ;
}
}
In some cases Decorators can also be useful take a look at here
There is no clean way of doing this at the moment in MapStruct. MapStruct is considerring bean tot map mapping. See here: https://github.com/mapstruct/mapstruct/pull/1744 which might come in helpful once implemented.
However, if you really have a lot of properties and this is a recurring problem, and you dislike reflection - like I do - you might want to give code generation an attempt and DIY. I posted an example some while ago for generating a mapper repository here: https://github.com/mapstruct/mapstruct-examples/tree/master/mapstruct-mapper-repo but, it's a bit of an steep learning curve.. sorry
Using Mapstruct, how can I create a mapper which would auto-map all but one (or two, three, etc.) fields which should be passed through some custom mapping logic?
Mapper
#Mapper
public interface MyEntityMapper
{
MyEntityMapper INSTANCE = Mappers.getMapper(MyEntityMapper.class);
#Mappings(
{
#Mapping(source = "createdByPerson.id", target = "createdByPersonId"),
})
MyEventPayload toEventPayload(MyEntity entity);
}
If I have a someString field which needs some custom mapping logging to be done first, how would I do that? I see this argument option to #Mapping, but that seems a bit crazy to write java code within a string within an annotation!
I was hoping to do something like:
#MappingFor(MyEntity.class, "someString")
default String mapSomeString(String value) {
return value + " custom mapping ";
}
Update
I found #AfterMapping and used it e.g.:
#AfterMapping
public void mapSomeString(MyEntity entity, MyEventPayload payload) {
// do fancy stuff here
}
But I'm still curious if you can provide per-field after-mapping / custom-mapping functionality.
If you want to map a single field in a specific way you can use Mapping methods selection based on qualifiers.
This looks something like
#Mapper
public interface MyEntityMapper {
#Mapping(target = "someString", qualifiedByName = "myFancyMapping")
MyEventPayload toEventPayload(MyEntity entity);
#Named("myFancyMapping") // org.mapstruct.Named
default String mapSomeString(String value) {
return value + " custom mapping ";
}
}
You can also use Mapping#qualifiedBy and construct your own Qualifier (org.mapstruct.Qualifier) annotation.
This looks like:
#Qualifier // org.mapstruct.Qualifier
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.CLASS)
public #interface MyFancyMapping {
}
#Mapper
public interface MyEntityMapper {
#Mapping(target = "someString", qualifiedBy = MyFancyMapping.class)
MyEventPayload toEventPayload(MyEntity entity);
#MyFancyMapping
default String mapSomeString(String value) {
return value + " custom mapping ";
}
}
Alternative
An alternative would be to do the custom mapping in an #AfterMapping or with an expression (I don't recommend using expressions, as it is error prone).
Have you looked at Expressions of MapStruct?
Here is example from Docs:
#Mapping(target = "timeAndFormat",
expression = "java( new org.sample.TimeAndFormat( s.getTime(), s.getFormat() ) )")
Instead of new org.sample.TimeAndFormat... you could use your class constructor or method.
I ended up using #AfterMapping e.g.:
#AfterMapping
public void mapSomeString(MyEntity entity, MyEventPayload payload) {
// do fancy stuff here
}
I have two domain entities:
class Identity {
Long id;
Set<Business> businesses;
}
class Business {
Long id;
String name;
}
I then have two DTOs that extend a base DTO:
class BaseDto {
String id;
}
class IdentityDto extends BaseDto {
Set<BaseDto> businesses;
}
class BusinessDto extends BaseDto {
String name;
}
Then I created a mapper that maps a list of my domain entities to either a Set of the specific dto, or a set of the more generic base dto. This is because when I am getting a list of businesses, I want the full business dto, but when I get an identity, I just what the base info in it's list of businesses.
But when I try to create the mapper for the identity I get the following error:
Ambiguous mapping methods found for mapping property
"Set<Business> businesses" to Set<BaseDto>:
Set<BusinessDto> BusinessMapper.toSet(Set<Business> businesses),
Set<BaseDto> BusinessMapper.toBaseSet(Set<Business> businesses).
I thought that mapstruct used the most specific method, so should know to use the toIdentifierSet method in this case.
How do I make mapstruct know which method to use?
There is no most specific method here as you are trying to map into Set<BaseDto>.
You can use Mapping method selection based on qualifiers.
You can define some annotations:
#Qualifier
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.CLASS)
public #interface BaseInfo {
}
Then in your BusinessMapper
#Mapper
public interface BusinessMapper {
Set<BusinessDto> toSet(Set<Business> businesses);
#BaseInfo
Set<BaseDto> toBaseSet(Set<Business> businesses);
}
Then in your identifier
#Mapper
public interface IdentifierMapper {
#Mapping(target = "businesses", qualifiedBy = BaseInfo.class)
IdentityDto map(Identity source);
}
In case you want to explicitly pick always you can add another annotation BusinessInfo and then annotate the other method. Then you would need to pick a method each time.