I am using MapStruct to convert entities to DTOs.
I have an entity A with list of entity B:
public class A {
List<B> bs;
}
I want to have a list of B ids in ADto class:
public class ADto {
List<Long> bIds;
}
I am using MapStruct to convert entities to DTOs.
I have an entity A with list of entity B:
public class A {
List<B> bs;
}
I want to have a list of B ids in ADto class:
public class ADto {
List<Long> bIds;
}
You’ll have to define a custom mapping method. (I do not know any other easier method to map a custom object to a Lang)
Anyways here would be the mapper
@Mapper
public interface AMapper {
@Mapping(source = "bs", target = "bIds", qualifiedByName = "bToId")
public ADto aToADto(A a);
@Named("bToId")
public static Long bToId(B b) {
return b.getId();
}
}
Basically the first method would map the list of Bs to Longs using the method defined by you beneath it (based on the @Named value)
This approach is similar to the approach taken by L_Cleo, but assumes that we have more (possibly many) use cases in which we want to map entities to their id. If you upvote my answer, you may want to give them an upvote aswell; my answer was inspired by theirs.
First, we create an interface HasId and let all entities having a long getId()-method implement this interface:
public interface HasId {
long getId();
}
@Builder
@Value
public class A implements HasId {
long id;
List<B> bs;
}
@Builder
@Value
public class B implements HasId {
long id;
}
Alternativley, if we already have an (abstract) superclass providing a long getId()-method, we can use this class instead. It works in the same manner.
Next, we define a mapper that maps a HasId-entity to their id. We do not have any support from MapStruct for this, so we have to create this mapper manually:
@Mapper
public class HasIdMapper {
final long toId(HasId entity) {
return entity.getId();
}
}
We define our Dto-class as usual:
@Builder
@Value
public class ADto {
List<Long> bIds;
}
And finally we define the mapper from A to ADto:
@Mapper(uses = HasIdMapper.class)
public interface AMapper {
@Mapping(source = "bs", target = "bIds")
ADto toDto(A entity);
}
The important bit here is the uses-attribute with which we trigger the usage of the HasIdMapper.
And for completeness sake, here is a small test case:
public static void main(String... args) {
final A a = A.builder()
.bs(List.of(
B.builder().id(1).build(),
B.builder().id(2).build(),
B.builder().id(3).build()))
.build();
final ADto dto = Mappers.getMapper(AMapper.class).toDto(a);
System.out.println(dto);
}
This will print out:
ADto(bIds=[1, 2, 3])