我的表格具有结构:
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;
}
即使在持续存在之前,要保持它始终正确设置。最佳策略取决于案例。
有关更多详细信息,请参见此问题和答案。