#SubclassMapping order - java

First time using MapStruct (1.5.0.Beta2)
Say I have the following class hierarchy: C extends B extends A and Cdto extends Bdto extends Adto. And the following mapper:
#Mapper(componentModel = "spring", subclassExhaustiveStrategy = RUNTIME_EXCEPTION)
public interface MyMapper{
#SubclassMapping(source = B.class, target = Bdto.class)
#SubclassMapping(source = C.class, target = Cdto.class)
Adto map(A source);
}
When I map a list of C objects I actually get a list of Bdtos. If however I change the ordering to:
#Mapper(componentModel = "spring", subclassExhaustiveStrategy = RUNTIME_EXCEPTION)
public interface MyMapper{
#SubclassMapping(source = C.class, target = Cdto.class)
#SubclassMapping(source = B.class, target = Bdto.class)
Adto map(A source);
}
I get a list of Cdtos as expected. Is this by design? Is there any way to make it less dependent on annotation order?

This is by design. The reason for this is to let the user control the order for the mappings. The same behavior is used for #Mapping annotations.
Your first example should also get a compiler warning, although it might refer to the wrong type (target instead of source) at the moment. This should be fixed in the next release.

Related

MapStruct inheritance and calling "this"

I have a denormalized database and a domain model that includes multiple classes. for example
class BMW {
EngineConfiguration engineConfiguration;
ModelMetadata modelMetadata;
BodyConfiguration bodyConfiguration;
}
class CarsEntity{
String modelName;
Integer year...
//etc. all fields, in same class
}
I would like to write MapStruct mappers for EngineConfiguration, ModelMetadata and BodyConfiguration and then when uniting them all in one mapper. Example
#Mapper(componentModel = "spring")
class EngineConfigurationMapper {
#Mapping(... specific fields mapping goes here)
EngineConfiguration mapToDomain(CarsEntity carsEntity);
}
#Mapper(componentModel = "spring", uses = {EngineConfigurationMapper.class , ...})
class BMWMapper {
BMW mapToDomain(CarsEntity carsEntity);
}
The problem is that my mappers are not working by default, BMWMapper does not have the calls to the others mappers and I've tried expression calling this like expression="(engineConfigurationMapper.mapToDomain(this))" target = "engineConfiguration) but the mappers are not included in the implementation.
How can I achieve this?
P.S.: MapperConfig is of no use as well
I guess when you say this you mean the source entity, i.e. carsEntity.
In Mapping#source you can use the source parameter name, which means that you can do the following:
#Mapper(componentModel = "spring", uses = {EngineConfigurationMapper.class , ...})
class BMWMapper {
#Mapping( target = "engineConfiguration", source = "carsEntity")
#Mapping( target = "modelMetadata", source = "carsEntity")
#Mapping( target = "bodyConfiguration", source = "carsEntity")
BMW mapToDomain(CarsEntity carsEntity);
}

How to create or enhance a custom annotation that uses mapstruct

Mapsturct has #Mapping annotation with predefined attributes
eg: #Mapping(source="", target="", qualifiedByName="") , what if i want to add another attribute it and use it to compute the logic
eg: #Mapping(source="", target="", qualifiedByName="" , version="")
I would like to pass the version number to it and depending on the version, it would set the target from source.
I tried to create a custom annotation and use #Mapping in it but didnt help
#CustomMapping(version = "1.0", mapping = #Mapping(source = "", target = "", qualifiedByName=""))
Why don't you just define a 2nd distinct annotation to be used alongside #Mapping?
#Mapping(source="", target="", qualifiedByName="")
#MappingVersion("1.0")
CarDto carToCarDto(Car car);
If your concern is that you want some kind of enforcement that version is always present when #Mapping is used then you could trivially write an annotation processor which does this at compile-time.
Based on the comments in the question I understand a bit more what needs to be done. Basically based on some input parameter different mapping methods need to be created.
Not sure how complex your logic is. However, what you can do is to create your own annotation processor that would be able to create MapStruct mappers.
Let's imagine that you have
#CustomMapper
public interface MyMapper {
#CustomMapping(version = "1.0", mappings = {
#Mapping(source = "numberOfSeats", target = "seatCount", qualifiedByName="")
})
#CustomMapping(version = "2.0", mappings = {
#Mapping(source = "numberOfSeats", target = "seats", qualifiedByName="")
})
CarDto map(Car car, String version);
}
So your annotation processor would need to handle CustomMapper.
The processor would also generate the different MapStruct versioned interfaces.
So:
#Mapper
public interface MyMapperV1 {
#Mapping(source = "numberOfSeats", target = "seatCount", qualifiedByName="")
CarDto map(Car car)
}
#Mapper
public interface MyMapperV2 {
#Mapping(source = "numberOfSeats", target = "seats", qualifiedByName="")
CarDto map(Car car)
}
And additionally an implementation of MyMapper. That looks like:
public class MyMapperImpl {
protected MyMapperV1 myMapperV1 = Mappers.getMapper(MyMapperV1.class):
protected MyMapperV2 myMapperV2 = Mappers.getMapper(MyMapperV2.class):
public CarDto map(Car car, String version) {
if ("1.0".equals(version)) {
return myMapperV1.map(car);
} else {
return myMapperV2.map(car);
}
}
}
Basically the goal is to have your processor generate the interfaces that would be picked up by MapStruct in the same compilation round. This is possible with annotation processing.
Another option is to write the MapStruct mappers on your own and in the caller place pick the one which is appropriate for the version. This might be simpler actually.

How to call MapStruct method from interface in java stream

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.

MapStruct Map Object to List

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

MapStruct: Is it possible to specify using the same named mapping for all nested fields of a type?

Is it possible to specify the qualifier for a nested mapper without having to specify it for each instance of a particular type of bean?
Some code to illustrate my point. I have a Parent object like:
public class ParentDTO {
ChildDTO childA;
ChildDTO childB;
ChildDTO childC;
// getters, setters, etc.
}
and I have a ChildMapper that includes more than one mapping:
#Mapper
public interface ChildMapper {
#Named("MinimalChildMapper")
#Mapping(target = "someAttribute", ignore = true)
ChildDTO toMinimalChildDTO(Child child);
#Named("ChildMapper")
ChildDTO toChildDTO(Child child);
}
I know that I can specify which child mapper to use for each child like this:
#Mapper(uses = ChildMapper.class)
public interface ParentMapper {
#Mapping(target = "childA", qualifiedByName = "MinimalChildMapping")
#Mapping(target = "childB", qualifiedByName = "MinimalChildMapping")
#Mapping(target = "childC", qualifiedByName = "MinimalChildMapping")
ParentDTO toParentDTO(Parent parent);
}
What I'm trying to figure out is if there is some way to use the mapping indicated in each qualifiedByName for the type (ChildDTO) rather that having to specify it for each instance of the type (childA, childB, childC). Is this possible?
Currently this is not possible.
However, what you could do is to have 2 ChildMapper(s). That way you can use the one with the minimal in your ParentMapper. One other option would be to defined the minimal mapping in your ParentMapper instead of reusing the ChildMapper.

Categories

Resources