How to call repository method in entity listener

676 views Asked by At

I'm trying to make call to repository inside my Entity Listener, when I call repository.findById() method inside my @prePersist method the same method is calling multiple time and I'm getting null pointer exception :

Here is code :

@Component
public class MyListener {

    public MyListener () {
        
    }
    
    private static MyRepo myRepo;

    @Autowired
    public void setMyRepo(MyRepo myRepository) {
        MyListener.myRepo= myRepository;
    }

    @PreUpdate
    @PrePersist
    public void preUpdate(MyEntity myEntity ) {
        
        MySecondEntity mySecondEntity = myRepo.findById(true);

        if(! myEntity.value.equals(mySecondEntity.getValue())) {
            myEntity.setNewValue(mySecondEntity.getValue());
        }
    }
}

Entity :

@Entity
@EntityListeners({MyListener .class})
public class MyEntity {
    //properties goes here
}

So my requirement here to get a value from one table and check with the entry in MyEntity table and save it before any save or update in MyEntity table. Any help is appreciated.

1

There are 1 answers

0
Kashan Nadeem On

You are getting NPE because MyListener is getting instantiated by Hibernate and not Spring AOP, thus MyRepo cannot be Autowired. I am not sure that a solution exists for what you are trying to do.

The best solution would be to change your approach.