1,编程式事务管理(jdbc的事务是绑定在connection上的)
Connection conn = null
try
{
Class.forName("com.mysql.jdbc.Driver")
conn = DriverManager.getConnection("jdbc:oracle:thin:@host:1521:SID","username","password")
conn.setAutoCommit(false) //取消自动提交
PreparedStatement ps = conn.prepareCall("update something")
ResultSet rs = ps.executeQuery()
conn.commit() //手动提交
}
catch (Exception e)
{
conn.rollback()
e.printStackTrace()
}
finally
{
conn.close()
}
2,声明式事务
先在工程的application.xml配置文件中添加如下代码,开启事务
<!-- 声明式事务控制配置 -->
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="datasource" ref="bassDataSource"></property>
</bean>
然后在你需要开启事务的接口前面添加注解
@Transactional(rollbackFor = IOException.class)
public void add(String name) throws IOException
{
System.out.println("可以再类里和方法里面添加事务注解0~0")
throw new IOException()
}
直接调用接口方法就好
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)