Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AuditingEntityListener is not working for the entity that extends another abstract entity in spring jpa

I have used the @CreatedBy, @CreatedDate, @LastModifiedBy, and @LastModifiedDate annotation on their respective fields. By using @MappedSuperclass,@EntityListeners i able to persist above columns.

But this is not working for the below case:

@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable<U> {
    @CreatedBy
    protected U createdBy;
    @CreatedDate
    @Temporal(TIMESTAMP)
    protected Date creationDate;
    @LastModifiedBy
    protected U lastModifiedBy;
    @LastModifiedDate
    @Temporal(TIMESTAMP)
    protected Date lastModifiedDate;
}

@Entity
@Table(name = "tabel1")
@PrimaryKeyJoinColumn(name = "ID")
class A extends B {

    @Column(name = "NAME1", nullable = false)
    private String name1;
    @Column(name = "CONTENT1", nullable = false)
    private String content1;
}

@Entity
@Table(name = "tabel2")
public abstract class B extends Auditable{
    @Id
    @GeneratedValue
    @Column(name = "ID", nullable = false)
    private int id;
    @Column(name = "NAME", nullable = false)
    private String name;
    @Column(name = "CONTENT", nullable = false)
    private String content;
}

AuditorAwareImpl.java

public class AuditorAwareImpl implements AuditorAware<String>
{
    @Override
    public Optional<String> getCurrentAuditor()
    {
        return Optional.ofNullable("Saravanan");

    }

}

JpaAuditConfiguration.java

@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
public class JpaAuditConfiguration
{
    @Bean
    public AuditorAware<String> auditorProvider()
    {

        return new AuditorAwareImpl();
    }
}

In the case, Entity B is populated with audit columns. But Entity A is not. Is there a way to populate Entity A or did i missed anything here..??

like image 827
Saravanan Avatar asked Oct 22 '25 03:10

Saravanan


1 Answers

I added @Entity annotation to your classes:

@Entity
public class A extends B {

    @Id
    @GeneratedValue
    private Integer id;

    private String name;
    private String content;

}

@Entity
public class B extends Auditable<String> {

    @Id
    @GeneratedValue
    private Integer id;

    private String name;
    private String content;
}

Persistence config class (for Spring Boot):

@Configuration
@EnableJpaAuditing
public class PersistenceConfig {
}

Everything works perfectly!

like image 158
huytmb Avatar answered Oct 24 '25 13:10

huytmb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!