0

How can I put initial data in DB after initiating Spring Boot?

I would like to do like this:

  1. If database already exists, nothing happens.
  2. After automatically a database created, which has many tables described in entity files,

I would like to put initial data by certain method like this:

@Autowire
UserRepository ur;
 
public void putdata(){
  User u = new User();
   
  ur.save(u);
}

The important point is #1 above. When database already exists, the method must not be called and not using a SQL file outside.

Simon Martinelli
  • 34,053
  • 5
  • 48
  • 82
kensuke1984
  • 949
  • 1
  • 11
  • 21
  • Issue query to see if data exists, if so don't do anything... You are probably overthinking this. Also letting Hibernate manage your database through its entities is a bad idea, ideal for rapid prototyping not for use in production!. – M. Deinum Jun 20 '22 at 14:00
  • Please read https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto.data-initialization – Simon Martinelli Jun 20 '22 at 14:01
  • 1
    Does this answer your question? [Spring Boot - Loading Initial Data](https://stackoverflow.com/questions/38040572/spring-boot-loading-initial-data). Add your desired condition to `run` method – Eskandar Abedini Jun 20 '22 at 14:19
  • ill take the one implementing application runner thank you – kensuke1984 Jun 20 '22 at 15:06
  • I asked https://stackoverflow.com/questions/72689308/how-to-see-if-spring-boot-initializes-database. please anser it as well – kensuke1984 Jun 20 '22 at 15:16

0 Answers0