2015-05-15 65 views
4

讓我們假設我有以下實體:春數據休息投影嵌入式實體

@Entity 
public class Registration { 

    @ManyToOne 
    private Student student; 
    //getters, setters 
} 

@Entity 
public class Student { 

    private String id; 
    private String userName; 
    private String name; 
    private String surname; 
    //getters, setters 
} 

@Projection(name="minimal", types = {Registration.class, Student.class}) 
public interface RegistrationProjection { 

    String getUserName(); 
    Student getStudent(); 

} 

我試圖創建下面的JSON表示,所以,當我使用http://localhost:8080/api/registrations?projection=minimal我不需要所有的用戶數據來沿着:

{ 
    "_links": { 
    "self": { 
     "href": "http://localhost:8080/api/registrations{?page,size,sort,projection}", 
    } 
    }, 
    "_embedded": { 
    "registrations": [ 
     { 
     "student": { 
      "userName": "user1" 
     } 
     } 
    ], 
    "_links": { 
     "self": { 
     "href": "http://localhost:8080/api/registrations/1{?projection}", 
     } 
    } 
    } 
} 

但是我已經制作的投影我得到一個異常(它的工作原理沒有getUserName()語句很顯然,我已經定義的方式是錯誤的界面...但它是做正確的方法像這樣?

編輯:異常是以下

Invalid property 'userName' of bean class [com.test.Registration]: 
Could not find field for property during fallback access! (through reference chain: org.springframework.hateoas.PagedResources["_embedded"] 
->java.util.UnmodifiableMap["registrations"]->java.util.ArrayList[0]->org.springframework.data.rest.webmvc.json.["content"] 
-&gt;$Proxy119[&quot;userName&quot;])</div></body></html> 
+0

如果你分享你得到的異常,可能會有幫助嗎? –

回答

9

作爲例外所述userName不是Registration實體的成員。那爲什麼它失敗了。但我認爲你已經明白了。

首先,在所有的,如果你只是想揭露其投影爲Registration你應該首先更改以下行:

@Projection(name="minimal", types = {Registration.class, Student.class}) 

通過設置types = {Registration.class, Student.class}你問春數據休息就Registration.classStudent.class應用計劃。這可能會導致一些問題,因爲根據類型你不應該有相同的成員/方法。在實踐中types必須共享一個共同的祖先。

否則,對於主要的問題,你應該嘗試virtual projections以後的事(我沒有嘗試在你的樣品,但它應該工作,我希望):

@Projection(name="minimal", types = {Registration.class}) 
public interface RegistrationProjection { 

    @Value("#{target.getStudent().getUserName()}") 
    String getUserName(); 
} 

我不知道你是否熟悉與SPeL但前面的代碼只是創建一個getUserNamethis.getStudent().getUserName(),因爲target綁定在實例對象上(請參閱文檔)。

+0

你似乎對預測有所瞭解。可能是一個奇怪的問題,但是你知道是否可以在不寫入自定義控制器的情況下向PATCH請求的POST添加投影。我們的API是在春天生成的。 – user1758777

+0

@ user1758777不幸的是,由於數年以來我沒有使用Spring數據休息,所以我不能幫助您,但我不認爲僅僅可以爲POST或PATCH進行投影。我建議你打開一個新的堆棧問題或向Spring數據休息Gitter提問 – Kakawait