OpenJPA - 嵌套的 OneToMany 关系合并问题

OpenJPA - Nested OneToMany relationships merge issue

在这里发布这个因为我在这里没有看到太多兴趣:http://www.java-forums.org/jpa/96175-openjpa-one-many-within-one-many-merge-problems.html

正在尝试确定这是 OpenJPA 的问题还是我可能做错了什么...

我在尝试使用 OpenJPA 更新包含与另一个实体的一对多关系的实体时遇到问题,该实体与另一个实体具有一对多关系。这是我正在谈论的内容的一个简单示例:

@Entity
@Table(name = "school")
public class School {

    @Column(name = "id")
    protected Long id;

    @Column(name = "name")
    protected String name;

    @OneToMany(mappedBy = "school", orphanRemoval = true, cascade = CascadeType.ALL)
    protected Collection<ClassRoom> classRooms;
}

@Entity
@Table(name = "classroom")
public class ClassRoom {

    @Column(name = "id")
    protected Long id;

    @Column(name = "room_number")
    protected String roomNumber;

    @ManyToOne
    @JoinColumn(name = "school_id")
    protected School school;

    @OneToMany(mappedBy = "classRoom", orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    protected Collection<Desk> desks;

}

@Entity
@Table(name = "desk")
public class Desk {

    @Column(name = "id")
    protected Long id;

    @ManyToOne
    @JoinColumn(name = "classroom_id")
    protected ClassRoom classRoom;

}

在 SchoolService class 中,我有以下更新方法:

    @Transactional
    public void update(School school) {
        em.merge(school);
    }

我正在尝试从学校中删除一个 Class 房间。我将其从 classRooms 集合中删除并调用更新。我注意到 Class 房间没有桌子,没有问题。但是如果 Class 房间有桌子,它会抛出一个约束错误,因为它似乎试图先删除 Class 房间,然后是桌子。 (classroom_id列有外键约束)

我是不是走错了路?在删除已删除的 Class Room 实例之前,我是否缺少某些设置以先删除内部 "Desk" 实例?

如有任何帮助,我们将不胜感激。如果您需要更多信息,请告诉我。 谢谢,

在将删除操作级联到子实体时,有各种关于 OpenJPA 中 FK 违规的错误报告:

OpenJPA 常见问题解答指出以下内容:

http://openjpa.apache.org/faq.html#reorder

Can OpenJPA reorder SQL statements to satisfy database foreign key constraints?

Yes. OpenJPA can reorder and/or batch the SQL statements using different configurable strategies. The default strategy is capable of reordering the SQL statements to satisfy foreign key constraints. However ,you must tell OpenJPA to read the existing foreign key information from the database schema:

您似乎可以通过在 OpenJPA 配置中设置以下 属性 来强制正确排序语句

<property name="openjpa.jdbc.SchemaFactory"> value="native(ForeignKeys=true)"/>

或通过向映射添加 org.apache.openjpa.persistence.jdbc.ForeignKey 注释:

@OneToMany(mappedBy = "classRoom", orphanRemoval = true, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@org.apache.openjpa.persistence.jdbc.ForeignKey
protected Collection<Desk> desks;

另请参阅:

https://issues.apache.org/jira/browse/OPENJPA-1936