Initialize Database(Execute schema.sql and data.sql) using JDBC in spring boot
Note: Follow these steps
1. create sample project pom.xml (edit it based on your version)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
[To see links please register here]
;
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.1</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>Init_Sql_Script</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Init_Sql_Script</name>
<description>Initialize a Database Using Basic SQL Scripts</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2. application properties && create new db name like employee in ur DB
# connection code for spring boot to your DB
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/employee
spring.datasource.username=Hari
spring.datasource.password=1998
spring.jpa.hibernate.ddl-auto=none
#--- control the sql db initialization (from schema.sql and data.sql)---
spring. SQL.init.mode=always
#---if any error it skips the script and executes the next script----
#spring.sql.init.continue-on-error=true
3. create two SQL files (schema.sql-create table query and data.sql-insert query) in the resource folder
4. run the application after that check db thats all Try it.
It is working for me I Hope its working for u also