简体   繁体   中英

How to merge two objects in Java Spring Boot application?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM