Fetch plans¶
Incubating
Fetch plans are annotated @Incubating (see API stability).
A query model selects what its own row holds. A fetch plan adds what a row cannot: the to-many children of each model
(an order's items), a to-one child found by key, a nested plan for a @Joined model, and values you look up yourself.
The library loads them once per page, in a few extra statements, so there is no query per row.
A plan and a child¶
Mark the field with @Child. A to-many child is a List of another @QueryModel and names the child's column that
points back, foreignKey; the child needs a @PrimaryKey.
@QueryModel(root = CustomerEntity.class)
public record CustomerOrders(
@PrimaryKey Long id,
String name,
@Child(foreignKey = "customer.id") List<OrderLines> orders) {}
@QueryModel(root = OrderEntity.class)
public record OrderLines(
@PrimaryKey Long id,
String status,
BigDecimal total,
@Child(foreignKey = "order.id") List<Line> items) {}
@QueryModel(root = OrderItemEntity.class)
public record Line(@PrimaryKey Long id, String productCode, Integer quantity) {}
key and foreignKey are attribute paths on the parent's and the child's entity. key defaults to the parent's
@PrimaryKey. Both take one path, and their types must be equal. A @Child of type Optional is a to-one child.
The processor generates a ChildField constant per @Child, such as QCustomerOrders.ORDERS.
Declaring @Child, case by case¶
A child is matched by comparing two columns: key on the parent and foreignKey on the child. Pick the row that
matches where the linking column lives. The parent entity does not need a @OneToMany collection for any of these:
@Child reads the columns, not the collection.
| Where the link lives | Field type | Declare |
|---|---|---|
The child has a @ManyToOne to the parent |
List |
@Child(foreignKey = "order.id") |
| The child has a plain column holding the parent's id | List |
@Child(foreignKey = "orderId") |
The parent has a @ManyToOne to the child |
Optional |
@Child(key = "customer.id") |
| The parent has a plain column holding the child's id | Optional |
@Child(key = "customerId") |
| The child holds the parent's id and has at most one row per parent (a one-to-one) | Optional |
@Child(foreignKey = "order.id") |
| Both sides link on a column other than an id | List or Optional |
@Child(key = "email", foreignKey = "customerEmail") |
| Many-to-many, mapped on the child's side | List |
@Child(foreignKey = "orders.id") |
| Many-to-many or any association path, mapped on the parent's side | List or Optional |
@Child(through = "labels") |
key defaults to the parent's @PrimaryKey and foreignKey to the child's. A path that ends at an association must
name one of its attributes: "order.id", not "order" (MQ3402). The two columns must have the same type (MQ3403).
The child points back with an association. OrderItemEntity has @ManyToOne OrderEntity order:
@QueryModel(root = OrderEntity.class)
public record OrderItems(
@PrimaryKey Long id,
String status,
@Child(foreignKey = "order.id") List<Line> items) {} // OrderItemEntity.order.id = OrderEntity.id
@QueryModel(root = OrderItemEntity.class)
public record Line(@PrimaryKey Long id, String productCode, Integer quantity) {}
The child points back with a plain column. PaymentEntity has @Column(name = "order_id") Long orderId and no
association:
@QueryModel(root = OrderEntity.class)
public record OrderPayments(
@PrimaryKey Long id,
@Child(foreignKey = "orderId") List<PaymentView> payments) {} // PaymentEntity.orderId = OrderEntity.id
@QueryModel(root = PaymentEntity.class)
public record PaymentView(@PrimaryKey Long id, BigDecimal amount, String state) {}
A JPA @OneToMany(mappedBy = "orderId") over such a column is not valid, since mappedBy must name an association.
Leave the collection off the entity, or map it with @OneToMany @JoinColumn(name = "order_id", insertable = false,
updatable = false); the model does not need it either way.
The parent holds the child's id. An order has one customer. Set key to the parent's column; foreignKey
defaults to the child's @PrimaryKey:
@QueryModel(root = OrderEntity.class)
public record OrderCustomer(
@PrimaryKey Long id,
@Child(key = "customer.id") Optional<Buyer> buyer) {} // OrderEntity.customer.id = CustomerEntity.id
@QueryModel(root = CustomerEntity.class)
public record Buyer(@PrimaryKey Long id, String name) {}
With a plain Long customerId column on the order instead, write key = "customerId". A null key leaves
Optional.empty(). A to-one association can also be read in the same row with @Join
(Writing a model); use @Child when the plan should decide whether to load it.
A one-to-one where the child holds the key. Each order has at most one shipment, whose order.id points back:
@QueryModel(root = OrderEntity.class)
public record OrderShipment(
@PrimaryKey Long id,
@Child(foreignKey = "order.id") Optional<ShipmentView> shipment) {}
@QueryModel(root = ShipmentEntity.class)
public record ShipmentView(@PrimaryKey Long id, String carrier, String trackingNo) {}
Two shipments for one order fail with MQ2601; use a List when the column is not unique on the child's side.
Several children, and children of children. Each @Child is a separate field, and a child model may declare its
own:
@QueryModel(root = OrderEntity.class)
public record OrderDetail(
@PrimaryKey Long id,
String status,
@Child(foreignKey = "order.id") List<Line> items,
@Child(foreignKey = "orderId") List<PaymentView> payments,
@Child(key = "customer.id") Optional<Buyer> buyer) {}
FetchPlan<OrderDetail> plan = FetchPlan.of(QOrderDetail.ALL)
.child(QOrderDetail.ITEMS, FetchPlan.of(QLine.ALL))
.child(QOrderDetail.PAYMENTS, FetchPlan.of(QPaymentView.ALL),
c -> c.where(f -> f.eq(QPaymentView.STATE, "SETTLED")))
.child(QOrderDetail.BUYER, FetchPlan.of(QBuyer.ALL));
A plan may leave out any child; it then reads as empty. Keys on other columns, many-to-many children and through have
their own sections below: A to-one child, and a key other than the primary
key and Many-to-many children.
The rules every case shares:
- A
Listchild needsforeignKeyorthrough, and its model needs a@PrimaryKey(MQ3405). keyandforeignKeyeach take one attribute; a composite or embedded key is refused (MQ3404).keymay not cross a collection.foreignKeymay, for a many-to-many child (MQ3402).throughandforeignKeyexclude each other (MQ3401).
A plan says which children to load. It is immutable, built bottom-up, and attached to the query with fetch(...):
FetchPlan<Line> lines = FetchPlan.of(QLine.ALL);
FetchPlan<OrderLines> orders = FetchPlan.of(QOrderLines.ALL).child(QOrderLines.ITEMS, lines);
FetchPlan<CustomerOrders> customers = FetchPlan.of(QCustomerOrders.ALL).child(QCustomerOrders.ORDERS, orders);
var q = QCustomerOrders.query()
.fetch(customers)
.orderBy(QCustomerOrders.NAME.asc())
.build();
fetch(plan) selects the plan's columns, and the columns it needs besides: each child's key. It replaces select, and
the last of the two wins as a whole, so call fetch last. q.withFetch(otherPlan) returns a copy of a query with
another plan, for a plan that depends on the call, such as an export's columns.
Run the query as usual. The plan runs on the models a call returns, at every level:
List<CustomerOrders> list = executor.list(q, Limit.of(100));
Slice<CustomerOrders> page = executor.page(q, PageSpec.of(0, 50), CountMode.NO_COUNT);
executor.export(q, ExportOptions.of(500), p -> p, sink);
List<CustomerOrders> list = customerRepository.findAll(q, Limit.of(100));
ModelPage<CustomerOrders> page = customerRepository.findPage(q, PageRequest.of(0, 50), CountMode.NO_COUNT);
customerRepository.export(q, ExportOptions.of(500), p -> p, sink);
A plan works with every paging mode. With keyset() or primaryKeyFirst(...), the children load for the models of
each page, after the page's own statements:
var deep = QCustomerOrders.query()
.fetch(customers)
.orderBy(QCustomerOrders.NAME.asc())
.keyset() // or .primaryKeyFirst(PrimaryKeyFirst.whenOffsetAbove(10_000))
.build();
executor.export(deep, ExportOptions.of(500), p -> p, sink);
customerRepository.export(deep, ExportOptions.of(500), p -> p, sink);
count and ONLY_COUNT load no children. stream refuses a plan that has any (MQ2605); use export, which runs
the plan on each page; on the last page it runs on the whole page and the export's limit cuts after, since a
pageTransformer can change the item count.
A to-one child, and a key other than the primary key¶
A to-one child is an Optional. It is matched on key, a column of the parent, against the child's foreignKey,
which defaults to the child's @PrimaryKey. Set key when the parent holds the child's key, as an order holds its
customer's:
@QueryModel(root = OrderEntity.class)
public record OrderBuyer(
@PrimaryKey Long id,
@Child(key = "customer.id") Optional<Buyer> buyer, // OrderEntity.customer.id = CustomerEntity.id
@Child(key = "referrerId") Optional<Buyer> referrer) {} // a plain, nullable column
@QueryModel(root = CustomerEntity.class)
public record Buyer(@PrimaryKey Long id, String name) {}
FetchPlan<Buyer> buyer = FetchPlan.of(QBuyer.ALL);
FetchPlan<OrderBuyer> plan = FetchPlan.of(QOrderBuyer.ALL)
.child(QOrderBuyer.BUYER, buyer)
.child(QOrderBuyer.REFERRER, buyer); // one plan serves both fields
An order whose referrerId is null keeps Optional.empty(). If two distinct child rows match one key, the load
fails with MQ2601 naming the field: use a List for a key that is not unique on the child's side.
Both sides may name other columns, of equal type, for children keyed on something other than an id:
@QueryModel(root = CustomerEntity.class)
public record CustomerNotes(
@PrimaryKey Long id,
String email,
@Child(key = "email", foreignKey = "customerEmail") List<Note> notes) {}
Keys are compared by the database. If the child's column has a case-insensitive collation and the parent's does not, a
child can match a key that differs in case, which fails with MQ2604 rather than attach it to the wrong parent.
A class model¶
A class model takes @Child the same way. The library sets the field through its setter on the same instance, rather
than building a copy as it does for a record. A mapped row holds List.of() or Optional.empty() until its child is
loaded, as a record does:
@QueryModel(root = OrderEntity.class)
public class OrderForm {
@PrimaryKey private Long id;
@Child(foreignKey = "order.id") private List<Line> items;
// a no-argument constructor, getters and setters
}
Filters, order and a cap on a child¶
child takes a ChildQuery to filter a child, order it and bound it:
.child(QCustomerOrders.ORDERS, orders, c -> c
.where(f -> f.eq(QOrderLines.STATUS, "PAID"))
.orderBy(QOrderLines.TOTAL.desc())
.maxPerParent(50))
The child's order is closed by its primary key, which is also the default order. A child row is read once per parent,
so a filter through a to-many join does not repeat it. A to-one child without a @PrimaryKey is not
deduplicated: reached through a to-many path it fails with MQ2601 on repeated rows, so give it a @PrimaryKey.
What to know¶
- A child not in the plan reads as empty. A model holds
List.of()orOptional.empty()until its child is loaded. A model from a query without the plan, or with a plan that omits the child, looks the same as a parent that has no children. Do not read an empty list as "none exist" unless the plan loads that child. - Children are unbounded without
maxPerParent. A page of 50 parents loads every child of those 50. WithmaxPerParent(n), a parent with more thannchildren, or a statement that reads its row cap, fails withMQ2603instead of loading them. Set it on every child whose size you do not control. - One consistent snapshot only inside a transaction. A page and each child load are separate statements. Outside a
transaction they are separate reads, and a child can change between them. Run the call in a read-only transaction to
read all of them from one snapshot. Child loads run on the same
EntityManager, inside your transaction if there is one. - Child keys are matched on the database values, split into rounds of at most the vendor's bind limit, so a large page
runs more than one statement per child. A child whose key matches none of its round's keys, which a case-insensitive
collation can cause, fails with
MQ2604. - A child on a grouped query is refused (
MQ1704): a grouped row has no single key. - A column a plan needs may not be read through a to-many join (
MQ1702), and a plan that names a child or join twice fails withMQ1703.
Many-to-many children¶
A many-to-many child has several parents, and each parent has several of it. It appears under every parent it belongs to. There are two ways to declare one.
From the child's side. If the child's entity maps the association back, a foreignKey may cross the child's
collection. An order's labels, where LabelEntity.orders is the owning side:
@QueryModel(root = OrderEntity.class)
public record OrderLabels(
@PrimaryKey Long id,
@Child(foreignKey = "orders.id") List<LabelView> labels) {}
With through. When the association is mapped on the parent's side only, name the path from the parent's entity
to the child's entity instead. The child query is rooted at the parent's entity and joined along the path.
// A unidirectional @ManyToMany: PatronEntity.referrers has no way back.
@QueryModel(root = PatronEntity.class)
public record PatronReferrers(
@PrimaryKey Long id,
@Child(through = "referrers") List<Referrer> referrers) {}
// The inverse side of a bidirectional one: OrderEntity.labels is mappedBy LabelEntity.orders.
@QueryModel(root = OrderEntity.class)
public record OrderLabelSet(
@PrimaryKey Long id,
@Child(through = "labels") List<LabelView> labels) {}
// Through a join entity: a label, the orders that carry it, and their customers.
@QueryModel(root = LabelEntity.class)
public record LabelBuyers(
@PrimaryKey Long id,
@Child(through = "orders.customer") List<Buyer> buyers) {}
The rules for through:
- The path may cross associations only, to-one or to-many, and must end at the child model's root entity. Anything else
is
MQ3406. - The parent's
keymust be its root's single@Id, which is the default. Any other key isMQ3406. throughandforeignKeyexclude each other (MQ3401).- A grouped child model is refused (
MQ3406). - A child's filter, order and customizer resolve their paths against the join at the end of the path, so the generated
columns of the child model work unchanged. A customizer must resolve paths through its
JoinContext, not throughquery.getRoots(), which holds the parent's entity.
So a through child is filtered, ordered and nested like any other. A label's paid orders, largest first, each with
its items:
@QueryModel(root = LabelEntity.class)
public record LabelOrders(
@PrimaryKey Long id,
@Child(through = "orders") List<OrderLines> orders) {}
FetchPlan<LabelOrders> plan = FetchPlan.of(QLabelOrders.ALL)
.child(QLabelOrders.ORDERS,
FetchPlan.of(QOrderLines.ALL).child(QOrderLines.ITEMS, FetchPlan.of(QLine.ALL)),
c -> c.where(f -> f.eq(QOrderLines.STATUS, "PAID")) // OrderLines.status, on the joined order
.orderBy(QOrderLines.TOTAL.desc()));
Plans through a join¶
A @Join field holds a model read in the same row. A plan for that model applies through the join, with its columns
re-rooted under it, so one plan serves on its own and nested:
@QueryModel(root = CustomerEntity.class)
public record Patron(
@PrimaryKey Long id,
String name,
@Child(foreignKey = "customer.id") List<OrderRef> orders) {}
@QueryModel(root = OrderEntity.class)
public record OrderPatrons(
@PrimaryKey Long id,
String status,
@Join Optional<Patron> customer,
@Join Optional<Patron> referrer) {} // a LEFT join: most orders have no referrer
FetchPlan<Patron> patron = FetchPlan.of(QPatron.ALL).child(QPatron.ORDERS, FetchPlan.of(QOrderRef.ALL));
FetchPlan<OrderPatrons> plan = FetchPlan.of(QOrderPatrons.ALL)
.join(QOrderPatrons.CUSTOMER_JOIN, patron) // the same plan under both joins
.join(QOrderPatrons.REFERRER_JOIN, patron);
The processor generates a JoinField constant per @Join, such as QOrderPatrons.CUSTOMER_JOIN. The patron plan
also runs on its own, on QPatron.query().fetch(patron). Its child loads in batches for all the page's customers,
not one statement per order.
An empty Optional from a LEFT join is skipped. A join plan whose join has no selected column at or below it fails
with MQ1701, and one that selects an aggregate with MQ1705.
Enrichers¶
An enricher fills a field the database cannot, once per page, from code you own. The field is @Transient, which the
library never fills itself, and the model needs a way to return a copy with it set. The enricher declares the columns it
reads, and the plan selects them for you.
Enricher.byKey collects a key from each model, makes one lookup for the page's distinct keys, and fills each model
from the result:
@QueryModel(root = CustomerEntity.class)
public record CustomerCard(
@PrimaryKey Long id,
String email,
@Transient Optional<LoyaltyTier> tier) {
CustomerCard withTier(Optional<LoyaltyTier> value) {
return new CustomerCard(id, email, value);
}
}
FetchPlan<CustomerCard> plan = FetchPlan.of(QCustomerCard.ALL)
.enrich(Enricher.byKey(
CustomerCard::email, // the key of one model
emails -> loyalty.tiersFor(emails), // one call per page: Map<String, LoyaltyTier>
(c, tier) -> c.withTier(Optional.of(tier)), // a model whose key is missing from the map stays as is
QCustomerCard.EMAIL)); // the columns the key reads
Enricher.of takes the whole page and returns it filled, one model per position, in the page's order: position i of
the result replaces position i of the page. Use it when your code already fills a list of models, or a value depends
on the page as a whole rather than on one key:
.enrich(Enricher.of(page -> loyalty.fillTiers(page), QCustomerCard.EMAIL)) // List<CustomerCard> in, same size out
A result of another size, or with a null element, fails with MQ2602.
An enricher on a joined model¶
A plan under a @Join carries its own enrichers, and join(...) runs them on the models the join produced, once per
page, before the outer plan's enrichers:
FetchPlan<Patron> patron = FetchPlan.of(SelectSet.of(QPatron.ID))
.child(QPatron.ORDERS, FetchPlan.of(QOrderRef.ALL))
.enrich(Enricher.byKey(Patron::name,
names -> names.stream().collect(Collectors.toMap(Function.identity(), name -> name + "/")),
(p, tag) -> p.withTag(tag + p.orders().size()),
QPatron.NAME));
FetchPlan<OrderPatrons> order = FetchPlan.of(SelectSet.of(QOrderPatrons.ID))
.join(QOrderPatrons.CUSTOMER_JOIN, patron)
.join(QOrderPatrons.REFERRER_JOIN, patron);
A lookup keyed by several columns¶
The key of a byKey enricher can be any type, including a record of several columns; the plan selects the columns the
key reads, and the lookup gets the page's distinct keys in one call:
record ArtistRef(long artistId, int catalogId) {}
Enricher<Line> profileEnricher = Enricher.byKey(
line -> new ArtistRef(line.id(), line.quantity()),
PROFILES::find, // one call per page: Map<ArtistRef, String>
(line, profile) -> line.withProfile(profile),
QLine.ID, QLine.QUANTITY);
Several keys on one model¶
A model with more than one look-up key uses byKeys: one key(...) per field, all on the same lookup, whose values
must share a type. byKey is its one-key case.
record PartyKey(int partyType, long partyId) {}
Enricher<DeliveryView> parties = Enricher.<DeliveryView, PartyKey, String>byKeys(
profiles::find) // one call per run: Map<PartyKey, String>
.key(DeliveryView::senderKey, DeliveryView::withSender)
.key(DeliveryView::recipientKey, DeliveryView::withRecipient)
.key(DeliveryView::courierKey, DeliveryView::withCourier)
.key(DeliveryView::approverKey, DeliveryView::withApprover) // null when absent: skipped
.reading(QDeliveryView.SENDER_PARTY_TYPE, QDeliveryView.SENDER_PARTY_ID,
QDeliveryView.RECIPIENT_PARTY_TYPE, QDeliveryView.RECIPIENT_PARTY_ID,
QDeliveryView.COURIER_PARTY_TYPE, QDeliveryView.COURIER_PARTY_ID,
QDeliveryView.APPROVER_PARTY_TYPE, QDeliveryView.APPROVER_PARTY_ID);
- For each model in page order and each key in declaration order, a
nullkey is skipped and never looked up, so an absent approver costs nothing. - The distinct non-null keys across models and keys go to one lookup call per run — a page, or an export batch — as an unmodifiable set in first-seen order. A party in two roles, or in two models, is looked up once and its value is passed to every role's setter.
batchSize(n)splits that set into consecutive chunks of at mostnkeys, in the same order, one call per chunk, on the calling thread. Each chunk is handed to the lookup once, so a lookup that itself splits its keys by a key part (one datasource per party type, say) calls each source at most once per chunk.- An absent key, or a
nullmap value, leaves the model as is. Size and order cannot change. reading(...)with nokey(...)fails withMQ1706, andbatchSize(0)withMQ1707, both at definition; a lookup returningnullfails withMQ2606.
Because Java cannot infer M through a builder chain of implicit lambdas, byKeys takes the explicit type witnesses
shown above. A plan built per call captures request-time state — a parameter, a cache shared with a child's
enricher — through withFetch(...) (see the recipes).
The order a plan runs in¶
Within a plan, children and joins run first, then its enrichers in the order added. A nested plan, under a join or a child, runs whole before the outer plan's enrichers, so an outer enricher sees the joined models filled:
FetchPlan<Patron> patron = FetchPlan.of(QPatron.ALL)
.child(QPatron.ORDERS, FetchPlan.of(QOrderRef.ALL)) // 1. the customer's orders
.enrich(Enricher.of(page -> tagged(page))); // 2. reads p.orders()
FetchPlan<OrderPatrons> plan = FetchPlan.of(QOrderPatrons.ALL)
.join(QOrderPatrons.CUSTOMER_JOIN, patron)
.enrich(Enricher.of(page -> noted(page), QOrderPatrons.STATUS)); // 3. reads o.customer() and its tag
Child loads over partitioned tables¶
Incubating
Key groups are annotated @Incubating (see API stability).
A child load asks for key IN (…). On a table partitioned by a column the key does not carry, such as a creation
time, that statement reads every partition. When the key encodes the partition, as a time-ordered id does, group the
keys: keyGroups reads a child's keys in rounds per group and binds each group's range into the same filter, so each
round reads only its partition.
A KeyGroups takes the key type and a function from a key to its group. bind gives a QueryParam the value of a
group, and the child's where reads that param. Here the parent order's id is a time-ordered id and monthOf(order)
is the month its events are created in:
record Month(Instant from, Instant to) {}
static final QueryParam<Instant> CREATED_FROM = QueryParam.of("createdFrom", Instant.class);
static final KeyGroups<Long, Month> BY_ORDER_MONTH = KeyGroups.by(Long.class, (Long order) -> monthOf(order))
.bind(CREATED_FROM, Month::from)
.assumeInRange();
FetchPlan<OrderEvents> plan = FetchPlan.of(QOrderEvents.ALL)
.child(QOrderEvents.EVENTS, FetchPlan.of(QEvent.ALL), c -> c
.where(f -> f.compare(QEvent.CREATED_AT, Op.GTE, Expr.param(CREATED_FROM)))
.keyGroups(BY_ORDER_MONTH));
var q = QOrderEvents.query().fetch(plan).orderBy(QOrderEvents.ID.asc()).build();
The plan is run as any other:
List<OrderEvents> orders = executor.list(q, Limit.of(100));
List<OrderEvents> orders = orderRepository.findAll(q, Limit.of(100));
The page's keys are split by group, in the order they first appear, and each group is read in its own round, with
its own value bound and the same statement text. Each key is in exactly one round, and a group larger than the
vendor's bind limit is split further. BY_ORDER_MONTH is a constant: a KeyGroups is immutable, and the engine
compares it by identity, so build it once.
Every declaration ends in verifyMissing(all) or assumeInRange(), since a child row whose partition column
disagrees with the value its key encodes (a backfill, clock skew, a time-zone edge at a month boundary) is excluded by
the bound filter:
assumeInRange()does not look for such rows. A row outside its key's range is silently not read, and the key looks like it has no children.verifyMissing(all)reads again, with the values ofall, the keys that found no row, and returns what that finds. It costs nothing while the keys agree with the data, and one statement over all partitions for the keys that do not. It logsMQ2608once per definition when a re-read finds a row. A to-many child cannot use it: a list that came back shorter than it should is not seen, soverifyMissingon one isMQ1708.
On a to-many child, a group param may be read only as a column's lower bound (>= or > with the param on the right)
or with EQ, since an upper bound would cut a parent's list. A lower bound alone drops the earlier partitions only,
about half of them on average, and its groups multiply when parents precede their children. Prefer a coarser group.
A to-one child loaded through an association path has at most one row per key, so it takes verifyMissing and a
two-sided range, and prunes to one partition. Under verifyMissing or groupWhen a group param may be read only in a
>, >=, < or <= comparison with a column, in one direction per param, since one catch-all value can't widen an
=, a <> or a read under NOT; assumeInRange() without groupWhen keeps any read.
Grouping pays when many keys share a group, and costs when they do not. Measured on PostgreSQL and MySQL:
- Group when each group holds about 300 keys or more. Keys that cluster (a time-ordered batch, one tenant's page) group well; keys spread thin over every partition do not.
- Do not group a small page spread over many partitions. Fifty keys over 36 months are 36 statements, about twenty
times slower than one. Key groups apply per child round, so every page of an export pays this.
groupWhen(rule, all)lets the call decide from the number of keys and groups (GroupingRule.minKeysPerGroup(300),GroupingRule.maxGroups(n)): when the rule says no, the load runs its ordinary rounds withall's values bound.allis the catch-all value, andverifyMissingaftergroupWhenmust be given the same one. - With
verifyMissing, bind the exact range. A margin widens the scan: a day's margin on a month overlaps three partitions. Past about 10 % misses the re-read is a large share of the ungrouped cost. - Bound values are the attribute's type, an
InstantfortimestamptzorDATETIME. They reach the driver as aTimestamp, which prunes on PostgreSQL and MySQL; the JVM and the database session must agree on the time zone, or a value at a boundary lands in the neighbouring partition. - PostgreSQL prunes at run time with generic plans and at plan time with custom ones; MySQL prunes at each execution.
On MySQL,
PARTITION BY RANGE COLUMNS (created_at)prunes cleaner thanRANGE (TO_DAYS(created_at)). MySQL needs the partition column in every unique key, so the table's primary key is(id, created_at)while the entity's@Idcan stayid.
A grouped ModelQuery (see Reading many keys) is a different
thing from a child's keyGroups: it is read only by byKeys and one(q, key).
Values and maps¶
An @ElementCollection holds values rather than entities: tags, phone numbers, the stops of a route, translations by
locale. A @Child(through = "...") whose path ends at one reads it into the model, and a @FilterColumn may filter
through it. All of it is incubating, new in 0.16.0. The examples read this entity:
@Entity
@Table(name = "orders")
public class OrderEntity {
@Id Long id;
String number;
@ElementCollection
@CollectionTable(name = "order_tags", joinColumns = @JoinColumn(name = "order_id"))
@Column(name = "tag")
List<String> tags;
@ElementCollection
@CollectionTable(name = "order_stops", joinColumns = @JoinColumn(name = "order_id"))
List<Stop> stops; // Stop is an @Embeddable with a city and a lat
@ElementCollection
@CollectionTable(name = "order_labels", joinColumns = @JoinColumn(name = "order_id"))
@MapKeyColumn(name = "label_key")
@Column(name = "label_val")
Map<String, String> labels;
}
Value children¶
A List or Set of the element type is a value child. The processor generates a ValueChildField, and
FetchPlan#values loads it:
@QueryModel(root = OrderEntity.class)
public record OrderTags(
@PrimaryKey Long id,
String number,
@Child(through = "tags") List<String> tags,
@Child(through = "tags") Set<String> tagSet) {}
var tags = QOrderTags.query()
.fetch(FetchPlan.of(QOrderTags.ALL)
.values(QOrderTags.TAGS)
.values(QOrderTags.TAG_SET, v -> v.maxPerParent(50)))
.orderBy(QOrderTags.NUMBER.asc())
.build();
List<OrderTags> list = executor.list(tags, Limit.of(100));
List<OrderTags> list = orderRepository.findAll(tags, Limit.of(100));
- A bag. One statement per round selects the parent's key and the value, and keeps every row: two equal tags are
two entries of the
List, and aNULLelement is kept. ASetkeeps the first of equal values. - Order. The
@OrderColumn's position first, if the mapping has one, then the value itself, unless it is a LOB.NULLsorts last on every database. A basic element type the database cannot order fails the load; mark it@Lob. - The key. Values match on the root's single
@Id, so the value child needs no@PrimaryKeyof its own. Thethroughpath may cross to-one associations first ("customer.tags"), never a collection (MQ3406). - The bound.
maxPerParent(n)counts rows, before aSetcollapses equal values; a parent with more isMQ2603. A value has no column to filter or order by, sovalues(field, v -> ...)takes nothing else. - The field. A field that is not a
ListorSetof the element type isMQ3407, and an element type the collection doesn't hold isMQ3002. A converted element is compared as the type its converter produces.
Embeddable elements: @ElementModel¶
Elements that are embeddables are read into an @ElementModel: a model of the embeddable, with columns, ALL and
MAPPER but no query() of its own. A List of it is a child, loaded with child(field, plan), whose query may
filter and order by the element's columns:
@ElementModel(Stop.class)
public record StopRow(String city, BigDecimal lat) {}
@QueryModel(root = OrderEntity.class)
public record OrderStops(@PrimaryKey Long id, @Child(through = "stops") List<StopRow> stops) {}
var stops = QOrderStops.query()
.fetch(FetchPlan.of(QOrderStops.ALL)
.child(QOrderStops.STOPS, FetchPlan.of(QStopRow.ALL), c -> c.orderBy(QStopRow.CITY.asc())))
.build();
List<OrderStops> list = executor.list(stops, Limit.of(100));
List<OrderStops> list = orderRepository.findAll(stops, Limit.of(100));
Element rows are bags too: a repeated stop is two rows, and an element whose columns are all NULL maps to a model
with null fields. An @ElementModel takes no @PrimaryKey, @Child, @Join or @FilterColumn (MQ3407 and the
model codes), and a model that is not the element model of the collection's embeddable is MQ3407.
Maps¶
A Map<K, V> field over a map element collection is a map child, loaded with FetchPlan#map. The key is a basic
value; the value is a basic value or an @ElementModel of an embeddable:
@QueryModel(root = OrderEntity.class)
public record OrderLabels(@PrimaryKey Long id, @Child(through = "labels") Map<String, String> labels) {}
var labels = QOrderLabels.query()
.fetch(FetchPlan.of(QOrderLabels.ALL).map(QOrderLabels.LABELS))
.build();
List<OrderLabels> list = executor.list(labels, Limit.of(100));
List<OrderLabels> list = orderRepository.findAll(labels, Limit.of(100));
An element-model map value can be filtered by its columns. For an element collection named spots whose values are
the Stop embeddable above:
@QueryModel(root = OrderEntity.class)
public record OrderSpots(@PrimaryKey Long id, @Child(through = "spots") Map<String, StopRow> spots) {}
var spots = QOrderSpots.query()
.fetch(FetchPlan.of(QOrderSpots.ALL).map(QOrderSpots.SPOTS,
q -> q.where(f -> f.eq(QStopRow.CITY, "Rome")).maxPerParent(1)))
.build();
List<OrderSpots> matching = executor.list(spots, Limit.of(100));
List<OrderSpots> matching = orderRepository.findAll(spots, Limit.of(100));
The bound counts matching entries. A non-empty filter on a basic-valued map fails at plan build with MQ1714.
- No order. The map is a
LinkedHashMapin the order the rows come; the statement never orders by the key, which EclipseLink can't render for an embeddable value. - Duplicate keys. Two entries with the same Java key for one parent are
MQ2609. Only a lossy key converter can make them, and a key converter (@Convert(attributeName = "key")) works on Hibernate only: EclipseLink refuses the mapping at startup. - Refused shapes. An entity or embeddable key, and a
Map<K, Entity>association, areMQ3408; read the latter as@Child(through = "...") List<...>of the entity's model.
Filters through an element collection¶
A @FilterColumn path may end at an element collection of basic values, or a map's values, or go on into an
embeddable element's attributes. It needs a joinType, as any path through a collection does (MQ3011):
@QueryModel(root = OrderEntity.class)
@FilterColumn(name = "TAG", path = "tags", joinType = JoinKind.LEFT)
@FilterColumn(name = "STOP_CITY", path = "stops.city", joinType = JoinKind.LEFT)
@FilterColumn(name = "LABEL", path = "labels", joinType = JoinKind.LEFT)
public record OrderSearch(@PrimaryKey Long id, String number) {}
The collection gets its table constant, TAGS_TABLE, only when a filter column goes through it, so a model with no
such filter gains no member that could clash with a field's name. A filter on the element, and exists over the
constant, bare or with a group:
var rush = QOrderSearch.query().select(QOrderSearch.ALL)
.where(f -> f.eq(QOrderSearch.TAG, "rush"))
.build();
var tagged = QOrderSearch.query().select(QOrderSearch.ALL)
.where(f -> f.exists(QOrderSearch.TAGS_TABLE))
.build();
var inRome = QOrderSearch.query().select(QOrderSearch.ALL)
.where(f -> f.exists(QOrderSearch.STOPS_TABLE, s -> s.eq(QOrderSearch.STOP_CITY, "Rome")))
.build();
List<OrderSearch> list = executor.list(rush, Limit.of(100));
long count = executor.count(rush);
List<OrderSearch> list = orderRepository.findAll(rush, Limit.of(100));
long count = orderRepository.count(rush);
An order tagged rush twice comes once, and count counts it once: a filter whose join nothing else in the statement
keeps renders as a semi-join, like any filter through a to-many join:
select o.id, o.number from orders o
where exists (select 1 from orders o2 left join order_tags t on o2.id = t.order_id
where o2.id = o.id and t.tag = ?)
A statement that also selects or orders by the element keeps the join, one row per element. By hand, the value of a basic element is a column with no attribute, on the collection's join, which a query may select:
record OrderTag(Long id, String tag) {}
static final TableField<OrderEntity, OrderEntity> ORDERS = TableField.root(OrderEntity.class);
static final TableField<OrderEntity, String> TAGS = TableField.join(ORDERS, "tags", JoinType.INNER);
static final ColumnField<OrderTag, OrderEntity, Long> ID = ColumnField.of(OrderTag.class, ORDERS, "id", Long.class);
static final ColumnField<OrderTag, String, String> TAG = ColumnField.element(OrderTag.class, TAGS, String.class);
var orderTags = ModelQuery.builder(ORDERS, row -> new OrderTag(row.get(ID), row.get(TAG)))
.select(SelectSet.of(ID, TAG))
.where(f -> f.in(TAG, List.of("rush", "gift")))
.build(); // one row per matching tag, and count counts the rows
ColumnField.element on anything but a join of basic values is MQ1002: an embeddable element's attributes are
columns of their own (ColumnField.of(OrderTag.class, STOPS, "city", String.class)). A @Join or a @JoinSource
column can't go through an element collection (MQ3003, MQ3044): a value repeated per parent row belongs in a
value child.
Diagnostics¶
The fetch-plan codes are MQ1701 to MQ1705 (checked when the query is built or first run), MQ2601 to MQ2605
(at execution) and MQ3401 to MQ3408 (at compile time); see Diagnostics. Value and map children
add MQ1713 (a value statement that joins another collection, at the plan build) and MQ2609 (a map key twice for
one parent). Key groups add
MQ1708 (a definition that does not match its child, or a group param read in a way the child does not allow, at the
plan build, before any statement), MQ2607 (a group function returned null, after the parent's statement and before
the first child round) and the logged MQ2608 (a row found only by the verifyMissing re-read). A param the child
reads that neither its model nor the groups bind stays MQ1512.
At DEBUG, the com.rey.modelquery.jpa.DefaultModelQueryExecutor logger logs each child load with its field and the
number of keys and rounds, for example child CustomerOrders.orders: 50 keys in 1 round(s). At TRACE, each round's
statement logs as any statement does. Key values are never logged; see Logging.