ROZZ
ROZZ

Reputation: 1454

Spring boot + JPA(Hibernate) Edit partial entity fields

all.

I have following simple form in which I want to edit the entity. The problem is that I have some fields which I don't want to be edited. For example (Image file path).

As it is now, I have the service method -

public void addOrModifyLayout(Layout layout){
    if(layout.getId() == null){
        layoutRepository.save(layout);
        }
    else {
        Layout modifiedLayout = new Layout();
        modifiedLayout.setId(layout.getId());
        modifiedLayout.setName(layout.getName());
        modifiedLayout.setStatus(layout.getStatus());
        modifiedLayout.setExhibitor(layout.getExhibitor());
        layoutRepository.save(modifiedLayout);
    }
}

As you can see, every field that I want to be able to be edited, I should explicitly put it in the service. Can I use some mapper or trick to update only some fields that are in the view (form) ? How you handle this kind of issues?

enter image description here

Upvotes: 1

Views: 402

Answers (1)

StanislavL
StanislavL

Reputation: 57381

You can either

store all the entity fields in hidden inputs (e.g. imageFilePath hidden input). So you can store on UI all the entity fields and get them back to assign to the entity.

OR

Avoid new entity creation but retrieve existing one and fill only necessary fields.

Layout modifiedLayout = layoutRepository.getById(layout.getId());
modifiedLayout.setName(layout.getName());
modifiedLayout.setStatus(layout.getStatus());
modifiedLayout.setExhibitor(layout.getExhibitor());
layoutRepository.save(modifiedLayout);

Upvotes: 2

Related Questions