Spring Boot JPA中java 8 的應(yīng)用實(shí)例
上篇文章中我們講到了如何在Spring Boot中使用JPA。 本文我們將會(huì)講解如何在Spring Boot JPA中使用java 8 中的新特習(xí)慣如:Optional, Stream API 和 CompletableFuture的使用。
Optional
我們從數(shù)據(jù)庫中獲取的數(shù)據(jù)有可能是空的,對(duì)于這樣的情況Java 8 提供了Optional類,用來防止出現(xiàn)空值的情況。我們看下怎么在Repository 中定義一個(gè)Optional的方法:
public interface BookRepository extends JpaRepository<Book, Long> { Optional<Book> findOneByTitle(String title);}
我們看下測(cè)試方法怎么實(shí)現(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
為什么會(huì)有Stream API呢? 我們舉個(gè)例子,如果我們想要獲取數(shù)據(jù)庫中所有的Book, 我們可以定義如下的方法:
public interface BookRepository extends JpaRepository<Book, Long> { List<Book> findAll(); Stream<Book> findAllByTitle(String title);}
上面的findAll方法會(huì)獲取所有的Book,但是當(dāng)數(shù)據(jù)庫里面的數(shù)據(jù)太多的話,就會(huì)消耗過多的系統(tǒng)內(nèi)存,甚至有可能導(dǎo)致程序崩潰。
為了解決這個(gè)問題,我們可以定義如下的方法:
Stream<Book> findAllByTitle(String title);
當(dāng)你使用Stream的時(shí)候,記得需要close它。 我們可以使用java 8 中的try語句來自動(dòng)關(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中使用。否則會(huì)報(bào)如下錯(cuò)誤:
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);
我們這樣使用這個(gè)方法:
@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)用實(shí)例的文章就介紹到這了,更多相關(guān)java8中Spring Boot JPA使用內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. python爬蟲實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊2. IntelliJ IDEA刪除類的方法步驟3. HTML 絕對(duì)路徑與相對(duì)路徑概念詳細(xì)4. python實(shí)現(xiàn)在內(nèi)存中讀寫str和二進(jìn)制數(shù)據(jù)代碼5. python實(shí)現(xiàn)PolynomialFeatures多項(xiàng)式的方法6. Spring如何使用xml創(chuàng)建bean對(duì)象7. Android Studio設(shè)置顏色拾色器工具Color Picker教程8. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法9. Java程序的編碼規(guī)范(6)10. python 利用toapi庫自動(dòng)生成api
