在Java中将枚举字段添加到Oracle DB

时间:2017-11-17 17:49:15

标签: java database oracle enums

我有一个枚举

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

这个枚举类型是我的实体的一个字段

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

我要做的是将该实体插入数据库。

 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')))"
        );

但是这种方式不起作用,因为它将valus作为布尔值。 `

有没有其他方法可以将带枚举类型的字段插入Oracle DB?

1 个答案:

答案 0 :(得分:0)

我建议你将db中的枚举存储为int并在代码中使用以下模式:

public interface HasIntId {
    int getId();
}

和枚举HourEmployeePositionType将是:

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