我想知道在应用程序启动之前加载初始数据库数据的最佳方法是什么?我要找的是一些东西,将填补我的H2数据库与数据。

例如,我有一个域模型“User”,我可以通过访问/users访问用户,但最初在数据库中不会有任何用户,所以我必须创建它们。有没有办法自动用数据填充数据库?

目前,我有一个Bean,它由容器实例化并为我创建用户。

例子:

@Component
public class DataLoader {

    private UserRepository userRepository;

    @Autowired
    public DataLoader(UserRepository userRepository) {
        this.userRepository = userRepository;
        LoadUsers();
    }

    private void LoadUsers() {
        userRepository.save(new User("lala", "lala", "lala"));
    }
}

但我非常怀疑这是不是最好的办法。真的是这样吗?


当前回答

如果您来到这里,似乎什么都不适合您,那么您可能受到了Spring Boot 2.5及以后引入的一些更改的影响。

这里是我为postgresql使用的全部属性集。

spring:
  sql.init.mode: always   <-----------------
  datasource:
    url: jdbc:postgresql://localhost:5432/products
    username: 
    password: 
  jpa:
    defer-datasource-initialization: true  <------------------
    hibernate:
      ddl-auto: create-drop   <----------------
    database-platform: org.hibernate.dialect.PostgreSQLDialect

我还用<——标记了当前主题的相关属性,以便实现以下功能。

ORM供应商将从Java实体模型为您创建数据库模式。 创建数据库模式后,初始数据将从data.sql文件加载到数据库中

Ps:不要忘记添加文件的初始数据,数据。src/main/resources下的SQL

同样作为参考:Spring Boot 2.5发行说明

其他回答

这也是可行的。

    @Bean
    CommandLineRunner init (StudentRepo studentRepo){
        return args -> {
            // Adding two students objects
            List<String> names = Arrays.asList("udara", "sampath");
            names.forEach(name -> studentRepo.save(new Student(name)));
        };
    }

Spring Boot允许您使用一个简单的脚本来初始化数据库,使用Spring Batch。

不过,如果您想使用一些更详细的东西来管理DB版本等等,Spring Boot可以很好地与Flyway集成。

参见:

Spring Boot数据库初始化

在Spring Boot 2数据中。SQL不像spring boot 1.5那样适合我

import.sql

此外,还有一个名为import的文件。如果Hibernate从头创建模式(也就是说,如果ddl-auto属性设置为create或create-drop),则在启动时执行类路径根目录中的sql。

非常重要的一点是,如果你插入键不可复制,不要使用ddl-auto属性被设置为更新,因为每次重启都会再次插入相同的数据

欲了解更多信息,请访问spring网站

https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html

如果你想快速插入一些查询,你可以使用h2数据。还有SQL查询

应用程序。属性包括:

spring.jpa.show-sql=true
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb

#This directs the data.sql file and help it to run
spring.sql.init.data-locations=classpath:data.sql
spring.jpa.defer-datasource-initialization=true

数据。SQL文件包括:

INSERT INTO todo (id, username, description, target_date, is_done) VALUES (10001, 'lighteducation', 'Learn dance', CURRENT_DATE ,false);

INSERT INTO todo (id, username, description, target_date, is_done) VALUES (10002, 'lighteducation', 'Learn Angular14', CURRENT_DATE, false);

INSERT INTO todo (id, username, description, target_date, is_done) VALUES (10003, 'lighteducation', 'Learn Microservices', CURRENT_DATE,false);

注:数据。SQL文件应该在src/main/resources中

你的@实体包含

@Getter
@Setter
@AllArgsConstructor
@ToString
@Entity
public class Todo {
    @Id
    @GeneratedValue
    private Long id;

    private String username;
    private String description;
    private Date targetDate;
    private boolean isDone;

    protected Todo() {

    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Todo todo = (Todo) o;
        return id == todo.id;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}

基本上就是这样。它将在内存中,这意味着当您重新启动应用程序时,数据将再次与查询显示的相同。

但它很容易进行快速检查

此外,您可以通过http://localhost:8080/h2-console/访问该路径,也可以从.properties文件编辑该路径

如果您来到这里,似乎什么都不适合您,那么您可能受到了Spring Boot 2.5及以后引入的一些更改的影响。

这里是我为postgresql使用的全部属性集。

spring:
  sql.init.mode: always   <-----------------
  datasource:
    url: jdbc:postgresql://localhost:5432/products
    username: 
    password: 
  jpa:
    defer-datasource-initialization: true  <------------------
    hibernate:
      ddl-auto: create-drop   <----------------
    database-platform: org.hibernate.dialect.PostgreSQLDialect

我还用<——标记了当前主题的相关属性,以便实现以下功能。

ORM供应商将从Java实体模型为您创建数据库模式。 创建数据库模式后,初始数据将从data.sql文件加载到数据库中

Ps:不要忘记添加文件的初始数据,数据。src/main/resources下的SQL

同样作为参考:Spring Boot 2.5发行说明