Java Spring boot,@ManyToMany,为联接表创建一个存储库
我有两个实体,它们之间有很多关系:Java Spring boot,@ManyToMany,为联接表创建一个存储库,java,spring-boot,Java,Spring Boot,我有两个实体,它们之间有很多关系: @Entity @Table(name="categories") public class CategoryEntity implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="id") priva
@Entity
@Table(name="categories")
public class CategoryEntity implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
private int categoryId;
@Column(name="name")
private String CategoryName;
@ManyToMany(mappedBy = "categories")
private List<ProductEntity> products = new ArrayList<ProductEntity>();
}
@Entity
@Table(name="products")
public class ProductEntity implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
private Integer productId;
@Column(name="name")
private String productName;
@Column(name="description")
private String description;
@Column(name="price")
private Float price;
@Column(name="rating")
private Float rating;
@Column(name="image")
private String image;
@Column(name="quantity")
private Integer quantity;
@ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(name = "product_category",
joinColumns = {@JoinColumn(name = "product_id")},
inverseJoinColumns = {@JoinColumn(name = "category_id")}
)
private List<CategoryEntity> categories = new ArrayList<>();
}
你有关系一致性问题。您正在将类别添加到产品中,但未将产品添加到类别中 将此方法添加到ProductEntity类中:
public void addCategory(CategoryEntity category) {
this.getCategories().add(category);
category.getProducts().add(this);
}
并使用此方法将类别添加到产品中
ProductEntity productEntity=productMapper.dtoToEntity(productDto);
for(CategoryDto categoryDto:productDto.getCategories()){
CategoryEntity categoryEntity=categoryMapper.dtoToEntity(categoryDto);
productEntity.addCategory(categoryEntity); //changed line
}
productEntity=productService.saveProduct(productEntity);
productDto.setProductId(productEntity.getProductId());
public void addCategory(CategoryEntity category) {
this.getCategories().add(category);
category.getProducts().add(this);
}
ProductEntity productEntity=productMapper.dtoToEntity(productDto);
for(CategoryDto categoryDto:productDto.getCategories()){
CategoryEntity categoryEntity=categoryMapper.dtoToEntity(categoryDto);
productEntity.addCategory(categoryEntity); //changed line
}
productEntity=productService.saveProduct(productEntity);
productDto.setProductId(productEntity.getProductId());