Hibernate @如何使Json引用现有的外键?

Hibernate @如何使Json引用现有的外键?,hibernate,rest,spring-data-jpa,spring-rest,Hibernate,Rest,Spring Data Jpa,Spring Rest,我正在制作一个Spring Boot RESTful应用程序。我有两个实体:访客: @Data @NoArgsConstructor @AllArgsConstructor @Entity public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private String em

我正在制作一个Spring Boot RESTful应用程序。我有两个实体:访客:

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private String email;
    private String gender;
}
及产品

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private int qty;
    private int price;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "customer_id", referencedColumnName = "id")
    private Customer customer;
}
这就是我试图通过控制器将Json推入OrderRequest对象的方式:

@PostMapping("/placeOrder")
    public Product saveOrder(@RequestBody OrderRequest request){
       return productRepository.save(request.getProduct());
    }
OrderRequest类:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class OrderRequest {

    private Product product;
}
存储库类是标准的:

public interface ProductRepository extends JpaRepository<Product, Integer> {}
public interface CustomerRepository extends JpaRepository<Customer, Integer> {}

问题:如何使客户表中已有一行,我可以向服务器发送Json,在其中,我只指出了产品参数和一个外键参数,该参数将作为对客户行的引用???谢谢

在控制器层中公开持久性级别实体不是最佳做法,因为API与数据的内部表示相耦合

实现需求的常用方法是使用Transfer对象模式。也就是说,创建单独的类以在API中使用。在您的用例中,您可以创建具有以下结构的ProductTO类:

public class ProductTO {
    private int id;
    private String name;
    private int qty;
    private int price;

    private int customerId;
}
然后,您可以手动在ProductTO和Product之间映射字段,或者使用任何映射库(例如:MapStruct)自动复制两个类中同名字段的值

外键应手动分配:

Customer customer = this.customerRepo.findById(productTO.getCustomerId()).orElseThrow(() -> new YourException());
product.setCustomer(customer);

如何使用mapstruct实现此功能@萨蒂亚戈
Customer customer = this.customerRepo.findById(productTO.getCustomerId()).orElseThrow(() -> new YourException());
product.setCustomer(customer);