java ssh开发常见问题总结

来源:互联网 发布:mac windows虚拟机 编辑:程序博客网 时间:2024/06/05 13:35

1.配置数据源 org.apache.tomcat.dbcp.dbcp2.BasicDataSource时可能会抛出异常,如果不是配置错误,原因可能是缺少包,只要引入tomcat-juli.jar问题就解决了

2.开启事务注解,
第一步:spring配置文件中添加以下代码

    <!-- 事物管理,统一管理sessionFactory的事物 -->    <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">        <property name="sessionFactory" ref="sessionFactory"></property>    </bean>    <!-- 启用事物注解 -->    <tx:annotation-driven transaction-manager="txManager" />

第二步:在需要事物代理的类或方法前加上注解

@Transactional(可选参数)

注意事项:1,如果启用了事物注解,必须使用getCurrentSession(),不能使用openSession(),前者用完会自动关闭,所以不能再加session.close(),否则会报如下错误

Exception in thread "main" org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction; nested exception is org.hibernate.TransactionException: commit failed
Caused by: org.hibernate.TransactionException: commit failed

原因是连接已自动关闭,connection为Null,再运行session.close()时会出错。

2,hibernate单独使用时,如果使用getCurrentSession,则配置文件中需把属性current_session_context_class设置为thread,但是hibernate和Spring整合并使用事物注解时,不能添加该属性,否则会抛出如下异常

Exception in thread "main" org.hibernate.HibernateException: save is not valid without active transaction
    at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)

原因可能是Spring获取的session与hibernate获取的session不是同一个,而他们又是在同一个线程,所以会出错。

3,@Transactional只有在修饰符声明为public的类或方法中有效。

0 0
原创粉丝点击