如何在Spring启动时使用JdbcTemplate进行Pagerequest

时间:2017-08-07 14:14:26

标签: spring-boot jdbctemplate

我想在PageRequest中制作一个JdbcTemplate。我不想做的是使用JPA。我搜索了近4个小时但找不到任何有用的东西。请告诉我们我,如果可能,我该怎么办

修改 我想从Oracle重新加载数据,但不想使用JPARepository 这是我的代码。这是我的控制器

@RestController
@RequestMapping(value = "/admin")
public class OrderController {

@Autowired
private OrderService orderService;

@RequestMapping(value = "/reload", method = RequestMethod.GET)
public List<Order> reload(){
    return  orderService.reload();
}

这是我的服务

@Service
public class OrderService {

@Autowired
private OrderRepository orderRepository;

public List<Order> reload(){
    return orderRepository.reload();
}

这是我的存储库

@Repository
public interface OrderRepository {

public List<Order> reload();
}

这是我的repositoryImpl类

 @Repository
 public class OrderRepositoryImpl implements OrderRepository{

@Autowired
private JdbcTemplate jdbcTemplate; 
@Override
public List<Order> reload(){

}

1 个答案:

答案 0 :(得分:0)

Using spring-data-commons

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.data.repository.support.PageableExecutionUtils.TotalSupplier;

/**
 * @param content list from jdbcTemplate
 * @param pageNum : zero-based, if null default to zero
 * @param pageSize : if null default list size
 * @return Page object (zero-based)
 */
public static <T> Page<T> pagingList(List<T> content, Integer pageNum, Integer pageSize){
    Assert.notNull(content, "List content must not be null!");
    pageNum = (pageNum == null) ? 0 : pageNum;
    pageSize = (pageSize == null) ? content.size() : pageSize;

    PageRequest pageable = new PageRequest(pageNum, pageSize);

    //System.out.println(" ======== PAGEABLE ========= ");
    //System.out.println(" pageable.getOffset     : " + pageable.getOffset());
    //System.out.println(" pageable.getPageNumber : " + pageable.getPageNumber());
    //System.out.println(" pageable.getPageSize   : " + pageable.getPageSize());

    TotalSupplier totalSupplier = new TotalSupplier() {

        @Override
        public long get() {
            return content.size();
        }
    };

    int fromOffset = pageable.getOffset();
    int toOffset =  Math.min(content.size(), fromOffset + pageSize);
    List<T> listPaging = new ArrayList<>();
    if(fromOffset < toOffset){
        listPaging = content.subList(fromOffset, toOffset);
    }
    return PageableExecutionUtils.getPage(listPaging, pageable, totalSupplier);
}

Above code does :

  • Accept list from jdbcTemplate
  • Create PageRequest object (with pageNum and pageSize)
  • Create subList from original list start from element fromOffset and toOffset

Be aware for huge size of list, not yet testing it.

Reference : Github spring-data-jpa