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);}
我們看下測試方法怎么實現(xiàn):
@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()); }
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 @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.
所以這里我們加上了@Transactional 注解。
CompletableFuture
使用java 8 的CompletableFuture, 我們還可以異步執(zhí)行查詢語句:
@Async CompletableFuture<Book> findOneByAuthor(String author);
我們這樣使用這個方法:
@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()); }
本文的例子可以參考https://github.com/ddean2009/learn-springboot2/tree/master/springboot-jpa
到此這篇關(guān)于Spring Boot JPA中java 8 的應(yīng)用實例的文章就介紹到這了,更多相關(guān)java8中Spring Boot JPA使用內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. XML入門的常見問題(三)2. XML基本概念XPath、XSLT與XQuery函數(shù)介紹3. WML的簡單例子及編輯、測試方法第1/2頁4. el-input無法輸入的問題和表單驗證失敗問題解決5. 關(guān)于html嵌入xml數(shù)據(jù)島如何穿過樹形結(jié)構(gòu)關(guān)系的問題6. CSS3實例分享之多重背景的實現(xiàn)(Multiple backgrounds)7. 不要在HTML中濫用div8. vue實現(xiàn)復(fù)制文字復(fù)制圖片實例詳解9. XML入門的常見問題(四)10. 前端html+css實現(xiàn)動態(tài)生日快樂代碼
