Subscribe / Unsubscribe Enewsletters | Login | Register

Pencil Banner

Jump into Java microframeworks, Part 2: Ninja

Matthew Tyson | Nov. 25, 2015
Build a functional Person application with Ninja.

Refresh the browser and you'll be able to create a person; just input a first and last name and hit Add.

Querying and rendering data

To round out our persistence model for the Person class, we'll render the people in the database. Start by creating a getPeople() handler method on ApplicationController, as shown in Listing 14. You'll notice that we're going with a single-page, RESTful-style web app.

Listing 14. ApplicationController.getPeople


	public Result getPeople(){

		EntityManager entityManager = entitiyManagerProvider.get();

	    Query q = entityManager.createQuery("SELECT p FROM Person p");

	    List<Person> people = (List<Person>) q.getResultList();

	    return Results.json().render(people);


In Listing 14 we annotate the getPeople() method with @UnitOfWork, which informs Guice/JPA that the method is instrumented as a non-transactional block. Again, we get the EntityManager, and then use it to create and execute a simple JPQL (Java Persistence Query Language) query for all Person entities. Finally, we render the list of Persons with the JSON helper method.

Next, let's add a simple div with an ID of people, to hold the list of people. Place the div in index.ftl.html, like so: <div id="people"></div>.

All we need now is to add a couple things to App.js, as shown in Listing 15.

Listing 15. App.js with loadPeople support

App = {

		startup: function(){




		addPerson: function(){

			var person = $('#personForm').serializeObject();


		        url: '/person',

		        type: 'POST',

		        contentType: 'application/json',

		        data: JSON.stringify(person),

		        success: function(){



		        error: function(x){

		        	console.error("encountered a problem: ", x);



			return false;


		loadPeople: function(){

			$.getJSON( "/people", function( data ) {

				  var items = [];

				  $.each( data, function( key, val ) {

				    items.push( "<li id='" + key + "'>" + val.firstName + " " + val.lastName + "</li>" );







$( document ).ready(function() {



Now when the application opens the index page, the list of people will be populated. It will also be updated when a new Person is added via the Add button. This is all done with basic jQuery processing of the JSON returned by the getPeople service.

Completing the CRUD cycle

So far we've covered the CR and D of CRUD -- the create, read, update, and delete functions of an application interface. The update function is easy to extrapolate from examples so far, so I'll leave that as an exercise for you. In a more complex application you'd also want to extract the data access into a DAO layer, but that is beyond the scope of the demo here.


Previous Page  1  2  3  4  5  6  7  8  Next Page 

Sign up for CIO Asia eNewsletters.