代码之家  ›  专栏  ›  技术社区  ›  amirouche

如何使用JPA2处理选项字段,Hibernate 3.5

  •  0
  • amirouche  · 技术社区  · 15 年前

    我有一个具有整型属性的实体,在 原型代码 :

    class MyEntity:
        String name
    
        @Choices({1, "BSD", 2, "Apache", 3, "GPL"}
        Integer frequency
    
        @ChoicesSegment({1000, 2000, 3000}, {"BSD", "Apache", "GPL"})
        Integer type
    
        String getFrequency()
               return getChoice("frequency", frequency)
        String getType()
               return getChoice("type", type)
    

    也许这个解决方案更可行:

    class MyEntity:
        String name
    
        final static private Something? frequencyChoices = {1000, 2000, 3000}, {"BSD", "Apache", "GPL"}
        Integer frequency
    
        final static private String[] typeChoices = new String[] {"BSD", "Apache", "GPL"}
        Integer type
    
        @Choices(MyEntity.frequencyChoices)
        String getFrequency()
               return frequency)
    
        @IntervalChoices(MyEntity.typeChoices)
        String getType()
               return type
    

    *get**访问器根据此表返回字符串。

    value(type) HumanReadableString(type)
      1             BSD
      2             Apache
      3             GPL
    
    min frequency         max frequency    HumanReadableString(frequency)
        0                     1000                rare
        1000                  2000              frequent
        2001                  3000                sexy
    

    应该可以获取属性可以采用的所有可能值,例如:

    getChoices(MyEntity, "type") returns ("rare", "frequent", "sexy")
    

    应该可以从字符串中获取绑定值:

    getValue(MyEntity, "frequency", "sexy") returns (2000,3000)
    

    编辑 : 所有这些的目的 这种方法应该简化表单和请求的生成(当然,这不应该是视图实现绑定的)

    编辑 增加了我想告诉Java的一些属性是SP*Suffic,以便它能够生成GET *访问器。

    编辑 :添加了如何在代码中提交选项

    编辑 :我在数据库中存储的唯一东西是整数,当我想打印它们时,它们应该以某种方式转换为人类可读的字符串。

    3 回复  |  直到 12 年前
        1
  •  1
  •   Daniel    15 年前

    您可以在枚举中获得其他信息:

    public enum License { 
    
        GPL("GPL"),
    
        APACHE("Apache License");
    
        public License(String displayName) {
            this.displayName=displayName;
        }
    
        String displayName;
    
     } 
    

    根据需要附加函数,但仔细查看哪些函数已经由枚举类提供。

        2
  •  0
  •   pihentagy    15 年前

    你可以不费吹灰之力地做到这一点(但请注意,db中的值将是 ordinal() 枚举的值。所以:

    public enum License { GPL, APACHE, BSD }
    

    FrequencyChoices 可以进入一个 @ElementCollection

    如果您需要人类可读的值,您可能希望将枚举转换为普通类,并将其作为单独的表持久化,这样您可以更容易地向列表中添加新许可证…

    @Entity
    public class License {
        @Id long id;
        String name;
    }
    
        3
  •  0
  •   Marek Halmo    12 年前

    我没有试图坚持这一点,但你可以尝试跟踪 http://marekhalmo.blogspot.sk/2012/09/cool-java-enums.html

    我会坚持做枚举。

    推荐文章