Skip to content

Commit 418171e

Browse files
committed
fix: Added transaction support for saveAll in JdbcChatMemoryRepository
Signed-off-by: Sun Yuhan <[email protected]>
1 parent 1ede664 commit 418171e

File tree

1 file changed

+28
-7
lines changed
  • memory/repository/spring-ai-model-chat-memory-repository-jdbc/src/main/java/org/springframework/ai/chat/memory/repository/jdbc

1 file changed

+28
-7
lines changed

memory/repository/spring-ai-model-chat-memory-repository-jdbc/src/main/java/org/springframework/ai/chat/memory/repository/jdbc/JdbcChatMemoryRepository.java

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,11 @@
1616

1717
package org.springframework.ai.chat.memory.repository.jdbc;
1818

19-
import java.sql.PreparedStatement;
20-
import java.sql.ResultSet;
21-
import java.sql.SQLException;
22-
import java.sql.Timestamp;
19+
import java.sql.*;
2320
import java.time.Instant;
2421
import java.util.ArrayList;
2522
import java.util.List;
23+
import java.util.Optional;
2624
import java.util.concurrent.atomic.AtomicLong;
2725

2826
import org.springframework.ai.chat.memory.ChatMemoryRepository;
@@ -35,6 +33,7 @@
3533
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
3634
import org.springframework.jdbc.core.JdbcTemplate;
3735
import org.springframework.jdbc.core.RowMapper;
36+
import org.springframework.jdbc.datasource.DataSourceUtils;
3837
import org.springframework.lang.Nullable;
3938
import org.springframework.util.Assert;
4039

@@ -83,9 +82,31 @@ public void saveAll(String conversationId, List<Message> messages) {
8382
Assert.hasText(conversationId, "conversationId cannot be null or empty");
8483
Assert.notNull(messages, "messages cannot be null");
8584
Assert.noNullElements(messages, "messages cannot contain null elements");
86-
this.deleteByConversationId(conversationId);
87-
this.jdbcTemplate.batchUpdate(dialect.getInsertMessageSql(),
88-
new AddBatchPreparedStatement(conversationId, messages));
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) {
97+
try {
98+
connection.rollback();
99+
}
100+
catch (SQLException e) {
101+
throw new RuntimeException("Transaction rollback exception", e);
102+
}
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+
89110
}
90111

91112
@Override

0 commit comments

Comments
 (0)