为什么我的外键字段在发布后为空?

问题描述 投票:0回答:1

我在本地使用 Java 和 Spring Boot 框架以及 PostgreSQL(通过 Hibernate)数据库。我有实体用户、产品和用户订单。每个 UserOrder 有 4 列:id、product_id(来自 Product)、user_id(来自 User)和数量。

我之前创建了一个 id 为 1 的产品和用户。当我通过 Postman 发布然后检索它时,product_id 和 user_id 为 null。

@Data
@Builder 
@NoArgsConstructor 
@AllArgsConstructor 
@Entity 
@Table(name = "_user")
public class User {
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Integer id;
    private String firstname;
    private String lastname;
    private String email;
    private String password;
    @Enumerated(EnumType.STRING)
    private Role role;

    @OneToOne(mappedBy = "user")
    private UserOrder userOrder;
}

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table
public class Product {
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Integer id;
    private String name;
    private String price;
    @OneToOne(mappedBy = "product",cascade = CascadeType.ALL)
    private UserOrder userOrder;
}

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table
public class UserOrder {
    @Getter
    @jakarta.persistence.Id
    @Id
    @GeneratedValue
    private Integer id;
    private String quantity;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "user_id")
    private User user;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "product_id")
    private Product product;
}

邮递员身体示例:

{
    "product_id":1,
    "user_id":1,
    "quantity":"50"
}

OneToOne
注释更改为
fetch = FetchType.LAZY
没有帮助。设置
@JoinColumn(name = "user_id",nullable = false)
会导致异常。

为什么我的外键字段为空?

java postgresql spring-data-jpa postman foreign-keys
1个回答
0
投票

确保要保存到UserOrder的User和Product确实存在于数据库的User和Product表中

© www.soinside.com 2019 - 2024. All rights reserved.