I have a weird (to me anyway) issue with Hibernate which I can't make any sense of. The code below is my attempt at modeling a ManyToOne relation with an attribute between the entities Case and Suggestion using an additional entity CaseToSuggestion with Case being my aggregate root:
@Entity
@Table(name = "sga_cases")
public class Case {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
// Business key
@Column(name = "caseid", unique = true, nullable = false)
private String caseId;
...
@OneToMany(mappedBy = "associatedCase", orphanRemoval = true, cascade = CascadeType.ALL)
private Set<CaseToSuggestion> associatedSuggestions = new HashSet<CaseToSuggestion>();
...
}
@Entity
@Table(name = "sga_suggestions")
public class Suggestion {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "suggestionid", unique = true, nullable = false)
private String suggestionId;
@Column(name = "localizationkey", nullable = false)
private String localizationKey;
@OneToMany(mappedBy = "associatedSuggestion", orphanRemoval = true, cascade = CascadeType.ALL)
private Set<CaseToSuggestion> caseMapping = new HashSet<CaseToSuggestion>();
...
}
@Entity
@Table(name = "sga_case2suggestion")
public class CaseToSuggestion {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "feedback")
private float feedback;
@ManyToOne
@JoinColumn(name = "caseid")
private Case associatedCase;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "suggestionid")
private Suggestion associatedSuggestion;
...
}
If I create new objects for the above entities, set the appropriate associations and then store them with the EntityManager everything works fine:
Case c = new Case(...)
Suggestion sugg = new Suggestion(...);
CaseToSuggestion case2sugg = new CaseToSuggestion(c, sugg, 1.0f);
c.getAssociatedSuggestions().add(case2sugg);
sugg.getAssociatedCases().add(case2sugg);
Followed by entityManager.persist(c);
If I want to add a new association to a Case that is already in the database I retrieve the Case and Suggestion entities I want to associate from the EntityManager and add them to a new CaseToSuggestion:
CaseToSuggestion c2s = new CaseToSuggestion(c, s, fb);
c.getAssociatedSuggestions().add(c2s);
s.getAssociatedCases().add(c2s);
Followed by entityManager.merge(c);
The the CaseToSuggestion entity is stored in the database but for every entry I get a "ghost entry" with a new generated id and all fields null:
+----+----------+--------+--------------+
| id | feedback | caseid | suggestionid |
+----+----------+--------+--------------+
| 3 | 1 | 3 | 1 |
| 4 | 1 | 4 | 2 |
| 5 | 1 | 5 | 2 |
| 6 | 0 | NULL | NULL |
| 7 | 1 | 6 | 2 |
| 8 | 0 | NULL | NULL |
| 9 | 1 | 7 | 2 |
| 10 | 0 | NULL | NULL |
+----+----------+--------+--------------+
Does anybody have an idea what might cause this?