Home > Software design >  Auditing fields not automatically filled by JPA in Spring Boot
Auditing fields not automatically filled by JPA in Spring Boot

Time:02-24

I have the following entity, which reflects some kind of background task and gonna be updated. I thought using the JPA auditing would be useful so I included it like this:

@Entity
@RequiredArgsConstructor
@Getter
@Setter
@Table(name = "FOO")
public class FooJob{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", unique = true, nullable = false)
    private long id;

    @LastModifiedDate
    @Column(name = "FINISHED", nullable = false)
    private LocalDateTime finished;

    ...

}

@Repository
public interface FooJobRepository
    extends JpaRepository<FooJob, Long>,
        JpaSpecificationExecutor<FooJob> {}

and I have enabled the @EnableJpaAuditing on the spring-boot application

spring version:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.0</version>
    <relativePath />
</parent>

But when running the code like this:

@Service
@Transactional
/*package*/ class FooJobService{
   public void run() {
     FooJob job = createJob();
     ....
   }

   private FooJob createJob(){
      FooJob job = new FooJob();
      job.setSomeValue("123");
      //Do not set "finished" date here
      repo.saveAndFlush(job); //THIS LINE THROWS EXCEPTION
   }
}

Ill get the following exception:

org.springframework.dao.DataIntegrityViolationException: not-null property references a null or transient value : my.package.entity.FooJob.finished; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value : my.package.entity.FooJob.finished

Why does this not work?

CodePudding user response:

You need to annotate @EnableJpaAuditing in your main class or a Configuration class (a class with @Configuration)

and have to annotate Entity class with @EntityListeners(AuditingEntityListener.class).

CodePudding user response:

Add this to Entity if you only update finished date:

@EntityListeners(AuditingEntityListener.class)

CodePudding user response:

You need to add more annotations to your entity so it can be audited (at least @Audited, @AuditTable and @EntityListeners.

Example:

@Entity
@Table(name = "my_table")
@AuditTable("my_table_audit")
@Audited
@EntityListeners(AuditingEntityListener.class)
public class MyEntity{
  @Column(name = "created_date", nullable = false)
  @CreatedDate
  private Date createdDate;
  @Column(name = "modified_date")
  @LastModifiedDate
  private Date modifiedDate;
  @Column(name = "created_by")
  @CreatedBy
  private String createdBy;
  @Column(name = "modified_by")
  @LastModifiedBy
  private String modifiedBy;
  @Version
  private Long version;

Also I'm not sure if @LastModifiedDate can be used with type LocalDateTime.

You also need an auditing framework like Hibernate Envers.

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-envers</artifactId>
</dependency>

In case you are using Hibernate Envers and MySQL the auditing should be like this:

CREATE TABLE revinfo
(
    revision_number integer AUTO_INCREMENT,
    REVTSTMP bigint,
    CONSTRAINT revinfo_pkey PRIMARY KEY (revision_number)
);

CREATE TABLE IF NOT EXISTS my_table
(
    ...
    created_date                datetime DEFAULT now(),
    modified_date               datetime DEFAULT now(),
    created_by                  VARCHAR(100)  NULL,
    modified_by                 VARCHAR(100)  NULL,
    version                     INT           NULL
);

CREATE TABLE IF NOT EXISTS my_table_audit
(
    ...
    created_date                datetime,
    modified_date               datetime,
    created_by                  VARCHAR(100),
    modified_by                 VARCHAR(100),
    version                     INT,
    revision_number             integer,
    revision_type               smallint,
    FOREIGN KEY fk_my_table_audit_rev_num (revision_number) REFERENCES REVINFO (revision_number)
);
  • Related