Ilja Veselov
Ilja Veselov

Reputation: 99

Entities relationships design to avoid recursion (Many-To-Many)

I am building small app which is Estonian-English-Estonian dictionary. English and estonian words are represented as Entities (tables) in database. Each entity contains word/phrase on its language and List of translations which List<Translation language>. I have many-to-many relationships between them - what means that many english words have many estonian translations and many estonian words have many english translations. (which seems to me logical). I am facing the problem when I am fetching a word on either language and getting JSON representation - infinite loop occurs, which is expected because each entity contains list of opposite entities and those entities contain List of opposite entities and so on... How would be possible to solve this problem? NOTE: I tried adding @JsonIgnore to either side - but when I fetch this side entity I have not resolved List of other entities and vice-versus. @JsonManaged and @JsonBacked do not solve the problem also. I need both sides entities to be resolved but without recursion.

@Entity
@Table(name = "english_word")
public class EnglishWord {

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

   @Column(name = "word")
   private String word;


   @ManyToMany(cascade = CascadeType.PERSIST)
   @JoinTable(name = "estonian_english",joinColumns = @JoinColumn(name = "englishWord_id")
   ,inverseJoinColumns = @JoinColumn(name = "estonianWord_id"))
   private List<EstonianWord> translations = new ArrayList<>();

   public EnglishWord(String word) {
       this.word = word;
   }

   public EnglishWord() {
   }
-------------------------------------------------------------------

@Entity
@Table(name = "estonian_word")
public class EstonianWord {

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

   @Column(name = "word")
   private String word;


   @ManyToMany(cascade = CascadeType.PERSIST)
   @JoinTable(name = "estonian_english",joinColumns = @JoinColumn(name = "estonianWord_id")
           ,inverseJoinColumns = @JoinColumn(name = "englishWord_id"))
   private List<EnglishWord> translations = new ArrayList<>();

   public EstonianWord(String word) {
       this.word = word;
   }

   public EstonianWord() {
   }


Upvotes: 0

Views: 397

Answers (1)

M. Dudek
M. Dudek

Reputation: 1085

You can use own DTO object to represent request/response.

Upvotes: 2

Related Questions