This is my “header” entity:
@Entity
@Table(name = "documenti")
@Inheritance(strategy=InheritanceType.JOINED)
public class Documento implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@OneToMany(
mappedBy="testataDocumento",
cascade=CascadeType.ALL,
fetch=FetchType.LAZY
)
private Set<RigaDocumento> righe= new HashSet<RigaDocumento>();
//...
}
and these are the “rows”:
@Entity
@Table(name="righe_documenti")
public class RigaDocumento implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@ManyToOne
private Documento testataDocumento;
//...
}
Well I have a common situation:
Documento d = new Documento();
// various Documento settings
List<RigaDocumento> rows;
// creation of rows
d.setRighe( rows );
Then I persist d.
Header is persisted correctly and rows too but…
the “testataDocumento_id” field (the key to the “one” side of the relationships) in the rows record is NULL.
Do I have to do a:
row.setTestataDocumento(d);
?
Why??
Yes, you do have to call
row.setTestataDocumento(d);as it is the owning side of the relationship. Ideally, you would have anaddRow()method in Documento which would add the row to set and also set the document of the row.