Application of java 8 in Spring Boot JPA

Keywords: Java Spring Database github

Article Directory


Application of java 8 in Spring Boot JPA

In the last article we talked about how to use JPA in Spring Boot.In this article, we will explain how to use the new special habits of java 8 in Spring Boot JPA, such as Optional, Stream API, and CompletableFuture.

Optional

The data we get from the database may be empty, in which case Java 8 provides an Optional class to prevent null values.Let's see how to define an Optional method in Repository:

public interface BookRepository extends JpaRepository<Book, Long> {

    Optional<Book> findOneByTitle(String title);
}

Let's see how the test method works:

    @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

Why is there a Stream API?Let's take an example. If we want to get all the books in the database, we can define the following methods:

public interface BookRepository extends JpaRepository<Book, Long> {

    List<Book> findAll();

    Stream<Book> findAllByTitle(String title);

}

The findAll method above takes all books, but when there is too much data in the database, it consumes too much system memory and may even cause the program to crash.

To solve this problem, we can define the following methods:

Stream<Book> findAllByTitle(String title);

When you use Stream, remember to close it.We can use the try statement in java 8 to automatically close:

   @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));
        }
    }

Note here that Stream must be used in Transaction.Otherwise, the following error will be reported:

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.

So here we add the @Transactional comment.

CompletableFuture

Using CompletableFuture for java 8, we can also execute queries asynchronously:

    @Async
    CompletableFuture<Book> findOneByAuthor(String author);

We use this method:

    @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());
    }

Examples of this article can be referenced https://github.com/ddean2009/learn-springboot2/tree/master/springboot-jpa

Refer to more tutorials Fldean's Blog

115 original articles were published. 119 were praised. 330,000 visits were received+
Private letter follow

Posted by Anarchatos on Wed, 26 Feb 2020 18:07:50 -0800