1Mai chuyển 500.000đ từ ví A sang B: transfer("A", "B", 500000) đi qua proxy @Transactional, mở một transaction gắn với một EntityManager, để các repository không tự commit riêng.Mai transfers 500,000 VND from A to B: transfer("A", "B", 500000) passes the @Transactional proxy, opening one transaction bound to one EntityManager so repositories never commit on their own.
2wallets.findById("A") và findById("B") đi qua EntityManager: SELECT hai ví, mỗi Wallet thành managed kèm snapshot. findById cùng id lần nữa sẽ lấy từ identity map, không query lại.wallets.findById("A") and findById("B") go through the EntityManager: two SELECTs, each Wallet becomes managed with a snapshot. Another findById for the same id hits the identity map, no new query.
3from.debit(500000) kiểm số dư rồi trừ, to.credit(500000) cộng: số dư trong bộ nhớ thành 1.500.000đ và 600.000đ. Không gọi save() vì dirty checking sẽ so với snapshot.from.debit(500000) checks the balance and subtracts, to.credit(500000) adds: in-memory balances become 1,500,000 and 600,000 VND. No save() call, because dirty checking compares against the snapshot.
4ledger.save(new LedgerEntry("A", "B", 500000)) đăng ký entity mới vào cùng EntityManager. Tuỳ cách sinh ID, INSERT có thể chạy sớm nhưng không commit riêng.ledger.save(new LedgerEntry("A", "B", 500000)) registers a new entity in the same EntityManager. Depending on ID generation, the INSERT may run early but never commits on its own.
5transfer() kết thúc, proxy commit: flush so snapshot, gửi UPDATE wallet ... WHERE version = ? cho hai ví và INSERT ledger, rồi COMMIT. Chỉ sau đó mới báo Mai thành công.transfer() returns and the proxy commits: flush compares snapshots, sends UPDATE wallet ... WHERE version = ? for both wallets plus the ledger INSERT, then COMMIT. Only then is Mai told it succeeded.
6Nhánh lỗi: nếu ghi sổ cái lỗi, hoặc @Version phát hiện giao dịch khác đã sửa ví (OptimisticLockException), RuntimeException làm proxy ROLLBACK cả lượt; số dư trong DB giữ nguyên. Bản demo chạy được: UnitOfWorkDemo ném lỗi giả sau transfer(), InMemoryUnitOfWork.rollback() vứt bỏ identity map và LedgerEntry mới, số dư đã lưu giữ nguyên.Failure branch: if the ledger write fails, or @Version detects another transaction changed a wallet (OptimisticLockException), the RuntimeException makes the proxy ROLL BACK everything; database balances stay unchanged. In the runnable demo, UnitOfWorkDemo throws a simulated failure after transfer(); InMemoryUnitOfWork.rollback() discards the identity map and the new LedgerEntry, so persisted balances stay the same.
7UnderTheHood cho thấy Spring làm gì: emf.createEntityManager() là Unit of Work, tx.begin(), em.find, debit/credit, em.persist(new LedgerEntry), tx.commit() (flush rồi COMMIT); RuntimeException thì tx.rollback(), cuối cùng em.close().UnderTheHood shows what Spring does: emf.createEntityManager() is the Unit of Work, tx.begin(), em.find, debit/credit, em.persist(new LedgerEntry), tx.commit() (flush then COMMIT); on RuntimeException tx.rollback(), and finally em.close().
8Bản Go: Service.Transfer gọi store.WithTx(ctx, fn). WithTx BeginTx rồi tạo Tx{Wallets, Ledger}, cả hai repo giữ cùng *sql.Tx qua DBTX. Trong fn: GetForUpdate khoá ví bằng FOR UPDATE, SetBalance chạy UPDATE tường minh (không có dirty checking), Ledger.Insert ghi sổ; fn trả nil nên Commit. Trong main.go, *sql.DB mở bằng driver memdb trong bộ nhớ nên toàn bộ đoạn này chạy thật mà không cần Postgres.Go: Service.Transfer calls store.WithTx(ctx, fn). WithTx calls BeginTx, then builds Tx{Wallets, Ledger}, both repos holding the same *sql.Tx through DBTX. Inside fn: GetForUpdate locks with FOR UPDATE, SetBalance issues an explicit UPDATE (no dirty checking), Ledger.Insert writes the entry; fn returns nil, so Commit. In main.go the *sql.DB is opened with the in-memory memdb driver, so this whole flow runs for real without Postgres.
9Nếu src < amount, fn trả ErrInsufficientFunds; defer trong WithTx thấy err khác nil và gọi sqlTx.Rollback(). Nếu fn panic, defer cũng rollback rồi panic lại để không nuốt lỗi.If src < amount, fn returns ErrInsufficientFunds; the defer in WithTx sees a non-nil err and calls sqlTx.Rollback(). If fn panics, the defer also rolls back, then re-panics so the bug is not swallowed.