我正在尝试将以下JSON发送到REST API并在数据库上保留,但只创建了Product
,而Image
则没有。
{ “名称”: “笔”, “描述”:“红笔”, “图像”:[{ “类型”: “JPEG”}] }
@Controller
@POST
@Path("/product/add")
@Consumes("application/json")
public Response addProduct(Product product) {
service.createProduct(product);
}
@服务
@Autowired
private ProductDAO productDAO;
@Autowired
private ImageDAO imageDAO;
public void createProduct(Product product) {
productDAO.save(product);
}
@product
@Entity
@Table
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer productId;
@Column(name = "NAME")
private String name;
@Column(name = "DESCRIPTION")
private String description;
@OneToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="product")
private Set<Image> images;
@OneToMany(cascade=CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="parent")
private Set<Product> children;
@ManyToOne
@JoinColumn(name = "PARENT_PRODUCT_ID")
private Product parent;
@Image
@Entity
@Table
public class Image implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer imageId;
@Column(name = "TYPE")
private String type;
@ManyToOne
@JoinColumn(name = "PRODUCT_ID", nullable = false)
private Product product;
在@POST
方法中,当打印收到的Product
对象时,会返回:
产品[productId = null,name = pen,description = red pen,images = [Image [id = null,type = jpeg,product = null]],children = null,parent = null]
正确的方法是先保留Product
,然后保留Image
,否则当我保留Image
时,Hibernate会自动保留Product
?
答案 0 :(得分:1)
Hibernate
将负责持久保存您的子实体。
您的Product
实体的集合为Image
。 Product
实体是此处的父实体。您只需在Product
和Image
个实体之间设置正确的关系,并仅保留Product
。 Hibernate将持久保存您的父级和子级实体。
你需要做什么
Product product = new Product();
product.setName("PRODUCT_NAME");
Set<Image> productImages = new HashSet<>();
Image productProfileImage = new Image();
productProfileImage.setType("PROFILE");
productProfileImage.setProduct(product);
//..set other fields
productImages.add(productProfileImage);
Image productCoverImage = new Image();
productCoverImage.setType("COVER");
productCoverImage.setProduct(product);
//..set other fields
productImages.add(productCoverImage);
product.setImages(productImages);
productRepository.save(product); //Persist only your product entity and the mapped child entities will be persisted
查看this类似的答案。
PS:我没有测试过代码,但这应该可行。