Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hibernate Bidirectional Mapping Problem.

 
Pradeep Bhat
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,


I have a parent child relationship.
Dept (One) ------ Student (Many)

Trying to persist a Dept along with its students.
Can see Dept entry in the database table.
Can see Student entries in the database table.

Problem : Student (child entity)entries have foreign key column as null in database.
What could be the problem for this?

Tried the following approaches.
1. Used <set>. Used java.util.Set in the Java class.
2. I have explicitly set parent reference to child objects.
3. Removed explicit foreign key constraint from database.

Table Details
----------------
Dept - ID(primary key) ........and other fields
Student - ID (primary key), DEPTID(foreign key), ........ and other fields.

HBM Mapping
----------------

<class entity-name="Dept" name="com.home.Dept" table="DEPT" lazy="false">
<id name="id" column="ID">
<generator class="increment"/>
</id>
<bag name="studentList" cascade="all" inverse="true" table="STUDENT" order-by="ID" lazy="false">
<key column="DEPTID" not-null="true"/>
<one-to-many entity-name="Student"/>
</bag>
</class>

<class entity-name="Student" name="com.home.Student" table="STUDENT" lazy="false">
<id name="id" column="ID">
<generator class="increment"/>
</id>
<many-to-one name="department" column="DEPTID" entity-name="Dept" lazy="false" insert="false" update="false" not-null="true"/>
</class>

Class Details
----------------

public class Dept implements IDept {
private long id;
private List studentList;

public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public List getStudentList() {
return studentList;
}
public void setStudentList(List studentList) {
this.studentList = studentList;
}
}

public class Student implements IStudent {
private long id;
private Dept department;

public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Dept getDepartment() {
return department;
}
public void setDepartment(Dept department) {
this.department = department;
}
}

Code used for persistance
---------------------------------
IDept dept = new Department();
List studentList = new ArrayList();
Student a = new Student();
Student b = new Student();
a.setDepartment(dept);
b.setDepartment(dept);
studentList.add(a);
studentList.add(b);
dept.setStudentList(studentList);
getHibernateTemplate().save("Dept", dept); // Using Spring's Hibernate Template.




Thanks,
Pradeep.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic