1

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 ?

Pra_A
  • 7,134
  • 12
  • 89
  • 170

1 Answers1

2

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

Robin Rozo
  • 84
  • 4
  • I am using Spring Data JPA repository queries for all kind of CRUD related queries. Still you want to suggest to use `@DynamicUpdate` ? Also, For updating data I am using DTO/Resource class and converting that to Entity classes using ResourceAssesmbler of HATEOAS. Any suggestion? – Pra_A Aug 18 '19 at 16:32
  • @DynamicUpdate does exactly what you want to do; saving only the modified fields of an entity. But, be aware that there is a performance cost. For mapping the DTO to Entity you probably need to write your own custom method that load the entity from the database an map only the modified fields to the entity. – Robin Rozo Aug 19 '19 at 14:46