Jdbi BindBean userdefined bean property (nested object)

I have a bean class

public class Group{string name;Type type; }

      

and another bean

public class Type{String name;}

      

Now I want to bind a group using 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);

      

How can I bind a user-defined property of an object as a member of a bean ??

+3


source to share


2 answers


You can implement your own Bind annotation here . I have implemented the one I am taking for this answer. He unfolds everything Type

.

I think it can be done completely generic with a little more work.

Your code will look like this (note what m.type.name

changed to m.type

):



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

      

This will be an annotation:

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


                }
            };
        }
    }
}

      

+3


source


Doing this in JDBI is not possible, you need to infer the property and give an argument.



+1


source







All Articles