0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

mybatisにhavingはなく、trimで代用できる

Posted at

mybatisでgroup byの際のhaving句を記載しようとした時に、
whereタグのような便利なhavingタグ的なのがあると思ったら、なくて困ったという話です

ドキュメントをよく読むと、trimタグを使用して、whereタグのhaving版を作成できました

havingはtrimタグで作れる

mybatisの動的SQLのドキュメントに次のように書いてあります
http://www.mybatis.org/mybatis-3/ja/dynamic-sql.html

where 要素の動作が期待と異なる場合は、trim 要素を定義することで処理内容をカスタマイズすることができます。

つまり、trimタグで下記のように記載することでwhereタグと同じ動作ができます
trimっていうだけに、前後のスペースとか除く的なやつだと思って、今まで読み飛ばしてました。。。

<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ... 
</trim>
  • prefixには、trimタグ内の結果がある場合に先頭に出力する文字を指定します
    つまり検索条件があればWHEREを先頭につける、なければなにもつけない
  • prefixOverridesには、trimタグ内の結果がパイプで区切った文字で始まる場合にその文字を削除します
    つまりWHERE以下がANDで始まったら、そのANDを除去する

なので、これをhavingで応用すると、

例えば、

  • チームの所属人数を出す
  • チーム内の最年長者の年齢を条件として範囲指定できる

ようなSQLを作る場合、trimタグを使用して、次のように書けます

<select id="sample" resultType="Account">
  SELECT team,count(*) FROM ACCOUNT GROUP BY team
  <trim prefix="HAVINNG" prefixOverrides="AND |OR ">
      <if test="search_max_age_from != null">
        max(age) > #{search_max_age_from }
      </if> 
      <if test="search_max_age_to != null">
        AND max(age) < #{search_max_age_to }
      </if>
  </trim >
</select>

whereタグを使用した場合と同様に大分スッキリ書くことができました

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?