10

JDBI 是否支持通过注解绑定枚举类型?

例如,假设一个包含方法的 DAO:

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

并且,foo等于Foo.BAR,我可以期待一个查询:

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

如果是这样,是toString()用来确定什么是替代的?

此外,JDBI 是否允许@Bind与任何扩展的类型一起使用Object?再次,如果是这样,toString()使用?

4

2 回答 2

10

根据源代码 Enum.name()是使用的,不是toString()

如果绑定了一个对象,jdbi 将使用setObject(Object object)您正在使用的 jdbc 驱动程序。Map例如,在我使用 PostgreSQL 的经验中,它成功地将shstore和数组绑定到 postgreSQL arrays,因为这就是 PostgreSQL 的 jdbc 驱动程序所做的。

如果您想以特定方式处理特定类型的对象,您可以实现ArgumentFactorys (似乎没有文档,但Stack Overflow中有一个示例)或BinderFactory s(我现在刚刚发现。)

于 2015-04-29T22:17:17.497 回答
1

要解决您的“任意类型”问题,您可以实现 aBinderFactory以绑定到您想要的任何东西。

@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.
                }
            };
        }
    }
}

如果您有想要以特定方式存储的复杂类型,例如二进制数据,或者您想要转换为 CSV 或仅存储在单独的映射表中的集合,这将非常有用。然后你像这样使用你的新花式活页夹:

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

你也可以使用@BindBean注解,它会通过绑定参数名自动查找对象上的字段(例如,它可以将查询占位符映射":userId"getUserId()方法)。

于 2015-06-23T15:19:12.703 回答