Creating custom JDBI binders!
Say you want to use JDBI's SQL Object API and have an insert statement that you want to run, for example:
INSERT INTO users (first_name, age) VALUES (:firstName, :age);
but your User class looks like:
class User { String firstName; String Date dateOfBirth; // constructor(s) // getters public int getAge() { // ... some vodoo to calculate age... } }
Writing a JDBI UserDao with the following method would crash since there is no "age" field in the User class and JDBI doesn't know how to bind to the ":age" parameter.
public void saveUser(@BindBean User user);
Start by creating a custom binding:
@BindingAnnotation(BindUser.UserBinderFactory.class) @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER}) public @interface BindUser { public static class UserBinderFactory implements BinderFactory { public Binder build(Annotation annotation) { return new Binder<BindUser, User>() { public void bind(SQLStatement q, BindUser bind, User user) { q.bind("firstName", user.getFirstName()); q.bind("age", user.getAge()); } }; } } }
Then change your saveUser() method to use the binding you just created:
public void saveUser(@BindUser User user);
Voila!














