-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAtomicUtil.java
53 lines (45 loc) · 1.47 KB
/
AtomicUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.coderevolt.util;
import com.coderevolt.connect.SqlConnectFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.function.Consumer;
public class AtomicUtil {
private static final Logger log = LoggerFactory.getLogger(AtomicUtil.class);
public static void txExecute(Consumer<Connection> consumer) throws SQLException {
Connection connection = null;
try {
connection = SqlConnectFactory.getConnection(SqlConnectFactory.getDefaultSourceName());
txExecute(connection, consumer);
} finally {
if (connection != null) {
connection.close();
}
}
}
/**
* 事务执行
*
* @param connection
* @param consumer
* @throws SQLException
*/
public static void txExecute(Connection connection, Consumer<Connection> consumer) throws SQLException {
Assert.isTrue(connection != null, "jdbc connection must not be null");
synchronized (connection) {
try {
connection.setAutoCommit(false);
consumer.accept(connection);
connection.commit();
} catch (Throwable e) {
log.error("transaction commit failed, will rollback", e);
connection.rollback();
throw e;
}
}
}
public String test() {
return null;
}
}