Core Java

Mapping your Entities to DTO’s Using Java 8 Lambda expressions

We all facing the cluttered overhead code when we need to convert our DTO’S to Entities(Hibernate Entities, etc..) and backwards.

In my example ill demonstrate how the code is getting much shorter with Java 8.

Let’s create the Target DTO:
 
 
 
 
 
 

public class ActiveUserListDTO {

    public ActiveUserListDTO() {
    }

    public ActiveUserListDTO(UserEntity userEntity) {

        this.username = userEntity.getUsername();

     ...
   }
}

A simple find method to retrieve all entities using Spring data JPA API:

userRepository.findAll();

Problem:

Find.All() method signature (like many others) returns java.lang.Iterable<T>
1

      java.lang.Iterable<T> findAll(java.lang.Iterable<ID> iterable)

We can’t make a Stream out of java.lang.Iterable(* Streams working on collections. Every Collection is Iterable but not every Iterable is necessary a collection).

So how do we get a Stream object in order to get Java8 Lambda’s Power?

Let’s use StreamSupport object to convert Iterable into Stream:

Stream<UserEntity> userEntityStream = StreamSupport.stream(userRepository.findAll().spliterator(), false);

Great. Now we’ve got Stream in our hands which is the key to our Java 8 labmda’s!

What’s left is to map and collect:

List<ActiveUserList> activeUserListDTOs =
            userEntities.stream().map(ActiveUserList::new).collect(Collectors.toList());

I am using Java 8 Method Reference and therefor initiating (and mapping) each entity into dto.

So let’s make one short line out of everything:

List<ActiveUserList> activeUserListDTOs=StreamSupport.stream(userRepository.findAll().spliterator(), false).map(ActiveUserList::new).collect(Collectors.toList());

That’s neat!!

Idan.

Related Articles:

Idan Fridman

Idan is Software engineer with experience in Server side technologies. Idan is responsible for various infrastructure models in the software industry(Telecommunications, Finance).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Yannick Majoros
Yannick Majoros
9 years ago

A DTO shouldn’t know about the entities it maps to. “Conversion” should be made elsewhere to avoid coupling them.

BTW, I hope you think twice because having all entities duplicated as “DTO’s”. Is it needed in your use case? I saw too much projects where this was done blindly without added value.

Idan
9 years ago

,
1. Conversion” should be made elsewhere
Please past an example I will be more than happy to adjust this.

2. “hope you think twice because having all entities duplicated”

In my case the DTO are being mapped back to DTO’S mostly because I am doing some data manipulation later on which I didnt want it to reflected on my Database. I find it hard to use entities as my dto’s in my project. you right it’s sometime costs us with duplicated classes but you cant avoid it.

Yannick Majoros
Yannick Majoros
9 years ago

1. About conversion, I was referring to your example: ActiveUserListDTO takes a UserEntity in its constructor. Why should your dto be coupled to your entity? If it is, there is some chance that they are the same. 2. What do you mean by “using entities as dto’s”? “You cant avoid it”, really? It’s quite common to use jpa entities in other layers nowadays. My point was that it’s more of an issue to duplicate every entity as a “dto” (please give an exact definition). If they have the same properties, they are probably the same thing anyway. Are you maybe… Read more »

Klaudiusz Wojtkowiak
Klaudiusz Wojtkowiak
9 years ago

In that case DTO object imports Entity class, and has a parse logic inside, which is forbidden.
Do You want to provide Entity classes as well? If not, there will be an import missing erros on the client side.

DTO (Data Transfer Object) contain default contructor (no contructor in the code) and getter/setters only.
DTO may import classes, but if’s standard JRE Java classes or another DTO as well.

chuck1300
chuck1300
9 years ago

It should actually be a mapper.
Rename for example ActiveUserListDTO to UserDtoMapper, it will have a UserDto and a method GetUserDto.
Then change the stream :
List userDtos = userEntities.stream()
.map(UserDtoMapper ::new)
.map(UserDtoMapper ::GetUserDto)
.collect(Collectors.toList());

Dean
Dean
8 years ago

I may be missing something, but I tried compiling and running this code, but it is missing classes and not running like the author suggests. Can the author please share the code he used or update the example

Back to top button