Introduction
During development and testing, there's often a need for some initial data in a database that would help us to, for example, try out something or write tests.
In this tutorial, we'll see how to seed the database in the Spring Boot project. Our idea is to first check if the database is really empty, and if it is, to write two User objects. Our code should execute right after the application starts so that we don't need to explicitly invoke it.
We don't need any additional Maven dependency, we'll be using Spring core and Spring data features.
Implementation
Let's create a User class where we will add three parameters: id, firstName, and lastName.
package com.javahowtos.dataseeddemo.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="users")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
public User(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Now, we need to create repository class for user:
package com.javahowtos.dataseeddemo.repository;
import org.springframework.data.repository.CrudRepository;
import com.javahowtos.dataseeddemo.model.User;
public interface UserRepository extends CrudRepository<User, Long> {
}
We don't need to annotate it with @Repository since CrudRepository already extends Repository interface.
Now, let's create our data seed class:
package com.javahowtos.dataseeddemo.dataseed;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.javahowtos.dataseeddemo.model.User;
import com.javahowtos.dataseeddemo.repository.UserRepository;
@Component
public class UserDataLoader implements CommandLineRunner {
@Autowired
UserRepository userRepository;
@Override
public void run(String... args) throws Exception {
loadUserData();
}
private void loadUserData() {
if (userRepository.count() == 0) {
User user1 = new User("John", "Doe");
User user2 = new User("John", "Cook");
userRepository.save(user1);
userRepository.save(user2);
}
System.out.println(userRepository.count());
}
}
As you can see in code, we're implementing the CommandRunner interface since its run method will execute just after the application starts. We also need to mark this class as Spring component so we're able to use UserRepository.
Conclusion
Database seeding is a handy and useful feature. In this tutorial, we've seen one way to implement it.
Complete code is available over on GitHub.