ManyToOne:deleteAll()和delete(object)无法正常工作

时间:2018-12-21 10:16:20

标签: spring-boot jpa-2.0 crud

我正在尝试使ManyToOne关系起作用,除此关系之外,其他所有关系都起作用。这是一个映射到一个人的帐户列表。

问题:

-当我尝试保存帐户时:

Account accountSave = AccountRepository.save(account); //works

-当我尝试保存多个帐户时:

Account accountASave = AccountRepository.save(accountA);
Account accountBSave = AccountRepository.save(accountB);
//not working: results in : Expected <2> but was:<4>

-当我尝试删除帐户时:

Account accountSave = AccountRepository.save(account);
AccountRepository.delete(account);
//does not delete the account

当我尝试删除所有帐户时:

Account accountASave = AccountRepository.save(accountA);
Account accountBSave = AccountRepository.save(accountB);
AccountRepository.deleteAll();
//deleted instance passed to merge
  • 当我尝试保存秘书时:有效
  • 当我尝试保存多个文员时:有效
  • 当我尝试删除文员时:有效
  • 当我尝试删除所有文员时:有效     (每次使用的策略都与上述相同)

我试图摆弄cascadeType,但没有运气

=>更改:将cascade = CascadeType.ALL更改为

cascade = {CascadeType.PERSIST,CascadeType.REFRESH,CascadeType.REMOVE}

不能解决问题

  • 在交易方法中添加@Transaction并不能解决任何问题 问题
  • @OnDelete(action = OnDeleteAction.CASCADE)添加到帐户不会 可以帮助

一对多关系:

@Entity
@DiscriminatorValue("B")
public class Clerk extends Werknemer {

    private String salary;

    @OneToMany(mappedBy = "clerk", cascade = CascadeType.ALL, 
        orphanRemoval = true)
    private List<Account> accounts = new ArrayList<>();
    (...)
}

ManyToOne关系:

@Entity
@Table(name = "ACCOUNTS")
public class Account implements Serializable, Comparable<Account>{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "clerk_id")
    private Clerk clerk;

    private String text;

    (...)
}

deleteAll()和delete(object)必须工作并且 当我尝试保存2个帐户时,保存2个帐户而不是4个 单元测试:

'    @Test
public void DeleteAccount() {
    Account account = new Account();
    account.setTekst("Tekst");

    Bediende bediende = new Bediende();
    bediende.setBedrijfsnaam("Bedrijfsnaam");
    bediende.setNaam("Naam");
    bediende.setVoornaam("Voornaam");
    bediende.setPersoneelsnummer(12345678);
    bediende.setSalaris("Salaris");

    Werkadres werkadres = new Werkadres();
    werkadres.setGemeente("Gemeente");
    werkadres.setHuisnummer("Huisnummer");
    werkadres.setPostcode("Postcode");
    werkadres.setStraat("Straat");

    bediende.setWerkadres(werkadres);

    account.setBediende(bediende);

    List<Account> accounts = new ArrayList<>();
    accounts.add(account);


    bediende.setAccounts(accounts);

    Account accountSave = accrep.save(account);
    accrep.delete(account);

    Iterable<Account> accountLijst = accrep.findAll();
    for (Account a : accountLijst) {
        Assert.fail();
    }
    Assert.assertTrue(true);
    accrep.deleteAll();
}'

0 个答案:

没有答案