jdbi BindBean bean的用户定义属性(嵌套对象)

时间:2015-06-24 14:45:44

标签: java jdbi

我有一个bean类

public class Group{string name;Type type; }

和另一个豆

public class Type{String name;}

现在,我想使用jdbi @BindBean

来绑定组
@SqlBatch("INSERT INTO (type_id,name) VALUES((SELECT id FROM type WHERE name=:m.type.name),:m.name)")
@BatchChunkSize(100)
int[] insertRewardGroup(@BindBean ("m") Set<Group> groups);

如何将用户定义对象的属性绑定为bean的成员??

2 个答案:

答案 0 :(得分:4)

您可以在此处实施your own Bind-annotation。我实施了一个我正在采用的答案。它将打开所有Type个。

我认为可以通过更多的工作使其完全通用。

您的代码看起来像这样(请注意m.type.name已更改为m.type):

@SqlBatch("INSERT ... WHERE name=:m.type),:m.name)")
@BatchChunkSize(100)
int[] insertRewardGroup(@BindTypeBean ("m") Set<Group> groups);

这将是注释:

@BindingAnnotation(BindTypeBean.SomethingBinderFactory.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface BindTypeBean {
    String value() default "___jdbi_bare___";

    public static class SomethingBinderFactory implements BinderFactory {
        public Binder build(Annotation annotation) {
            return new Binder<BindTypeBean, Object>() {
                public void bind(SQLStatement q, BindTypeBean bind, Object arg) {
                    final String prefix;
                    if ("___jdbi_bare___".equals(bind.value())) {
                        prefix = "";
                    } else {
                        prefix = bind.value() + ".";
                    }

                    try {
                        BeanInfo infos = Introspector.getBeanInfo(arg.getClass());
                        PropertyDescriptor[] props = infos.getPropertyDescriptors();
                        for (PropertyDescriptor prop : props) {
                            Method readMethod = prop.getReadMethod();
                            if (readMethod != null) {
                                Object r = readMethod.invoke(arg);
                                Class<?> c = readMethod.getReturnType();
                                if (prop.getName().equals("type") && r instanceof Type) {
                                    r = ((Type) r).getType();
                                    c = r.getClass();
                                }
                                q.dynamicBind(c, prefix + prop.getName(), r);
                            }
                        }
                    } catch (Exception e) {
                        throw new IllegalStateException("unable to bind bean properties", e);
                    }


                }
            };
        }
    }
}

答案 1 :(得分:1)

在JDBI中执行此操作是不可能的,您必须提取属性并给出一个参数。