Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA Auditing not working for the JpaRepository update method with @Modifying annotation, why?

Tags:

I am working on Spring Data JPA and Postgres example. In this example, I've implemented Auditing by following link: https://www.baeldung.com/database-auditing-jpa and Spring Boot JPA@CreatedDate @LastModifiedDate not being populated when saving the object. Auditing working very fine When I do the repository.save, in this case both fields annotated with @CreatedDate and @LastModifiedDate are saving correctly.

But same is not happening when I'm trying to update the method.

I've developed following method.

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@EntityListeners(AuditingEntityListener.class)
@Entity
@Table(uniqueConstraints = {
        @UniqueConstraint(name="student_name_key",columnNames = {"studentName"})
})
public class Student {
    ....
    ....
    @Column(name="lastUpdateUser")
    private String lastUpdateUser;

    @LastModifiedDate
    @Column(name="lastUpdateDate", nullable = false)
    private LocalDateTime lastUpdateDate; 
}

Main.App

@SpringBootApplication
@EnableJpaAuditing
@EnableJpaRepositories(basePackages = {"com.xxx.xxx.repository"})
@ComponentScan(basePackages = {"com.xxx.yyy","com.xxx.xxx.studentportfolio"})
@EnableCaching
@EnableAsync
@EnableAspectJAutoProxy(proxyTargetClass = true)
@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class, SecurityAutoConfiguration.class})
public class MainApplication extends SpringBootServletInitializer implements CommandLineRunner{

    public static void main(String[] args) {
        SpringApplication.run(ProgramApplication.class, args);
    }
}

StudentRepository.java

public interface StusentRepository extenss JpaRepository<Stusent, Long>{

    @Mosifying(clearAutomatically = true)
    @Query("UPDATE Stusent s SET s.studentDescription=:stuDesc, s.studentId=:studentId, s.sivisionCode=:cd, "
            + "s.status=:status WHERE s.studentName=:stuName")
    vois upsateStudent(@Param("stuName") String studentName,
                        @Param("stuDesc") String studentDescription,
                        @Param("studentId") String studentId,
                        @Param("cd") String cd,
                        @Param("status") String status);
}
like image 236
PAA Avatar asked Jun 30 '19 09:06

PAA


1 Answers

Auditing is based on the JPA Lifecycle events. Only the methods directly manipulating instances (persist, merge and remove) trigger such events.

The execution of queries, modifying or otherwise, does not trigger any events and therefore, won't cause auditing to happen.

See the JPA Specification section 3.5.2 Lifecycle Methods for details.

like image 153
Jens Schauder Avatar answered Nov 15 '22 05:11

Jens Schauder