I need to implement a function
private void saveChild(Integer parentId) {
//save a child object to the DB that has Child.parent.id = parentId;
}
As far as I know, the way to do this is to create the Child and Parent objects, and then to call the Session.save() function, passing in the child object.
Below is a sample mapping file for the Child and Parent class.
This wouldn't be a problem except that in my real life example, Parent class has a many to one relationship to a GrandParent table and so on and so forth.
So it seems I only have two choices:
1. Manually create the whole chain of objects related to this mapping, which is huge.
2. Query for a Parent object using the passed in parentId. Then set Child.parent to this queried Parent object
There must be a better way...is there?
Code:
<class name = "Child" table = "Child_Table">
<many-to-one name="parent" column="PARENT_ID" class="Parent" not-null="true"/>
</class>
<class name = "Parent" table = "Parent_Table">
<id name="parentId" column="PARENT_ID">
<generator class="native"/>
</id>
</class>
class Child {
private Parent parent;
public getParent() {
return parent;
}
public setParent(Parent parent) {
this.parent = parent;
}
}
class Parent {
private Integer parentId;
}
CREATE TABLE Child (
PARENT_ID number
CONSTRAINT fk_parentId
FOREIGN KEY PARENT_ID
REFERENCES PARENT (PARENT_ID))
)
CREATE TABLE PARENT {
PARENT_ID number
}