Application Development: Back-End Solution With Java

In this article we'll develop a back-end solution that can be used with any front-end (Web, mobiles...). In the next article we'll extend on this example and work on the front-end using AngularJS, JQuery and Bootstrap CSS.

The goal of the application is to be able to administer books. In particular, we'll develop the back-end solution for that application that should be able to:

  • Add new book
  • Update existing book
  • Delete an existing book
  • List all books
  • Display details of the selected book
  • Delete all books

Disclaimer: This article does not provide detailed tutorial nor instructions how to use frameworks listed below. It is a step by step guide how to develop an sample application with different frameworks and technologies combined. If the same steps as described below are followed, the end result will be a fully developed back-end application

All the data will be stored in transactional database and exposed to front-end through JSON REST API.

All the code will be done in the TDD fashion. If this is your first time working with TDD, tests that we will be writing might look like a waste or overkill. I urge you to give TDD a try. After a bit of practice, most people find TDD indispensable as a way to design their code as well as a safety net. On a unit level, we have all our code always tested and working as we expect. All our test classes will follow the same naming convention. They will be located in src/test/java directory in the same package as the implementation code. Class name will be sufixed with Test. For example, tests for the Book class should be in the BookTest class. Try to follow the tests. Pick the first one for the specified class, run it and observe that it fails, implement just enough to make the test pass, run all tests and observe that they all pass, refactor the code, repeat.

Make sure that Java and Gradle are installed before starting this tutorial. We will be using IntelliJ IDEA as our favorite IDE.

Completed code can be found in the TechnologyConversationsBooks GIT repository.

Following frameworks and libraries are selected for the back-end of this application:

  • Gradle: Gradle can automate the building, testing, publishing, deployment and more of software packages or other types of projects such as generated static websites, generated documentation or indeed anything else. It combines the power and flexibility of Ant with the dependency management and conventions of Maven into a more effective way to build.
  • JUnit: Simple framework to write repeatable tests.
  • Hamcrest: Provides a library of matcher objects.
  • JSONAssert: Allows easier creation of JSON tests.
  • HSQLDB: HSQLDB offers a small, fast multithreaded and transactional database engine with in-memory and disk-based tables and supports embedded and server modes.
  • Hibernate: Hibernate is idiomatic persistence for Java and relational databases.
  • Jersey: Jersey helps with development of RESTful Web Services in Java.
  • Grizzly: Grizzly helps developers to build scalable and robust servers using NIO as well as offering extended framework components: Web Framework (HTTP/S), WebSocket, Comet, and more.


We will start by creating a new Gradle Java project. Once we're all set, we'll create data persistence to the database. From there on we'll move into JSON REST API. Finally, since this is a public API that should be used by others, we'll package the application.

Project setup

gradleCreate a new project in IDEA by selecting Gradle as project type. Put following dependencies to the build.gradle file:


Whole file can be found in the build.gradle GIT repository.

booksDependenciesRefresh dependencies by clicking the "Refresh All Gradle Projects" icon inside the "Gradle" tab. Once project is refreshed you'll see all the dependencies in the project External Libraries.

Create directories src/main/java and src/test/java. They will hold implementation code and tests. Both of those directories should have the package com.technologyconversations.books.


Our API should be able to provide following book information:

  • ID: Unique identifier
  • Image: The URL to the item cover-art
  • Title: The title of the item
  • Author: The author of the item
  • Price: The price of the item
  • Link: The link to the item details

Let's create the Book class that will act as Java bean object holding all this information. This bean will implement getters and setters for each data type. Following is the test for ID getter/setter followed with the implementation.



Similar code should be repeated for the rest of getters and setters.

Further on, we should override equals and hashCode methods so that we can compare two instances of our Book bean (this will come in handy with tests we'll write later on).



Similar code should be repeated for the rest of fields that should be included in equals method.

Finally, we should add persistence annotations to the Book class and all fields.


Final version of tests can be found in the and implementation in the


hibernate_logo_aWe will use Hibernate to store and retrieve data from HSQLDB. For the sake of fast execution of tests we'll use in-memory database. Production version of the application should change the mode to file or even switch to a different DB.

First step is to create a new directory src/main/resources and place the hibernate.cfg.xml inside. This is the Hibernate configuration file. Please take a look at the final version of hibernate.cfg.xml. The file is pretty straight-forward and easy to understand. The key entry is the mapping that should point to the Book class created earlier. Another setup file is the Tests can be seen from With both in place, we can start working on our Book DAO (Data Access Object) that will provide a bridge between the Book class and the HSQL database.

We'll implement following methods:

  • deleteAllBooks: Removes all books from the database.
  • getAllBooks: Gets all books from the database.
  • getBook: Retrieves the specified book.
  • saveOrUpdateBook: If the book already exists, it gets updated. Otherwise, new book is inserted to the database.
  • deleteBook: Deletes the specified book.

We'll start by creating @Before and @After methods that will be executed before and after each test. Their purpose is to setup initial set of data (one book) and delete all data after each test. Both will be required by tests further on.


We'll have to implement those two methods. Later on we'll refactor them and write more extensive tests. At the moment it is important that all books can be deleted and that we can insert new books.


By doing this implementation without tests we are breaking the TDD rule to write tests first. However, alternative would be to use JDBC directly without Hibernate for those first tests. We will get back to those methods later on. Now that we have our setup and cleaning in place, we can start working on our tests and implementation. We'll start with tests for the getAllBooks method.



Next we'll want to save bandwidth by retrieving only the necessary columns (ID and title). Also, in order to provide pagination capabilities we should be able to return books starting from specified offset and to limit the number of results. Tests that verify those requirements could be:


If we do the implementation of each test one by one, final solution might look something like:


Please consult for the complete set of tests and for the final implementation.

Now that we have the persistence done, we can move to the JSON REST API.


grizzlyHeadWe will be using Grizzly as the server serving JSON REST requests. For that purpose we'll create It will be used by our tests to start and stop the server. Also, it will contain the main method that can be used to start the server manually.


Complete source code can be found in the


Our back-end solution will expose API through JSON REST services. This way we are removing any coupling between back-end and front-end. Later on we can create Web site, Android, iOS or desktop applications that consume those services.

As with the BookDaoTest, we'll start with setup and cleanup methods. This time we'll introduce 2 new annotations: @BeforeClass and @AfterClass. Unlike @Before and @After that are executed before and after each test, @BeforeClass and @AfterClass annotations are executed before and after the class itself. In other words, @BeforeClass is executed before the first test and @AfterClass is executed after the last test in that class. In this case we want to start the server before the first test and stop it at the end.


Let's start with the request that should return the list of all books.The URL should be /api/v1/items. Response should be JSON list of books. Functionalities should reflect those stated in the DAO with offset and maximum number of books to retrieve as optional parameters. Response should be using format [{id: BOOK_ID, link: LINK_TO_DETAILS, title: BOOK_TITLE}, {...}].


The implementation after all the tests from above looks like:


For the rest of requests, please consult and


Now that we have the code and the tests for our back-end application done, it is time to package our application. Gradle makes this task very simple. All we have to do is add war and application plugins.


Full version can be found in build.gradle.

To create zipped distribution with the compiled JAR, dependencies and startup scripts:

The result is a ZIP file with startup scripts inside the bin directory. When run, it will run the Grizzly server and start serving JSON requests.

To create WAR file suitable for deployment to any Web server:

What Next?

Right now we have our back-end application with permanent storage and capable of serving JSON requests. Now we're ready to start working on the front-end. Next article Application development: front-end solution with JavaScript continues where we stopped. We'll work with HTML5, AngularJS, JQuery, Bootstrap CSS and plain old JavaScript.

Test-Driven Java Development

7429OS_Test-Driven Java DevelopmentTest-Driven Java Development book wrote by Alex Garcia and me has been published by Packt Publishing. It was a long, demanding, but very rewarding journey that resulted in a very comprehensive hands-on material for all Java developers interested in learning or improving their TDD skills.

If you liked this article I am sure that you'll find this book very useful. It contains extensive tutorials, guidelines and exercises for all Java developers eager to learn how to successfully apply TDD practices.

You can download a sample or purchase your own copy directly from Packt or Amazon.

14 thoughts on “Application Development: Back-End Solution With Java

  1. routers

    great submit, very informative. I ponder why the other specialists
    of this sector do not realize this. You should continue your writing.
    I am sure, you’ve a great readers’ base already!

  2. laullobet

    Hi Viktor and Jordi, this article has been very usefull.
    I’m having troubles in deploying the war file on glassfish, how should I do ti ? At what path should my curl rest request be sent to ? Should i need to add code to the project ( extend an app from org.glassfish.jersey.server.ResourceConfig ) as said in here If so, which package should I point to ?

    Thanks !! Gracies !!


  3. Dana Dabbagh

    Hi guys, thank you for the great article. I’m following it currently but I’ve run into an issue – note I haven’t used hibernate before this tutorial. But essentially, I get this error:
    “Batch update returned unexpected row count from update” when trying to run BookDaoTest. I tried using your code as well and get the same problem. When I looked into it further i found that setting Book ID directly causes this issue since it conflicts with the ” @GeneratedValue(strategy=GenerationType.AUTO)” tag in Book ID. See this answer on SF:

    I fixed it by not directly setting the ID.


  4. Pingback: Application Development Technologies – My Snaps

  5. problemcocaina

    Hey there! Love your article. Very useful for a quick approach.
    I think you´ve forgot the StandaloneServer part.
    Keep going!


Leave a Reply