当我org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: safu.Publisher
尝试运行以下代码时出现异常:
public class SafuClient {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Publisher publisher = new Publisher("ABC", "ABC Co.");
Book book = new Book("1-932394-88-5", "Safu", publisher);
session.save(book);
session.getTransaction().commit();
}
}
我有从书到出版商的多对一关系。Book 和 Publisher 实体如下:
@Entity
public class Book {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String isbn;
private String name;
@ManyToOne(cascade={CascadeType.PERSIST})
@JoinColumn(name="publisher_id")
private Publisher publisher;
public Book() {}
public Book(String isbn, String name, Publisher publisher) {
this.isbn = isbn;
this.name = name;
this.publisher = publisher;
}
}
@Entity
public class Publisher {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String code;
private String name;
public Publisher() {}
public Publisher(String code, String name) {
this.code = code;
this.name = name;
}
}
如果我在实体中@ManyToOne(cascade={CascadeType.PERSIST})
替换为一切正常。@ManyToOne(cascade={CascadeType.ALL})
Book
有人可以解释为什么会这样吗?