Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JsonView-定义默认视图_Java_Spring_Jpa_Jackson_Spring Boot - Fatal编程技术网

Java JsonView-定义默认视图

Java JsonView-定义默认视图,java,spring,jpa,jackson,spring-boot,Java,Spring,Jpa,Jackson,Spring Boot,我正在开发一个SpringBoot(MVC,JPA)应用程序,它需要在不同的请求上返回不同的属性。我找到了@JsonView注释,它似乎可以工作。但是我需要用基本视图注释每个属性吗 例如: 实体1 @Entity public class Entity1 implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;

我正在开发一个SpringBoot(MVC,JPA)应用程序,它需要在不同的请求上返回不同的属性。我找到了@JsonView注释,它似乎可以工作。但是我需要用基本视图注释每个属性吗

例如:

实体1

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

    }
实体3

@Entity
public class Entity3 implements Serializable {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  private String name;
}
视图

public class JsonViews {
  public static class BasicView { }
  public static class ExtendedView extends BasicView { }
}
控制器

@RequestMapping(method = RequestMethod.GET)
  @JsonView(JsonViews.BasicView.class)
  public @ResponseBody List<Entity1> index() {

    return repositoryEntity1.findAll();

  }
@RequestMapping(method=RequestMethod.GET)
@JsonView(JsonViews.BasicView.class)
public@ResponseBody列表索引(){
return repositoryEntity1.findAll();
}
这是一个简化的例子,但我认为它适用于这个问题。我希望控制器返回id和
Entity2
对象列表。但它返回一个空对象,且“没有属性”。如果我注释了这个请求中涉及的每个类的每个属性,它似乎是有效的,但这是真的需要还是最好的解决方案?有没有办法定义“DefaultView”

谢谢


编辑:如果我对JpaRepository进行注释,它将返回整个对象,包括包含Entity3对象的列表。

否,您不需要在所有属性上定义视图。插入

spring.jackson.mapper.default view inclusion=true

在您的
应用程序.properties中。这将导致响应中包含不带
@JsonView
注释的属性,并且只过滤带注释的属性


在您的控制器中,将返回没有视图或带有
BasicView
注释的属性。

是的,您确实需要将其添加到每个变量中。请查看您的帖子。当您注释对象中的字段(该字段是另一个没有@JsonView注释的对象中的字段)时,第一个对象中的字段都将被包括在内。
@RequestMapping(method = RequestMethod.GET)
  @JsonView(JsonViews.BasicView.class)
  public @ResponseBody List<Entity1> index() {

    return repositoryEntity1.findAll();

  }