/
JdbcTransaction.java
91 lines (79 loc) · 2.18 KB
/
JdbcTransaction.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
* Copyright © 2013-2020, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.seedstack.jdbc;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Savepoint;
/**
* Represents a JDBC transaction. In JDBC you can only have one connection per thread. If partial rollback are needed, we use the Savepoint object on
* the already known connection.
*/
public class JdbcTransaction {
private Connection connection;
private Savepoint savepoint;
private boolean rollbackOnly;
/**
* Constructor
*
* @param connection the jdbc connection
*/
public JdbcTransaction(Connection connection) {
this.connection = connection;
}
/**
* Constructor
*
* @param connection the jdbc connection
* @param savepoint the savepoint
*/
public JdbcTransaction(Connection connection, Savepoint savepoint) {
this.connection = connection;
this.savepoint = savepoint;
}
/**
* Commits the transaction, thus the underlying connection
*
* @throws SQLException when db error
*/
public void commit() throws SQLException {
connection.commit();
}
/**
* Rollbacks the transaction, thus the underlying connection
*
* @throws SQLException when db error
*/
public void rollBack() throws SQLException {
if (savepoint != null)
connection.rollback(savepoint);
else
connection.rollback();
}
/**
* If the transaction is marked as rollback only
*/
public void setRollbackOnly() {
this.rollbackOnly = true;
}
/**
* Whether the transaction is marked as rollback only or not
*
* @return is rollback only
*/
public boolean getRollbackOnly() {
return rollbackOnly;
}
/**
* Gets the connection of this transaction
*
* @return the connection
*/
public Connection getConnection() {
return connection;
}
}