【问题标题】:Spring Data JPA Auditing not working for the JpaRepository update method with @Modifying annotation, why?Spring Data JPA 审计不适用于带有 @Modifying 注释的 JpaRepository 更新方法,为什么?
【发布时间】:2019-11-11 09:43:51
【问题描述】:

我正在研究 Spring Data JPA 和 Postgres 示例。在这个例子中,我通过以下链接实现了Auditinghttps://www.baeldung.com/database-auditing-jpaSpring Boot JPA@CreatedDate @LastModifiedDate not being populated when saving the object。审核工作非常好当我执行 repository.save 时,在这种情况下,使用 @CreatedDate@LastModifiedDate 注释的两个字段都正确保存。

但是,当我尝试更新方法时,却没有发生同样的情况。

我开发了以下方法。

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

【问题讨论】:

    标签: java postgresql spring-data-jpa auditing


    【解决方案1】:

    @Audited 注解可以应用于类、方法和类型。我遇到了类似的问题,并尝试在update... 方法上应用@Audited 注释,并且能够看到填充在_AUD 表中的审计信息。
    @Audited的定义如下:https://docs.jboss.org/hibernate/orm/5.2/javadocs/org/hibernate/envers/Audited.html

    【讨论】:

      【解决方案2】:

      审核基于 JPA 生命周期事件。 只有直接操作实例的方法(persistmergeremove)才会触发此类事件。

      查询的执行、修改或其他方式不会触发任何事件,因此不会导致审计发生。

      有关详细信息,请参阅 JPA 规范第 3.5.2 节生命周期方法。

      【讨论】:

      • 所以没有办法将jpq查询结果保存在审计文件中?
      猜你喜欢
      • 2019-03-10
      • 1970-01-01
      • 2018-12-30
      • 2021-12-24
      • 2022-01-02
      • 2019-01-21
      • 2012-03-08
      • 1970-01-01
      相关资源
      最近更新 更多