I forgot to mention that we use another column in the tables. The column
is called "deleted" and it indicates whether that row is deleted or not. This is done as a standard in order to avoid physical deletion of rows.
Table 1
Part_Id - int identity (10) - Primary key
Part_Code - Char (10)
Part_Name - Varchar (50)
deleted - int(1) - value zero or one
Table 2
Sequence_Id - int identity (10) - Primary key
Part_Id - int(10) - Foreign key -->Table1.Part_Id
Replacing_Part_Id - int(10) - Foreign key-->Table1.Part_Id
deleted - int(1) - value zero or one
And I created my mappings like this.
Code:
<hibernate-mapping>
<class name="Table1ClassName" table="Table1">
<id name="partId" >
<column name="Part_Id">
<generator class="increment" />
</column>
</id>
<property name="partCode" type="string">
<column name="Part_Code" length="10" />
</property>
<property name="partName" type="string">
<column name="Part_Name" length="50" />
</property>
<set name="replacingParts" lazy="false" inverse="true" cascade="save-update" sort="unsorted">
<key column="Part_Id"></key>
<one-to-many class="Table2ClassName"/>
</set>
<property name="deleted" column="DELETED" />
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="Table2ClassName" table="Table2">
<id name="sequenceId" >
<column name="Sequence_Id">
<generator class="increment"/>
</column>
</id>
<many-to-one name="table1PartId" class="Table1ClassName" cascade="save-update">
<column name="Part_Id">
</many-to-one>
</class>
</hibernate-mapping>
Note that I didn't use the second many-to-one mapping in Table2ClassName that you had given (which might be the solution to the problem that i am facing right now).
This one-to-many mapping of parent-child relationship worked fine except for one condition.
If I want to delete a part in the parent table, I actually update the delete column value of that part to one. Under this condition, I should update(mark as delete) child rows in table 2 as well. I cud do that for those rows that have the part_id as foriegn key in table 2 (since they are of collections in Table1ClassName). However there could be reference to this part id in the Replacing_Part_Id columns of Table2.
Code:
Part_Id Part_Code Delete
1 AE 0
2 AF 0
3 AS 0
4 FS 0
5 KS 0
seq_Id Part_Id replacing_part_id Delete
1001 1 2 0
1002 1 3 0
1003 3 5 0
1004 4 1 0
Now If I mark
part_id 1 as deleted in table 1 I can easily mark the 1001 and 1002 sequence rows of table2 as deleted. How do I find the fourth row (sequnce 1004) which has reference to part_id 1?
Please provide java class definition for correct mappings. Many thanks for yoor help!!