有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Hibernate正在@OneToOne中创建条目但未设置FK

我有两个实体,它们通过@OneToOne注释连接。首先,为了更好地理解我的课程:

第二实体:

@Table(name = "REASON_FOR_CLIENT_CHEQUE_PAYMENT_REVERSAL")
@Entity
public class ReversalReason implements Serializable{
    /**
     * 
     */
    private static final long serialVersionUID = 3338809410372872259L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer code;

    private boolean tax;
    private boolean currency;
    private boolean amountChange;
    private boolean locationChange;
    private boolean recipient;
    private boolean period;

    public ReversalReason() {

    }
}

基本实体:

@Table(name = "CLIENT_CHEQUE_PAYMENT")
@Entity
public class ClientChequePayment extends BaseDomainObject implements Serializable {
    /** Serial version UID */
    private static final long serialVersionUID = -1988633355L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer code;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "code", nullable = true)
    private ReversalReason reasonForReversal;

    @Column(nullable = true, length = 50)
    private String proposeReversalUser;
    @Column(length = 50, unique = true)
    private String displayCode;
    @Column(length = 50)
    private String originalEntry;

    private PaymentStatus originalPaymentStatus;

我对一些字段进行了ommit,因为否则代码会太多。现在让我们来看问题:

在我的程序中,我希望能够通过调用session.update(clientChequePayment);来设置reasonForReversalClientChequePayment字段。我检查了在调用update之前是否设置了该字段,结果是。问题是,hibernate确实为ReversalReason创建了一个条目,但它没有将ReversalReason的PK设置为ClientChequePayment条目中的FK。因此,我可以为1ClientChequePayment创建几个ReversalReasonenries

我的映射正确吗(我不需要通过ReversalReason访问ClientChequePayment,反之亦然)?即使不需要,映射是否应该是双向的


共 (1) 个答案

  1. # 1 楼答案

    继续评论

    这就是问题所在,您需要一个列,该列具有指向REASON_FOR_CLIENT_CHEQUE_PAYMENT_REVERSAL的外键

    也就是说,表CLIENT_CHEQUE_PAYMENT需要一个外键来REASON_FOR_CLIENT_CHEQUE_PAYMENT_REVERSAL,类似于id_reversal_reason,然后您可以执行以下操作:

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "id_reversal_reason", nullable = true)
    private ReversalReason reasonForReversal;
    

    联接列位于源表的所属表上

    来自@JoinColumnjavadocs的name的片段:

    (Optional) The name of the foreign key column.
     * The table in which it is found depends upon the
     * context.
     * <ul>
     * <li>If the join is for a OneToOne or ManyToOne
     *  mapping using a foreign key mapping strategy,
     * the foreign key column is in the table of the
     * source entity or embeddable.