GraphQL: Java Schema Annotations

[This post is woefully out of date, read the Update]

In my prior post on GraphQL server in Java I noted the complexity of defining the schema and committed to look at the tools offered to ease the process. Here we are. I’ve migrated the schema definition over to using an annotation package and as I’m generally pleased with the results as it really did simplify the schema definition.

Class Definitions

Defining the classes was trivial. Simply adding a few annotations to the entity getter methods:

Once those are in place, anywhere you reference that type in your queries or mutations will “do the right thing.”


This was a bit less polished, but worked well enough too. They offered a couple of approaches and in the end I implemented the following pattern:

There a few things going on here to note.  First the annotation tool scans the .class definition, so either you use static methods, or if you use instance methods it’s going to call the no argument constructor to create and instance.  Since data fetchers need data, I was a little confused about what to do with static methods, or a no argument instance – how do you get your data access objects in there?  Obviously you could make you DAO objects into singletons and get at them that way but that seemed ugly.  What I found, by digging into the code was that if your GraphQL dispatcher passed in a context object that was accessible via the DataFetchingEnvironment.getSource() method. So I went with static methods and as you see in line 6 above I access the DAO via getSource().

Using the Annotated Classes

Once you’ve annotated your entities and created an annotated query and mutation class here is how to create your schema:


I felt the annotations definitely made the code simpler and cleaner.  About my only complaint was that the documentation and examples were so terse that I ended up tracing through the code to figure out how some of it came together.


2 thoughts on “GraphQL: Java Schema Annotations

  1. Pingback: GraphQL: Java Server, JavaScript Client | My name is Ozymandias
  2. Pingback: GraphQL Java 6.o | My name is Ozymandias

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s