Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 835 Vote(s) - 3.54 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Spring Boot - Loading Initial Data

#1
I'm wondering what the best way to load initial database data before the application starts? What I'm looking for is something that will fill my H2 database with data.

For example, I have a domain model "User" I can access users by going to /users but initially there won't be any users in the database so I have to create them. Is there anyway to fill the database with data automatically?

At the moment I have a Bean that gets instantiated by the container and creates users for me.

Example:

@Component
public class DataLoader {

private UserRepository userRepository;

@Autowired
public DataLoader(UserRepository userRepository) {
this.userRepository = userRepository;
LoadUsers();
}

private void LoadUsers() {
userRepository.save(new User("lala", "lala", "lala"));
}
}

But I very much doubt that is the best way of doing it. Or is it?
Reply

#2
Spring Boot allows you to use a simple script to initialize your database, using [Spring Batch][1].

Still, if you want to use something a bit more elaborated to manage DB versions and so on, Spring Boot integrates well with [Flyway][2].

**See also:**

- [Spring Boot Database initialization][3]


[1]:

[To see links please register here]

[2]:

[To see links please register here]

[3]:

[To see links please register here]

Reply

#3
You can simply create a `import.sql` file in `src/main/resources` and Hibernate will execute it when the schema is created.
Reply

#4
If I just want to insert simple test data I often implement a [`ApplicationRunner`][1]. Implementations of this interface are run at application startup and can use e.g. a autowired repository to insert some test data.

I think such an implementation would be slightly more explicit than yours because the interface implies that your implementation contains something you would like to do directly after your application is ready.

Your implementation would look sth. like this:

@Component
public class DataLoader implements ApplicationRunner {

private UserRepository userRepository;

@Autowired
public DataLoader(UserRepository userRepository) {
this.userRepository = userRepository;
}

public void run(ApplicationArguments args) {
userRepository.save(new User("lala", "lala", "lala"));
}
}

[1]:

[To see links please register here]

Reply

#5
You can use something like this:

@SpringBootApplication
public class Application {

@Autowired
private UserRepository userRepository;

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@Bean
InitializingBean sendDatabase() {
return () -> {
userRepository.save(new User("John"));
userRepository.save(new User("Rambo"));
};
}
}

Reply

#6
Here is the way I got that:

@Component
public class ApplicationStartup implements ApplicationListener<ApplicationReadyEvent> {

/**
* This event is executed as late as conceivably possible to indicate that
* the application is ready to service requests.
*/

@Autowired
private MovieRepositoryImpl movieRepository;

@Override
public void onApplicationEvent(final ApplicationReadyEvent event) {
seedData();
}

private void seedData() {
movieRepository.save(new Movie("Example"));

// ... add more code
}

}

Thanks to the author of this article:

[To see links please register here]

Reply

#7
This will also work.

@Bean
CommandLineRunner init (StudentRepo studentRepo){
return args -> {
// Adding two students objects
List<String> names = Arrays.asList("udara", "sampath");
names.forEach(name -> studentRepo.save(new Student(name)));
};
}
Reply

#8
The most compact (for dynamic data) put @mathias-dpunkt solution into MainApp (with Lombok `@AllArgsConstructor`):

@SpringBootApplication
@AllArgsConstructor
public class RestaurantVotingApplication implements ApplicationRunner {
private final VoteRepository voteRepository;
private final UserRepository userRepository;

public static void main(String[] args) {
SpringApplication.run(RestaurantVotingApplication.class, args);
}

@Override
public void run(ApplicationArguments args) {
voteRepository.save(new Vote(userRepository.getOne(1), LocalDate.now(), LocalTime.now()));
}
}
Reply

#9
If someone are struggling in make this to work even following the [accepted answer][1], for me only work adding in my `src/test/resources/application.yml` the H2 `datasource` details:

spring:
datasource:
platform: h2
url: jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
driver-class-name: org.h2.Driver
username: sa
password:

[1]:

[To see links please register here]

Reply

#10
In Spring Boot 2 data.sql was not working with me as in spring boot 1.5


> import.sql

In addition, a file named `import.sql` in the root of the classpath is executed on startup if Hibernate creates the schema from scratch (that is, if the ddl-auto property is set to create or create-drop).

**Note very important if you insert Keys cannot be duplicated do not use ddl-auto property is set to update because with each restart will insert same data again**

For more information you vist spring websit

[To see links please register here]

Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through