What is best way to JPA repository update?

489 Views Asked by At

I am extending my question here: Spring Data JPA Auditing not working for the JpaRepository update method with @Modifying annotation, why?. I am using Spring Boot + Spring Data JPA.

I've developed update

@Modifying(clearAutomatically = true)
@Query("UPDATE Student s SET s.studentDescription=:stuDesc, s.studentId=:studentId, s.sivisionCode=:cd, "
        + "s.status=:status, s.firstName=:firstName, s.lastName=:lastName, s.email=:email WHERE s.studentName=:stuName")
void updateStudent(@Param("stuName") String studentName,
                    @Param("stuDesc") String studentDescription,
                    @Param("studentId") String studentId,
                    @Param("cd") String cd,
                    @Param("firstName") String firstName,
                    @Param("lastName") String lastName,
                    @Param("email") String email,
                    .........
                    ...........
                    .........
                    ..........
                    // 8 more parameters here
                    ...........
                    @Param("status") String status); 

Note: I know this way code works and it updates only those fields which I am passing. But I am trying to understand the best way to update Student record here.

Another way to fetch Student Record and set the updated value and save(). Will this be good practice ? Is there any way best way of doing this ?

1

There are 1 best solutions below

2
On BEST ANSWER

Hibernate provides an annotation @DynamicUpdate to update only modified fields of an entity.