一. 使用create语句创建数据表
create table TBL_ORDER -- TBL_ORDER是表名
(
order_id NUMBER(10) not null, -- 主键
customer_id NUMBER(10) not null, -- 外键, 表中存的是id, 类中存的是对象引用
order_type_id NUMBER(10) not null, -- 外键, 表中存的是id, 类中存的是对象引用
project_num VARCHAR2(10), -- 以下是普通字段
project_name VARCHAR2(30),
st_time VARCHAR2(20), not null, -- 非空约束
en_time VARCHAR2(20), not null,
cycle FLOAT default 0, -- 设置默认值
amount FLOAT default 0,
principal VARCHAR2(20),
state NUMBER(10) default 0,
attachment VARCHAR2(50),
field1 VARCHAR2(30),
field2 VARCHAR2(30),
field3 VARCHAR2(30),
field4 VARCHAR2(30),
field5 VARCHAR2(30),
order_num VARCHAR2(30) not null,
isdelete NUMBER(10) default 0 not null
)
tablespace USERS -- 使用者
pctfree 10 -- 这些参数默认就好
initrans 1
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
二. 添加注释
-- Add comments to the columns
comment on column TBL_ORDER.order_id -- TBL_ORDER.order_id: 表名.字段
is '订单id'; -- 这里写入注释
comment on column TBL_ORDER.customer_id -- 其他字段一样注释
is '客户id';
三. 设定主键
-- Create/Recreate primary, unique and foreign key constraints
alter table TBL_ORDER -- TBL_ORDRE: 表名
add primary key (ORDER_ID) -- ORDER_ID: 主键字段
using index -- 以下参数默认就好
tablespace USERS -- 使用者
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
四. 设定外键
alter table TBL_ORDER -- TBL_ORDER: 存在外键的表的表名
-- FK_ID_CUSTOMER: 自定义, 但一般是FK_外键名倒写, CUSTOMER_ID: 本表(TBL_ORDER)中的外键字段名
add constraint FK_ID_CUSTOMER foreign key (CUSTOMER_ID)
-- TBL_CUSTOMER: 以这个外键为主键的那个表的表名, CUSTOMER_ID: 这个表的主键
references TBL_CUSTOMER (CUSTOMER_ID);
alter table TBL_ORDER -- 同上
add constraint FK_ID_ORDER_TYPE foreign key (ORDER_TYPE_ID)
references TBL_ORDER_TYPE (ORDER_TYPE_ID);
五. 创建触发器
-- 在ORCLE中, 没有像MYSQL那样, 如插入一条记录, 主键可以自增
-- ORCLE中需要创建触发器, 在每插入一条记录的时候触发, 主键自增
-- SEQ_TBL_ORDER: 自定义, 但这个值要和POJO类中的@SequenceGenerator(sequenceName="SEQ_TBL_ORDER")
-- 这个注解的sequenceName的值一样, start with: 开始值, increment by: 步长, 其他照写
create sequence SEQ_TBL_ORDER start with 1 increment by 1
nomaxvalue
nominvalue
nocache;
-- 什么情况下触发触发器, SEQ_TBL_ORDER: 和上面的值一样
CREATE OR REPLACE TRIGGER SEQ_TBL_ORDER
BEFORE INSERT ON TBL_ORDER -- TBL_ORDER: 针对哪个表, 在插入记录时触发
-- new表示一张临时表, 照写; ORDER_ID表示需要自增的字段, 这里说如果主键为空的情况下插入一条记录就会触发自增
FOR EACH ROW WHEN (new.ORDER_ID is null)
begin
select SEQ_TBL_ORDER.nextval into:new.ORDER_ID from dual; -- 同上, dual是临时表, 照写
end;
-------------------------------<完>-------------------------------