使用Spring Data JPA提交事务

时间:2015-11-24 10:27:24

标签: java spring hibernate jpa

我从这里Accessing Data with JPA下载了一个Spring Data 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类,@Transactional添加到demo()方法不是解决方案。

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

1 个答案:

答案 0 :(得分:0)

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

添加

application.properties

drop_up_to_and_including = lambda l,f : list(itertools.dropwhile(lambda y: not(f(y)),l))[1:] 是解决方案。

相关问题