3

I need to do a merge of objects in Java Spring Boot application (ProductDTO and Product).

ProductDTO does not contain all the fields from Product, and I would like to map only the fields that are the same in both objects, while preserving the other values in the destination object.

I am coming from the C# world, so I don't know what is the best way to achieve the same behavior in Java. In C# I would do it like this:

    var project = new Project
    {
        Name = "Project 1",
        Description = "Description"
    };

    var projectDto = new ProjectDTO
    {
        Name = "Project 1 (changed)"
    };

    Mapper.Map(projectDto, project);

After execution of the Map method, the project object still contains the original value for the Description field.

What is the best way to do this in Java Spring?

1

2 Answers 2

6

There is a BeanUtils class in spring beans library.

BeanUtils.copyProperties(source, target);

As long as your classes contain the same property names the appropriate setter will be called in the target. It will ignore any properties which are not present in the target.

Sign up to request clarification or add additional context in comments.

Comments

3

For your case you can do it using Apache or Spring bean utils.

org.apache.commons.beanutils.BeanUtils.copyProperties(Object destination, Object source)
org.springframework.beans.BeanUtils.copyProperties(Object source, Object dest)

Position of parameters is different in both cases.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.