首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用JDBI3持久化枚举字段的清洁方法?

使用JDBI3持久化枚举字段的清洁方法?
EN

Stack Overflow用户
提问于 2018-08-24 17:51:34
回答 2查看 1.3K关注 0票数 3

我正在用Dropwizard构建一个应用程序,我希望我的一个持久化实体有一个enum字段:

代码语言:javascript
复制
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的值持久化到数据库,而不是名称或序号?

EN

回答 2

Stack Overflow用户

发布于 2018-08-25 09:57:19

Jdbi 3支持Enum作为参数类型,但它存储为enum值的名称。

但是,您可以将自定义参数用于Jdbi本机不支持的数据类型。

您的案例中的参数工厂示例如下:

代码语言:javascript
复制
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());
        }
    };
  }  
}
票数 0
EN

Stack Overflow用户

发布于 2018-08-28 20:08:27

这是我最后得到的解决方案:

代码语言:javascript
复制
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());
    }
  }
}

如果我需要对每一个持久的枚举值使用它,我想它们都可以共享一个共同的接口,如果可以的话,我觉得有点长。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52009523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档