0

我有一个名为的类TableConnectionInfo,其中包含有关表的详细信息,例如tableName它的columns. 我编写了一个方法,我应该使用table.getColumns()每个表的方法中的列值来生成随机选择 sql。

假设 table1 它有 10 列,例如 -

col1
col2
col3
col4
col5
col6
col7
col8
col9
col10

下面是我尝试使用table.getColumns(). 这tableTableConnectionInfo对象。

private static Random random = new SecureRandom();

private String generateRandomSQL(TableConnectionInfo table) {

    int rNumber = random.nextInt(table.getColumns().size());

    List<String> shuffledColumns = new ArrayList<String>(table.getColumns());
    Collections.shuffle(shuffledColumns);

    String columnsList = "";

    for (int i = 0; i < rNumber; i++) {
        columnsList += ("," + shuffledColumns.get(i));
    }

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

    return sql;
}

下面是我的TableConncectionInfo课程,tableName它的columns列表

public class TableConnectionInfo {

    public String tableName;
    public ArrayList<String> columns;

    public ArrayList<String> getColumns() {
        return columns;
    }

    public void setColumns(ArrayList<String> columns) {
        this.columns = columns;
    }

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }
}

问题陈述:-

所以上述方法的问题是,它会随机打乱所有列,我会得到这样的结果-

`SELECT ID, CREATION_DATE, LAST_MODIFIED_DATE, col3, col1, col5 from table1 where id = ?`
`SELECT ID, CREATION_DATE, LAST_MODIFIED_DATE, col7, col2, col3, col1 from table1 where id = ?`
`SELECT ID, CREATION_DATE, LAST_MODIFIED_DATE, col8, col1, col2, col6 from table1 where id = ?`
... Other possible combinations

我正在寻找这样的东西。在 ArrayList 中插入列的方式 - 假设这是顺序 -

col1, col2, col3, col4, col5, col6, col7, col8, col9, col10

那么我的列SELECT SQL应该是相同的顺序。意义-

`SELECT ID, CREATION_DATE, LAST_MODIFIED_DATE, col1, col3, col5 from table1 where id = ?`
`SELECT ID, CREATION_DATE, LAST_MODIFIED_DATE, col7, col8, col9, col10 from table1 where id = ?`
`SELECT ID, CREATION_DATE, LAST_MODIFIED_DATE, col1, col4, col5, col6, col10 from table1 where id = ?`

它不应该是随机的,例如col1, then col5, then col2(这是错误的)。它应该是-

col5, col7, col10
col3, col6, col8, col10

other options

基本上,我希望在我的 SELECT sql 中以插入 ArrayList 的方式但以随机顺序插入列。Like- 按插入顺序选择任意 4 个或按插入顺序选择任意 6 个或按插入顺序选择任意 7 个

4

1 回答 1

1

1 解决方法如下

private static 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, ",");
}

我正在使用来自commons-lang 的StringUtils

于 2013-02-27T03:55:35.293 回答