繁体   English   中英

使用Spring Data JPA提交事务

[英]Commit Transaction with Spring Data JPA

我从此处下载了一个Spring Data JPA示例,该示例使用JPA访问数据,它可以正常工作。

@SpringBootApplication
public class Application {

  private static final Logger log = LoggerFactory.getLogger(Application.class);

  public static void main(String[] args) {
    SpringApplication.run(Application.class);
  }

  @Bean
  public CommandLineRunner demo(CustomerRepository repository) {
    return (args) -> {
      // 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
      log.info("Customers found with findAll():");
      log.info("-------------------------------");
      for (Customer customer : repository.findAll()) {
        log.info(customer.toString());
      }
      log.info("");

      // fetch an individual customer by ID
      Customer customer = repository.findOne(1L);
      log.info("Customer found with findOne(1L):");
      log.info("--------------------------------");
      log.info(customer.toString());
      log.info("");

      // fetch customers by last name
      log.info("Customer found with findByLastName('Bauer'):");
      log.info("--------------------------------------------");
      for (Customer bauer : repository.findByLastName("Bauer")) {
        log.info(bauer.toString());
      }
      log.info("");
    };
  }

}

然后,我尝试从内存数据库更改为真实数据库。 为此,我在当前目录中添加了一行一行application.properties文件:

spring.datasource.url=jdbc:h2:C:/users/semaphor/H2Database;DB_CLOSE_ON_EXIT=FALSE

现在,当我运行该应用程序时,可以看到在预期目录中创建了数据库文件。

现在,我想看看客户存储在数据库中,并且在我重新启动应用程序时仍然在那里。 因此,我删除了一些行,这些行最初是将客户保存在数据库中的,但后来他们没有使用findAll()监听。

我想这个事务没有提交,但是我不知道该怎么做。 解决方案不是简单地将批注@EnableTranscationManagement添加到Application类,并将@Transactionaldemo()方法。

我必须添加什么来提交事务(如果这确实是问题)?

请参阅问题下方的M. Deinum的评论。

新增中

spring.jpa.hibernate.ddl-auto=update

application.properties是解决办法。

暂无
暂无

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

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