我正在用Dropwizard构建一个应用程序,我希望我的一个持久化实体有一个enum字段:
class DogEntity {
public String name;
public DogType type;
}
enum DogType {
HUSKY("canis lupus familiaris"),
LAB("canus familiaris")
private final String value;
Type(String value) {
this.value = value;
}
}如何使JDBI将DogType的值持久化到数据库,而不是名称或序号?
发布于 2018-08-25 09:57:19
Jdbi 3支持Enum作为参数类型,但它存储为enum值的名称。
但是,您可以将自定义参数用于Jdbi本机不支持的数据类型。
您的案例中的参数工厂示例如下:
public class DogTypeArgumentFactory extends AbstractArgumentFactory<DogType> {
public DogTypeArgumentFactory() {
super(Types.VARCHAR);
}
@Override
public Argument build(final DogType dogType, ConfigRegistry config) {
return new Argument() {
@Override
public void apply(int position, PreparedStatement statement, StatementContext ctx) throws SQLException {
statement.setString(position, dogType.getValue());
}
};
}
}发布于 2018-08-28 20:08:27
这是我最后得到的解决方案:
public class DogTypeArgumentFactory implements ArgumentFactory {
@Override
public Optional<Argument> build(Type type, Object value, ConfigRegistry config) {
if (value == null || !type.getTypeName().equals(DogType.class.getName())) {
return Optional.empty();
}
return Optional.of(new DogTypeArgument((DogType) value));
}
private class DogTypeArgument implements Argument {
private final DogType value;
private DogTypeArgument(DogType value) {
this.value = value;
}
@Override
public void apply(
int position, PreparedStatement statement, StatementContext context) throws SQLException {
statement.setInt(position, value.getValue());
}
}
}如果我需要对每一个持久的枚举值使用它,我想它们都可以共享一个共同的接口,如果可以的话,我觉得有点长。
https://stackoverflow.com/questions/52009523
复制相似问题