I have a hibernate entity class
public class MyComplexClass implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String name;
int number;
@ElementCollection
Map<String,String> myMap;
@ManyToOne
Simple simple;
public MyComplexClass(String name, int number, Map<String,String> myMap) {
this.name = name;
this.port = number;
this.myMap = myMap;
}
public MyComplexClass() {
// TODO Auto-generated constructor stub
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setNumber(int number) {
this.port = number;
}
public int getPort() {
return port;
}
public void setMyMap(Map<String,String> myMap) {
this.myMap = myMap;
}
public Map<String,String> getMyMap() {
return this.myMap;
}
public Simple getSimple() {
return this.simple;
}
And in the class simple I have a mapping of the form
@Entity
@Table(name = "Simple")
public class Simple implements Comparable<Simple>, Serializable {
@JsonProperty
@OneToMany(mappedBy="simple",fetch = FetchType.EAGER,cascade = CascadeType.ALL)
Set<MyComplexClass> myComplexClass;
public void setMyComplexClass(List<MyComplexClass> myComplexClass) {
this.myComplexClass = myComplexClass;
}
public List<MyComplexClass> getMyComplexClass() {
return this.myComplexClass;
}
Somewhere in the system I set the values as
Map<String, String> myMap = new HashMap<String,String>();
myMap.put("value","value");
MyComplexClass myComplexClass = new MyComplexclass("a", 123, myMap)
Set<MyComplexClass> myComplexClassList = new HashSet<MyComplexClass>();
myComplexClassList.add(myComplexClassList)
simple.setMyComplexClass(myComplexClassList);
myComplexClass.setSimple(simple);
// save to the database
dao.save(simple);
This gets persisted in the database with multiple rows for my complex class with the same foreign key for the simple classs
Table: MyComplexClass
id name number simple_id
1 abc 234 1
2 abc 234 1
3 abc 234 1
4 abc 234 1
5 abc 234 1
6 xyz 432 2
7 xyz 432 2
8 xyz 432 2
What have I missed? The id for all these rows is different which makes me think that they have been initialized multiple times in the code. But they aren't. Any reason they have different entries? I am using AKKA actors, could that be a reason?
Based on various similar problems. I have changed the Collection to be a Set and also added a compareTo method as follows
public int compareTo(MyComplexClass o) {
if (o == null) {
return 1;
}
if (this.getName().equals(o.getName()) && this.getNumber() == o.getPort()) {
return 0;
}
return (int) (id - o.id);
}