'How to call repository method in entity listener
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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kashan Nadeem |