Can @Bind be used with enums and other arbitrary types using JDBI?

Does JDBI support enumeration type binding via annotation?

For example, assuming DAO includes a method:

@SqlQuery("select count(*) from answer a where a.foo = :foo") Long someSqlQuery(@Bind("foo") Foo foo); 

And, foo , equal to Foo.BAR , could I expect a request:

 select count(*) from answer a where a.foo = 'BAR' 

If so, is toString() to determine what is replaced?

Also, does JDBI allow @Bind to use any type that extends Object ? And again, if so, is toString() ?

+8
java mysql dropwizard jdbi
source share
2 answers

According to the source code Enum.name() , not toString()

If the object is bound, jdbi uses the setObject(Object object) the jdbc driver used. For example, in my experience with PostgreSQL, it successfully binds Map to hstore and arrays to postgreSQL array , because PostgreSQL jdbc driver does it.

If you want to process a certain type of objects in a certain way, you can implement ArgumentFactory (for which there seems to be no documentation, but an example is here in the Stack Overflow ) or BinderFactory (which I just opened now.)

+9
source share

To answer the "custom types" question, you can implement a BinderFactory to bind to whatever you want.

 @BindingAnnotation(UserBinder.UserBinderFactory.class) @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER}) public @interface UserBinder { public static class UserBinderFactory implements BinderFactory { @Override public Binder build(Annotation annotation) { return new Binder<UserBinder, User>() { @Override public void bind(SQLStatement<?> q, UserBinder bind, User arg) { q.bind("userId", arg.getUserId()); q.bind("uuid", arg.getUuid()); q.bind("openId", arg.getOpenId()); q.bind("givenName", arg.getGivenName()); // etc. } }; } } } 

This is most useful if you have complex types that you want to store in a certain way, for example. binary data or collections that you want to convert to CSV or only in separate mapping tables. Then you use your new fancy binder:

 @SqlUpdate( "INSERT INTO user (openId,givenName,uuid," + // etc. ") VALUES (:openId,:givenName,:uuid" + // etc. ")" ) public abstract int createUser( @UserBinder User user ); 

You can also use the @BindBean annotation, which will automatically search for object fields by the name of the binding parameter (for example, it can match the request placeholder ":userId" with the getUserId() method).

0
source share

All Articles