使用了mybatis后,比如有相关的增删改,这些都是与事务相关的,但是使用mybatis,就是一个接口,接口对应的配置文件,service再去调用这个接口,增删改都是与事务有关,怎么体现事务呢?我觉得我在写程序的过程中好像没有用到事务, 求解
一般使用Mybaits也就这么几种情况。
(1)单独使用Mybatis不与Spring集成,那么应该这么使用,最原始的方式。
[code="java"] //这里要传false 手动事务
SqlSession session = sqlSessionFactory.openSession(false);
try {
//插入A表
//修改B表
session.commit();
} catch (Exception e) {
session.rollback();
} finally {
session.close();
}[/code]
(2)与Spring集成使用,但是没有将事务托管给Spring,一般都是使用SqlSessionTemplate这个类,这种情况在Mybatis执行增删改查以后Mybatis会自动提交事务,关闭session。
[code="java"]
private class SqlSessionInterceptor implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
final SqlSession sqlSession = getSqlSession(
SqlSessionTemplate.this.sqlSessionFactory,
SqlSessionTemplate.this.executorType,
SqlSessionTemplate.this.exceptionTranslator);
try {
Object result = method.invoke(sqlSession, args);
if (!isSqlSessionTransactional(sqlSession, SqlSessionTemplate.this.sqlSessionFactory)) {
// force commit even on non-dirty sessions because some databases require
// a commit/rollback before calling close()
sqlSession.commit(true);
}
return result;
} catch (Throwable t) {
Throwable unwrapped = unwrapThrowable(t);
if (SqlSessionTemplate.this.exceptionTranslator != null && unwrapped instanceof PersistenceException) {
Throwable translated = SqlSessionTemplate.this.exceptionTranslator.translateExceptionIfPossible((PersistenceException) unwrapped);
if (translated != null) {
unwrapped = translated;
}
}
throw unwrapped;
} finally {
closeSqlSession(sqlSession, SqlSessionTemplate.this.sqlSessionFactory);
}
}
}
[/code]
(3)与Spring集成使用,并且使用了Spring的事物上下文,那么事物会由Spring管理,这与hibernate与Spring集成的事物没有区别,Spring会管理事物。
[code="java"]
1.首先要看你的spring 配置文件里面,有没有配置事务管理方式
比如
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="interceptorPointCuts"
expression="execution(* com.bluesky.spring.dao.*.*(..))" />
<aop:advisor advice-ref="txAdvice"
pointcut-ref="interceptorPointCuts" />
</aop:config>
这种对整个service或者dao自动aop方式加入事务,或者具体的某个以insert*,update*,delete*等开头的方法配置事务
2.在需要加事务的地方通过注解配置
@Transactional
public void saveUser(..)
类似这样的注解的
现在事务配置更倾向于非侵入式的。
[/code]
一般使用Mybaits也就这么几种情况。
(1)单独使用Mybatis不与Spring集成,那么应该这么使用,最原始的方式。
[code="java"]
//注意这里获取session的时候要传参数 false 需要手动事务的意思.
SqlSession session = sqlSessionFactory.openSession(false);
try {
//插入A表
//修改B表
session.commit();
} catch (Exception e) {
session.rollback();
} finally {
session.close();
}
[/code]