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?

@Selectでどうやったら動的SQLを書くのか気になったので調べた

Last updated at Posted at 2025-07-02

現場では@Selectなどを使用し静的SQL部分のみ担当しているため、動的に記述する際はどのように書くのか気になり個人メモ。
現場のようにテキストブロックで記述。

環境

MacBook Air M1
Intellij
Java21

@Selectで記述する場合

Mapper.Java
    @Select("""
            <script>
                SELECT * FROM todos
                <where>
                    <if test="id != null and 0 &lt; id">
                        id = #{id}
                    </if>
                    <if test="id == null or id &lt;= 0">
                        id = 1
                    </if>
                </where>
            </script>""")
    ToDo selectById(@Param("id") Integer id);

個人的には見づらい。

@SelectProvider

動的に書くなら@SelectProviderというものがあると知り簡易コードで記述。

Mapper.Java
    @SelectProvider(type = Test.class, method = "select")
    ToDo selectById(@Param("id") Integer id);
Test.Java
public class Test {
    public String select(Integer id){
        return """
                SELECT * FROM todos %s"""
                .formatted((id != null && 0 < id )? "WHERE id = #{id}" : "WHERE id = 1")
                .stripTrailing();
    }
}

stripTrailing()はいらないと思いますが、おまじないで使用。
見やすいかは微妙ですね。

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?