Spring Data Conservation Projection for Inline Objects

Suppose I have the following objects:

@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();

}

I am trying to create the following JSON view, so when I use http://localhost:8080/api/registrations?projection=minimal, I do not need all user data:

{
  "_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}",
      }
    }
  }
}

However, the Projection I created I get an exception (it works without the getUserName () operator. Obviously, I did not correctly define the interface ... but what is the right way to do something like this?

EDIT: The exception is as follows

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>
+4
source share
1 answer

As an exception, the specified is userNamenot a member of the object Registration. That is why he failed. But I think you already understand that.

, Registration, :

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

types = {Registration.class, Student.class}, Spring Data Rest Registration.class Student.class. , /. types .

: , , ):

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

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

, SPeL, getUserName this.getStudent().getUserName(), target (. ).

+9

All Articles