我有一些Java类,我正在与Grails(2.4.0)项目集成(我需要使用Java类,因为我们应用程序中的其他项目都是纯Java)。当我创建父对象并添加子对象然后保存时,MySQL返回一个错误,指出外键字段不能为空。看来父母的主键没有插入到孩子的外键字段中。
我是否缺少JPA选项来启用级联保存/插入?
Groovy代码
def author = new Author(name:"Joe")
.addToBooks(
new Book(title:"My Title")
)
.save(failOnError:true)
错误
Message: Hibernate operation: could not execute statement; SQL [n/a]; NULL not allowed for column "AUTHOR_ID"; SQL statement:
insert into book (id, author_id, title) values (null, ?, ?) [23502-173]; nested exception is org.h2.jdbc.JdbcSQLException: NULL not allowed for column "AUTHOR_ID"; SQL statement:
insert into book (id, author_id, title) values (null, ?, ?) [23502-173]
Author.java
@Entity
public class Author {
private long id;
private List<Book> books;
private String name;
@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@OneToMany(cascade = CascadeType.ALL, mappedBy = "author")
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
@Column
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Book.java
@Entity
public class Book {
private int id;
private String title;
private Author author;
@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name="TITLE")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "AUTHOR_ID", foreignKey = @ForeignKey(name = "author_fk1"), nullable = false)
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
}