Hibernate One to One id为null,为什么?

时间:2016-05-19 14:05:19

标签: hibernate jpa identifier one-to-one

我的代码:

financialTransactionEntity.getFinancialTransaction_5000().setFinancialTransactionEntity(financialTransactionEntity);

和我的课程:

@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;
    }
}

但我将在DB中获得的内容如下:

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    |

如何确保financialTransaction_5000_id也 1

2 个答案:

答案 0 :(得分:0)

删除@OneToOne中的mappedBy参数

答案 1 :(得分:0)

来自@OneToOne.mappedBy() javadoc:

  

拥有这种关系的领域。此元素仅在关联的反向(非拥有)侧指定。

你只需要在“非拥有”实体上指定,所以我猜你要么坚持关联的错误方面,要么让mappedBy在错误的一方。