2010-05-01 62 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; 
}