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.
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.
CodePudding user response:
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);
CodePudding user response:
Your question is not silly, you want to make it better, but you are already doing it, like it is supposed to be done.
However, having a lot of fields in a table, could indicate a problem in the DB design, if you are not using Cassandra or something like that.