In my struts action I retrieve an object X from the database, get a reference to a one to many collection it contains, add a few objects to this collection and save the original object X.
Problem is I don’t get any error thrown but the table referenced by the one to many collection does not get any new rows added to it.
Heres my action code …
public String saveSelectedDefinitions()
{
WordT wordT = wordDao.get(2);
Set<DefinitionT> storedDefs = wordT.getDefinitionTs();
for( int i=0; i<3; i++)
{
DefinitionT selectedDef = new DefinitionT();
selectedDef.setValue("abc");
selectedDef.setWordT(wordT);
storedDefs.add(selectedDef);
}
wordT.setDefinitionTs(storedDefs);
wordDao.save(wordT);
return SUCCESS;
}
Heres my WordT class
@Entity
@Table(name = "word_t", schema = "public")
public class WordT implements java.io.Serializable {
private int id;
private Set<DefinitionT> definitionTs = new HashSet<DefinitionT>(0);
public WordT() {
}
public WordT(int id) {
this.id = id;
}
public WordT(int id, Set<DefinitionT> definitionTs) {
this.id = id;
this.definitionTs = definitionTs;
}
@Id
@Column(name = "id", unique = true, nullable = false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@OneToMany(fetch = FetchType.EAGER, mappedBy = "wordT")
public Set<DefinitionT> getDefinitionTs() {
return this.definitionTs;
}
public void setDefinitionTs(Set<DefinitionT> definitionTs) {
this.definitionTs = definitionTs;
}
}
and heres my DefinitionT class
@Entity
@Table(name = "definition_t", schema = "public")
public class DefinitionT implements java.io.Serializable {
private int id;
private WordT wordT;
public DefinitionT() {
}
public DefinitionT(int id, WordT wordT) {
this.id = id;
this.wordT = wordT;
}
public DefinitionT(int id, WordT wordT, String value, int typeId,
Boolean selected) {
this.id = id;
this.wordT = wordT;
}
@Id
@Column(name = "id", unique = true, nullable = false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "word_id", nullable = false)
public WordT getWordT() {
return this.wordT;
}
public void setWordT(WordT wordT) {
this.wordT = wordT;
}
}
I used Hibernate tools to generate my Daos and Pojos
If I use a DefinitionDao to persist a definitionT instance it persists fine so the table integrity is ok. Why would it not save the collection and not give me any error as to why it failed to do so?
Yo have no cascade on the OneToMany association, so any operation you might do on the word entity doesn’t cascade to its definitions. Moreover, since the definition entity is the owner of the association, you need to set its word property for Hibernate to persist the association.