Spring JPA Cascade.ALL不会删除父对象

时间:2018-03-19 23:47:32

标签: java spring hibernate jpa cascade

我跟随这个"双向多对多链接实体生命周期"这里的教程https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#associations-many-to-many。但是,我使用的是Spring JPA而不是Entity Manager。当我使用存储库接口删除地址时,即使我已经级联ALL,也不会删除PersonAddress记录。它给了我外键约束异常。

"参照完整性约束违规:" FKCYC1KRSXQELKM4UWH65AVIJ23:PUBLIC.PERSON_ADDRESS FOREIGN KEY(ADDRESS_ID)参考PUBLIC.ADDRESS(ID)(1)&#34 ;; SQL语句:"

我的classess在下面。

@Entity(name = "Address")
public class Address  {

@Id
@GeneratedValue
private Long id;

private String street;

@Column(name = "number")
private String number;

private String postalCode;

@OneToMany(mappedBy = "address", cascade = {CascadeType.ALL}, orphanRemoval = true, fetch=FetchType.LAZY)
private List<PersonAddress> owners = new ArrayList<>();

PersonAddress.java

 @Entity(name = "PersonAddress")
    public class PersonAddress implements Serializable {

    @Id
    @ManyToOne
    private Person person;

    @Id
    @ManyToOne
    private Address address;

Person.java

@Entity(name = "Person")
public class Person{

    @Id
    @GeneratedValue
    private Long id;

    @NaturalId
    private String registrationNumber;

    @OneToMany(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<PersonAddress> addresses = new ArrayList<>();

在Person和Address关联后删除地址的测试方法。这应该删除PersonAddress中的记录,因为Address有Cascade.ALL但它没有发生。我错过了什么?

@Test
@Transactional
public void testDeleteAddressAfterPatronAdd() {

Person person1 = new Person("ABC-123");
Person person2 = new Person("DEF-456");
Address address1 = new Address("12th Avenue", "12A", "4005A");
Address address2 = new Address("18th Avenue", "18B", "4007B");

Person savedPerson1 = personRepository.save(person1);
Person savedPerson2 = personRepository.save(person2);       
Address savedAddress1 = addressRepository.save(address1);
Address savedAddress2 = addressRepository.save(address2);
personRepository.flush();       
addressRepository.flush();

PersonAddress personAddress1 = new PersonAddress(savedPerson1, savedAddress1);      
PersonAddress personAddress2 = new PersonAddress(savedPerson2, savedAddress2);
savedPerson1.getAddresses().add(personAddress1);
savedPerson2.getAddresses().add(personAddress2);
personRepository.flush();       
addressRepository.flush();

Address loadedAddress1 = addressRepository.findById(savedAddress1.getId());
loadedAddress1.getOwners();
addressRepository.delete(loadedAddress1);       
addressRepository.flush();

1 个答案:

答案 0 :(得分:0)

你没有正确维护协会的双方。 A = FOREACH us_citystate GENERATE state; B = DISTINCT A; C = JOIN raw_bus_data BY state, B BY state; bus_us_data = FOREACH C GENERATE raw_bus_data::var1 AS var1, raw_bus_data::var2 AS var2; 引用了raw_bus_data,但personAddress1在其所有者列表中没有任何元素。

因此,当您删除address1时,Hibernate不会将删除级联到任何所有者,因为列表中没有任何内容。删除因此失败,因为您尝试删除address1引用的address1,尽管是FK约束。