在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java  HTML/ Hibernate的HibernateTemplate

Hibernate的HibernateTemplate

在練習ssh框架整合時,實現(xiàn)一個功能:將一個本地的一個excel表格中的數(shù)據(jù)添加到數(shù)據(jù)庫中,并在頁面中顯示,結果出現(xiàn)一下報錯:
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.
百度上的解決方案是各種read-only="false",如下:

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <!-- 對連接點方法上要使用的事務屬性進行配置  即:使以下方法具有事務的屬性,可以根據(jù)需要使用-->
        <tx:method name="save" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
        <tx:method name="update" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
        <tx:method name="delete" isolation="DEFAULT" propagation="REQUIRED" read-only="false"/>
        <tx:method name="find*" isolation="DEFAULT" propagation="REQUIRED" rollback-for="BuyStockException"/>
    </tx:attributes>
</tx:advice>

@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW )
public interface BaseDao<T> {}

等等。。

可惜依舊報錯?,F(xiàn)求各位大佬解答。。。

hibernate版本:4.3.11

回答
編輯回答
情已空
關于這個問題,剛剛看書,書中的一句話點醒夢中人,這句話的大意是:所有方法都需要注冊事務屬性?。?!那重點來了,“所有方法”指的是什么? 
假如,你的Service層中有如下方法:
public class UserServiceImpl implements UserService {
    @Resource
    public void setUserDao(UserDao userDao) {}
    public UserDao getUserDao() {}
    public void save(User user) {}
    public void update(User user) {}
    public void delete(Serializable id) {}
    public User findObjectById(Serializable id) {}
    public List<User> findObjects() {}
    public void exportExcel(List<User> userList, ServletOutputStream outputStream) {}
    public void importExcel(File userExcel, String userExcelFileName) {
        for(User user : ImportExcelUtil.importExcel(userExcel,userExcelFileName)) {
            save(user);
        }
    }  
}

其中以save()為代表的增刪改查等方法,會對數(shù)據(jù)庫進行改動,所以要注冊事務,這毋庸置疑;
但是請注意importExcel()也是對數(shù)據(jù)庫進行操作的方法,只不過是調(diào)用了save()實現(xiàn)的;但是它也要注冊到事務中?。。。ㄖ攸c,請畫)
我就是沒有注冊importExcel(),所以運行報錯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.(好像在提問的時候沒說明這個情況,失誤。。。),注冊之后,一切順利。

所以,在這里在強調(diào)一下,所有,所有,所有Service層方法都要進行事務的注冊!
2017年9月15日 07:57