问题描述
我有一个Product类,其中包含一个ProductCategory参考,即 ProductCategory类别和另一个包含产品列表的类ProductCategory。 我正在明智地保存产品类别,因此需要在相应产品中插入当前类别对象。 我想通过主要方法将数据保存在数据库中
productCategoryRepository.save(new ProductCategory(1,"Book",Arrays.asList(
new Product(1,this,"pqr","abc","xyz",true,100,999,LocalDate.now())
));
实体
Product.java
package com.ecommerce.springbootecommerce.entity;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.*;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import lombok.Data;
@Entity
@Table(name = "product")
@Data
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@ManyToOne
@JoinColumn(name = "category_id",nullable = false)
private ProductCategory category;
@Column(name = "sku")
private String sku;
@Column(name = "name")
private String name;
@Column(name = "description")
private String description;
@Column(name = "unit_price")
private BigDecimal unitPrice;
@Column(name = "image_url")
private String imageUrl;
@Column(name = "active")
private boolean active;
@Column(name = "units_in_stock")
private int unitsInStock;
@Column(name = "date_created")
@CreationTimestamp
private Date dateCreated;
@Override
public String toString() {
return "Product [id=" + id + ",category=" + category + ",sku=" + sku + ",name=" + name + ",description=" + description + ",unitPrice=" + unitPrice + ",imageUrl=" + imageUrl + ",active=" +
active + ",unitsInStock=" + unitsInStock + ",dateCreated=" + dateCreated + ",lastUpdated=" +
lastUpdated + "]";
}
@Column(name = "last_updated")
@UpdateTimestamp
private Date lastUpdated;
}
ProductCategory.java
package com.ecommerce.springbootecommerce.entity;
import java.util.Set;
import javax.persistence.*;
import lombok.Getter;
import lombok.Setter;
@Entity
@Table(name = "product_category")
// @Data --known bug
@Getter
@Setter
public class ProductCategory {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "category_name")
private String categoryName;
@OneToMany(cascade = CascadeType.ALL,mappedBy = "category")
private Set<Product> products;
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)