您的位置:首页 > 编程语言 > Java开发

spring事务处理相关,整合mybatis的系统如何单独做事务控制

2017-05-22 00:00 441 查看
需求:系统有一个地方需要单独做事务控制,可以使用的方式这里记录一下。

第一种方式:使用 @Transactional 注解

配置文件里面要配置该注解相关:

<!-- 定义一个数据源 -->
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/spring_test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>

<!-- 定义JdbcTemplate的Bean -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource">
</bean>

<!-- 配置事务管理器 -->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource">
</bean>

<!-- enables scanning for @Transactional annotations -->
<tx:annotation-driven transaction-manager="txManager" />

<!-- 在该Bean的代码中标注@Transactional可以被事务管理器注入 -->
<bean id="userScore"
class="net.hingyi.springDemo.transaction.service.UserScoreServiceImpl"
p:userScoreRepository-ref="userScoreRepository_jdbc" />

<bean id="userScoreRepository_jdbc"
class="net.hingyi.springDemo.transaction.repository.UserScoreRepositoryImpl"
p:jdbcTemplate-ref="jdbcTemplate" />

使用:直接用该注解即可使用

@Transactional
public class UserScoreRepositoryImpl {

private JdbcTemplate jdbcTemplate;

@Override
public UserScore getUserSocore(String userNo) {

final UserScore us = new UserScore();
...
return us;
}
...

}

具体的可以参数 https://my.oschina.net/guanzhenxing/blog/214228 的文章。

第二种:在事务切面表达式那里入手

<aop:config>
<aop:aspect ref="dynamicDataSourceAspect">
<aop:pointcut id="backMethod"
expression="execution(public * com.yundaex..CompleteInboundNoticeBackToQimenDaoImpl.query*(..))
|| execution(public * com.yundaex.wms..InventoryCountReportToQimenDaoImpl.query*(..))
|| execution(public * com.yundaex.wms..OrderProcessReportToQimenDaoImpl.query*(..))
|| execution(public * com.yundaex.wms..OutboundNoticeConfirmBackToQimenDaoImpl.query*(..))
|| execution(public * com.yundaex.wms..ReturnOrderBackToQimenDaoImpl.query*(..))
|| execution(public * com.yundaex.wms..StockChangeReportToQimenDaoImpl.query*(..)) "/>
<aop:around method="aroundMethod"  pointcut-ref="backMethod"/>
</aop:aspect>
</aop:config>

如上的写法,可以配置多个切面表达式

第三种:在spring中注入并且获取session

class A{
@Autowired
private SqlSessionFactory sqlSessionFactory;

......
}


SqlSession sqlSession = sqlSessionFactory.openSession();

如上,即可在方法中做事务控制

第四种:spring如果没有生效的情况下使用:

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
* spring 上下文获取 有时候需要在代码中直接获取spring bean,就可能通过这种方式
*/
public class SpringContextUtil implements ApplicationContextAware {

private static ApplicationContext context;

public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.context = applicationContext;
}

/**
* 根据bean的name来获取bean
*
* @param beanName
* @return
*/
public static Object getBean(String beanName) {
return context.getBean(beanName);
}

/**
* 获取spring上下文
*
* @return
*/
public static ApplicationContext getContext() {
return context;
}

}

SqlSessionFactory sqlSessionFactory =SpringContextUtil.getContext().getBean(SqlSessionFactory.class);
//SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) SpringContextUtil.getBean("sqlSessionFactory");
SqlSession sqlSession = sqlSessionFactory.openSession();//打开事务
try {
。。。。。。。。。。。。。。。。。。。
sqlSession.commit();
} catch (BaseException | Exception e) {
e.printStackTrace();
sqlSession.rollback(); //回滚事务
} finally {
sqlSession.close();
}

所有的一切,事务都要注意关闭事务

附录:

import java.sql.Connection;

import java.sql.DriverManager;
import java.sql.Statement;
public class RunInsert {
/**

* @param args

*/

public static void main(String[] args) {

Connection conn = null;

Statement stmt = null;

try {

// 动态导入数据库的驱动

Class.forName("com.mysql.jdbc.Driver");

// 获取数据库链接

conn = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/jdbc_teaching", "root", "");

// 开启事务

conn.setAutoCommit( false );

// 创造SQL语句

String sql = "INSERT INTO user_list ( user_name, user_password ) VALUES ( 'Eric', '123' )";

// 执行SQL语句

stmt = conn.createStatement();

stmt.executeUpdate(sql);

// 提交事务

conn.commit();

System.out.println( "OK!" );

} catch (Exception e) {

e.printStackTrace();

// 回滚事务

try {

conn.rollback();

} catch ( Exception e2 ) {}

} finally {

// 关闭Statement

try {

stmt.close();

} catch (Exception e) {}

// 关闭Connection

try {

conn.close();

} catch (Exception e) {}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring