Direct self-reference leading to cycle exception

后端 未结 5 649
执笔经年
执笔经年 2021-01-04 00:18

I have a class; something like the following:

public abstract class ElasticSearchValue {

  private Long txId;
  private Long currentTxId;
  private         


        
相关标签:
5条回答
  • 2021-01-04 00:23

    Try @JsonIdentityInfo annotation as given in this example. More details here http://wiki.fasterxml.com/JacksonFeatureObjectIdentity

    @JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
    public class Identifiable
    {
        public int value;
    
        public Identifiable next;
    }
    
    0 讨论(0)
  • 2021-01-04 00:23

    I guess somewhere in your code. The previous of some instance of DailyActivity point to itself.

    0 讨论(0)
  • 2021-01-04 00:28

    The self-reference is here:

    public class DailyActivity extends ElasticSearchValue<DailyActivity> {
    

    You're saying DailyActivity is an ElasticSearchValue<DailyActivity>, which is by itself an ElasticSearchValue<ElasticSearchValue<DailyActivity>>, and this goes on infinitely...

    Update: I would break that in two classes. Create DailyActivity without subclassing ElasticSearchValue:

    public class DailyActivity {
      // the same content as your class above
    

    then create another class like:

    public class ElacticDailyActivity extends ElasticSearchValue<DailyActivity> {
    
    0 讨论(0)
  • In this case you need to annotate the relationships with @JsonManagedReference and @JsonBackReference like this:

     @ManyToOne
     @JoinColumn(name = "company_id", referencedColumnName = "id")
     @JsonBackReference
     private Company company 
    

    And

     @OneToMany(mappedBy="company")
     @JsonManagedReference
     private Set<Employee> employee = new HashSet<Employee>();
    

    There is a nice example here

    0 讨论(0)
  • 2021-01-04 00:45

    SerializationFeature has a property called FAIL_ON_SELF_REFERENCES default is true but you can set to false to skip this kind of exception.

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, false);
    

    If you are using SpringBoot you can simply add spring.jackson.serialization.fail-on-self-references=false in your application.properties

    0 讨论(0)
提交回复
热议问题