Creating tables and importing data from .sql files in Spring boot

故事扮演 提交于 2021-02-10 06:42:08

问题


Current apporach:

application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/db_name
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto=update

spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.connection.zeroDateTimeBehavior=convertToNull
spring.datasource.initialization-mode=always
spring.jpa.properties.hibernate.hbm2ddl.import_files=<name>.sql 
spring.datasource.platform=mysql

Not sure what am I missing, and why in this configuration, the .sql files are not executed?


回答1:


UPDATE

We can use

spring.datasource.schema= # Schema (DDL) script resource references.
spring.datasource.data= # Data (DML) script resource references.
  • No need to change the SQL filenames
  • Can Keep schema generation and insertion in the same file
  • Can specify multiple files

    spring.datasource.schema = classpath:/abc.sql,classpath:/abc2.sql

NOTE:

  • For schema generation and insertion in the same file do not use spring.datasource.data, we have to use spring.datasource.schema
  • Keep all files in src/main/resources
  • set spring.jpa.hibernate.ddl-auto=none

Initial Answer

Spring boot already configures Hibernate to create your schema based on your entities. To create it using SQL (in src/main/resources) files set

spring.jpa.hibernate.ddl-auto=none

Create schema.sql (to create the table) and data.sql (to insert the records) in src/main/resources

schema.sql

CREATE TABLE country (
    id   INTEGER      NOT NULL AUTO_INCREMENT,
    name VARCHAR(128) NOT NULL,
    PRIMARY KEY (id)
);

data.sql

INSERT INTO country (name) VALUES ('India');
INSERT INTO country (name) VALUES ('Brazil');
INSERT INTO country (name) VALUES ('USA');
INSERT INTO country (name) VALUES ('Italy');

application.properties

spring.datasource.platform=mysql
spring.datasource.initialization-mode=always
spring.datasource.url=jdbc:mysql://localhost:3306/db_name?createDatabaseIfNotExist=true
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto=none
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect



来源:https://stackoverflow.com/questions/57527702/creating-tables-and-importing-data-from-sql-files-in-spring-boot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!