简体   繁体   English

@OneToMany关系:“one”id没有持久化

[英]@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. 行记录中的“testataDocumento_id”字段(关系的“一”侧的键)为NULL。

Do I have to do a: 我必须做一个:

row.setTestataDocumento(d);

?

Why?? 为什么??

Yes, you do have to call row.setTestataDocumento(d); 是的,你必须调用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. 理想情况下,您将在Documento中使用addRow()方法,该方法将添加要设置的行并设置行的文档。

Yes, you have to, because you have a bidirectional association, and the owner side of the association is RigaDocumento. 是的,您必须,因为您有双向关联,并且该关联的所有者方是RigaDocumento。 The owner side is the side which doesn't have the mappedBy attribute. 所有者方是没有mappedBy属性的一方。 The other side is called the inverse side, and is ignored by JPA/Hibernate. 另一边称为反面,并被JPA / Hibernate忽略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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