Using Spring JDBC, what is the right way to convert an enum to and from a custom value?

Viewed 482

I have an enum with custom integer values mapped to each enum because the orders may change often so I can't rely on the ordinal. I see similar questions specific to JPA/Hibernate (this is the exact scenario I have: Map enum in JPA with fixed values?), but we are only using JDBC templates in my project so there is no JPA/Hibernate integration.

I can create a RowMapper and set the enum manually, but I wanted to avoid doing so because the default behavior for all of the other columns is correct. I was able to write the value from the enum by overriding setTypeValue on the enum class, but I'm not sure what the equivalent would be for doing this on read.

Example (from copied question):

  public enum Right {
      READ(100), WRITE(200), EDITOR (300);

      private int value;

      Right(int value) { this.value = value; }

      public int getValue() { return value; }
  };

I want to be able to use getValue() to set the value in the database and to read it back and map it to the enum (e.g., "200" in the DB needs to map to Right.WRITE

1 Answers

As for now, AFAIK, it is not possible. Also spring official doc on sping-data-jdbc said that enums get mapped on their names. There is an issue btw to implement this kind of feature, but on current spring-data-jdbc version, which is 2.3.0, I do not know any ways you can do it somehow decoratively (I assume this is what you actually wanted), i.e. annotations.

Related