Hi all,
I'm new to Hibernate and I have a question about cascade delete...
In my application I'm using user/role relationship in the following way:
Code:
CREATE TABLE pb_user (
id INTEGER NOT NULL PRIMARY KEY,
username VARCHAR(128) NOT NULL UNIQUE,
password VARCHAR(128) NOT NULL,
email_address VARCHAR(128) NOT NULL UNIQUE,
enabled BOOLEAN NOT NULL,
creation_date TIMESTAMP NOT NULL,
last_visit TIMESTAMP NOT NULL
);
CREATE TABLE pb_authority (
id INTEGER NOT NULL PRIMARY KEY,
authority VARCHAR(128) NOT NULL,
description VARCHAR(1024)
);
CREATE TABLE pb_granted_authority (
user_id INTEGER NOT NULL,
authority_id INTEGER NOT NULL
);
ALTER TABLE pb_granted_authority ADD CONSTRAINT c2ad45de FOREIGN KEY (user_id) REFERENCES pb_user(id);
ALTER TABLE pb_granted_authority ADD CONSTRAINT d4ffa12e FOREIGN KEY (authority_id) REFERENCES pb_authority(id);
This is mapped to Hibernate as follows:
Code:
<hibernate-mapping auto-import="true" default-lazy="false">
<class name="pb.user.User" table="pb_user">
<id name="id" type="long" column="id" unsaved-value="0">
<generator class="increment" />
</id>
<property name="username" type="string" column="username" length="128" not-null="true" unique="true" />
<property name="password" type="string" column="password" length="128" not-null="true" unique="true" />
<property name="emailAddress" type="string" column="email_address" length="128" not-null="true" unique="true" />
<property name="enabled" type="boolean" column="enabled" not-null="true" />
<property name="creationDate" type="timestamp" column="creation_date" not-null="true" />
<property name="lastVisit" type="timestamp" column="last_visit" not-null="true" />
<set name="grantedAuthorities" table="pb_granted_authority" cascade="all">
<key column="user_id" />
<many-to-many column="authority_id" class="pb.user.Authority" />
</set>
</class>
<class name="pb.user.Authority" table="pb_authority">
<id name="id" type="long" column="id" unsaved-value="0">
<generator class="increment" />
</id>
<property name="authority" type="string" column="authority" length="128" />
<property name="description" type="string" column="description" length="1024" />
</class>
</hibernate-mapping>
This works fine when creating users (the user is created in pb_user and also any entries in the pb_granted_authority table).
However, when I delete a user, the row in the pb_authority reference table is also deleted. This is not what I want. pb_authority should be a reference table managed outside of any application code. It lists the available authorities and should be only referenced.
What I want is that, when I delete a user, the corresponding granted authorities are also removed from the pb_granted_authorities table, but the reference authorities in pb_authority should NOT be removed.
How can I do that? Is it simply removing the foreign key constraint to pb_authority from pb_granted_authority?
Many thanks,
James