簡體   English   中英

Spring數據REST findBy嵌套實體

[英]Spring data REST findBy nested entity

我有一個使用Spring-data-rest的Spring Boot項目來生成我的REST接口,我試圖允許嵌套資源的分頁。 我遵循這個解決方法,並堅持實現findBy查詢。

我有以下設備實體:

@Entity
@Table(name = "devices")
public class Device extends ResourceSupport {

  ...

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "user_id")
  private User user;
}

我需要使用userId查詢它:

@RequestMapping(path = "/users/{id}/devices", method = RequestMethod.GET)
public ModelAndView getUserDevices(@PathVariable Integer id) {
    return new ModelAndView("forward:/devices/search/findByUserId?userId=" + id);
}

所以我在DeviceRepository中創建了以下方法:

@Repository
public interface DeviceRepository extends JpaRepository<Device, Long> {

  @PreAuthorize("hasRole('ROLE_ADMIN') OR @securityCheck.check(#user, authentication)")
  Page<Device> findByUserId(@Param("user") User user, Pageable pageable);

}

但是在嘗試向此端點發送請求時,我收到以下異常:

Unable to locate Attribute  with the the given name [id] on this ManagedType [com.example.User]

有沒有人有一些建議我做錯了什么?

編輯:謝謝你的回復,我改變了方法

Page<Device> findByUser_UserId(@Param("user") User user, Pageable pageable);

我的用戶實體包含userId字段。

但是,現在我收到以下異常:

{
    "cause": {
        "cause": {
            "cause": null,
            "message": "Cannot resolve URI 1. Is it local or remote? Only local URIs are resolvable."
        },
        "message": "Failed to convert from type [java.net.URI] to type [@org.springframework.data.repository.query.Param com.example.User] for value '1'; nested exception is java.lang.IllegalArgumentException: Cannot resolve URI 1. Is it local or remote? Only local URIs are resolvable."
    },
    "message": "Failed to convert 1 into me.originalsin.user.model.User!"
}

所以我似乎錯誤地使用了查詢?

請查看文檔

屬性表達式只能引用被管實體的直接屬性,如前面的示例所示。 在查詢創建時,您已確保已解析的屬性是托管域類的屬性。 但是,您也可以通過遍歷嵌套屬性來定義約束。 假設一個人有一個帶ZipCode的地址。 在這種情況下,方法名稱為

List<Person> findByAddressZipCode(ZipCode zipCode);

[...]雖然這應該適用於大多數情況,但算法可能會選擇錯誤的屬性。 假設Person類也有一個addressZip屬性。 該算法將在第一個拆分輪中匹配,並且基本上選擇了錯誤的屬性並最終失敗(因為addressZip的類型可能沒有代碼屬性)。 要解決這種歧義,可以在方法名稱中使用_來手動定義遍歷點。 所以我們的方法名稱最終會像這樣:

List<Person> findByAddress_ZipCode(ZipCode zipCode);

這意味着:除了您的Device類具有字段userId之外,您所做的工作應該有效。

您向我們展示的例外是原始問題中的以下內容。

無法在此ManagedType [com.example.User]上找到具有給定名稱[id]的Attribute

這看起來像您的類User沒有名為id的字段。 既然你沒有向我們展示這個類的代碼我就不知道是不是這樣。 (確保在存儲庫中導入了正確的User類)

問題已更新,因此另一個答案存在另一個錯誤

現在的問題是您將User對象傳遞給存儲庫方法,但按ID過濾。 只需將第一個參數更改為用戶標識的數據類型即可。 我認為這應該有效。

假設id的類型為int該方法可能如下所示

Page<Device> findByUser_UserId(@Param("userId") int userId, Pageable pageable);

嘗試

 Page<Device> findByUser_Id(@Param("user") User user, Pageable pageable);

由於您要在DeviceRepository中創建方法,並且要在嵌套字段(user.id)上進行搜索,因此需要使用“_”進行引用

暫無
暫無

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

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