Fabio B.
Fabio B.

Reputation: 9410

@OneToMany relationship: "one" id not persisted

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??

Upvotes: 0

Views: 184

Answers (2)

JB Nizet
JB Nizet

Reputation: 692281

Yes, you have to, because you have a bidirectional association, and the owner side of the association is RigaDocumento. The owner side is the side which doesn't have the mappedBy attribute. The other side is called the inverse side, and is ignored by JPA/Hibernate.

Upvotes: 1

John Farrelly
John Farrelly

Reputation: 7459

Yes, you do have to call row.setTestataDocumento(d); as it is the owning side of the relationship. Ideally, you would have an addRow() method in Documento which would add the row to set and also set the document of the row.

Upvotes: 1

Related Questions