Hibernate:级联上的违规持续存在

时间:2016-06-22 14:38:28

标签: java hibernate jpa

我有两个类,订单和联系人注释如下

public class Order {
      @Id
      @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "order_id_gen")
      @Column(name = "id_order")
      private long id;

      @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
      @JoinColumn(name = "id_order")
      private List<Contact> contacts = new ArrayList<>();

}

public class Contact {
      @Id
      @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "order_contact_id_gen")
      @Column(name = "id_contact")
      private long id;

        @ManyToOne
        @JoinColumn(name = "id_order")
        private Order order;

}

当我尝试使用JPA存储库保存整个订单时,如

public interface OrderRepository extends JpaRepository<Order, Long> {}

使用

orderRepository.save(order);

我得到了一个例外

javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1763)
Caused by: org.postgresql.util.PSQLException: ERROR: the INSERT or the UPDATE on table "ms_contact" violates foreign key constraint "fk_4uonv9hs08picha25luywl3on"
Detail: the key (id_order)=(602) is not present in "ms_order".

并且联系人不会保留。

0 个答案:

没有答案