spring 为什么cascade在children(mappedBy)定义时不起作用?

wf82jlnq  于 2023-04-28  发布在  Spring
关注(0)|答案(1)|浏览(125)

假设我有两个模型:

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Category {
  @Id
  @GeneratedValue
  private Long id;
  
  @Basic(optional = false)
  private String name;
  
  @ManyToMany(mappedBy = "categories", cascade = { CascadeType.MERGE, CascadeType.PERSIST })
  private List<Product> products;
}

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product {
  
  @Id
  @GeneratedValue
  private Long id;
  
  @ManyToMany(cascade = { CascadeType.MERGE, CascadeType.PERSIST})
  private List<Category> categories;
}

当我试图持久化一个产品,里面有一些类别,就像这样:

@Bean
CommandLineRunner t(CategoryRepository categoryRepository, ProductRepository productRepository) {
    return new CommandLineRunner() {
        @Override
        @Transactional
        public void run(String... args) throws Exception {
            categoryRepository.save(new Category(null, "name 1", null));
            categoryRepository.save(new Category(null, "name 2", null));
            categoryRepository.save(new Category(null, "name 3", null));

            List<Category> all = categoryRepository.findAll();
            all.add(new Category(null, "$$$", null));

            productRepository.save(new Product(null, all));
            
        }
    };
}

它确实工作,我可以看到“连接表”x1c 0d1x中的数据
但是如果我还原这个过程,persist a category with some products inside的意思是:

@Bean
CommandLineRunner t(CategoryRepository categoryRepository, ProductRepository productRepository) {
    return new CommandLineRunner() {
        @Override
        @Transactional
        public void run(String... args) throws Exception {
            productRepository.save(new Product());
            productRepository.save(new Product());
            productRepository.save(new Product());

            List<Product> all = productRepository.findAll();
            all.add(new Product());

            categoryRepository.save(new Category(null, "%%%%%%%%", all));
        }
    };
}

虽然它没有抛出任何错误/异常,但结果并不是我所期望的。我认为它应该像第一种情况--“连接表”应该有一些行--但实际上只有categoryproduct包含行。
你能解释一下为什么第二个案子不行吗?是虫子吗?

szqfcxe2

szqfcxe21#

根据JPA规范,对双向关联的mappedBy端的更改不会持久化。协会的一方,即“拥有”方,有责任坚持变革。“无主”端在某种意义上是只读的。

相关问题