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

service

ExternalCodeReference!

(required)

The Java target. className is the fully-qualified implementing class (the carrying artifact must be a dependency the module declares itself; see Make the class nameable); method is the Java method’s name and is required, a reference without one failing the build; argMapping rebinds GraphQL argument names to Java parameter names ("javaParam: graphqlArg, …").

contextArguments

[String!]

none

Names of values pulled from the request GraphQLContext and threaded into the Java method as additional arguments. The runtime must place each named value on the context per request.

transactionControl

TransactionControl

GRAPHITRON

Who owns the transaction a mutation field’s service runs in. GRAPHITRON is the field’s one transaction. SERVICE hands it to the method: graphitron opens none for the field, the method runs on the same connection in autocommit, and a transaction it opens is its own. SERVICE is allowed only on a field of the root mutation type; anywhere else the build fails with SERVICE_TRANSACTION_OUTSIDE_MUTATION. See the constraint below.

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:

  1. What you wrote. An argMapping entry naming the parameter: an argument path, $session, $session.<member>, or $context.<key>, the request context’s value under that key. A contextArguments element naming it: the request context’s value under that key.

  2. Its type, for the jOOQ context. A DSLContext or a Configuration parameter takes the request’s jOOQ context.

  3. Its name. An argument of the field with the parameter’s name.

  4. 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.

  5. 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 @scalarType is the type its constant coerces to: ExtendedScalars.Date arrives as a LocalDate. A sole [EndreInput!]! argument therefore fills a sole List<EndreInputRecord> parameter whatever the two are called.

  6. 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 @scalarType and so no known Java type. A last pair whose types are both known and disagree, a list of String against a List<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 argMapping or contextArguments.

  • 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 argMapping entry and a contextArguments element both name it. Write it once.

  • Mismatched (PARAMETER_MISMATCH): the argument it takes, by name or by an argMapping path, 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: an ID as a String, never a Long; an Int as an Integer or int. An Object parameter 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 an ID needs @nodeId to decode it, with typeName: where the record’s table has no one node. A node id decoded onto a parameter is the @nodeId rules' 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, so Enum.valueOf would 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 a String to 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. Where argMapping paths take an argument in part, as fra: range.fraVerdi does, 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 a Map, an Object or 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 @scalarType and take its Java type. A @condition takes 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 null writes NULL, on a NOT NULL column too, whatever else the input sends.

  • A @nodeId field writes the key columns of its node, or of the reference its path names; sent as null, it writes NULL to 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 @nodeId field declared ID! 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 null element 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 ID carrying @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.id walks two levels.

  • Reading is null-safe: if any level along the path is absent, the parameter receives null rather than an error.

  • A bare name with no dots is the single-slot form, and is what an entry without argMapping binds to implicitly. "filmIds: ids" and "filmIds: ids.value" differ only in depth.

Constraints

  • service: is required: graphql-java rejects a @service without it at parse time.

  • service.className and service.method are both required, and neither has a default: a @service whose service: names no class or no method fails the build at the directive with SERVICE_WITHOUT_METHOD. (@externalField is the one directive that defaults the method, to the field name.)

  • argMapping is parsed as "javaParam: path" entries, comma-separated, a $tenant: path entry 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’s DSLContext. 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 named k with the value the request context carries under k; it is the argMapping entry k: $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 @service and @condition that names it: a key filling a Long at one call and a long or a String at another is refused at each (CONTEXT_KEY_TYPE_DISAGREES), since the request context’s one value under it is read as one class. The argMapping entry param: $context.key fills param from the request context’s value under key, so the parameter’s name may differ from the key’s; the duplicate and type-agreement rules above apply to it as to a contextArguments element. The right-hand side is exactly one key after the dot, and the left names a parameter: $context., $context.a.b or $tenant: $context.key is refused as CONTEXT_KEY_MALFORMED. The entry is read on @service only; on @condition and the other directives it is refused as CONTEXT_SITE_UNSUPPORTED, and contextArguments names the key there.

  • @service and @mutation are mutually exclusive on the same field. Use @mutation for fully-generated DB writes, @service for custom logic.

  • An input object a @service takes 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: CycleInput inside CycleInput, 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): a GENERIC handler naming the exception or a supertype of it, or a DATABASE handler for an SQLException. IOException and InterruptedException are exempt, and an unchecked exception needs no handler.

  • A @service cannot 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 @service under an object cannot answer an interface whose rows may be any of several participants yet; only a root @service is 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 @service whose 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 argMapping path 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 a String. Each list it steps through arrives as a java.util.List, so the parameter declares a List for 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 a Set, a Collection or 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 a List.

  • A @service on 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 @service returning 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 @service must 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.String for a String and java.lang.Integer for an Int, and not many where the field is one record, scalar or enum. Under an object this holds per key, for a Map’s values or for a `List’s elements in the keys' order, so a list field answers `Map<Key, List<V>> or List<List<V>>, and an enum field answers its Java enum, Map<FilmRecord, MpaaRating>. A Map’s key is the class the `Sources parameter collects, since each parent’s answer is found by the key it was handed, and its value names a class: a raw Map or a type variable says nothing the field can be handed. Wherever one field is handed many, a Set, a jOOQ Result or any other Iterable of them serves as a List does, read in the order it iterates. A single value under a list field is refused as LIST_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 @service answers for a type carrying @table are 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 @table they are read as handed, as any class is, and need no key.

  • A @service field 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, @service always 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 a Sources parameter, the parent keys, and returns one value per key: Set<Key> paired with Map<Key, V>, or List<Key> paired with List<V> in the same order. Key is Row<N>, Record<N> or a typed TableRecord, 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 no Sources parameter is rejected at build time as SOURCE_PARAMETER_MISSING; there is no per-parent service call. @splitQuery is not needed: the field is already split, so the directive is ignored and draws the splitquery-redundant-on-service-child lint 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 jOOQ Result of anything but the parent’s table records, an answer other than a Map by key or a List/Result, and a List answer under Set keys, since a Set gives 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 Sources parameter 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 as Row<N> or Record<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 as NO_KEY_FROM_PARENT, one with two as KEY_ROW_AMBIGUOUS, and one whose only such members return a list of the records as MANY_KEYS_INTO_ONE, since a service batches one key per parent; a field without @service fetching its own rows there reads the member named as the field, and two such members are refused as KEY_ROW_AMBIGUOUS too. The keys' table needs a primary key to batch by, or the field is refused as KEY_TABLE_WITHOUT_PRIMARY_KEY, which holds for a field without @service fetching 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 @service on 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 @error channel claims the exception into a payload. A ctx.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 @service on 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 @service says transactionControl: 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, a ctx.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 @outbox on 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 @service invocation: on the escape-hatch path, and on Query fields on either path, the generated fetcher calls your method on a bare DSLContext, so the method owns the commit point, and a service whose contract is all-or-nothing must open the transaction itself with ctx.transactionResult(…​) on the injected context. A @mutation write 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