简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM