MapStruct inheritance and calling "this" - java

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);
}

Related

#SubclassMapping order

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.

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: How to default a target String to Empty String when the Source is Null (Both fields have the same name and type) Java / Spring

I have two Objects Source and Target both with the same field names and types.
If a source field is null I would like the target to be "" (Empty String)
My Interface mapping looks like this (This is just two field, I have many)
#Mapper(componentModel = "spring", nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT)
public interface MyMapper {
#Mappings({
#Mapping(target="medium", defaultExpression="java(\"\")"),
#Mapping(target="origin", defaultExpression="java(\"\")")
})
public Target mapFrom(Source source)
If the Source has a value it should be copied across, if it is null in the source it should be "" in the target.
Mapstruct-1.3.0 seems to just keep everything null.
Any Idea? I would like default to be empty String for everything
You need to set the NullValuePropertyMappingStrategy (as part of the Mapper annotation) for defining how null properties are to be mapped.
See NullValuePropertyMappingStrategy.html#SET_TO_DEFAULT
The default value for String is "". You don't need to define it explicitly.
So, your mapper can simply look like this:
#Mapper(
componentModel = "spring",
nullValueMappingStrategy = NullValueMappingStrategy.RETURN_DEFAULT,
nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.SET_TO_DEFAULT
)
public interface MyMapper {
public Target mapFrom(Source source);
}
When your Source object has the same fields as Target object and when you want to manage all Source null values (e.g. for String) to became an empty String ("") in the Target object, you could create mapper interface from MapStruct library as below:
Step 1:
#Mapper(componentModel = "spring")
public interface SourceToTargetMapper {
Target map(Source source);
#BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.SET_TO_DEFAULT)
void update(Source source, #MappingTarget Target target);
}
The whole trick is to define nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.SET_TO_DEFAULT but you cannot define it in #Mapper annotation. Instead of that you had to place it as parameter in #BeanMapping annotation for update() method.
You can read more about this in MapStruct documentation.
Step 2:
Therefore you had to do one more operation in your code and use just implemented 'update()' method:
#Component
public class ClassThatUsingMapper {
private final SourceToTargetMapper mapper;
public Target someMethodToMapObjects(Source source) {
Target target = mapper.map(source);
mapper.update(source, target)
return target;
}
}
All null to empty String process takes place under mapper.update(source, target) method. After run mvn clean install for your project, you can check how it looks and how it works in target/generated-sources/annotations/...../SourceToTargetMapperImpl.java file.

Categories

Resources