Hibernate version: 3.1, annotations 3.1 beta 7
Hi
I am modelling a legacy Oracle 9 database using Hibernate 3.1 with annotations (3.1 beta 7) and I have come across an interesting problem.
I have two tables linked by a foreign key. Here's a simplified diagram:
Code:
+------------------------+
| MESSAGE |
+------------------------+
| (PK) id: integer |
| (FK) hash: varchar(40) |
+------------------------+
+------------------------+
| MESSAGE_BODY |
+------------------------+
| (PK) id: varchar(40) |
| data: varchar(blob) |
+------------------------+
In addition there is a referential integrity constraint on the MESSAGE_BODY.ID column which states that the owner of the hash is the MESSAGE.HASH column, thus nothing can be inserted into the MESSAGE_BODY table without the hash already existing in MESSAGE.
The relevant methods in the corresponding POJOs are as follows.
Message.java:
Code:
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "HASH")
public MessageBody getMessageBody() {
return this.messageBody;
}
MessageBody.java:
Code:
@Id(generate = GeneratorType.NONE)
@OneToOne(mappedBy = "messageBody")
@Column(name = "ID", length = 40)
public String getHash() {
return hash;
}
I am using the
GenericHibernateDao persistence method.
When I attempt to persist a Message object, I get an "integrity constraint violated - parent key not found" error, because Hibernate attempts to persist the MessageBody object first.
I have two questions. 1) Is this behaviour to be expected?, and 2) Is there anything I can do to configure Hibernate such that the Message object is persisted before the MessageBody object?
Whilst this is probably an unusual database set up, I am unfortunately stuck with it for legacy reasons. I believe I could work around the issue by overriding makePersistent() in my DAO and writing specific INSERT queries to allow Message to be persisted first, but this does seem to be a rather desperate hack.
Thanks in advance.