@Test
public void testFindOneByTitle(){
Book book = new Book();
book.setTitle("title");
book.setAuthor(randomAlphabetic(15));
bookRepository.save(book);
log.info(bookRepository.findOneByTitle("title").orElse(new Book()).toString());
}
@Test
@Transactional
public void testFindAll(){
Book book = new Book();
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.
@Test
public void testByAuthor() throws ExecutionException, InterruptedException {
Book book = new Book();
book.setTitle("titleA");
book.setAuthor("author");
bookRepository.save(book);
log.info(bookRepository.findOneByAuthor("author").get().toString());
}