gpt4 book ai didi

java - @OneToMany 分离实体传递到持久化

转载 作者:行者123 更新时间:2023-12-02 10:27:19 28 4
gpt4 key购买 nike

在订单表中插入时遇到此错误

org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist: org.vi.entities.LineItem; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: org.vi.entities.LineItem

映射这就是我映射我的类的方式:

@Entity
public class Order implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@Column(name = "delivered", nullable = false)
private boolean delivered;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "fk_order")
private Set<LineItem> lineItems= new HashSet<LineItem>();
}
@Entity
public class LineItem implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@Column(name="quantity", nullable = false)
private int quantity;
@ManyToOne
private Product product;
}
@Entity
public class Product implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
@Column(name = "reference", unique = true, nullable = false)
private String reference;
@Column(name = "price", nullable = false)
private double price;
}

插入我的表格这就是我在表中保存新行的方法

Product p1 = new Product("reference1",10000);
Product p2 = new Product("reference2",20000;
productRepository.save(p1);productRepository.save(p2);

LineItem li1 = new LineItem(6, p1);
LineItem li1 = new LineItem(9, p2);
lineItemRepository.save(li1);lineItemRepository.save(li2);

Set<LineItem> lineItems1= new HashSet<LineItem>();
lineItems1.add(li1);
lineItems1.add(li2);

Order o1 = new Order(false,lineItems1);
orderRepository.save(o1);

如果映射有问题,您能帮我吗?

最佳答案

尝试以下:

Order o1 = new Order(false,lineItems1);
o1.getLineItems().add(new LineItem(6, p1););
o1.getLineItems().add(new LineItem(6, p1););
orderRepository.save(o1);

不要创建新的 HashSet,而是使用顺序中的现有 HashSet,因为那是 hibernate 正在跟踪的对象。

关于java - @OneToMany 分离实体传递到持久化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53855506/

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