班级学生
public class Student {
private Long id;
private String name;
private String className;
private List phones;
// getter setter
}
课程电话
public class Phone {
private Long id;
private String number;
//getter setter
}
– > mappping文件Student.hbm.xml
– >映射文件Phone.hbm.xml
当我尝试更新电话号码(列表)时,前一个条目不会被删除,但idx(列表索引)和外键为空,新条目用正确的idx和外键标记!!另一个数据(不是列表)完全更新.在这里,我从数据库中获取类对象,修改它并将对象传递给saveorupdate(),但没有帮助.一直在尝试这么久.
要读取和更新的代码:
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 phones = new ArrayList();
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();
}
}