我有两个表,“书籍”和“书店”都有@OneToMany对“book_to_bookstore”表的引用,该表记录了书店中有多少本书。 如果书籍或书店被删除,那么这些信息也应该消失。
因此我使用标准JPA CascadeType.ALL和orphanRemoval = true。为了使“正确”的SQL模式在使用Java时访问它时也能正常工作,我添加了EclipseLink特定的@CascadeOnDelete注释,期望在两个FOREIGN KEY语句之后出现CASCADE ON DELETE。
有趣的是,它只出现在其中一个我无法解释之后!
我尝试了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,请注意 last 行中缺少的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)