如何用java开启mysql事务,要求详细

在线等待
2024-12-02 08:46:05
推荐回答(3个)
回答1:

看你是什么事务,jdbc事务,还是分布式事务,还是容器事务

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配置文件中添加如下代码,开启事务







然后在你需要开启事务的接口前面添加注解
@Transactional(rollbackFor = IOException.class)
public void add(String name) throws IOException
{
System.out.println("可以再类里和方法里面添加事务注解0~0");
throw new IOException();
}
直接调用接口方法就好

分布式事务处理(mysql貌似在5.X之后才支持) 的话,
1.可以直接使用spring+atomikos框架进行管理
参考:http://blog.chinaunix.net/uid-21162795-id-3424973.html
就不贴测试代码了,自己看着配置吧

2,使用JTA(Java Transaction API)进行分布式事务管理(测试代码如下)
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.sql.DataSource;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

//分布式事务处理
public class transferAccount
{
@SuppressWarnings("null")
public void testTransferAccount()
{
UserTransaction userts = null;
Connection connA = null;
PreparedStatement psA = null;
InitialContext context = null;
Connection connB = null;
PreparedStatement psB = null;

try
{
//获得事务管理对象
userts = (UserTransaction) context.lookup("java:comp/UserTransaction");
//获取两个数据库
connA = getDataSourceA().getConnection();
connB = getDataSourceB().getConnection();
//开启事务
userts.begin();
//sql语句
psA = connA.prepareStatement("我加1");
psB = connB.prepareStatement("我减1");
//执行sql
psA.executeUpdate();
psB.executeUpdate();
//事务提交
userts.commit();

} catch (Exception e)
{
try
{
userts.rollback();
} catch (IllegalStateException | SecurityException
| SystemException e1)
{
e1.printStackTrace();
}
e.printStackTrace();
}
finally
{
try
{
psA.close();
psB.close();
connA.close();
connB.close();
} catch (SQLException e)
{
e.printStackTrace();
}
}
}

public DataSource getDataSourceA()
{
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setDatabaseName("mysql");
dataSource.setServerName("server");
dataSource.setPortNumber(1433);
dataSource.setUser("test");
dataSource.setPassword("test");
return dataSource;
}

public DataSource getDataSourceB()
{
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setDatabaseName("mysql");
dataSource.setServerName("server");
dataSource.setPortNumber(1435);
dataSource.setUser("test1");
dataSource.setPassword("test1");
return dataSource;
}
}

回答2:

java.sql.*里面的Connection可以开始事务

回答3:

ttsbegin ttscommit