简体   繁体   中英

How to use Stream method in jparepository

I am new to Spring.How to use Stream method in jparepository.I want to get data from jparepository. I configure applicationcontext.xml also.I am using spring 4 version

My Repository class

 @Repository public interface CustomerRepository extends JpaRepository<Customer, Long>{ @Query("select c from Customer c") Stream<Customer> getAllFirstNames(); } 

my mainclass.java

  @Transactional public class VaadinUI extends UI { @Autowired private CustomerRepository repo; System.out.println("enter into try block"); Stream<Customer> customers= repo.getAllFirstNames(); System.out.println("Customers"+ customers); } 

now i got error like
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.

How to slove that issue.How to call repository stream method in maincalss.java I add @Transactional(readonly=true) till i got same error. please help me out!

You need to do couple of things.

  1. Processing data with a Stream requires us to close a Stream when we finish it. It can be done by calling the close() method on a Stream or by using try-with-resources

      try (Stream<Customer> customers = repo.getAllFirstNames()) { System.out.println("Customers"+ customers); } 
  2. Make your method calling this function as Transactional(readonly=true)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM