Pages

Monday, February 10, 2014

Spring-data-jpa Tutorial

Spring-data-jpa is one of my favorite Spring projects. This is probably because writing and editing SQL is way down my list of 'fun things to do'. The Spring-data project allows you to just write an interface for the repository and leave the actual implementation to the library. If you are familiar with Ruby it's similar to how ActiveRecord works.

All of the source code for this tutorial can be found on here.

BuildScript

I'll start off with the build script. Pretty simple and straightforward. We are using Hibernate as our JPA provider, but any should work fine. For this tutorial I'm also using the in-memory database HSQLDB. Even in real projects I like to include HSQLDB for testing. It allows us to have unit tests that hit an actual database but are still fast and work if you aren't connected to a work VPN.


Java Configuration

To enable the spring-data-jpa repositories add the annotation @EnableJpaRepositories and provide it with the package(s) that contain repositories. A couple of things to notice about this configuration file is that we tell Spring how to close the database when it is shutdown (@Bean(destroyMethod = "shutdown")). Failure to do this can lead to all kinds of weirdness. The second thing I wanted to point out are the properties at the bottom. Among some other things this will load the schema from the annotations in the Java files and create a file called schema.sql which you can use to create your database. This is super useful for testing using an in-memory database or as a base for creating your production database.


The Domain and Repository

The domain is annotated like you've been doing using JPA or Hibernate. The real magic is the repository. It's just an interface. All the implementation details are hidden away in the spring-data-jpa project. For the majority of your CRUD methods you can use the methods provided or create your own using just the method signature. If you need more control you can use the @Query annotation and provide your own SQL.


A test

A test to make sure everything works

If this has piqued your interest I highly recommend reading through the spring-data-jpa documentation. It's relatively short and very well written in my opinion.

Generating Schema with JPA/Hibernate

When creating new projects I tend to create the application code first and generate the database schema from that code. One of the nicer things added in JPA 2.1, which has been supported in Hibernate for several years, is the ability to generate a schema based on Java annotated classes. In practice I've found that in order to accomplish generating the schema and using it to test with an in memory database requires both Hibernate and JPA properties.

These properties will generate a script called schema.sql that will create the schema for an HSQL database. It will also load that schema with data from a file called data.sql. Note that data.sql needs to be on the classpath.

    jpaProperties.put(Environment.HBM2DDL_AUTO, "create");
    jpaProperties.put(Environment.HBM2DDL_IMPORT_FILES, "data.sql");
    jpaProperties.put("javax.persistence.schema-generation.create-database-schemas", "true");
    jpaProperties.put("javax.persistence.schema-generation.scripts.action", "create");
    jpaProperties.put("javax.persistence.schema-generation.scripts.create-target",
        "src/test/resources/schema.sql");
    jpaProperties.put("javax.persistence.database-product-name", "HSQL");

 See the complete Java configuration on github here. It uses Spring framework, Spring-data-jpa, and Hibernate.

Sunday, February 9, 2014

Modern Spring 4 MVC Hello World Tutorial

I was browsing reddit as I am wont to do at pretty much any hour of any day and came across a Spring 4 MVC tutorial. At work I use Spring 4 and was curious what a beginner tutorial would look like. Even though it was a small tutorial I expected to see things like @RestController and JavaConfig. I even hoped to see Gradle, but alas it was all XML configuration and a maven build with even more XML. No wonder people get such a bad impression of Spring and Java. Below I've quickly put together a tutorial using techniques I use working with Spring 4. I'm glossing over some things so if something doesn't make sense just leave a comment. It's super simple and some things are overkill but it's just so you can get a flavor of what working with Java and Spring 4 can really be like.

All the code can be found on it's github repository.

The build file

The most important parts are the repositories section and the dependencies section. The repositories section defines where to find the dependencies of your project designated in the dependencies section. In this case we can get everything from Maven central. The ext section defines some variables used for the specific versions of your dependencies. The buildscript section allows us to add functionality into gradle. In this case we are adding a tomcat plugin so we can launch a tomcat instance directly from the gradle build.


The Configuration

We will be using a completely XML-less configuration. This requires a server that supports servlet 3.0 and above. This means >= Tomcat 7 or >= Jetty 8. Major takeaway is that we will put our controller in the com.hello.controller package so we need to scan that package.


The Controller

Spring 4 introduced a new controller annotation @RestController. This is just a convenience annotation that means the class is an @Controller class and all the methods are @ResponseBody methods. This is a nice addition when building out REST webservices using Spring MVC.


The view

We are using AngularJS to interact with our controller. The way most of the webapps I've been writing lately work is having a Java backend provide a REST webservice to a javascript frontend. There are pros and cons to this approach which can be debated but I've been having fun and been productive using this method.

The Controller Test

Spring has really nice support for testing your controllers as well.



Result

Make sure you have JDK 7 installed and then run it yourself by grabbing the code and from the command line run ./gradlew tomcatRun for OSX/Linux or gradlew.bat tomcatRun if you are on Windows. Gradle should take care of everything else for you.

Package Filters in Eclipse

Package filtering is a way to help weed out all those useless packages that pop up when importing a class into some code you are writing.

In the video below I show you how to set it up.


Saturday, February 8, 2014

Open resources in eclipse

The open resources dialog is a quick and easy way to navigate through your code base. In my opinion it becomes essential once the code base reaches a non-trivial size.

Opened using Ctrl-R in Windows/Linux and Cmd-R in OSX.