I would like to intercept and modify SQL statements before they get executed in JDBI 3 (SQL Objects). The reason for it is to replace custom token placeholders with schema names. I found this thread but it is for JDBI 2 (Using Dropwizard & JDBI to query database with multiple schemas?). I tried the approach below but I got stuck on how to modify the final SQL query before it's executed.
public class Product {
private int id = -1;
private String name = "";
public Product() {
}
public Product(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
public class ProductMapper implements RowMapper<Product> {
@Override
public Product map(ResultSet r, StatementContext ctx) throws SQLException {
Product product = new Product();
product.setId(r.getInt("id"));
product.setName(r.getString("name"));
return product;
}
}
@SchemaRewriterFactory
@UseClasspathSqlLocator
public interface ProductDao {
/**
* The sql query is located in resources ([package]/listProducts.sql)
* listProducts.sql: SELECT PRODUCT_ID ID, NAME FROM :schema.PRODUCTS
* @return
*/
@SqlQuery
@RegisterRowMapper(ProductMapper.class)
List<Product> listProducts();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@SqlStatementCustomizingAnnotation(SchemaRewriterFactory.SchemaRewriter.class)
public @interface SchemaRewriterFactory {
public class SchemaRewriter implements SqlStatementCustomizerFactory {
@Override
public SqlStatementCustomizer createForMethod(Annotation annotation, Class<?> sqlObjectType, Method method) {
return null;
}
@Override
public SqlStatementParameterCustomizer createForParameter(Annotation annotation, Class<?> sqlObjectType, Method method, Parameter param, int index, Type paramType) {
return null;
}
@Override
public SqlStatementCustomizer createForType(Annotation annotation, Class<?> sqlObjectType) {
return q -> q.addCustomizer(new StatementCustomizer() {
@Override
public void beforeBinding(PreparedStatement stmt, StatementContext ctx) throws SQLException {}
@Override
public void beforeExecution(PreparedStatement stmt, StatementContext ctx) throws SQLException {
System.out.println(stmt.toString());
//TODO: HOW DO I MODIFY SQL (REPLACE TOKENS - :schema) BEFORE IT GETS EXECUTED?
}
@Override
public void afterExecution(PreparedStatement stmt, StatementContext ctx) throws SQLException { }
});
}
}
}
I also found this thread which deals with custom tag replacements using @Define (Dynamic Order in JDBI SQL Object Queries). If possible, I would like to avoid passing extra parameters on every call. Any help would be appreciated!