【问题标题】:Creating tables and importing data from .sql files in Spring boot在 Spring boot 中创建表并从 .sql 文件中导入数据
【发布时间】:2019-12-22 23:01:28
【问题描述】:

目前的方法:

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

不确定我遗漏了什么,为什么在这个配置中,.sql 文件没有被执行?

【问题讨论】:

    标签: mysql hibernate spring-boot spring-data-jpa


    【解决方案1】:

    更新

    我们可以使用

    spring.datasource.schema= # Schema (DDL) script resource references.
    spring.datasource.data= # Data (DML) script resource references.
    
    • 无需更改 SQL 文件名
    • 可以将模式生成和插入保持在同一个文件中
    • 可以指定多个文件

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

    注意:

    • 对于同一个文件中的模式生成和插入,不要使用spring.datasource.data,我们必须使用spring.datasource.schema
    • 将所有文件保存在 src/main/resources
    • 设置spring.jpa.hibernate.ddl-auto=none

    初步回答

    Spring boot 已经将 Hibernate 配置为根据您的实体创建架构。使用 SQL(在 src/main/resources 中)文件集创建它

    spring.jpa.hibernate.ddl-auto=none
    

    src/main/resources中创建schema.sql(创建表)和data.sql(插入记录)

    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
    

    【讨论】:

    • 有没有办法在不将文件重命名为 data.sql 和 schema.sql 的情况下做到这一点。事实上,我在一个文件中有数据和模式。换句话说,是否有可能让它在这样的条件下工作:与您指定的名称不同并且在一个 .sql 文件中具有混合模式和数据?
    • 你好,@Schroedinger 我已经更新了答案,如果对你有帮助,请接受并投票
    猜你喜欢
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 2012-11-04
    • 1970-01-01
    • 2011-09-19
    相关资源
    最近更新 更多