Spring Data saves you a lot of time by creating smart DAOs that you can basically get for free without writing any code. It basically follows the Repository Pattern from Eric Evans’ DDD book and treats entities as collections. It has a great convention that allows you to specify criteria for complex queries, and even leverage the JPA Criteria API or the QueryDSL fluent APIs for even more complex queries/specifications. The best part is the abstraction works not just for JPA, but many other providers. There are some great examples using spring-data within the spring ecosystem like Spring Boot but some times you want to use it outside the magical, enchanted world of Spring Boot.
And if you’re doing any serious system integration, you’re probably also using Apache Camel, so in the following quick blog (promise) I’ll show you the salient parts you’ll need when using with Camel… however, there’s nothing too special here. We basically deconstruct some of the magic that Spring Boot otherwise takes care of for you and allows you to understand the constituent pieces that will be necessary to have in place (and this is true if running Tomcat, Dropwizard, Wildfly, or any container).
To use JPA, we’ll also want an persistence.xml file. If you want to use Mongo or something else, refer to that specific spring-data mdoule for how to do that.
This should give us the foundation for using spring-data! Now, let’s do some fun stuff. We’ll add a Repository that will allow us to do CRUD operations (and more!) against the database:
We have our repository but we need to tell spring how to find it and apply some magic. So let’s add it to the spring context like this (and have spring scan a package to discover the repository)
Note, this will require the appropriate namespaces (assumption is we’re using the spring XML config; java config is also supported but not shown here):
Now let’s inject our repository into our own POJO class from which we can use it! Woah, woah… “we haven’t actually written any code to implement this repository” you say… yes that’s true! Spring-data does that for us!
Let’s inject:
Note the name of the repository organizationRepository is created by convention by spring when it scans the package for repositories, but we can still get a hold of it and use it like any other spring bean in the bean factory. Now, let’s use this wrapper class (OrganizationCollection in this case) in our Camel routes:
Cool! We have 3 separate routes that use our orgCollection pojo (which in turn uses the organizationRepository that leverages spring-data). Let’s take a look at that POJO:
We inject the OrganizationRepository and use it here to query the data store. Notice the parameters have Apache Camel annotations that extract values from the headers and body to use as parameters.