2

I have tables with structure:

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

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

Entities:

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:

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

I'm persisting MyOrderEntity in such way:

MyOrderDetailsEntity details = new MyOrderDetailsEntity();
details.paymentType = "default";

MyOrderEntity order = new MyOrderEntity();
order.amount = 123L;
order.details = details;

myOrderRepository.save(order);

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

I want that order_details.order_fk will be filled by order.id.

How can I do this?

pirho
  • 11,565
  • 12
  • 43
  • 70
Roman Cherepanov
  • 1,639
  • 2
  • 24
  • 44

1 Answers1

3

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

details.order = order;

before save.

You can also add following method to MyOrderEntity:

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

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

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.

Roman Cherepanov
  • 1,639
  • 2
  • 24
  • 44
pirho
  • 11,565
  • 12
  • 43
  • 70