【问题标题】:Getting HibernateException: illegally attempted to associate a proxy with two open Sessions when attempting to update获取 HibernateException:在尝试更新时非法尝试将代理与两个打开的会话相关联
【发布时间】:2019-01-23 08:36:27
【问题描述】:

我正在尝试使用 Hibernate 更新表中的元素,但出现以下错误:

出现意外错误(类型=内部服务器错误, 状态=500)。非法尝试将代理与两个打开的 会议;嵌套异常是 org.hibernate.HibernateException: 非法尝试将代理与两个打开的会话关联

道:

    @Override
public Demande getDemandeById(int id) {
    // TODO Auto-generated method stub
    Session session;
     try {
         session = this.sessionFactory.getCurrentSession();
        } catch (HibernateException ex) {
            session = this.sessionFactory.openSession();
        }

    Demande d = (Demande) session.load(Demande.class, new Integer(id));
    return d;
}
@Override
public void updateDemande(Demande d) {
    // TODO Auto-generated method stub
    Session session;
     try {
         session = this.sessionFactory.getCurrentSession();
        } catch (HibernateException ex) {
            session = this.sessionFactory.openSession();
        }

    session.update(d);

    logger.info("Person updated successfully, Person Details="+d);
}

控制器:

@GetMapping("rh/editProfilDemande")
public String  RHEditProfilForm(Model m, @RequestParam int id_demande) {  
    this.profil_id = pf.getIdProfil();
    Demande d = demandeService.getDemandeById(id_demande);
    this.idDemande = id_demande; 

    m.addAttribute("profil", pf);

    m.addAttribute("demande", d); 
    return "RHEditProfil";


}   

@PostMapping("rh/editProfilDemande")
public String  RHEditProfil(Model m, Profil pf) {
    Demande d= demandeService.getDemandeById(this.idDemande);



    demandeService.updateDemande(d);
     m.addAttribute("demande",d);
    return "RHDemandeTraiteSuccess";


} 

【问题讨论】:

    标签: java hibernate spring-mvc orm


    【解决方案1】:

    您正在打开新会话,但如果这部分代码被执行,您将永远不会关闭它们:

    session = this.sessionFactory.openSession();
    

    如果你真的想保持这个逻辑:

      try {
         session = this.sessionFactory.getCurrentSession();
        } catch (HibernateException ex) {
            session = this.sessionFactory.openSession();
        }
    

    您必须确保在完成工作之后添加session.close(),并且在使用openSession() 代替getCurrentSession() 之后;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      • 2013-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多