2

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.

Musakkhir Sayyed
  • 7,012
  • 13
  • 42
  • 65
Haider Sultan
  • 121
  • 1
  • 8
  • Create a before insert trigger type so it will populate data into role_id. If you need more explanation i will post some sample code. – Tharunkumar Reddy Aug 11 '15 at 05:54
  • 1
    See [How to create id with AUTO_INCREMENT on Oracle](http://stackoverflow.com/questions/11296361/how-to-create-id-with-auto-increment-on-oracle) – obourgain Aug 11 '15 at 05:55
  • @Tarun Thanks for the answer and it helped me a lot, is it going to work if don't specify anything for the field role_id when I am doing it through java program, I have tried through and it is not working for me – Haider Sultan Aug 11 '15 at 06:02

1 Answers1

1

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;
Tharunkumar Reddy
  • 2,773
  • 18
  • 32