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

liwlm1x9  于 2024-01-07  发布在  PostgreSQL
关注(0)|答案(1)|浏览(121)

我使用Java与Sping Boot 框架和PostgreSQL(通过Hibernate)本地数据库。我有实体User,Product和UserOrder。每个UserOrder有4列:id,product_id(来自Product),user_id(来自User)和quantity。
我以前创建了一个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;
}

字符串
示例Postman主体:

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


OneToOne注解更改为fetch = FetchType.LAZY没有帮助。设置@JoinColumn(name = "user_id",nullable = false)会导致异常。
为什么我的外键字段为null?

9q78igpj

9q78igpj1#

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

相关问题