Reshad
Reshad

Reputation: 2652

How to work with ENUM types in sql with java

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

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

something like this

public enum getStatus() {
    return Status;
}

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

Upvotes: 2

Views: 25662

Answers (2)

arcy
arcy

Reputation: 13123

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.

Upvotes: 1

Rahul
Rahul

Reputation: 45060

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

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);
}

Upvotes: 6

Related Questions