Search code examples
hibernatejpaidentifierone-to-one

Hibernate One to One id is null, why?


Code I have:

financialTransactionEntity.getFinancialTransaction_5000().setFinancialTransactionEntity(financialTransactionEntity);

and the classes I have:

@Entity
@Table(name = "master_card_daily_financial_transaction_entity")
public class FinancialTransactionEntity {

    private Long id;

    private FinancialTransaction_5000 financialTransaction_5000;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @OneToOne(mappedBy = "financialTransactionEntity",
            targetEntity = FinancialTransaction_5000.class,
            cascade = javax.persistence.CascadeType.ALL)
    @Cascade({org.hibernate.annotations.CascadeType.ALL})
    public FinancialTransaction_5000 getFinancialTransaction_5000() {
        return financialTransaction_5000;
    }

    public void setFinancialTransaction_5000(FinancialTransaction_5000 financialTransaction_5000) {
        this.financialTransaction_5000 = financialTransaction_5000;
    }
}

--

@Entity
@Table(name = "master_card_daily_financial_transaction_5000")
public class FinancialTransaction_5000 {

    private Long id;
    private FinancialTransactionEntity financialTransactionEntity;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @OneToOne(targetEntity = FinancialTransactionEntity.class,
            cascade = javax.persistence.CascadeType.ALL)
    @Cascade({org.hibernate.annotations.CascadeType.ALL})
    public FinancialTransactionEntity getFinancialTransactionEntity() {
        return financialTransactionEntity;
    }

    public void setFinancialTransactionEntity(FinancialTransactionEntity financialTransactionEntity) {
        this.financialTransactionEntity = financialTransactionEntity;
    }
}

but what I will get in the DB is as follows:

table: master_card_daily_financial_transaction_entity
+-----+------------------------------+
| id  | financialTransaction_5000_id |
+-----+------------------------------+
|   1 |                         NULL |

table: master_card_daily_financial_transaction_5000
+-----+-------------------------------+
| id  | financialTransactionEntity_id |
+-----+-------------------------------+
|   1 |                          1    |

How can I make sure that I financialTransaction_5000_id is also 1?


Solution

  • From the @OneToOne.mappedBy() javadoc:

    The field that owns the relationship. This element is only specified on the inverse (non-owning) side of the association.

    You only need to specify on the "non-owning" entity, so I guess you are either persisting the wrong side of the association, or have the mappedBy on the wrong side.