5

我有两个表,“书”和“书店”,它们都有一个对“book_to_bookstore”表的@OneToMany 引用,该表保存了哪个书店中有多少本书的信息。如果一本书或书店被删除,该信息也应该消失。

因此我使用标准的 JPA CascadeType.ALL 和 orphanRemoval=true。为了使“正确”的 SQL 模式在不使用 Java 访问它时也可以工作,我添加了 EclipseLink 特定的 @CascadeOnDelete 注释,期望 CASCADE ON DELETE 出现在两个 FOREIGN KEY 语句之后。

有趣的是,它只出现在其中一个之后,我无法解释!

我尝试了 MySQL 和 PostgreSQL 的 DDL 生成,但两者都是相同的。

为什么?

一个可编译的迷你项目在这里:svn+ssh://lathspell@svn.code.sf.net/p/lathspellsphp/code/java_test_eclipselink_cascade_bug

重要的类:

public class Bookstore implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")

    private Integer id;
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "bookstoreId", orphanRemoval = true)
    @CascadeOnDelete
    private List<BookToBookstore> bookToBookstoreList;
    ...

public class Book implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "bookId", orphanRemoval = true)
    @CascadeOnDelete
    private List<BookToBookstore> bookToBookstoreList;
    ...

public class BookToBookstore implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;

    @JoinColumn(name = "bookstore_id", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Bookstore bookstoreId;

    @JoinColumn(name = "book_id", referencedColumnName = "id")
    @ManyToOne(optional = false)
    private Book bookId;
    ...

为 MySQL 生成的 SQL,请注意最后一行中缺少 CASCADE ON DELETE :

CREATE TABLE books (id INTEGER AUTO_INCREMENT NOT NULL, PRIMARY KEY (id))
CREATE TABLE book_to_bookstore (id INTEGER AUTO_INCREMENT NOT NULL, book_id INTEGER, bookstore_id INTEGER, PRIMARY KEY (id))
CREATE TABLE bookstores (id INTEGER AUTO_INCREMENT NOT NULL, PRIMARY KEY (id))
ALTER TABLE book_to_bookstore ADD CONSTRAINT FK_book_to_bookstore_book_id FOREIGN KEY (book_id) REFERENCES books (id) ON DELETE CASCADE
ALTER TABLE book_to_bookstore ADD CONSTRAINT FK_book_to_bookstore_bookstore_id FOREIGN KEY (bookstore_id) REFERENCES bookstores (id)
4

0 回答 0