Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The best way to update entity in spring boot

I’m new to spring boot and trying to make my first api. I’ve made a lot of apis on python using FastAPI framework, but now i decided to study this technology. But here, I met a problem. So I’m using the jpa for database communication and I don’t really understand how to update entity’s fields correctly.

I’ve read a lot of guidelines, and all of them says that updating an entity carried out like this:

    public void updateUserInDatabase(long userId, UserUpdateModel newData) {
        UserEntity user = userRepo.findById(userId).orElseThrow();
        if(newData.getUsername() != null) {
            user.setUsername(newData.getUsername());
        }
        if(newData.getPassword() != null) {
            user.setPassword(newData.getPassword());
        }
    }

But I think it’s not useful as newData can have a lot of fields, so for updating an entity I’ll need a lot of conditions.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So, yeah, maybe this question is silly, but I really try to understand XD. If you know the answer, please tell me! I’d really appreciate it. Thank you in advance.

>Solution :

You could use an entity mapper like MapStruct or ModelMapper

A ModelMapper example:

ModelMapper mapper = new ModelMapper();
// this will tell ModelMapper to ignore null fields when mapping the source (newData) to the destination (user)
mapper.getConfiguration().setSkipNullEnabled(true);

UserEntity user = userRepo.findById(userId).orElseThrow();
// this will tell ModelMapper to map newData into user
mapper.map(newData, user);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading