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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
| /**
* XA数据访问对象基类
*/
public abstract class XABaseDAO {
protected final XATransactionManager transactionManager;
protected final String resourceId;
public XABaseDAO(XATransactionManager transactionManager, String resourceId) {
this.transactionManager = transactionManager;
this.resourceId = resourceId;
}
/**
* 执行更新操作
*/
protected int executeUpdate(String sql, Object... params) throws SQLException {
XATransactionId xid = XATransactionContext.getCurrentTransaction();
if (xid == null) {
throw new SQLException("当前没有活跃的XA事务");
}
return transactionManager.executeUpdate(xid, resourceId, sql, params);
}
/**
* 执行查询操作
*/
protected <T> T executeQuery(String sql, ResultSetExtractor<T> extractor, Object... params) throws SQLException {
XATransactionId xid = XATransactionContext.getCurrentTransaction();
if (xid == null) {
throw new SQLException("当前没有活跃的XA事务");
}
return transactionManager.executeQuery(xid, resourceId, sql, extractor, params);
}
/**
* 查询单个对象
*/
protected <T> T queryForObject(String sql, RowMapper<T> rowMapper, Object... params) throws SQLException {
return executeQuery(sql, rs -> {
if (rs.next()) {
return rowMapper.mapRow(rs, 1);
}
return null;
}, params);
}
/**
* 查询对象列表
*/
protected <T> List<T> queryForList(String sql, RowMapper<T> rowMapper, Object... params) throws SQLException {
return executeQuery(sql, rs -> {
List<T> list = new ArrayList<>();
int rowNum = 1;
while (rs.next()) {
list.add(rowMapper.mapRow(rs, rowNum++));
}
return list;
}, params);
}
/**
* 查询计数
*/
protected long queryForCount(String sql, Object... params) throws SQLException {
return executeQuery(sql, rs -> {
if (rs.next()) {
return rs.getLong(1);
}
return 0L;
}, params);
}
/**
* 确保分支事务已启动
*/
protected void ensureBranchStarted() throws SQLException {
XATransactionId xid = XATransactionContext.getCurrentTransaction();
if (xid != null) {
transactionManager.startBranch(xid, resourceId);
}
}
}
/**
* 行映射器接口
*/
@FunctionalInterface
interface RowMapper<T> {
T mapRow(ResultSet rs, int rowNum) throws SQLException;
}
/**
* 用户DAO示例
*/
public class UserXADAO extends XABaseDAO {
public UserXADAO(XATransactionManager transactionManager, String resourceId) {
super(transactionManager, resourceId);
}
public void createUser(User user) throws SQLException {
ensureBranchStarted();
String sql = "INSERT INTO users (id, username, email, created_at) VALUES (?, ?, ?, ?)";
executeUpdate(sql, user.getId(), user.getUsername(), user.getEmail(), user.getCreatedAt());
}
public User findById(Long id) throws SQLException {
String sql = "SELECT id, username, email, created_at FROM users WHERE id = ?";
return queryForObject(sql, this::mapUser, id);
}
public List<User> findByUsername(String username) throws SQLException {
String sql = "SELECT id, username, email, created_at FROM users WHERE username LIKE ?";
return queryForList(sql, this::mapUser, "%" + username + "%");
}
public void updateUser(User user) throws SQLException {
ensureBranchStarted();
String sql = "UPDATE users SET username = ?, email = ? WHERE id = ?";
executeUpdate(sql, user.getUsername(), user.getEmail(), user.getId());
}
public void deleteUser(Long id) throws SQLException {
ensureBranchStarted();
String sql = "DELETE FROM users WHERE id = ?";
executeUpdate(sql, id);
}
public long countUsers() throws SQLException {
String sql = "SELECT COUNT(*) FROM users";
return queryForCount(sql);
}
private User mapUser(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getLong("id"));
user.setUsername(rs.getString("username"));
user.setEmail(rs.getString("email"));
user.setCreatedAt(rs.getTimestamp("created_at"));
return user;
}
}
/**
* 订单DAO示例
*/
public class OrderXADAO extends XABaseDAO {
public OrderXADAO(XATransactionManager transactionManager, String resourceId) {
super(transactionManager, resourceId);
}
public void createOrder(Order order) throws SQLException {
ensureBranchStarted();
String sql = "INSERT INTO orders (id, user_id, total_amount, status, created_at) VALUES (?, ?, ?, ?, ?)";
executeUpdate(sql, order.getId(), order.getUserId(), order.getTotalAmount(),
order.getStatus(), order.getCreatedAt());
}
public Order findById(Long id) throws SQLException {
String sql = "SELECT id, user_id, total_amount, status, created_at FROM orders WHERE id = ?";
return queryForObject(sql, this::mapOrder, id);
}
public List<Order> findByUserId(Long userId) throws SQLException {
String sql = "SELECT id, user_id, total_amount, status, created_at FROM orders WHERE user_id = ?";
return queryForList(sql, this::mapOrder, userId);
}
public void updateOrderStatus(Long id, String status) throws SQLException {
ensureBranchStarted();
String sql = "UPDATE orders SET status = ? WHERE id = ?";
executeUpdate(sql, status, id);
}
private Order mapOrder(ResultSet rs, int rowNum) throws SQLException {
Order order = new Order();
order.setId(rs.getLong("id"));
order.setUserId(rs.getLong("user_id"));
order.setTotalAmount(rs.getBigDecimal("total_amount"));
order.setStatus(rs.getString("status"));
order.setCreatedAt(rs.getTimestamp("created_at"));
return order;
}
}
/**
* 用户实体
*/
class User {
private Long id;
private String username;
private String email;
private Timestamp createdAt;
// Constructors, getters and setters
public User() {}
public User(Long id, String username, String email) {
this.id = id;
this.username = username;
this.email = email;
this.createdAt = new Timestamp(System.currentTimeMillis());
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
public Timestamp getCreatedAt() { return createdAt; }
public void setCreatedAt(Timestamp createdAt) { this.createdAt = createdAt; }
@Override
public String toString() {
return String.format("User{id=%d, username='%s', email='%s'}", id, username, email);
}
}
/**
* 订单实体
*/
class Order {
private Long id;
private Long userId;
private BigDecimal totalAmount;
private String status;
private Timestamp createdAt;
// Constructors, getters and setters
public Order() {}
public Order(Long id, Long userId, BigDecimal totalAmount, String status) {
this.id = id;
this.userId = userId;
this.totalAmount = totalAmount;
this.status = status;
this.createdAt = new Timestamp(System.currentTimeMillis());
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public Long getUserId() { return userId; }
public void setUserId(Long userId) { this.userId = userId; }
public BigDecimal getTotalAmount() { return totalAmount; }
public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; }
public String getStatus() { return status; }
public void setStatus(String status) { this.status = status; }
public Timestamp getCreatedAt() { return createdAt; }
public void setCreatedAt(Timestamp createdAt) { this.createdAt = createdAt; }
@Override
public String toString() {
return String.format("Order{id=%d, userId=%d, amount=%s, status='%s'}",
id, userId, totalAmount, status);
}
}
|