2010-05-01 63 views
0

我有一个实体整数属性,看起来像这样在原代码如何处理选择字段JPA 2,Hibernate的3.5

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 

*根据此表,获取**存取器返回字符串。

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的一些属性是特殊的,以便它可以产生获得*访问者按照。

编辑:增加了如何在代码提交选择

编辑:我存储在数据库中的唯一的事情是整数,当我想打印出来,他们应该以某种方式转化为自己的可读的字符串。

+0

你可以改变什么?你可以使用枚举吗?哪些部件必须是动态的?数据库中存储哪些部分? – 2010-05-01 17:28:14

+0

我不知道动态Java是否存在,我会添加一些关于如何将它写入的信息。也许枚举是好的,但我应该如何使用它们? – amirouche 2010-05-01 18:20:43

+0

我不是指动态Java,而是指动态值(例如,无需重新编译代码即可添加新许可证)。 – 2010-05-01 19:56:38

回答

1

你可以有更多的信息在枚举:

public enum License { 

    GPL("GPL"), 

    APACHE("Apache License"); 

    public License(String displayName) { 
     this.displayName=displayName; 
    } 

    String displayName; 

} 

附加功能的要求,但有其功能已经由枚举类提供的密切关注。

0

你可以做到这一点,没有任何麻烦(但要注意的是,在DB中的值将是ordinal()值的枚举所以:。

public enum License { GPL, APACHE, BSD } 

FrequencyChoices可能进入一个@ElementCollection

如果您需要人类可读的值,您可能希望将您的Enum转换为普通类,并将其作为单独的表保存,以便您可以更容易地将新许可证添加到列表中...

@Entity 
public class License { 
    @Id long id; 
    String name; 
}