2015-10-21 18 views
1

香草實體用戶 -爲什麼Spring HATEOAS返回導致JSON反序列化異常的重複鏈接?

public class User implements Serializable { 
    private static final long serialVersionUID = 262950482349139355L; 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 

    @Column(name = "FIRST_NAME", nullable = false, unique = false) 
    @Convert(converter = NameConverter.class) 
    private String firstName; 

    @Column(name = "LAST_NAME", nullable = false, unique = false) 
    @Convert(converter = NameConverter.class) 
    private String lastName; 

    @Column(name = "PHONE_NUM", nullable = false, unique = false) 
    @Convert(converter = PhoneNumberConverter.class) 
    private String phoneNum; 

    @Column(name = "EMAIL", nullable = true, unique = false) 
    @Convert(converter = OptionalStringConverter.class) 
    private Optional<String> email; 
} 

搜索與主機名導致URL變了 - 現在

{ 
    "_links" : { 
    "self" : { 
     "href" : "http://hostname/users/search/findByLastName?lastName=doe{&page,size,sort}", 
     "templated" : true 
    } 
    }, 
    "_embedded" : { 
    "users" : [ { 
     "firstName" : "John", 
     "lastName" : "Doe", 
     "phoneNum" : "111-111-1111", 
     "email" : null, 
     "_links" : { }, 
     "_embedded" : { }, 
     "_links" : { 
     "self" : { 
      "href" : "http://hostname/users/1", 
      "templated" : false 
     } 
     } 
    } ] 
    }, 
    "page" : { 
    "size" : 20, 
    "totalElements" : 1, 
    "totalPages" : 1, 
    "number" : 0 
    } 
} 

編輯 2個_links:

重複的鏈接不存在,當資源訪問它自己的。但是,當客戶(我的情況下是一個微服務)使用RestTemplate發出請求時,響應會返回2 _links,如上所示。我使用Spring Data JPA,Spring Data Rest,Spring HATEOAS和Spring Cloud。我使用Spring Data JPA,Spring Data Rest,Spring HATEOAS和Spring Cloud。這是我的Github上的link to the project

完全披露:我已經在Spring HATEOAS Github上提交了一個問題。

+0

請告訴我們你的代碼,你組裝的資源。實體和預期的結果是不夠的。我們在自己的軟件中做了一個非常類似的事情,它很有用。 –

+0

@ThomasUhrig我不組裝資源。我正在使用Spring JPA爲我做這件事。我已經更新了我的帖子,澄清了這一點,並提供了一段代碼鏈接。 –

+0

我不想通過你的GitHub倉庫來修復你的東西。請發佈相關代碼。實體和結果在這種情況下不相關。如果我會瀏覽你的回購 - 理論上 - 我會說你用一個'PersistentEntityResourceAssembler'在你的控制器中組裝你的資源。但是在你做之前,你會手動鏈接到UserSearchResult。所以,是的,你組裝的資源,你做錯了。所以顯示代碼。 –

回答

0

首先,您使用的不僅僅是spring-hateoas的spring-data-rest。所以你沒有資源和控制器。我認爲這是這裏的主要誤解。

我認爲你的自定義存儲庫有問題。從UserRepositoryCustomImpl

  • 刪除@Repository
  • 化妝UserRepository延長UserRepositoryCustom

所以

public interface UserRepository extends JpaRepository<User, Long>, UserRepositoryCustom 

我會改變兩件事

public class UserRepositoryCustomImpl implements UserRepositoryCustom 

這是你需要,以實現自定義庫的方法是什麼:

又見http://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/#repositories.custom-implementations

+0

我沒有使用'UserRepositoryCustom',我最初提出這個想法,但沒有最終使用它。 UserRepository'只是擴展'JpaRepository' '公共接口UserRepository擴展JpaRepository {...}' –

+1

我確認UserRepositoryCustom與這個問題無關(通過刪除UserRepositoryCustom)。我在帖子中添加了更多信息。 –