【问题标题】:How to handle choice field with JPA 2, Hibernate 3.5如何使用 JPA 2、Hibernate 3.5 处理选择字段
【发布时间】:2011-02-14 13:34:29
【问题描述】:

我有一个具有整数属性的实体,在原型代码中看起来像这样:

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)

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

edit:添加了我想告诉 Java 某些属性是特殊的,以便它可以相应地生成 get* 访问器。

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

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

【问题讨论】:

  • 你能改变什么?你可以使用枚举吗?哪些部分必须是动态的?哪些部分存储在数据库中?
  • 我不知道动态Java是否存在,我将添加一些关于我希望如何编写它的信息。也许枚举很好,但我应该如何使用它们?
  • 我不是指动态 Java,我指的是动态值(例如,无需重新编译代码即可添加新许可证)。

标签: java hibernate orm data-modeling jpa-2.0


【解决方案1】:

您可以在枚举中获得更多信息:

public enum License { 

    GPL("GPL"),

    APACHE("Apache License");

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

    String displayName;

 } 

根据需要添加其他功能,但仔细查看 Enum 类已经提供了哪些功能。

【讨论】:

    【解决方案2】:

    您可以毫不费力地做到这一点(但请注意,数据库中的值将是枚举的ordinal() 值。所以:

    public enum License { GPL, APACHE, BSD }
    

    FrequencyChoices 可以转为@ElementCollection

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

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

    【讨论】:

      【解决方案3】:

      我没有尝试坚持,但你可以尝试关注http://marekhalmo.blogspot.sk/2012/09/cool-java-enums.html

      我会坚持使用枚举。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-12
        • 1970-01-01
        • 2019-09-14
        • 2021-08-07
        相关资源
        最近更新 更多