I do have 2 entitys, which are connected via @OneToOne
annotation. First my classes for better understanding:
2nd Entity:
@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() {
}
}
Base entity:
@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;
I did ommit some fields because otherwise the code would be too much. Now lets go to the problem:
In my program I want to be able to set the field reasonForReversal
of ClientChequePayment
with calling session.update(clientChequePayment);
. I checked if the field was set before calling update
and it was. The problem is, that hibernate does create a entry for ReversalReason
, but it does not set the PK of ReversalReason
as FK in ClientChequePayment
entry. Because of that, i can create several ReversalReason
enries for 1 ClientChequePayment
.
Is my mapping correct (I have no need to acces ClientChequePayment
via ReversalReason
, but vice versa)? Should the mapping be bi-directional even tho its not needed?
Continuing from the comments.
That's the problem, you need a column that has a foreign key to REASON_FOR_CLIENT_CHEQUE_PAYMENT_REVERSAL
.
Meaning, your table CLIENT_CHEQUE_PAYMENT
needs a foreign key to REASON_FOR_CLIENT_CHEQUE_PAYMENT_REVERSAL
, something like id_reversal_reason
and then you can do:
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "id_reversal_reason", nullable = true)
private ReversalReason reasonForReversal;
The join column is on the owning table for source table.
A snippet from name
from the @JoinColumn
javadocs:
(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.