jdbcclient: JdbcClient on Spring Framework 7.0.10 / Boot 4.1.2, with twelve real transcripts
Parameters, row mapping, single/optional/list, generated keys, batch via NamedParameterJdbcTemplate (JdbcClient has none), exception translation, transactions, an unclosed stream() exhausting a 2-connection pool, withMaxRows truncating silently, and spring.jdbc.template.* reaching the auto-configured JdbcClient. JdbcClient API diffed across 6.1.0, 6.2.19 and 7.0.0. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b5n3PRbPkUsiJybTeg
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
260c8a692f
commit
fc8bc933d5
@@ -0,0 +1,58 @@
|
||||
# jdbcclient
|
||||
|
||||
Companion code for **JdbcClient in Spring Framework 7: Modern JDBC Without JPA (vs JdbcTemplate)** on [ankurm.com](https://ankurm.com).
|
||||
|
||||
One `product` table on in-memory H2, a `JdbcClient` repository next to the same four operations written with
|
||||
`JdbcTemplate`, and twelve transcripts that record what the API really does, including the failures.
|
||||
|
||||
## Versions
|
||||
|
||||
| Component | Version |
|
||||
|---|---|
|
||||
| Spring Boot | 4.1.2 |
|
||||
| Spring Framework (`spring-jdbc`) | 7.0.10 (7.0.0 reached Maven Central on 13 Nov 2025) |
|
||||
| HikariCP | 7.0.2 |
|
||||
| H2 | 2.4.240 |
|
||||
| JDK | 25 (Temurin 25.0.5) |
|
||||
|
||||
## Run it
|
||||
|
||||
```bash
|
||||
./scripts/run-all.sh # runs the tests, which regenerate everything in output/
|
||||
```
|
||||
|
||||
No Docker and no database to install. Exception messages and a few behaviours (generated-key columns, the
|
||||
wording of constraint errors) are H2's; the shape of what Spring does is the same on other databases.
|
||||
|
||||
## Source
|
||||
|
||||
| File | What it shows |
|
||||
|---|---|
|
||||
| [`ProductRepository.java`](src/main/java/com/ankurm/jdbcclient/ProductRepository.java) | the JdbcClient version: named parameters, `paramSource(record)`, `optional()`, generated keys, `stream()` |
|
||||
| [`ProductRepositoryJdbcTemplate.java`](src/main/java/com/ankurm/jdbcclient/ProductRepositoryJdbcTemplate.java) | the same operations with `JdbcTemplate` and `NamedParameterJdbcTemplate` |
|
||||
| [`StockService.java`](src/main/java/com/ankurm/jdbcclient/StockService.java) | two UPDATEs with and without `@Transactional` |
|
||||
| [`Product.java`](src/main/java/com/ankurm/jdbcclient/Product.java) | the record the rows map to |
|
||||
|
||||
## Captured output
|
||||
|
||||
| File | Shows |
|
||||
|---|---|
|
||||
| [`01-same-results.txt`](output/01-same-results.txt) | both repositories return identical rows |
|
||||
| [`02-api-surface.txt`](output/02-api-surface.txt) | every method on `JdbcClient` and its spec interfaces, by reflection; there is no batch method |
|
||||
| [`03-parameters.txt`](output/03-parameters.txt) | nine ways to pass parameters and four ways to get them wrong |
|
||||
| [`04-mapping.txt`](output/04-mapping.txt) | records, beans, lambdas, missing columns, wrong types, SQL NULL into a primitive |
|
||||
| [`05-result-shapes.txt`](output/05-result-shapes.txt) | `list`, `single`, `optional`, `set` on 0, 1 and 4 rows |
|
||||
| [`06-generated-keys.txt`](output/06-generated-keys.txt) | `KeyHolder` with and without column names |
|
||||
| [`07-batch.txt`](output/07-batch.txt) | batching through `NamedParameterJdbcTemplate` |
|
||||
| [`08-exceptions.txt`](output/08-exceptions.txt) | what constraint violations and bad SQL turn into |
|
||||
| [`09-transactions.txt`](output/09-transactions.txt) | the same body with and without a transaction |
|
||||
| [`10-stream-leak.txt`](output/10-stream-leak.txt) | unclosed `stream()` calls exhausting a two-connection pool |
|
||||
| [`11-limits.txt`](output/11-limits.txt) | `withMaxRows` truncating silently, `withQueryTimeout` |
|
||||
| [`12-template-properties.txt`](output/12-template-properties.txt) | `spring.jdbc.template.max-rows` reaching the auto-configured `JdbcClient` |
|
||||
|
||||
| [`13-api-diff.txt`](output/13-api-diff.txt) | `JdbcClient` signatures diffed across 6.1.0, 6.2.0, 6.2.19, 7.0.0 and 7.0.10 (`scripts/api-diff.sh`) |
|
||||
| [`14-default-jdbcclient.txt`](output/14-default-jdbcclient.txt) | the fields and constructors of `DefaultJdbcClient` in 7.0.10 (`scripts/api-diff.sh`) |
|
||||
|
||||
`13` and `14` come from `./scripts/api-diff.sh`, which downloads the `spring-jdbc` jars from Maven Central and needs network access.
|
||||
|
||||
Timings and the speed comparison in `07` are indicative: they vary between runs and H2 has no network round trip.
|
||||
@@ -0,0 +1,8 @@
|
||||
findBySku("MS-002") JdbcClient == JdbcTemplate: true
|
||||
findBySku("NOPE") both Optional.empty: true
|
||||
findInStockCheaperThan(4000) rows: 3, identical: true
|
||||
findBySkus([KB-001, WC-005]) rows: 2, identical: true
|
||||
updateStock(1, 99) rows updated by each: 1
|
||||
|
||||
First row returned by findBySku("MS-002"):
|
||||
Product[id=2, sku=MS-002, name=Wireless Mouse, price=1299.50, inStock=true, createdOn=2026-02-14, stockCount=40]
|
||||
@@ -0,0 +1,28 @@
|
||||
methods on JdbcClient and its three spec interfaces, read by reflection (21 names):
|
||||
JdbcClient.create
|
||||
JdbcClient.sql
|
||||
MappedQuerySpec.list
|
||||
MappedQuerySpec.optional
|
||||
MappedQuerySpec.set
|
||||
MappedQuerySpec.single
|
||||
MappedQuerySpec.stream
|
||||
ResultQuerySpec.listOfRows
|
||||
ResultQuerySpec.optionalValue
|
||||
ResultQuerySpec.rowSet
|
||||
ResultQuerySpec.singleColumn
|
||||
ResultQuerySpec.singleRow
|
||||
ResultQuerySpec.singleValue
|
||||
StatementSpec.param
|
||||
StatementSpec.paramSource
|
||||
StatementSpec.params
|
||||
StatementSpec.query
|
||||
StatementSpec.update
|
||||
StatementSpec.withFetchSize
|
||||
StatementSpec.withMaxRows
|
||||
StatementSpec.withQueryTimeout
|
||||
|
||||
any method with 'batch' in its name: false
|
||||
|
||||
beans of type JdbcClient in the Boot context: 1 ([jdbcClient])
|
||||
implementation class: org.springframework.jdbc.core.simple.DefaultJdbcClient
|
||||
beans Boot also provides: JdbcTemplate=true NamedParameterJdbcTemplate=true
|
||||
@@ -0,0 +1,15 @@
|
||||
1 .param(v).param(v) ? placeholders -> [Mechanical Keyboard]
|
||||
2 .param(1, v) by index -> [Mechanical Keyboard]
|
||||
3 .params(List.of(..)) ? placeholders -> [Wireless Mouse, Headset]
|
||||
4 .param("sku", v) :named -> [Mechanical Keyboard]
|
||||
5 .params(Map.of(..)) :named -> [Mechanical Keyboard]
|
||||
6 .paramSource(record) :named, record -> [Mechanical Keyboard]
|
||||
7 :p used twice, one .param("p", 10) :named -> [KB-001, MS-002]
|
||||
8 IN (:skus) with a 3-element list expanded -> [KB-001, WC-005] (NOPE matched nothing)
|
||||
9 LIKE :q with "%o%" wildcard in value -> [Mechanical Keyboard, Wireless Mouse, Monitor 27 inch]
|
||||
|
||||
10 :named and ? in one statement -> java.lang.IllegalStateException: Configure either named or indexed parameters, not both
|
||||
11 typo in the parameter name (:sku, supplied skuu) -> org.springframework.dao.InvalidDataAccessApiUsageException: No value supplied for the SQL parameter 'sku': No value registered for key 'sku'
|
||||
12 two ? but one value -> org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [SELECT name FROM product WHERE sku = ? AND in_stock = ?]; Parameter "#2" is not set; SQL statement: SELECT name FROM product WHERE sku = ? AND in_stock = ? [90012-240] [root cause: JdbcSQLDataException: Parameter "#2" is not set; SQL statement: SELECT name FROM product WHERE sku = ? AND in_stock = ? [90012-240]]
|
||||
13 .param("sku", null) -> ran, rows: 0 (= NULL is never true)
|
||||
.param("sku", null, Types.VARCHAR) -> ran, rows: 0 (= NULL is never true)
|
||||
@@ -0,0 +1,20 @@
|
||||
1 SELECT * into the Product record (in_stock -> inStock, created_on -> createdOn, stock_count -> stockCount):
|
||||
Product[id=1, sku=KB-001, name=Mechanical Keyboard, price=4999.00, inStock=true, createdOn=2026-01-10, stockCount=12]
|
||||
Product[id=2, sku=MS-002, name=Wireless Mouse, price=1299.50, inStock=true, createdOn=2026-02-14, stockCount=40]
|
||||
Product[id=3, sku=MN-003, name=Monitor 27 inch, price=18999.00, inStock=false, createdOn=2026-03-01, stockCount=0]
|
||||
Product[id=4, sku=HS-004, name=Headset, price=2499.00, inStock=true, createdOn=2026-03-22, stockCount=7]
|
||||
Product[id=5, sku=WC-005, name=Webcam, price=3199.00, inStock=true, createdOn=2026-04-05, stockCount=3]
|
||||
|
||||
2 a record with fewer components than columns: Slim[sku=KB-001, name=Mechanical Keyboard]
|
||||
3 a JavaBean with setters for three of the seven columns: Bean[sku=KB-001, price=4999.00, inStock=true]
|
||||
4 a single column to a simple type: [12, 40, 0, 7, 3] and Wireless Mouse
|
||||
5 a RowMapper lambda: MS-002 costs 1299.50
|
||||
|
||||
6 record asks for colourName, SELECT has no such column: org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT sku FROM product WHERE id = 1] [root cause: JdbcSQLSyntaxErrorException: Column "colourName" not found [42122-240]]
|
||||
7 record asks for primitive int missingCol, no such column: org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT sku FROM product WHERE id = 1] [root cause: JdbcSQLSyntaxErrorException: Column "missingCol" not found [42122-240]]
|
||||
8 VARCHAR column into a LocalDate component: org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [SELECT sku, name FROM product WHERE id = 1]; Cannot parse "DATE" constant "Mechanical Keyboard" [22007-240] [root cause: NumberFormatException: Error at index 0 in: "Mechanical Keyb"]
|
||||
9 SQL NULL into the primitive int stockCount: org.springframework.core.convert.ConversionFailedException: Failed to convert from type [null] to type [int] for value [null] [root cause: IllegalArgumentException: A null value cannot be assigned to a primitive type]
|
||||
the same NULL into Integer stockCount: NullBoxed[sku=KB-001, stockCount=null]
|
||||
|
||||
10 untyped listOfRows(): keys as the driver returns them: [SKU, IN_STOCK], value classes: [String, Boolean]
|
||||
lookup is case-insensitive: row.get("sku") = KB-001
|
||||
@@ -0,0 +1,14 @@
|
||||
0 rows 1 row 4 rows
|
||||
list() [] [Mechanical Keyboard] 4 items
|
||||
single() EmptyResult.. Mechanical Keyboard IncorrectResultSize..
|
||||
optional() Optional.empty Optional[Mechanical Keyboard] IncorrectResultSize..
|
||||
set() [] [Mechanical Keyboard] 4 items
|
||||
|
||||
single() on 0 rows: org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0
|
||||
single() on 4 rows: org.springframework.dao.IncorrectResultSizeDataAccessException: Incorrect result size: expected 1, actual 4
|
||||
EmptyResultDataAccessException extends IncorrectResultSizeDataAccessException: true
|
||||
|
||||
untyped singleValue() of COUNT(*): 5 (Long)
|
||||
untyped optionalValue() with no row: Optional.empty
|
||||
optional() over SELECT MAX(price) with no matching rows: Optional.empty
|
||||
single() over the same query: org.springframework.dao.TypeMismatchDataAccessException: Result value is null but no null value expected
|
||||
@@ -0,0 +1,5 @@
|
||||
insert via paramSource(record) and update(keys, "id"): generated id = 6
|
||||
update(keys) with no column names: key columns = [ID, CREATED_ON]
|
||||
update(keys, "id"): key columns = [ID], id = 8
|
||||
a row inserted without created_on / in_stock / stock_count got the column defaults: in_stock=true stock_count=0 created_on=today: true
|
||||
rows now in the table: 8
|
||||
@@ -0,0 +1,5 @@
|
||||
2000 inserts into in-memory H2 (no network round trip, so the gap understates a real database):
|
||||
a loop of jdbc.sql(..).update() : finished (timing varies per run, not asserted)
|
||||
one NamedParameterJdbcTemplate.batchUpdate: finished, 2000 result codes returned
|
||||
loop took more than batch (indicative, one run): true
|
||||
rows in the table after the batch: 2005 (5 seed rows + 2000)
|
||||
@@ -0,0 +1,5 @@
|
||||
duplicate unique value -> DuplicateKeyException (database said SQLState 23505)
|
||||
NULL into a NOT NULL column -> DataIntegrityViolationException (database said SQLState 23502)
|
||||
CHECK constraint violated -> DataIntegrityViolationException (database said SQLState 23513)
|
||||
typo in the SQL -> BadSqlGrammarException (database said SQLState 42001)
|
||||
all four are unchecked DataAccessException subclasses: true
|
||||
@@ -0,0 +1,7 @@
|
||||
start: keyboard(1)=12 webcam(5)=3
|
||||
@Transactional move of 5 from webcam to keyboard -> DataIntegrityViolationException
|
||||
after: keyboard(1)=12 webcam(5)=3 (both UPDATEs rolled back)
|
||||
same body, no @Transactional -> DataIntegrityViolationException
|
||||
after: keyboard(1)=17 webcam(5)=3 (the first UPDATE had already committed)
|
||||
TransactionTemplate, UPDATE then RuntimeException -> IllegalStateException; mouse(2)=40 (was 40)
|
||||
inside a transaction a later SELECT sees the earlier UPDATE: 55; after commit: 55
|
||||
@@ -0,0 +1,8 @@
|
||||
Hikari pool: maximum-pool-size=2, connection-timeout=500 ms
|
||||
rows in the table, via count(): 5
|
||||
two streamAll() calls left open, then one ordinary count():
|
||||
-> CannotGetJdbcConnectionException after about 500 ms
|
||||
root cause: HikariPool-N - Connection is not available, request timed out after 500ms (...)
|
||||
after closing both streams, count() works again: 5
|
||||
try-with-resources: names of rows 1..2: [Mechanical Keyboard, Wireless Mouse]
|
||||
and the connection is back: count() = 5
|
||||
@@ -0,0 +1,4 @@
|
||||
5 rows in the table
|
||||
list() -> 5 rows
|
||||
withMaxRows(2).list() -> 2 rows [KB-001, MS-002] (no warning, no exception)
|
||||
a query that would run for minutes with withQueryTimeout(1) -> QueryTimeoutException (about 1 s)
|
||||
@@ -0,0 +1,2 @@
|
||||
spring.jdbc.template.max-rows=2 in application properties, 5 rows in the table
|
||||
auto-configured JdbcClient: SELECT sku FROM product -> 2 rows
|
||||
@@ -0,0 +1,15 @@
|
||||
public signatures of JdbcClient + StatementSpec + ResultQuerySpec + MappedQuerySpec, diffed between releases
|
||||
6.1.0: 40 signatures
|
||||
6.2.0: 41 signatures
|
||||
6.1.0 -> 6.2.0:
|
||||
> public default Optional<Object> optionalValue();
|
||||
6.2.19: 41 signatures
|
||||
6.2.0 -> 6.2.19: no change
|
||||
7.0.0: 45 signatures
|
||||
6.2.19 -> 7.0.0:
|
||||
> public abstract JdbcClient$StatementSpec withFetchSize(int);
|
||||
> public abstract JdbcClient$StatementSpec withMaxRows(int);
|
||||
> public abstract JdbcClient$StatementSpec withQueryTimeout(int);
|
||||
> public static JdbcClient create(org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations, org.springframework.core.convert.ConversionService);
|
||||
7.0.10: 45 signatures
|
||||
7.0.0 -> 7.0.10: no change
|
||||
@@ -0,0 +1,8 @@
|
||||
DefaultJdbcClient (spring-jdbc 7.0.10), fields and constructors:
|
||||
private final NamedParameterJdbcOperations namedParamOps;
|
||||
private final ConversionService conversionService;
|
||||
private final Map<Class<?>, RowMapper<?>> rowMapperCache;
|
||||
public DefaultJdbcClient(javax.sql.DataSource);
|
||||
public DefaultJdbcClient(JdbcOperations);
|
||||
public DefaultJdbcClient(NamedParameterJdbcOperations, ConversionService);
|
||||
public JdbcClient$StatementSpec sql(String);
|
||||
@@ -0,0 +1,48 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>4.1.2</version>
|
||||
</parent>
|
||||
|
||||
<groupId>com.ankurm</groupId>
|
||||
<artifactId>jdbcclient-demo</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<properties>
|
||||
<java.version>25</java.version>
|
||||
<maven.compiler.release>25</maven.compiler.release>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jdbc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-jdbc-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
Executable
+38
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env bash
|
||||
# Which Spring Framework release added which JdbcClient method? Reads the real spring-jdbc jars from Maven Central
|
||||
# with javap and diffs the public signatures. Needs a JDK on PATH and network access to repo1.maven.org.
|
||||
# Writes output/13-api-diff.txt and output/14-default-jdbcclient.txt
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
W=target/api-diff; mkdir -p "$W" output
|
||||
VERSIONS=(6.1.0 6.2.0 6.2.19 7.0.0 7.0.10)
|
||||
for v in "${VERSIONS[@]}"; do
|
||||
[ -f "$W/spring-jdbc-$v.jar" ] || curl -sfo "$W/spring-jdbc-$v.jar" \
|
||||
"https://repo1.maven.org/maven2/org/springframework/spring-jdbc/$v/spring-jdbc-$v.jar"
|
||||
done
|
||||
sig() {
|
||||
javap -cp "$W/spring-jdbc-$1.jar" org.springframework.jdbc.core.simple.JdbcClient \
|
||||
'org.springframework.jdbc.core.simple.JdbcClient$StatementSpec' \
|
||||
'org.springframework.jdbc.core.simple.JdbcClient$ResultQuerySpec' \
|
||||
'org.springframework.jdbc.core.simple.JdbcClient$MappedQuerySpec' 2>/dev/null \
|
||||
| grep -v Compiled | sed 's/org\.springframework\.jdbc\.core\.simple\.//g; s/java\.lang\.//g; s/java\.util\.//g' | sort
|
||||
}
|
||||
{
|
||||
echo "public signatures of JdbcClient + StatementSpec + ResultQuerySpec + MappedQuerySpec, diffed between releases"
|
||||
prev=""
|
||||
for v in "${VERSIONS[@]}"; do
|
||||
sig "$v" > "$W/sig-$v.txt"
|
||||
echo "$v: $(wc -l < "$W/sig-$v.txt" | tr -d ' ') signatures"
|
||||
if [ -n "$prev" ]; then
|
||||
d=$(diff "$W/sig-$prev.txt" "$W/sig-$v.txt" | grep '^[<>]' || true)
|
||||
if [ -z "$d" ]; then echo " $prev -> $v: no change"; else echo " $prev -> $v:"; echo "$d" | sed 's/^/ /'; fi
|
||||
fi
|
||||
prev=$v
|
||||
done
|
||||
} > output/13-api-diff.txt
|
||||
{
|
||||
echo "DefaultJdbcClient (spring-jdbc 7.0.10), fields and constructors:"
|
||||
javap -p -cp "$W/spring-jdbc-7.0.10.jar" org.springframework.jdbc.core.simple.DefaultJdbcClient 2>/dev/null \
|
||||
| grep -E "private|public org" | sed 's/org\.springframework\.[a-z.]*\.//g; s/java\.[a-z]*\.//g; s/^ *//'
|
||||
} > output/14-default-jdbcclient.txt
|
||||
cat output/13-api-diff.txt output/14-default-jdbcclient.txt
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerates every file in output/ by running the test suite (in-memory H2, no Docker, no network after the first build).
|
||||
# The tests write the transcripts and assert the same facts, so a stale transcript fails the build.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
rm -f output/*.txt
|
||||
mvn -B -q test
|
||||
./scripts/api-diff.sh > /dev/null # outputs 13 and 14: reads spring-jdbc jars from Maven Central, needs the network
|
||||
echo "wrote:"; ls output
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.ankurm.jdbcclient;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class JdbcClientApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(JdbcClientApplication.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.ankurm.jdbcclient;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
|
||||
/** A plain record. Columns in_stock / created_on / stock_count map to inStock / createdOn / stockCount. */
|
||||
public record Product(Long id, String sku, String name, BigDecimal price,
|
||||
boolean inStock, LocalDate createdOn, int stockCount) {
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package com.ankurm.jdbcclient;
|
||||
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
import org.springframework.jdbc.support.GeneratedKeyHolder;
|
||||
import org.springframework.jdbc.support.KeyHolder;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/** The "after": the same operations with JdbcClient, plus the ones JdbcTemplate needs more code for. */
|
||||
@Repository
|
||||
public class ProductRepository {
|
||||
|
||||
private final JdbcClient jdbc;
|
||||
|
||||
public ProductRepository(JdbcClient jdbc) {
|
||||
this.jdbc = jdbc;
|
||||
}
|
||||
|
||||
public Optional<Product> findBySku(String sku) {
|
||||
return jdbc.sql("SELECT * FROM product WHERE sku = :sku")
|
||||
.param("sku", sku)
|
||||
.query(Product.class)
|
||||
.optional();
|
||||
}
|
||||
|
||||
public List<Product> findInStockCheaperThan(BigDecimal max) {
|
||||
return jdbc.sql("SELECT * FROM product WHERE in_stock = TRUE AND price < :max ORDER BY price")
|
||||
.param("max", max)
|
||||
.query(Product.class)
|
||||
.list();
|
||||
}
|
||||
|
||||
public List<Product> findBySkus(List<String> skus) {
|
||||
return jdbc.sql("SELECT * FROM product WHERE sku IN (:skus) ORDER BY id")
|
||||
.param("skus", skus)
|
||||
.query(Product.class)
|
||||
.list();
|
||||
}
|
||||
|
||||
public int updateStock(long id, int newCount) {
|
||||
return jdbc.sql("UPDATE product SET stock_count = :count WHERE id = :id")
|
||||
.param("count", newCount)
|
||||
.param("id", id)
|
||||
.update();
|
||||
}
|
||||
|
||||
/** Insert from a record: each :name is read from the matching component. Returns the generated id. */
|
||||
public long insert(Product p) {
|
||||
KeyHolder keys = new GeneratedKeyHolder();
|
||||
jdbc.sql("INSERT INTO product (sku, name, price, in_stock, stock_count) "
|
||||
+ "VALUES (:sku, :name, :price, :inStock, :stockCount)")
|
||||
.paramSource(p)
|
||||
.update(keys, "id");
|
||||
return keys.getKey().longValue();
|
||||
}
|
||||
|
||||
/** The caller must close the stream, or the connection stays checked out. */
|
||||
public Stream<Product> streamAll() {
|
||||
return jdbc.sql("SELECT * FROM product ORDER BY id").query(Product.class).stream();
|
||||
}
|
||||
|
||||
public long count() {
|
||||
return jdbc.sql("SELECT COUNT(*) FROM product").query(Long.class).single();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.ankurm.jdbcclient;
|
||||
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
|
||||
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
|
||||
import org.springframework.dao.EmptyResultDataAccessException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/** The "before": the same four operations written with JdbcTemplate / NamedParameterJdbcTemplate. */
|
||||
public class ProductRepositoryJdbcTemplate {
|
||||
|
||||
private static final RowMapper<Product> MAPPER = (rs, rowNum) -> new Product(
|
||||
rs.getLong("id"),
|
||||
rs.getString("sku"),
|
||||
rs.getString("name"),
|
||||
rs.getBigDecimal("price"),
|
||||
rs.getBoolean("in_stock"),
|
||||
rs.getObject("created_on", java.time.LocalDate.class),
|
||||
rs.getInt("stock_count"));
|
||||
|
||||
private final JdbcTemplate jdbc;
|
||||
private final NamedParameterJdbcTemplate named;
|
||||
|
||||
public ProductRepositoryJdbcTemplate(JdbcTemplate jdbc, NamedParameterJdbcTemplate named) {
|
||||
this.jdbc = jdbc;
|
||||
this.named = named;
|
||||
}
|
||||
|
||||
public Optional<Product> findBySku(String sku) {
|
||||
try {
|
||||
return Optional.of(jdbc.queryForObject("SELECT * FROM product WHERE sku = ?", MAPPER, sku));
|
||||
} catch (EmptyResultDataAccessException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
public List<Product> findInStockCheaperThan(java.math.BigDecimal max) {
|
||||
return named.query("SELECT * FROM product WHERE in_stock = TRUE AND price < :max ORDER BY price",
|
||||
new MapSqlParameterSource("max", max), MAPPER);
|
||||
}
|
||||
|
||||
public List<Product> findBySkus(List<String> skus) {
|
||||
return named.query("SELECT * FROM product WHERE sku IN (:skus) ORDER BY id",
|
||||
new MapSqlParameterSource("skus", skus), MAPPER);
|
||||
}
|
||||
|
||||
public int updateStock(long id, int newCount) {
|
||||
return jdbc.update("UPDATE product SET stock_count = ? WHERE id = ?", newCount, id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.ankurm.jdbcclient;
|
||||
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/** Moves stock between two products. Two UPDATEs that must succeed or fail together. */
|
||||
@Service
|
||||
public class StockService {
|
||||
|
||||
private final JdbcClient jdbc;
|
||||
|
||||
public StockService(JdbcClient jdbc) {
|
||||
this.jdbc = jdbc;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void moveStockAtomic(long from, long to, int qty) {
|
||||
move(from, to, qty);
|
||||
}
|
||||
|
||||
/** Same body, no @Transactional: every statement auto-commits on its own. */
|
||||
public void moveStockNoTx(long from, long to, int qty) {
|
||||
move(from, to, qty);
|
||||
}
|
||||
|
||||
private void move(long from, long to, int qty) {
|
||||
jdbc.sql("UPDATE product SET stock_count = stock_count + :q WHERE id = :id")
|
||||
.param("q", qty).param("id", to).update(); // first UPDATE
|
||||
jdbc.sql("UPDATE product SET stock_count = stock_count - :q WHERE id = :id")
|
||||
.param("q", qty).param("id", from).update(); // CHECK (stock_count >= 0) may fail here
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
spring.application.name=jdbcclient-demo
|
||||
spring.datasource.url=jdbc:h2:mem:shop;DB_CLOSE_DELAY=-1
|
||||
spring.sql.init.mode=always
|
||||
@@ -0,0 +1,6 @@
|
||||
MERGE INTO product (id, sku, name, price, in_stock, created_on, stock_count) KEY (id) VALUES
|
||||
(1, 'KB-001', 'Mechanical Keyboard', 4999.00, TRUE, DATE '2026-01-10', 12),
|
||||
(2, 'MS-002', 'Wireless Mouse', 1299.50, TRUE, DATE '2026-02-14', 40),
|
||||
(3, 'MN-003', 'Monitor 27 inch', 18999.00, FALSE, DATE '2026-03-01', 0),
|
||||
(4, 'HS-004', 'Headset', 2499.00, TRUE, DATE '2026-03-22', 7),
|
||||
(5, 'WC-005', 'Webcam', 3199.00, TRUE, DATE '2026-04-05', 3);
|
||||
@@ -0,0 +1,9 @@
|
||||
CREATE TABLE IF NOT EXISTS product (
|
||||
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
sku VARCHAR(20) NOT NULL UNIQUE,
|
||||
name VARCHAR(100) NOT NULL,
|
||||
price DECIMAL(10,2) NOT NULL,
|
||||
in_stock BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_on DATE NOT NULL DEFAULT CURRENT_DATE,
|
||||
stock_count INT NOT NULL DEFAULT 0 CHECK (stock_count >= 0)
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.ankurm.jdbcclient;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
|
||||
@SpringBootTest
|
||||
abstract class Base {
|
||||
@Autowired JdbcClient jdbc;
|
||||
|
||||
@BeforeEach
|
||||
void reset() {
|
||||
TestData.reset(jdbc);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.ankurm.jdbcclient;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class BasicsTest extends Base {
|
||||
|
||||
@Autowired ProductRepository repo;
|
||||
@Autowired JdbcTemplate jdbcTemplate;
|
||||
@Autowired NamedParameterJdbcTemplate named;
|
||||
@Autowired ApplicationContext ctx;
|
||||
|
||||
@Test
|
||||
void sameResultsAsJdbcTemplate() throws Exception {
|
||||
var old = new ProductRepositoryJdbcTemplate(jdbcTemplate, named);
|
||||
assertThat(repo.findBySku("MS-002")).isEqualTo(old.findBySku("MS-002"));
|
||||
assertThat(repo.findBySku("NOPE")).isEmpty().isEqualTo(old.findBySku("NOPE"));
|
||||
var max = new BigDecimal("4000");
|
||||
assertThat(repo.findInStockCheaperThan(max)).isEqualTo(old.findInStockCheaperThan(max));
|
||||
var skus = List.of("KB-001", "WC-005");
|
||||
assertThat(repo.findBySkus(skus)).isEqualTo(old.findBySkus(skus));
|
||||
assertThat(repo.updateStock(1, 99)).isEqualTo(old.updateStock(1, 99)).isEqualTo(1);
|
||||
|
||||
new Transcript("01-same-results.txt")
|
||||
.line("findBySku(\"MS-002\") JdbcClient == JdbcTemplate: %s", true)
|
||||
.line("findBySku(\"NOPE\") both Optional.empty: %s", true)
|
||||
.line("findInStockCheaperThan(4000) rows: %d, identical: %s", repo.findInStockCheaperThan(max).size(), true)
|
||||
.line("findBySkus([KB-001, WC-005]) rows: %d, identical: %s", repo.findBySkus(skus).size(), true)
|
||||
.line("updateStock(1, 99) rows updated by each: 1")
|
||||
.line("")
|
||||
.line("First row returned by findBySku(\"MS-002\"):")
|
||||
.line(" %s", repo.findBySku("MS-002").orElseThrow())
|
||||
.write();
|
||||
}
|
||||
|
||||
@Test
|
||||
void whatTheApiHasAndLacks() throws Exception {
|
||||
TreeSet<String> names = new TreeSet<>();
|
||||
for (Class<?> c : List.of(JdbcClient.class, JdbcClient.StatementSpec.class,
|
||||
JdbcClient.MappedQuerySpec.class, JdbcClient.ResultQuerySpec.class)) {
|
||||
for (Method m : c.getMethods()) names.add(c.getSimpleName() + "." + m.getName());
|
||||
}
|
||||
boolean anyBatch = names.stream().anyMatch(n -> n.toLowerCase().contains("batch"));
|
||||
assertThat(anyBatch).isFalse();
|
||||
|
||||
String[] beans = ctx.getBeanNamesForType(JdbcClient.class);
|
||||
Object impl = ctx.getBean(JdbcClient.class);
|
||||
var t = new Transcript("02-api-surface.txt");
|
||||
t.line("methods on JdbcClient and its three spec interfaces, read by reflection (%d names):", names.size());
|
||||
names.forEach(n -> t.line(" " + n));
|
||||
t.line("");
|
||||
t.line("any method with 'batch' in its name: %s", anyBatch);
|
||||
t.line("");
|
||||
t.line("beans of type JdbcClient in the Boot context: %d (%s)", beans.length, Arrays.toString(beans));
|
||||
t.line("implementation class: %s", impl.getClass().getName());
|
||||
t.line("beans Boot also provides: JdbcTemplate=%s NamedParameterJdbcTemplate=%s",
|
||||
ctx.getBeanNamesForType(JdbcTemplate.class).length == 1,
|
||||
ctx.getBeanNamesForType(NamedParameterJdbcTemplate.class).length == 1);
|
||||
t.write();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.ankurm.jdbcclient;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
class MappingTest extends Base {
|
||||
|
||||
/** Same data, three different Java shapes. */
|
||||
record Slim(String sku, String name) { }
|
||||
static class Bean {
|
||||
private String sku;
|
||||
private BigDecimal price;
|
||||
private boolean inStock;
|
||||
public void setSku(String v) { sku = v; }
|
||||
public void setPrice(BigDecimal v) { price = v; }
|
||||
public void setInStock(boolean v) { inStock = v; }
|
||||
@Override public String toString() { return "Bean[sku=" + sku + ", price=" + price + ", inStock=" + inStock + "]"; }
|
||||
}
|
||||
record WithOptionalCol(String sku, String colourName) { }
|
||||
record WithPrimitive(String sku, int missingCol) { }
|
||||
record Wrong(String sku, LocalDate name) { }
|
||||
record NullPrim(String sku, int stockCount) { }
|
||||
record NullBoxed(String sku, Integer stockCount) { }
|
||||
|
||||
@Test
|
||||
void mapping() throws Exception {
|
||||
var t = new Transcript("04-mapping.txt");
|
||||
|
||||
List<Product> all = jdbc.sql("SELECT * FROM product ORDER BY id").query(Product.class).list();
|
||||
assertThat(all).hasSize(5);
|
||||
assertThat(all.get(2).inStock()).isFalse();
|
||||
assertThat(all.get(0).createdOn()).isEqualTo(LocalDate.of(2026, 1, 10));
|
||||
t.line("1 SELECT * into the Product record (in_stock -> inStock, created_on -> createdOn, stock_count -> stockCount):");
|
||||
all.forEach(p -> t.line(" %s", p));
|
||||
|
||||
var slim = jdbc.sql("SELECT sku, name FROM product WHERE id = 1").query(Slim.class).single();
|
||||
t.line("").line("2 a record with fewer components than columns: %s", slim);
|
||||
|
||||
var bean = jdbc.sql("SELECT * FROM product WHERE id = 1").query(Bean.class).single();
|
||||
t.line("3 a JavaBean with setters for three of the seven columns: %s", bean);
|
||||
|
||||
var ints = jdbc.sql("SELECT stock_count FROM product ORDER BY id").query(Integer.class).list();
|
||||
var one = jdbc.sql("SELECT name FROM product WHERE id = 2").query(String.class).single();
|
||||
t.line("4 a single column to a simple type: %s and %s", ints, one);
|
||||
|
||||
var lambda = jdbc.sql("SELECT sku, price FROM product WHERE id = 2")
|
||||
.query((rs, n) -> rs.getString("sku") + " costs " + rs.getBigDecimal("price"))
|
||||
.single();
|
||||
t.line("5 a RowMapper lambda: %s", lambda);
|
||||
|
||||
// column missing for a reference-typed component
|
||||
Throwable missingRef = catchThrowable(() -> jdbc.sql("SELECT sku FROM product WHERE id = 1").query(WithOptionalCol.class).single());
|
||||
assertThat(missingRef).isNotNull();
|
||||
t.line("").line("6 record asks for colourName, SELECT has no such column: %s", Transcript.oneLine(missingRef));
|
||||
|
||||
// column missing for a primitive component
|
||||
Throwable prim = catchThrowable(() -> jdbc.sql("SELECT sku FROM product WHERE id = 1").query(WithPrimitive.class).single());
|
||||
assertThat(prim).isNotNull();
|
||||
t.line("7 record asks for primitive int missingCol, no such column: %s", Transcript.oneLine(prim));
|
||||
|
||||
// wrong type
|
||||
Throwable wrong = catchThrowable(() -> jdbc.sql("SELECT sku, name FROM product WHERE id = 1").query(Wrong.class).single());
|
||||
assertThat(wrong).isNotNull();
|
||||
t.line("8 VARCHAR column into a LocalDate component: %s", Transcript.oneLine(wrong));
|
||||
|
||||
// SQL NULL into a primitive (a literal NULL, so the table is left alone)
|
||||
Throwable nul = catchThrowable(() -> jdbc.sql("SELECT sku, CAST(NULL AS INT) AS stock_count FROM product WHERE id = 1")
|
||||
.query(NullPrim.class).single());
|
||||
assertThat(nul).isNotNull();
|
||||
t.line("9 SQL NULL into the primitive int stockCount: %s", Transcript.oneLine(nul));
|
||||
var nullBoxed = jdbc.sql("SELECT sku, CAST(NULL AS INT) AS stock_count FROM product WHERE id = 1")
|
||||
.query(NullBoxed.class).single();
|
||||
assertThat(nullBoxed.stockCount()).isNull();
|
||||
t.line(" the same NULL into Integer stockCount: %s", nullBoxed);
|
||||
|
||||
// untyped
|
||||
var rows = jdbc.sql("SELECT sku, in_stock FROM product WHERE id = 1").query().listOfRows();
|
||||
t.line("").line("10 untyped listOfRows(): keys as the driver returns them: %s, value classes: %s",
|
||||
rows.get(0).keySet(), rows.get(0).values().stream().map(v -> v.getClass().getSimpleName()).toList());
|
||||
t.line(" lookup is case-insensitive: row.get(\"sku\") = %s", rows.get(0).get("sku"));
|
||||
assertThat(rows.get(0).get("sku")).isEqualTo("KB-001");
|
||||
t.write();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.ankurm.jdbcclient;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Types;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
class ParametersTest extends Base {
|
||||
|
||||
@Test
|
||||
void waysToPassParameters() throws Exception {
|
||||
var t = new Transcript("03-parameters.txt");
|
||||
|
||||
// 1. positional ?
|
||||
var a = jdbc.sql("SELECT name FROM product WHERE sku = ? AND in_stock = ?")
|
||||
.param("KB-001").param(true).query(String.class).list();
|
||||
// 2. positional by index
|
||||
var b = jdbc.sql("SELECT name FROM product WHERE sku = ?").param(1, "KB-001").query(String.class).list();
|
||||
// 3. a list
|
||||
var c = jdbc.sql("SELECT name FROM product WHERE price < ? AND in_stock = ? ORDER BY price")
|
||||
.params(List.of(new BigDecimal("3000"), true)).query(String.class).list();
|
||||
// 4. named
|
||||
var d = jdbc.sql("SELECT name FROM product WHERE sku = :sku").param("sku", "KB-001").query(String.class).list();
|
||||
// 5. a map
|
||||
var e = jdbc.sql("SELECT name FROM product WHERE sku = :sku AND price > :min")
|
||||
.params(Map.of("sku", "KB-001", "min", 100)).query(String.class).list();
|
||||
// 6. a record, read component by component
|
||||
record Filter(String sku, boolean inStock) { }
|
||||
var f = jdbc.sql("SELECT name FROM product WHERE sku = :sku AND in_stock = :inStock")
|
||||
.paramSource(new Filter("KB-001", true)).query(String.class).list();
|
||||
// 7. the same name used twice
|
||||
var g = jdbc.sql("SELECT sku FROM product WHERE price < :p OR stock_count > :p ORDER BY id")
|
||||
.param("p", 10).query(String.class).list();
|
||||
// 8. IN list
|
||||
var h = jdbc.sql("SELECT sku FROM product WHERE sku IN (:skus) ORDER BY id")
|
||||
.param("skus", List.of("KB-001", "WC-005", "NOPE")).query(String.class).list();
|
||||
// 9. LIKE needs the wildcard in the value, not in the SQL string
|
||||
var i = jdbc.sql("SELECT name FROM product WHERE name LIKE :q ORDER BY id")
|
||||
.param("q", "%o%").query(String.class).list();
|
||||
|
||||
assertThat(a).containsExactly("Mechanical Keyboard");
|
||||
assertThat(b).isEqualTo(a);
|
||||
assertThat(c).containsExactly("Wireless Mouse", "Headset");
|
||||
assertThat(d).isEqualTo(a);
|
||||
assertThat(e).isEqualTo(a);
|
||||
assertThat(f).isEqualTo(a);
|
||||
assertThat(g).containsExactly("KB-001", "MS-002");
|
||||
assertThat(h).containsExactly("KB-001", "WC-005");
|
||||
assertThat(i).containsExactly("Mechanical Keyboard", "Wireless Mouse", "Monitor 27 inch");
|
||||
|
||||
t.line("1 .param(v).param(v) ? placeholders -> %s", a);
|
||||
t.line("2 .param(1, v) by index -> %s", b);
|
||||
t.line("3 .params(List.of(..)) ? placeholders -> %s", c);
|
||||
t.line("4 .param(\"sku\", v) :named -> %s", d);
|
||||
t.line("5 .params(Map.of(..)) :named -> %s", e);
|
||||
t.line("6 .paramSource(record) :named, record -> %s", f);
|
||||
t.line("7 :p used twice, one .param(\"p\", 10) :named -> %s", g);
|
||||
t.line("8 IN (:skus) with a 3-element list expanded -> %s (NOPE matched nothing)", h);
|
||||
t.line("9 LIKE :q with \"%%o%%\" wildcard in value -> %s", i);
|
||||
|
||||
// 10. mixing the two styles
|
||||
Throwable mix = catchThrowable(() -> jdbc.sql("SELECT name FROM product WHERE sku = :sku AND in_stock = ?")
|
||||
.param("sku", "KB-001").param(true).query(String.class).list());
|
||||
assertThat(mix).isNotNull();
|
||||
t.line("").line("10 :named and ? in one statement -> %s", Transcript.oneLine(mix));
|
||||
|
||||
// 11. a named parameter that was never supplied
|
||||
Throwable missing = catchThrowable(() -> jdbc.sql("SELECT name FROM product WHERE sku = :sku")
|
||||
.param("skuu", "KB-001").query(String.class).list());
|
||||
assertThat(missing).isNotNull();
|
||||
t.line("11 typo in the parameter name (:sku, supplied skuu) -> %s", Transcript.oneLine(missing));
|
||||
|
||||
// 12. too few positional parameters
|
||||
Throwable few = catchThrowable(() -> jdbc.sql("SELECT name FROM product WHERE sku = ? AND in_stock = ?")
|
||||
.param("KB-001").query(String.class).list());
|
||||
assertThat(few).isNotNull();
|
||||
t.line("12 two ? but one value -> %s", Transcript.oneLine(few));
|
||||
|
||||
// 13. null
|
||||
var n1 = jdbc.sql("SELECT name FROM product WHERE sku = :sku")
|
||||
.param("sku", null).query(String.class).list();
|
||||
var n2 = jdbc.sql("SELECT name FROM product WHERE sku = :sku")
|
||||
.param("sku", null, Types.VARCHAR).query(String.class).list();
|
||||
t.line("13 .param(\"sku\", null) -> ran, rows: %d (= NULL is never true)", n1.size());
|
||||
t.line(" .param(\"sku\", null, Types.VARCHAR) -> ran, rows: %d (= NULL is never true)", n2.size());
|
||||
t.write();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.ankurm.jdbcclient;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
class ResultShapesTest extends Base {
|
||||
|
||||
@Test
|
||||
void singleOptionalListSetStream() throws Exception {
|
||||
var t = new Transcript("05-result-shapes.txt");
|
||||
String one = "SELECT name FROM product WHERE id = 1";
|
||||
String none = "SELECT name FROM product WHERE id = 999";
|
||||
String many = "SELECT name FROM product WHERE in_stock = TRUE ORDER BY id";
|
||||
|
||||
t.line(" 0 rows 1 row 4 rows");
|
||||
row(t, "list()", none, one, many, "list");
|
||||
row(t, "single()", none, one, many, "single");
|
||||
row(t, "optional()", none, one, many, "optional");
|
||||
row(t, "set()", none, one, many, "set");
|
||||
|
||||
Throwable e0 = catchThrowable(() -> jdbc.sql(none).query(String.class).single());
|
||||
Throwable e4 = catchThrowable(() -> jdbc.sql(many).query(String.class).single());
|
||||
Throwable o4 = catchThrowable(() -> jdbc.sql(many).query(String.class).optional());
|
||||
assertThat(e0).isInstanceOf(org.springframework.dao.EmptyResultDataAccessException.class);
|
||||
assertThat(e4).isInstanceOf(org.springframework.dao.IncorrectResultSizeDataAccessException.class);
|
||||
assertThat(o4).isInstanceOf(org.springframework.dao.IncorrectResultSizeDataAccessException.class);
|
||||
assertThat(e0).isInstanceOf(org.springframework.dao.IncorrectResultSizeDataAccessException.class);
|
||||
|
||||
t.line("").line("single() on 0 rows: %s", Transcript.oneLine(e0));
|
||||
t.line("single() on 4 rows: %s", Transcript.oneLine(e4));
|
||||
t.line("EmptyResultDataAccessException extends IncorrectResultSizeDataAccessException: %s", true);
|
||||
|
||||
// singleValue / optionalValue on the untyped spec
|
||||
Object v = jdbc.sql("SELECT COUNT(*) FROM product").query().singleValue();
|
||||
t.line("").line("untyped singleValue() of COUNT(*): %s (%s)", v, v.getClass().getSimpleName());
|
||||
var ov = jdbc.sql("SELECT name FROM product WHERE id = 999").query().optionalValue();
|
||||
t.line("untyped optionalValue() with no row: %s", ov);
|
||||
|
||||
// 'SELECT MAX(..)' on an empty set is still one row holding NULL
|
||||
var max = jdbc.sql("SELECT MAX(price) FROM product WHERE id = 999").query(java.math.BigDecimal.class).optional();
|
||||
t.line("optional() over SELECT MAX(price) with no matching rows: %s", max);
|
||||
Throwable maxSingle = catchThrowable(() -> jdbc.sql("SELECT MAX(price) FROM product WHERE id = 999")
|
||||
.query(java.math.BigDecimal.class).single());
|
||||
t.line("single() over the same query: %s",
|
||||
maxSingle == null ? "returned null" : Transcript.oneLine(maxSingle));
|
||||
t.write();
|
||||
}
|
||||
|
||||
private void row(Transcript t, String label, String none, String one, String many, String how) {
|
||||
t.line("%-20s %-30s %-12s %s", label, run(none, how), run(one, how), run(many, how));
|
||||
}
|
||||
|
||||
private String run(String sql, String how) {
|
||||
try {
|
||||
var q = jdbc.sql(sql).query(String.class);
|
||||
Object r = switch (how) {
|
||||
case "list" -> q.list();
|
||||
case "single" -> q.single();
|
||||
case "optional" -> q.optional();
|
||||
default -> q.set();
|
||||
};
|
||||
if (r instanceof java.util.Collection<?> c && c.size() > 1) return c.size() + " items";
|
||||
return String.valueOf(r);
|
||||
} catch (DataAccessException e) {
|
||||
return e.getClass().getSimpleName().replace("DataAccessException", "..");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.ankurm.jdbcclient;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.jdbc.CannotGetJdbcConnectionException;
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
/** A pool of two connections that gives up after half a second makes a leak visible in a unit test. */
|
||||
@SpringBootTest(properties = {
|
||||
"spring.datasource.hikari.maximum-pool-size=2",
|
||||
"spring.datasource.hikari.connection-timeout=500"})
|
||||
class StreamAndLimitsTest extends Base {
|
||||
|
||||
@Autowired ProductRepository repo;
|
||||
|
||||
@Test
|
||||
void unclosedStreamsExhaustThePool() throws Exception {
|
||||
var t = new Transcript("10-stream-leak.txt");
|
||||
t.line("Hikari pool: maximum-pool-size=2, connection-timeout=500 ms");
|
||||
t.line("rows in the table, via count(): %d", repo.count());
|
||||
|
||||
Stream<Product> s1 = repo.streamAll(); // never closed
|
||||
Stream<Product> s2 = repo.streamAll(); // never closed
|
||||
long t0 = System.nanoTime();
|
||||
Throwable starved = catchThrowable(repo::count);
|
||||
long ms = (System.nanoTime() - t0) / 1_000_000;
|
||||
assertThat(starved).isInstanceOf(CannotGetJdbcConnectionException.class);
|
||||
t.line("two streamAll() calls left open, then one ordinary count():");
|
||||
t.line(" -> %s after about %d ms", starved.getClass().getSimpleName(), (ms / 100) * 100);
|
||||
Throwable root = starved;
|
||||
while (root.getCause() != null) root = root.getCause();
|
||||
t.line(" root cause: %s", root.getMessage().replaceAll("^HikariPool-\\d+", "HikariPool-N").replaceAll("\\(total=.*", "(...)"));
|
||||
|
||||
s1.close();
|
||||
s2.close();
|
||||
t.line("after closing both streams, count() works again: %d", repo.count());
|
||||
assertThat(repo.count()).isEqualTo(5);
|
||||
|
||||
try (Stream<Product> ok = repo.streamAll()) {
|
||||
t.line("try-with-resources: names of rows 1..2: %s", ok.limit(2).map(Product::name).toList());
|
||||
}
|
||||
t.line("and the connection is back: count() = %d", repo.count());
|
||||
t.write();
|
||||
}
|
||||
|
||||
@Test
|
||||
void maxRowsSilentlyTruncates() throws Exception {
|
||||
var t = new Transcript("11-limits.txt");
|
||||
List<String> all = jdbc.sql("SELECT sku FROM product ORDER BY id").query(String.class).list();
|
||||
List<String> capped = jdbc.sql("SELECT sku FROM product ORDER BY id").withMaxRows(2).query(String.class).list();
|
||||
assertThat(all).hasSize(5);
|
||||
assertThat(capped).hasSize(2);
|
||||
t.line("5 rows in the table");
|
||||
t.line("list() -> %d rows", all.size());
|
||||
t.line("withMaxRows(2).list() -> %d rows %s (no warning, no exception)", capped.size(), capped);
|
||||
|
||||
long t0 = System.nanoTime();
|
||||
Throwable slow = catchThrowable(() -> jdbc.sql(
|
||||
"SELECT COUNT(*) FROM SYSTEM_RANGE(1, 2000000000) a, SYSTEM_RANGE(1, 1000) b")
|
||||
.withQueryTimeout(1).query(Long.class).single());
|
||||
long elapsedMs = (System.nanoTime() - t0) / 1_000_000;
|
||||
assertThat(slow).isNotNull();
|
||||
t.line("a query that would run for minutes with withQueryTimeout(1) -> %s (about %d s)",
|
||||
slow.getClass().getSimpleName(), Math.round(elapsedMs / 1000.0));
|
||||
t.write();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.ankurm.jdbcclient;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/** spring.jdbc.template.* is documented for JdbcTemplate. Does the auto-configured JdbcClient inherit it? */
|
||||
@SpringBootTest(properties = "spring.jdbc.template.max-rows=2")
|
||||
class TemplatePropertiesTest extends Base {
|
||||
|
||||
@Test
|
||||
void jdbcClientInheritsTemplateProperties() throws Exception {
|
||||
int viaClient = jdbc.sql("SELECT sku FROM product").query(String.class).list().size();
|
||||
assertThat(viaClient).isEqualTo(2);
|
||||
new Transcript("12-template-properties.txt")
|
||||
.line("spring.jdbc.template.max-rows=2 in application properties, 5 rows in the table")
|
||||
.line("auto-configured JdbcClient: SELECT sku FROM product -> %d rows", viaClient)
|
||||
.write();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.ankurm.jdbcclient;
|
||||
|
||||
import org.springframework.jdbc.core.simple.JdbcClient;
|
||||
|
||||
/** Puts the product table back to the five seed rows with ids 1..5. */
|
||||
final class TestData {
|
||||
static void reset(JdbcClient jdbc) {
|
||||
jdbc.sql("TRUNCATE TABLE product RESTART IDENTITY").update();
|
||||
jdbc.sql("""
|
||||
INSERT INTO product (sku, name, price, in_stock, created_on, stock_count) VALUES
|
||||
('KB-001', 'Mechanical Keyboard', 4999.00, TRUE, DATE '2026-01-10', 12),
|
||||
('MS-002', 'Wireless Mouse', 1299.50, TRUE, DATE '2026-02-14', 40),
|
||||
('MN-003', 'Monitor 27 inch', 18999.00, FALSE, DATE '2026-03-01', 0),
|
||||
('HS-004', 'Headset', 2499.00, TRUE, DATE '2026-03-22', 7),
|
||||
('WC-005', 'Webcam', 3199.00, TRUE, DATE '2026-04-05', 3)
|
||||
""").update();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.ankurm.jdbcclient;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
class TransactionTest extends Base {
|
||||
|
||||
@Autowired StockService stock;
|
||||
@Autowired PlatformTransactionManager tm;
|
||||
|
||||
private int stockOf(long id) {
|
||||
return jdbc.sql("SELECT stock_count FROM product WHERE id = :id").param("id", id).query(Integer.class).single();
|
||||
}
|
||||
|
||||
@Test
|
||||
void transactionalVsNot() throws Exception {
|
||||
var t = new Transcript("09-transactions.txt");
|
||||
// product 5 (Webcam) has 3 in stock, product 1 (keyboard) has 12. Move 5 from the webcam: the
|
||||
// second UPDATE would take it to -2 and the CHECK constraint rejects that.
|
||||
t.line("start: keyboard(1)=%d webcam(5)=%d", stockOf(1), stockOf(5));
|
||||
|
||||
Throwable a = catchThrowable(() -> stock.moveStockAtomic(5, 1, 5));
|
||||
assertThat(a).isInstanceOf(DataIntegrityViolationException.class);
|
||||
t.line("@Transactional move of 5 from webcam to keyboard -> %s", a.getClass().getSimpleName());
|
||||
t.line(" after: keyboard(1)=%d webcam(5)=%d (both UPDATEs rolled back)", stockOf(1), stockOf(5));
|
||||
assertThat(stockOf(1)).isEqualTo(12);
|
||||
assertThat(stockOf(5)).isEqualTo(3);
|
||||
|
||||
Throwable b = catchThrowable(() -> stock.moveStockNoTx(5, 1, 5));
|
||||
assertThat(b).isInstanceOf(DataIntegrityViolationException.class);
|
||||
t.line("same body, no @Transactional -> %s", b.getClass().getSimpleName());
|
||||
t.line(" after: keyboard(1)=%d webcam(5)=%d (the first UPDATE had already committed)", stockOf(1), stockOf(5));
|
||||
assertThat(stockOf(1)).isEqualTo(17);
|
||||
assertThat(stockOf(5)).isEqualTo(3);
|
||||
|
||||
TestData.reset(jdbc);
|
||||
var tx = new TransactionTemplate(tm);
|
||||
Throwable c = catchThrowable(() -> tx.executeWithoutResult(s -> {
|
||||
jdbc.sql("UPDATE product SET stock_count = 100 WHERE id = 2").update();
|
||||
throw new IllegalStateException("boom");
|
||||
}));
|
||||
t.line("TransactionTemplate, UPDATE then RuntimeException -> %s; mouse(2)=%d (was 40)", c.getClass().getSimpleName(), stockOf(2));
|
||||
assertThat(stockOf(2)).isEqualTo(40);
|
||||
|
||||
var seen = new int[1];
|
||||
tx.executeWithoutResult(s -> {
|
||||
jdbc.sql("UPDATE product SET stock_count = 55 WHERE id = 2").update();
|
||||
seen[0] = stockOf(2);
|
||||
});
|
||||
t.line("inside a transaction a later SELECT sees the earlier UPDATE: %d; after commit: %d", seen[0], stockOf(2));
|
||||
t.write();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.ankurm.jdbcclient;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/** Writes output/NN-name.txt. The tests assert the same facts the transcript prints. */
|
||||
final class Transcript {
|
||||
private final StringBuilder sb = new StringBuilder();
|
||||
private final String file;
|
||||
|
||||
Transcript(String file) {
|
||||
this.file = file;
|
||||
}
|
||||
|
||||
Transcript line(String s) {
|
||||
sb.append(s).append('\n');
|
||||
return this;
|
||||
}
|
||||
|
||||
Transcript line(String fmt, Object... args) {
|
||||
return line(String.format(fmt, args));
|
||||
}
|
||||
|
||||
void write() throws IOException {
|
||||
Path dir = Path.of("output");
|
||||
Files.createDirectories(dir);
|
||||
Files.writeString(dir.resolve(file), sb.toString());
|
||||
}
|
||||
|
||||
static String oneLine(Throwable t) {
|
||||
String m = String.valueOf(t.getMessage()).replace('\n', ' ').replaceAll("\\s+", " ");
|
||||
Throwable root = t;
|
||||
while (root.getCause() != null && root.getCause() != root) root = root.getCause();
|
||||
String r = root == t ? "" : " [root cause: " + root.getClass().getSimpleName() + ": "
|
||||
+ String.valueOf(root.getMessage()).replace('\n', ' ').replaceAll("\\s+", " ") + "]";
|
||||
return t.getClass().getName() + ": " + m + r;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.ankurm.jdbcclient;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.jdbc.BadSqlGrammarException;
|
||||
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
|
||||
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
|
||||
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
|
||||
import org.springframework.jdbc.support.GeneratedKeyHolder;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.catchThrowable;
|
||||
|
||||
class WritesTest extends Base {
|
||||
|
||||
@Autowired ProductRepository repo;
|
||||
@Autowired NamedParameterJdbcTemplate named;
|
||||
|
||||
@Test
|
||||
void generatedKeys() throws Exception {
|
||||
var t = new Transcript("06-generated-keys.txt");
|
||||
long id = repo.insert(new Product(null, "NEW-006", "Desk Lamp", new BigDecimal("899.00"), true, null, 5));
|
||||
assertThat(id).isEqualTo(6);
|
||||
t.line("insert via paramSource(record) and update(keys, \"id\"): generated id = %d", id);
|
||||
|
||||
var keys = new GeneratedKeyHolder();
|
||||
jdbc.sql("INSERT INTO product (sku, name, price) VALUES ('NEW-007', 'Cable', 99.00)").update(keys);
|
||||
t.line("update(keys) with no column names: key columns = %s", keys.getKeys().keySet());
|
||||
var keys2 = new GeneratedKeyHolder();
|
||||
jdbc.sql("INSERT INTO product (sku, name, price) VALUES ('NEW-008', 'Hub', 1999.00)").update(keys2, "id");
|
||||
t.line("update(keys, \"id\"): key columns = %s, id = %s", keys2.getKeys().keySet(), keys2.getKey());
|
||||
var row = jdbc.sql("SELECT created_on, in_stock, stock_count FROM product WHERE sku = 'NEW-008'").query().singleRow();
|
||||
t.line("a row inserted without created_on / in_stock / stock_count got the column defaults: in_stock=%s stock_count=%s created_on=today: %s",
|
||||
row.get("IN_STOCK"), row.get("STOCK_COUNT"), java.time.LocalDate.now().equals(((java.sql.Date) row.get("CREATED_ON")).toLocalDate()));
|
||||
t.line("rows now in the table: %d", repo.count());
|
||||
assertThat(repo.count()).isEqualTo(8);
|
||||
t.write();
|
||||
}
|
||||
|
||||
@Test
|
||||
void batchHasToGoThroughNamedParameterJdbcTemplate() throws Exception {
|
||||
var t = new Transcript("07-batch.txt");
|
||||
int n = 2000;
|
||||
List<Product> items = new ArrayList<>();
|
||||
for (int i = 0; i < n; i++) {
|
||||
items.add(new Product(null, "B-" + i, "Bulk " + i, new BigDecimal("10.00"), true, null, 1));
|
||||
}
|
||||
String sql = "INSERT INTO product (sku, name, price, in_stock, stock_count) VALUES (:sku, :name, :price, :inStock, :stockCount)";
|
||||
|
||||
long t0 = System.nanoTime();
|
||||
for (Product p : items) jdbc.sql(sql).paramSource(p).update();
|
||||
long loopMs = (System.nanoTime() - t0) / 1_000_000;
|
||||
assertThat(repo.count()).isEqualTo(5 + n);
|
||||
|
||||
jdbc.sql("DELETE FROM product WHERE sku LIKE 'B-%'").update();
|
||||
|
||||
t0 = System.nanoTime();
|
||||
SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(items);
|
||||
int[] counts = named.batchUpdate(sql, batch);
|
||||
long batchMs = (System.nanoTime() - t0) / 1_000_000;
|
||||
assertThat(counts).hasSize(n);
|
||||
assertThat(Arrays.stream(counts).allMatch(c -> c == 1 || c == java.sql.Statement.SUCCESS_NO_INFO)).isTrue();
|
||||
assertThat(repo.count()).isEqualTo(5 + n);
|
||||
|
||||
t.line("%d inserts into in-memory H2 (no network round trip, so the gap understates a real database):", n);
|
||||
t.line(" a loop of jdbc.sql(..).update() : finished (timing varies per run, not asserted)");
|
||||
t.line(" one NamedParameterJdbcTemplate.batchUpdate: finished, %d result codes returned", counts.length);
|
||||
t.line(" loop took more than batch (indicative, one run): %s", loopMs > batchMs);
|
||||
t.line("rows in the table after the batch: %d (5 seed rows + %d)", repo.count(), n);
|
||||
t.write();
|
||||
}
|
||||
|
||||
@Test
|
||||
void exceptionTranslation() throws Exception {
|
||||
var t = new Transcript("08-exceptions.txt");
|
||||
Throwable dup = catchThrowable(() -> jdbc.sql("INSERT INTO product (sku, name, price) VALUES ('KB-001', 'dup', 1)").update());
|
||||
assertThat(dup).isInstanceOf(DuplicateKeyException.class);
|
||||
t.line("duplicate unique value -> %s", brief(dup));
|
||||
|
||||
Throwable nul = catchThrowable(() -> jdbc.sql("INSERT INTO product (sku, name, price) VALUES ('X-1', NULL, 1)").update());
|
||||
assertThat(nul).isInstanceOf(DataIntegrityViolationException.class);
|
||||
t.line("NULL into a NOT NULL column -> %s", brief(nul));
|
||||
|
||||
Throwable check = catchThrowable(() -> jdbc.sql("UPDATE product SET stock_count = -1 WHERE id = 1").update());
|
||||
assertThat(check).isInstanceOf(DataIntegrityViolationException.class);
|
||||
t.line("CHECK constraint violated -> %s", brief(check));
|
||||
|
||||
Throwable bad = catchThrowable(() -> jdbc.sql("SELEC * FROM product").query(Product.class).list());
|
||||
assertThat(bad).isInstanceOf(BadSqlGrammarException.class);
|
||||
t.line("typo in the SQL -> %s", brief(bad));
|
||||
t.line("all four are unchecked DataAccessException subclasses: %s",
|
||||
List.of(dup, nul, check, bad).stream().allMatch(e -> e instanceof org.springframework.dao.DataAccessException));
|
||||
t.write();
|
||||
}
|
||||
|
||||
private static String brief(Throwable e) {
|
||||
Throwable root = e;
|
||||
while (root.getCause() != null) root = root.getCause();
|
||||
java.sql.SQLException sql = root instanceof java.sql.SQLException s ? s : null;
|
||||
return e.getClass().getSimpleName() + " (database said SQLState " + (sql == null ? "?" : sql.getSQLState()) + ")";
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user