如何使用java在sql中使用ENUM类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19741590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:51:28  来源:igfitidea点击:

How to work with ENUM types in sql with java

javamysqlenums

提问by Reshad

Hello I have one field for STATUS in the database as a enum type.

您好,我在数据库中有一个 STATUS 字段作为枚举类型。

But how do I create the setters for this? as String, INT or the "Java Enum"

但是我如何为此创建设置器?作为字符串、INT 或“Java 枚举”

something like this

像这样的东西

public enum getStatus() {
    return Status;
}

public void setStatus(enum Status) {
    this.Status = Status;
}

采纳答案by SudoRahul

You need to use the name of the enum as the type for status. Some like this

您需要使用枚举的名称作为status. 有些像这样

enum MyEnum { // Assuming MyEnum is the name of the enum
    // enum values sample below
    ACTIVE, INACTIVE, PENDING
}

Edit:After our discussion, this might suit you more.

编辑:经过我们的讨论,这可能更适合您。

private MyEnum status;

public String getStatus() {
    return this.status.name();
}

public void setStatus(String status) {
    this.status = MyEnum.valueOf(status);
}

回答by arcy

I would see if this suited you:

我会看看这是否适合你:

public enum MyStatus { ACTIVE, INACTIVE, PENDING }

public class OtherClass
{
  private MyStatus status = null;

  /* other code */

  /* when it is time to get a value of status to store in the database: */
  String statusString = status.name();

  /* when it is time to take a string from the database 
   * and translate to the variable */
  status = MyStatus.value(stringFromDatabase);

}

You do have to remember that you cannot eliminate values from the enum in a later version of the program, or you have to remember to eliminate all of them from the database, or you have to catch the resulting exception from valueOf() and do something intelligent with it.

你必须记住,你不能在程序的更高版本中从枚举中删除值,或者你必须记住从数据库中删除所有这些值,或者你必须从 valueOf() 捕获产生的异常并做一些事情智能与它。