gpt4 book ai didi

hibernate - 单向 ManyToOne : Why transient instance saved with CascadeType. ALL 但不是 CascadeType.PERSIST

转载 作者:行者123 更新时间:2023-12-02 01:49:48 28 4
gpt4 key购买 nike

当我尝试运行以下代码时,出现 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();

}
}

我有一个从图书到出版商的多对一关系。图书和出版商实体如下:


@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;
}

}

如果我在 Book entity 一切正常。

有人可以解释为什么会这样吗?

最佳答案

尝试 session.persist(book); 这可以解决问题而不是 session.save(book);

关于hibernate - 单向 ManyToOne : Why transient instance saved with CascadeType. ALL 但不是 CascadeType.PERSIST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23521039/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com