javascript
Spring Boot JPA中java 8 的应用
文章目錄
- Optional
- Stream API
- CompletableFuture
Spring Boot JPA中java 8 的應(yīng)用
上篇文章中我們講到了如何在Spring Boot中使用JPA。 本文我們將會講解如何在Spring Boot JPA中使用java 8 中的新特習(xí)慣如:Optional, Stream API 和 CompletableFuture的使用。
Optional
我們從數(shù)據(jù)庫中獲取的數(shù)據(jù)有可能是空的,對于這樣的情況Java 8 提供了Optional類,用來防止出現(xiàn)空值的情況。我們看下怎么在Repository 中定義一個Optional的方法:
public interface BookRepository extends JpaRepository<Book, Long> {Optional<Book> findOneByTitle(String title); }我們看下測試方法怎么實(shí)現(xiàn):
@Testpublic 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());}Stream API
為什么會有Stream API呢? 我們舉個例子,如果我們想要獲取數(shù)據(jù)庫中所有的Book, 我們可以定義如下的方法:
public interface BookRepository extends JpaRepository<Book, Long> {List<Book> findAll();Stream<Book> findAllByTitle(String title);}上面的findAll方法會獲取所有的Book,但是當(dāng)數(shù)據(jù)庫里面的數(shù)據(jù)太多的話,就會消耗過多的系統(tǒng)內(nèi)存,甚至有可能導(dǎo)致程序崩潰。
為了解決這個問題,我們可以定義如下的方法:
Stream<Book> findAllByTitle(String title);當(dāng)你使用Stream的時候,記得需要close它。 我們可以使用java 8 中的try語句來自動關(guān)閉:
@Test@Transactionalpublic 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中使用。否則會報(bào)如下錯誤:
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.所以這里我們加上了@Transactional 注解。
CompletableFuture
使用java 8 的CompletableFuture, 我們還可以異步執(zhí)行查詢語句:
@AsyncCompletableFuture<Book> findOneByAuthor(String author);我們這樣使用這個方法:
@Testpublic 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());}本文的例子可以參考https://github.com/ddean2009/learn-springboot2/tree/master/springboot-jpa
更多精彩內(nèi)容且看:
- 區(qū)塊鏈從入門到放棄系列教程-涵蓋密碼學(xué),超級賬本,以太坊,Libra,比特幣等持續(xù)更新
- Spring Boot 2.X系列教程:七天從無到有掌握Spring Boot-持續(xù)更新
- Spring 5.X系列教程:滿足你對Spring5的一切想象-持續(xù)更新
- java程序員從小工到專家成神之路(2020版)-持續(xù)更新中,附詳細(xì)文章教程
更多教程請參考 flydean的博客
總結(jié)
以上是生活随笔為你收集整理的Spring Boot JPA中java 8 的应用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Boot 之Spring
- 下一篇: Spring Boot中Spring d