Issue
I have a Repositoy (StockRepository ) class which extends from JpaRepository.
When calling the method findAll(Pageable pageable); the return result is Page<Stock>
.
Now I want to convert the Page<Stock>
to Page<StockDto>
. But the compiler give the error below.
How can I correct this Compile error ?
import org.springframework.core.convert.converter.Converter;
...
public Page<StockDto> getAllStocksPageable(int pageNumber, int pageSize) {
Pageable pageable = PageRequest.of(pageNumber, pageSize);
Page<Stock> stocks = stockRepository.findAll(pageable);
Page<StockDto> dtoPage = stocks.map(new Converter<Stock, StockDto>() {
@Override
public StockDto convert(Stock entity) {
StockDto stockDto = new StockDto();
...
return stockDto;
}
});
return null;
}
@Entity
@Table(name = "stock")
public class Stock {
....
}
// Pojo
public class StockDto {
....
}
@Repository
public interface StockRepository extends JpaRepository<Stock, Integer> {
....
}
Solution
The error is pretty clear: Page.map()
accepts a Function
, but you've given it a Converter
. Replace new Converter(
with new Function(
and convert(
with apply(
and it'll compile:
Page<StockDto> dtoPage = stocks.map(new Function<Stock, StockDto>() {
@Override
public StockDto apply(Stock entity) {
StockDto stockDto = new StockDto();
...
return stockDto;
}
});
Better yet, use a lambda:
Page<StockDto> dtoPage = stocks.map(entity -> {
StockDto stockDto = new StockDto();
...
return stockDto;
});
Answered By - Jelaby
Answer Checked By - Timothy Miller (JavaFixing Admin)