亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

與 Spring Data JPA 和泛型類型混淆

與 Spring Data JPA 和泛型類型混淆

九州編程 2021-10-27 16:21:01
表格:StudentHistory 1--->n StudentTeacherHistory 1--->n Teacher我嘗試重新組合歷史的 JPA 行為,因為它們做同樣的事情(例如,從給定的歷史中檢索學生/老師)。具有泛型類型的實體:// Entitiespublic abstract class AbstractHistory <T> {}public class StudentHistory extends AbstractHistory<Student> {}public class TeacherHistory extends AbstractHistory<Teacher> {}具有通用類型的存儲庫:// repositoriespublic interface IHistoryRepository<T> extends CrudRepository<AbstractHistory<T>, Long> {    public AbstractHistory<T> findFirst();}    public interface StudentHistoryRepository extends IHistoryRepository<Student> {}public interface TeacherHistoryRepository extends IHistoryRepository<Teacher> {}我雖然可以這樣做:StudentHistory stuHisto = new StudentHistoryRepository().findFirst(); 但我收到此錯誤:    // err ->  Type mismatch: cannot convert from AbstractHistory<Student> to StudentHistory1/ 為什么我不能從我的 'StudentHistoryRepository' 中檢索一個 'StudentHistory' ?2/ 我應該如何處理?
查看完整描述

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> {}


查看完整回答
反對 回復 2021-10-27
  • 1 回答
  • 0 關注
  • 227 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號