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?

Developer Thing
  • 2,704
  • 3
  • 21
  • 26
  • Convert objects to json and merge afterwards. Have a look at https://stackoverflow.com/questions/2403132/merge-concat-multiple-jsonobjects-in-java – nologin Apr 11 '19 at 14:32

2 Answers2

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.

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.

Himanshu
  • 164
  • 4