JPA& amp; Spring Boot H2:创建了DB文件,但没有任何内容保留

时间:2014-05-09 15:40:12

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

我在修改此基本Spring JPA example时遇到问题,无法继续更改。

我修改了以下示例:

1)在Application类中,我添加了

@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,但没有Customer表。如果我确实更改了Application类并添加了

@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创建的SimpleJpaRepository中的LocalContainerEntityManagerFactoryBean似乎已正确配置,因为它包含

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

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

1 个答案:

答案 0 :(得分:1)

尝试在方法上添加@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"));
    }

}