Ankish Gupta
Ankish Gupta

Reputation: 71

Hibernate Envers Custom Listener not working with Spring Data JPA

I'm trying to implement custom revision entity with my Spring application to add username in the revision table. But the revinfo table is only having rev and revtstmp columns, the username column is not getting generated. I'm using Spring Data JPA. Below is the code I've tried:

import com.xyz.listener.MyRevisionListener;
import org.hibernate.envers.DefaultRevisionEntity;
import org.hibernate.envers.RevisionEntity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "revinfo")
@RevisionEntity(MyRevisionListener.class)
public class MyRevisionEntity extends DefaultRevisionEntity {
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Column(name = "username")
    private String username;
}
import com.xyz.entity.MyRevisionEntity;
import org.hibernate.envers.RevisionListener;

public class MyRevisionListener implements RevisionListener {

    @Override
    public void newRevision(Object revisionEntity) {
        MyRevisionEntity rev = (MyRevisionEntity) revisionEntity;
        String userId = ContextAccessor.getUserId();
        rev.setUsername(userId);
    }
}

The above code works fine if I directly add the above classes in my microservice, and username is properly populated in revinfo table. But I'm trying to create an audit jar which has these classes, and then I add the jar in my microservice, then MyRevisionListener is not called.

If I add spring.jpa.properties.org.hibernate.envers.revision_listener=com.xyz.listener.MyRevisionListener in application.properties, then the listener is called but I get the error java.lang.ClassCastException: org.hibernate.envers.DefaultRevisionEntity cannot be cast to com.xyz.entity.MyRevisionEntity

Upvotes: 2

Views: 2536

Answers (1)

Ankish Gupta
Ankish Gupta

Reputation: 71

Solution:

The problem was since it was added as library, Spring application was ignoring MyRevisionEntity. Add the package of MyRevisionEntity in the @EntityScan and it will work.

Upvotes: 1

Related Questions