How to Beautifully Update a JPA Entity in Spring Data

How to beautifully update a JPA entity in Spring Data?

Even better then @Tanjim Rahman answer you can using Spring Data JPA use the method T getOne(ID id)

Customer customerToUpdate = customerRepository.getOne(id);
customerToUpdate.setName(customerDto.getName);
customerRepository.save(customerToUpdate);

Is's better because getOne(ID id) gets you only a reference (proxy) object and does not fetch it from the DB. On this reference you can set what you want and on save() it will do just an SQL UPDATE statement like you expect it. In comparsion when you call find() like in @Tanjim Rahmans answer spring data JPA will do an SQL SELECT to physically fetch the entity from the DB, which you dont need, when you are just updating.

How do I modify only part of an entity in spring data jpa?

You should add an if check to make sure the latitude/longitude are not null before calling their setters.

public void modifyDrawing(Long no, String name, Double lat, Double lon, String physicalName, String desc) {
Drawing drawing = drawingRepository.findById(no)
.orElseThrow(NoSuchElementException::new);

drawing.setName(name);
if (lat != null) {
drawing.setLat(lat);
}
if (lon != null) {
drawing.setLon(lon);
}
drawing.setPhysicalName(physicalName);
drawing.setDesc(desc);
drawingRepository.save(drawing);
}

Update entity in jpa

No, you can use JpaRepository.save(S entity) that saves or updates the entity if existing.

To achieve that, make sure that the entity has its JPA @Id valued before invoking save() otherwise a new record will indeed be created.

Jpa Repository save() doesn't update existing data

Your Entity Employer looks to be in detached/Transient state and you are passing id value manually which is not permitted, as it is marked as @GeneratedValue(strategy = GenerationType.IDENTITY).

What you need to do is when you know the primary key value i.e id value, first you fetch the Entity from the database using findById() method, by which Entity comes into Managed state and then try to update the Entity by calling save() method. This will update your Entity.

For more info on Entity state you can refer this:
https://vladmihalcea.com/a-beginners-guide-to-jpa-hibernate-entity-state-transitions/



Related Topics



Leave a reply



Submit