Data JDBC SQLite
Arconia Data JDBC SQLite adds SQLite support to Spring Data JDBC. It contributes an SQLite dialect, the translation of SQLite errors into Spring data access exceptions, and the SQLite JDBC driver, so you can use SQLite as the database backing your Spring Data JDBC repositories.
Dependencies
Add the Arconia Data JDBC SQLite Spring Boot Starter dependency to your project.
-
Gradle
-
Maven
dependencies {
implementation 'io.arconia:arconia-data-jdbc-sqlite-spring-boot-starter'
}
<dependency>
<groupId>io.arconia</groupId>
<artifactId>arconia-data-jdbc-sqlite-spring-boot-starter</artifactId>
</dependency>
The starter includes the Spring Boot Starter for Spring Data JDBC and the org.xerial:sqlite-jdbc driver, so no additional dependency is required.
Arconia publishes a BOM (Bill of Materials) that you can use to manage the version of the Arconia libraries. It is recommended to use the BOM to ensure that all dependencies are compatible.
-
Gradle
-
Maven
dependencyManagement {
imports {
mavenBom "io.arconia:arconia-bom:0.33.0"
}
}
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.arconia</groupId>
<artifactId>arconia-bom</artifactId>
<version>0.33.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Configuration
Configure the data source to point at an SQLite database file. The SQLite JDBC driver applies the pragmas set as parameters of the JDBC URL to each connection it opens.
spring:
datasource:
url: "jdbc:sqlite:./data/app.db?journal_mode=WAL&synchronous=NORMAL&busy_timeout=5000&foreign_keys=true"
SQLite creates the database file when it doesn’t exist, but not the directory containing it. Opening a connection fails with an SQLITE_CANTOPEN error when the directory is missing.
The parameters in the example are recommended for applications serving concurrent requests.
-
journal_mode=WALenables write-ahead logging, so that reading the database doesn’t block writing to it and the other way around. SQLite still allows one writer at a time. -
synchronous=NORMALwaits less often for the disk to confirm writes. In write-ahead logging mode, it keeps the database consistent, but the most recent transactions can be lost on a power failure or an operating system crash. -
busy_timeoutis how long, in milliseconds, a connection waits for another one to finish writing before failing with anSQLITE_BUSYerror. The driver default is 3000. -
foreign_keys=trueenforces the foreign key constraints of the schema, which SQLite ignores by default.
Spring Boot detects the JDBC URL and configures the data source automatically. Spring Data JDBC discovers the SQLite dialect contributed by this module via Spring’s spring.factories mechanism, so no further wiring is required.
Other pragmas can help with larger databases.
-
journal_size_limitis the size, in bytes, that the write-ahead log file is truncated to after it has been written back to the database. Without it, the file keeps the size it reached at its peak. -
cache_sizeis the amount of database pages each connection keeps in memory. A negative value is a size in kibibytes, such as-65536for 64 MiB. The SQLite default is-2000, about 2 MB. -
mmap_sizeis the size, in bytes, of the part of the database file that SQLite reads through memory-mapped I/O instead of system calls.
Connection Pool
Spring Boot configures a pool of up to 10 connections. In write-ahead logging mode, they read the database in parallel, but write to it one at a time. A connection that wants to write waits for the current writer to finish, for up to the busy timeout. Keep write transactions short, so that the other writers don’t run out of time while they wait.
In-Memory Databases
SQLite creates a separate in-memory database for each connection, so the connections of a pool don’t see each other’s data. To use an in-memory database, limit the pool to a single connection and keep that connection open for the lifetime of the application.
spring:
datasource:
url: "jdbc:sqlite::memory:"
hikari:
maximum-pool-size: 1
max-lifetime: 0
For tests, consider a database file in a temporary directory instead, as described in Testing.
Schema Initialization
Spring Boot doesn’t consider SQLite an embedded database, so it doesn’t run the schema.sql and data.sql scripts by default. Enable them explicitly, or manage the schema with a database migration tool such as Flyway.
spring:
sql:
init:
mode: always
Testing
Point tests at a database file in a temporary directory, which gives each test class a new database and works with the default pool configuration. When the JDBC URL comes from a @DynamicPropertySource method, Spring Boot keeps the SQLite data source in tests annotated with @DataJdbcTest or @JdbcTest, instead of replacing it with an embedded database.
@DataJdbcTest(properties = "spring.sql.init.mode=always")
class BookRepositoryTests {
@TempDir
static Path databaseDirectory;
@DynamicPropertySource
static void sqliteProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", () -> "jdbc:sqlite:" + databaseDirectory.resolve("test.db"));
}
// ...
}
Deployment
SQLite runs inside the application process and relies on file locks to coordinate access to the database file.
-
Keep the database file on a local disk. Network file systems don’t implement file locks reliably, which can corrupt the database.
-
Run a single instance of the application against a database file, instead of several instances sharing it through a volume.
-
Back up the database with
VACUUM INTO, which writes a consistent copy while the application keeps running, or replicate it continuously with a tool such as Litestream. Copying the database file of a running application can produce a corrupt copy.
Native Access
The SQLite JDBC driver loads a native library. Starting from Java 24, the JVM prints a warning when a library calls restricted methods to do that, and future Java versions will block the call unless native access is enabled. Run the application with the --enable-native-access=ALL-UNNAMED JVM option to allow it.
Ahead-of-Time Processing
When using Spring Data JDBC with ahead-of-time processing (targeting either the JVM or a native image), the default dialect resolution requires a database connection at build time. To avoid that, declare a JdbcDialect bean for SQLite so the dialect is known statically.
import io.arconia.data.jdbc.sqlite.dialect.JdbcSqliteDialect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
class JdbcConfiguration {
@Bean
JdbcSqliteDialect jdbcDialect() {
return JdbcSqliteDialect.INSTANCE;
}
}
Type Mapping
SQLite has no dedicated types for dates, times, and booleans. The SQLite dialect maps them as follows.
Dates and Times
Values of the java.time types are stored as ISO-8601 text, in the format of the SQLite date and time functions such as datetime() and CURRENT_TIMESTAMP. SQLite compares them as text, so values written by the application and by SQLite sort and compare correctly together.
| Java type | Stored value |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
SQLite treats every date and time as UTC, so Instant, OffsetDateTime, ZonedDateTime, and OffsetTime values are converted to UTC. Values of the types with an offset or a time zone are read back as the same instant with a UTC offset. When reading, the date and time can also be separated by T, the fraction can have any number of digits, and the value can end with an offset such as +02:00 or Z. A value without an offset is read as UTC. Values stored as numbers, such as the ones returned by the unixepoch() and julianday() functions, can’t be read as dates and times.
The dialect applies to the values that Spring Data JDBC writes, including the parameters of repository query methods. With JdbcClient and JdbcTemplate, the SQLite JDBC driver writes a java.time value as the result of its toString() method instead, such as 2026-07-31T10:34:56Z. SQLite doesn’t compare those values correctly with the ones in the format above, since it compares them as text. Format such values yourself, or let SQLite produce them with its date and time functions.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSSSS")
.withZone(ZoneOffset.UTC);
jdbcClient.sql("UPDATE book SET published_at = :publishedAt WHERE id = :id")
.param("publishedAt", formatter.format(Instant.now()))
.param("id", id)
.update();
The legacy date and time types are stored in the same formats.
| Java type | Stored as |
|---|---|
|
|
|
|
|
|
|
|
A java.sql.Date or java.sql.Time value is converted to a date or a time in the default time zone of the JVM, as its toLocalDate() or toLocalTime() method does. A java.sql.Time value keeps whole seconds only.
Decimals
SQLite stores a value in a column declared as NUMERIC or DECIMAL as a floating-point number when it has a fractional part, keeping about 15 significant digits. To store BigDecimal values exactly, declare the column as TEXT.
Error Handling
The SQLite JDBC driver reports errors without the SQL state that Spring relies on to categorize them. Arconia contributes an SqliteExceptionTranslator that categorizes them based on the SQLite result code instead. Spring Boot applies it to the auto-configured JdbcTemplate, which Spring Data JDBC repositories and JdbcClient use too, and Arconia applies it to the transaction manager.
| SQLite error | Exception |
|---|---|
A violated |
|
Any other violated constraint, such as |
|
A database that is busy or locked by another connection |
|
A CannotAcquireLockException is a transient error, so the operation can succeed when retried. Other errors are translated as Spring does by default. The translator is also applied in tests annotated with @JdbcTest or @DataJdbcTest. To use a translator of your own, declare an SQLExceptionTranslator bean, and Arconia doesn’t contribute its own.
Limitations
Spring Data JDBC features that SQLite doesn’t support behave as follows.
-
Pessimistic locking. Queries annotated with
@Lockrun without a lock clause, since SQLite has no row locks and allows one writer at a time. In write-ahead logging mode, a transaction that reads and then writes fails if another connection wrote to the database in the meantime, without waiting for the busy timeout. The failure is reported as aCannotAcquireLockException, so retry the whole transaction. Thetransaction_mode=IMMEDIATEparameter of the JDBC URL avoids the failure by making each transaction wait for its turn to write when it starts. Spring Data JDBC runs repository queries in transactions too, though, so with that parameter, reading also waits for the current writer to finish. -
Read-only transactions. Writing in a transaction declared as read-only, such as with
@Transactional(readOnly = true), succeeds. The SQLite JDBC driver can only make a connection read-only when opening it, so Spring runs the transaction without that flag. Don’t set thejdbc.explicit_readonlyparameter of the JDBC URL to change that, since it leaves a pooled connection read-only after a read-only transaction, and later writes on that connection fail. -
Upserts. Calling
JdbcAggregateTemplate.upsert()fails with anIllegalArgumentException, since Spring Data JDBC doesn’t support upserts for third-party dialects (spring-data-relational#2304). -
Escaping
LIKEpatterns. Spring Data JDBC escapes the%and_characters in the values of derived queries such asfindByNameContaining, but SQLite only honors the escape character when the query declares it with anESCAPEclause, which Spring Data JDBC doesn’t add. A value containing those characters matches no rows. Write such queries with@Queryinstead. -
Sequences. Identifiers are generated by the database, for example, with an
INTEGER PRIMARY KEYcolumn.