Idan Fridman

About 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).

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:

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

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

  1. Yannick Majoros says:

    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.

  2. Idan says:

    @Yannick,
    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.

  3. Yannick Majoros says:

    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 talking about methods that you want in your entities and not in your dto’s (or vice versa)? Well, in that case, the behavior they represent shouldn’t be in the same class to begin with.

    I know someone will probably use the word “anemic”…

Leave a Reply


× 7 = twenty one



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close