【问题标题】:Can hibernate initialize data after entity-table is created?创建实体表后休眠可以初始化数据吗?
【发布时间】:2021-09-27 14:39:18
【问题描述】:

只有在创建特定实体表之后,才能在 Spring Boot 中让休眠添加一些 data.sql。 (我不想在初始化 Spring Boot 应用程序时初始化架构和数据)

    package io.fall.model;

    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;

    @Entity
    @Table(name = "userprofile")
    public class UserProfile {
        
        @Id
        @GeneratedValue
        private int id;
        private int theme;
        private String userName;

        UserProfile(){}

        public int getTheme() {
            return theme;
        }

        public void setTheme(int theme) {
            this.theme = theme;
        }

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }
    }

我想在hibernate创建实体表userprofile之后插入这些值

INSERT INTO userprofile (id,theme,userName,summary) 
VALUES (1, 1 , 'John Doee'),
       (2, 2 , 'Jenny Doee'),
       (3, 3 , 'James Doee');

【问题讨论】:

  • Hibernate 没有这样的功能。但是你可以使用 spring 来实现,甚至你可以使用 flyway 或 liquibase 来做这些事情。

标签: java sql spring-boot hibernate spring-data-jpa


【解决方案1】:

听起来您正在寻找错误的工具。 看看 Liquibase 或 Flyway,一旦您从开发阶段转移到生产阶段,您可能想要使用它们。

但是既然你问的是 Spring Boot 和 Hibernate:你可以用 Spring Boot 来实现它。

  1. 确保userprofile.id 具有唯一约束
  2. 创建一个包含插入语句的data.sql
  3. 在您的application.properties set spring.datasource.continue-on-error=true

insert 语句将在每次启动时执行,但在第一次之后会失败。 Spring Boot 将忽略此错误,因为您在应用程序属性中如此告知。

这假设插入的值保留在数据库中并且不会被删除。

这种方法的缺点是忽略错误可能会导致您错过插入或其他 SQL 语句的其他问题。

【讨论】:

    【解决方案2】:

    如果您使用休眠schema generation,那么您可以尝试使用importing script files 来达到您的目的。

    spring.jpa.properties.hibernate.hbm2ddl.import_files=data.sql
    

    模式自动生成后,Hibernate 会执行脚本文件。

    或者您也可以使用javax.persistence.schema-generation.create-script-source 属性(请参阅文档的this section)用于相同目的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-11
      • 2017-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      相关资源
      最近更新 更多