簡體   English   中英

如何在實體偵聽器中調用存儲庫方法

[英]How to call repository method in entity listener

我正在嘗試在我的實體偵聽器中調用存儲庫,當我在 @prePersist 方法中調用 repository.findById() 方法時,同一方法正在多次調用並且我得到 null 指針異常:

這是代碼:

@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
@EntityListeners({MyListener .class})
public class MyEntity {
    //properties goes here
}

所以我在這里的要求是從一個表中獲取一個值並檢查 MyEntity 表中的條目並在 MyEntity 表中進行任何保存或更新之前保存它。 任何幫助表示贊賞。

您正在獲得 NPE,因為MyListener正在由 Hibernate 而不是 Spring AOP 實例化,因此無法自動裝配MyRepo 我不確定您正在嘗試做的事情是否存在解決方案。

最好的解決方案是改變你的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM