gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:50:43 25 4
gpt4 key购买 nike

我正在尝试将以下 JSON 发送到 REST API 并保存在数据库中,但只创建了 Product,而没有创建 Image

{"name":"pen", "description":"red pen", "images":[{"type":"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);
}

@产品

@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;

@图片

@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 对象时,返回的是:

Product [productId=null, name=pen, description=red pen, images=[Image [id=null, type=jpeg, product=null]], children=null, parent=null]

正确的做法是先持久化Product,再持久化Image或者我持久化时Hibernate会自动持久化Image 产品?

最佳答案

Hibernate 会在正确实现双向映射并且在实体对象之间设置正确关系的情况下负责持久化子实体。

您有一个 Product 实体,其中包含 Image 的集合。 Product 实体是这里的父实体。您可以简单地在 ProductImage 实体之间设置适当的关系,并仅保留 Product。 Hibernate 将保留您的父实体和您的子实体。

What you need to do

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:我没有测试代码,但这应该可以。

关于java - 使用 OneToMany 将对象从 JSON 保存到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43432095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com