4

I have a table and want to save the status using a enum. I created a enum as below

/**
 * Enumeration for Status
 * 
 * 
 * Current defined values are :
 * <ul>
 *  <li>ACTIVE = 1</li>
 *  <li>INACTIVE = 2</li>
 * </ul>
 */
public enum Status {

    /**
     * ACTIVE (Ordinal 1).
     */
    ACTIVE(1),

    /**
     * INACTIVE (Ordinal 2).
     */
    INACTIVE(2),



    private int value;

    private Status(int value) {
        this.value = value;
    }



   public static void main (String ars[]){
       for (Status str : Status.values()) {
           System.out.println("====str==========="+str.name() +"::::::: "+str.ordinal());
       }
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }


}

How to I get the ordinal value from 1. My output is like this

====str===========ACTIVE::::::: 0
====str===========INACTIVE::::::: 1

Actually i have mapped this enum to my Entity and i have used it as below

@Column(name = "STATUS",nullable=false)
    @Enumerated(EnumType.ORDINAL)
    private Status status; 

How to i save the Active status as 1 ... ?

1
  • 4
    An enum should never be mutable. You should never have a setXXX method on an enum and an enum should never have non-final variables. Having a mutable enum violates many of the guarantees provided by enum. Commented Mar 19, 2014 at 11:19

3 Answers 3

5

You could override the toString() method of your enum or provide a getter.

public enum Status {

    /**
     * ACTIVE (Ordinal 1).
     */
    ACTIVE(1),

    /**
     * INACTIVE (Ordinal 2).
     */
    INACTIVE(2); // Note the semicolon



    private final int value;

    private Status(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    // OR
    @Override
    public String toString() {
         return String.valueOf(value);
    }
}

Then you can call

System.out.println(ACTIVE); // toString is called

or

System.out.println(ACTIVE.getValue());
Sign up to request clarification or add additional context in comments.

1 Comment

Actually i have mapped this enum to my Entity and i have used it as below
1

Use getValue() instead of ordinal()? ordinal() doesn't magically know to call your method, it just returns the ordinal.

Comments

0

print str.getValue().

ordinal gives you default values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.