lundi 2 mars 2015

JsonView - define Default View

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.


Aucun commentaire:

Enregistrer un commentaire