I am working on a Spring boot (MVC, JPA) application and it is required to return different attributes on different requests. I found the @JsonView annotation and it seems to work. But do I need to annotate every attribute with a basic view?
Example:
Entity1
@Entity
public class Entity1 implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonView(JsonViews.ExtendedView.class)
private String name;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "entity1", fetch = FetchType.EAGER)
List<Entity2> entities2;
@JsonView(JsonView.ExtendedView.class)
@OneToMany(cascade = CascadeType.ALL, mappedBy = "entity1", fetch = FetchType.LAZY)
List<Entity3> entities3;
}
Entity2
@Entity
public class Entity2 implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
Entity3
@Entity
public class Entity3 implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
Views
public class JsonViews {
public static class BasicView { }
public static class ExtendedView extends BasicView { }
}
Controller
@RequestMapping(method = RequestMethod.GET)
@JsonView(JsonViews.BasicView.class)
public @ResponseBody List<Entity1> index() {
return repositoryEntity1.findAll();
}
This is a trimmed example but I think it applies to the problem. I expect that the controller returns the Ids and the list of Entity2
objects. But it returns an empty object with "No Properties". If I annotate every attribute of every class involved in this request, it seems to work, but is this really needed or the best solution? Is there a way to define a "DefaultView"?
thanks
Edit: If I annotate the JpaRepository it returns the entire object including the list with Entity3 objects.
No, you do not need to define views on all properties. Insert
spring.jackson.mapper.default-view-inclusion=true
in your application.properties
. This will cause properties without the @JsonView
annotation to be included in the response and only the annotated properties will be filtered.
In your Controller, properties without a view or with the BasicView
annotated will be returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With