Skip to content
Advertisement

Java Spring Boot – how to seed a database like in PHP Laravel

I’m trying to learn Java Spring Boot. I’m coming from PHP Laravel and the one thing I miss about the framework is how easy it is to make database seeders and factories etc. I’m trying to figure out a way where I can seed my h2 db so that every time the application does a hot reload it will create some data for testing. So far in the SpringBootApplication file I have this

JavaScript

As you can see it’s all hard coded, but I was wondering if there is a better way to do this.

For example something like this came to mind:

JavaScript

The above didn’t really work. I was wondering if anyone knows of a better solution. I’m not even sure if this is where I should be seeding the database or if there are better options for doing this in terms of architecture/design. For example what if I need to seed my database with something like different roles a user might have in the application.

So for example in Laravel I could do something like this as a join table (hopefully this will illustrate the point more):

JavaScript

Appreciate any help with this, thank you.

EDIT: I finally got something working, but I’m having another issue with it creating null rows and always in the same location and I’m not sure why. Both of the maps don’t have any null data. I’m not sure what I did wrong here, thank you for your help.

Here is my code:

JavaScript

Another strange thing is sometimes the amount of rows is off. It should be 10 rows each time, but for some reason it can be off by 1

enter image description here

9 rows in the above result.

enter image description here

10 rows in the above result.

Advertisement

Answer

Figured it out. The issue was with the set methods that were using a List<T> and having the new instance of each Entity outside of the loop. Once I put it inside everything worked. The only thing I couldn’t get done was the randomness part, but the data is there which was the point of this exercise. I hope this helps anyone else that’s trying to do something similar. Also check out this solution for making a database seeder class How to seed the database in Spring Boot project?

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement