Vlad Demyan
Vlad Demyan

Reputation: 363

Add enum field to Oracle DB in Java

I have an enum

public enum HourEmployeePOSITION_TYPE {
None,Cleaner,Waiter, Barmen, Barback, HeadWaiter, Manager, Assistant_Manager,General_Manager}

And this enum type is one of the fields of my entity`

 public class 
    HourEmployeeEntities {
    private int id;
    private String firstName;
    private String lastName;
    private HourEmployeePOSITION_TYPE position;

What I'm trying to do is insert that entity to databse.

 connection = createConnection();
 statement = connection.createStatement();
 statement.execute("CREATE TABLE Employees(" +
                "id int," +
                " firstName varchar(60)," +
                " lastName varchar(60)," +
                " position varchar(60) not null check (position in ('None', 'Cleaner', 'Waiter', 'Barmen', 'Barback', 'HeadWaiter')))"
        );

But this way is not working, as it takes the valus as boolean. `

Are there any other ways to insert my field with enum type into the Oracle DB?

Upvotes: 0

Views: 1657

Answers (1)

yanefedor
yanefedor

Reputation: 2262

I suggest you to store enum in db as int and use following pattern in your code:

public interface HasIntId {
    int getId();
}

and enum HourEmployeePositionType will be:

public enum HourEmployeePositionType implements HasIntId {

    None(0),
    Cleaner(1),
    Waiter(2),
    Barmen(3),
    Barback(4),
    HeadWaiter(5),
    Manager(6),
    Assistant_Manager(7),
    General_Manager(8);

    private final int id;

    HourEmployeePositionType(int id) {
        this.id = id;
    }

    @Override
    public int getId() {
        return id;
    }

    public static HourEmployeePositionType getById(int id) {
         for (HourEmployeePositionType employeePositionType : HourEmployeePositionType.values()) {
             if (employeePositionType.getId == id) {
                 return employeePositionType;
             }
         }
         return HourEmployeePositionType.None;
    }
}

Upvotes: 1

Related Questions