Spring Boot - Loading Initial Data



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








102















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?










share|improve this question

















  • 3





    That will work, or simply add data.sql and/or schema.sql to init data.. All this is documented in the reference guide (which I suggest to read).

    – M. Deinum
    Jun 27 '16 at 5:47











  • Please mark the correct answer if that helped you.

    – Reborn
    Mar 8 '17 at 9:40











  • Has anyone got this to work? I am still unable to put this together and not sure what I am missing here. git.io/v5SWx

    – tapitoe
    Sep 16 '17 at 4:30


















102















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?










share|improve this question

















  • 3





    That will work, or simply add data.sql and/or schema.sql to init data.. All this is documented in the reference guide (which I suggest to read).

    – M. Deinum
    Jun 27 '16 at 5:47











  • Please mark the correct answer if that helped you.

    – Reborn
    Mar 8 '17 at 9:40











  • Has anyone got this to work? I am still unable to put this together and not sure what I am missing here. git.io/v5SWx

    – tapitoe
    Sep 16 '17 at 4:30














102












102








102


39






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?










share|improve this question














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?







spring spring-boot spring-data






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jun 26 '16 at 16:20









LithicasLithicas

83731420




83731420







  • 3





    That will work, or simply add data.sql and/or schema.sql to init data.. All this is documented in the reference guide (which I suggest to read).

    – M. Deinum
    Jun 27 '16 at 5:47











  • Please mark the correct answer if that helped you.

    – Reborn
    Mar 8 '17 at 9:40











  • Has anyone got this to work? I am still unable to put this together and not sure what I am missing here. git.io/v5SWx

    – tapitoe
    Sep 16 '17 at 4:30













  • 3





    That will work, or simply add data.sql and/or schema.sql to init data.. All this is documented in the reference guide (which I suggest to read).

    – M. Deinum
    Jun 27 '16 at 5:47











  • Please mark the correct answer if that helped you.

    – Reborn
    Mar 8 '17 at 9:40











  • Has anyone got this to work? I am still unable to put this together and not sure what I am missing here. git.io/v5SWx

    – tapitoe
    Sep 16 '17 at 4:30








3




3





That will work, or simply add data.sql and/or schema.sql to init data.. All this is documented in the reference guide (which I suggest to read).

– M. Deinum
Jun 27 '16 at 5:47





That will work, or simply add data.sql and/or schema.sql to init data.. All this is documented in the reference guide (which I suggest to read).

– M. Deinum
Jun 27 '16 at 5:47













Please mark the correct answer if that helped you.

– Reborn
Mar 8 '17 at 9:40





Please mark the correct answer if that helped you.

– Reborn
Mar 8 '17 at 9:40













Has anyone got this to work? I am still unable to put this together and not sure what I am missing here. git.io/v5SWx

– tapitoe
Sep 16 '17 at 4:30






Has anyone got this to work? I am still unable to put this together and not sure what I am missing here. git.io/v5SWx

– tapitoe
Sep 16 '17 at 4:30













14 Answers
14






active

oldest

votes


















168














You can simply create a data.sql file (or data-h2.sql if you only want it to be applied in case H2 is your database) in your src/main/resources folder and it will be automatically executed on startup. In this file you just add some insert statements, eg.:



INSERT INTO users (username, firstname, lastname) VALUES
('lala', 'lala', 'lala'),
('lolo', 'lolo', 'lolo');



Similarly, you can create a schema.sql file (or schema-h2.sql) as well to create your schema:



CREATE TABLE task (
id INTEGER PRIMARY KEY,
description VARCHAR(64) NOT NULL,
completed BIT NOT NULL);


Though normally you shouldn't have to do this since Spring boot already configures Hibernate to create your schema based on your entities for an in memory database. If you really want to use schema.sql you'll have to disable this feature by adding this to your application.properties:



spring.jpa.hibernate.ddl-auto=none


More information can be found at the documentation about Database initialization.




If you're using Spring boot 2, database initialization only works for embedded databases (H2, HSQLDB, ...). If you want to use it for other databases as well, you need to change the spring.datasource.initialization-mode property:



spring.datasource.initialization-mode=always





share|improve this answer

























  • Thank you @g00glen00b for clearing up : "and it will be automatically executed on startup". I was getting errors as I included the data.sql file in my bean's configuration using the addScript(s) option. As at this point the schema had not yet been built.

    – Benjamin Slabbert
    Apr 26 '17 at 7:40











  • I am having issue with the sequencing of creating the DB objects and running the data.sql. The script is run before creating the db entities. Here is my post on the issue:stackoverflow.com/questions/38040572/…

    – tapitoe
    Sep 7 '17 at 15:57







  • 3





    @nespapu You have it wrong though, the schema.sql/data.sql files will be executed when spring.datasource.initialize is true (which is the default). spring.jpa.hibernate.ddl-auto can be used to generate your tables based on your entity configuration rather than using a SQL file. This is by default enabled on in-memory databases. That's why I added the note in my answer, explaining that if you use an in-memory database and you want to use the schema.sql, you need to disable spring.jpa.hibernate.ddl-auto otherwise both will try to create your table.

    – g00glen00b
    Oct 11 '17 at 8:03







  • 5





    If you want to use the data-h2.sql filename for your initial data, you should set spring.datasource.platform=h2 in your application properties as well.

    – Jason Evans
    Mar 29 '18 at 10:45






  • 1





    The data.sql file is executed each time the spring-boot application is fired up. This means that if you have insert statements, they may cause an org.h2.jdbc.JdbcSQLException-exception, because the data is already present in the database. I am using an embedded H2 database, but the problem stays the same.

    – Igor
    Apr 22 '18 at 10:22


















57














If I just want to insert simple test data I often implement a ApplicationRunner. 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"));







share|improve this answer

























  • public void run(); method needs to be public

    – eosimosu
    Jun 26 '17 at 14:02


















21














As suggestion try this:



@Bean
public CommandLineRunner loadData(CustomerRepository repository)
return (args) ->
// save a couple of customers
repository.save(new Customer("Jack", "Bauer"));
repository.save(new Customer("Chloe", "O'Brian"));
repository.save(new Customer("Kim", "Bauer"));
repository.save(new Customer("David", "Palmer"));
repository.save(new Customer("Michelle", "Dessler"));

// fetch all customers
log.info("Customers found with findAll():");
log.info("-------------------------------");
for (Customer customer : repository.findAll())
log.info(customer.toString());

log.info("");

// fetch an individual customer by ID
Customer customer = repository.findOne(1L);
log.info("Customer found with findOne(1L):");
log.info("--------------------------------");
log.info(customer.toString());
log.info("");

// fetch customers by last name
log.info("Customer found with findByLastNameStartsWithIgnoreCase('Bauer'):");
log.info("--------------------------------------------");
for (Customer bauer : repository
.findByLastNameStartsWithIgnoreCase("Bauer"))
log.info(bauer.toString());

log.info("");




Option 2: Initialize with schema and data scripts



Prerequisites: in application.properties you have to mention this:



spring.jpa.hibernate.ddl-auto=none (otherwise scripts will be ignored by hibernate, and it will scan project for @Entity and/or @Table annotated classes)



Then, in your MyApplication class paste this:



@Bean(name = "dataSource")
public DriverManagerDataSource dataSource()
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:~/myDB;MV_STORE=false");
dataSource.setUsername("sa");
dataSource.setPassword("");

// schema init
Resource initSchema = new ClassPathResource("scripts/schema-h2.sql");
Resource initData = new ClassPathResource("scripts/data-h2.sql");
DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema, initData);
DatabasePopulatorUtils.execute(databasePopulator, dataSource);

return dataSource;



Where scripts folder is located under resources folder (IntelliJ Idea)



Hope it helps someone






share|improve this answer
































    10














    You can add a spring.datasource.data property to application.properties listing the sql files you want to run. Like this:



    spring.datasource.data=classpath:accounts.sql, classpath:books.sql, classpath:reviews.sql


    The sql insert statements in each of these files will then be run, allowing you to keep things tidy






    share|improve this answer























    • pretty clean and simple solution. thanks

      – mustache1up
      Jun 11 '18 at 0:38


















    8














    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"));
    ;







    share|improve this answer























    • I guess this is the easiest way so far...

      – bitsnaps
      Nov 25 '18 at 15:52


















    7














    Spring Boot allows you to use a simple script to initialize your database, using Spring Batch.



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



    See also:



    • Spring Boot Database initialization





    share|improve this answer


















    • 4





      suggesting spring batch here seems overkill.

      – Nick
      Jun 22 '18 at 16:10











    • @Nick, the OP does not mention the amount of data.. Anyway the answer is not all about spring batch.

      – Xtreme Biker
      Jun 22 '18 at 17:25


















    5














    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:



    http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/






    share|improve this answer























    • This does not work if you are using service, and if service in autowiring repository

      – silentsudo
      Aug 2 '18 at 9:47


















    5














    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



    https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html






    share|improve this answer






























      2














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






      share|improve this answer






























        1














        If someone are struggling in make this to work even following the accepted answer, 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:





        share|improve this answer






























          1














          I solved similar problem this way:



          @Component
          public class DataLoader

          @Autowired
          private UserRepository userRepository;

          //method invoked during the startup
          @PostConstruct
          public void loadData()
          userRepository.save(new User("user"));


          //method invoked during the shutdown
          @PreDestroy
          public void removeData()
          userRepository.deleteAll();







          share|improve this answer






























            1














            you can register and event listener to achieve that like below:



            @EventListener
            public void seed(ContextRefreshedEvent event)
            userRepository.save(new User("lala", "lala", "lala"));



            When the ContextRefreshEvent is fired, we get access to all autowired beans in the application — including models and repositories.






            share|improve this answer
































              0














              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)));
              ;






              share|improve this answer






























                0














                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()));







                share|improve this answer























                  protected by cassiomolin Mar 3 at 19:46



                  Thank you for your interest in this question.
                  Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                  Would you like to answer one of these unanswered questions instead?














                  14 Answers
                  14






                  active

                  oldest

                  votes








                  14 Answers
                  14






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  168














                  You can simply create a data.sql file (or data-h2.sql if you only want it to be applied in case H2 is your database) in your src/main/resources folder and it will be automatically executed on startup. In this file you just add some insert statements, eg.:



                  INSERT INTO users (username, firstname, lastname) VALUES
                  ('lala', 'lala', 'lala'),
                  ('lolo', 'lolo', 'lolo');



                  Similarly, you can create a schema.sql file (or schema-h2.sql) as well to create your schema:



                  CREATE TABLE task (
                  id INTEGER PRIMARY KEY,
                  description VARCHAR(64) NOT NULL,
                  completed BIT NOT NULL);


                  Though normally you shouldn't have to do this since Spring boot already configures Hibernate to create your schema based on your entities for an in memory database. If you really want to use schema.sql you'll have to disable this feature by adding this to your application.properties:



                  spring.jpa.hibernate.ddl-auto=none


                  More information can be found at the documentation about Database initialization.




                  If you're using Spring boot 2, database initialization only works for embedded databases (H2, HSQLDB, ...). If you want to use it for other databases as well, you need to change the spring.datasource.initialization-mode property:



                  spring.datasource.initialization-mode=always





                  share|improve this answer

























                  • Thank you @g00glen00b for clearing up : "and it will be automatically executed on startup". I was getting errors as I included the data.sql file in my bean's configuration using the addScript(s) option. As at this point the schema had not yet been built.

                    – Benjamin Slabbert
                    Apr 26 '17 at 7:40











                  • I am having issue with the sequencing of creating the DB objects and running the data.sql. The script is run before creating the db entities. Here is my post on the issue:stackoverflow.com/questions/38040572/…

                    – tapitoe
                    Sep 7 '17 at 15:57







                  • 3





                    @nespapu You have it wrong though, the schema.sql/data.sql files will be executed when spring.datasource.initialize is true (which is the default). spring.jpa.hibernate.ddl-auto can be used to generate your tables based on your entity configuration rather than using a SQL file. This is by default enabled on in-memory databases. That's why I added the note in my answer, explaining that if you use an in-memory database and you want to use the schema.sql, you need to disable spring.jpa.hibernate.ddl-auto otherwise both will try to create your table.

                    – g00glen00b
                    Oct 11 '17 at 8:03







                  • 5





                    If you want to use the data-h2.sql filename for your initial data, you should set spring.datasource.platform=h2 in your application properties as well.

                    – Jason Evans
                    Mar 29 '18 at 10:45






                  • 1





                    The data.sql file is executed each time the spring-boot application is fired up. This means that if you have insert statements, they may cause an org.h2.jdbc.JdbcSQLException-exception, because the data is already present in the database. I am using an embedded H2 database, but the problem stays the same.

                    – Igor
                    Apr 22 '18 at 10:22















                  168














                  You can simply create a data.sql file (or data-h2.sql if you only want it to be applied in case H2 is your database) in your src/main/resources folder and it will be automatically executed on startup. In this file you just add some insert statements, eg.:



                  INSERT INTO users (username, firstname, lastname) VALUES
                  ('lala', 'lala', 'lala'),
                  ('lolo', 'lolo', 'lolo');



                  Similarly, you can create a schema.sql file (or schema-h2.sql) as well to create your schema:



                  CREATE TABLE task (
                  id INTEGER PRIMARY KEY,
                  description VARCHAR(64) NOT NULL,
                  completed BIT NOT NULL);


                  Though normally you shouldn't have to do this since Spring boot already configures Hibernate to create your schema based on your entities for an in memory database. If you really want to use schema.sql you'll have to disable this feature by adding this to your application.properties:



                  spring.jpa.hibernate.ddl-auto=none


                  More information can be found at the documentation about Database initialization.




                  If you're using Spring boot 2, database initialization only works for embedded databases (H2, HSQLDB, ...). If you want to use it for other databases as well, you need to change the spring.datasource.initialization-mode property:



                  spring.datasource.initialization-mode=always





                  share|improve this answer

























                  • Thank you @g00glen00b for clearing up : "and it will be automatically executed on startup". I was getting errors as I included the data.sql file in my bean's configuration using the addScript(s) option. As at this point the schema had not yet been built.

                    – Benjamin Slabbert
                    Apr 26 '17 at 7:40











                  • I am having issue with the sequencing of creating the DB objects and running the data.sql. The script is run before creating the db entities. Here is my post on the issue:stackoverflow.com/questions/38040572/…

                    – tapitoe
                    Sep 7 '17 at 15:57







                  • 3





                    @nespapu You have it wrong though, the schema.sql/data.sql files will be executed when spring.datasource.initialize is true (which is the default). spring.jpa.hibernate.ddl-auto can be used to generate your tables based on your entity configuration rather than using a SQL file. This is by default enabled on in-memory databases. That's why I added the note in my answer, explaining that if you use an in-memory database and you want to use the schema.sql, you need to disable spring.jpa.hibernate.ddl-auto otherwise both will try to create your table.

                    – g00glen00b
                    Oct 11 '17 at 8:03







                  • 5





                    If you want to use the data-h2.sql filename for your initial data, you should set spring.datasource.platform=h2 in your application properties as well.

                    – Jason Evans
                    Mar 29 '18 at 10:45






                  • 1





                    The data.sql file is executed each time the spring-boot application is fired up. This means that if you have insert statements, they may cause an org.h2.jdbc.JdbcSQLException-exception, because the data is already present in the database. I am using an embedded H2 database, but the problem stays the same.

                    – Igor
                    Apr 22 '18 at 10:22













                  168












                  168








                  168







                  You can simply create a data.sql file (or data-h2.sql if you only want it to be applied in case H2 is your database) in your src/main/resources folder and it will be automatically executed on startup. In this file you just add some insert statements, eg.:



                  INSERT INTO users (username, firstname, lastname) VALUES
                  ('lala', 'lala', 'lala'),
                  ('lolo', 'lolo', 'lolo');



                  Similarly, you can create a schema.sql file (or schema-h2.sql) as well to create your schema:



                  CREATE TABLE task (
                  id INTEGER PRIMARY KEY,
                  description VARCHAR(64) NOT NULL,
                  completed BIT NOT NULL);


                  Though normally you shouldn't have to do this since Spring boot already configures Hibernate to create your schema based on your entities for an in memory database. If you really want to use schema.sql you'll have to disable this feature by adding this to your application.properties:



                  spring.jpa.hibernate.ddl-auto=none


                  More information can be found at the documentation about Database initialization.




                  If you're using Spring boot 2, database initialization only works for embedded databases (H2, HSQLDB, ...). If you want to use it for other databases as well, you need to change the spring.datasource.initialization-mode property:



                  spring.datasource.initialization-mode=always





                  share|improve this answer















                  You can simply create a data.sql file (or data-h2.sql if you only want it to be applied in case H2 is your database) in your src/main/resources folder and it will be automatically executed on startup. In this file you just add some insert statements, eg.:



                  INSERT INTO users (username, firstname, lastname) VALUES
                  ('lala', 'lala', 'lala'),
                  ('lolo', 'lolo', 'lolo');



                  Similarly, you can create a schema.sql file (or schema-h2.sql) as well to create your schema:



                  CREATE TABLE task (
                  id INTEGER PRIMARY KEY,
                  description VARCHAR(64) NOT NULL,
                  completed BIT NOT NULL);


                  Though normally you shouldn't have to do this since Spring boot already configures Hibernate to create your schema based on your entities for an in memory database. If you really want to use schema.sql you'll have to disable this feature by adding this to your application.properties:



                  spring.jpa.hibernate.ddl-auto=none


                  More information can be found at the documentation about Database initialization.




                  If you're using Spring boot 2, database initialization only works for embedded databases (H2, HSQLDB, ...). If you want to use it for other databases as well, you need to change the spring.datasource.initialization-mode property:



                  spring.datasource.initialization-mode=always






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 29 '18 at 11:18

























                  answered Jun 27 '16 at 6:17









                  g00glen00bg00glen00b

                  23.6k95381




                  23.6k95381












                  • Thank you @g00glen00b for clearing up : "and it will be automatically executed on startup". I was getting errors as I included the data.sql file in my bean's configuration using the addScript(s) option. As at this point the schema had not yet been built.

                    – Benjamin Slabbert
                    Apr 26 '17 at 7:40











                  • I am having issue with the sequencing of creating the DB objects and running the data.sql. The script is run before creating the db entities. Here is my post on the issue:stackoverflow.com/questions/38040572/…

                    – tapitoe
                    Sep 7 '17 at 15:57







                  • 3





                    @nespapu You have it wrong though, the schema.sql/data.sql files will be executed when spring.datasource.initialize is true (which is the default). spring.jpa.hibernate.ddl-auto can be used to generate your tables based on your entity configuration rather than using a SQL file. This is by default enabled on in-memory databases. That's why I added the note in my answer, explaining that if you use an in-memory database and you want to use the schema.sql, you need to disable spring.jpa.hibernate.ddl-auto otherwise both will try to create your table.

                    – g00glen00b
                    Oct 11 '17 at 8:03







                  • 5





                    If you want to use the data-h2.sql filename for your initial data, you should set spring.datasource.platform=h2 in your application properties as well.

                    – Jason Evans
                    Mar 29 '18 at 10:45






                  • 1





                    The data.sql file is executed each time the spring-boot application is fired up. This means that if you have insert statements, they may cause an org.h2.jdbc.JdbcSQLException-exception, because the data is already present in the database. I am using an embedded H2 database, but the problem stays the same.

                    – Igor
                    Apr 22 '18 at 10:22

















                  • Thank you @g00glen00b for clearing up : "and it will be automatically executed on startup". I was getting errors as I included the data.sql file in my bean's configuration using the addScript(s) option. As at this point the schema had not yet been built.

                    – Benjamin Slabbert
                    Apr 26 '17 at 7:40











                  • I am having issue with the sequencing of creating the DB objects and running the data.sql. The script is run before creating the db entities. Here is my post on the issue:stackoverflow.com/questions/38040572/…

                    – tapitoe
                    Sep 7 '17 at 15:57







                  • 3





                    @nespapu You have it wrong though, the schema.sql/data.sql files will be executed when spring.datasource.initialize is true (which is the default). spring.jpa.hibernate.ddl-auto can be used to generate your tables based on your entity configuration rather than using a SQL file. This is by default enabled on in-memory databases. That's why I added the note in my answer, explaining that if you use an in-memory database and you want to use the schema.sql, you need to disable spring.jpa.hibernate.ddl-auto otherwise both will try to create your table.

                    – g00glen00b
                    Oct 11 '17 at 8:03







                  • 5





                    If you want to use the data-h2.sql filename for your initial data, you should set spring.datasource.platform=h2 in your application properties as well.

                    – Jason Evans
                    Mar 29 '18 at 10:45






                  • 1





                    The data.sql file is executed each time the spring-boot application is fired up. This means that if you have insert statements, they may cause an org.h2.jdbc.JdbcSQLException-exception, because the data is already present in the database. I am using an embedded H2 database, but the problem stays the same.

                    – Igor
                    Apr 22 '18 at 10:22
















                  Thank you @g00glen00b for clearing up : "and it will be automatically executed on startup". I was getting errors as I included the data.sql file in my bean's configuration using the addScript(s) option. As at this point the schema had not yet been built.

                  – Benjamin Slabbert
                  Apr 26 '17 at 7:40





                  Thank you @g00glen00b for clearing up : "and it will be automatically executed on startup". I was getting errors as I included the data.sql file in my bean's configuration using the addScript(s) option. As at this point the schema had not yet been built.

                  – Benjamin Slabbert
                  Apr 26 '17 at 7:40













                  I am having issue with the sequencing of creating the DB objects and running the data.sql. The script is run before creating the db entities. Here is my post on the issue:stackoverflow.com/questions/38040572/…

                  – tapitoe
                  Sep 7 '17 at 15:57






                  I am having issue with the sequencing of creating the DB objects and running the data.sql. The script is run before creating the db entities. Here is my post on the issue:stackoverflow.com/questions/38040572/…

                  – tapitoe
                  Sep 7 '17 at 15:57





                  3




                  3





                  @nespapu You have it wrong though, the schema.sql/data.sql files will be executed when spring.datasource.initialize is true (which is the default). spring.jpa.hibernate.ddl-auto can be used to generate your tables based on your entity configuration rather than using a SQL file. This is by default enabled on in-memory databases. That's why I added the note in my answer, explaining that if you use an in-memory database and you want to use the schema.sql, you need to disable spring.jpa.hibernate.ddl-auto otherwise both will try to create your table.

                  – g00glen00b
                  Oct 11 '17 at 8:03






                  @nespapu You have it wrong though, the schema.sql/data.sql files will be executed when spring.datasource.initialize is true (which is the default). spring.jpa.hibernate.ddl-auto can be used to generate your tables based on your entity configuration rather than using a SQL file. This is by default enabled on in-memory databases. That's why I added the note in my answer, explaining that if you use an in-memory database and you want to use the schema.sql, you need to disable spring.jpa.hibernate.ddl-auto otherwise both will try to create your table.

                  – g00glen00b
                  Oct 11 '17 at 8:03





                  5




                  5





                  If you want to use the data-h2.sql filename for your initial data, you should set spring.datasource.platform=h2 in your application properties as well.

                  – Jason Evans
                  Mar 29 '18 at 10:45





                  If you want to use the data-h2.sql filename for your initial data, you should set spring.datasource.platform=h2 in your application properties as well.

                  – Jason Evans
                  Mar 29 '18 at 10:45




                  1




                  1





                  The data.sql file is executed each time the spring-boot application is fired up. This means that if you have insert statements, they may cause an org.h2.jdbc.JdbcSQLException-exception, because the data is already present in the database. I am using an embedded H2 database, but the problem stays the same.

                  – Igor
                  Apr 22 '18 at 10:22





                  The data.sql file is executed each time the spring-boot application is fired up. This means that if you have insert statements, they may cause an org.h2.jdbc.JdbcSQLException-exception, because the data is already present in the database. I am using an embedded H2 database, but the problem stays the same.

                  – Igor
                  Apr 22 '18 at 10:22













                  57














                  If I just want to insert simple test data I often implement a ApplicationRunner. 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"));







                  share|improve this answer

























                  • public void run(); method needs to be public

                    – eosimosu
                    Jun 26 '17 at 14:02















                  57














                  If I just want to insert simple test data I often implement a ApplicationRunner. 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"));







                  share|improve this answer

























                  • public void run(); method needs to be public

                    – eosimosu
                    Jun 26 '17 at 14:02













                  57












                  57








                  57







                  If I just want to insert simple test data I often implement a ApplicationRunner. 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"));







                  share|improve this answer















                  If I just want to insert simple test data I often implement a ApplicationRunner. 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"));








                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jul 11 '17 at 14:05









                  eenblam

                  3401519




                  3401519










                  answered Jun 27 '16 at 8:52









                  Mathias DpunktMathias Dpunkt

                  6,6422050




                  6,6422050












                  • public void run(); method needs to be public

                    – eosimosu
                    Jun 26 '17 at 14:02

















                  • public void run(); method needs to be public

                    – eosimosu
                    Jun 26 '17 at 14:02
















                  public void run(); method needs to be public

                  – eosimosu
                  Jun 26 '17 at 14:02





                  public void run(); method needs to be public

                  – eosimosu
                  Jun 26 '17 at 14:02











                  21














                  As suggestion try this:



                  @Bean
                  public CommandLineRunner loadData(CustomerRepository repository)
                  return (args) ->
                  // save a couple of customers
                  repository.save(new Customer("Jack", "Bauer"));
                  repository.save(new Customer("Chloe", "O'Brian"));
                  repository.save(new Customer("Kim", "Bauer"));
                  repository.save(new Customer("David", "Palmer"));
                  repository.save(new Customer("Michelle", "Dessler"));

                  // fetch all customers
                  log.info("Customers found with findAll():");
                  log.info("-------------------------------");
                  for (Customer customer : repository.findAll())
                  log.info(customer.toString());

                  log.info("");

                  // fetch an individual customer by ID
                  Customer customer = repository.findOne(1L);
                  log.info("Customer found with findOne(1L):");
                  log.info("--------------------------------");
                  log.info(customer.toString());
                  log.info("");

                  // fetch customers by last name
                  log.info("Customer found with findByLastNameStartsWithIgnoreCase('Bauer'):");
                  log.info("--------------------------------------------");
                  for (Customer bauer : repository
                  .findByLastNameStartsWithIgnoreCase("Bauer"))
                  log.info(bauer.toString());

                  log.info("");




                  Option 2: Initialize with schema and data scripts



                  Prerequisites: in application.properties you have to mention this:



                  spring.jpa.hibernate.ddl-auto=none (otherwise scripts will be ignored by hibernate, and it will scan project for @Entity and/or @Table annotated classes)



                  Then, in your MyApplication class paste this:



                  @Bean(name = "dataSource")
                  public DriverManagerDataSource dataSource()
                  DriverManagerDataSource dataSource = new DriverManagerDataSource();
                  dataSource.setDriverClassName("org.h2.Driver");
                  dataSource.setUrl("jdbc:h2:~/myDB;MV_STORE=false");
                  dataSource.setUsername("sa");
                  dataSource.setPassword("");

                  // schema init
                  Resource initSchema = new ClassPathResource("scripts/schema-h2.sql");
                  Resource initData = new ClassPathResource("scripts/data-h2.sql");
                  DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema, initData);
                  DatabasePopulatorUtils.execute(databasePopulator, dataSource);

                  return dataSource;



                  Where scripts folder is located under resources folder (IntelliJ Idea)



                  Hope it helps someone






                  share|improve this answer





























                    21














                    As suggestion try this:



                    @Bean
                    public CommandLineRunner loadData(CustomerRepository repository)
                    return (args) ->
                    // save a couple of customers
                    repository.save(new Customer("Jack", "Bauer"));
                    repository.save(new Customer("Chloe", "O'Brian"));
                    repository.save(new Customer("Kim", "Bauer"));
                    repository.save(new Customer("David", "Palmer"));
                    repository.save(new Customer("Michelle", "Dessler"));

                    // fetch all customers
                    log.info("Customers found with findAll():");
                    log.info("-------------------------------");
                    for (Customer customer : repository.findAll())
                    log.info(customer.toString());

                    log.info("");

                    // fetch an individual customer by ID
                    Customer customer = repository.findOne(1L);
                    log.info("Customer found with findOne(1L):");
                    log.info("--------------------------------");
                    log.info(customer.toString());
                    log.info("");

                    // fetch customers by last name
                    log.info("Customer found with findByLastNameStartsWithIgnoreCase('Bauer'):");
                    log.info("--------------------------------------------");
                    for (Customer bauer : repository
                    .findByLastNameStartsWithIgnoreCase("Bauer"))
                    log.info(bauer.toString());

                    log.info("");




                    Option 2: Initialize with schema and data scripts



                    Prerequisites: in application.properties you have to mention this:



                    spring.jpa.hibernate.ddl-auto=none (otherwise scripts will be ignored by hibernate, and it will scan project for @Entity and/or @Table annotated classes)



                    Then, in your MyApplication class paste this:



                    @Bean(name = "dataSource")
                    public DriverManagerDataSource dataSource()
                    DriverManagerDataSource dataSource = new DriverManagerDataSource();
                    dataSource.setDriverClassName("org.h2.Driver");
                    dataSource.setUrl("jdbc:h2:~/myDB;MV_STORE=false");
                    dataSource.setUsername("sa");
                    dataSource.setPassword("");

                    // schema init
                    Resource initSchema = new ClassPathResource("scripts/schema-h2.sql");
                    Resource initData = new ClassPathResource("scripts/data-h2.sql");
                    DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema, initData);
                    DatabasePopulatorUtils.execute(databasePopulator, dataSource);

                    return dataSource;



                    Where scripts folder is located under resources folder (IntelliJ Idea)



                    Hope it helps someone






                    share|improve this answer



























                      21












                      21








                      21







                      As suggestion try this:



                      @Bean
                      public CommandLineRunner loadData(CustomerRepository repository)
                      return (args) ->
                      // save a couple of customers
                      repository.save(new Customer("Jack", "Bauer"));
                      repository.save(new Customer("Chloe", "O'Brian"));
                      repository.save(new Customer("Kim", "Bauer"));
                      repository.save(new Customer("David", "Palmer"));
                      repository.save(new Customer("Michelle", "Dessler"));

                      // fetch all customers
                      log.info("Customers found with findAll():");
                      log.info("-------------------------------");
                      for (Customer customer : repository.findAll())
                      log.info(customer.toString());

                      log.info("");

                      // fetch an individual customer by ID
                      Customer customer = repository.findOne(1L);
                      log.info("Customer found with findOne(1L):");
                      log.info("--------------------------------");
                      log.info(customer.toString());
                      log.info("");

                      // fetch customers by last name
                      log.info("Customer found with findByLastNameStartsWithIgnoreCase('Bauer'):");
                      log.info("--------------------------------------------");
                      for (Customer bauer : repository
                      .findByLastNameStartsWithIgnoreCase("Bauer"))
                      log.info(bauer.toString());

                      log.info("");




                      Option 2: Initialize with schema and data scripts



                      Prerequisites: in application.properties you have to mention this:



                      spring.jpa.hibernate.ddl-auto=none (otherwise scripts will be ignored by hibernate, and it will scan project for @Entity and/or @Table annotated classes)



                      Then, in your MyApplication class paste this:



                      @Bean(name = "dataSource")
                      public DriverManagerDataSource dataSource()
                      DriverManagerDataSource dataSource = new DriverManagerDataSource();
                      dataSource.setDriverClassName("org.h2.Driver");
                      dataSource.setUrl("jdbc:h2:~/myDB;MV_STORE=false");
                      dataSource.setUsername("sa");
                      dataSource.setPassword("");

                      // schema init
                      Resource initSchema = new ClassPathResource("scripts/schema-h2.sql");
                      Resource initData = new ClassPathResource("scripts/data-h2.sql");
                      DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema, initData);
                      DatabasePopulatorUtils.execute(databasePopulator, dataSource);

                      return dataSource;



                      Where scripts folder is located under resources folder (IntelliJ Idea)



                      Hope it helps someone






                      share|improve this answer















                      As suggestion try this:



                      @Bean
                      public CommandLineRunner loadData(CustomerRepository repository)
                      return (args) ->
                      // save a couple of customers
                      repository.save(new Customer("Jack", "Bauer"));
                      repository.save(new Customer("Chloe", "O'Brian"));
                      repository.save(new Customer("Kim", "Bauer"));
                      repository.save(new Customer("David", "Palmer"));
                      repository.save(new Customer("Michelle", "Dessler"));

                      // fetch all customers
                      log.info("Customers found with findAll():");
                      log.info("-------------------------------");
                      for (Customer customer : repository.findAll())
                      log.info(customer.toString());

                      log.info("");

                      // fetch an individual customer by ID
                      Customer customer = repository.findOne(1L);
                      log.info("Customer found with findOne(1L):");
                      log.info("--------------------------------");
                      log.info(customer.toString());
                      log.info("");

                      // fetch customers by last name
                      log.info("Customer found with findByLastNameStartsWithIgnoreCase('Bauer'):");
                      log.info("--------------------------------------------");
                      for (Customer bauer : repository
                      .findByLastNameStartsWithIgnoreCase("Bauer"))
                      log.info(bauer.toString());

                      log.info("");




                      Option 2: Initialize with schema and data scripts



                      Prerequisites: in application.properties you have to mention this:



                      spring.jpa.hibernate.ddl-auto=none (otherwise scripts will be ignored by hibernate, and it will scan project for @Entity and/or @Table annotated classes)



                      Then, in your MyApplication class paste this:



                      @Bean(name = "dataSource")
                      public DriverManagerDataSource dataSource()
                      DriverManagerDataSource dataSource = new DriverManagerDataSource();
                      dataSource.setDriverClassName("org.h2.Driver");
                      dataSource.setUrl("jdbc:h2:~/myDB;MV_STORE=false");
                      dataSource.setUsername("sa");
                      dataSource.setPassword("");

                      // schema init
                      Resource initSchema = new ClassPathResource("scripts/schema-h2.sql");
                      Resource initData = new ClassPathResource("scripts/data-h2.sql");
                      DatabasePopulator databasePopulator = new ResourceDatabasePopulator(initSchema, initData);
                      DatabasePopulatorUtils.execute(databasePopulator, dataSource);

                      return dataSource;



                      Where scripts folder is located under resources folder (IntelliJ Idea)



                      Hope it helps someone







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Jul 10 '17 at 11:14

























                      answered Jan 13 '17 at 22:57









                      RebornReborn

                      1,12231937




                      1,12231937





















                          10














                          You can add a spring.datasource.data property to application.properties listing the sql files you want to run. Like this:



                          spring.datasource.data=classpath:accounts.sql, classpath:books.sql, classpath:reviews.sql


                          The sql insert statements in each of these files will then be run, allowing you to keep things tidy






                          share|improve this answer























                          • pretty clean and simple solution. thanks

                            – mustache1up
                            Jun 11 '18 at 0:38















                          10














                          You can add a spring.datasource.data property to application.properties listing the sql files you want to run. Like this:



                          spring.datasource.data=classpath:accounts.sql, classpath:books.sql, classpath:reviews.sql


                          The sql insert statements in each of these files will then be run, allowing you to keep things tidy






                          share|improve this answer























                          • pretty clean and simple solution. thanks

                            – mustache1up
                            Jun 11 '18 at 0:38













                          10












                          10








                          10







                          You can add a spring.datasource.data property to application.properties listing the sql files you want to run. Like this:



                          spring.datasource.data=classpath:accounts.sql, classpath:books.sql, classpath:reviews.sql


                          The sql insert statements in each of these files will then be run, allowing you to keep things tidy






                          share|improve this answer













                          You can add a spring.datasource.data property to application.properties listing the sql files you want to run. Like this:



                          spring.datasource.data=classpath:accounts.sql, classpath:books.sql, classpath:reviews.sql


                          The sql insert statements in each of these files will then be run, allowing you to keep things tidy







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 13 '18 at 13:50









                          robjwilkinsrobjwilkins

                          2,51022439




                          2,51022439












                          • pretty clean and simple solution. thanks

                            – mustache1up
                            Jun 11 '18 at 0:38

















                          • pretty clean and simple solution. thanks

                            – mustache1up
                            Jun 11 '18 at 0:38
















                          pretty clean and simple solution. thanks

                          – mustache1up
                          Jun 11 '18 at 0:38





                          pretty clean and simple solution. thanks

                          – mustache1up
                          Jun 11 '18 at 0:38











                          8














                          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"));
                          ;







                          share|improve this answer























                          • I guess this is the easiest way so far...

                            – bitsnaps
                            Nov 25 '18 at 15:52















                          8














                          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"));
                          ;







                          share|improve this answer























                          • I guess this is the easiest way so far...

                            – bitsnaps
                            Nov 25 '18 at 15:52













                          8












                          8








                          8







                          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"));
                          ;







                          share|improve this answer













                          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"));
                          ;








                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Aug 27 '17 at 19:45









                          GrauzoneGrauzone

                          11017




                          11017












                          • I guess this is the easiest way so far...

                            – bitsnaps
                            Nov 25 '18 at 15:52

















                          • I guess this is the easiest way so far...

                            – bitsnaps
                            Nov 25 '18 at 15:52
















                          I guess this is the easiest way so far...

                          – bitsnaps
                          Nov 25 '18 at 15:52





                          I guess this is the easiest way so far...

                          – bitsnaps
                          Nov 25 '18 at 15:52











                          7














                          Spring Boot allows you to use a simple script to initialize your database, using Spring Batch.



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



                          See also:



                          • Spring Boot Database initialization





                          share|improve this answer


















                          • 4





                            suggesting spring batch here seems overkill.

                            – Nick
                            Jun 22 '18 at 16:10











                          • @Nick, the OP does not mention the amount of data.. Anyway the answer is not all about spring batch.

                            – Xtreme Biker
                            Jun 22 '18 at 17:25















                          7














                          Spring Boot allows you to use a simple script to initialize your database, using Spring Batch.



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



                          See also:



                          • Spring Boot Database initialization





                          share|improve this answer


















                          • 4





                            suggesting spring batch here seems overkill.

                            – Nick
                            Jun 22 '18 at 16:10











                          • @Nick, the OP does not mention the amount of data.. Anyway the answer is not all about spring batch.

                            – Xtreme Biker
                            Jun 22 '18 at 17:25













                          7












                          7








                          7







                          Spring Boot allows you to use a simple script to initialize your database, using Spring Batch.



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



                          See also:



                          • Spring Boot Database initialization





                          share|improve this answer













                          Spring Boot allows you to use a simple script to initialize your database, using Spring Batch.



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



                          See also:



                          • Spring Boot Database initialization






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Jun 26 '16 at 16:38









                          Xtreme BikerXtreme Biker

                          19.6k1093163




                          19.6k1093163







                          • 4





                            suggesting spring batch here seems overkill.

                            – Nick
                            Jun 22 '18 at 16:10











                          • @Nick, the OP does not mention the amount of data.. Anyway the answer is not all about spring batch.

                            – Xtreme Biker
                            Jun 22 '18 at 17:25












                          • 4





                            suggesting spring batch here seems overkill.

                            – Nick
                            Jun 22 '18 at 16:10











                          • @Nick, the OP does not mention the amount of data.. Anyway the answer is not all about spring batch.

                            – Xtreme Biker
                            Jun 22 '18 at 17:25







                          4




                          4





                          suggesting spring batch here seems overkill.

                          – Nick
                          Jun 22 '18 at 16:10





                          suggesting spring batch here seems overkill.

                          – Nick
                          Jun 22 '18 at 16:10













                          @Nick, the OP does not mention the amount of data.. Anyway the answer is not all about spring batch.

                          – Xtreme Biker
                          Jun 22 '18 at 17:25





                          @Nick, the OP does not mention the amount of data.. Anyway the answer is not all about spring batch.

                          – Xtreme Biker
                          Jun 22 '18 at 17:25











                          5














                          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:



                          http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/






                          share|improve this answer























                          • This does not work if you are using service, and if service in autowiring repository

                            – silentsudo
                            Aug 2 '18 at 9:47















                          5














                          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:



                          http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/






                          share|improve this answer























                          • This does not work if you are using service, and if service in autowiring repository

                            – silentsudo
                            Aug 2 '18 at 9:47













                          5












                          5








                          5







                          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:



                          http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/






                          share|improve this answer













                          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:



                          http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 28 '18 at 22:57









                          adkladkl

                          175213




                          175213












                          • This does not work if you are using service, and if service in autowiring repository

                            – silentsudo
                            Aug 2 '18 at 9:47

















                          • This does not work if you are using service, and if service in autowiring repository

                            – silentsudo
                            Aug 2 '18 at 9:47
















                          This does not work if you are using service, and if service in autowiring repository

                          – silentsudo
                          Aug 2 '18 at 9:47





                          This does not work if you are using service, and if service in autowiring repository

                          – silentsudo
                          Aug 2 '18 at 9:47











                          5














                          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



                          https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html






                          share|improve this answer



























                            5














                            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



                            https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html






                            share|improve this answer

























                              5












                              5








                              5







                              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



                              https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html






                              share|improve this answer













                              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



                              https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 6 '18 at 20:30









                              IsmailIsmail

                              26746




                              26746





















                                  2














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






                                  share|improve this answer



























                                    2














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






                                    share|improve this answer

























                                      2












                                      2








                                      2







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






                                      share|improve this answer













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







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Jan 13 '17 at 10:28









                                      Francesco PapagnoFrancesco Papagno

                                      442624




                                      442624





















                                          1














                                          If someone are struggling in make this to work even following the accepted answer, 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:





                                          share|improve this answer



























                                            1














                                            If someone are struggling in make this to work even following the accepted answer, 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:





                                            share|improve this answer

























                                              1












                                              1








                                              1







                                              If someone are struggling in make this to work even following the accepted answer, 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:





                                              share|improve this answer













                                              If someone are struggling in make this to work even following the accepted answer, 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:






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Sep 5 '18 at 16:53









                                              DherikDherik

                                              6,30144679




                                              6,30144679





















                                                  1














                                                  I solved similar problem this way:



                                                  @Component
                                                  public class DataLoader

                                                  @Autowired
                                                  private UserRepository userRepository;

                                                  //method invoked during the startup
                                                  @PostConstruct
                                                  public void loadData()
                                                  userRepository.save(new User("user"));


                                                  //method invoked during the shutdown
                                                  @PreDestroy
                                                  public void removeData()
                                                  userRepository.deleteAll();







                                                  share|improve this answer



























                                                    1














                                                    I solved similar problem this way:



                                                    @Component
                                                    public class DataLoader

                                                    @Autowired
                                                    private UserRepository userRepository;

                                                    //method invoked during the startup
                                                    @PostConstruct
                                                    public void loadData()
                                                    userRepository.save(new User("user"));


                                                    //method invoked during the shutdown
                                                    @PreDestroy
                                                    public void removeData()
                                                    userRepository.deleteAll();







                                                    share|improve this answer

























                                                      1












                                                      1








                                                      1







                                                      I solved similar problem this way:



                                                      @Component
                                                      public class DataLoader

                                                      @Autowired
                                                      private UserRepository userRepository;

                                                      //method invoked during the startup
                                                      @PostConstruct
                                                      public void loadData()
                                                      userRepository.save(new User("user"));


                                                      //method invoked during the shutdown
                                                      @PreDestroy
                                                      public void removeData()
                                                      userRepository.deleteAll();







                                                      share|improve this answer













                                                      I solved similar problem this way:



                                                      @Component
                                                      public class DataLoader

                                                      @Autowired
                                                      private UserRepository userRepository;

                                                      //method invoked during the startup
                                                      @PostConstruct
                                                      public void loadData()
                                                      userRepository.save(new User("user"));


                                                      //method invoked during the shutdown
                                                      @PreDestroy
                                                      public void removeData()
                                                      userRepository.deleteAll();








                                                      share|improve this answer












                                                      share|improve this answer



                                                      share|improve this answer










                                                      answered Nov 15 '18 at 8:00









                                                      A-BagA-Bag

                                                      112




                                                      112





















                                                          1














                                                          you can register and event listener to achieve that like below:



                                                          @EventListener
                                                          public void seed(ContextRefreshedEvent event)
                                                          userRepository.save(new User("lala", "lala", "lala"));



                                                          When the ContextRefreshEvent is fired, we get access to all autowired beans in the application — including models and repositories.






                                                          share|improve this answer





























                                                            1














                                                            you can register and event listener to achieve that like below:



                                                            @EventListener
                                                            public void seed(ContextRefreshedEvent event)
                                                            userRepository.save(new User("lala", "lala", "lala"));



                                                            When the ContextRefreshEvent is fired, we get access to all autowired beans in the application — including models and repositories.






                                                            share|improve this answer



























                                                              1












                                                              1








                                                              1







                                                              you can register and event listener to achieve that like below:



                                                              @EventListener
                                                              public void seed(ContextRefreshedEvent event)
                                                              userRepository.save(new User("lala", "lala", "lala"));



                                                              When the ContextRefreshEvent is fired, we get access to all autowired beans in the application — including models and repositories.






                                                              share|improve this answer















                                                              you can register and event listener to achieve that like below:



                                                              @EventListener
                                                              public void seed(ContextRefreshedEvent event)
                                                              userRepository.save(new User("lala", "lala", "lala"));



                                                              When the ContextRefreshEvent is fired, we get access to all autowired beans in the application — including models and repositories.







                                                              share|improve this answer














                                                              share|improve this answer



                                                              share|improve this answer








                                                              edited Feb 3 at 19:13









                                                              Chandra Sekhar

                                                              13.2k96082




                                                              13.2k96082










                                                              answered May 19 '18 at 13:14









                                                              Ahmed AhmedAhmed Ahmed

                                                              415512




                                                              415512





















                                                                  0














                                                                  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)));
                                                                  ;






                                                                  share|improve this answer



























                                                                    0














                                                                    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)));
                                                                    ;






                                                                    share|improve this answer

























                                                                      0












                                                                      0








                                                                      0







                                                                      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)));
                                                                      ;






                                                                      share|improve this answer













                                                                      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)));
                                                                      ;







                                                                      share|improve this answer












                                                                      share|improve this answer



                                                                      share|improve this answer










                                                                      answered Apr 20 '18 at 9:34









                                                                      Udara S.S LiyanageUdara S.S Liyanage

                                                                      2,01082229




                                                                      2,01082229





















                                                                          0














                                                                          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()));







                                                                          share|improve this answer





























                                                                            0














                                                                            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()));







                                                                            share|improve this answer



























                                                                              0












                                                                              0








                                                                              0







                                                                              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()));







                                                                              share|improve this answer















                                                                              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()));








                                                                              share|improve this answer














                                                                              share|improve this answer



                                                                              share|improve this answer








                                                                              edited Aug 10 '18 at 13:14

























                                                                              answered Aug 10 '18 at 13:05









                                                                              GKislinGKislin

                                                                              8,096347105




                                                                              8,096347105















                                                                                  protected by cassiomolin Mar 3 at 19:46



                                                                                  Thank you for your interest in this question.
                                                                                  Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                  Would you like to answer one of these unanswered questions instead?



                                                                                  Popular posts from this blog

                                                                                  Kleinkühnau

                                                                                  Makov (Slowakei)

                                                                                  Deutsches Schauspielhaus