Cube Query Engine
Pivot, grouped, and flat queries over JPA entities, built for grid UIs such as AG Grid's Server-Side Row Model, with no-probing security.
Overview
A Genesis Spring/JPA application normally reads its data through hand-written repository queries
or the JPA entities generated from the dictionary (see Data access APIs (JPA) and
Data model (Spring)). The genesis-data-cube-spring-boot-starter module adds a
second, declarative layer on top of those same entities, purpose-built for grid UIs: flat, grouped
and pivoted queries, with paging, filtering and an HTTP wire protocol tuned for AG Grid's
Server-Side Row Model (SSRM).
Concretely, it gives you:
- A single query API,
Cube<ROW, FILTER>, covering flat rows, DTO-projected rows, and aggregated/pivotedTuplerows, all built from one consistent overload pattern (data → projection → window → scope). - A factory,
CubeFactory, that turns a JPA entity or a hand-written JPQL string into a cube, with the expensive state (query plan, pivot discovery, group counts) cached and shared across every caller of the same source. - A declarative exposure layer (
CubeResource, built viaCubeResourceBuilderor thecubeResource { }Kotlin DSL) that turns a cube into a named HTTP resource: which operations exist, which columns callers may group/pivot/filter on, and what per-user row scoping applies. - An internal HTTP wire layer exposing each resource at
/api/v1/cubes/{resource}/..., with ETag caching and RFC 9457problem+jsonerrors.
Reach for it when you're building a grid-backed view — a positions blotter, a P&L breakdown, a trade summary grouped and pivoted by currency — over data that already exists as a JPA entity, without wanting to hand-write JPQL, pagination, filtering and caching for every such view. If the view is a single named report shape, declare it as an operation; if the caller needs to choose its own grouping/pivoting (an AG Grid SSRM datasource), expose the whole cube instead.
What it is not:
- Not a replacement for the classic Genesis Data Server / Request Server query path — it is a parallel, JPA/Hibernate-backed, HTTP-first surface that sits alongside it.
- Not a general-purpose reporting engine: filtering on an aggregated measure after grouping
(
HAVING) is not available over HTTP, and pivot discovery is capped (25 discovered columns by default; see Query types). - Not a write path. A cube is read-only; writes still go through the normal JPA repository/entity layer.
The cube engine queries JPA entities — it does not generate or map entities itself. The entity a
cube reads is the JPA entity generated by the Spring data-model codegen (it extends
GenesisReadOnlyJpaEntity), in the package set by genesisSpring { entities { packageName } } —
see Data model (Spring). That entity must already exist before you can build a
cube over it, whether you use the entity API directly or write JPQL against it.
Set-up
Add the starter alongside genesis-spring-boot-starter:
dependencies {
implementation("global.genesis:genesis-data-cube-spring-boot-starter")
}
Set these properties in the Spring module's application.properties (or application.yml) — see
Getting Started with Spring: Step 11:
| Property | Default | Purpose |
|---|---|---|
genesis.cube.pivot-ttl-millis | 600000 (10 min) | Default time-to-live for a discovered pivot's column set, overridable per call |
genesis.cube.remembered-max-entries | 1000 | Bound on how many distinct query plans/runners CubeFactory caches |
genesis.cube.web.max-page-size | 1000 | Ceiling on the wire size parameter |
genesis.cube.web.max-filter-length | 8192 | Character budget for the wire filter parameter before you should switch from GET to POST |
genesis.cube.web.max-sort-orders | 64 | Ceiling on the number of comma-separated sort entries |
genesis.cube.pivot.max-columns | 25 | Ceiling on the number of discovered pivot columns, and on an OverflowPolicy.TopN bound. Must be at least 1; anything else fails startup |
The starter registers its HTTP layer through its own autoconfiguration, independently of
GenesisSpringBootConfiguration and GenesisSpringWebConfig — excluding those two from a test
context does not exclude a cube resource's endpoints.
The curl/wire examples below assume the default port 8080 — see Getting Started with Spring: Step
11 for how to run on a different port via plain Spring Boot
server.port configuration.
Declaring a cube resource
Every code sample on this page refers to the following types by their simple name only:
| Type | Package | Notes |
|---|---|---|
CubeResource | global.genesis.spring.data.cube.resource | |
CubeResourceRegistry | global.genesis.spring.data.cube.resource | |
ResolvedCubeResource | global.genesis.spring.data.cube.resource | |
PrincipalValues | global.genesis.spring.data.cube.resource | |
cubeResource | global.genesis.spring.data.cube.resource | Kotlin DSL entry point, used as cubeResource { } to build a CubeResource; import it explicitly |
projection | global.genesis.spring.data.cube.resource | Kotlin DSL extension function, used as projection<T>() inside exposeQuery { } or operation(...) { }; import it explicitly |
CubeFactory | global.genesis.spring.data.cube | |
EntityCube | global.genesis.spring.data.cube | |
QueryRequest | global.genesis.spring.data.cube.model | |
GroupKey | global.genesis.spring.data.cube.model | |
Aggregate | global.genesis.spring.data.cube.model | |
Function | global.genesis.spring.data.cube.model | |
PivotSpec | global.genesis.spring.data.cube.model | |
PivotDimension | global.genesis.spring.data.cube.model | |
PivotMeasure | global.genesis.spring.data.cube.model | |
PivotDiscovery | global.genesis.spring.data.cube.model | Enum on PivotDimension: how a dimension's pivot columns are discovered (DISTINCT or INTERVAL) |
CubeResult<T> | global.genesis.spring.data.cube.model | What Cube.query(filter, pageable) and query(request, pageable) return: a Spring Data Page plus the result's columns |
EntityQueryRequest<E> | global.genesis.spring.data.cube.model | A QueryRequest whose filter is a JPA Specification<E> |
UnfilteredQueryRequest | global.genesis.spring.data.cube.model | A QueryRequest with no filter |
EntityCriteriaCube<E> | global.genesis.spring.data.cube | What CubeFactory.forEntityCriteria(...) returns: an entity cube whose filter is a criteriaMatch string |
Tuple | jakarta.persistence | |
Pageable | org.springframework.data.domain | |
PageRequest | org.springframework.data.domain |
A CubeResource is an immutable descriptor, built via the Java-first CubeResourceBuilder or the
Kotlin cubeResource { } DSL, then published as a Spring bean. At startup, every CubeResource
bean is resolved and validated fail-fast: referenced columns must exist on the entity, a
JPQL-sourced exposure's projection aliases must all resolve to real columns on the source query, an
operation must declare at least one groupBy/aggregation, an operation's aggregates must suit
their columns' types (a SUM over a string column, for example), output column names must not
collide, and none may be named ROW_REF (reserved for row addressing). An operation may not be
named query or schema, since those paths belong to the dynamic-query and schema endpoints. A
baseCriteria template is validated here too (see
Per-user row scoping). A misconfigured resource fails
application startup rather than the first request — a typo in a JPQL projection alias, for example,
throws at bean instantiation rather than silently mislabelling a column.
The smallest realistic exposure — one entity, one named operation, queried over HTTP — uses the
generated JPA entity Trade (fields including currencyId, tradeType, tradeDate,
quantity and price):
- Kotlin
- Java
import <packageName>.dao.Trade // the JPA entity generated into your entities.packageName
@Configuration
class TradeCubeConfig {
@Bean
fun tradesByCurrency(): CubeResource = cubeResource<Trade> {
// No exposeQuery(): only the named operation below is reachable over the wire.
operation("byCurrency") {
groupBy("currencyId")
sum("quantity")
}
// FilterPolicy.GroupKeys (the default): callers may only filter on currencyId.
}
}
import <packageName>.dao.Trade; // the JPA entity generated into your entities.packageName
@Configuration
public class TradeCubeConfig {
@Bean
public CubeResource tradesByCurrency() {
return CubeResource.forEntity(Trade.class)
.operation("byCurrency", op -> op
.groupBy("currencyId")
.sum("quantity"))
.build();
}
}
The bean name (tradesByCurrency) becomes the resource's wire name unless you pin one explicitly
with .name("..."). Query it at /api/v1/cubes/{resource}/{operation}, with filter as a
criteriaMatch expression (grammar covered in Filtering below):
GET /api/v1/cubes/tradesByCurrency/byCurrency?filter=currencyId=='USD'&sort=quantity&page=0&size=50
filter here is gated to the operation's filterable columns — just currencyId, its own group
key. Filtering on quantity is rejected the same way a made-up column would be (see
no-probing), because this operation declared no wider FilterPolicy. sort, page
and size default to unsorted, 0 and 100 respectively. A POST with a JSON body is equivalent
and preferred for longer filters.
A few further builder forms exist alongside the ones above: exposeQuery() with no customizer
exposes the dynamic query path with no restrictions (equivalent to an empty block); sum, avg,
min and max each take an optional second argument naming the output alias
(sum("quantity", "totalQuantity")), defaulting to the source column's own name; and count()
similarly takes an optional alias, as count("widgetCount").
Like any endpoint behind a Genesis Spring Boot app's session-token
authentication, a cube endpoint needs a valid
SESSION_AUTH_TOKEN to answer anything but 401 — see Testing an HTTP
endpoint for a complete MockMvc test against a
@RestController endpoint that stubs the session lookup instead of logging in for real; the same
shape works against a cube resource's endpoints.
The response is an envelope object: a rows array, hasMore, rowKind, an echoed page, and the
resolved columns — plus a ROW_REF per row when the operation's group key doubles as its
addressable identity. ROW_REF is an opaque, versioned identity string — round-trip it as
supplied rather than parsing or constructing one yourself.
For the byCurrency operation above, the response looks like this (the ROW_REF value is
elided; it is opaque):
{
"rows": [
{ "currencyId": "USD", "quantity": 1250, "ROW_REF": "..." }
],
"hasMore": false,
"rowKind": "GROUPED",
"page": { "number": 0, "size": 50 },
"columns": [
{ "name": "currencyId", "role": "KEY", "type": "STRING", "pivot": null, "groupLevel": null, "numberAsString": false, "encoding": null },
{ "name": "quantity", "role": "MEASURE", "type": "LONG", "pivot": null, "groupLevel": null, "numberAsString": false, "encoding": null },
{ "name": "ROW_REF", "role": "ROW_REF", "type": "STRING", "pivot": null, "groupLevel": null, "numberAsString": false, "encoding": null }
],
"generation": "..."
}
| Envelope field | Meaning |
|---|---|
rows | The page of rows, in the order columns describes |
hasMore | Whether a further page exists past this one |
rowKind | How a row can be addressed back: FLAT, GROUPED, TOTAL or UNADDRESSABLE. TOTAL and UNADDRESSABLE publish no ROW_REF |
page | The number and size the caller asked for (not the effective sort) |
columns | One descriptor per result column, plus a ROW_REF descriptor when rows carry one |
generation | The source-freshness sample the response's ETag was minted from (see Caching). null exactly when no ETag is emitted |
Each entry in columns is a column descriptor:
| Descriptor field | Meaning |
|---|---|
name | The column's stable output name; read row values by it |
role | KEY (a non-aggregated column), MEASURE (an aggregate), PIVOT (a data-driven pivot column) or ROW_REF |
type | The Genesis dictionary field type of the column |
pivot | Present only on a PIVOT column, otherwise null: the values the column slices by (one per pivot dimension, in order), the base measure it aggregates, and other (true for the catch-all OTHER bucket, whose values is empty) |
groupLevel | The hierarchy level a KEY column groups at during a lazy group expansion (0 is the top level); null otherwise |
numberAsString | true when the column's values arrive as JSON strings rather than numbers, because their range would not survive a JSON number. A client must not parse them as numbers |
encoding | The declared encoding of a RAW column, when one was declared; null means base64. A declared BASE_64 reads the same as null, so do not treat a non-null encoding alone as "this column is text" |
A pivot column's descriptor therefore looks like this (its name is generated by the cube, shown
here as a placeholder):
{
"name": "<generated name>",
"role": "PIVOT",
"type": "LONG",
"pivot": { "values": ["USD"], "measure": "totalQuantity", "other": false },
"groupLevel": null,
"numberAsString": false,
"encoding": null
}
Query types
Cube<ROW, FILTER> answers three query shapes — flat, grouped, and pivoted — each following the
data → projection → window → scope order introduced above.
Flat
Plain rows, no aggregation — query(filter, pageable). A cube can be built over a mapped JPA
entity or over hand-written JPQL text; both share the same query surface once built. The
difference is only in how the source is declared and how the raw row is shaped (ROW is the entity
type for an entity cube, always Tuple for a JPQL cube, since it's a column projection):
- Kotlin
- Java
@Autowired
lateinit var cubeFactory: CubeFactory
fun example(pageable: Pageable) {
val trades: EntityCube<Trade> = cubeFactory.forEntity(Trade::class.java)
val page = trades.query(filter = null, pageable = pageable) // CubeResult<Trade>
}
@Autowired
CubeFactory cubeFactory;
void example(Pageable pageable) {
EntityCube<Trade> trades = cubeFactory.forEntity(Trade.class);
CubeResult<Trade> page = trades.query(null, pageable);
}
forJpql parses and validates the query eagerly, at cube-creation time rather than on first
query — a bad source, or a join without allowJoins = true acknowledged explicitly (a join can
multiply rows and inflate SUM/COUNT), fails fast here rather than on a caller's request.
A read that selects rows by position (a page, or a limited list) comes back in a total order — the caller's sort, then the row's own identity as a tiebreaker — so paging never repeats or drops rows, provided the source has an identity to tiebreak on. An unpaged, unsorted read is explicitly arbitrary order, not a stable one to rely on. See Sorting for what a flat request can sort on.
Every column in a flat query's response — including a computed one, such as a JPQL expression
column — carries role: KEY in the envelope's columns list, since none of them are aggregated;
role only distinguishes KEY/MEASURE/ROW_REF once a query groups or pivots (see
Grouped below).
Grouped
Group keys plus aggregates (SUM/AVG/MIN/MAX/COUNT), returned as Tuples or a projection
DTO. A resource exposes this dynamically with .exposeQuery { }, bounding which columns a caller
may group by:
- Kotlin
- Java
import global.genesis.spring.data.cube.resource.projection
val trades = cubeResource<Trade> {
exposeQuery {
projection<TradeFlat>() // the caller's flat shape when it groups by nothing
groupBy("currencyId", "tradeDate") // grouping is narrowed to these two columns
pivotOn("currencyId") // pivoting is narrowed to this one column
}
}
CubeResource trades = CubeResource.forEntity(Trade.class)
.exposeQuery(q -> q
.projection(TradeFlat.class)
.groupBy("currencyId", "tradeDate")
.pivotOn("currencyId"))
.build();
TradeFlat is a plain projection of Trade's query-relevant columns:
- Kotlin
- Java
data class TradeFlat(
val tradeId: Long,
val currencyId: String,
val tradeDate: OffsetDateTime,
val quantity: Int,
val price: Double,
)
record TradeFlat(long tradeId, String currencyId, OffsetDateTime tradeDate, int quantity, double price) {}
Every shape goes through POST /api/v1/cubes/{resource}/query (there's no GET here — the query
shape doesn't fit comfortably in query parameters). A grouped request populates groupKeys and
aggregates:
POST /api/v1/cubes/trades/query
{
"groupKeys": [
{ "expr": { "type": "field", "attribute": "currencyId" } }
],
"aggregates": [
{
"function": "SUM",
"input": { "type": "field", "attribute": "quantity" },
"alias": "totalQuantity"
}
]
}
Every column named in the request must lie within the resource's visible set — the same
no-probing rule that governs every other rejection. Post-aggregation filtering
(HAVING) is not available over HTTP.
The POST .../query body accepts only filter, sort, page, size, groupKeys, aggregates,
calculations and pivot, whichever query type you send. Any other field is rejected with 400
rather than ignored — including having and groupExpansion, which exist on the in-process
QueryRequest but not on the wire.
See Sorting for what a grouped request can sort on.
The same shape is also reachable directly in-process, with no resource involved — Cube.query
takes a QueryRequest overload alongside the flat one, always returning Tuples:
- Kotlin
- Java
@Autowired
lateinit var cubeFactory: CubeFactory
fun example(pageable: Pageable) {
val trades: EntityCube<Trade> = cubeFactory.forEntity(Trade::class.java)
val grouped: CubeResult<Tuple> = trades.query(
QueryRequest(
groupKeys = listOf(GroupKey("currencyId", "currencyId")),
aggregates = listOf(Aggregate(Function.SUM, "quantity", "totalQuantity")),
filter = null,
),
pageable,
)
}
@Autowired
CubeFactory cubeFactory;
void example(Pageable pageable) {
EntityCube<Trade> trades = cubeFactory.forEntity(Trade.class);
CubeResult<Tuple> grouped = trades.query(
new EntityQueryRequest<>(
List.of(new GroupKey("currencyId", "currencyId")),
List.of(new Aggregate(Function.SUM, "quantity", "totalQuantity")),
List.of(),
null,
null,
null,
List.of()),
pageable);
}
For an entity cube, FILTER is a Spring Data JPA org.springframework.data.jpa.domain.Specification<Trade>
— not a criteriaMatch string (that's only the filter type for a cube built via forEntityCriteria/forJpqlCriteria,
shown in Filtering). A real, non-null filter for this generic overload is a Specification lambda:
- Kotlin
- Java
val filtered: CubeResult<Tuple> = trades.query(
QueryRequest(
groupKeys = listOf(GroupKey("currencyId", "currencyId")),
aggregates = listOf(Aggregate(Function.SUM, "quantity", "totalQuantity")),
filter = Specification { root, _, cb -> cb.equal(root.get<String>("currencyId"), "USD") },
),
pageable,
)
CubeResult<Tuple> filtered = trades.query(
new EntityQueryRequest<>(
List.of(new GroupKey("currencyId", "currencyId")),
List.of(new Aggregate(Function.SUM, "quantity", "totalQuantity")),
List.of(),
null,
null,
(root, query, cb) -> cb.equal(root.get("currencyId"), "USD"),
List.of()),
pageable);
Pivoted
A grouped query whose pivot is set: one or more pivot dimensions are discovered — their
distinct values found by a live query against current data — and become dynamic output columns.
noPivot() on the same exposeQuery spec disables pivoting entirely for a resource that should
never allow it.
POST /api/v1/cubes/trades/query
{
"groupKeys": [
{ "expr": { "type": "field", "attribute": "tradeDate" } }
],
"pivot": {
"dimensions": [
{ "expr": { "type": "field", "attribute": "currencyId" } }
],
"measures": [
{
"type": "aggregate",
"aggregate": {
"function": "SUM",
"input": { "type": "field", "attribute": "quantity" }
}
}
]
}
}
currencyId must additionally be in the resource's pivotOn allowlist to be used as a pivot
dimension. See Sorting for which pivot columns a request can sort on.
The response envelope of a pivot with group keys reports rowKind: GROUPED, because rowKind says
how a row is addressed (by its group keys), not which query shape produced it. The pivot shows up in
the column descriptors instead, as a pivot entry on each generated pivot column's descriptor.
The same request is callable directly in-process, exactly as for a grouped query:
- Kotlin
- Java
@Autowired
lateinit var cubeFactory: CubeFactory
fun example(pageable: Pageable) {
val trades: EntityCube<Trade> = cubeFactory.forEntity(Trade::class.java)
val pivoted: CubeResult<Tuple> = trades.query(
QueryRequest(
groupKeys = listOf(GroupKey("tradeDate", "tradeDate")),
pivot = PivotSpec(
dimensions = listOf(PivotDimension("currencyId", PivotDiscovery.DISTINCT, false, null, null, false)),
measures = listOf(PivotMeasure.OfAggregate(Aggregate(Function.SUM, "quantity", "totalQuantity"))),
),
filter = null,
),
pageable,
)
}
@Autowired
CubeFactory cubeFactory;
void example(Pageable pageable) {
EntityCube<Trade> trades = cubeFactory.forEntity(Trade.class);
CubeResult<Tuple> pivoted = trades.query(
new EntityQueryRequest<>(
List.of(new GroupKey("tradeDate", "tradeDate")),
List.of(),
List.of(),
new PivotSpec(
List.of(new PivotDimension("currencyId", PivotDiscovery.DISTINCT, false, null, null, false)),
List.of(new PivotMeasure.OfAggregate(new Aggregate(Function.SUM, "quantity", "totalQuantity")))),
null,
null,
List.of()),
pageable);
}
Discovered pivot-column count is capped by genesis.cube.pivot.max-columns (default 25; see
Set-up). A pivot whose discovered set (or an OverflowPolicy.TopN bound) would exceed
the cap fails the request rather than silently truncating — use an OverflowPolicy (TopN or
Within) to keep a high-cardinality pivot dimension under it.
A caller cannot request a group-expansion (an SSRM drill-down step) over HTTP: groupExpansion is
one of the fields the request body rejects (see Grouped). Drill down with the next level
as the only group key and an equality filter on the parent path instead (see Grid integration).
Explicit pivot values
Instead of discovering a dimension's values, a single-dimension pivot can name them explicitly.
Each value is typed (int, long, decimal or string; a decimal is sent as a string), and
includeOther adds a column that collects every row outside the listed values:
"dimensions": [
{
"expr": { "type": "field", "attribute": "currencyId" },
"values": [
{ "type": "string", "value": "USD" },
{ "type": "string", "value": "EUR" }
],
"includeOther": true
}
]
With explicit values the generated column names are known up front (SUM_quantity_USD,
SUM_quantity_EUR, SUM_quantity_OTHER), so the request can sort on them. Explicit
values cannot be combined with an overflow policy or with INTERVAL discovery, and
includeOther is rejected without values.
If the measure has an alias, the alias replaces the SUM_quantity part of these names, so the
columns are <alias>_<value> (alias q gives q_USD, not SUM_q_USD), and sorts and filters must
use that name.
Sorting
Sorting applies to every query type above. sort has its own, smaller grammar: a comma-separated
list of column names, each optionally prefixed with - for descending — no prefix means ascending,
and the order between entries is significant for a multi-column sort. It compiles to a Spring Data org.springframework.data.domain.Sort,
and the number of comma-separated entries is capped by genesis.cube.web.max-sort-orders (see
Set-up).
On POST .../query, a sort may only name the request's own output columns. A flat request can
sort on any visible column. A grouped request can sort on its group keys, aggregates and
calculations, using either the explicit alias or the derived name (currencyId for a group key,
SUM_quantity for an unaliased aggregate). A pivoted request can sort on generated columns only
when the pivot lists its values explicitly; discovered pivot columns can't
be sorted. Anything else is rejected with 400, naming the columns that may be sorted.
On a GET, sort, page and size are query parameters. On any POST — .../query or a named
operation — they are fields of the JSON body alongside filter: sort as the same comma-separated
string, page and size as numbers. A POST that carries a query string at all is rejected with
400. Sorting the grouped request from Grouped by total quantity, largest first, and
taking the first 50 groups:
POST /api/v1/cubes/trades/query
{
"groupKeys": [{ "expr": { "type": "field", "attribute": "currencyId" } }],
"aggregates": [
{ "function": "SUM", "input": { "type": "field", "attribute": "quantity" }, "alias": "totalQuantity" }
],
"sort": "-totalQuantity,currencyId",
"page": 0,
"size": 50
}
alias is optional on group keys, aggregates and calculations. An aggregate without one is named
from its function and input, so SUM over quantity becomes SUM_quantity; a group key without
one keeps its field name, as currencyId does here.
The same request, sorted on that derived name:
POST /api/v1/cubes/trades/query
{
"groupKeys": [{ "expr": { "type": "field", "attribute": "currencyId" } }],
"aggregates": [
{ "function": "SUM", "input": { "type": "field", "attribute": "quantity" } }
],
"sort": "-SUM_quantity,currencyId",
"page": 0,
"size": 50
}
Security
A resource or an operation can declare permission(...) with a Genesis user right code. The built-in
/api/v1/cubes endpoints check that code against the caller's rights: a request with no authenticated
caller is rejected with HTTP 401 (.../problems/cube/unauthenticated), and a caller who lacks the right
with HTTP 403 (.../problems/cube/forbidden). A request that names no operation is checked against the
resource's permission. A request that names an operation is checked against that operation's own
permission instead of the resource's, with no fallback, so an operation that declares none is open
even when its resource declares one. The describe and schema paths accept a caller who holds any one of
the route's rights.
No-probing and column visibility
The engine's central design invariant is that a caller can never tell a hidden column from a
nonexistent one. Every rejection — an unpermitted filter column, an unsortable one, a column
outside the visible set — surfaces as the same RFC 9457 problem+json error
(.../problems/cube/query-rejected), as HTTP 400 Bad Request with a standard ProblemDetail body.
The guarantee extends to the free-text detail field itself: its wording is a fixed template per
rejection kind (unpermitted filter column, unsortable column, outside the visible set) that only
ever echoes back column names the caller already supplied in their own request — so the string
never differs between a hidden column and a nonexistent one. Filtering tradesByCurrency on
quantity (a column that exists but isn't in this operation's FilterPolicy — see Declaring a
cube resource) produces exactly the same shape a request naming a
made-up column would:
{
"type": "https://docs.genesis.global/problems/cube/query-rejected",
"title": "Query rejected",
"status": 400,
"detail": "Filter references column(s) not filterable on cube resource 'tradesByCurrency': [quantity]. Only these columns may be filtered: [currencyId]"
}
Filtering on bogusColumn — a column that doesn't exist on Trade at all — produces the identical
shape, right down to the same type:
{
"type": "https://docs.genesis.global/problems/cube/query-rejected",
"title": "Query rejected",
"status": 400,
"detail": "Filter references column(s) not filterable on cube resource 'tradesByCurrency': [bogusColumn]. Only these columns may be filtered: [currencyId]"
}
Splitting that error per reason would reintroduce, in a machine-readable field, exactly the column-existence discrimination the rule exists to prevent.
That HTTP wrapping only happens at the HTTP endpoint boundary — an internal @RestControllerAdvice
scoped to that layer catches the rejection and renders it as the problem+json body above. Reached
in-process instead — via CubeResourceRegistry.require(name) returning a ResolvedCubeResource,
the same route the per-user row scoping example uses — the identical
rejection surfaces as a raw, uncaught
global.genesis.spring.data.cube.model.CubeRequestException, carrying the same message as the
HTTP body's detail, just unwrapped. The no-probing guarantee lives specifically at the
ResolvedCubeResource layer: a raw Cube/EntityCube/CubeFactory has no visibleColumns or
FilterPolicy concept at all, so it enforces no column-visibility restriction of its own.
A FilterPolicy governs which columns a caller may reference in a named operation's filter,
beyond the columns it already groups by (implicitly filterable, since their values are already
enumerated in the output). It does not apply to the dynamic .exposeQuery { } path (see
Complete usage examples): that path is bounded purely by
visibleColumns — all source columns by default, or narrowed to exactly the fields named in an
explicit projection<...>() if the exposeQuery block declares one. Grouping and pivoting follow
the same default: if the exposeQuery { } block never calls groupBy(...)/pivotOn(...), a caller
may group or pivot on any visible column — both stay open rather than defaulting to empty.
| Policy | Filterable columns |
|---|---|
GroupKeys (default) | Group-by columns only |
GroupKeysAndAggregated | Plus the columns the operation aggregates — chosen deliberately, since a measured column's per-row values become interval-recoverable through the filter bound even though the output never shows the column itself |
GroupKeysPlus(columns) | Plus an explicit whitelist |
AllExcept(columns) | Every column except a blacklist |
AnyColumn | Every source column |
At most one policy may be declared per resource. A whitelist or blacklist is validated against the entity's real columns at startup, so a typo fails application startup rather than silently letting a column through (or blocking one you meant to allow).
Per-user row scoping
A resource can declare .baseCriteria("currencyId == :username") — a criteriaMatch template
(v1 supports only the :username placeholder) that's ANDed server-side underneath every caller's
own filter, so two users querying the same resource only ever see their own rows. The reified
filter is itself part of the cache key, so per-user isolation of cached results falls out of
caching for free, and a caller cannot widen past their own scope by supplying a conflicting filter
value.
The template is checked at startup, so a mistake in it fails the application rather than the first
request. It must parse, reference only columns on the source, and be a single boolean expression
(a trailing ; is enough to break it). On an entity-sourced resource, the template's own literals
must also convert to their column's type — an enum constant name that no longer exists, for
example. Values substituted for placeholders such as :username are not part of this check.
At the resource-resolution level — a custom controller, or a test — you supply the caller's
identity yourself as a PrincipalValues binding:
- Kotlin
- Java
@Bean
fun tradesByCurrencyScoped(): CubeResource = cubeResource<Trade> {
baseCriteria("currencyId == :username") // reified per caller; scopes every request
operation("byCurrency") {
groupBy("currencyId")
count()
}
}
@Autowired
lateinit var registry: CubeResourceRegistry
fun tradesFor(username: String): CubeResult<*> {
val trades = registry.require("tradesByCurrencyScoped")
val principal = PrincipalValues { name -> if (name == "username") username else null }
return trades.queryOperation("byCurrency", callerCriteria = null, PageRequest.of(0, 100), principal)
}
@Bean
public CubeResource tradesByCurrencyScoped() {
return CubeResource.forEntity(Trade.class)
.baseCriteria("currencyId == :username")
.operation("byCurrency", op -> op.groupBy("currencyId").count())
.build();
}
@Autowired
CubeResourceRegistry registry;
CubeResult<?> tradesFor(String username) {
ResolvedCubeResource trades = registry.require("tradesByCurrencyScoped");
PrincipalValues principal = name -> "username".equals(name) ? username : null;
return trades.queryOperation("byCurrency", null, PageRequest.of(0, 100), principal);
}
The built-in /api/v1/cubes/... endpoints bind :username to the name of the authenticated
caller (the Genesis user name), so a resource declaring baseCriteria can be exposed over them and
each request is scoped to its own caller. In a custom controller that calls
CubeResourceRegistry/ResolvedCubeResource directly, supply the binding yourself as a
PrincipalValues sourced from the authenticated principal, as above.
The same resolution-level call is what you exercise in a test — autowire CubeResourceRegistry
inside a @GenesisSpringTest the same way you would in application code, and assert on the
CubeResult for each simulated caller:
- Kotlin
- Java
@GenesisSpringTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
class TradesByCurrencyBaseCriteriaTest {
@Autowired
lateinit var registry: CubeResourceRegistry
@Test
fun `base criteria scopes each caller to their own currency`() {
val trades = registry.require("tradesByCurrencyScoped")
val usdPrincipal = PrincipalValues { name -> if (name == "username") "USD" else null }
val usdResult = trades.queryOperation("byCurrency", null, PageRequest.of(0, 100), usdPrincipal)
assertEquals(1, usdResult.totalElements)
assertEquals("USD", (usdResult.content.single() as Tuple).get("currencyId"))
val eurPrincipal = PrincipalValues { name -> if (name == "username") "EUR" else null }
val eurResult = trades.queryOperation("byCurrency", null, PageRequest.of(0, 100), eurPrincipal)
assertEquals(1, eurResult.totalElements)
assertEquals("EUR", (eurResult.content.single() as Tuple).get("currencyId"))
}
}
@GenesisSpringTest
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
public class TradesByCurrencyBaseCriteriaTest {
@Autowired
CubeResourceRegistry registry;
@Test
@DisplayName("base criteria scopes each caller to their own currency")
void baseCriteriaScopesEachCallerToOwnCurrency() {
ResolvedCubeResource trades = registry.require("tradesByCurrencyScoped");
PrincipalValues usdPrincipal = name -> "username".equals(name) ? "USD" : null;
CubeResult<?> usdResult = trades.queryOperation("byCurrency", null, PageRequest.of(0, 100), usdPrincipal);
assertEquals(1, usdResult.getTotalElements());
assertEquals("USD", ((Tuple) usdResult.getContent().get(0)).get("currencyId"));
PrincipalValues eurPrincipal = name -> "username".equals(name) ? "EUR" : null;
CubeResult<?> eurResult = trades.queryOperation("byCurrency", null, PageRequest.of(0, 100), eurPrincipal);
assertEquals(1, eurResult.getTotalElements());
assertEquals("EUR", ((Tuple) eurResult.getContent().get(0)).get("currencyId"));
}
}
See Testing API (Spring) for @GenesisSpringTest itself — the live in-memory database,
fixture loading, and the @DirtiesContext sharing model this example relies on.
What fails and why
The validation rules on this page, collected in one place. A startup failure stops the application from starting; an HTTP 400, 401 or 403 rejects that one request.
| Condition | Fails with | Documented in |
|---|---|---|
genesis.cube.pivot.max-columns is set below 1 | Startup failure | Set-up |
| A column the resource references does not exist on the entity | Startup failure | Declaring a cube resource |
| A JPQL-sourced exposure's projection alias does not resolve to a column on the source query | Startup failure | Declaring a cube resource |
An operation declares no groupBy or aggregation | Startup failure | Declaring a cube resource |
An operation's aggregate does not suit its column's type (a SUM over a string column, for example) | Startup failure | Declaring a cube resource |
Output column names collide, or one is named ROW_REF | Startup failure | Declaring a cube resource |
An operation is named query or schema | Startup failure | Declaring a cube resource |
A FilterPolicy whitelist or blacklist names a column the entity does not have | Startup failure | No-probing and column visibility |
A baseCriteria template does not parse, references a column not on the source, or is not a single boolean expression; or, on an entity-sourced resource, one of its literals does not convert to its column's type | Startup failure | Per-user row scoping |
A JPQL source is invalid, or contains a join without allowJoins = true | Fails when forJpql creates the cube | Flat |
A filter references a column outside the operation's FilterPolicy, or outside the visible set on the exposeQuery path — whether the column is hidden or does not exist | HTTP 400 | No-probing and column visibility |
A POST .../query request names a column outside the resource's visible set | HTTP 400 | Grouped |
A pivot dimension is not in the resource's pivotOn allowlist | HTTP 400 | Pivoted |
A pivot's discovered columns, or its OverflowPolicy.TopN bound, would exceed genesis.cube.pivot.max-columns | HTTP 400 | Pivoted |
Explicit pivot values are combined with an overflow policy or INTERVAL discovery, or includeOther is set without values | HTTP 400 | Explicit pivot values |
A sort names a column the request cannot sort on | HTTP 400 | Sorting |
A POST .../query body carries a field other than filter, sort, page, size, groupKeys, aggregates, calculations and pivot (including having and groupExpansion) | HTTP 400 | Grouped |
A POST carries a query string | HTTP 400 | Sorting |
A GET carries an unknown or duplicate query parameter (including one produced by an unencoded && in filter) | HTTP 400 | Filtering |
| A filter is malformed, references an unknown column, calls an unsupported method, has more than one statement, or is not boolean | HTTP 400 | Filtering |
A filter ends in ; on a resource that declares baseCriteria | HTTP 400 | Filtering |
A route declares a permission and the request has no authenticated caller | HTTP 401 | Security |
The caller lacks the right code the route's permission declares | HTTP 403 | Security |
Filtering
Filtering reuses the Genesis Data Server's own criteriaMatch grammar: a Groovy expression over
column names, parsed into a backend-neutral form and compiled independently by whichever backend
the cube uses (JPA Criteria, or JPQL text). The same grammar is used whether you call a cube
directly with a criteriaMatch-flavoured cube (forEntityCriteria/forJpqlCriteria) or supply a
resource's HTTP filter parameter/body field.
| Expression | Meaning |
|---|---|
currencyId == 'USD' | equality |
currencyId == 'USD' || currencyId == 'EUR' | logical OR |
currencyId == 'USD' && price >= 5 | logical AND + comparison |
!(instrumentId == null) | unary NOT + null check |
quantity % 2 == 0 | arithmetic (modulo) |
currencyId.toUpperCase() == 'USD' | string method call |
currencyId.substring(0, 1) == 'U' | substring |
The query endpoint accepts exactly four query parameters — filter, sort, page and size —
and nothing else. Any unknown or duplicate parameter is rejected with 400 rather than silently
ignored, which is deliberate: an unrecognised parameter would otherwise let a caller's own
cache-buster (for example ?_=<timestamp>) silently defeat HTTP caching. On a POST the same
four travel in the JSON body instead, and any query string is rejected (see Sorting).
A filter must be a single boolean expression. A malformed expression, an unknown column, an
unsupported method call, more than one statement or an expression that isn't boolean is rejected,
not thrown as a raw parser exception. A single trailing ; is tolerated on its own, but is rejected
when the resource declares baseCriteria, because the filter is then wrapped in parentheses and
combined with it — so leave the trailing ; off:
- Kotlin
- Java
val trades = cubeFactory.forEntityCriteria(Trade::class.java)
val usdHighPrice = trades.query(
filter = "currencyId == 'USD' && price >= 5",
pageable = Pageable.ofSize(200),
)
EntityCriteriaCube<Trade> trades = cubeFactory.forEntityCriteria(Trade.class);
CubeResult<Trade> usdHighPrice = trades.query(
"currencyId == 'USD' && price >= 5",
Pageable.ofSize(200)
);
Over HTTP, the same expression is a query parameter or a body field. This assumes an operation
whose resource has widened its FilterPolicy to cover the filtered column — tradesByCurrency
itself only permits filtering on currencyId, its group key, under the default
FilterPolicy.GroupKeys (see Declaring a cube resource). Adding
filterOn("price") at the resource level (see Security) permits it:
- Kotlin
- Java
@Bean
fun tradesByCurrencyWide(): CubeResource = cubeResource<Trade> {
filterOn("price") // FilterPolicy.GroupKeysPlus("price"), widened beyond the group key
operation("byCurrency") {
groupBy("currencyId")
sum("quantity")
}
}
@Bean
public CubeResource tradesByCurrencyWide() {
return CubeResource.forEntity(Trade.class)
.filterOn("price")
.operation("byCurrency", op -> op
.groupBy("currencyId")
.sum("quantity"))
.build();
}
On a GET, the filter must be URL-encoded: an unencoded && splits the query string, and the
server rejects the request with 400 for an unknown query parameter.
curl -G http://localhost:8080/api/v1/cubes/tradesByCurrencyWide/byCurrency \
--data-urlencode "filter=currencyId=='USD' && price>=5"
In a POST body the filter is a plain JSON string, sent unencoded:
POST /api/v1/cubes/tradesByCurrencyWide/byCurrency
{
"filter": "currencyId=='USD' && price>=5"
}
An empty or blank filter is treated as "no filter" and is accepted without error — worth knowing
if your own frontend adapter can produce a blank criteria string (for example, all filter
conditions cleared) and needs to distinguish that from "no filter supplied" at all.
Which columns a caller may reference beyond an operation's own group-by columns is bounded by its
FilterPolicy — see Security.
Grid integration
The wire protocol and response shapes (the response envelope, row references) are generic JSON —
nothing in the HTTP layer imports or depends on AG Grid directly. The assumption that does exist is
architectural: the whole-cube exposeQuery() path's shape (group keys, aggregates, pivot
dimensions, flat vs. grouped vs. pivoted results) maps onto what an AG Grid Server-Side Row
Model datasource needs to drive rowGroupCols,
groupKeys, pivotMode and filterModel.
Translating AG Grid's rowGroupCols/groupKeys/pivotMode/filterModel into a cube query
request — including switching to a flat, equality-filtered query once a request reaches leaf rows,
for an SSRM drill-down step — is left to your own frontend adapter; the /query body shape itself
is exactly what's shown in Query types.
Caching
Every GET response is validated with a three-part ETag covering: the request's identity (minted
from the effective, already-gated filter and shape — never the raw caller filter, since that could
leak a hidden base criterion), the source's freshness generation, and an era covering
discovered-pivot-column/memoized-count staleness.
GEThonoursIf-None-Matchand answers304 Not Modified;POSTnever does, since a dynamic query has no cacheable identity to key on ahead of execution.- A resource is only cacheable if the engine can prove its full source-table set and every source is trackable — an uncacheable cube simply always re-executes; nothing fails at startup because of it.
An initial request returns the ETag alongside the rows:
GET /api/v1/cubes/tradesByCurrency/byCurrency?filter=currencyId=='USD'
200 OK
ETag: "a1b2c3d4-42-7"
Replaying that value as If-None-Match on a later, identical request skips re-execution — and the
body — as long as none of the three parts (request identity, source freshness generation, pivot/count
era) have moved on:
GET /api/v1/cubes/tradesByCurrency/byCurrency?filter=currencyId=='USD'
If-None-Match: "a1b2c3d4-42-7"
304 Not Modified
The cube subscribes to the update queue for each of a resource's source tables and invalidates its
cached responses when any of those tables is updated: the update advances the source freshness
generation, so the next identical GET gets a new ETag, and replaying the old one as
If-None-Match returns 200 with the current rows rather than 304. The era advances
independently, whenever the cube's remembered entry for the request is dropped and re-planned —
when it expires after genesis.cube.pivot-ttl-millis, is evicted to stay within
genesis.cube.remembered-max-entries, or is cleared by Cube.refresh() — with the same effect on
a conditional GET.
GET /api/v1/cubes/{resource} describes a resource itself, before you issue any query against it —
whether rows are addressable, the identity columns, pagination/caching guarantees, and the
request-size limits:
{
"addressable": true,
"identity": ["tradeId"],
"paginationStable": true,
"maxFilterLength": 8192,
"maxPageSize": 1000,
"defaultPageSize": 100,
"maxSortOrders": 64,
"maxPivotColumns": 25,
"cacheable": true
}
This document is itself boot-time ETagged, and returns a 404 if the resource name is unknown or
if it exists but declares neither an operation nor exposeQuery — deliberately indistinguishable
from "unknown", extending the no-probing rule to a resource's own existence.
GET /api/v1/cubes/{resource}/schema returns the same resource's wire shapes as JSON Schema, one
schema per shape:
envelope— the response envelope wrapperoperationRequest— a bare named-operation requestoperations— a map from operation name to the shape of that operation's result rowsqueryRequest— aPOST .../queryrequest body, including the limits the server enforces (page size, filter length, list sizes), so a request built from it won't be rejected on boundsquery— the shape of aPOST .../queryresult row. It is deliberately loose, because the columns depend on the request
queryRequest and query are null for a resource without exposeQuery.
Same ETag and 404 behaviour as the capability document above: cacheable, validated with
If-None-Match, answering 304 Not Modified on a match, and 404 under the same condition — an
unknown resource, or one that declares neither an operation nor exposeQuery.
Testing
Testing an HTTP endpoint exercises a @RestController
without booting a real Genesis process: it uses Spring Boot's @WebMvcTest slice, imports only
GenesisSpringSecurityConfig, and declares a mock OnDemandUserSessionCache bean. A cube resource
can't use that recipe as-is — it needs a real JPA entity backed by a real database, which only
exists under @GenesisSpringTest, and the @WebMvcTest slice loads none of the starter's JPA or
cube autoconfiguration.
@GenesisSpringTest composes @SpringBootTest(classes = [GenesisTestApplication::class]) with no
webEnvironment override, so it defaults to Spring Boot's own MOCK — the same environment
@AutoConfigureMockMvc expects — and it leaves the starter's JPA autoconfiguration
(GenesisDataConfig) and cube autoconfiguration to wire up exactly as they would in a real process.
Combining the two annotations therefore gives you MockMvc in front of a fully booted cube resource,
querying a real JPA-backed data source, with no exclusion trick needed. As with Testing an HTTP
endpoint, stubbing the suspend liveSessionOrNull
cleanly needs mockito-kotlin's onBlocking { … }, so this example is Kotlin-only.
The AutoConfigureMockMvc import below needs testImplementation("org.springframework.boot:spring-boot-starter-webmvc-test"); see Testing API (Spring) for the full set of test dependencies:
package com.example.myapp.jpa
import global.genesis.session.OnDemandUserSessionCache
import global.genesis.session.UserSessionCache.UserSessionRef
import global.genesis.springboot.security.GenesisSessionAuthenticator.Companion.SESSION_AUTH_TOKEN_HEADER
import global.genesis.springboot.test.GenesisSpringTest
import global.genesis.springboot.test.GenesisTestApplication
import org.joda.time.DateTime
import org.junit.jupiter.api.Test
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.test.annotation.DirtiesContext
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
@GenesisSpringTest
@SpringBootTest(classes = [GenesisTestApplication::class, TradeCubeConfig::class, CubeHttpQueryTest.SessionStub::class])
@AutoConfigureMockMvc
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
class CubeHttpQueryTest {
@Autowired
lateinit var mockMvc: MockMvc
@Test
fun `queries a real JPA-backed cube resource over its HTTP endpoint`() {
mockMvc.perform(
get("/api/v1/cubes/tradesByCurrency/byCurrency")
.header(SESSION_AUTH_TOKEN_HEADER, VALID_TOKEN),
)
.andExpect(status().isOk)
.andExpect(jsonPath("$.rowKind").value("GROUPED"))
.andExpect(jsonPath("$.rows").isArray)
}
// A unique @Primary bean wins Spring's own resolution over the Guice-bridged
// OnDemandUserSessionCache (see Application core: BeanFactory bridging), without excluding
// GenesisSpringBootConfiguration/GenesisSpringWebConfig — so the real cube/JPA
// autoconfiguration stays wired.
@Configuration(proxyBeanMethods = false)
open class SessionStub {
@Bean
@Primary
open fun onDemandUserSessionCache(): OnDemandUserSessionCache = mock {
onBlocking { liveSessionOrNull(VALID_TOKEN) } doReturn UserSessionRef(
userName = "JaneDoe",
sessionId = "session-1",
token = VALID_TOKEN,
expiryDateTime = DateTime.now().plusHours(1),
)
}
}
private companion object {
const val VALID_TOKEN = "valid-session-token"
}
}
TradeCubeConfig is the @Configuration class declaring tradesByCurrency from Declaring a cube
resource — like any hand-written bean under @GenesisSpringTest
(GenesisTestApplication does no component scanning), it has to be listed explicitly in
@SpringBootTest(classes = [...]) alongside GenesisTestApplication and the session stub, or the
resource's bean — and its endpoint — is never registered. liveSessionOrNull is the method to
stub, with a non-blank userName on the returned session: see Testing an HTTP endpoint
for why. @Primary is what makes the override win: Application core's BeanFactory
bridging notes that Spring's own resolution, including @Primary,
always takes priority over a Guice-bridged singleton like the real OnDemandUserSessionCache this starter
would otherwise install.
Seed real rows through the same JPA repository a non-cube test would use — see Testing API (Spring): A
simple example — and the response reflects them exactly as a
manual curl against a running app would; nothing about going through MockMvc changes the cube's
own query, filtering or no-probing behaviour described earlier on this page.
Asserting that a bad declaration fails startup
An invalid cube resource fails application startup (see Declaring a cube
resource). To assert that in a test, start a child context with
Spring Boot's ApplicationContextRunner, using the @GenesisSpringTest context as its parent.
The child imports the cube starter's own CubeConfig (global.genesis.spring.data.cube.lifecycle)
and declares the resource under test. The parent does not need to contain that resource: the
child's CubeConfig validates only the CubeResource beans declared in the child. See Testing API
(Spring) for the test dependencies. In this example, Widget is a
generated entity with a quality field, and the bad declaration names an operation query, which
is reserved:
- Kotlin
- Java
import global.genesis.spring.data.cube.lifecycle.CubeConfig
import global.genesis.spring.data.cube.model.CubeServerException
import global.genesis.spring.data.cube.resource.CubeResource
import global.genesis.spring.data.cube.resource.cubeResource
import global.genesis.spring.demo.dao.Widget
import global.genesis.springboot.test.GenesisSpringTest
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.convert.ApplicationConversionService
import org.springframework.boot.test.context.runner.ApplicationContextRunner
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
@GenesisSpringTest
class BadCubeDeclarationTest {
@Autowired lateinit var context: ApplicationContext
private fun runner() = ApplicationContextRunner()
.withParent(context)
.withInitializer { it.beanFactory.conversionService = ApplicationConversionService.getSharedInstance() }
.withUserConfiguration(CubeConfig::class.java) // global.genesis.spring.data.cube.lifecycle
@Test fun `reserved operation name fails startup`() {
runner().withUserConfiguration(BadCube::class.java).run { ctx ->
assertThat(ctx).hasFailed()
assertThat(ctx).getFailure().rootCause()
.isInstanceOf(CubeServerException::class.java) // ...cube.model
.hasMessageContaining("reserved")
}
}
@Test fun `control - valid cube in the same child context starts`() {
runner().withUserConfiguration(GoodCube::class.java).run { ctx -> assertThat(ctx).hasNotFailed() }
}
@Configuration(proxyBeanMethods = false)
class BadCube {
@Bean fun badWidgets(): CubeResource = cubeResource<Widget> {
operation("query") { groupBy("quality"); count() }
}
}
@Configuration(proxyBeanMethods = false)
class GoodCube {
@Bean fun goodWidgets(): CubeResource = cubeResource<Widget> {
operation("byQuality") { groupBy("quality"); count() }
}
}
}
import global.genesis.spring.data.cube.lifecycle.CubeConfig;
import global.genesis.spring.data.cube.model.CubeServerException;
import global.genesis.spring.data.cube.resource.CubeResource;
import global.genesis.spring.demo.dao.Widget;
import global.genesis.springboot.test.GenesisSpringTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.convert.ApplicationConversionService;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
@GenesisSpringTest
class BadCubeDeclarationTest {
@Autowired
ApplicationContext context;
private ApplicationContextRunner runner() {
return new ApplicationContextRunner()
.withParent(context)
.withInitializer(ctx -> ctx.getBeanFactory().setConversionService(ApplicationConversionService.getSharedInstance()))
.withUserConfiguration(CubeConfig.class);
}
@Test
void reservedOperationNameFailsStartup() {
runner().withUserConfiguration(BadCube.class).run(ctx -> {
assertThat(ctx).hasFailed();
assertThat(ctx).getFailure()
.rootCause()
.isInstanceOf(CubeServerException.class)
.hasMessageContaining("reserved");
});
}
@Test
void validCubeInTheSameChildContextStarts() {
runner().withUserConfiguration(GoodCube.class).run(ctx -> assertThat(ctx).hasNotFailed());
}
@Configuration(proxyBeanMethods = false)
static class BadCube {
@Bean
CubeResource badWidgets() {
return CubeResource.forEntity(Widget.class)
.operation("query", op -> op
.groupBy("quality")
.count())
.build();
}
}
@Configuration(proxyBeanMethods = false)
static class GoodCube {
@Bean
CubeResource goodWidgets() {
return CubeResource.forEntity(Widget.class)
.operation("byQuality", op -> op
.groupBy("quality")
.count())
.build();
}
}
}
Keep the withInitializer line. A bare ApplicationContextRunner context has no Spring Boot
conversion service, so without it even a valid cube fails to start in the child context, for an
unrelated reason. The bad-cube test would then pass without proving anything. The control test
shows that the same child context starts cleanly with a valid cube, so the only difference between
the two is the bad declaration.
Complete usage examples
1. A grouped and pivoted trade blotter
Declaring a resource that supports flat, grouped and pivoted access to the same entity, all through
one exposeQuery() block:
- Kotlin
- Java
import global.genesis.spring.data.cube.resource.projection
@Configuration
class TradesCubeConfig {
@Bean
fun trades(): CubeResource = cubeResource<Trade> {
exposeQuery {
projection<TradeFlat>()
groupBy("currencyId", "tradeDate")
pivotOn("currencyId")
}
}
}
@Configuration
public class TradesCubeConfig {
@Bean
public CubeResource trades() {
return CubeResource.forEntity(Trade.class)
.exposeQuery(q -> q
.projection(TradeFlat.class)
.groupBy("currencyId", "tradeDate")
.pivotOn("currencyId"))
.build();
}
}
A flat query, filtered but ungrouped:
POST /api/v1/cubes/trades/query
{ "filter": "currencyId == 'USD'" }
The same resource, grouped by currency with a summed quantity:
POST /api/v1/cubes/trades/query
{
"groupKeys": [{ "expr": { "type": "field", "attribute": "currencyId" } }],
"aggregates": [
{ "function": "SUM", "input": { "type": "field", "attribute": "quantity" }, "alias": "totalQuantity" }
]
}
And pivoted, with currency discovered as dynamic columns per trade date:
POST /api/v1/cubes/trades/query
{
"groupKeys": [{ "expr": { "type": "field", "attribute": "tradeDate" } }],
"pivot": {
"dimensions": [{ "expr": { "type": "field", "attribute": "currencyId" } }],
"measures": [
{ "type": "aggregate", "aggregate": { "function": "SUM", "input": { "type": "field", "attribute": "quantity" } } }
]
}
}
Before wiring up a frontend, GET /api/v1/cubes/trades tells you up front whether the resource is
addressable, cacheable, and what its page-size/filter-length limits are (see
Caching).
The dynamic exposeQuery path is reachable in-process too, without HTTP —
ResolvedCubeResource.query/prepareQuery are the exposeQuery counterparts of
queryOperation/prepareOperation: the request carries the query shape
only (its own filter must stay null), and the caller's criteriaMatch filter, if any, arrives as
a separate argument instead. Reproducing the grouped-by-currency query above:
- Kotlin
- Java
@Autowired
lateinit var registry: CubeResourceRegistry
fun example(pageable: Pageable) {
val trades = registry.require("trades")
val grouped: CubeResult<*> = trades.query(
request = QueryRequest(
groupKeys = listOf(GroupKey("currencyId", "currencyId")),
aggregates = listOf(Aggregate(Function.SUM, "quantity", "totalQuantity")),
),
callerCriteria = null,
pageable = pageable,
)
}
In Kotlin, principal is optional and defaults to a binding that resolves nothing, the same as the Java sample's name -> null.
@Autowired
CubeResourceRegistry registry;
void example(Pageable pageable) {
ResolvedCubeResource trades = registry.require("trades");
CubeResult<?> grouped = trades.query(
new UnfilteredQueryRequest(
List.of(new GroupKey("currencyId", "currencyId")),
List.of(new Aggregate(Function.SUM, "quantity", "totalQuantity")),
List.of(),
null,
null,
List.of()),
null,
pageable,
name -> null);
}
2. A JPQL report with a column whitelist
A resource can be built from hand-written JPQL rather than a mapped entity — useful for a report
shape that doesn't map cleanly onto one entity's own columns — with an explicit FilterPolicy
widening beyond its group keys:
- Kotlin
- Java
@Configuration
class TradeReportCubeConfig {
private val tradeColumns =
"select t.currencyId as ccy, t.price as px, t.quantity as qty, t.tradeType as tt from Trade t"
@Bean
fun tradeReport(): CubeResource = cubeResource(tradeColumns) {
filterOn("tt") // whitelist beyond the group key
operation("byCurrency") {
groupBy("ccy")
sum("qty")
}
}
}
@Configuration
public class TradeReportCubeConfig {
private static final String TRADE_COLUMNS =
"select t.currencyId as ccy, t.price as px, t.quantity as qty, t.tradeType as tt from Trade t";
@Bean
public CubeResource tradeReport() {
return CubeResource.forJpql(TRADE_COLUMNS)
.filterOn("tt")
.operation("byCurrency", op -> op.groupBy("ccy").sum("qty"))
.build();
}
}
The filter is URL-encoded, as in Filtering:
curl -G http://localhost:8080/api/v1/cubes/tradeReport/byCurrency \
--data-urlencode "filter=ccy=='USD' && tt=='BUY'"
ccy (the group key) and tt (the whitelisted column) are both filterable; px is not, and a
request naming it is rejected with the same error as a nonexistent column, per the
no-probing rule.
3. A named operation alongside a dynamic exposeQuery
exposeQuery { } and operation(...) aren't mutually exclusive — a single resource can expose both
the dynamic query path and one or more named shortcuts over the same entity, each bounded
independently:
- Kotlin
- Java
@Configuration
class TradesWithOperationCubeConfig {
@Bean
fun tradesWithOperation(): CubeResource = cubeResource<Trade> {
exposeQuery {
projection<TradeFlat>()
groupBy("currencyId", "tradeDate")
}
operation("byCurrency") {
groupBy("currencyId")
sum("quantity")
}
}
}
@Configuration
public class TradesWithOperationCubeConfig {
@Bean
public CubeResource tradesWithOperation() {
return CubeResource.forEntity(Trade.class)
.exposeQuery(q -> q
.projection(TradeFlat.class)
.groupBy("currencyId", "tradeDate"))
.operation("byCurrency", op -> op
.groupBy("currencyId")
.sum("quantity"))
.build();
}
}
POST /api/v1/cubes/tradesWithOperation/query reaches the dynamic path, bounded by exposeQuery's
own visibleColumns/groupBy/pivotOn; GET /api/v1/cubes/tradesWithOperation/byCurrency reaches
the named shortcut, bounded by its own FilterPolicy. The two paths share the underlying cube and
cache, but each enforces its own column-visibility rules.
4. A typed projection on a JPQL-sourced exposeQuery
.projection<...>() isn't limited to an entity-backed resource — a JPQL source can use it too,
shaping the dynamic path's flat rows as a DTO instead of a raw Tuple:
- Kotlin
- Java
@Configuration
class TradeReportDynamicCubeConfig {
private val tradeColumns =
"select t.currencyId as ccy, t.price as px, t.quantity as qty, t.tradeType as tt from Trade t"
data class TradeReportRow(val ccy: String, val px: Double, val qty: Int, val tt: String)
@Bean
fun tradeReportDynamic(): CubeResource = cubeResource(tradeColumns) {
exposeQuery {
projection<TradeReportRow>()
groupBy("ccy", "tt")
}
}
}
@Configuration
public class TradeReportDynamicCubeConfig {
private static final String TRADE_COLUMNS =
"select t.currencyId as ccy, t.price as px, t.quantity as qty, t.tradeType as tt from Trade t";
record TradeReportRow(String ccy, double px, int qty, String tt) {}
@Bean
public CubeResource tradeReportDynamic() {
return CubeResource.forJpql(TRADE_COLUMNS)
.exposeQuery(q -> q
.projection(TradeReportRow.class)
.groupBy("ccy", "tt"))
.build();
}
}
A flat, ungrouped POST /api/v1/cubes/tradeReportDynamic/query returns rows shaped like
TradeReportRow — ccy, px, qty and tt — exactly as a JPQL-backed named operation would,
just without pinning the caller to one fixed group-by shape.
See also
- Getting Started with Spring — step-by-step tutorial for adding Spring to a Genesis application.
- Data access APIs (JPA) — repositories and entities the cube engine reads from.
- Data model (Spring) — the dictionary-to-JPA codegen that produces the entities a cube is built over; a hard prerequisite for this module.
- Application core — the security filter chain a cube resource's HTTP endpoints run through.
- Grid Pro — the AG Grid-based grid component this module's wire shape is designed to drive via its Server-Side Row Model datasource.