A Java alternative to import.sql using ApplicationListener

A Java alternative to import.sql using ApplicationListener

I’ve long been using a useful feature in Hibernate – import.sql files, which can fill your application at setup with development data. As the name suggests, however, this requires the execution of an SQL file. Clunky generating tools notwithstanding, this requires manual work. Refactoring becomes more difficult, it’s tricky to generate random data, and so on.

Several solutions are available to this, but I personally quite like the concept of Loaders within the Spring Framework.

You can make one of these classes for every logical little block you have. Since you will end up using Java methods here, it cleanly changes along when you’re refactoring. In order to fill it up with some reliable data, I like making use of jFairy by Codearte. This lightweight library allows you to quickly generate blobs of fake text, names, phone numbers, etc. All very useful for prototyping.

Generally, I either autowire an entity repository in here to persist some test data. Additionally, I also sometimes generate in-memory items which I can attach to a singleton.

One problem I ran into when beginning to use these, is the order the Loaders were executed. Often, I would have a certain object that depends on the existence of other persisted data. One could combine the generation of this different data into its own loader, but generally it is more interesting to keep everything nicely segregated. Spring actually provides the Ordered interface for this – which will require you to implement the getOrder() method.

However, if this is still not plenty, it is also possible to force a loader to take priority over all the others. Instead of implementing Order, you implement the PriorityOrdered interface.


Kevin Deyne

A 25-year-old Software Engineer with a passion for Web, Java and Writing. Working at RealDolmen, he focuses on customer-centric projects that can actually help people and move organisations forward. Most hours of the day, he's thinking about code, integrating architectures and how to solve the next big problem. He also wrote a Lovecraft-inspired thriller called Whitewood and is working on Envir, a high-end project management tool.

Leave a Reply