Specific relations between two entity

30 Views Asked by At

Please help me with architecture of my Spring Boot app.I want to create a Dictionary in which I can put some words with transcriptions, translation and set of synonyms. So the question is: i have a Word entity and every word can have some set of synonyms,BUT I can't understand how to create a relations between Word and Synonym because synonym is also a word per se. I can't define a Set synonyms within Word entity. So how I can implement it? What I try but I understand that this is stupid way:

@Table(name = "Word")
public class Word {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;
    @NotBlank(message = "You should add some word here!")
    @Column(name = "spelling")
    private String spelling;
    @Column(name = "transcription")
    private String transcription;
    @NotBlank(message = "You should add translation here!")
    @Column(name = "translation")
    private String translation;
    @ManyToOne
    @JoinColumn(name = "synonyms_id", referencedColumnName = "id")
    private Synonyms synonyms;
    @ManyToOne
    @JoinColumn(name = "dictionary_id", referencedColumnName = "id")
    private Dictionary dictionary;
@Table(name = "Synonyms")
public class Synonyms {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;
    @OneToMany(mappedBy = "synonyms", fetch = FetchType.LAZY)
    private Set<Word> words;
1

There are 1 best solutions below

1
Shariq Shaikh On
I think according to your use-case if a word is also a synonym then you don't need another entity to make relationship
        and you can create a many to many relationship means a word can be associated with synonyms and also a word can be synonyms of other words just like this

@ManyToMany
        @JoinTable(
            name = "word_synonyms", 
            joinColumns = @JoinColumn(name = "word_id"), 
            inverseJoinColumns = @JoinColumn(name = "synonym_id")
        )
     private Set<Word> synonyms = new HashSet<>();

     @ManyToMany(mappedBy = "synonyms")
     private Set<Word> synonymousOf = new HashSet<>();