我有2张桌子顾客&我的Oracle数据库中的帐户。我有序列号用于为两个表生成代理键值。
CREATE SEQUENCE customers_seq NOCACHE;
CREATE SEQUENCE accounts_seq NOCACHE;
CREATE TABLE customers
(
customer_surrogate_id NUMBER(10),
customer_id VARCHAR2(8) UNIQUE NOT NULL,
customer_password VARCHAR2(20),
customer_name VARCHAR2(20),
customer_pan VARCHAR2(10) UNIQUE,
customer_email_id VARCHAR2(20) UNIQUE,
CONSTRAINT customer_pk
PRIMARY KEY (customer_surrogate_id)
);
CREATE TABLE accounts
(
accounts_surrogate_id NUMBER(10),
account_id VARCHAR2(10) UNIQUE NOT NULL,
customer_surrogate_id NUMBER(10),
account_type VARCHAR2(10),
account_currency VARCHAR2(20),
account_balance NUMBER(20, 2),
CONSTRAINT accounts_pk
PRIMARY KEY (accounts_surrogate_id),
CONSTRAINT accounts_fk
FOREIGN KEY (customer_surrogate_id)
REFERENCES customers(customer_surrogate_id)
);
我知道如何使用sequence_name.NEXTVAL
&插入语句中的sequence_name.CURRVAL
来执行引用
问题在于使用NEXTVAL
& CURRVAL
是假设两个表的插入顺序发生,如
insert into Customers(// use NEXTVAL here)
insert into Accounts(// use CURRVAL here to reference the above row in Customers)
但是在我的java应用程序中,Customers表的多个插入可以在Accounts表中发生一次插入之前发生。 CURRVAL
将返回Customers表的最后一个插入行的值。
在Accounts表中插入行时,我可以在我的应用程序中获取customers_id值。是否应使用customer_id
查询Customers表以获取customer_surrogate_id
,如下所示?
insert into Customers(// use NEXTVAL here)
...
insert into Accounts(// use the customer_id to query and find customer_surrogate_id)
在这种情况下,有没有更好的方法来引用Customers表?
编辑:我正在使用JDBC访问数据库。
答案 0 :(得分:0)
只需选择值,并将其存储在变量中:
long customer1Id = selectNextValueFromSequence("customers_seq");
long customer2Id = selectNextValueFromSequence("customers_seq");
insertCustomerWithId(customer1Id);
insertCustomerWithId(customer2Id);
insertAccountWithCustomerId(customer1Id);
insertAccountWithCustomerId(customer2Id);