用JDBI3保留枚举字段的干净方法?

时间:2018-08-24 17:51:35

标签: java enums dropwizard jdbi

我正在使用Dropwizard构建应用程序,并且我希望我的一个持久实体具有一个枚举字段:

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的持久化到数据库中,而不是名称或顺序数?

2 个答案:

答案 0 :(得分:0)

Jdbi 3开箱即用,支持将Enum作为参数类型,但它存储为枚举值的名称。

但是,对于Jdbi本身不支持的数据类型,您可以使用Custom Arguments

您的案例的参数工厂示例为:

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

答案 1 :(得分:0)

这是我想到的解决方案:

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

如果我需要将其用于每个持久性枚举值,那感觉有些漫长...我想它们可以共享一个通用接口,如果可行的话。