我确实有2个实体,它们通过@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;


我确实省略了一些字段,因为否则代码会太多。现在让我们去解决问题:

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

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

最佳答案

从评论继续。

这就是问题所在,您需要一个具有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;


连接列在源表的所属表上。

来自name javadocs的@JoinColumn的片段:

(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.

07-24 15:23