LoginSignup
4
6

More than 5 years have passed since last update.

MyBatisで取得するカラム名を動的に変更する方法

Last updated at Posted at 2017-03-15

MyBatisで取得するカラム名を動的に変更する方法

MyBatisでwhere句の条件値を動的に渡すには、下記のように「#」を使用してプリペアードステートメントとして扱われるのは一般的だと思います。

SQL定義ファイル.xml
<select id="getHogeValue" resultType="java.util.Map">
select * 
form hoge_table
where foo_1 = #{foovalue}
</select>

ここでは、取得するカラムを動的に変更する方法を説明します。
つまり、select句で指定するカラムが不定の時に役立ちます。

環境

Java:JDK1.7
MyBatis:mybatis-3.2.5.jar

実装方法

プリペアードステートメントの値として渡すのではなく、
文字列として渡すには、「$」を使用します。

以下、例になります。

データアクセスクラス.java
    //カラム名の動的部分をListに定義
    List<Integer> columnIdList = Arrays.asList(1,2,3,4);

    //Mapとしてカラム名動的部分のListを設定
    Map params = new HashMap();
    params.put("column_id_list", columnIdList);

    //Hogeテーブルから FOO_1, FOO_2, FOO_3, FOO_4, BAR_1, BAR_2, BAR_3, BAR_4 を取得する
    List<Map> hogeValueLsit = hogeTableMapper.getHogeValue(params);

    //取得した中身を確認する
    for (Map elm : hogeValueLsit) {
      int idx = 0;
      for (Integer columnId : columnIdList) {

        String foo = (String)elm.get("FOO_"+columnId);
        System.out.println("FOO_" + idx + "番目は" + foo + "です。");

        String bar = (String)elm.get("BAR_"+columnId);
        System.out.println("BAR_" + idx + "番目は" + bar + "です。");

      }
    }
SQL定義ファイル.xml
    <select id="getHogeValue" resultType="java.util.Map">
    select 
      <foreach item="column_id" collection="column_id_list">
         foo_${column_id}
        ,bar_${column_id}
      </foreach>
    from hoge_table 
    </select>

注意点

Java側で取得する時、カラム名は「大文字」であることに注意
SQL定義ファイル側で「foo_」と小文字にしていても、
Java側のMapキーは「FOO_」と大文字でないと取得できません。

以上です。

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6