2017-04-15 87 views
1

我想發送以下JSON到REST API並堅持數據庫,但只有Product創建,Image它不是。保存OneToMany從JSON到數據庫的對象

{ 「名稱」: 「筆」, 「描述」: 「紅色筆」, 「圖像」:[{ 「類型」: 「JPEG」}] }

@控制器

@POST 
@Path("/product/add") 
@Consumes("application/json") 
public Response addProduct(Product product) { 
    service.createProduct(product); 
} 

@Service

@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,名字=筆,描述=紅筆,圖像= [圖像[id = null,type = jpeg,product = null]],children = null,parent = null]

正確的方法是先堅持Product,然後堅持Image或Hibernate可以自動堅持Image當我堅持Product

回答

0

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:我沒有測試代碼,但這應該工作。