本文介绍了坚持使用JPA会使嵌套对象的db外键字段为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表格结构如下:

orders
- id: bigint(20)
- amount: bigint(20)

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

实体:

MyOrderEntity

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

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后,我在order_details.order_fk字段中具有 null 值.


After order saving I have null value in order_details.order_fk field.

我希望order_details.order_fkorder.id填充.

我该怎么做?

推荐答案

您还需要将MyOrderEntity显式设置为MyOrderDetailsEntity. JPA实现无法为您完成此任务.因此,添加以下行:

You need also to explicitly set the MyOrderEntity to MyOrderDetailsEntity. JPA implementation does not do it for you. So add line:

details.order = order;

保存之前.

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

You can also add following method to MyOrderEntity:

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

为避免到处都有样板代码,请将MyOrderDetailsEntity设置为MyOrderEntity.

to avoid boilerplate code everywhere you set the MyOrderDetailsEntity to MyOrderEntity.

但是最好的方法是设置MyOrderDetailsEntity.details字段private并创建一个设置器,例如:

But the best way is to set MyOrderDetailsEntity.details field private and create a setter like:

setDetails(MyOrderDetailsEntity details) {
    this.details = details;
    details.order = this;
}

使其始终正确设置,即使在保存之前也是如此.最佳策略视情况而定.

to keep it always set correctly, even before persisting. Best strategy depends on the case.

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

See this question and answers for more details.

这篇关于坚持使用JPA会使嵌套对象的db外键字段为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 12:48