java一对多更新,java – saveorupdate()不会在hibernate中更新集合(列表)一对多映射

班级学生

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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值