Spring Boot - JPA Repository - Stream resultset thrown could not advance using next() error

Viewed 542

I am trying to stream data from repository and write it to the servlet output stream. While streaming , am facing unable to read data error. I already have @Transactional annotation in place..

@Autowired
private MyRepository < Y > repository;

@Autowired
private Gson gson;

@Transactional(readOnly = true)
public long writeData(ServletOutputStream outputStream) {
  JsonWriter writer = new JsonWriter(new OutputStreamWriter(outputStream, UTF_8));
  int count = 0;
  writer.beginArray();
  try (Stream < T > stream = repository.findAll()) {
    stream.forEach(e ->{
      gson.toJson(e, e.getClass(), writer);
      count++;
    });
  }
  writer.endArray();
  writer.flush();
  writer.close();
}

Error: org.hibernate.exception.GenericJDBCException: could not advance using next()

1 Answers

MyRepository had entitymanager bean injected in configuration class. so I was able to print the data in repository class.

But when the program control flows back to the method where am doing this operation, I was not able to do so because entitymanager is not part of scope of this class.

What I did is, added constructor(MyRepository repo) to class and updated the configuration file. This solved the problem.

@Configuration
@EnableTransactionManagement
public class MyConfiguration extends ConfigurationTemplate < MyEntity > {

  @Autowired
  private EntityManager entityManager;

  @Override
  @Bean
  @Scope("prototype")
  public DataStreamWriter < MyEntity > streamWriter() {
    return new DataStreamWriter < >(myRepository());
  }

  @Override
  @Bean
  public MyRepository myRepository() {
    return new MyRepository < >(MyEntity.class, entityManager);
  }

}

Related