Referencing Surrogate keys - java

I have 2 tables Customers & Accounts in my Oracle Database. I have sequence numbers for generating surrogate key values for both tables.
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)
);
I know how to use sequence_name.NEXTVAL & sequence_name.CURRVAL in insert statements to perform the reference
The problem is with using NEXTVAL & CURRVAL is that it assumes that inserts to both tables occur sequentially like
insert into Customers(// use NEXTVAL here)
insert into Accounts(// use CURRVAL here to reference the above row in Customers)
But in my java application, the multiple inserts for the Customers table can occur before even one insert occurs in Accounts table. CURRVAL will return the value of the last inserted row of the Customers table.
When inserting a row into Accounts table, I can get customers_id values in my application. Should the customer_id be used to query the Customers table to get the customer_surrogate_id as shown below?
insert into Customers(// use NEXTVAL here)
...
insert into Accounts(// use the customer_id to query and find customer_surrogate_id)
Is there better way to reference the Customers table in this situation?
Edit: I am using JDBC to access the database.

Simply select the value, and store it in a variable:
long customer1Id = selectNextValueFromSequence("customers_seq");
long customer2Id = selectNextValueFromSequence("customers_seq");
insertCustomerWithId(customer1Id);
insertCustomerWithId(customer2Id);
insertAccountWithCustomerId(customer1Id);
insertAccountWithCustomerId(customer2Id);

Related

update UUID column from a select in mysql

I have a 2 tables let's say (Account and Customer) that uses UUID as the primary key without proper relationship, and I am trying to fix appropriately.
The customer_id(not the UUID (PK)) on account is the same thing as the provider_customer_id on customer table,
when I tried to update the account table by setting customer_id as the UUID of the customer table so as to reference the customer table from there with the script below
SET FOREIGN_KEY_CHECKS=0;
ALTER TABLE accounts
MODIFY COLUMN customer_id BINARY(16) NOT NULL;
UPDATE accounts a
INNER JOIN customers c on a.customer_id = c.provider_customer_id
SET a.customer_id = (c.id)
WHERE c.provider_customer_id is not null ;
ALTER TABLE accounts
ADD CONSTRAINT FK_ACCOUNTS_ON_CUSTOMER FOREIGN KEY (customer_id) REFERENCES customers (id);
SET FOREIGN_KEY_CHECKS=1;
mysql updated as expected, but the UUID is totally different from what was in the customer table this was what it was updated to
43313231-3443-4134-0000-000000000000
43313231-3634-3137-0000-000000000000
43313231-3436-4847-0000-000000000000
43313231-3443-4134-0000-000000000000

Oracle sql adding auto incremented field

I have made a table in oracle which uses auto incremented field thorough sequence.
Here is the sql:
CREATE TABLE Users(
user_ID INT NOT NULL,
user_name VARCHAR (20) NOT NULL,
user_password VARCHAR (20) NOT NULL,
user_role INT NOT NULL,
PRIMARY KEY (user_ID)
);
ALTER TABLE Users
ADD FOREIGN KEY (user_role) REFERENCES User_Roles (role_ID);
CREATE SEQUENCE seq_users
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10;
Now I need to insert the data into the table through a java program, is there any way, I don't have to use the query like this:
Insert into User_Roles values (seq_user_roles.nextval,'system admin');
User Role Table:
CREATE TABLE User_Roles(
role_ID INT NOT NULL,
role_name VARCHAR (20) NOT NULL,
PRIMARY KEY (role_ID)
);
CREATE SEQUENCE seq_user_roles
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 10;
I want to insert the data from a java program and can't specify that name of the sequence.
Crete below trigger after sequence creation. So it will populate date into your column. And no need to mention role_id column in you insert statement script.
CREATE OR REPLACE TRIGGER TRG_User_Roles_BRI
BEFORE INSERT
ON User_Roles
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
BEGIN
:NEW.role_ID := seq_user_roles.NEXTVAL;
END;

Java DB How to Insert Values for Foreign Keys into Table Column

I am using java DB database and NetBeans 8.0 for a desktop application
I am also using a PreparedStatement to query the database.
below is the code for creating the tables.
CREATE TABLE ALUMNUS (
ALUMNUA_ID INT NOT NULL PRIMARY KEY
GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
FIRST_NAME VARCHAR (45),
LAST_NAME VARCHAR (45),
OTHER_NAME VARCHAR (100)
);
CREATE TABLE DUES (
ID INT NOT NULL PRIMARY KEY
GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
PAYMENT_YEAR DATE,
AMOUNT DOUBLE,
ALUMNUS_ID INT
);
--FOREIGN KEY
ALTER TABLE APP.DUES
ADD FOREIGN KEY (ALUMNUS_ID) REFERENCES APP.ALUMNUS(ID);
Now I want to insert, delete and update the foreign key values in APP.DUES table. what is the best option; trigger , stored procedure or the preparedstatement?
An example will be good.
If you want to primarily insert into the DUES table, you would use a sub select in SQL. I havent tested it with Java DB, but it basically looks like:
INSERT INTO DUES(PAYMENT_YEAR, AMOUNT,ALUMNUS_ID)
VALUES(2014, 100.0,
(SELECT ALUMNUA_ID from ALUMNUS where ...));
You need to catch the "not found" error case and prepend a INSERT (and need to catch the duplicate case for that as well).
See also: Insert Data Into Tables Linked by Foreign Key

Assign ID number automatically

strSQL = "INSERT INTO emp(NO, EMP_NAME, EMP_TEL)VALUES(088000, 'JIMMY', *****)";
stmt.executeUpdate(strSQL);
I have this statement to insert a new employee into the database.
What if I want the employee NO to be automatically generated by adding 1 to the previous employee NO? How can this be done in JSP?
While not JSP, a possible solution would be to create an auto generated incrementing column (known as an identity column) in the database. Importantly, this avoids the race condition that exists with a solution that retrieves the current maximum and increments it.
MySQL example:
create table emp (
emp_id integer not null auto_increment,
...
);
Apache Derby example:
create table emp (
emp_id integer not null generated always as identity,
...
);
MS SQL Server 2008 R2 example:
create table emp (
emp_id integer not null identity,
...
);
The INSERT statements do not include the emp_id column. See Statement.getGeneratedKeys() for obtaining generated id if required.
Depending of your DB... I give you a mysql example.
create table emp{
NO int unsigned auto_increment,
EMP_NAME varchar(30) not null,
...
}
insert into emp(EMP_NAME,...) values ("Jimmy", ...);
Now you can ask mysql the last inserted id with
LAST_INSERT_ID()
Yes of course, you can do this by setting "employee no" to be unique and A_I (auto_increament) in this column properties
Check database Schema where you are creating table emp with ID int NOT NULL AUTO_INCREMENT
Then update the schema strSQL = "INSERT INTO emp(EMP_NAME, EMP_TEL) VALUES('ABC_NAME', '321321')";
Though it is possible BUT we should not do any logical operation into JSP. Forward all input in Servlet and do there.
There are several way to do.
Some of databases like Oracle has features like sequence, which allows you to increment numbers sequently and operates as atomic.
Set the column (possibly primary key) to auto increment ( database option ), and do not specify that "NO" in your query. That way, the NO column you didn't add will be added by database automatically.
You can get max values from database table and add 1 for new NO, or you can save those latest value even in file, memcached, whatever you want. The problem of this #3 is, if you don't make program to be atomic between GET LATEST VALUE, ADD 1, CALL DATABASE INSERT QUERY, multiple query can have same NO to use. It's OK, however, if NO is primary key since only very first update/insert query will executed and others query will be failed due to primary key unique violation... but problematic in some cases.
You can use the AUTOINCREMENT option on the field NO on the database, or execute a query like SELECT MAX(NO) FROM emp
and get the max value
I think this will be going to solve your doubt in database and use this following query as:
CREATE TABLE:
CREATE TABLE `test` (
`id` INT(5) UNSIGNED NOT NULL AUTO_INCREMENT,
`emp_name` VARCHAR(50) NOT NULL,
`emp_tel` INT(5) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
INSERT TABLE METHOD:1
INSERT INTO test
VALUES (0,jmail,1234567)OR(?,?,?);
INSERT TABLE METHOD:2
INSERT INTO test (id,emp_name,emp_tel)
VALUES (0,jmail,1234567);
If you had any doubt give me comment.
And if your using the sqlyog to use the shortcut.
if your wants this method like following as:
PreparedStatement ps = con.prepareStatement("INSERT INTO test(id,emp_name,emp_tel)
VALUES (0,jmail,1234567)");
ps.executeUpdate();
PreparedStatement ps = con.prepareStatement("INSERT INTO test(id,emp_name,emp_tel)
VALUES (?,?,?)");
ps.setString(1, id );
ps.setString(2, name);
ps.setString(3, tel);
ps.executeUpdate();

Java SQL simple update syntax issue

I have a table named books with bookID, bookName, count , orderCount
i'd like to write an sql query that will update all books.orderCount to books.orderCount+1.
How shall i do that using executeQuery("UPDATE books...."); ?
I'm having troubles with the syntax.
I've tried to search info on the net however most articles are about INSERT or DELETE commands and the only article that was related suggested to retrieve orderCount to Java, update it and then write it back to SQL. if possible i prefer to avoid it as it may cause serious problems (Locks on records are not needed for this task so i can not use them to avoid problems)
this should be pretty straight forward,
UPDATE books
SET orderCount = orderCount + 1
If it's about a primary key:
Also, you can AUTO INCREMENT.
CREATE TABLE Persons
(
P_Id int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id)
)
To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:
ALTER TABLE Persons AUTO_INCREMENT=100
To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column (a unique value will be added automatically):
INSERT INTO Persons (FirstName,LastName)
VALUES ('Lars','Monsen')

Categories

Resources