@OneToMany独立实体已传递以持久化

时间:2018-12-19 16:35:39

标签: java hibernate spring-data-jpa

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

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);

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

3 个答案:

答案 0 :(得分:1)

尝试以下方法:

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

不是创建新的HashSet,而是使用现有的from顺序的HashSet,因为这是hibernate跟踪的对象。

答案 1 :(得分:0)

我认为您应该尝试删除lineItemRepository.save(li1);lineItemRepository.save(li2);行,因为CascadeType.ALL还将保留Set<LineItem>

答案 2 :(得分:0)

替换此代码,

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

如有任何问题,请告知。