1 回答

TA貢獻1789條經驗 獲得超10個贊
你有這個問題,因為你的方法顯式返回一個AbstractHistory而不是子類型。
你需要投...
...如果只有您的存儲庫實現理解每個 T 您都會獲得特定的歷史記錄。
您可以嘗試添加另一種類型,但我擔心它會失敗:
public interface IHistoryRepository<
T,
H extends AbstractHistory<T>
> extends CrudRepository<H, Long> {
public H findFirst();
}
public interface StudentHistoryRepository extends IHistoryRepository<Student, StudentHistory> {}
public interface TeacherHistoryRepository extends IHistoryRepository<Teacher, TeacherHistory> {}
我不知道您使用的是什么框架,可能是名稱中的 Spring Data;雖然我過去用過它,但我不知道它是否能夠做到這一點。
畢竟,它需要獲取具體類,并且由于它是泛型,因此類型擦除可能會干擾(如果關于表示 H 的具體類型的信息在反射中丟失,那么 Spring Data 在這里可能無法做太多事情,除非您用注釋或其他東西幫助它)。
另一個應該可行的解決方案是按每個子界面執行此操作:
public interface StudentHistoryRepository extends CrudRepository<StudentHistory, Long> {
StudentHistory findFirst();
}
或者使用另一個接口:
public interface FindFirst<T> {
T findFirst();
}
public interface StudentHistoryRepository extends CrudRepository<StudentHistory, Long>, FindFirst<StudentHistory> {}
添加回答
舉報