Hi,
I am using
Hibernate 3.0 & SQL Server 2000.
I have 3 tables Account (Id[PK], Name) , Role (Id[PK], Description), R_Account_Role (Account_Id[FK], Role_Id[FK]). Account and Role have a many-to-many relationship via R_Account_Role table.
Account.hbm.xml
Code:
<hibernate-mapping>
<class name="Account" table="Account">
<id name="id" column="ID" type="integer" >
<generator class="identity"/>
</id>
<property name="name" column="Name" not-null="true" type="string" />
<set name="roles" table="R_Account_Role" lazy="false" cascade="all" >
<key column="Account_Id" not-null="true"/>
<many-to-many column="Role_Id" class="Role" />
</set>
</class>
</hibernate-mapping>
Role.hbm.xmlCode:
<hibernate-mapping>
<class name="Role" table="Role">
<id name="id" column="ID" type="integer" >
<generator class="identity"/>
</id>
<property name="description" column="Description" not-null="true" type="string" />
<set name="accounts" table="R_Account_Role" lazy="false" cascade="all" >
<key column="Role_Id" not-null="true"/>
<many-to-many column="Account_Id" class="Account" />
</set>
</class>
</hibernate-mapping>
Java code to delete an accountCode:
Account account = (Account) session.load(Account.class, accountId);
session.delete(account);
session.flush();
If I execute this, then all the roles associated with this account also gets deleted from Role table.
Ideally, only the records from Account-Role relationship table should get deleted.
If I do not use "cascade=all" then exception is thrown when I try to delete Account, since accountId is foreign key in R_Account_Role table.
Basically, I want to be able to create, update, delete an Account (and records in Account-Role relationship table), keeping Role table relatively constant [i.e. number of roles are fixed]
I am confused whether to create another hbm.xml file for R_Account_Role table or above code is sufficient with some changes. Please help.
Thanx.