SQLプロセッサ

SQL プロセッサは、対応する SQL テンプレートから生成された SQL ステートメントを処理できます。DAO メソッドを SQL プロセッサとして指定するには、@SqlProcessor を使用して注釈を付けてください。

@Dao
public interface EmployeeDao {
    @SqlProcessor
    <R> R process(Integer id, BiFunction<Config, PreparedSql, R> handler);
    // ...
}

警告

この機能を使用する際には、SQLインジェクションの脆弱性に注意することが不可欠です。可能な限り、より安全な代替手段を検討してください。

戻り値

戻り値の型は、 BiFunction の 3 番目の型パラメータと同じ型でなければなりません。

@SqlProcessor
String process(Integer id, BiFunction<Config, PreparedSql, String> handler);

戻り値の型が void の場合、 BiFunction の 3 番目の型パラメータは Void でなければなりません。

@SqlProcessor
void process(Integer id, BiFunction<Config, PreparedSql, Void> handler);

パラメータ

タイプが BiFunction であるパラメータを含めます。 BiFunction パラメータは設定と SQL ステートメントを受け取り、それらを処理します。 SQL テンプレートでは BiFunction パラメータ以外のパラメータが使用されます。

SQL テンプレートから生成された SQL ステートメントを変更して実行するとします。

void doSomething() {
    EmployeeDao dao = new EmployeeDaoImpl(config);
    dao.process(1, (config, preparedSql) -> {
      String sql = preparedSql.getRawSql();
      String anotherSql = createAnotherSql(sql);
      DataSource dataSource = config.getDataSource();
      Connection connection = dataSource.getConnection();
      PreparedStatement statement = connection.prepareStatement(anotherSql);
      return statement.execute();
    });
}
select * from employee where id = /*^ id */0