1

I have two set object Set<Foo> fooSet and Set<Bar> barSet. Foo is the entity object and Bar is the DTO which i want to use for sending data to the UI. I want to copy all the properties from fooSet into barSet.

public class Foo {
    @Id
    @Column(name = "Category_Id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long categoryId;

    @OneToMany(mappedBy="productCategory")
    private Set<ProductEntity> products;
}

public class BarDto {

   private Long categoryId;

   private Set<ProductDto> products;

}

I am trying to convert Entity into DTO object like:

public BarDto mapDomainToDto(Foo domain) {

        BarDto barDto= new BarDto();
        barDto.setCategoryId(domain.getCategoryId());
       //trying to do something like:
       barDto.setProducts(domain.getProducts());
}

Is there any way to achieve this in Java 8?

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
implosivesilence
  • 536
  • 10
  • 24
  • 1
    What's the relation between the Foo and Bar classes? – Eran Aug 20 '20 at 06:55
  • 1
    You can write a converter method for converstion and use like `fooSet.stream().map(e -> convertFooToBar()).collect(toSet())`, there are some library for mapping one model into another one like ModelMapper – Eklavya Aug 20 '20 at 07:00
  • This question is similar [How to map a DTO to an existing JPA entity?](https://stackoverflow.com/questions/46536060/how-to-map-a-dto-to-an-existing-jpa-entity) – Eklavya Aug 20 '20 at 07:36

2 Answers2

2

Java 8 itself doesn't provide such mapping feature and with pure Java all the left is manual calls of getters and setters as you already do:

BarDto barDto = new BarDto();
barDto.setCategoryId(domain.getCategoryId());
barDto.setProducts(domain.getProducts());
...

This is not bad itself as long as the number of such object mappings and parameters is low. For more complex object hierarchies I recommend MapStruct. ModelMapper is its alternative (IMHO, MapStruct is the way easier to configure and use, though it does the job the same).

@Mapper
public interface FooBarMapper {
 
    FooBarMapper INSTANCE = Mappers.getMapper(FooBarMapper.class);

    BarDto fooToBarDto(Foo domain);
}
BarDto barDto = FooBarMapper.INSTANCE.fooToBarDto(domain);

Back to Java 8, I bet you refer to either Stream API, Optional or anything related to the functional paradigm. Again, there is not such feature in this or any newer verstion of Java. However, it might help you with mapping of collections of objects using the library above:

FooBarMapper mapper = FooBarMapper.INSTANCE;

List<Foo> fooList = ...
List<BarDto> barDtoList = fooList.stream()
                                 .map(mapper::fooToBarDto)
                                 .collect(Collectors.toList());
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
0

Usualy we write model mapper. Or u can use some libraries like http://modelmapper.org/getting-started/