繁体   English   中英

不存在Spring Boot JPA和H2记录

[英]Spring Boot JPA & H2 Records Not Persisted

作为基准,我正在使用Spring Boot演示Accessing Data JPA

我的目标是能够使用h2控制台查看持久化的实体。 我可以使用Maven运行该应用程序,但是当我随后与h2控制台连接时,数据库为空。

如果我设置spring.jpa.hibernate.ddl_auto=none那么该应用程序将无法运行,因此我知道此值是从src/main/resources ,但是我将其设置为createupdate ,数据库仍然是在mvn spring-boot:run运行结束时为空。

在Spring和Hibernate的过去版本中,我已经设置了auto_dll = create,并且Hibernate已经创建了数据库(如果尚不存在)。 这不再有效吗?

这是更新后的示例应用程序的样子,减去导入声明:

@Configuration
@EnableAutoConfiguration
public class Application {

    @Bean
    public DataSource dataSource() {
        HikariConfig config = new HikariConfig();
        config.setDriverClassName("org.h2.Driver");
        config.setJdbcUrl("jdbc:h2:file:~/db1");
        config.setUsername("sa");
        config.setPassword("");
        return new HikariDataSource(config);
    }

public static void main(String[] args) {

    ConfigurableApplicationContext context = SpringApplication.run(Application.class);
    CustomerRepository repository = context.getBean(CustomerRepository.class);

    // save a couple of customers
    repository.save(new Customer("Jack", "Bauer"));
    repository.save(new Customer("Chloe", "O'Brian"));
    repository.save(new Customer("Kim", "Bauer"));
    repository.save(new Customer("David", "Palmer"));
    repository.save(new Customer("Michelle", "Dessler"));

    // fetch all customers
    Iterable<Customer> customers = repository.findAll();
    System.out.println("Customers found with findAll():");
    System.out.println("-------------------------------");
    for (Customer customer : customers) {
        System.out.println(customer);
    }
    System.out.println();

    // fetch an individual customer by ID
    Customer customer = repository.findOne(1L);
    System.out.println("Customer found with findOne(1L):");
    System.out.println("--------------------------------");
    System.out.println(customer);
    System.out.println();

    // fetch customers by last name
    List<Customer> bauers = repository.findByLastName("Bauer");
    System.out.println("Customer found with findByLastName('Bauer'):");
    System.out.println("--------------------------------------------");
        for (Customer bauer : bauers) {
            System.out.println(bauer);
        }

        context.close();
    }

}

TIA-Ole

默认情况下,JPA数据库配置设置为在开始时创建表,然后在末尾创建表。 可以通过application.properties文件中的以下条目来更改此设置:

spring.jpa.hibernate.ddl-auto=update

请参阅此处的参考。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM