Hibernate 带JPA和JPA的弹簧靴;H2:DB文件已创建,但未保留任何内容

Hibernate 带JPA和JPA的弹簧靴;H2:DB文件已创建,但未保留任何内容,hibernate,jpa,spring-data,h2,spring-boot,Hibernate,Jpa,Spring Data,H2,Spring Boot,我在修改此基本设置以保持更改时遇到问题 我对示例进行了如下修改: 1) 在应用程序类中,我添加了 @PropertySource("classpath:application.properties") 并将数据访问代码重构为非静态: @Autowired EntityManager em; @Autowired CustomerRepository repository; @Autowired DataSource dataSource; @Autowired EntityManagerFac

我在修改此基本设置以保持更改时遇到问题

我对示例进行了如下修改:

1) 在应用程序类中,我添加了

@PropertySource("classpath:application.properties")
并将数据访问代码重构为非静态:

@Autowired EntityManager em;
@Autowired CustomerRepository repository;
@Autowired DataSource dataSource;
@Autowired EntityManagerFactory emf;
public static void main(String[] args) {
    ConfigurableApplicationContext run = SpringApplication.run(
            Application.class, args);
    Application app = run.getBean(Application.class);
    app.run();
    run.close();
}
public void run(String... args) {
    repository.save(new Customer("Jack", "Bauer"));
2) 并将application.properties放在/src/main/resources中:

spring.datasource.url: jdbc:h2:./database/bootDB;AUTO_SERVER=TRUE
spring.datasource.driverClassName: org.h2.Driver
spring.jpa.show-sql: true
现在,当我运行程序时,会创建一个bootDB,但没有客户表。如果我更改应用程序类并添加

@Bean
public EntityManagerFactory entityManagerFactory() {
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(true);

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(vendorAdapter);
    factory.setPackagesToScan("hello");
    factory.setDataSource(dataSource);
    factory.afterPropertiesSet();

    return factory.getObject();
}
一切都很好。然而,当我调试以前的版本时,为CustomerRepository创建的SimpleParepository中的LocalContainerEntityManagerFactoryBean似乎已正确配置,因为它包含

ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; defaultTransactionIsolation=-1;(...) url=jdbc:h2:./database/bootDB;AUTO_SERVER=TRUE; username=sa; (...) dataSource=null; dataSourceJNDI=null; (...)

为什么在初始设置中没有任何对象被持久化?我可以用更短(或更好)的方式修复它吗?

尝试在方法上添加@Transactional注释

另一个解决方案是创建一个实现InitializingBean的服务。例如:

@Service
public class DataPopulator implements InitializingBean  {

@Autowired
private CustomerRepository  repository;

    @Override
    @Transactional()
    public void afterPropertiesSet() throws Exception {
        repository.save(new Customer("Jack", "Bauer"));
    }

}

ps:@Stefan K。您不需要包含@PropertySource(“类路径:application.properties”)。弹簧护套将包括自动保护装置。见