Hi!
I have two tables, Users and Events... The relationship is described as (one) Event know about which (one) User who registered the event. A user does not know what events it have registered. Looks like a one way directional one-to-one relationship, right?
But I figured i could get away with many-to-one by using the primary key from Users as a foreign key in Events. Am i on the right track?
Event.hbm.xml
Code:
<class
name="se.rullstol.ejb.persistence.Event"
table="Events"
dynamic-update="false"
dynamic-insert="false">
<many-to-one
name="user"
class="se.rullstol.ejb.persistence.User"
cascade="all"
outer-join="auto"
update="true"
insert="true"
column="userId"/>
</class>
User.hbm.xmlCode:
<class
name="se.rullstol.ejb.persistence.User"
table="Users"
dynamic-update="false"
dynamic-insert="false">
<id name="id" column="Id" type="long">
<generator class="identity">
</generator>
</id>
</class>
database:Code:
table Users (
Id BIGINT NOT NULL AUTO_INCREMENT,
primary key (Id)
);
table Events (
Id BIGINT NOT NULL AUTO_INCREMENT,
userId BIGINT,
primary key (Id)
);
alter table Events add index (userId), add constraint FK7C6CCD39CE2B2E46 foreign key (userId) references Users (Id);
Events
+----+--------+
| id | userid |
+----+--------+
| 1 | 1 |
| 2 | 1 |
| 3 | 2 |
+----+--------+
Users
+----+
| id |
+----+
| 1 |
| 2 |
+----+
This actually works to good. Add and Update, fine! Deleting users that have their FK in the Events table also seems ok to hibernate?? I thought that hibernate (2.1) would throw an excpetion since it will break the integrity of the tables... and since im using (the latest version) of MySQL, the database wont complain either.. here's the testcode:
Testcode:Code:
User user = (User)session.load(User.class, new Long(1));
session.delete(user);
session.flush();
I've been reading, reading and trying, trying but nothing seems to work... one-to-one relationship (with property-ref) in the Events.hbm.xml doesnt seem to work either..
Thankful for any help
regards,
Kristoffer