假设我有两个模型:
@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));
}
};
}
虽然它没有抛出任何错误/异常,但结果并不是我所期望的。我认为它应该像第一种情况--“连接表”应该有一些行--但实际上只有category
和product
包含行。
你能解释一下为什么第二个案子不行吗?是虫子吗?
1条答案
按热度按时间szqfcxe21#
根据JPA规范,对双向关联的
mappedBy
端的更改不会持久化。协会的一方,即“拥有”方,有责任坚持变革。“无主”端在某种意义上是只读的。