gpt4 book ai didi

spring - 使用 @ManyToOne 关联时传递到持久错误的分离实体

转载 作者:行者123 更新时间:2023-12-02 04:08:07 27 4
gpt4 key购买 nike

我有Book & Bookdetail

当我尝试使用相同的BookDetail时我的两个信息Book使用 @ManyToOne 的对象,我正在得到

"detached entity passed to persist error".

我尝试了同样的 JpaRepositoryCrudRepository 。但结果相同

请帮助我。提前致谢

主类

@SpringBootApplication
public class HelloJpaApplication implements CommandLineRunner{

private static final Logger logger = LoggerFactory.getLogger(HelloJpaApplication.class);

@Autowired
private BookRepository bookRepository;

public void run(String... arg0) throws Exception {

Book book1=new Book();
book1.setName("my thoughts");

Book book2=new Book();
book2.setName("your thoughts");

Bookdetail detail=new Bookdetail();
detail.setCategory("good books");

book1.setBookdetail(detail);
book2.setBookdetail(detail);

bookRepository.save(book1);
bookRepository.save(book2);
}

public static void main(String[] args) {
SpringApplication.run(HelloJpaApplication.class, args);
}
}

BookRepository接口(interface)

public interface BookRepository extends JpaRepository<Book,Integer>{

}

图书类(class)

@Entity
public class Book {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int bookid;

private String name;

@ManyToOne(cascade = {CascadeType.PERSIST,CascadeType.MERGE})
private Bookdetail bookdetail;

public Book() {
}

public Book(String name) {
this.name=name;
}

public int getBookid() {
return bookid;
}
public void setBookid(int bookid) {
this.bookid = bookid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Bookdetail getBookdetail() {
return bookdetail;
}
public void setBookdetail(Bookdetail bookdetail) {
this.bookdetail = bookdetail;
}

}

图书详细信息类

@Entity
@Table(name="bookdetail")
public class Bookdetail {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int bookid;

private String category;

public Bookdetail() {
}
public Bookdetail(String category) {
this.category=category;
}

public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}

}

最佳答案

仅使用 BookdetailDetail=new Bookdetail(); 创建的每个对象都是一个独立的实体,这意味着他不在 hibernate session 中或没有标识符id .
并且您必须将持久、更新或删除的服务包装到事务中。

因此,首先您必须保存detail您的分离实体:bookdetailRepository.save(detail)以将其附加到 session 但是在您的情况下您已指定 cascade = {CascadeType.PERSIST,CascadeType.MERGE}

@ManyToOne(cascade = {CascadeType.PERSIST,CascadeType.MERGE})
private Bookdetail bookdetail;

无需事先保存,工作将自动完成。

解决方案是用@Transactional注释方法run()

...
@Transactional
public void run(String... arg0)
...
bookdetailRepository.save(detail)
book1.setBookdetail(detail);
...

关于spring - 使用 @ManyToOne 关联时传递到持久错误的分离实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38350374/

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