Storing EnumSet in a database?

前端 未结 10 1812
借酒劲吻你
借酒劲吻你 2020-12-03 21:24

So in C++/C# you can create flags enums to hold multiple values, and storing a single meaningful integer in the database is, of course, trivial.

In Java you have Enu

10条回答
  •  借酒劲吻你
    2020-12-03 21:36

    Storing the ordinal as a representation of the EnumSet is not a good idea. The ordinal numbers depend on the order of the definition in the Enum class (a related discussion is here). Your database may be easily broken by a refactoring that changes the order of Enum values or introduces new ones in the middle.

    You have to introduce a stable representation of individual enum values. These can be int values again and represented in the proposed way for the EnumSet.

    Your Enums can implement interfaces so the stable represenation can be directly in the enum value (adapted from Adamski):

    interface Stable{
        int getStableId();
    }
    public enum X implements Stable {
        A(1), B(2);
    
        private int stableId;
    
        X(int id){
            this.stableId = id;
        }
    
        @Override public int getStableId() {
            return stableId;
        }
    }
    

    adapted from Adamski's code:

    public  int encode(EnumSet set) {
      int ret = 0;
    
      for (E val : set) {
        ret |= (1 << val.getStableId());
      }
    
      return ret;
    }
    

提交回复
热议问题