Spring Data JPA持久化一对多引用的实体

时间:2017-12-25 17:10:54

标签: java spring spring-mvc jpa reference

我正在使用Spring Data JPA(1.4.0,spring boot)并拥有以下代码

ExternalOrder实体:

 @Entity
 @Table(name = "External_Orders")
 public class ExternalOrder {
    ...

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "externalOrder", orphanRemoval = true, cascade = CascadeType.ALL)
    private List<ExternalOrderElement> elements;

    ...
}

ExternalOrderElement实体:

@Entity
@Table(name = "External_Order_Elements")
public class ExternalOrderElement implements Serializable {

    @Id
    @ManyToOne(optional = false)
    @JoinColumn(name = "ExternalOrderID")
    private ExternalOrder externalOrder;

    @Id
    @OneToOne(optional = false)
    @JoinColumn(name = "BoardGameID")
    private BoardGame boardGame;

    ...
}

我也有ExternalOrder的默认Crud存储库

public interface ExternalOrderRepository extends CrudRepository<ExternalOrder, Integer>{

}

我想在外部订单中添加一些元素并坚持下去。我设法创建了自定义的repostitory界面并实现了它,但我现在试图将逻辑移到服务方法中,如下所示:

@Override
@Transactional
public void addElementToExternalOrder(int externalOrderId, ExternalOrderElement element) {
    ExternalOrder externalOrder = findExternalOrderById(externalOrderId);

    element.setExternalOrder(externalOrder);
    externalOrder.getElements().add(element);

    externalOrderRepository.save(externalOrder);
}

这导致执行时出现以下异常

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'ExternalOrderID' cannot be null

我对JPA缺少什么?好像我还没有在ExternalOrderElement上设置ExternalOrder参考,但我已经完成了。

先谢谢你们的帮助。

0 个答案:

没有答案