Announcement Announcement Module
Collapse
No announcement yet.
Enums with parameters Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Enums with parameters

    For mapping enums to the database, I'm not satisfied with the JPA options. Saving the ordinal value seems like a bad idea, and the string value only slightly better. Unfortunately, since JPA2 doesn't give us a standard way to use an alternate value, I'm looking for feedback on what the best solution would be.

    I'm thinking the resulting code would follow this pattern:
    Code:
    public enum Sex{
    
          MALE(1),
          FEMALE(2);
    
          private int value;
    
          Sex(int value) {
              this.value = value;
          }
    
          // the identifierMethod
          public int toInt() {
            return value;
          }
    
           // the valueOfMethod
           public  static Sex fromInt(int value) {    
               switch(value) {
                   case 1: return MALE;
                   case 2: return FEMALE;
                   default:
                           return UNKNOW;
               }
          }
         
          public String toString() {
            switch(this) {
              case MALE:
                  return "Male";
              case FEMALE:
                  return "Female";
            }
          }
      }
    1) Change the enum generation code to allow args/arg types to be passed in. The args would be optional.

    2) Create an addon (complexenum?) to implement this functionality.

    The other part to this is changing entity fields that are enums to be annotated with the provider-specific annotations (UserType for Hibernate) to supply the conversion class.

    Has anyone looked at this already?

  • #2
    Any ideas on how to best implement something like this?

    One approach I tried was to create a new plugin that allowed params to be passed into the enum constructor. That works. However, creating the additional methods is problematic. The methods need to change each time a new enum constant is added, but I don't see a way to modify methods in the enum. JavaParserMutableClassOrInterfaceTypeDetails will allow you to add and remove fields but the methods are immutable.

    So, seems like a good candidate for an ITD, except enums don't support that in the current AspectJ (1.6.9) as far as I can tell.

    Comment

    Working...
    X