unidirectional one-to-many relation without join table
@Entity
@Table
public class Book {
@Id @GeneratedValue @Column private Long bookId;
@Column private String name;
@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
@JoinColumn(name="bookId")
private List<Chapter> 开发者_开发百科chapters=new ArrayList<Chapter>();
.....
@Entity
@Table
public class Chapter {
@Id @Column @GeneratedValue
private Long cid;
@Column private String name;
@Column private Long bookId;
....
What annotation should I use in Chapter.bookId to refer Book.bookId, so that chapter.bookid will take the generated value of Book.bookId while inserting a new Book .
Book bk=new Book();
bk.setName("b1");
Chapter ch=new Chapter();
ch.setName("b1c1");
bk.getChapters().add(ch);
I get this error Hibernate: insert into Book (name) values (?) Hibernate: insert into Chapter (bookId, name) values (?, ?) 19:56:59,094 ERROR JDBCExceptionReporter:234 - Column 'bookId' cannot be null
You'd have to set Chapter.bookId
yourself or change the reference in Chapgter
from Long
to Book
, add the @ManyToOne
annotation and set the reference to the book manually.
In this case, the owning side of the relation is actually Chapter
, i.e. a chapter defines which book it belongs to.
Use @Column(nullable=true) if you really need null value, otherwise as have been said in previous answer - you need to set it manually, adding Chapter to list doesn't set bookId
精彩评论