Cyclic references in a bidirectional many to many relationship

后端 未结 2 1541
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-12 00:53

I\'m having a bidirectional many to many relationship in my entities. See the example below:

public class Collaboration {

    @JsonManagedReference(\"COLLAB         


        
相关标签:
2条回答
  • 2021-01-12 01:28

    I ended up implementing the following solution.

    One end of the relationship is considered to be the parent. It does not need any Jackson related annotation.

    public class Collaboration {
    
        private Set<Tag> tags;
    
    }
    

    The other side of the relationship is implemented as follows.

    public class Tag {
    
        @JsonSerialize(using = SimpleCollaborationSerializer.class)
        private Set<Collaboration> collaborations;
    
    }
    

    I'm using a custom serializer to will make sure that no cyclic references will occur. The serializer could be implemented like this:

    public class SimpleCollaborationSerializer extends JsonSerializer<Set<Collaboration>> {
    
        @Override
        public void serialize(final Set<Collaboration> collaborations, final JsonGenerator generator,
            final SerializerProvider provider) throws IOException, JsonProcessingException {
            final Set<SimpleCollaboration> simpleCollaborations = Sets.newHashSet();
            for (final Collaboration collaboration : collaborations) {
                simpleCollaborations.add(new SimpleCollaboration(collaboration.getId(), collaboration.getName()));                
            }
            generator.writeObject(simpleCollaborations);
        }
    
        static class SimpleCollaboration {
    
            private Long id;
    
            private String name;
    
            // constructors, getters/setters
    
        }
    
    }
    

    This serializer will only show a limited set of the properties of the Collaboration entity. Because the "tags" property is omited, no cyclic references will occur.

    A good read about this topic can be found here. It explains all possibilities when you're having a similar scenario.

    0 讨论(0)
  • 2021-01-12 01:46

    very handy interface implementation is provided in jackson 2 library as

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

    in maven

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.0.2</version>
    </dependency>
    
    0 讨论(0)
提交回复
热议问题