I am developing an application using Spring MVC (version 3.1), Hibernate (Version 3.5) and MySQL. In this application, I am creating a database schema each time when the application runs. I want to insert some default data into a few tables using import.sql script file. For this I have created import.sql script in the root and using the following statements in hibernate. cfg. xml file.
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.hbm2ddl.import_files">import.sql</property>
<property name="connection.autocommit">true</property>
But I am not getting success to insert default data into tables.
Please guide me.
Spring Boot can automatically create the schema (DDL scripts) of your DataSource and initialize it (DML scripts). It loads SQL from the standard root classpath locations: schema. sql and data. sql , respectively.
sql is executed to populate the database. Also, script-based initialization is performed by default only for embedded databases, to always initialize a database using scripts, we'll have to use: spring.sql.init.mode=always. Please refer to official Spring documentation on initializing databases using SQL scripts.
So coming to the loading of initial data while startup, we need to separate our DDL (create) and DML (inserts/updates) scripts in two different files that are schema. sql and data. sql respectively.
Spring must know where to find your file.
If you are using maven, there are several way of doing so.
you can use classpath:/import.sql and put your file in src/test/resources or src/main/resources, depending if you need this for test only or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With