I'm trying to send the following JSON to a REST API and persist on database, but only the Product
is created, the Image
it is not.
{"name":"pen", "description":"red pen", "images":[{"type":"jpeg"}] }
@Controller
@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;
At the @POST
method, when print the Product
object received, this is what returns:
Product [productId=null, name=pen, description=red pen, images=[Image [id=null, type=jpeg, product=null]], children=null, parent=null]
The correct way is to first persist the Product
, and then persist the Image
or the Hibernate can automatically persist the Image
when I persist the Product
?