I have a below Student entity and I want to update only not null fields when I call CrudRepository save method. For example;
Student student = new Student();
student.setName("test");
student.setNumber("32323");
studentRepository.save(student);
When I call save method It also updates address field to null value. What I want to do is "if it has null value then don't update". Is there any way to do this?
@Entity
@Table(name = "student")
public class Student implements Serializable{
@Id
@Column
private String name;
@Column
private String number;
@Column
private String address;
....
}
I have a below Student entity and I want to update only not null fields when I call CrudRepository save method.
You can't do this in this way because when you provide an entity to Spring or JPA for an update operation, they cannot guess why some fields of this entity are null : is it null
because you want to set the field to null ? Or is is null
because you have not fulfilled this field but you don't want that the existing value to be overwritten ?
So, they don't make guesworks and simply update the row with effective values in the fields of your entity.
So you should write a JPQL Query where you explicit fields to update :
UPDATE Student e SET e.name=%1 AND e.number=%2
WHERE ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With