0

I am new to Hibernate. I am trying to read the object from the database and make an update.
Consider this Bi-directional mapping

STUDENT    --->   COURSES  
One               Many

hbm.xml's:
Student.hbm.xml:

<set name="courses" table="COURSES" inverse="false" >
            <key>
                <column name="STUDENT_ID" />
            </key>
            <one-to-many  class="Courses" />
</set>     

Courses.hbm.xml:

<many-to-one name="student" class="Student" >
        <column name="STUDENT_ID" />
</many-to-one>

Java Code:

        Session session = Utility.getSessionFactory().openSession();
        session.beginTransaction();

        Student student = (Student)session.get(Student.class, 1);

        Courses course = new Courses();
        course.setPriceOpen(new Float("1.2"));
        course.setPriceClose(new Float("1.1"));
        course.setPrceChange(new Float("10.0"));
        course.setDate(new Date());

        course.setStudent(student);        
        student.getCourses().add(course);

        session.save(course);
        session.update(student);

        session.getTransaction().commit();
        session.close();

After loading an Student object from the database, I am trying to add a new Course to that loaded Student instance.
However, i do get this error

Exception in thread "main" org.hibernate.HibernateException: 
identifier of an instance of Course was altered from 1 to 0.

Any suggestions on how will I update that Student instance, so that this instance of Student will now have 2 courses assigned to it.

Farhan stands with Palestine
  • 13,890
  • 13
  • 58
  • 105
  • How did you define identity column in HBM? http://stackoverflow.com/questions/4179166/hibernate-how-to-fix-identifier-of-an-instance-altered-from-x-to-y – nayakam Jan 27 '15 at 01:19
  • You dont need to save course. Just update the student. and in hbm file set cascade=update for course. Let me know if that works – javafan Jan 27 '15 at 03:09

0 Answers0