1

データベースからテーブルを取得するためにqueryForListを使用していますList<Map<String, Object>>。選択した 2 つの列を使用して、これをMap<String, Integer>.

現時点で私はこれをやっています

List<Map<String, Object>> customers = jdbc.queryForList("SELECT id, name FROM customers");

Map<String, Integer> customerMap = new HashMap<String, Integer>();

for (Map<String, Object> each : customers)
{
    String name = ((String)each.get("name")).trim();
    Integer id = Integer.valueOf(((BigDecimal)each.get("id")).intValue());

    customerMap.put(name, id);
}

もっと良い方法はないかと考えました。ありがとう

4

3 に答える 3

1

次の行に不要なボックス化があります。

Integer id = Integer.valueOf(((BigDecimal)each.get("id")).intValue());

次のように置き換える必要があります。

Integer id = ((BigDecimal) each.get("id")).intValue();
于 2012-12-07T11:58:46.733 に答える
0

私の知る限り、それを行う別の方法はありません。通常、マッパーを必要なオブジェクトに変換するエンティティ静的メソッドにそのコードをカプセル化するだけです。

public class Person{
    //  define atributes, constructor, etc

    public static Iterable<Person> ExtractFromMap(List<Map<String, Object>> dataList){
        //  iterate over the List like the example you gave
        //  try to be efficient with your casts and conversions

        LinkedList<Person> ret = new LinkedList<Person>();
        for (Map<String, Object> data : dataList)
        {
            //  using the constructor
            //  or put the code directly here
            ret.add(new Person(data));
        }
        return ret;
    }

    //  you can also create a constructor that receives a Map<String, Object> to
    //  use in the static method
    private Person(Map<String, Object> data){
        //  extract and instantiate your attributes

        this.name = ((String)each.get("name")).trim();
        //  ...
    }
}

必要に応じて、リフレクションを使用するジェネリック メソッドを作成することもできますが、シンプルにするために、この例は良いアイデアを与えると思います。

于 2012-12-07T12:20:51.063 に答える