我有结构的表:

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并创建一个setter,例如:

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


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

有关更多详细信息,请参见this question and answers

09-28 08:38