I have little problem with Spring and Mybatis connection in JHipster framework( (out of the box).
Problem is occurred when I try inject class, which have Mybatis mapper injected. In this situation class returns null pointer exception. When I try to autowire this class I get "cannot find candidate to autowire error".
Architecture of class:
Repository(Mybatis mapper interface) ->
ServiceImplementation (Class with injected Mybatis Repository, business logic) ->
Resource (REST controller with instance of Service)
I think solution is simple, but I cannot find right implementation:
Service Implementation is invisible for Spring Beans Mapper and I
can't find in JHipster configuration for them.
I have to use another annotation to get right injection of Service
Implemenation
Somebody meet with this situation and can get litte clue for me to refactor my code? :-) Thanks
Code:
Repository
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.apache.ibatis.annotations.Insert;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import pl.xxx.xxx.domain.City;
import pl.xxx.xxx.domain.Dish;
#Mapper
public interface CityMapper {
#Select("SELECT * FROM CITY WHERE id = #{id}")
City getCityByID(#Param("id") Long id);
#Select("SELECT * FROM CITY WHERE name = #{name}")
City getCityByName(#Param("name") String name);
#Insert("INSERT INTO CITY('name') VALUES(#{name})")
void createCity(City city);
#Delete("DELETE FROM CITY WHERE id = #{id}")
void deleteCityByID(City city);
#Select("SELECT count(*) FROM CITY")
int getNumberOfCities();
#Select("<script>"
+ "SELECT * FROM CITY "
+ "</script>")
List<City> findAll();
}
Service
package pl.xxx.xxx.service.impl;
import java.util.List;
import javax.inject.Inject;
import pl.xxxx.xxxx.domain.City;
import pl.xxxx.xxx.repository.CityMapper;
import pl.xxx.xxx.service.CityService;
import pl.xxx.xxx.web.rest.util.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.context.annotation.Bean;
#Service
#Transactional
public class CityServiceImpl implements CityService {
#Inject
private CityMapper cityMapper;
#Override
public List<City> findAll(Pageable pageable) {
return cityMapper.findAll();
}
}
Interface
package pl.xxx.xxx.service;
import java.util.List;
import pl.xxx.xxx.domain.City;
import pl.xxxx.xxx.domain.Dish;
import pl.xxx.xxx.web.rest.util.Pageable;
public interface CityService {
/**
* Get all the dishes.
*
* #param pageable the pagination information
* #return the list of entities
*/
List<City> findAll(Pageable pageable);
}
Resource
package pl.xxx.xxxx.web.rest;
import com.codahale.metrics.annotation.Timed;
import pl.xxx.xxx.xxx.City;
import pl.xxx.xxx.domain.Dish;
import pl.xxx.xxx.repository.CityMapper;
import pl.xxx.xxx.service.impl.CityServiceImpl;
import pl.xxx.xxx.web.rest.util.Pageable;
import pl.xxx.xxx.web.rest.util.PaginationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import javax.annotation.Resource;
import javax.inject.Inject;
import static org.elasticsearch.index.query.QueryBuilders.*;
/**
* REST controller for managing City.
*/
#RestController
#RequestMapping("/api")
public class CityResource {
private final Logger log = LoggerFactory.getLogger(CityResource.class);
private CityServiceImpl cityServiceImpl;
#Inject
private CityMapper cityMapper;
/**
* GET /Cities: get all the cities.
*
* #param pageable the pagination information
* #return the ResponseEntity with status 200 (OK) and the list of citires in body
* #throws URISyntaxException if there is an error to generate the pagination HTTP getHeaders()
*/
#RequestMapping(value = "/cities",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed()
public ResponseEntity<List<City>> getAllCities(Pageable pageable)
throws URISyntaxException {
log.debug("REST request to get a page of Cities");
Pageable p = new Pageable();
List<City> page = cityServiceImpl.findAll(p);
HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeadersLM("/api/cities");
return new ResponseEntity<>(page, headers, HttpStatus.OK);
}
}
Related
I'm creating a read only REST API using Spring Boot 2.7 and Java 19
I followed the idea posted here: https://www.baeldung.com/spring-data-read-only-repository
I've created a read only generic repository:
package com.scope.mdm.domain;
import java.util.List;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.Repository;
#NoRepositoryBean
public interface ReadOnlyRepository<T, ID> extends Repository<T, ID> {
List<T> findAll();
}
This is a simplify view of the entity definition:
package com.scope.mdm.domain;
import javax.persistence.Column;
import javax.persistence.Table;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.annotations.Immutable;
#Entity
#Immutable
#Table(name = "v_LegalEntity", schema = "entity_reference")
public class LegalEntity {
#Id
#Column(name = "LegalEntityId")
Integer legalEntityId;
#Column(name = "SO_Id")
String soId;
#Column(name = "Source_LegalEntityId")
I implemented a read only repository as follows:
package com.scope.mdm.domain;
import java.util.List;
import java.util.Optional;
public interface LegalEntityReadOnlyRepository extends ReadOnlyRepository<LegalEntity, Integer> {
// Fetch legal entities by Scope One Id
Optional<LegalEntity> findBySoId(String soId);
// Fetch legal entities by its data source provided ID
LegalEntity findByLegalEntityId(String legalEntityId);
// Legal entities containing the name
List<LegalEntity> findByLegalEntityNameLike(String legalEntityName);
}
This is the controller:
package com.scope.mdm.web;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.beans.factory.annotation.Autowired;
import com.scope.mdm.domain.LegalEntity;
import com.scope.mdm.domain.LegalEntityReadOnlyRepository;
#RestController
public class LegalEntityController {
#Autowired
private LegalEntityReadOnlyRepository repository;
#RequestMapping(value="/legalEntities", method=RequestMethod.GET)
public Iterable<LegalEntity> getLegalEntity() {
return repository.findAll();
}
}
I want to do a simple unit test like this:
package com.scope.mdm;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.scope.mdm.domain.LegalEntityReadOnlyRepository;
import com.scope.mdm.domain.LegalEntityRepository;
import org.junit.jupiter.api.Assertions;
#SpringBootTest(classes = mdmWebAPIApplication.class)
public class legalEntitySearchTest {
#Autowired
private LegalEntityRepository repository;
#Autowired
private LegalEntityReadOnlyRepository repositoryReadOnly;
#Test
public void contextLoads() {
Assertions.assertNotNull(repositoryReadOnly);
Assertions.assertNotNull(repository);
}
}
When running the test from VSCODE I get this error:
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No
qualifying bean of type
'com.scope.mdm.domain.LegalEntityReadOnlyRepository' available:
expected single matching bean but found 2:
legalEntityRepository,legalEntityReadOnlyRepository
I tried with the #Qualifier annotation to explicitly specify the bean but the result is the same.
Hi I am new to spring and have created an Export csv application with two controllers which can give all the data as well as selective columns data and want to write junits for the same but it is quite difficult for me to do the same as I am not aware how i should do it some help would be really great
Main class:
package com.example;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.model.Example;
import com.example.repository.ExampleRepository;
import net.bytebuddy.implementation.bind.annotation.Super;
#SpringBootApplication
public class ExampleApplication implements CommandLineRunner {
#Autowired
ExampleRepository exampleRepository;
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
List<Example> example= new ArrayList<>();
// create dummy
example.add(new Example(1,"abc","sachin","abc","abc"));
example.add(new Example(2,"abc","rahul","abc","abc"));
example.add(new Example(3,"abc","rahul","abc","abc"));
exampleRepository.saveAll(example);
}
}
Entity layer:
package com.example.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="example")
public class Example{
#Column(name="city")
private String city;
#Column(name="name")
private String name;
#Column(name="amount")
private String amount;
#Column(name="country")
private String country;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
private long id;
//getter and setters
}
Repository layer is as follows:
package com.example.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.example.model.Example;
#Repository("exampleRepository")
public interface ExampleRepository extends JpaRepository<Example,Long> {
List<Report> findByName(String name);
}
service layer is as follows
package com.example.services;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.model.Example;
import com.example.repository.ExampleRepository;
#Transactional
#Service
public class ExampleService {
#Autowired
ExampleRepository exampleRepository;
public List<Example> fetchAll() {
return exampleRepository.findAll();
}
public List<Example> findByName(String name){
return exampleRepository.findByName(name);
}
}
I have 2 controllers one to get all details and one to get selective columns and here we are generating csv files based on records that match the name
COntroller 1:
package com.example.controllers;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.example.model.Example;
import com.example.services.ExampleService;
#RestController
#RequestMapping("/demo")
public class Controller1 {
#Autowired
ExampleService exampleService;
#GetMapping("/result")
public void exportCSV(#RequestParam(name="name") String name ,HttpServletResponse response) throws Exception {
// set file name and content type
String filename = "names.csv";
response.setContentType("text/csv");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"");
// Configure the CSV writer builder
StatefulBeanToCsvBuilder<Example> builder = new StatefulBeanToCsvBuilder<Example>(response.getWriter()).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withOrderedResults(false);
// create a csv writer
StatefulBeanToCsv<Example> writer = builder.build();
// write all employees to csv file
writer.write(examplesService.findByName(name));
}
}
Controller 2:
package com.reports.controllers;
import java.util.Arrays;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.example.model.Example;
import com.example.services.ExampleService;
#RestController
#RequestMapping("/example")
public class Controller2 {
#Autowired
ExampleService exampleService;
#GetMapping("/output")
public void exportCSV(#RequestParam(name="name") String name ,HttpServletResponse response) throws Exception {
// set file name and content type
String filename = "details.csv";
response.setContentType("text/csv");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"");
// Configure the CSV writer builder
StatefulBeanToCsvBuilder<Example> builder = new StatefulBeanToCsvBuilder<Example>(response.getWriter()).withQuotechar(CSVWriter.NO_QUOTE_CHARACTER).withSeparator(CSVWriter.DEFAULT_SEPARATOR).withOrderedResults(false);
// Ignore any field except the `id` and `amount` ones
Arrays.stream(Example.class.getDeclaredFields())
.filter(field -> !("id".equals(field.getName()) || "amount".equals(field.getName())
))
.forEach(field -> builder.withIgnoreField(Report.class, field));
// create a csv writer
StatefulBeanToCsv<Example> writer = builder.build();
// write all employees to csv file
writer.write(exampleService.findByname(name));
}
}
Try this approach :
generate a file in your /src/test/resources path and then test if it contains the generated data you expected
use combine it with a file system mocking to do it
You will :
test your ResController
mock your Service class
Also use Contructor Injection for you dependency
I'm trying to Log unique request id for each http request using MDC to my resource for debugging and trace a particular request. For same I've created one custom annotation #TagRequestID. Below is the for logging request id. But what I'm not able to achieve the request is not going via DynamicFilter implementation what I think there should be some method or way in VertxResteasyDeployment class which should help to resolve this.
Basically the request is not going via filter even I tried with setProviders method of VertxResteasyDeployment class. Can someone please guide what I'm missing here ? I believe there should be some config which request to pass request via DynamicFeature implementation where we inject RequestIdConfig bean. (Assume I've RequestIdConfig bean created).
#TagRequestID code :
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.METHOD)
public #interface TagRequestID {
}
custom class RequestIdConfig :
import lombok.Data;
import javax.validation.constraints.NotNull;
#Data
public class RequestIdConfig {
#NotNull
private String resourcePackage;
#NotNull
private String requestIdHeaderKey;
#NotNull
private Boolean requestIdMandatoryFlag;
}
custom class RequestIdFeature :
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import javax.ws.rs.ConstrainedTo;
import javax.ws.rs.RuntimeType;
import javax.ws.rs.container.DynamicFeature;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.Provider;
#Slf4j
#AllArgsConstructor
#Provider
public class RequestIdFeature
implements DynamicFeature {
RequestIdConfig requestIdConfig;
#Override
public void configure(ResourceInfo resourceInfo, FeatureContext featureContext) {
log.info("testing now===");
final Class<?> resourceClass = resourceInfo.getResourceClass();
//Check if the current resource is to validated
if (resourceClass.getPackage().getName().startsWith(requestIdConfig.getResourcePackage())) {
//Check if the Validation annotation is present
if (resourceInfo.getResourceMethod().getAnnotation(TagRequestID.class) != null) {
log.info(resourceInfo.getResourceMethod() + " registered for clientID validation");
featureContext.register(new RequestIdFilter(requestIdConfig, resourceInfo));
}
}
}
}
custom class for filter :
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jboss.logging.MDC;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.UUID;
#Data
#AllArgsConstructor
#Slf4j
#Provider
public class RequestIdFilter
implements ContainerRequestFilter {
RequestIdConfig requestIdConfig;
ResourceInfo resourceInfo;
public static final String REQUEST_ID = "request-Id";
#Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
log.info("ClientIdValidation filter method invoked");
Method resourceMethod = resourceInfo.getResourceMethod();
// Validate Clients
validatePermissions(containerRequestContext);
}
private void validatePermissions(final ContainerRequestContext containerRequestContext) {
String requestId = containerRequestContext.getHeaderString(requestIdConfig.getRequestIdHeaderKey());
//Make sure the Header key is present if mandatory flag is true
if (requestIdConfig.getRequestIdMandatoryFlag() && StringUtils.isAnyEmpty(requestId)) {
throw new WebApplicationException(requestIdConfig.getRequestIdHeaderKey() + " can't be null", Response.Status.UNAUTHORIZED);
}
//If no request ID present, generate a UUID
if (StringUtils.isAnyEmpty(requestId)) {
requestId = UUID.randomUUID()
.toString();
}
containerRequestContext.setProperty(REQUEST_ID, requestId);
MDC.put(REQUEST_ID, requestId);
}
}
Resource or Controller code :
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.container.AsyncResponse;
import javax.ws.rs.container.Suspended;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import io.vertx.core.Vertx;
import io.vertx.core.WorkerExecutor;
public class Processor {
#POST
#TagRequestID
#Path("/update_record")
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON })
public void updateEvent(String data) throws Exception{
//do something here
}
Server code from where we run this:
import mypackage.Processor;
import io.vertx.core.AbstractVerticle;
import org.jboss.resteasy.plugins.server.vertx.VertxRequestHandler;
import org.jboss.resteasy.plugins.server.vertx.VertxResteasyDeployment;
import org.springframework.context.ApplicationContext;
public class VertxServer extends AbstractVerticle {
VertxServer(final ApplicationContext context) {
}
#Override
public void start() throws Exception {
VertxResteasyDeployment deployment = new VertxResteasyDeployment();
deployment.start();
deployment.getRegistry().addPerInstanceResource(Processors.class);
vertx.createHttpServer()
.requestHandler(new VertxRequestHandler(vertx, deployment))
.listen(8080);
}
}
Once server is up and running then just hit two request simultaneously on the above controller . i.e :
curl -X POST \ http://localhost:8080/v1/update_record \ -H
'Cache-Control: no-cache' \ -H 'Content-Type: application/json' \
-H 'Postman-Token: c9494189-4ac9-9f6c-44f6-216186c74431' \ -d '{"id":"123"}'
In VertxServer.java register your dynamicFeature instance in providerFactory before you register your resources. This dynamicFeatures and filters registered in providerFactory will be used while registering resources.
Your code will go like this:
VertxResteasyDeployment deployment = new VertxResteasyDeployment();
deployment.start();
deployment.getProviderFactory().register(new RequestIdFeature(getRequiredBean());
deployment.getRegistry().addPerInstanceResource(Processors.class);
vertx.createHttpServer()
.requestHandler(new VertxRequestHandler(vertx, deployment))
.listen(8080);
VertxServer.java
deployment.getProviderFactory().register(RequestIdFilter.class)
I am trying to display data from MySQL database using spring data with Pageable class. I am new in Spring Data and unfortunately I get all rows shown in my browser, instead of some.
Find below my code
pom.xml
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.5.0.RELEASE</version>
</dependency>
ProductDaoImpl
package com.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.model.Product;
#Repository
public class ProductDaoImpl implements ProductDao {
#Autowired
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
#SuppressWarnings("unchecked")
public Page<Product> getPageProduct(#Param("libelleProduct")String libelleProduct, Pageable pageable) {
List<Product> listProduct = sessionFactory.getCurrentSession().createQuery("From Product p where p.libelleProduct like :libelleProduct").setParameter("libelleProduct", libelleProduct).list();
Page<Product> pageProduct = new PageImpl<Product>(listProduct, pageable, listProduct.size());
return pageProduct;
}
}
ProductService
package com.service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import com.dao.ProductDao;
import com.model.Product;
#Service
#Transactional
public class ProductServiceImpl implements ProductService {
#Autowired
private ProductDao productDao;
public ProductDao getProductDao() {
return productDao;
}
public Page<Product> getPageProduct(String libelleProduct, int page, int size) {
return productDao.getPageProduct(libelleProduct, new PageRequest(page, size));
}
}
ProductController
package com.controller;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.model.Product;
import com.service.ProductService;
#RestController
public class ProductController {
public Logger logger = Logger.getLogger(ProductController.class);
public ProductController(){
System.out.println("ProductController()");
}
#Autowired
private ProductService service;
#RequestMapping(value="/listedesproduit", method=RequestMethod.GET, headers="Accept=application/json")
#ResponseBody
public Page<Product> getPageProduct(){
Page<Product> pageProduct = service.getPageProduct("%e%",0, 1);
pageProduct.forEach(p->System.out.println(p.getLibelleProduct()));
return pageProduct;
}
}
Find below the result I get in my browser, I get four rows shown instead of one on each page.
{"content":[{"idProduct":2,"libelleProduct":"sprite","qteProduct":5},{"idProduct":3,"libelleProduct":"eku","qteProduct":5},{"idProduct":4,"libelleProduct":"33 export","qteProduct":5},{"idProduct":6,"libelleProduct":"guiness","qteProduct":5}],"size":1,"number":0,"numberOfElements":4,"sort":null,"totalPages":4,"totalElements":4,"firstPage":true,"lastPage":false}
Can you please help me to find what I do wrong?
You are using it wrong here:
List<Product> listProduct = sessionFactory.getCurrentSession()
.createQuery("From Product p where p.libelleProduct like :libelleProduct")
.setParameter("libelleProduct", libelleProduct).list();
Page<Product> pageProduct = new PageImpl<Product>(listProduct, pageable, listProduct.size());
You are basically loading all the query results and then returning it in a PageImpl, which is just a wrapper of the data.
You should create a PagingAndSortingRepository and call query methods passing the Pageable, which is the page request to be executed by the repository.
If this doesn't make sense to you, look for tutorials about "spring data paging" like this one and take a look at the documentation.
I am trying to Stream results from a Spring Data Rest Call and am getting the error:
java.lang.IllegalArgumentException: PersistentEntity must not be null!
The call works when I do not try to stream the results. Any insight is appreciated.
Here is the Repository definition:
/**
*
*/
package com.xxx.beverage.repository.db2;
import java.util.List;
import java.util.stream.Stream;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.transaction.annotation.Transactional;
import com.xxx.xxx.model.db2.Vbrk;
#RepositoryRestResource
public interface VbrkRepository extends PagingAndSortingRepository<Vbrk, String> {
Vbrk findOne(String id);
#RestResource(path="findByKunag")
#Query(value="SELECT * FROM VBRK v WHERE v.KUNAG = :kunag ", nativeQuery=true)
Stream<Vbrk> findByKunagAndStream(#Param("kunag") String kunag);
Page<Vbrk> findAll(Pageable pageable);
}