使用OneToMany将对象从JSON保存到数据库

时间:2017-04-15 23:01:49

标签: java json hibernate rest jax-rs

我正在尝试将以下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

1 个答案:

答案 0 :(得分:1)

如果您的双向映射已正确实现并且您已在实体对象之间设置了适当的关系,那么

Hibernate将负责持久保存您的子实体。

您的Product实体的集合为ImageProduct实体是此处的父实体。您只需在ProductImage个实体之间设置正确的关系,并仅保留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:我没有测试过代码,但这应该可行。