If you are from a Laravel background, you will know how easy it is to load initial data into the database. In Spring Boot, the process is as simple as it is in the Laravel framework.
While using JPA, your entity would look something like this:
@Entity
public class User {
@Id
@GeneratedValue(strategy = IDENTITY)
private Integer id;
@NotBlank(message = "Username is required")
private String username;
@Email
@NotEmpty(message = "Email is required")
private String email;
// Getters and setters
}
When you run your application, the table ‘user’ will be created.
Alternately, you can also create tables by writing entities schema in a file named schema.sql in the resources folder.
But there will come a situation when there is a need for some data in your table when you access your application. For example, an admin user data to let the admin do his/her task.
To do this typical task, create a file named data.sql in the resources folder and write an insert script. For example:
insert into sa_user(id, email,username) values (1, 'foo','foo@foo.com');
Importantly, in your application.properties file customize data initialization mode as follows: (given that you’re using a database other than embedded DataSource)
spring.datasource.initialization-mode=always