gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 20:01:28 27 4
gpt4 key购买 nike

我有一个bean类

public class Group{string name;Type type; }

还有一个 bean

public class Type{String name;}

现在,我想使用jdbi @BindBean 绑定(bind)组

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

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

最佳答案

你可以实现 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);
}


}
};
}
}
}

关于java - jdbi BindBean 用户定义的 bean 属性(嵌套对象),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31029747/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com