繁体   English   中英

具有双向关系时,仅在从关系的一侧访问时如何避免出现字段

[英]When having a bidirectional relationship, how to avoid a field only when accessing from one side of the relationship

我有两节课:

@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, 
property = "id")
public class Client {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "client_id")
private Long id;
private char gender;
@OneToMany(mappedBy = "client", cascade = CascadeType.ALL)
private List<SurveyData> survey = new ArrayList<SurveyData>(); }

和SurveyData:

@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, 
property = "id")
public class SurveyData{

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "SURVEY_ID")
private Long Id;
private double score;
@ManyToOne
@JoinColumn(name = "client_id")
public Client client; }

通过这种方式,当我访问SurveyData时,也可以得到客户端模型。 当我访问客户端时,我也会获得SurveyData。 但是我的问题是这个。 我有一个查询会根据条件返回SurveyData,因此说我会将其作为JSON结果:

{id:1
 client:
        {name: Name,
         lastName: last,
         survey:[{
           score: 10,
             ///
          }]

从SurveyData访问时,如何避免获得调查列表。 我无法使用JsonIgnore,因为我还有其他方法可以在访问客户端模型时使用列表来访问调查模型。 有没有办法做到这一点 ?

因此,基本上,仅在调用SurveyData时,我需要忽略Client类中的List调查。否则,我需要使用它。

请看看@JsonView Message类示例中,它提供了一个使用@JsonView(View.Summary.class)@JsonView(View.SummaryWithRecipients.class)的漂亮示例。

public class View {
    interface Summary {}
    interface SummaryWithRecipients extends Summary {}
}

public class Message {

    @JsonView(View.Summary.class)
    private Long id;

    @JsonView(View.Summary.class)
    private LocalDate created;

    @JsonView(View.Summary.class)
    private String title;

    @JsonView(View.Summary.class)
    private User author;

    @JsonView(View.SummaryWithRecipients.class)
    private List<User> recipients;

    private String body;
}

现在,根据注释,它将包括或排除收件人列表。

// excludes list of recipients
@JsonView(View.Summary.class)
@GetMapping("/")
public List<Message> getAllMessages() {
    return messageService.getAll();
}

// includes list of recipients
@JsonView(View.SummaryWithRecipients.class)
@GetMapping("/with-recipients")
public List<Message> getAllMessagesWithRecipients() {
    return messageService.getAll();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM