如何在oracle数据库中存储具有枚举字段类型的对象

时间:2016-08-05 09:45:48

标签: sql oracle enumeration

我的程序中有以下类,我希望这个类存储在oracle 11c数据库中,我知道如何存储大部分信息但是如何存储类型为enum的usertype?我有以下数据模型方案:

here should be picture

这是mu用户类

public class User {

    @Id
    protected Identity<User> id;

    protected String identifier;

    protected UserType type;

    protected String password;

    public static enum UserType {
        CUSTOMER, COURIER;
    }

}

1 个答案:

答案 0 :(得分:3)

只有两个固定值,最简单的方法是a check constraint

create table users (
  id number primary key,
  identifier varchar2(30),
  password raw(64),
  type varchar2(8) not null check (type in ('CUSTOMER', 'COURIER'))
);

check (type in ('CUSTOMER', 'COURIER'))非常明显; Oracle检查为该列提供的值是否为这两个值之一。假设您希望始终设置它,not null确保它不会被设置为空。

insert into users (id, identifier, password, type)
values (1, 'Bob', null, 'CUSTOMER');

1 row inserted.

insert into users (id, identifier, password, type)
values (2, 'Alice', null, null);

ORA-01400: cannot insert NULL into ("SCHEMA"."USERS"."TYPE")

insert into users (id, identifier, password, type)
values (2, 'Alice', null, 'INVALID');

ORA-02290: check constraint (SCHEMA.SYS_C00113048) violated

使用命名约束会好一点:

create table users (
  id number,
  identifier varchar2(30),
  password raw(64),
  type varchar2(8) not null,
  constraint users_pk primary key (id),
  constraint users_type_ck check (type in ('CUSTOMER', 'COURIER'))
);

更一般地说,特别是对于可以更改的值,您将拥有查找表和外键关系:

create table user_types (
  id number,
  description varchar2(8),
  constraint user_types_pk primary key (id),
  constraint user_types_desc_uk unique (description)
);

create table users (
  id number,
  identifier varchar2(30),
  password raw(64),
  type_id number not null,
  constraint users_pk primary key (id),
  constraint users_type_fk foreign key (type_id) references user_types(id)
);

insert into user_types (id, description) values (1, 'CUSTOMER');
insert into user_types (id, description) values (2, 'COURIER');

insert into users (id, identifier, password, type_id)
values (1, 'Bob', null, 1);

1 row inserted.

insert into users (id, identifier, password, type_id)
values (2, 'Alice', null, null);

ORA-01400: cannot insert NULL into ("SCHEMA"."USERS"."TYPE_ID")

insert into users (id, identifier, password, type_id)
values (2, 'Alice', null, 3);

ORA-02291: integrity constraint (SCHEMA.USERS_TYPE_FK) violated - parent key not found