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);}
我們看下測試方法怎么實(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. Android自定義控件實(shí)現(xiàn)方向盤效果2. XHTML 1.0:標(biāo)記新的開端3. 基于javaweb+jsp實(shí)現(xiàn)企業(yè)財(cái)務(wù)記賬管理系統(tǒng)4. Java 生成帶Logo和文字的二維碼5. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?6. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案7. xml中的空格之完全解說8. springcloud alibaba nacos linux配置的詳細(xì)教程9. Javaweb工程運(yùn)行報(bào)錯(cuò)HTTP Status 404解決辦法10. asp讀取xml文件和記數(shù)
