class Student
public class Student {
private Long id;
private String name;
private String className;
private List<Phone> phones;
// getter setter
}
class Phone
public class Phone {
private Long id;
private String number;
//getter setter
}
-> mappping 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>
-> mapping file Phone.hbm.xml
<id name="id" type="long" column="id">
<generator class="native" />
</id>
<property name="number" column="number" type="string" />
when i try to update the the phone number (a list), the previous entry is not deleted but the idx(list index) and the foreign key are null and the new entries are marked with the correct idx and foreign key!!The other data (not a list) is updated completely fine. Here I get the class object from the database, modify that and pass the object to saveorupdate()
, but didn't help. Been trying this so long.
Code to read and update:
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")); //here if I SET rather adding, the already existing values, update is done accordingly
phones.add(new Phone("789789"));//but when I use the list as a string type(instead of Phone Type), adding a new 0bject deletes the previous
student.setPhones(phones);//entries and adds new list on its own but not in the case of user defined type.
} 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();
}
}
If you want to update a list of phones, you shouldn't do
The above code doesn't update the list of phones, but create a brand new one. To update a list of phones, you should retrieve the old lists and update its entries: