我有以下测试:

@Test
public void createNewShopAndCheckUserShopsCollection()
{
    //given
    ShopEntity shop = new ShopEntity();
    String shopName = "test shop";

    MallEntity mall = new MallEntity();
    mall.setId(1L);

    UserEntity user = userService.findOne(1L);
    int shopsModeratedBefore = user.getModeratedShops().size();

    shop.setMall(mall);
    shop.setName(shopName);
    shop.setModerators(Collections.singletonList(user));


    ShopEntity savedShop = shopRepository.save(shop);
    user = userService.findOne(1L);

    assertThat(user.getModeratedShops()).hasSize(shopsModeratedBefore + 1);
}


在带有@Transactional注释的类中。执行完后,我需要回滚,以便其他测试不会失败。但是,似乎在方法末尾(断言下降)之前未填充联接表。如何手动确保它已更新?

这是UserEntity.java中的映射

@ManyToMany(mappedBy = "moderators")
@JsonBackReference(value = "moderatedShops")
@Setter
@Getter
private List<ShopEntity> moderatedShops;


在ShopEntity.java中

@ManyToMany
@JoinTable(name = "shop_moderators",
        joinColumns = @JoinColumn(name = "shop_id"),
        inverseJoinColumns = @JoinColumn(name = "user_id"))
@JsonManagedReference(value = "moderatedShops")
@Setter
@Getter
private List<UserEntity> moderators;

最佳答案

您在实施中缺少的是对孩子的级联。只需将@ManyToMany(cascade = CascadeType.ALL)添加到您的帐户,保存/删除也应适用于子实体。

10-08 03:10