SpringMVC4、Hibernate4整合過程中出現的問題

1.如果在數據層調用HibernateTemplate來實現數據的CRUD,會報如下錯誤:
HTTP Status 500 - Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Write operations are not allowed in read-only mode (FlushMode.MANUAL): 
Turn your Session into FlushMode.COMMIT/AUTO or remove 'readOnly' marker from transaction definition.
方1(不可行):在web.xml文件中配置如下:
    <filter>
    <filter-name>openSessionInViewerFilter</filter-name>
    <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
    <!-- <init-param>
      <param-name>singleSession</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>flushMode</param-name>
      <param-value>AUTO</param-value>
    </init-param> -->
  </filter>
  <filter-mapping>
    <filter-name>openSessionInViewerFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
           這是網上大部分的解決方法,通過查看源碼能看到對於Hibernate3可能是適用的,但是對於Hibernate4(我用的是4.0.8)是不適用的
方2:(可行)[有前提]
在數據層通過SessionFactory得到Session對象來實現CRUD,
引發的問題:update方法和 delete方法不起作用,控制檯也不報錯也不打印sql語句
解決方法:自己用SQL語句寫一下,不要直接調用session的update、delete方法,舉個例子:
                   1//this.getSession().delete(user);
                   2this.getSession().createQuery("delete from User where id=?").setParameter(0, id).executeUpdate();
                   把1句該爲2句就對了
                   原因:不太清楚,可能是Hibernate優化的原因吧,那天有時間看看源碼,再來補充


小小問題:浪費我如此長的時間,希望能幫助其他小夥伴。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章