|
20 | 20 | import java.time.Instant; |
21 | 21 | import java.util.ArrayList; |
22 | 22 | import java.util.List; |
23 | | -import java.util.Optional; |
24 | 23 | import java.util.concurrent.atomic.AtomicLong; |
25 | 24 |
|
26 | 25 | import org.springframework.ai.chat.memory.ChatMemoryRepository; |
|
33 | 32 | import org.springframework.jdbc.core.BatchPreparedStatementSetter; |
34 | 33 | import org.springframework.jdbc.core.JdbcTemplate; |
35 | 34 | import org.springframework.jdbc.core.RowMapper; |
36 | | -import org.springframework.jdbc.datasource.DataSourceUtils; |
| 35 | +import org.springframework.jdbc.datasource.DataSourceTransactionManager; |
37 | 36 | import org.springframework.lang.Nullable; |
| 37 | +import org.springframework.transaction.support.TransactionTemplate; |
38 | 38 | import org.springframework.util.Assert; |
39 | 39 |
|
40 | 40 | /** |
@@ -83,30 +83,22 @@ public void saveAll(String conversationId, List<Message> messages) { |
83 | 83 | Assert.notNull(messages, "messages cannot be null"); |
84 | 84 | Assert.noNullElements(messages, "messages cannot contain null elements"); |
85 | 85 |
|
86 | | - Connection connection = null; |
87 | | - Assert.notNull(jdbcTemplate.getDataSource(), "jdbcTemplate.getDataSource() cannot be null"); |
88 | | - try { |
89 | | - connection = DataSourceUtils.getConnection(jdbcTemplate.getDataSource()); |
90 | | - connection.setAutoCommit(false); |
91 | | - this.deleteByConversationId(conversationId); |
92 | | - this.jdbcTemplate.batchUpdate(dialect.getInsertMessageSql(), |
93 | | - new AddBatchPreparedStatement(conversationId, messages)); |
94 | | - connection.commit(); |
95 | | - } |
96 | | - catch (SQLException ex) { |
| 86 | + Assert.notNull(jdbcTemplate.getDataSource(), "dataSource can not be null"); |
| 87 | + TransactionTemplate transactionTemplate = new TransactionTemplate( |
| 88 | + new DataSourceTransactionManager(jdbcTemplate.getDataSource())); |
| 89 | + |
| 90 | + transactionTemplate.execute(status -> { |
97 | 91 | try { |
98 | | - connection.rollback(); |
| 92 | + deleteByConversationId(conversationId); |
| 93 | + jdbcTemplate.batchUpdate(dialect.getInsertMessageSql(), |
| 94 | + new AddBatchPreparedStatement(conversationId, messages)); |
99 | 95 | } |
100 | | - catch (SQLException e) { |
101 | | - throw new RuntimeException("Transaction rollback exception", e); |
| 96 | + catch (RuntimeException e) { |
| 97 | + status.setRollbackOnly(); |
| 98 | + throw e; |
102 | 99 | } |
103 | | - throw new RuntimeException("save messages failed", ex); |
104 | | - } |
105 | | - finally { |
106 | | - Optional.ofNullable(connection) |
107 | | - .ifPresent(conn -> DataSourceUtils.releaseConnection(conn, jdbcTemplate.getDataSource())); |
108 | | - } |
109 | | - |
| 100 | + return null; |
| 101 | + }); |
110 | 102 | } |
111 | 103 |
|
112 | 104 | @Override |
|
0 commit comments