@TestpublicvoidtestFindOneByTitle(){
Book book =newBook();
book.setTitle("title");
book.setAuthor(randomAlphabetic(15));
bookRepository.save(book);
log.info(bookRepository.findOneByTitle("title").orElse(newBook()).toString());}
@Test@TransactionalpublicvoidtestFindAll(){
Book book =newBook();
book.setTitle("titleAll");
book.setAuthor(randomAlphabetic(15));
bookRepository.save(book);try(Stream<Book> foundBookStream
= bookRepository.findAllByTitle("titleAll")){assertThat(foundBookStream.count(),equalTo(1l));}}
这里要注意, 使用Stream必须要在Transaction中使用。否则会报如下错误:
org.springframework.dao.InvalidDataAccessApiUsageException: You're trying to execute a streaming query method without a surrounding transaction that keeps the connection open so that the Stream can actually be consumed. Make sure the code consuming the stream uses @Transactional or any other way of declaring a (read-only) transaction.