Add the transactions module, and move the migration project under migration-behavior/
The repository now aggregates two independent modules. migration-behavior/ is the
original project, moved unchanged; it stays on Spring Boot 4.0.6 / JDK 21 because
that is what the four published migration articles were verified against, and
upgrading it would silently invalidate output they quote. The article-tagged trees
are untouched, so links into a tag are unaffected.
transactions/ Companion code for "@Transactional in Spring: Propagation, Isolation,
and the Six Ways It Silently Does Nothing". Spring Boot 4.1.1 / JDK 25.
Every row of the propagation matrix is produced by calling the method and asking the
transaction manager what it did. The transaction NAME is the exhibit: a scope that
joined reports its caller's name, a scope that started its own reports its own.
Three things the transcripts settle:
- Propagation.NESTED cannot be used with JpaTransactionManager. It fails twice,
with two different messages, the second of which blames your JPA provider. The
savepoint manager comes from the object the JpaDialect returns when it begins the
transaction, and Hibernate's does not implement one. It works on
DataSourceTransactionManager, because a savepoint is a JDBC concept -- shown
working there rather than only failing here.
- Catching a REQUIRED inner failure does not save the transaction. The inner scope
has already marked it rollback-only, so the commit throws
UnexpectedRollbackException from a place with no connection to the cause.
- A checked exception commits, and so does a swallowed one. Those two do not merely
fail to start a transaction; they commit work the code was abandoning.
19 contract tests, six captured transcripts, all regenerated by scripts/run-all.sh.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gip4srpzMwjgoba6uEfbr5
This commit is contained in:
43
transactions/scripts/demo-isolation.sh
Executable file
43
transactions/scripts/demo-isolation.sh
Executable file
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env bash
|
||||
# Isolation and read-only: honoured where the transaction starts, ignored where it joins.
|
||||
set -euo pipefail
|
||||
set +m
|
||||
cd "$(dirname "$0")/.."
|
||||
source scripts/env.sh
|
||||
{
|
||||
echo "== isolation and readOnly =="
|
||||
echo
|
||||
start_app > /dev/null
|
||||
curl -s "http://127.0.0.1:${APP_PORT}/tx/isolation" | python3 -c '
|
||||
import json,sys
|
||||
d=json.load(sys.stdin)
|
||||
def show(label, s):
|
||||
print(" %-46s active=%-5s readOnly=%-5s isolation=%s" % (
|
||||
label, s["actualTransactionActive"], s["readOnly"], s["isolationLevel"]))
|
||||
show("@Transactional(readOnly = true)", d["readOnlyScope"])
|
||||
print()
|
||||
show("@Transactional(isolation = SERIALIZABLE) [outer]", d["serializableOuter"]["outer"])
|
||||
show(" REQUIRED inner joining it", d["serializableOuter"]["inner"])
|
||||
print()
|
||||
show("plain @Transactional [outer]", d["participantDeclaringReadUncommitted"]["outer"])
|
||||
show(" inner declaring READ_UNCOMMITTED", d["participantDeclaringReadUncommitted"]["inner"])'
|
||||
echo
|
||||
echo "The last pair is the point. The inner method declares"
|
||||
echo "@Transactional(isolation = READ_UNCOMMITTED) and gets ISOLATION_DEFAULT, because it"
|
||||
echo "joined an existing physical transaction whose isolation was fixed when it began."
|
||||
echo "The declaration is not rejected and nothing is logged -- it is simply ignored."
|
||||
echo
|
||||
echo "Set validateExistingTransaction=true on the transaction manager and this becomes an"
|
||||
echo "exception instead of a silent no-op. It is off by default."
|
||||
echo
|
||||
echo "The same applies to readOnly and timeout on a participating scope."
|
||||
echo
|
||||
echo "== the transaction manager's own log lines =="
|
||||
echo
|
||||
grep -E "Creating new transaction|Participating in existing" "$LOG" | tidy | head -12
|
||||
echo
|
||||
echo "Note ISOLATION_SERIALIZABLE appears on the 'Creating new transaction' line and never"
|
||||
echo "on a 'Participating' one: participation carries no settings of its own."
|
||||
stop_app
|
||||
} > docs/output/05-isolation.txt 2>&1
|
||||
cat docs/output/05-isolation.txt
|
||||
46
transactions/scripts/demo-nested.sh
Executable file
46
transactions/scripts/demo-nested.sh
Executable file
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env bash
|
||||
# Can you actually use Propagation.NESTED with Spring Data JPA? Three attempts.
|
||||
set -euo pipefail
|
||||
set +m
|
||||
cd "$(dirname "$0")/.."
|
||||
source scripts/env.sh
|
||||
{
|
||||
echo "== attempt 1: a stock Spring Boot JPA application =="
|
||||
echo "\$ java -jar $JAR"
|
||||
echo
|
||||
start_app > /dev/null
|
||||
curl -s "http://127.0.0.1:${APP_PORT}/tx/propagation" | python3 -c '
|
||||
import json,sys
|
||||
v=json.load(sys.stdin)["NESTED"]["withOuterTransaction"]
|
||||
print(" " + v.get("exception","(no exception)"))
|
||||
print(" " + v.get("message",""))'
|
||||
echo
|
||||
echo "== attempt 2: nestedTransactionAllowed = true, as the message instructs =="
|
||||
echo "\$ java -jar $JAR --demo.nested-allowed=true"
|
||||
echo
|
||||
start_app --demo.nested-allowed=true > /dev/null
|
||||
curl -s "http://127.0.0.1:${APP_PORT}/tx/propagation" | python3 -c '
|
||||
import json,sys
|
||||
v=json.load(sys.stdin)["NESTED"]["withOuterTransaction"]
|
||||
print(" " + v.get("exception","(no exception)"))
|
||||
print(" " + v.get("message",""))'
|
||||
echo
|
||||
echo "A different message, from a second check. The savepoint manager is obtained from the"
|
||||
echo "object the JpaDialect returns when it begins the transaction, and Hibernate's does not"
|
||||
echo "implement one -- so no amount of configuration gets NESTED working here."
|
||||
echo
|
||||
echo "== attempt 3: the same propagation on a JDBC transaction manager =="
|
||||
echo "\$ curl -s localhost:$APP_PORT/tx/nested-jdbc"
|
||||
echo
|
||||
curl -s "http://127.0.0.1:${APP_PORT}/tx/nested-jdbc" | python3 -m json.tool | sed 's/^/ /'
|
||||
echo
|
||||
echo "This is what NESTED is for: the nested scope rolled back to its savepoint, the outer"
|
||||
echo "transaction carried on and committed, and one of the two rows survived."
|
||||
echo
|
||||
echo "A savepoint is a JDBC concept. DataSourceTransactionManager holds the JDBC connection"
|
||||
echo "and can issue one; JpaTransactionManager holds an EntityManager and cannot. The"
|
||||
echo "reference documentation does say NESTED works with JDBC resource transactions -- what"
|
||||
echo "it does not say is that the JPA path fails, twice, with two different messages."
|
||||
stop_app
|
||||
} > docs/output/03-nested.txt 2>&1
|
||||
cat docs/output/03-nested.txt
|
||||
60
transactions/scripts/demo-propagation.sh
Executable file
60
transactions/scripts/demo-propagation.sh
Executable file
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env bash
|
||||
# All seven propagation values, each called with and without an outer transaction.
|
||||
set -euo pipefail
|
||||
set +m
|
||||
cd "$(dirname "$0")/.."
|
||||
source scripts/env.sh
|
||||
{
|
||||
echo "== the propagation matrix =="
|
||||
echo
|
||||
echo "Each inner method is called twice: once from a @Transactional caller and once from a"
|
||||
echo "plain one. 'active' is TransactionSynchronizationManager.isActualTransactionActive();"
|
||||
echo "'name' is the transaction's name, which is how you tell JOINING from STARTING -- a"
|
||||
echo "joining method reports the OUTER method's name."
|
||||
echo
|
||||
start_app > /dev/null
|
||||
curl -s "http://127.0.0.1:${APP_PORT}/tx/propagation" | python3 -c '
|
||||
import json,sys
|
||||
d=json.load(sys.stdin)
|
||||
print(" %-14s %-24s %-8s %s" % ("PROPAGATION","CALLER","ACTIVE","TRANSACTION NAME / OUTCOME"))
|
||||
print(" " + "-"*76)
|
||||
for name,row in d.items():
|
||||
for ctx,label in (("withOuterTransaction","inside @Transactional"),
|
||||
("withoutOuterTransaction","no transaction")):
|
||||
v=row[ctx]
|
||||
if "exception" in v:
|
||||
print(" %-14s %-24s %-8s %s" % (name, label, "--", v["exception"].split(".")[-1]))
|
||||
else:
|
||||
i=v["inner"]
|
||||
print(" %-14s %-24s %-8s %s" % (name, label, i["actualTransactionActive"],
|
||||
str(i["transactionName"]).split(".")[-1]))
|
||||
print()'
|
||||
echo
|
||||
echo "Reading it:"
|
||||
echo " REQUIRED inside a transaction the inner name is the OUTER method -- it joined."
|
||||
echo " REQUIRES_NEW the inner name is its own method -- it started a second transaction."
|
||||
echo " NESTED fails outright on JpaTransactionManager. See docs/output/03-nested.txt."
|
||||
echo " SUPPORTS joins if there is one, runs with none if there is not. No transaction"
|
||||
echo " is created, so the write below it lands on an auto-commit connection."
|
||||
echo " NOT_SUPPORTED suspends the outer transaction: active=False even inside one."
|
||||
echo " MANDATORY requires a caller's transaction; IllegalTransactionStateException if none."
|
||||
echo " NEVER requires the absence of one; IllegalTransactionStateException if present."
|
||||
echo
|
||||
echo "== the exact exception messages =="
|
||||
curl -s "http://127.0.0.1:${APP_PORT}/tx/propagation" | python3 -c '
|
||||
import json,sys
|
||||
for name,row in json.load(sys.stdin).items():
|
||||
for ctx in ("withOuterTransaction","withoutOuterTransaction"):
|
||||
v=row[ctx]
|
||||
if "exception" in v:
|
||||
print(" %s (%s)" % (name, ctx))
|
||||
print(" %s" % v["exception"])
|
||||
print(" %s" % v["message"])
|
||||
print()'
|
||||
echo "== what the transaction manager logged while doing it =="
|
||||
echo
|
||||
grep -E "Creating new transaction|Participating in existing|Suspending current|Initiating transaction|Not creating" "$LOG" \
|
||||
| tidy | head -24
|
||||
stop_app
|
||||
} > docs/output/01-propagation.txt 2>&1
|
||||
cat docs/output/01-propagation.txt
|
||||
32
transactions/scripts/demo-rollback.sh
Executable file
32
transactions/scripts/demo-rollback.sh
Executable file
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env bash
|
||||
# Does the inner write survive when the outer transaction fails? And what happens when the
|
||||
# caller catches the inner exception?
|
||||
set -euo pipefail
|
||||
set +m
|
||||
cd "$(dirname "$0")/.."
|
||||
source scripts/env.sh
|
||||
{
|
||||
echo "== rollback behaviour =="
|
||||
echo
|
||||
start_app > /dev/null
|
||||
curl -s "http://127.0.0.1:${APP_PORT}/tx/rollback" | python3 -c '
|
||||
import json,sys
|
||||
for k,v in json.load(sys.stdin).items():
|
||||
print(" %s" % k)
|
||||
print(" outcome : %s" % v["outcome"])
|
||||
if "message" in v: print(" message : %s" % v["message"])
|
||||
print(" rows : %s -> %s" % (v["auditRowsSurviving"], v["verdict"]))
|
||||
print()'
|
||||
echo "The third and fourth rows are the ones worth sitting with."
|
||||
echo
|
||||
echo "When a REQUIRED inner scope throws, it marks the SHARED transaction rollback-only"
|
||||
echo "before the exception leaves it. The caller can catch the exception -- and does, and"
|
||||
echo "returns normally -- but the transaction is already doomed, so the commit at the end"
|
||||
echo "throws UnexpectedRollbackException. Catching the exception did not save the work; it"
|
||||
echo "only moved the failure to a place with no useful stack trace."
|
||||
echo
|
||||
echo "With REQUIRES_NEW the inner scope had its own physical transaction, so its rollback"
|
||||
echo "is contained and the caller's catch behaves the way the code reads."
|
||||
stop_app
|
||||
} > docs/output/02-rollback.txt 2>&1
|
||||
cat docs/output/02-rollback.txt
|
||||
36
transactions/scripts/demo-silent.sh
Executable file
36
transactions/scripts/demo-silent.sh
Executable file
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env bash
|
||||
# The six ways @Transactional silently does nothing.
|
||||
set -euo pipefail
|
||||
set +m
|
||||
cd "$(dirname "$0")/.."
|
||||
source scripts/env.sh
|
||||
{
|
||||
echo "== six pieces of code carrying @Transactional that are not transactional =="
|
||||
echo
|
||||
echo "Row 0 is the control: the SAME annotated method, reached through the proxy."
|
||||
echo
|
||||
start_app > /dev/null
|
||||
curl -s "http://127.0.0.1:${APP_PORT}/tx/silent" | python3 -m json.tool | sed 's/^/ /'
|
||||
echo
|
||||
echo "Reading it:"
|
||||
echo
|
||||
echo " 0 control actualTransactionActive=true. The mechanism works."
|
||||
echo " 1 self-invocation entryPoint() is not annotated and calls this.annotated...(),"
|
||||
echo " so the proxy is never involved. Same class, same annotation,"
|
||||
echo " no transaction."
|
||||
echo " 2 private method a CGLIB proxy advises by overriding, and private methods"
|
||||
echo " cannot be overridden. Legal Java, no effect."
|
||||
echo " 3 checked exception the default rollback rule is RuntimeException or Error. A"
|
||||
echo " checked exception propagates AND the transaction commits."
|
||||
echo " Fix: @Transactional(rollbackFor = Exception.class)."
|
||||
echo " 4 swallowed nothing propagates, so the interceptor sees a normal return"
|
||||
echo " and commits. The write survives the failure it 'handled'."
|
||||
echo " 5 @PostConstruct the proxy does not exist yet during initialisation."
|
||||
echo " 6 new no container, no proxy, no transaction."
|
||||
echo
|
||||
echo "Note what rows 3 and 4 have in common: the row is still there afterwards. These two"
|
||||
echo "do not merely fail to start a transaction -- they start one and COMMIT work that the"
|
||||
echo "code was trying to abandon."
|
||||
stop_app
|
||||
} > docs/output/04-silent-failures.txt 2>&1
|
||||
cat docs/output/04-silent-failures.txt
|
||||
13
transactions/scripts/demo-versions.sh
Executable file
13
transactions/scripts/demo-versions.sh
Executable file
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
source scripts/env.sh
|
||||
{
|
||||
echo "== versions =="
|
||||
java -version 2>&1 | clean
|
||||
echo
|
||||
echo "spring-boot-starter-parent: $(grep -A2 '<artifactId>spring-boot-starter-parent' pom.xml | grep '<version>' | sed 's/.*<version>\(.*\)<\/version>.*/\1/')"
|
||||
echo "database: H2 in-memory"
|
||||
echo "transaction manager: JpaTransactionManager (Spring Boot default for JPA)"
|
||||
} > docs/output/00-versions.txt 2>&1
|
||||
cat docs/output/00-versions.txt
|
||||
51
transactions/scripts/env.sh
Executable file
51
transactions/scripts/env.sh
Executable file
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env bash
|
||||
# Shared environment. Point JAVA_HOME at a JDK 25 (or newer) installation.
|
||||
: "${JAVA_HOME:?set JAVA_HOME to a JDK 25+ installation}"
|
||||
export PATH="$JAVA_HOME/bin:$PATH"
|
||||
MVN="${MVN:-mvn}"
|
||||
JAR="target/transactions-1.0.0.jar"
|
||||
APP_PORT="${APP_PORT:-8081}"
|
||||
LOG="${LOG:-/tmp/transactions-demo.log}"
|
||||
|
||||
# Strip machine-specific noise from committed transcripts.
|
||||
clean() { grep -v "Picked up JAVA_TOOL_OPTIONS" | grep -v "^OpenJDK 64-Bit Server VM warning"; }
|
||||
|
||||
# Reduce a Spring log line to its message, so transcripts diff cleanly between runs.
|
||||
tidy() { sed -E 's/^[0-9T:.-]+Z +//; s/^[A-Z]+ +[0-9]+ --- \[[^]]*\] \[[^]]*\] +//; s/ +: /: /'; }
|
||||
|
||||
# Start detached and block until it answers. Deliberately NOT setsid: setsid forks when it is
|
||||
# not already a process-group leader, so $! would name a process that exits immediately and
|
||||
# the JVM would survive every later stop_app -- holding the port, so the next scenario fails
|
||||
# to bind and curl answers from the previous one. That reads exactly like the configuration
|
||||
# under test having had no effect.
|
||||
start_app() {
|
||||
stop_app
|
||||
mkdir -p target
|
||||
nohup java -jar "$JAR" "$@" > "$LOG" 2>&1 < /dev/null &
|
||||
echo $! > target/app.pid
|
||||
for _ in $(seq 1 60); do
|
||||
curl -s -o /dev/null "http://127.0.0.1:${APP_PORT}/tx/silent" 2>/dev/null && return 0
|
||||
kill -0 "$(cat target/app.pid)" 2>/dev/null || { echo "JVM exited during startup:"
|
||||
tail -20 "$LOG"; return 1; }
|
||||
sleep 1
|
||||
done
|
||||
echo "application did not answer"; tail -20 "$LOG"; return 1
|
||||
}
|
||||
|
||||
# Stop by recorded PID. Never by pattern: `ps | grep transactions` also matches the shell
|
||||
# running this script, because that string is on its own command line.
|
||||
stop_app() {
|
||||
if [ -f target/app.pid ]; then
|
||||
pid=$(cat target/app.pid)
|
||||
if [ -n "$pid" ] && grep -qa "transactions" "/proc/$pid/cmdline" 2>/dev/null; then
|
||||
kill -9 "$pid" 2>/dev/null || true
|
||||
wait "$pid" 2>/dev/null || true
|
||||
fi
|
||||
rm -f target/app.pid
|
||||
fi
|
||||
for _ in $(seq 1 40); do
|
||||
if ! (exec 3<>/dev/tcp/127.0.0.1/"${APP_PORT}") 2>/dev/null; then break; fi
|
||||
sleep 0.25
|
||||
done
|
||||
exec 3<&- 2>/dev/null || true
|
||||
}
|
||||
16
transactions/scripts/run-all.sh
Executable file
16
transactions/scripts/run-all.sh
Executable file
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerate every transcript under docs/output/.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
source scripts/env.sh
|
||||
|
||||
"$MVN" -B -q package -DskipTests
|
||||
|
||||
for demo in versions propagation rollback nested silent isolation; do
|
||||
echo "=== $demo ==="
|
||||
"scripts/demo-$demo.sh" > /dev/null
|
||||
done
|
||||
stop_app
|
||||
echo
|
||||
echo "regenerated:"
|
||||
ls -1 docs/output/
|
||||
Reference in New Issue
Block a user