java – jdbi BindBean bean的用户定义属性(嵌套对象)
作者:互联网
我有一个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的成员?
解决方法:
你可以在这里实现your own Bind-annotation.我实施了一个我正在采用的答案.它会解开所有类型的.
我认为可以通过更多工作使其完全通用.
您的代码看起来像这样(请注意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);
}
}
};
}
}
}
标签:java,jdbi 来源: https://codeday.me/bug/20190519/1137259.html