我有两个实体,产品和属性。我必须在 Product Attribute 之间创建多对多关系,使用另一个名为 ProductAttribute 的单独实体,它应该有一个值字段。 我可以成功地向数据库添加和删除产品和属性,但我无法在 ProductAttribute 表中创建任何条目,因为在服务类(最后一个代码片段)中,存储库将我的新 ProductAttribute 视为 null。 这是我的实体:
@Table
@Entity
@Data
public class Product{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;
@OneToMany(mappedBy = "product")
private List<ProductAttribute> productAttributes;
// other fields -------
@Table
@Entity
@Data
public class Attribute{
@Id
@GeneratedValue
@Column(name = "id",nullable = false)
private Long id;
@Column(nullable = false)
private String name;
@OneToMany(mappedBy = "attribute")
private List<ProductAttribute> productAttributes;
}
ProductAttribute 实体和 Key 类
@Entity
@Table(name = "product_attribute")
@Data
public class ProductAttribute {
@EmbeddedId
private ProductAttributeKey id;
@ManyToOne
@MapsId("productId")
private Product product;
@ManyToOne
@MapsId("attributeId")
private Attribute attribute;
@Column
String value;
}
@Embeddable
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ProductAttributeKey implements Serializable {
@Column(name = "product_id")
private Long productId;
@Column(name = "attribute_id")
private Long attributeId;
}
我为除 ProductAttributeKey 之外的每个关系都实现了 JpaRepository。 这是来自 ProductAttributeService 类的方法:
@Transactional
public ProductAttribute createProductAttribute(CreateProductAttributeModel createProductAttributeModel) {
Product product = productRepository.findById(createProductAttributeModel.getProductId())
.orElseThrow(() -> new EntityNotFoundException("Product with id " + createProductAttributeModel.getProductId() + " not found!"));
Attribute attribute = attributeRepository.findById(createProductAttributeModel.getAttributeId())
.orElseThrow(() -> new EntityNotFoundException("Attribute with id " + createProductAttributeModel.getAttributeId() + " not found!"));
String value = createProductAttributeModel.getValue();
//create new productAttribute
ProductAttribute productAttribute = new ProductAttribute();
productAttribute.setProduct(product);
productAttribute.setAttribute(attribute);
productAttribute.setValue(value);
return productAttributeRepository.save(productAttribute);
}
当您尝试使用
ProductAttribute
保存此 productAttributeRepository
对象时,存储库正在尝试为该对象生成一个 ID,但由于 id 属性为 null,它无法这样做并返回一个空对象。
这应该可以解决您的问题:
//create new productAttribute
ProductAttribute productAttribute = new ProductAttribute();
ProductAttributeKey id = new ProductAttributeKey();
id.setProductId(createProductAttributeModel.getProductId());
id.setAttributeId(createProductAttributeModel.getAttributeId());
productAttribute.setId(id);
productAttribute.setProduct(product);
productAttribute.setAttribute(attribute);
productAttribute.setValue(value);
return productAttributeRepository.save(productAttribute);