【问题标题】:Enum saving in Hibernate在休眠中保存枚举
【发布时间】:2014-01-16 17:11:17
【问题描述】:

我正在尝试将 Enum 字段保存到数据库,但在将字段映射到数据库时遇到问题。我的代码如下:

public enum InvoiceStatus {
PAID,
UNPAID;
}

我在我的一个应用程序类中使用这个枚举,如下所示:

public class Invoice {

Enumerated(EnumType.ORDINAL)
@Column(name="INVOICE_STATUS", nullable = false, unique=false)
private InvoiceStatus invoiceStatus;

}

最后,我让应用用户使用下拉菜单从视图 (JSP) 中选择发票状态。

但我不确定如何将从下拉菜单选择中收到的值映射到发票状态字段

我尝试如下将收到的值映射为short,但它不会编译

invoice.setInvoiceStatus(Short.parseShort(request.getParameter("inbStatus")));

有人可以告诉我如何将从视图接收到的数据映射到枚举字段吗?

【问题讨论】:

  • 这取决于您在网页端输入中用作value 的内容......!

标签: java hibernate enums


【解决方案1】:

枚举序数值是从零开始的索引。在你的情况下:

PAID = 0
UNPAID = 1

所以下面的代码会返回PAID

int invoiceStatus = 0;
invoice.setInvoiceStatus(InvoiceStatus.values()[invoiceStatus]);

以下代码将返回UNPAID

int invoiceStatus = 1;
invoice.setInvoiceStatus(InvoiceStatus.values()[invoiceStatus]);

这意味着你应该可以这样做:

short invoiceStatus = Short.parseShort(request.getParameter("inbStatus"));
invoice.setInvoiceStatus(InvoiceStatus.values()[invoiceStatus]);

如果inbStatus01。您应该始终验证用户输入的 null 值和无效值。

【讨论】:

    【解决方案2】:

    我看到你正在使用

    Enumerated(EnumType.ORDINAL)
    

    但是,如果您的枚举会增长,那么在一段时间后可能很难排除故障。序数的另一个问题是您可以重构代码并更改枚举值的顺序,然后您可能会遇到麻烦。主要是如果它是一个共享代码库,并且有人只是决定清理代码并“将相关的枚举常量组合在一起”。如果你会使用:

    Enumerated(EnumType.STRING)
    

    直接将枚举“名称”插入数据库。 (因此您需要 Varchar 类型)。如果您想呈现更用户友好的枚举版本,您可能有:

    public enum InvoiceStatus {
        PAID(0, "Paid"), UNPAID(1, "Unpaid"), FAILED(2, "Failed"), PENDING(3, "Pending");
    
        private int st;
        private in uiLabel;
    
        private InvoiceStatus(int st, String uiLabel){
            this.st = st;
            this.uiLabel = uiLabel;
        }
    
        private Map<String, InvoiceStatus> uiLabelMap = new HashMap<String, InvoiceStatus> ();
    
        static {
          for(InvoiceStatus status : values()) {
            uiLableMap.put(status.getUiLabel(), status);
          }
        }
    
        /** Returns the appropriate enum based on the String representation used in ui forms */
        public InvoiceStatus fromUiLabel(String uiLabel) {
          return uiLableMap.get(uiLabel); // plus some tweaks (null check or whatever)
        }
    
           //
           // Same logic for the ORDINAL if you are keen to use it
           //
    
    }
    

    也许这也可以解决您的问题,但是我真的不会使用基于 ORDINAL 的映射。不过只是个人感觉。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      • 1970-01-01
      • 2011-10-01
      • 1970-01-01
      相关资源
      最近更新 更多