簡體   English   中英

如何從數據庫(java)讀取的字符串中為實體設置枚舉屬性?

[英]How can I set an enum attribute in my entity from a string read from a database (java)?

我正在從數據庫中讀取數據,該數據庫的“ BUY_SELL”列的值為“ BUY”或“ SELL”

在Java中,我已將此屬性制成一個枚舉,稱為RequestType。 在下面的代碼行中,我試圖將我的實體屬性設置為從數據庫列中讀取的值,但是我不確定如何將字符串輸入為枚舉類型。

似乎沒有適合的結果集.method

 req.setRequestType(rs.getString("BUY_SELL")); //The method setRequestType(RequestType) in the type Request is not applicable for the arguments (String)

嘗試

RequestType reqType = RequestType.valueOf(rs.getString("BUY_SELL"));
req.setRequestType(reqType);

我假設BUY和SELL作為Enum的有效值存在,即:

public enum RequestType { BUY, SELL }

您可以將枚舉更改為:

public enum RequestTypeEnum {
    BUY("BUY"), SELL("SELL"),BUY_SELL("BUY_SELL");

  private String text;

  RequestTypeEnum(String text) {
    this.text = text;
  }

  public String getText() {
    return this.text;
  }
  public static RequestTypeEnum fromString(String text) {
    if (text != null) {
      for (RequestTypeEnum req : RequestTypeEnum.values()) {
        if (text.equalsIgnoreCase(req.text)) {
          return req;
        }
      }
    }
    throw new RuntimeException("Invalid String!!");
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM