Reputation: 49
I'm going trough some trouble. I am coding the back-end of a website in spring and I am using a Rest API. I created two classes that are the relation "ManyToMany". The first class is "StateOfArt" and the second is "Tag". When I start the server , I post 2 StateOfArt in Json (I'm using Insomnia) and it's working pretty well. I mean The two StateOfArt are in my DB. The problem is that Tags are duplicated even if the two StateOfArt have the same tags.
Here is an example: I'm posting two StateOfArt in Json and this is ma DB:
I would like to have this in my join table:
1 1
1 2
2 1
2 2
And I would like to not have the redundancy in the table tag.
Is it possible to help me ?
Here the code of my two classes:
@Entity(name = "StateOfArt")
public class StateOfArt {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Integer id;
private String author;
private String title;
private String date;
private ArrayList<String> co_author;
private String theabstract;
//@ManyToMany(fetch = FetchType.LAZY ,cascade = {CascadeType.ALL})
@ManyToMany(fetch = FetchType.LAZY, cascade = {
CascadeType.ALL
})
@JoinTable(name = "state_of_art_tag",
joinColumns = @JoinColumn(name = "stateofart_id"),//, referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "tag_id"))//, referencedColumnName = "id"))
//@JsonIgnore
private Set<Tag> tags = new HashSet<>();
public StateOfArt(){}
public StateOfArt(Integer id, String author, String title, String date,ArrayList<String> co_author,String theabstract, HashSet<Tag> tags){
super();
this.id = id;
this.title = title;
this.author =author;
this.date =date;
this.co_author = co_author;
this.theabstract = theabstract;
//this.articles = articles;
this.tags = tags;
}
//Getters and Setters are here
}
@Entity(name = "Tag")
@Table(name = "tag_for_stateofart")
public class Tag {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
Integer id;
@Column(length = 50)
private String name;
@ManyToMany(mappedBy = "tags")
private Set<StateOfArt> stateofarts = new HashSet<>();
public Tag() {}
public Tag(String name) {
this.name = name;
}
public String getTag() {
return this.name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tag tag = (Tag) o;
return Objects.equals(name, tag.name);
}
}
Thank you for your help.
Upvotes: 0
Views: 342
Reputation: 2933
Probably you are creating the same tag again. Check if tag with that name exists in DB, if yes, load it from Tag table.
Upvotes: 1
Reputation: 870
It must be a problem with tags table in your your database. When you create the table you should specify column name in tags table to have unique values.
Upvotes: 0