Skip to main content

Java Order Tutorial

Build understanding around one draft Order: load its complete item list, change Notebook quantity from 2 to 3, save the Order and line totals together, then read the result in a new process. Follow the recorded native SQLite application and learn why each query, expression and transaction boundary is needed. The version and publication boundaries below apply to this specific example.

The core Order tutorial was verified on the published Java runtime. Java lifecycle and sustained-load checks are WORKSPACE PASS — RELEASE PENDING for the JDBC COMMIT-cleanup repair. Keep those scopes separate.

1. Prepare the example​

Use the Java Order source download (SHA-256 checksum). It includes the generated type library, console startup, handwritten application, model and fixture. You do not need the site checkout, a retained built workspace, a TeaQL runtime source checkout or a generator account.

Install JDK 21, Maven 3.9+, Bash, curl and unzip. The commands below target macOS/Linux; Windows readers can use WSL. Confirm that java -version and mvn -version both report JDK 21. If necessary, set JAVA_HOME to your JDK 21 installation and put its bin directory on PATH. Python 3 is optional for the independent SQLite check later; no database server or Docker is needed.

From an empty working directory:

curl --fail --location --remote-name https://teaql.io/examples/order/java-first-run/order-java-first-run.zip
curl --fail --location --remote-name https://teaql.io/examples/order/java-first-run/SHA256SUMS
shasum -a 256 -c SHA256SUMS # On Linux, sha256sum -c SHA256SUMS also works.
unzip order-java-first-run.zip
cd order-java
bash order.sh build

The build installs library/ into the package-local .m2/repository, then packages application/ as an executable JAR. It uses the included Maven settings for both user and global settings, downloading dependencies from Maven Central and the public TeaQL Maven repository. First use requires internet access and can take several minutes. It does not use your preinstalled TeaQL artifacts or submit a model to a service. The generated library and dependency manifests remain unchanged.

This example pins TeaQL 1.555-RELEASE to preserve the recorded application. It is a first-run qualification of that published version, not a claim about the latest release. The new receipt records the exact package, toolchain and resolved dependencies. Existing lifecycle/stress pending markers still apply to their own scopes.

The package reuses the evaluated Order v1.0 model and three-order fixture. Do not substitute the isolation/stock fixture: those are separately evaluated model revisions. For a new model, follow the Java Quick Start and obtain Order-scoped Assist for that generated revision.

The handwritten application is included unchanged at application/src/main/java/com/example/orderworkflowservice/OrderCheck.java. The excerpts below are function-body excerpts, not standalone files. Keep its package declaration, generated Q/E, CustomerOrder/OrderItem, UserContext and helper imports. require, status, object and report are application helpers in that file.

2. Initialize SQLite and complete the first edit​

From the extracted order-java directory:

bash order.sh init
bash order.sh read
bash order.sh edit
bash order.sh verify

init creates .local/orders.sqlite, ensures the schema and seeds the fixture. It refuses an existing database rather than importing duplicate Orders or clearing data. read, edit and verify each start a separate JVM against that same file; they refuse a missing database. verify reads the persisted graph, so its output demonstrates that the edit survived application shutdown.

Command / phaseExpected result
init → bootstrap, seedExplicit schema setup, three Orders and six items; ORDER_OK for both phases.
read → draft-graphORD-2026-1001 is DRAFT with total 3850 USD cents.
edit → draft-editNotebook quantity 3, Notebook line total 3750, Order total 5100.
verify → restart-readbackThe same totals in a new process; Order and changed item version 2, untouched item version 1.

Read/edit handlers print ORDER_CASE JSON and an ORDER_OK completion line. Find the Order by business number and the line by SKU; numeric IDs are not portable fixture keys. Run the edit once when comparing the first-run version numbers. To repeat from scratch, select a new disposable absolute path and run init, read, edit, verify again:

export ORDER_DATABASE="$(mktemp -d)/orders.sqlite"
bash order.sh init
bash order.sh read
bash order.sh edit
bash order.sh verify

For an optional independent, read-only database assertion after the edit:

python3 check_database.py "${ORDER_DATABASE:-$PWD/.local/orders.sqlite}" edited fixture.json

This checks persisted totals, quantities, versions, relationships and database integrity; it does not seed or repair data. To explore the already-recorded null and validation handlers, run bash order.sh notes: value, SQL NULL, empty text and NotLoaded stay distinct, and quantities 0, -1, 1.5 and 101 are rejected. The NotLoaded probes intentionally report native errors and finish successfully.

What happens at startup​

The included App.java owns the Hikari data source, JDBC executor and runtime registry. It constructs CustomUserContext, explicitly calls context.ensureSchema(), delegates to OrderCheck.run(phase, context), and closes the data source on exit. WorkspaceTeaQLDatabase is an included application SQL adapter; it does not require a runtime source checkout. Copying OrderCheck.java alone omits this setup and the generated type library.

Module installation registers metadata and behavior. Schema reconciliation is an explicit database operation. This disposable console runs it at startup; keep startup/admin schema work separate from service requests, and obtain production tenant/actor/policy from trusted server context.

First-run evidence and scope​

The 2026-11-14 first-run receipt binds the downloadable source package, unchanged generated library, application, runner and published dependencies. The build used a fresh directory and empty Maven cache with explicit public-repository settings; the three-order seed and edited database passed the independent SQLite oracle. Repeated initialization was refused without changing the database, and a missing-database read did not create an empty file. This is an isolated local build on the recorded toolchain, not a fresh OS image or an additional fault/stress campaign.

The historical core receipt remains the authority for the other handlers and API excerpts. See the package README for the file layout. Advanced query, mutation, isolation and stock recipes retain their own fixture, workspace and release requirements; the first-run download does not qualify all of those paths.

3. Load the full Order before editing​

var rows = Q.customerOrders().withOrderNumberIs("ORD-2026-1001").selectOrderStatus()
.selectOrderItemListWith(Q.orderItems().orderBySkuCodeAscending().orderByIdAscending().limit(101))
.limit(2).comment("Load full draft order and complete bounded items")
.purpose("Validate and edit one draft order").executeForList(context);

The outer bound of 2 lets the application reject a duplicate business identity. The child bound of 101 is an overflow sentinel for a supported maximum of 100 items. Require exactly one Order, DRAFT status and at most 100 loaded items before continuing. A one-item preview is useful for a list screen, but cannot supply the complete total for an edit. The full source performs these checks after the query; keep them when adapting the excerpt.

comment describes the operation and purpose records the business reason. Both travel with execution through the trusted context. A buyer filter in this v1.0 fixture is a business predicate; it does not authenticate or authorize a buyer. Use the separate buyer/tenant isolation contract when implementing protected access.

4. Validate money and save one atomic edit​

The application validates integral quantity in [1, 100], USD currency, each stored line amount and the complete new Order total. Prices and totals are integer cents. It finds exactly one SKU-NOTEBOOK, computes 3 × 1250 + 3 × 450 = 5100, then changes the selected item and Order together. The following write excerpt assumes those validated, fully loaded variables; it is not a replacement for validation.

The audit reason is Edit draft Order quantity and totals atomically, named EDIT in most examples and editReason/EditReason in Go, Swift and .NET.

changed.updateQuantity((int)quantity);
changed.updateLineTotalMinor(Math.multiplyExact((int)quantity,E.orderItem(changed).getUnitPriceMinor().eval()));
order.updateTotalMinor(total);
System.out.println("ORDER_GRAPH_ATTEMPT");
order.auditAs(EDIT).save(context);

The edit uses checked integer arithmetic (Math.multiplyExact and Math.addExact). The audited Order graph save is the native transaction boundary in this core example. The separate lifecycle example uses an explicit native transaction and a workspace JDBC repair.

A successful audited save returns the persisted typed entity. The core example reads again after mutation, rather than treating a pre-save object as independent evidence of committed state. A rejected stale write requires reloading authoritative state and a business decision before retrying; it is not permission to overwrite the winner or retry every provider error.

5. Use projections, nulls and pages deliberately​

TaskJava API in this exampleResult / responsibility
Execute a bounded queryexecuteForList(context)Typed SmartList; preserve native errors and check cardinality.
Read selected moneyE.customerOrder(order).getTotalMinor().eval()Loaded integer cents; not a formatting or currency conversion API.
Access selected itemsorder.getOrderItemList()Only the relation that was explicitly loaded.
Default a selected SQL NULL notegetOrderNote().orIfNull("No note")Null-only fallback; an empty string stays empty and NotLoaded still reports a missing field.
Save an audited mutationorder.auditAs(EDIT).save(context)Persisted typed entity; the required transaction includes all changed entities.
Request an exact page totaloffset(offset, limit).count() → page.getTotalCount()Total of the filtered set, independent of page length.

The note accessors in the table are called on the corresponding E expression. required, report, pageRows, load, edit and prepare_edit are application helpers where present; they are not additional generated terminal methods.

Note stateExpected behavior
Selected valueLeave at reception stays that value.
Selected SQL NULLA null-only default produces No note.
Selected empty textRemains the empty string.
Omitted fieldNative NotLoaded diagnostic, including when a null-only default is attempted.

For a read-only list screen, the existing bounded-page handler validates offset >= 0 and 1 <= limit <= 3, sets a stable total/ID order and explicitly selects one item preview per Order. With validated offset, limit and buyer, its native query is:

var page=Q.customerOrders().withBuyerReferenceIs(buyer).orderByTotalMinorAscending().orderByIdAscending()
.selectOrderItemListWith(Q.orderItems().orderBySkuCodeAscending().orderByIdAscending().limit(1)).offset(offset,limit).count()
.comment("Read bounded Order pages").purpose("Compare filtered totals and per-order item previews").executeForList(context);

This query only reads. Do not save its one-item preview as if it were a full Order edit or infer deletion of omitted items. The pagination fixture has eight matching BUYER-EXPORT Orders, whereas the first-edit fixture above has three Orders overall. See the page API decision guide for fixture selection, continuous export, retained-ID jumps and aggregate results.

6. Diagnose a failure before changing code​

A bare ConcurrentModifyException can have no message. Catch the public type rather than relying only on English error text.

SymptomFirst action
Java release/enforcer errorCheck mvn -version and java -version; both need the documented JDK 21.
Dependency download failureCheck access to Maven Central and the TeaQL public repository. Keep the pinned versions and retry bash order.sh build after connectivity is restored.
JAR missingFinish bash order.sh build in the extracted package before running phases.
Database already exists or seed failed partwaySelect a new absolute ORDER_DATABASE and initialize again. init never deletes or repairs an existing file.
Empty Order or duplicate rowConfirm absolute DB path, fixture and business number; preserve the cardinality check.
Wrong total after editCheck complete item loading and integer validation before the audited save.
Missing field errorReload the field/relation explicitly; do not substitute a null default.
Version conflictReload authoritative state and decide whether the requested edit is still valid.
Busy/locked, commit or cancellation failureInspect native provider error and transaction boundary; follow the Java Order troubleshooting table.

Continue with the Order API usage guide, Java advanced data operations, version and qualification table and documentation coverage matrix. The School regression baseline and all prior Order receipts remain unchanged.

Continue with advanced Order writes​

Follow Java Advanced Order Mutations for explicit line deletion, legal state transitions and stale-version recovery. Each recipe explains its starting state, transaction boundary, native errors and independent readback using the existing qualified example. Start a fresh recipe database; do not reuse the quantity-edited database above.

Continue with Order queries​

Use Java Order Queries for continuous export, retained-ID page jumps and provider summaries. The query recipes use separate nine-/ten-order datasets; keep the fixture and context/store lifetime with the operation you are learning.

Continue with buyer and tenant isolation​

Use Java Order Isolation to upgrade the model to v1.1 and build root/buyer scope from an application-owned trusted session.