java – 杰克逊循环依赖

前端之家收集整理的这篇文章主要介绍了java – 杰克逊循环依赖前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个循环依赖,我现在正在努力解决
拿这两个类 – 去掉锅炉板代码用于演示目的

1级

@Entity
@Table(name = "T_CREDENTIAL")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class,property="@id")
public class Credential implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;


    //Removed @JsonIgnore as want to disable certain fields if no credentials are available    
    //Also fetch this in an eager fashion instead of lazily loading it
    @OneToMany(mappedBy = "credential",fetch=FetchType.EAGER)
    private Set

2级

@Entity
@Table(name = "T_USERTASK")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class,property="@id")
public class UserTask implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -8179545669754377924L;


    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;


    @ManyToOne(fetch=FetchType.EAGER)
    @NotNull(message = "Credential must not be null")
    private Credential credential;

不幸的是,我有一些用例,其中UserTask需要加载凭据和Credential需要加载Usertasks的情况

@JsonIdentityInfo注释似乎正在完成它的工作
如果我加载所有UserTasks,它会加载第一个userTask及其凭据,但随后该凭据对象还将加载分配给该凭证的任何UserTasks.然后会遇到新的@Id或userTask,现在用凭证加载它而不是2个用户任务

有什么想法我可以做些什么来规避这个问题?

干杯
达米安

– 问题更新
我现在更新了我的代码以使用其他用户提到的新注释

1级

    @Entity
@Table(name = "T_CREDENTIAL")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Credential implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -8696943454186195541L;



    //Removed @JsonIgnore as want to disable certain fields if no credentials are available    
    //Also fetch this in an eager fashion instead of lazily loading it
    @OneToMany(mappedBy = "credential",fetch=FetchType.EAGER)
    @JsonManagedReference("credential")
    private Set

2级

@Entity
@Table(name = "T_USERTASK")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class UserTask implements Serializable {


    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    private Long id;

    @ManyToOne(fetch=FetchType.EAGER)
    @NotNull(message = "Credential must not be null")
    @JsonBackReference("credential")
    private Credential credential;
....
....

现在这些类现在可以工作,并且没有循环依赖
但是,当我现在进行查询获取我的usertasks或单个任务时,即使我没有指定@jsonIgnore注释,也不会返回凭证对象.是什么原因引起了这个?

最佳答案
如果你使用Jackson HttpMessageConverter,你应该查看他们的文档 – http://wiki.fasterxml.com/JacksonFeatureBiDirReferences

您应该添加此处显示的注释:

public class NodeList
{
    @JsonManagedReference
    public List
原文链接:https://www.f2er.com/spring/431539.html

猜你在找的Spring相关文章