[英]@OneToMany detached entity passed to persist
I face this error when inserting in Order table 在订单表中插入时会遇到此错误
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
Mapping this is how i map my classes : 映射这就是我映射类的方式:
@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;
}
Inserting in my tables this is how i save new rows in my tables 在表中插入这是我在表中保存新行的方式
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);
Could you please help me if there is a problem in the mapping? 如果映射有问题,请您帮我吗?
Try below: 请尝试以下方法:
Order o1 = new Order(false,lineItems1);
o1.getLineItems().add(new LineItem(6, p1););
o1.getLineItems().add(new LineItem(6, p1););
orderRepository.save(o1);
Instead of creating a new HashSet use the existing one from order since that's the object that hibernate is tracking. 不用创建新的HashSet,而是使用现有的from顺序的,因为这是hibernate跟踪的对象。
I think you should try to remove the lineItemRepository.save(li1);lineItemRepository.save(li2);
我认为您应该尝试删除
lineItemRepository.save(li1);lineItemRepository.save(li2);
line, since CascadeType.ALL
will persist te Set<LineItem>
also. 行,因为
CascadeType.ALL
还将保留Set<LineItem>
。
Replace this code, 替换此代码,
LineItem li1 = new LineItem(6, p1);
LineItem li2 = new LineItem(9, p2);
lineItemRepository.save(li1);lineItemRepository.save(li2);
if any issue inform. 如果有任何问题,请告知。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.