Showing posts with label spring. Show all posts
Showing posts with label spring. Show all posts

Jul 2, 2015

Single Repository, one Aggregate

A Repository as defined in Domain Driven Design manages a single Aggregate. An aggregate may contain many entities, and value objects, but will have a single object as its root. Many of the Dao and even now some of the Repository implementations I see do not follow this, they are more likely to have a Repository per entity, than a Repository per aggregate, and of course in some cases this is required for various reasons.

Ok, to start out we need our POM (or you can use Gradle), which configures our dependencies and plugins. We use a starter for Spring Data JPA, which pulls in Spring Data JPA and all of it's suggested dependencies such as Hibernate. We also need a database and a database driver so we configure H2. Since we are inheriting from the Spring Platform BOM we don't need to specify versions as it can configure them for us. We of course want to use Java 8 and specify our Application class so we will be able to run mvn spring-boot:run at the end.


Next Let's configure our application to show the SQL that it is running, this isn't required. You need to put application.properties in src/main/resources.

Now we need to create our Entities, let's start at the entity Bar that is the deepest part of the Aggregate root. It extends AbstractPersistable so that we get an Auto Incrementing or Sequenced id. We also use AbstractPeristable because for our task we require that our entities implement Persistable, as it changes the behavior of save on the repository if your objects are new.

Next let's create Foo, it is much the same, but you'll notice the @OneToOne that specifies CascadeType.ALL. This is important as without it persist and merge won't work.
Alright, let's put together our repository, we could just make a CrudRepository, but let's show off some paging too. You'll notice that you have to pass the Entity and it's Primary Key identifier type to the PagingAndSorting interface, the single method that we specify will find all the Foos by the nested baz property, using a LIKE '%mystring%' query. Spring data will parse this interface and make an implementation for you automatically.

You can create other lastly we do our Application, which is not designed to be a web server (it will exit immediately). The @SpringBootApplication makes Spring Boot able to start the app and scan for components appropriately. We also Enable JPA repositories using the @EnableJpaRepositories. It's main method (not recommended to prepopulate data this way), creates and save several Foos with nested bars, then I demonstrate a way that you can page the saved objects 2 at a time whilst filtering by that like statement, only 3 of the 4 entities saved will return.

The full source is available here.

Sep 2, 2014

Using Spring to create a full REST API in less than 60 lines of code

Spring with Spring Data is awesome. Seriously, I've never been able to throw up a full HATEOAS REST web service this fast. To start, I'll admit my headliner lie, I'm not counting the pom.xml.


cloc .                                                                 slave-vi
       5 text files.
       5 unique files.
       2 files ignored.

http://cloc.sourceforge.net v 1.62  T=0.04 s (104.8 files/s, 3930.8 lines/s)
-------------------------------------------------------------------------------
Language                     files          blank        comment           code
-------------------------------------------------------------------------------
Maven                            1              6              7             65
Java                             3             15              0             57
-------------------------------------------------------------------------------
SUM:                             4             21              7            122
-------------------------------------------------------------------------------

The basics of the web service is we want to be able to create tasks, like those on a todo list, for now we want the simplest tasks possible, in as little code possible. We should use UUID's so that our service can scale horizontally, so that we can easily generate known test ID's and we know that no two entities will share an id if we ever wanted to flatten things. We need to be able to perform basic CRUD on all of our entities as well as list them.

First let's create our Task. As you can see it's incredibly simple, we have our UUID identity, the uuid and uuid2 basically are telling Hibernate and H2/PostgreSQL to use UUID's. You might ask why limit description to 100 characters, well, since these are quick tasks, I might want to share them in a tweet, and this allows enough room for a url shortner plus the description. I think the rest is pretty self explanatory.

Now let's create our Repository. Well that doesn't do anything... oh but it does, and although it doesn't show it, because this application doesn't need it, there's a nifty method signature parser dsl that allows you to build queries just by writing a method signature.

Here's our Application. ... and pom for dependencies and stuff.

Here's the output of some curl commands I ran.

For a slightly more in depth tutorial you can see the official spring date rest getting started page. In the future I'll try to write about how to actually connect to PostgreSQL and set up API Authentication and Authorization

People are always telling me how verbose Java is, how much less typing their language (especially Perl is). I'd love to see a Perl app that can do all this in fewer lines of Perl (restriction, no line may be longer than 120 characters, and must be humanly readable), I personally don't think it can be done at this time (not with full HATEOAS and as many response codes), but I'm waiting for the day it can, and can be structured this simply.