Reputation: 277
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.
Upvotes: 1
Views: 989
Reputation: 123
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.
Upvotes: 1