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;
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
add a comment |
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
3
That will work, or simply adddata.sqland/orschema.sqlto 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
add a comment |
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
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
spring spring-boot spring-data
asked Jun 26 '16 at 16:20
LithicasLithicas
83731420
83731420
3
That will work, or simply adddata.sqland/orschema.sqlto 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
add a comment |
3
That will work, or simply adddata.sqland/orschema.sqlto 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
add a comment |
14 Answers
14
active
oldest
votes
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
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, theschema.sql/data.sqlfiles will be executed whenspring.datasource.initializeistrue(which is the default).spring.jpa.hibernate.ddl-autocan 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 theschema.sql, you need to disablespring.jpa.hibernate.ddl-autootherwise both will try to create your table.
– g00glen00b
Oct 11 '17 at 8:03
5
If you want to use thedata-h2.sqlfilename for your initial data, you should setspring.datasource.platform=h2in 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 anorg.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
|
show 8 more comments
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"));
public void run(); method needs to be public
– eosimosu
Jun 26 '17 at 14:02
add a comment |
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
add a comment |
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
pretty clean and simple solution. thanks
– mustache1up
Jun 11 '18 at 0:38
add a comment |
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"));
;
I guess this is the easiest way so far...
– bitsnaps
Nov 25 '18 at 15:52
add a comment |
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
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
add a comment |
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/
This does not work if you are using service, and if service in autowiring repository
– silentsudo
Aug 2 '18 at 9:47
add a comment |
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
add a comment |
You can simply create a import.sql file in src/main/resources and Hibernate will execute it when the schema is created.
add a comment |
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:
add a comment |
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();
add a comment |
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.
add a comment |
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)));
;
add a comment |
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()));
add a comment |
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
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
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, theschema.sql/data.sqlfiles will be executed whenspring.datasource.initializeistrue(which is the default).spring.jpa.hibernate.ddl-autocan 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 theschema.sql, you need to disablespring.jpa.hibernate.ddl-autootherwise both will try to create your table.
– g00glen00b
Oct 11 '17 at 8:03
5
If you want to use thedata-h2.sqlfilename for your initial data, you should setspring.datasource.platform=h2in 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 anorg.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
|
show 8 more comments
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
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, theschema.sql/data.sqlfiles will be executed whenspring.datasource.initializeistrue(which is the default).spring.jpa.hibernate.ddl-autocan 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 theschema.sql, you need to disablespring.jpa.hibernate.ddl-autootherwise both will try to create your table.
– g00glen00b
Oct 11 '17 at 8:03
5
If you want to use thedata-h2.sqlfilename for your initial data, you should setspring.datasource.platform=h2in 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 anorg.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
|
show 8 more comments
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
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
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, theschema.sql/data.sqlfiles will be executed whenspring.datasource.initializeistrue(which is the default).spring.jpa.hibernate.ddl-autocan 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 theschema.sql, you need to disablespring.jpa.hibernate.ddl-autootherwise both will try to create your table.
– g00glen00b
Oct 11 '17 at 8:03
5
If you want to use thedata-h2.sqlfilename for your initial data, you should setspring.datasource.platform=h2in 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 anorg.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
|
show 8 more comments
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, theschema.sql/data.sqlfiles will be executed whenspring.datasource.initializeistrue(which is the default).spring.jpa.hibernate.ddl-autocan 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 theschema.sql, you need to disablespring.jpa.hibernate.ddl-autootherwise both will try to create your table.
– g00glen00b
Oct 11 '17 at 8:03
5
If you want to use thedata-h2.sqlfilename for your initial data, you should setspring.datasource.platform=h2in 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 anorg.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
|
show 8 more comments
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"));
public void run(); method needs to be public
– eosimosu
Jun 26 '17 at 14:02
add a comment |
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"));
public void run(); method needs to be public
– eosimosu
Jun 26 '17 at 14:02
add a comment |
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"));
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"));
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
add a comment |
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
add a comment |
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
add a comment |
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
add a comment |
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
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
edited Jul 10 '17 at 11:14
answered Jan 13 '17 at 22:57
RebornReborn
1,12231937
1,12231937
add a comment |
add a comment |
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
pretty clean and simple solution. thanks
– mustache1up
Jun 11 '18 at 0:38
add a comment |
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
pretty clean and simple solution. thanks
– mustache1up
Jun 11 '18 at 0:38
add a comment |
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
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
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
add a comment |
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
add a comment |
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"));
;
I guess this is the easiest way so far...
– bitsnaps
Nov 25 '18 at 15:52
add a comment |
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"));
;
I guess this is the easiest way so far...
– bitsnaps
Nov 25 '18 at 15:52
add a comment |
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"));
;
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"));
;
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
add a comment |
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
add a comment |
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
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
add a comment |
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
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
add a comment |
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
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
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
add a comment |
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
add a comment |
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/
This does not work if you are using service, and if service in autowiring repository
– silentsudo
Aug 2 '18 at 9:47
add a comment |
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/
This does not work if you are using service, and if service in autowiring repository
– silentsudo
Aug 2 '18 at 9:47
add a comment |
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/
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/
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
add a comment |
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
add a comment |
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
add a comment |
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
add a comment |
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
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
answered Nov 6 '18 at 20:30
IsmailIsmail
26746
26746
add a comment |
add a comment |
You can simply create a import.sql file in src/main/resources and Hibernate will execute it when the schema is created.
add a comment |
You can simply create a import.sql file in src/main/resources and Hibernate will execute it when the schema is created.
add a comment |
You can simply create a import.sql file in src/main/resources and Hibernate will execute it when the schema is created.
You can simply create a import.sql file in src/main/resources and Hibernate will execute it when the schema is created.
answered Jan 13 '17 at 10:28
Francesco PapagnoFrancesco Papagno
442624
442624
add a comment |
add a comment |
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:
add a comment |
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:
add a comment |
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:
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:
answered Sep 5 '18 at 16:53
DherikDherik
6,30144679
6,30144679
add a comment |
add a comment |
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();
add a comment |
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();
add a comment |
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();
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();
answered Nov 15 '18 at 8:00
A-BagA-Bag
112
112
add a comment |
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
edited Feb 3 at 19:13
Chandra Sekhar
13.2k96082
13.2k96082
answered May 19 '18 at 13:14
Ahmed AhmedAhmed Ahmed
415512
415512
add a comment |
add a comment |
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)));
;
add a comment |
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)));
;
add a comment |
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)));
;
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)));
;
answered Apr 20 '18 at 9:34
Udara S.S LiyanageUdara S.S Liyanage
2,01082229
2,01082229
add a comment |
add a comment |
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()));
add a comment |
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()));
add a comment |
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()));
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()));
edited Aug 10 '18 at 13:14
answered Aug 10 '18 at 13:05
GKislinGKislin
8,096347105
8,096347105
add a comment |
add a comment |
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?
3
That will work, or simply add
data.sqland/orschema.sqlto 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