使用 JPA 保留会留下嵌套对象的 db 外键字段空



我的表格具有结构:

orders
- id: bigint(20)
- amount: bigint(20)
order_details
- id: bigint(20)
- payment_type: varchar(255)
- order_fk: bigint(20)

实体:

MyOrderEntity

@Entity
@Table(name = "orders")
public class MyOrderEntity {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    public Long id;
    public Long amount;
    @OneToOne(fetch = LAZY, mappedBy = "order", cascade = ALL)
    public MyOrderDetailsEntity details;
}

MyOrderDetailsEntity

@Entity
@Table(name = "order_details")
public class MyOrderDetailsEntity {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    public Long id;
    @OneToOne
    @JoinColumn(name = "order_fk")
    public MyOrderEntity order;
    public String paymentType;
}

存储库

@Repository
public interface MyOrderRepository extends JpaRepository<MyOrderEntity, Long> {}

我以这种方式坚持MyOrderEntity

MyOrderDetailsEntity details = new MyOrderDetailsEntity();
details.paymentType = "default";
MyOrderEntity order = new MyOrderEntity();
order.amount = 123L;
order.details = details;
myOrderRepository.save(order);

order保存后,我有 null order_details.order_fk字段中的值。

我希望order_details.order_fk将被order.id填充。

我该怎么做?

您还需要明确将MyOrderEntity设置为MyOrderDetailsEntity。JPA实施不适合您。因此,添加行:

details.order = order;

保存之前。

您还可以将以下方法添加到MyOrderEntity

@PrePersist
private void prePersist() {
    if(null!=details) details.order=this;
}

避免将MyOrderDetailsEntity设置为 MyOrderEntity的任何地方的样板代码。

,但最好的方法是设置MyOrderDetailsEntity.details字段private并创建一个类似于:

的设置器
setDetails(MyOrderDetailsEntity details) {
    this.details = details;
    details.order = this;
}

即使在持续存在之前,要保持它始终正确设置。最佳策略取决于案例。

有关更多详细信息,请参见此问题和答案。

相关内容

  • 没有找到相关文章

最新更新