Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert default data into table using import.sql file in Hibernate, MySQL Application

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.

like image 480
Manoj Agarwal Avatar asked Jan 29 '13 06:01

Manoj Agarwal


People also ask

Where do I put SQL data in spring boot?

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.

What is SQL init mode always?

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.

How do I add data to startup in spring boot?

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.


1 Answers

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.

like image 127
Samuel EUSTACHI Avatar answered Oct 19 '22 15:10

Samuel EUSTACHI