class Student
public class Student {
private Long id;
private String name;
private String className;
private List<Phone> phones;
}
class Phone
public class Phone {
private Long id;
private String number;
}
-> display file Student.hbm.xml
<id name="id" type="long" column="id">
<generator class="native" />
</id>
<property name="name" column="name" type="string" />
<property name="className" column="class_name" type="string" />
<list name="phones" cascade="all-delete-orphan">
<key column="student_id"/>
<list-index column="idx" />
<one-to-many class="Phone" />
</list>
-> Phone.hbm.xml mapping file
<id name="id" type="long" column="id">
<generator class="native" />
</id>
<property name="number" column="number" type="string" />
when I try to update the phone number (list), the previous record is not deleted, and idx (list index) and foreign key are zero, and new entries are marked with the correct idx and foreign key! Other data (not a list) is completely updated. Here I get the class object from the database, modify it and pass the object saveorupdate(), but it did not help. Tried this for so long. It would be a great help.
Code for reading and updating:
private void readAndUpdateStudent() {
Student student = null;
Session session = HibernateUtil.getSessionFactory().openSession();
String name = "John";
try {
String queryString = "from Student student where student.name =:name";
Query query = session.createQuery(queryString);
query.setString("name", name);
student = (Student) query.uniqueResult();
System.out.println(student.getName());
student.setName("Mary");
List<Phone> phones = new ArrayList<Phone>();
phones.add(new Phone("555555"));
phones.add(new Phone("789789"));
student.setPhones(phones);
} catch (Exception e) {
e.printStackTrace();
if (session != null) {
session.close();
}
}finally{
session.close();
updateStudent(student);
}
}
private void updateStudent(Student student) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.saveOrUpdate(student);
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}

source
share