title: Map enum in JPA with fixed values?
body: <p>I'm looking for the different ways to map an enum using JPA. I especially want to set the integer value of each enum entry and to save only the integer value.</p>
  
  <pre><code>@Entity
  @Table(name = "AUTHORITY_")
  public class Authority implements Serializable {
  
    public enum Right {
        READ(100), WRITE(200), EDITOR (300);
  
        private int value;
  
        Right(int value) { this.value = value; }
  
        public int getValue() { return value; }
    };
  
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "AUTHORITY_ID")
    private Long id;
  
    // the enum to map : 
    private Right right;
  }
  </code></pre>
  
  <p>A simple solution is to use the Enumerated annotation with EnumType.ORDINAL:</p>
  
  <pre><code>@Column(name = "RIGHT")
  @Enumerated(EnumType.ORDINAL)
  private Right right;
  </code></pre>
  
  <p>But in this case JPA maps the enum index (0,1,2) and not the value I want (100,200,300).</p>
  
  <p>Th two solutions I found do not seem simple...</p>
  
  <h2>First Solution</h2>
  
  <p>A solution, <a href="http://forums.java.net/jive/thread.jspa?threadID=32048" rel="noreferrer">proposed here</a>, uses @PrePersist and @PostLoad to convert the enum to an other field and mark the enum field as transient:</p>
  
  <pre><code>@Basic
  private int intValueForAnEnum;
  
  @PrePersist
  void populateDBFields() {
    intValueForAnEnum = right.getValue();
  }
  
  @PostLoad
  void populateTransientFields() {
    right = Right.valueOf(intValueForAnEnum);
  }
  </code></pre>
  
  <h2>Second Solution</h2>
  
  <p>The second solution <a href="http://appfuse.org/display/APF/Java+5+Enums+Persistence+with+Hibernate" rel="noreferrer">proposed here</a> proposed a generic conversion object, but still seems heavy and hibernate-oriented (@Type doesn't seem to exist in Java EE): </p>
  
  <pre><code>@Type(
      type = "org.appfuse.tutorial.commons.hibernate.GenericEnumUserType",
      parameters = {
              @Parameter(
                  name  = "enumClass",                      
                  value = "Authority$Right"),
              @Parameter(
                  name  = "identifierMethod",
                  value = "toInt"),
              @Parameter(
                  name  = "valueOfMethod",
                  value = "fromInt")
              }
  )
  </code></pre>
  
  <h2>Is there any other solutions ?</h2>
  
  <p>I've several ideas in mind but I don't know if they exist in JPA:</p>
  
  <ul>
  <li>use the setter and getter methods of right member of Authority Class when loading and saving the Authority object</li>
  <li>an equivalent idea would be to tell JPA what are the methods of Right enum to convert enum to int and int to enum</li>
  <li>Because I'm using Spring, is there any way to tell JPA to use a specific converter (RightEditor) ?</li>
  </ul>