|
@@ -0,0 +1,42 @@
|
|
|
|
+package org.example;
|
|
|
|
+
|
|
|
|
+import org.springframework.jdbc.core.JdbcTemplate;
|
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
|
+import org.springframework.stereotype.Service;
|
|
|
|
+
|
|
|
|
+import javax.transaction.Transactional;
|
|
|
|
+
|
|
|
|
+@Service
|
|
|
|
+public class TestService {
|
|
|
|
+
|
|
|
|
+ private JdbcTemplate primaryJdbcTemplate;
|
|
|
|
+ private JdbcTemplate secondaryJdbcTemplate;
|
|
|
|
+ public TestService(JdbcTemplate primaryJdbcTemplate, JdbcTemplate secondaryJdbcTemplate) {
|
|
|
|
+ this.primaryJdbcTemplate = primaryJdbcTemplate;
|
|
|
|
+ this.secondaryJdbcTemplate = secondaryJdbcTemplate;
|
|
|
|
+ }
|
|
|
|
+ @Transactional
|
|
|
|
+ public void tx() {
|
|
|
|
+// String sql="insert into User values(?,?)";
|
|
|
|
+// Object[] args= {30, "aaa"};
|
|
|
|
+// int update = primaryJdbcTemplate.update(sql, args);
|
|
|
|
+// int update2 = secondaryJdbcTemplate.update(sql, args);
|
|
|
|
+// System.out.println(update);
|
|
|
|
+// System.out.println(update2);
|
|
|
|
+ // 修改test1库中的数据
|
|
|
|
+ primaryJdbcTemplate.update("update user set age = ? where name = ?", 30, "aaa");
|
|
|
|
+ // 修改test2库中的数据
|
|
|
|
+ secondaryJdbcTemplate.update("update user set age = ? where name = ?", 30, "aaa");
|
|
|
|
+ }
|
|
|
|
+ @Transactional
|
|
|
|
+ public void tx2() {
|
|
|
|
+ // 修改test1库中的数据
|
|
|
|
+// String sql="insert into User values(?,?)";
|
|
|
|
+// Object[] args= {"aaa", 30};
|
|
|
|
+// int update = primaryJdbcTemplate.update(sql, args);
|
|
|
|
+// System.out.println(update);
|
|
|
|
+ primaryJdbcTemplate.update("update user set age = ? where name = ?", 40, "aaa");
|
|
|
|
+ // 模拟:修改test2库之前抛出异常
|
|
|
|
+ throw new RuntimeException();
|
|
|
|
+ }
|
|
|
|
+}
|