java ssh开发常见问题总结

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的类或方法中有效。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值