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);
}
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.
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