Replaces the generated DB operation for a field with a call to an external Java method. Use it when the operation cannot be expressed by the directive surface: multi-statement transactions, business-logic-heavy reads, third-party calls, or shapes the framework does not (yet) cover. On the owned-connection path a @service mutation runs inside the one transaction graphitron opens for its top-level field, unless it says transactionControl: SERVICE; elsewhere graphitron opens no transaction around a @service invocation and the method owns its own boundaries. See the constraint below.
SDL signature
directive @service(
service: ExternalCodeReference!,
contextArguments: [String!],
transactionControl: TransactionControl = GRAPHITRON
) on FIELD_DEFINITION
enum TransactionControl { GRAPHITRON, SERVICE }
input ExternalCodeReference {
className: String
method: String
argMapping: String
}
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
|
|
(required) |
The Java target. |
|
|
none |
Names of values pulled from the request |
|
|
|
Who owns the transaction a mutation field’s service runs in. |
Canonical example
The example schema’s root services hand off three different return shapes:
type Query {
filmsByService(ids: [Int!]!): [Film!]!
@service(service: {
className: "no.sikt.graphitron.rewrite.test.services.SampleQueryService",
method: "filmsByService"
})
filmsByServiceRenamed(ids: [Int!]!): [Film!]!
@service(service: {
className: "no.sikt.graphitron.rewrite.test.services.SampleQueryService",
method: "filmsByServiceRenamed",
argMapping: "filmIds: ids"
})
filmCount: Int!
@service(service: {
className: "no.sikt.graphitron.rewrite.test.services.SampleQueryService",
method: "filmCount"
})
}
filmsByService returns a Result<FilmRecord>, and because Film carries @table the framework reads those records as key carriers: it lifts each record’s primary key and re-selects the requested fields from the table, so the method need only populate the key columns. filmsByServiceRenamed shows argMapping: the GraphQL arg ids binds to the Java parameter filmIds because the service method’s signature reads more naturally that way. filmCount returns a plain scalar.
The Java surface for the first method:
public class SampleQueryService {
public SampleQueryService(DSLContext context) { … }
public Result<FilmRecord> filmsByService(List<Integer> ids) { … }
}
The framework constructs the service with whatever it can resolve from the request context (a DSLContext for the request’s database session is the most common parameter); the rest of the method signature is filled from the field’s GraphQL arguments, as the next section sets out.
How each parameter is filled
Each parameter of the method is filled once, by the first of these that reaches it:
-
What you wrote. An
argMappingentry naming the parameter: an argument path,$session,$session.<member>, or$context.<key>, the request context’s value under that key. AcontextArgumentselement naming it: the request context’s value under that key. -
Its type, for the jOOQ context. A
DSLContextor aConfigurationparameter takes the request’s jOOQ context. -
Its name. An argument of the field with the parameter’s name.
-
The call’s source. On a non-root field, a collection parameter takes the parent keys the batch hands the call; see the batching constraint below.
-
Its type. A parameter still open takes an argument still open when each is the other’s only match by type: the same list-ness, and an element the argument’s value arrives as. An input object arrives as the class it is built into, which any class outside the JDK can be; an enum as a class or a
String; a scalar as its Java type, boxed or not, which for a scalar bound with@scalarTypeis the type its constant coerces to:ExtendedScalars.Datearrives as aLocalDate. A sole[EndreInput!]!argument therefore fills a soleList<EndreInputRecord>parameter whatever the two are called. -
What is left. Where one named parameter and one argument are all that is still open, they pair when their list-ness agrees and type cannot tell them apart: an input object, or a scalar with no
@scalarTypeand so no known Java type. A last pair whose types are both known and disagree, a list ofStringagainst aList<Integer>, stays unfilled, since the call could not compile.
A parameter an argMapping entry names is that entry’s, even where the entry’s path lands nowhere;
the entry’s own error reports it, and nothing else stands in. Five refusals name the parameter at
the @service, and one names what the client sends:
-
Unfilled: nothing above reaches it. Name it after its argument, or bind it in
argMappingorcontextArguments. -
Ambiguous: it could take more than one argument by type, or an argument it could take could go to another parameter too. Name it after its argument, or bind it in
argMapping. -
Filled twice: an
argMappingentry and acontextArgumentselement both name it. Write it once. -
Mismatched (
PARAMETER_MISMATCH): the argument it takes, by name or by anargMappingpath, is a list where the parameter takes one value or one value where it takes a list, or arrives as a class the parameter is not: anIDas aString, never aLong; anIntas anIntegerorint. AnObjectparameter takes any scalar or enum value whole. A member of an input bean is judged the same way, at its input field, so a jOOQ record member filled from anIDneeds@nodeIdto decode it, withtypeName:where the record’s table has no one node. A node id decoded onto a parameter is the@nodeIdrules' to judge. -
Missing constant (
ENUM_CONSTANT_MISSING): a GraphQL enum value it takes as a Java enum constant names no constant the enum declares, its@field(name:)or else its own name, soEnum.valueOfwould throw when a client sends it. An input bean’s enum member is judged the same way, at its input field. Take the value as aStringto read it by name instead. -
Left behind (
ARGUMENT_UNBOUND): an argument, or an input field inside one, that nothing takes. An argument no parameter takes, itself or anything inside it, is reported at the argument. WhereargMappingpaths take an argument in part, asfra: range.fraVerdidoes, an input field none of them reaches,range.tilVerdi, is reported at that field, once, at the outermost such field: the value a client sends there would go nowhere. Bind it, or remove it. -
Taken as a map (
SERVICE_INPUT_AS_MAP): an input object it takes as aMap, anObjector a list of either. A map at the service boundary is a permanent anti-pattern: take a typed bean, a record or a class with a public no-arg constructor mirroring the input object, or, for open-ended JSON, declare a custom scalar with@scalarTypeand take its Java type. A@conditiontakes the map.
An input object a parameter takes as a table’s jOOQ record (FilmRecord) is built column by
column, each input field writing the column it binds on that table:
-
A field the client did not send leaves its column untouched, so the record’s changed flags say exactly what the client wrote. A field sent as
nullwritesNULL, on aNOT NULLcolumn too, whatever else the input sends. -
A
@nodeIdfield writes the key columns of its node, or of the reference its path names; sent asnull, it writesNULLto those of its columns no other field wrote. -
Where two fields write one column, the values must agree, or the request fails with "Conflicting values supplied for input fields 'a', 'b'", naming every field writing it.
-
A nested input object groups its fields: they write the record as if they were declared beside it. A grouping not sent, or sent as
null, leaves every column under it untouched and decodes nothing, so a@nodeIdfield declaredID!inside it is only required when the grouping is sent. A list of input objects cannot group. -
In a list of input objects, built into records or classes, a
nullelement is refused: the method is handed the objects, not gaps.
The build fails at the input field where a record cannot be built this way: a field naming no
column of the table (COLUMN_UNRESOLVED, or COLUMN_AMBIGUOUS where its name reaches several), and
a @nodeId field with no route onto the table, where no one foreign key joins the two and no
@reference path is written (NODE_ID_LANDS_ON_TABLE). That holds however the record reaches the
method, by name or through argMapping.
An input object a parameter takes as any other class is built into it: a Java record by its
canonical constructor, another class by its public no-argument constructor and setters. Each input
field fills the member its @field(name:) names, or its own name; a nested input object fills the
member of that name, built into the member’s class in turn, or where no member has its name groups
its fields onto the enclosing object. The build fails at the field where it cannot:
-
a class nothing constructs, being abstract, not public, or without such a constructor (
BUILT_CLASS_UNBUILDABLE); -
a field nothing takes, whose value would reach nothing (
MEMBER_UNKNOWN): it fills no member, matched exactly, case included, and no field inside it fills one or is otherwise bound. A nested input object none of whose fields fills a member is reported itself, at that field, and its fields are not (Alf, 2026-11-17); -
a list of input objects filling no member, which has no one object to group onto (
GROUPING_LIST), and any list of input objects inside a jOOQ record; -
two fields filling one member of one object (
MEMBER_FILLED_TWICE); node ids decoding into one record member are one record and allowed; -
a record component no field fills (
MEMBER_UNFILLED), since its canonical constructor takes every component; a field reaching it through a grouping fills it.
Binding a parameter to a nested input field
An argMapping entry is javaParam: path. The left-hand side names a Java method parameter; the
right-hand side names a GraphQL slot in scope, optionally followed by dot-separated segments. The
right-hand side works identically on every directive that accepts an argMapping:
@service, @condition and
@routine. Only the left-hand side differs, because each directive binds a
different kind of target. Entries are separated by commas; a string that does not parse, an entry
missing its colon say, is refused as ARGMAPPING_UNPARSEABLE rather than read as no mapping.
On @service the left-hand side may also be $tenant, in a build with database-per-tenant routing
(<tenantColumn>): argMapping: "filmId: id, $tenant: input.org" says the root service’s call runs
on the tenant input.org names. It fills no parameter. The value is read as
@tenant reads it, with the same type and same-tenant rules, and $tenant is the
preferred form: @tenant on the value says the same, and is due for removal. Naming one call’s tenant by both, on
different values, is refused as TENANT_NAMED_TWICE; $tenant on any directive but @service is
refused as TENANT_SITE_UNSUPPORTED, and anywhere in a build without <tenantColumn> as
TENANT_ROUTES_NOTHING.
A dot opens the thing at that position, and what it opens into depends on what the thing is. An input
object opens into its fields, which is the case below. An ID carrying
@nodeId(typeName:) opens into the key columns of the node type it names, so the
segment after it names a key column rather than a field of any SDL type; see
Projecting a key column out of a node id. At a @service
parameter a list of node ids opens the same way, the parameter taking a List of the column, one
element per id; see Projecting one key column. A scalar
carrying @generatedScalar opens into the components its kind decodes a
value into, so start: input.sti.startType hands the method the path’s start type; the call decodes
and checks the value first, and a component is the only way such a value reaches a call. Nothing else
opens, and a segment on something that does not is a build error.
The common case is a wrapper input, the shape a Relay-style mutation has: the field declares one input argument and the values the Java method wants live inside it.
input RentFilmInput {
inventoryId: Int!
customerId: Int!
}
type Mutation {
rentFilm(input: RentFilmInput!): Rental
@service(service: {
className: "com.example.RentalService",
method: "rent",
argMapping: "inventoryId: input.inventoryId, customerId: input.customerId"
})
}
rent(Integer inventoryId, Integer customerId) receives the two values read out of the input
object; the wrapper itself is never handed to the method.
The rules:
-
The head segment (before the first dot) must name a slot in scope at the directive’s site: a GraphQL argument of the field, or the input field itself for an input-field-level
@condition. A head naming nothing in scope is a build error that lists the slots that are. -
Each subsequent segment must name something the value at that depth opens into: a field on the input-object type there, a key column of the node type where that value is an
IDcarrying@nodeId(typeName:), or a component where it is a generated scalar. A segment naming none of these is a build error naming what it looked in and suggesting the near miss. -
A path may be any depth.
input.customer.idwalks two levels. -
Reading is null-safe: if any level along the path is absent, the parameter receives
nullrather than an error. -
A bare name with no dots is the single-slot form, and is what an entry without
argMappingbinds to implicitly."filmIds: ids"and"filmIds: ids.value"differ only in depth.
Constraints
-
service:is required: graphql-java rejects a@servicewithout it at parse time. -
service.classNameandservice.methodare both required, and neither has a default: a@servicewhoseservice:names no class or no method fails the build at the directive withSERVICE_WITHOUT_METHOD. (@externalFieldis the one directive that defaults the method, to the field name.) -
argMappingis parsed as"javaParam: path"entries, comma-separated, a$tenant: pathentry among them. Whitespace around:and,is tolerated; multi-line text-block input is accepted. Empty string is identity. The right-hand side may walk into nested input fields; see Binding a parameter to a nested input field. -
The method may be static or an instance method. For an instance method the generated fetcher makes the object it runs on with the class’s public constructor taking one
DSLContext, else its public no-argument constructor, and passes it the request’sDSLContext. A class with neither, an abstract class, an interface, or one whose constructors all take something else, is refused: make the method static or add such a constructor. A context value fills a method parameter, never a constructor’s. -
contextArguments: ["k"]fills the Java parameter namedkwith the value the request context carries underk; it is theargMappingentryk: $context.k. Naming one parameter twice, by two elements or by an element and a$context.<key>entry, is refused, since nothing says which value fills it. One key fills parameters of one Java type across the whole schema, every@serviceand@conditionthat names it: a key filling aLongat one call and alongor aStringat another is refused at each (CONTEXT_KEY_TYPE_DISAGREES), since the request context’s one value under it is read as one class. TheargMappingentryparam: $context.keyfillsparamfrom the request context’s value underkey, so the parameter’s name may differ from the key’s; the duplicate and type-agreement rules above apply to it as to acontextArgumentselement. The right-hand side is exactly one key after the dot, and the left names a parameter:$context.,$context.a.bor$tenant: $context.keyis refused asCONTEXT_KEY_MALFORMED. The entry is read on@serviceonly; on@conditionand the other directives it is refused asCONTEXT_SITE_UNSUPPORTED, andcontextArgumentsnames the key there. -
@serviceand@mutationare mutually exclusive on the same field. Use@mutationfor fully-generated DB writes,@servicefor custom logic. -
An input object a
@servicetakes is built into the class its parameter holds. Inside an input object built into a jOOQ record, the build does not place a list of node ids (BUILD_NODE_ID_LIST_UNSUPPORTED) or the id of several node types (BUILD_NODE_ID_SEVERAL_TYPES_UNSUPPORTED) yet. An input object that reaches itself again inside the value being built,self: CycleInputinsideCycleInput, is refused (INPUT_CYCLE_EXPANDED): the class cannot be built without end, and the nested value would be dropped. -
A checked exception the method declares must be covered by a handler of the field’s outcome (
CHECKED_EXCEPTION_UNHANDLED): aGENERIChandler naming the exception or a supertype of it, or aDATABASEhandler for anSQLException.IOExceptionandInterruptedExceptionare exempt, and an unchecked exception needs no handler. -
A
@servicecannot answer a union (SERVICE_UNION_RETURN): a Java method declares one result type, and no Java type is a union of others. Answer an interface the members implement. -
A
@serviceunder an object cannot answer an interface whose rows may be any of several participants yet; only a root@serviceis lifted participant by participant, and the build refuses the child (SERVICE_CHILD_POLYMORPHIC_UNSUPPORTED). An outcome, the call’s success beside its errors, is no such answer. -
A
@servicewhose outcome claims validation is validated once per fetch, before the call, at a root field lifting onto at most one table. Under an object, or answering participants on tables of their own, the build refuses it (SERVICE_CHILD_VALIDATION_UNSUPPORTED). -
An
argMappingpath that steps through a list above its last name reads each element’s value for a scalar, or for an enum the parameter takes by name as aString. Each list it steps through arrives as ajava.util.List, so the parameter declares aListfor each, two at most. Landing such a path on a node id, an input object, or an enum the parameter takes as its Java constant, or into a parameter collecting the elements as aSet, aCollectionor another container, is refused (SERVICE_ARGUMENT_PATH_UNSUPPORTED): hand the parameter the list itself, take the enum by name, land the path on a scalar, or declare the parameter aList. -
A
@serviceon a type with no table of its own that is reached from more than one place is refused (SERVICE_SEVERAL_OCCURRENCES_UNSUPPORTED): each place is a producer of its own, and the field’s one fetcher serves one place so far. -
A
@servicereturning a discriminated interface reads every participant off the one shared row. Until more is generated there, the build refuses a participant on a table of its own (SERVICE_DISCRIMINATED_OWN_TABLE_UNSUPPORTED), a participant’s field answering an object with no table of its own down a path (SERVICE_DISCRIMINATED_OBJECT_PATH_UNSUPPORTED), and a participant’s field reading a value more than one step off the shared table (SCALAR_PATH). -
A
@servicemust answer what its field is handed (SERVICE_RETURN_MISMATCH): the record of the table the field’s type is bound to, a value of the class the field’s scalar arrives as,java.lang.Stringfor aStringandjava.lang.Integerfor anInt, and not many where the field is one record, scalar or enum. Under an object this holds per key, for aMap’s values or for a `List’s elements in the keys' order, so a list field answers `Map<Key, List<V>>orList<List<V>>, and an enum field answers its Java enum,Map<FilmRecord, MpaaRating>. AMap’s key is the class the `Sourcesparameter collects, since each parent’s answer is found by the key it was handed, and its value names a class: a rawMapor a type variable says nothing the field can be handed. Wherever one field is handed many, aSet, a jOOQResultor any otherIterableof them serves as aListdoes, read in the order it iterates. A single value under a list field is refused asLIST_OVER_ONE_VALUE. Records answered under one payload type with no table are lifted into it; a list of objects answered into a payload whose data field holds one object is refused, the payload having no one object for them. Table records a@serviceanswers for a type carrying@tableare read back from their table by its primary key, so a table without one is refused there (KEY_TABLE_WITHOUT_PRIMARY_KEY); under a type without@tablethey are read as handed, as any class is, and need no key. -
A
@servicefield cannot return a connection yet: graphitron would page the rows the service answers, which is not generated for a service, so the build refuses it (SERVICE_CONNECTION_UNSUPPORTED). Return a list, or read the rows with a field graphitron fetches and pages. -
On a non-root field,
@servicealways batches. The generated fetcher collects the parents the request touched and calls the method once per field per request, through a DataLoader. The method therefore declares aSourcesparameter, the parent keys, and returns one value per key:Set<Key>paired withMap<Key, V>, orList<Key>paired withList<V>in the same order.KeyisRow<N>,Record<N>or a typedTableRecord, and carries only the key columns. A key of any other class, a DTO of the author’s own, is refused (SERVICE_SOURCES_NOT_KEYS): nothing says how to put a parent’s key into it. A method with noSourcesparameter is rejected at build time asSOURCE_PARAMETER_MISSING; there is no per-parent service call.@splitQueryis not needed: the field is already split, so the directive is ignored and draws thesplitquery-redundant-on-service-childlint warning, which offers to delete it. Single-statement nested resolution is not supported on the service path. A batch shape the frame cannot read is refused (SERVICE_BATCH_SHAPE_UNSUPPORTED): keys as a jOOQResultof anything but the parent’s table records, an answer other than aMapby key or aList/Result, and aListanswer underSetkeys, since aSetgives the service no order to answer in. -
Conditions and other DB-customisation directives on the same field are ignored: the service is opaque and the generator does not splice generated SQL into a custom method’s body.
-
Under a parent holding an object rather than a table’s row, the keys are read off that object, through the one member of its class that returns records of the table the
Sourcesparameter collects; where the object is itself such a record, its own columns are the key. The member is found by what it returns, not by its name. Keys taken asRow<N>orRecord<N>of the key columns are not read off such a member yet, and are refused there (SERVICE_KEY_OFF_OBJECT_UNSUPPORTED): take the table’s own records. A class with no such member is refused asNO_KEY_FROM_PARENT, one with two asKEY_ROW_AMBIGUOUS, and one whose only such members return a list of the records asMANY_KEYS_INTO_ONE, since a service batches one key per parent; a field without@servicefetching its own rows there reads the member named as the field, and two such members are refused asKEY_ROW_AMBIGUOUStoo. The keys' table needs a primary key to batch by, or the field is refused asKEY_TABLE_WITHOUT_PRIMARY_KEY, which holds for a field without@servicefetching its own rows under such a parent too. -
Where the transaction comes from depends on the path. On the owned-connection path (
runtime.newGraphQL(schema)), a@serviceon a Mutation field runs inside the one transaction graphitron opens for each top-level mutation field (Transactions on the owned-connection path): every write the method makes, in what looks to it like autocommit, commits when the field succeeds and rolls back when it fails, including when an@errorchannel claims the exception into a payload. Actx.transactionResult(…)the method opens there joins the field’s transaction: it takes no savepoint and commits nothing, graphitron logs a warning naming your method once, and if it fails the whole field rolls back even when your code catches the exception, so a service cannot commit in steps or carry on past a failed nested scope inside one field. On PostgreSQL, a statement the method catches still aborts the transaction, and the field is then reported as failed rather than as a success whose writes are gone. The same join applies to a transaction a@serviceon a Query field opens on the owned-connection path: what it nests inside its own transaction joins it, and a caught nested failure makes that transaction’s commit fail. Work that must commit on its own belongs in its own top-level mutation field, or in a field whose@servicesaystransactionControl: SERVICE. Such a field opens no transaction of graphitron’s: the method runs on the connection the field would use, in autocommit, so what it writes outside a transaction commits at once, actx.transactionResult(…)it opens is a transaction of its own that commits as the method leaves it, and graphitron logs no warning. If the field fails, graphitron rolls nothing back: what the method committed stands, and the field’s error says the service failed and that nothing was rolled back. An@outboxon the field follows the field’s outcome, not what the method committed (When the message is written). In dev mode, which discards every write at the end of the operation, the method’s transactions are savepoints inside that discarded transaction, so they commit and roll back as they do in production and still leave nothing behind. Everywhere else graphitron opens no transaction around a@serviceinvocation: on the escape-hatch path, and on Query fields on either path, the generated fetcher calls your method on a bareDSLContext, so the method owns the commit point, and a service whose contract is all-or-nothing must open the transaction itself withctx.transactionResult(…)on the injected context. A@mutationwrite always runs inside a transaction graphitron opens, batch writes included. On the escape-hatch path that leaves a generated batch mutation and a service batch mutation sitting side by side in one schema with different integrity guarantees and nothing in the SDL to signal it, and a@service(or a@routine) that writes from a Query field is equally undemarcated on both paths. For what the asymmetry means once a call fails partway through, see Pitfalls on the error channel.
See also
-
How-to: Handle services covers nested-input mapping, response shaping, and the child-field batching contract in depth.
-
@mutationfor the framework-generated alternative. -
How-to: Test your schema for the consumer test pattern with services in play.