Persistent Chat Memory in Spring AI with JDBC (H2, MySQL, Postgres)

  • Last Updated:
  • By: javahandson
  • Series
img

Persistent Chat Memory in Spring AI with JDBC (H2, MySQL, Postgres)

Add persistent chat memory in Spring AI with JdbcChatMemoryRepository. Save chat history to H2, MySQL or Postgres — verified against Spring AI 2.0.1.

1. Introduction

Most chat memory demos store messages in RAM and call it done. That works fine until you restart the app. Then every past conversation is gone. So in this guide, we will build persistent chat memory in Spring AI, step by step, and keep our history safe in a real database.

In the previous article, we looked at ChatMemory, MessageWindowChatMemory, and memory advisors. We used the default in-memory store there. Now we take the next step. We will swap that store for JdbcChatMemoryRepository and save messages in H2, MySQL, and Postgres.

This article builds on those basics. If ChatMemory is new to you, read the linked memory article first. Here, our focus stays on storage. In short, we make the memory last.

By the end of this guide, you will know:

  • why in-memory chat memory is risky for real apps
  • what JdbcChatMemoryRepository does under the hood
  • how to set up persistent memory with H2 in a few minutes
  • how to switch the same code to MySQL or Postgres
  • how Spring AI picks the right SQL dialect for your database
  • the small traps that trip up most beginners

I have kept the language simple throughout. Let us get started.

2. Why In-Memory Chat Memory Is Not Enough

Let me begin with a fair question. The default memory already works, so why change it at all?

The short answer is that the default store lives only in RAM. It is quick and needs zero setup. However, it forgets everything the moment your app stops. For a demo, that is fine. For a real product, it is a problem. Here are the three pain points I hit most often.

2.1 The Restart Problem

The default store is InMemoryChatMemoryRepository. It keeps messages inside a simple map in memory. As a result, a restart wipes the whole map clean.

Think about a normal deploy. You push new code, the app restarts, and every user loses their chat history. That feels broken to the user. A database fixes this because the data sits on disk, not in RAM.

2.2 Many Instances, One Truth

Real apps rarely run on a single server. Instead, you run two or three copies behind a load balancer. Now imagine each copy holds its own in-memory map.

A user sends message one, and server A remembers it. Then the next message lands on server B, which knows nothing. So the bot suddenly forgets the chat. A shared database gives all servers one common memory.

2.3 History That Actually Lasts

Sometimes you want chat history to live for days or weeks. For example, a support bot may need last month’s conversation. In-memory storage cannot do that safely.

With a database, you decide how long to keep data. Moreover, you can query it, back it up, and audit it later. These are basic needs in most serious systems.

2.4 In-Memory vs JDBC at a Glance

Here is a quick side-by-side to make the choice clear:

  • Setup: in-memory needs nothing, while JDBC needs a datasource and a driver.
  • Restart: in-memory loses data, while JDBC keeps it on disk.
  • Many servers: in-memory splits memory, while JDBC shares one table.
  • Best for: in-memory suits demos, while JDBC suits real products.

So the trade-off is simple. You spend a little setup time and gain durable memory. For most real apps, that deal is easy to accept.

3. A Quick Recap of Spring AI Chat Memory

Before the JDBC part, let us refresh a few building blocks. We covered these in detail earlier, so this is just a short reminder.

3.1 ChatMemory vs ChatMemoryRepository

These two names sound similar, but they do different jobs.

  • ChatMemory decides the policy. It answers what to keep, such as the last N messages.
  • ChatMemoryRepository decides the storage. It answers where the messages go, such as RAM or a database.

So the policy and the storage stay separate. That split is the key idea. Because of it, you can keep the same policy and change only the storage to JDBC.

3.2 MessageWindowChatMemory and conversationId

MessageWindowChatMemory is the default ChatMemory in Spring AI. It keeps a sliding window of recent messages. By default, it holds up to 20 messages and always preserves system messages.

Each conversation needs its own key. That key is the conversationId. You pass it with every call, usually a username or a session id. Spring AI then stores and loads messages per conversationId. In short, one id means one private chat thread.

3.3 The Memory Advisor

One more piece links memory to the ChatClient. That piece is MessageChatMemoryAdvisor. It loads past messages before the call and saves new ones after. So you never touch the repository directly in your controller.

There was also a PromptChatMemoryAdvisor in older versions. It was removed in Spring AI 2.0. If you spot it in an old tutorial, use MessageChatMemoryAdvisor instead.

💡 Interview Insight
Interviewers often ask the difference between ChatMemory and ChatMemoryRepository. Keep it crisp. ChatMemory is the policy, which decides what and how much to remember. ChatMemoryRepository is the backend, which decides where it is stored. Swapping in-memory for JDBC changes only the repository, not the policy.

4. Meet JdbcChatMemoryRepository

JdbcChatMemoryRepository is a built-in implementation of ChatMemoryRepository. It uses plain JDBC to store messages in a relational database. Therefore, it fits any app that already speaks SQL.

4.1 One Table, Many Databases

All messages go into a single table named SPRING_AI_CHAT_MEMORY. Each row holds one message with its conversation id, content, type, and a timestamp. Spring AI handles the reading and writing for you.

The best part is the database support. JdbcChatMemoryRepository works out of the box with many databases, including:

  • H2 (great for local testing)
  • MySQL and MariaDB
  • PostgreSQL
  • SQL Server
  • HSQLDB
  • Oracle Database

So you can start on H2 today and move to Postgres later. Notably, your Java code stays almost the same across all of them.

4.2 How It Fits the Flow

The repository sits behind the memory advisor. When a request comes in, the advisor loads past messages from the table. Next, it adds them to the prompt. After the model replies, the advisor saves the new messages back. The whole cycle happens for you.

Flow diagram of persistent chat memory in Spring AI, showing a user message going to the ChatClient, the MessageChatMemoryAdvisor loading past messages from JdbcChatMemoryRepository and the SPRING_AI_CHAT_MEMORY table, the full history plus the new message going to the LLM, and the reply being saved back to the database.

4.3 What Gets Stored

Each row maps to one message in the chat. The main values are the conversation id, the message content, and the message type. The type tells user messages apart from assistant messages.

There is one gap worth knowing early. Tool-call messages are not saved by this repository. We will cover that fully in the pitfalls section. For now, just remember that normal chat messages are stored, while tool steps are skipped.

5. Setting Up JDBC Chat Memory with H2

Let us build a working example now. We will start with H2 because it needs no separate install. The same setup moves to MySQL or Postgres with tiny changes, as you will see soon.

5.1 Add the Dependencies

First, add the JDBC chat memory starter and the H2 driver in your pom.xml. I assume the Spring AI BOM and a model starter are already in place from the earlier articles.

<!-- JDBC chat memory support -->
<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-chat-memory-repository-jdbc</artifactId>
</dependency>
 
<!-- H2 database driver -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

One quick note from my side. You may see an old artifact called spring-boot-h2console in some tutorials. That artifact does not exist. To open the H2 web console, you just set a property, which we add in the next step.

5.2 Configure the H2 Database

Next, add the datasource settings in application.properties. We will use a file-based H2 database so the data survives restarts.

# H2 file-based database
spring.datasource.url=jdbc:h2:file:~/chatmemory;AUTO_SERVER=true
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
 
# Open the H2 web console at /h2-console
spring.h2.console.enabled=true
 
# Let Spring AI create the chat memory table
spring.ai.chat.memory.repository.jdbc.initialize-schema=always

A few points are worth calling out here:

  • The file: URL stores data on disk, so a restart keeps your history.
  • AUTO_SERVER=true lets the console and the app share the same file.
  • The initialize-schema property tells Spring AI to create the table for you.

5.3 Wire the ChatMemory and Advisor

Now we connect the pieces in a small config class. We take the auto-configured JdbcChatMemoryRepository and wrap it in MessageWindowChatMemory. Then we attach the memory advisor to the ChatClient.

@Configuration
public class ChatMemoryConfig {
 
    // Build a windowed memory backed by the JDBC repository
    @Bean
    ChatMemory jdbcChatMemory(JdbcChatMemoryRepository chatMemoryRepository) {
        return MessageWindowChatMemory.builder()
                .chatMemoryRepository(chatMemoryRepository)
                .maxMessages(10)
                .build();
    }
 
    // Attach the memory advisor to the ChatClient
    @Bean
    ChatClient chatClient(ChatClient.Builder builder, ChatMemory chatMemory) {
        return builder
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())
                .build();
    }
}

The flow here is simple. Spring AI auto-configures the JdbcChatMemoryRepository because the starter is on the classpath. We inject it, set a window of ten messages, and hand it to the advisor. From now on, every call reads and writes memory through JDBC.

5.4 Create the Controller

Let us expose a small endpoint to test the memory. We pass the username as the conversationId, so each user gets a separate thread.

@RestController
@RequestMapping("/api")
public class ChatMemoryController {
 
    private final ChatClient chatClient;
 
    public ChatMemoryController(ChatClient chatClient) {
        this.chatClient = chatClient;
    }
 
    @GetMapping("/chat-memory")
    public ResponseEntity<String> chatMemory(
            @RequestHeader("username") String username,
            @RequestParam("message") String message) {
 
        String conversationId = username;
        String answer = chatClient.prompt()
                .user(message)
                .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, conversationId))
                .call()
                .content();
 
        return ResponseEntity.ok(answer);
    }
}

Notice the conversationId param on the advisor. It ties every message to one user. Without it, Spring AI 2.0 throws an error, which we will discuss later.

5.5 Test It and Peek at the Data

Run the app and send two calls with the same username. The second call should use the context from the first.

curl -H "username: suraj" \
  "http://localhost:8080/api/chat-memory?message=My+name+is+Suraj"
 
curl -H "username: suraj" \
  "http://localhost:8080/api/chat-memory?message=What+is+my+name"

If the bot answers with your name, the memory works. Now open the H2 console at http://localhost:8080/h2-console. Use the same JDBC URL from your properties. Then run a quick query to see the stored rows.

SELECT * FROM SPRING_AI_CHAT_MEMORY ORDER BY "timestamp";

You should see your messages saved as rows. That confirms the data is on disk and not just in RAM. Next, try a third call with a different username. You will get a fresh thread with no memory of Suraj. That proves the conversationId keeps users apart.

6. Understanding Schema Initialization

The initialize-schema property does a lot of quiet work. So let us slow down and understand it. This single setting decides whether Spring AI creates the table for you.

6.1 The Three Values

The property spring.ai.chat.memory.repository.jdbc.initialize-schema takes three values:

  • embedded is the default. It creates the table only for embedded databases like H2 or HSQLDB.
  • always creates the table on every startup, for any database. It is handy during development.
  • never skips creation entirely. You own the schema, often through Flyway or Liquibase.

So for H2, the default already works because H2 is embedded. For MySQL or Postgres, you must set always or create the table yourself. We will return to this choice in the best-practices section.

6.2 Where the Schema Script Lives

Spring AI ships SQL scripts for each database. It picks the right one using a platform placeholder. The default location is shown below.

classpath:org/springframework/ai/chat/memory/repository/jdbc/schema-@@platform@@.sql

The @@platform@@ part becomes mysql, postgresql, h2, and so on. Spring AI detects the platform from your datasource. Still, you can override both values when needed:

# Force a platform if detection is wrong
spring.ai.chat.memory.repository.jdbc.platform=postgresql
 
# Point to your own schema script
spring.ai.chat.memory.repository.jdbc.schema=classpath:/custom/schema-postgresql.sql

6.3 What the Table Holds

The SPRING_AI_CHAT_MEMORY table is small and clear. It stores the conversation id, the message content, the message type, and a timestamp. In Spring AI 2.0, the schema also adds a sequence column to keep messages in the exact order they arrived.

That ordering matters for busy chats. Two messages can share the same timestamp down to the millisecond. The sequence value then breaks such ties cleanly.

6.4 H2 File Mode vs In-Memory Mode

H2 can run in two modes. The in-memory mode uses a URL like jdbc:h2:mem:testdb. It is fast, yet it still clears on restart. So it does not solve our main problem.

The file mode uses jdbc:h2:file:~/chatmemory instead. It writes to a file on disk. As a result, your chat history survives restarts. For persistent memory, always pick the file mode.

💡 Interview Insight
A common question is why embedded is the default instead of always. The reason is safety. Auto-creating tables on a shared production database can clash with migration tools. So Spring AI only auto-creates for embedded databases by default, and it leaves real databases to you.

7. Switching to MySQL

H2 is great for testing. For production, though, many teams prefer MySQL. The good news is that the move is mostly a config change.

7.1 Swap the Driver

Replace the H2 driver with the MySQL driver in your pom.xml. Keep the chat memory starter as it is.

<!-- MySQL driver (use the new artifactId) -->
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
</dependency>

Please use mysql-connector-j, not the old mysql-connector-java. The old artifact is deprecated now.

7.2 Point to MySQL

Now update the datasource in application.properties. Since MySQL is not embedded, set initialize-schema to always for local runs.

spring.datasource.url=jdbc:mysql://localhost:3306/spring_ai
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
 
# MySQL is not embedded, so ask Spring AI to create the table
spring.ai.chat.memory.repository.jdbc.initialize-schema=always

Create the database first with a simple command. After that, start the app and the table appears on its own.

CREATE DATABASE IF NOT EXISTS spring_ai;

You may also want to watch the SQL during setup. A quick way is to raise the log level for the JDBC package. That helps you confirm the inserts and selects.

logging.level.org.springframework.jdbc=DEBUG

Everything else stays the same. Your config class, controller, and advisor do not change at all. That is the real benefit of the repository abstraction.

8. Switching to PostgreSQL

Postgres follows the same pattern. Only the driver and the datasource URL change.

8.1 Add the Postgres Driver

<!-- PostgreSQL driver -->
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <scope>runtime</scope>
</dependency>

8.2 Point to Postgres

spring.datasource.url=jdbc:postgresql://localhost:5432/spring_ai
spring.datasource.username=postgres
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=org.postgresql.Driver
 
spring.ai.chat.memory.repository.jdbc.initialize-schema=always

Start a Postgres database, run the app, and you are done. The same SPRING_AI_CHAT_MEMORY table shows up, this time in Postgres. So moving across H2, MySQL, and Postgres is really a driver-and-URL job.

In cloud setups, your Postgres often sits behind a managed service. The URL and credentials then come from environment variables. So keep them out of your properties file and out of Git.

9. How Spring AI Picks the Right Dialect

You might wonder how one repository handles so many databases. The answer is the dialect abstraction. A dialect holds the correct SQL for each database.

9.1 Auto-Detection From the URL

By default, Spring AI reads your JDBC URL and chooses the dialect for you. A URL with mysql picks the MySQL dialect. A URL with postgresql picks the Postgres one. So most of the time, you do nothing extra.

9.2 Setting the Dialect Yourself

Sometimes auto-detection fails, often behind a proxy or a custom URL. In that case, you can build the repository by hand and pass the dialect directly.

@Bean
JdbcChatMemoryRepository jdbcChatMemoryRepository(JdbcTemplate jdbcTemplate) {
    return JdbcChatMemoryRepository.builder()
            .jdbcTemplate(jdbcTemplate)
            .dialect(new PostgresChatMemoryRepositoryDialect())
            .build();
}

You can also detect the dialect from the datasource and then check it. This helps when you want to fail fast on a wrong database.

JdbcChatMemoryRepositoryDialect dialect =
        JdbcChatMemoryRepositoryDialect.from(dataSource);

For MySQL, use MysqlChatMemoryRepositoryDialect instead. The idea stays the same across databases. Only the dialect class changes.

9.3 Custom Dialects for Other Databases

What if your database is not on the built-in list? Then you can write your own dialect. You implement the dialect interface and supply the SQL for insert, select, and delete. After that, you pass it to the builder, just like the built-in ones.

Most teams never need this. Still, it is good to know the door is open. The design keeps Spring AI flexible without forcing you to fork the framework.

💡 Interview Insight
If asked how one repository supports many databases, mention the dialect abstraction. Each dialect carries the right SQL for that database. Spring AI auto-detects it from the JDBC URL, and you can override it with a builder when detection fails.

10. Things to Watch Out For

Persistent memory is powerful, yet a few details bite beginners. Let me share the ones I have seen most.

10.1 Tool-Call Messages Are Not Saved

This one surprises many developers. JdbcChatMemoryRepository does not store tool-call messages. It silently skips assistant messages that contain tool calls and their tool responses.

So if your app uses tool calling, do not expect those steps in the table. Plain user and assistant messages are saved normally. Keep this in mind while debugging missing rows.

10.2 Do Not Use always in Production

The always value is tempting because it just works. However, it runs the schema script on every startup. On a shared production database, that can clash with your migration tools.

For production, I prefer initialize-schema=never. Then I manage the table with Flyway or Liquibase. That way, the database team stays in control. Also, deployments become predictable.

10.3 Mind the Context Window

A database can hold thousands of messages per user. Still, the model has a limited context window. So you cannot send the entire history every time.

This is why MessageWindowChatMemory keeps only the recent messages. Tune maxMessages to match your model and your cost budget. For very long chats, a vector-store memory is a better fit, since it fetches only the relevant parts.

10.4 conversationId Is Required

In Spring AI 2.0, the conversationId is mandatory. If you forget to pass it, the call fails with an error. Earlier versions had a default id, but that default is gone now.

So always set the id on the advisor param. A username, a session id, or a chat id all work well. Just keep it stable for the same thread.

10.5 Other Practical Tips

  • Use a connection pool. Chat apps make many small queries, and pooling keeps them fast.
  • Avoid storing secrets in the chat. The messages sit in plain text in the table.
  • Index the conversation id. The built-in schema already does this for you.
  • Back up the table like any other business data.
💡 Interview Insight
A likely follow-up is how to make JDBC memory production-ready. Cover four points. Set initialize-schema to never and use Flyway. Add a connection pool for speed. Cap history with maxMessages to respect the context window. Finally, remember that tool-call messages are not persisted.

11. FAQ’s on persistent chat memory in Spring AI

Q: What is JdbcChatMemoryRepository in Spring AI?

A: It is a built-in ChatMemoryRepository that stores chat history in a relational database using plain JDBC. It saves every message in a table named SPRING_AI_CHAT_MEMORY, so your conversations survive app restarts and work across many servers.

Q: Which databases does Spring AI JDBC chat memory support?

A: It works out of the box with H2, MySQL, MariaDB, PostgreSQL, SQL Server, HSQLDB, and Oracle. Spring AI picks the right SQL dialect from your JDBC URL, so the same code moves across these databases with only a driver and URL change.

Q: What does the initialize-schema property do?

A: The property spring.ai.chat.memory.repository.jdbc.initialize-schema controls table creation. It takes three values: embedded (the default, which creates the table only for embedded databases like H2), always (creates it on every startup), and never (you own the schema, usually through Flyway or Liquibase).

Q: Do I need to set initialize-schema for H2?

A: Not strictly. H2 is an embedded database, so the default embedded value already creates the table for you. Many tutorials still set it to always to be explicit. For MySQL or Postgres, though, you must use always or create the table yourself.

Q: Why is my tool-call history missing from the table?

A: This is expected. JdbcChatMemoryRepository silently skips assistant messages that contain tool calls, along with their tool responses. Plain user and assistant messages are saved normally, but tool-calling steps are not persisted.

Q: Is the conversationId required in Spring AI 2.0?

A: Yes. In Spring AI 2.0 the conversationId is mandatory, and a missing id throws an error. Older versions had a default id, but that default was removed. Pass a stable value such as a username or session id on the advisor param with every call.

Q: How do I make JDBC chat memory production-ready?

A: Set initialize-schema to never and manage the table with Flyway or Liquibase. Add a connection pool for speed, cap history with maxMessages to respect the model’s context window, and remember that tool-call messages are not stored. Also back up the table like any other business data.

12. Conclusion

Persistent chat memory in Spring AI turns a forgetful demo into a real assistant. With JdbcChatMemoryRepository, your chat history survives restarts and works across many servers. Best of all, the setup is short.

Here is a quick recap of the steps:

  • Add the JDBC chat memory starter and a database driver.
  • Configure the datasource and the initialize-schema property.
  • Wrap JdbcChatMemoryRepository in MessageWindowChatMemory.
  • Attach MessageChatMemoryAdvisor to the ChatClient.
  • Pass a stable conversationId with every call.

Start with H2 on your machine. Then move to MySQL or Postgres for production, where only the driver and URL change. That small effort gives your AI a memory that truly lasts.

One last thought from my side. Memory is only one part of a strong AI app. Pair it with good prompts, tool calling, and RAG for the best results. Each piece adds a bit more intelligence.

13. Further Reading

Leave a Comment