Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update only specific field with spring jpa repository?

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;
    ....
}
like image 758
hellzone Avatar asked Sep 14 '25 05:09

hellzone


1 Answers

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 ...
like image 122
davidxxx Avatar answered Sep 16 '25 20:09

davidxxx