问题一:

SSH整合, Hibernate正确执行了save方法,但是数据没有保存到数据库

 1、Srping的配置文件里的Hibernate的属性配置必须加上

        <prop key="hibernate.connection.autocommit">true</prop>   如下图:

   SSH项目中save,delete,update无效解决方法

 2、Spring配置文件里加上模型驱动

    <tx:annotation-driven transaction-manager="transactionManager"/> 


 3、 在Service的实现类上添加事务注释@Transactional,如下:
@Transactional

public classUserServiceImplimplements UserService {}


 4、在DAO中获取session的时候应该采用sessionFactory.getCurrentSession();不能采用

    sessionFactory.openSession();,否则事务不能自动提交,同时session也不能自动关闭。

sessionFactory.getCurrentSession();和sessionFactory.openSession();的区别请看此博文:

问题二:

 

save()方法添加数据了,可是delete()和Update()方法总是没有效果

 原因:session是个一级缓存,当你save的时候,不会存放在缓存中,直接添加到数据库!
update和delete时,会先将session缓存的数据删除,然后提交到数据库,但是你这个时候
已经将session关闭了!要加session.flush() 
解决办法一:

 在delete()和update()方法后面加入flush()即可

  public void delete(Long id) {
    Object obj = findById(id);
    if(obj!=null)
    getSession().delete(obj);
    getSession().flush();
    }

   public void update(T entity) {
     getSession().update(entity);
     getSession().flush();

   }

 解决办法二:
 使用事务管理@Transactional












 

相关文章:

  • 2021-07-30
  • 2021-09-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-24
  • 2022-01-18
  • 2021-06-18
猜你喜欢
  • 2021-11-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-26
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案