返回总条数和分页数据
public PreviewData preview(String tableName, Integer pageNo, Integer pageSize) {
    List<String> strings = qeuryTables();
    if (!strings.contains(tableName)) {
        throw new DdlException(ErrorCodeEnum.NOT_EXIST_TABLE);
    }
    Connection connection = null;
    try {
        connection = jdbcTemplate.getDataSource().getConnection();
        DatabaseMetaData metaData = connection.getMetaData();
        ResultSet rs = metaData.getColumns(null, null, tableName, null);
        List<PreviewData.Field> fields = Lists.newArrayList();
        while (rs.next()) {
            fields.add(PreviewData.Field.builder().name(rs.getString("COLUMN_NAME")).type(rs.getString("TYPE_NAME")).build());
        }
        PreviewData build = PreviewData.builder().fields(fields).build();
        String originalSql = "select * from " + warpName(tableName);
        String countSql = "select count(1) as count from (%s) ";
        String format = String.format(countSql, originalSql);
        List<Map<String, Object>> maps1 = jdbcTemplate.queryForList(format);
        if (!org.springframework.util.CollectionUtils.isEmpty(maps1)) {
            BigInteger count = (BigInteger) (maps1.get(0).get("count"));
            if (count == null) {
                build.setTotal(0L);
            } else {
                build.setTotal(count.longValue());
            }
        }
        originalSql = originalSql + " limit " + pageNo + "," + pageSize;
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(originalSql);
        build.setRecords(maps);
        build.setPageno(pageNo);
        build.setPagesize(pageSize);
        return build;
    } catch (SQLException e) {
        log.info("", e);
    } finally {
        JdbcUtils.closeConnection(connection);
    }
    return PreviewData.builder().build();
}

更多推荐

【Java开发bug-002】返回总条数和分页数据