package com.meeno.common.utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.meeno.siliandan.area.entity.MiningArea;
import com.meenoframework.util.PageData;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @Author: GoslingWu
* @Date: Created in 2020/11/11
* @Description: JDBC工具类
*/
@Component
@Slf4j
public class JdbcTemplateUtils {
private static JdbcTemplate jdbcTemplate;
@Autowired
public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
JdbcTemplateUtils.jdbcTemplate = jdbcTemplate;
}
/**
* jdbc分页
* @param sql
* @param params
* @param pageable
* @param clazz
* @param <T>
* @return
*/
public static <T> PageData<T> page(String sql, List<Object> params, Pageable pageable, Class<T> clazz){
return page(sql, params, (int) pageable.getOffset(), pageable.getPageSize(), clazz);
}
/**
* jdbc分页
* @param sql
* @param params
* @param pageIndex
* @param pageSize
* @param clazz
* @param <T>
* @return
*/
public static <T> PageData<T> page(String sql, List<Object> params, Integer pageIndex, Integer pageSize, Class<T> clazz){
String selectSql = " select * ";
Integer index = pageIndex;
String limit = " limit " + index + " , " + pageSize;
String resultSql = selectSql + sql + limit;
List<Map<String, Object>> mapList = jdbcTemplate.queryForList(resultSql, params.toArray());
List<T> list = mapList.stream()
.map(stringObjectMap -> JSONObject.parseObject(JSONObject.toJSONString(stringObjectMap), clazz))
.collect(Collectors.toList());
String countSql = " select count(*) ";
Long count = jdbcTemplate.queryForObject(countSql + sql, params.toArray(), Long.class);
PageData<T> pageData = new PageData<T>(count, list);
return pageData;
}
}