0

我正在尝试使用以下方法生成随机列,在生成列之后,我在我的SELECT sql.

final String columnsList = getColumns(table.getColumns());
final String selectSql = "SELECT ID, CREATION_DATE, LAST_MODIFIED_DATE, " + columnsList + "  from " + table.getTableName() + " where id = ?";

/**
 * A simple method to get the column names in the order in which it was
 * inserted
 * 
 * @param columns
 * @return
 */
private String getColumns(final List<String> columns) {
    List<String> copy = new ArrayList<String>(columns);
    Collections.shuffle(copy);

    int rNumber = random.nextInt(columns.size());

    List<String> subList = copy.subList(0, rNumber);
    Collections.sort(subList, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            return columns.indexOf(o1) < columns.indexOf(o2) ? -1 : 1;
        }
    });
    return StringUtils.join(subList, ",");
}

问题陈述:-

有时我看到columnsListvalue 是空的,如果它是空的,那么将不起作用,因为之前selectSql会有额外的。我如何确保每次至少返回一个条目。,from keywordgetColumns

我相信nextInt会在0 (inclusively) and n (exclusively). 所以它有时可能会选择 0,任何生成随机数的方式1(inclusively) and n (exclusively)

4

1 回答 1

1

一种方法是:

return subList.isEmpty() ? "1" : StringUtils.join(subList, ",");

但我认为更好的是修改selectSql

final String selectSql = "SELECT ID, CREATION_DATE, LAST_MODIFIED_DATE " + columnsList + "  from " + table.getTableName() + " where id = ?";

进而

return subList.isEmpty() ? "" : ","+StringUtils.join(subList, ",");

如果您希望至少有一个随机值,您也可以使用:

int rNumber = 1+random.nextInt(columns.size()-1);
于 2013-03-01T20:15:15.717 回答