How to insert a sequence as a primary key

Hello,
I've set up a sequence on a table in order to allocate sequential primary keys to records as they are written.
My question is, how do I implement this in the code generated by JDeveloper. I've created a business components form to enter the data. What code do I need to add (and where) to implement the sequence.
any help would be appreciated.
Thanks.

Hi Katy,
I'm about to post a HOWTO on this subject.
Hope it helps,
Avrom

Similar Messages

  • Sequences to generate primary keys

    Hi,
    A question on using sequences to generate primary keys. We have a table and in all environments, test, uat, prod, a sequence exists to generate the primary key for the table. This table is a reference table and is not updateable by the users.
    When developing scripts to insert records into the table, the developers are currently not using the sequence but typing in unique numbers so data scripts consist of something like this:
    INSERT INTO EMPLOYEE_GROUP
    (employee_group_id, code, description,...)
    VALUES
    (45,'sdf','sdfsdfsf');
    INSERT INTO EMPLOYEE_GROUP
    (employee_group_id, code, description,...)
    VALUES
    (46,'sdf','sdfsdfsf',...);
    a) Is this normal practice?
    b) Sometimes they are using the sequence to generate the primary key in development but then hardcoding the number in the script so in development the sequence might be at 160, but in the other environments the sequences will still be at one. Is this also normal practice?
    My usual method in developing scripts is to use <seqeunce>.nextval but it's somewhat incompatitble in the current environment.

    You are using a surrogate, or synthetic primary key. For a primary key generated in this way, the value is inconsequential. All that matters is that it is unique and the tables with foreign keys into it, if any, also have that value set properly. But it doesn't matter if the value is 1, 100, 12344, 2222222222, etc. All you care about is the uniqueness.
    If you create the data properly then child records and their parents should be correct in all systems you mention, it's just that the actual value of the key will differ and that's fine. You care about the relationship of the records, not the value of the synthetic keys.

  • How to set two attributes as  a primary key in database ?

    how to set two attributes as a primary key?
    Take COffeesbreak as an example ,
    let's suppose that there are cof_name ,sup_id,price and so on;
    the same cof_name may be suplied by more sup_ids,
    and one sup_id may suply more cof_names.
    so the Primary key should be set the cof_name and sup_id ,
    how to set ?
    (of course that i konw if I set a cof_id,the problem will be easy work out
    but now there are those like above)
    I set that as following:
    create table coffees (cof_name VARCHAR(32) PRIMARY KEY,sup_id INTEGER, PRIMARY KEY,PRICE INTEGER )
    THE database print error :cant add more primary keys!
    thanks in advance

    You can only use the PRIMARY KEY declaration on a column if it is the only Primary Key column.
    Use the PRIMARY KEY constraint statement instead.
    create table coffees (
      cof_name VARCHAR(32),
      sup_id INTEGER,  
      PRICE INTEGER,
      PRIMARY KEY ( cof_name ,sup_id )
    )Dave

  • How do I autogen a value for primary key on inserts

    I'm running 4.0. I am writing an app that maintains distributed database inventory information. All of my tables have surrogate numeric primary keys. I have created several report/form combinations. From the report, I can choose to create a new instance of an object; Server for instance. When I click the "Add Server >" button, the Detail page opens for me to create the new entry. On this page, I need to have the Server_ID autogenerated. I'm thinking something as simple as "Select (max(server_id)+1) from Server" should do. In fact, it looks like it is going to work because the field gets populated correctly. But, when I click the "Create" button on this page I get an error that says the Server_ID is null. Seems like the generated value isn't making it to the INSERT statement.
    On the Page Definition, I have Server_ID set as Display Only and in the Source section for the attribute I have "Only when current value in session state is null" selected and "SQL Query (return single value)" selected with "Select (max(server_id)+1) from Server" in the "Source value or expresssion" field.

    Hi Ken,
    From your description it appears you want the new server ID to be assigned and show on the page prior to collecting the rest of the information, rather than assigning it upon saving the new row. What you're doing will get the next available ID, but what happens if two or more people are entering new servers at once? There's a good chance they'll all get the same next ID.
    Tony's suggestion will ensure the uniqueness of the server ID because it'll get assigned upon saving the row, rather than on display of the page where a user could leave the screen sitting there while others "take" that next ID. You can return the value that the trigger assigns for display - if you're using an Automatic Row Processing process, see the Return Key into Item setting.
    If you're going to stick with your approach and just need to know how to make sure that field is included in the INSERT, you need to create a computation on that item and move your "select max..." there, and then for the server ID item change the Source Used to "Always...", Source Type to Database Column, and specify the column name from the table in the Source Value. The reason is hasn't been working is that field isn't currently mapped to the table column.
    Hope this helps,
    John

  • How to create sequence based (SERIAL) primary key?

    Does anybody know any workaround to modify dictionary table outside Web Dynpro?
    I specify default column value in SQL Studio:
    ALTER TABLE PB_ORGANIZATION COLUMN ORG_ID ADD DEFAULT SERIAL(1)
    Everything is OK, but when I try to insert values in modified table from Web Dinpro EJB application I get the error:
    com.sap.engine.services.ejb.exceptions.
    BaseReliableNoSuchEntityException: The entity does not
    exist in the database. Its value in the cache has to be
    refreshed.
    It seems WebAS keeps some metadata, generated by Web Dynpro, and manual changes in a database table put it out of sync with this metadata.
    I need serial primary keys in my project. Is it possible to solve the above problem?

    I'll better send You entire application. It has Web Service frontend (PhoneBook) which can be used for testing. Method createOrganization() throws the exception.
    No, this error appears in EJB application only.
    BTW, I have even made attempt to replace <default-value>0</default-value> by <default-value>SERIAL(1)</default-value> but it didn't help.

  • How to insert a sequence into a main production

    I am making a production with many sequences.  What is the bext way to insert a sequence into the main production?  I see that I can nest the secondary sequence, but I don't see any way to undo that in the event I want to make changes.
    Thank you for any help.

    Assuming you are on CC:
    Drag the sequence from the Project Window into the main timeline.
    For induvidual clips uncheck this button.

  • How to populate field on page with Primary Key value from previous page

    I am trying to create a patient tracking system for a group of doctors. There is an add patient form based on the Patient table (which has Patient_Id as its primary key) which branches to a pre-operative assessment form. I would like to populate the pre-op assessment Patient_Id field with the Patient_Id generated by the Add Patient page during processing, which comes from the Patient_seq sequence. How can I do this? I have tried using a computation on the Pre-Op Assessment form, but no matter what I put in, the field remains blank.

    Hi,
    If I understand you correctly, once patient record is created you branching to next page (pre-operative assessment form). First create a static hidden item in patient form *:PX_PATIENT_ID_COPY*.
    Create an On submit after computation and validation process in patient form to get the inserted patient_id from patient table. Here is the code -
    SELECT patient_id into :PX_PATIENT_ID_COPY from patient_table where rownum=1
    order by patient_id descI would not use the sequence to get the current value because if the inserted record been deleted from your patient table, sequence current value would not be valid to find that record in patient table.
    Basically when the record been inserted, the process get the value and put into the hidden item.
    Pass the value from the hidden item to the next page by setting them in page branch. Under the Action section in the page branch, Set this items field type - *:PX_PATIENT_ID* (next page item for patient_id). Type *&PX_PATIENT_ID_COPY.* in the with these values field. Make sure you include dot(.) after *&PX_PATIENT_ID_COPY*.
    Give it a try now. Hope it would helps.
    Regards,
    Tajuddin
    Blog: http://aspblog.whitepagesbd.com
    web: http://tajuddin.whitepagesbd.com

  • How do I add a record's primary key to a query string and add that to an .xml catalog?

    Hello everyone,
    I am using Dreamweaver CS3 on a MacBook Pro Leopard 10.5.6 and MAMP 1.7. I am also teaching myself how to work with PHP and MySQL, using David Powers book The Essential Guide to Dreamweaver CS3.
    I am trying to create a wedding photography web site, with a personal page after login, which will display the photographs of the customers wedding.
    The same page will also be a catalog/shopping cart, so the customer can choose which photo's they want, and pay for them. (I am aware that there are instructions in The Essential Guide in chapter 15 page 515, on how to redirect to a personal page, but it doesn't fully cover what I am asking).
    I have already created the login success page, which greets users by name, as per the instructions in The Essential Guide. I have also created a catalog page. However my catalog page is not calling information from the database, instead it is taking information from an XML page using PHP.
    I would like to insert a list menu on the login success page, which lists the customers name, and when they select their name they will then select a link that will take them to a personal page with just their wedding photographs.
    I am unsure of how to pass the customer_id, in what will be the username list menu, to the page which will contain the customers set of wedding images.
    Is it the same process used in chapter 14 where you add a record's primary key to a query string?
    I am asking because when I set up a recordset from the MySQL database it lists the images as witten names not actual images, I have tried calling the images with PHP code but it just doesn't work.
    The catalog page I have set up at the moment is not calling the images from the database, but directly from the image folder.
    Is what I am trying to do possible?
    If so how do I pass the customer_id and username to a recordset and link that recordset to the xml catalog so the customers personal wedding images are displayed on the catalog page for the shopping cart?  I need step by step instructions, or maybe a link to a good tutorial.
    Can somebody help me please?
    Thankyou.

    QuickTime 7 can set the poster frame, but I've not had much success with it. This is what QuickTime 7 Help says about this topic:
    +A "poster frame" is a still image of a movie that represents the movie in places like the Finder. The default poster frame is the first frame in the movie. You can change the poster frame.+
    +To change a movie's poster frame:+
    +In QuickTime Player 7, drag the playhead (or use the arrow keys to move the playhead) to the desired frame.+
    +Choose View > Set Poster Frame.+
    +To view a movie's poster frame, choose View > "Go to Poster Frame."+
    If you don't have QuickTime 7 (version 7.6.6) it can be installed from your Snow Leopard disc using a custom install. Otherwise download it from this Apple site: http://support.apple.com/kb/DL923
    John

  • How to get the auto increment integer primary key value of a new record

    I have a DB table that has a auto increment integer primary key, if I insert a new record into it by SQL statement "INSERT INTO...", how can I get the integer primary key value of that newly created record?

    Well maybe someone knows a better method, but one workaround would be to add a dummy field to your table. When a new record is inserted this dummy field will be null. Then you can select your record with SELECT keyField FROM yourTable WHERE dummyField IS NULL. Once you've got the key number, you then update the record with a non-null value in the dummyField. Bit of a bodge, but it should work...
    Another alternative is, instead of using an Autonumbered key field, you could assign your own number by getting the MAX value of the existing keys (with SELECT MAX(keyField) FROM yourTable) and using that number + 1 for your new key. Might be a problem if you have lots of records and frequent deletions though.

  • How to persist an entity with Composite primary key

    Problem Statement:-
    Entity A have many to one relation with Entity C
    Entity B have many to one relation with Entity C
    Entity C have a composite primary key of (Entity A PK & Entity B PK)
    A --< C
    B --< C
    the entites are automatic generated by Dali tool
    @Entity
    public class C implements Serializable
         @EmbeddedId
         private C.PK pk;
         private int attribute;
         //Code
         @Embeddable
         public static class PK implements Serializable
              public int A_Id;
              public int B_Id;
              //Code
    @Entity
    public class A implements Serializable
         @Id
         private int AId;
         @OneToMany
         private Set<C> C_Collection;
         //Code
    @Entity
    public class B implements Serializable
         @Id
         private int BId;
         @OneToMany
         private Set<C> C_Collection;
         //Code
    i made a session Bean which add a new entity C
    Session
         A a = em.find(A.class, AId);
         B b = em.find(B.class, BId);
         C c = new C();
         C.PK pk = new C.PK();
         pk.AId(a.getID());
         pk.BId(b.getID());
         c.setPk(pk);
         c.setA(a);
         c.setB(b);
         c.setAttribute(12);
         em.persist(c);
    when running this code an exception is raised
    Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2006.8 (Build 060830)): oracle.toplink.essentials.exceptions.DatabaseException
    Internal Exception: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown column 'A_ID' in 'field list'Error Code: 1054
    Call:INSERT INTO C (attribute, Aid, A_ID, B_ID, Bid) VALUES (?, ?, ?, ?, ?)
         bind => [2, 6, 6, 1, 1]
    this is logic as Table "C" has only 3 coloumns only "attribute" , "Aid" , "Bid"
    but the mapping is different as it adds the composite PK attributes to the insert statement
    if there is a sample code or how to solve this issue it would be great

    Hello Juwen,
    The problem is you are registering an object, assigning it a null pk, and then commiting the uow/transaction. TopLink uses registered objects to keep track of changes you make inorder to persist those changes on commit. So the simple fix is to not commit the UnitOfWork - call release() on it instead.
    Another solution is to use the session copyObject api. The simple form that only takes an object will work similar to registering the object as it will copy all persistent attributes but it will leave the primary key null. You can also use this method to specify a copyPolicy to customize the process. Using this method will be a bit more efficient, since a UOW makes both a working copy and a back up copy of objects registered, inorder to keep track of changes. Using the copyObject api will only make a single copy.
    Best Regards,
    Chris

  • How can I see all references to primary key

    How can I make a query for my primary key to see the detail foreign keys and see which key is not available?

    select a.table_name, a.constraint_name, b.table_name as Ref_Table, b.constraint_name as Ref_Constraint
    From ALL_CONSTRAINTS a, ALL_CONSTRAINTS b
    where a.r_constraint_name = b.constraint_name
    and a.constraint_type = 'R'
    and b.table_name = 'TABLE_NAME';
    OR, more exactly:
    select a.table_name, a.constraint_name, b.table_name as Ref_Table, b.constraint_name as Ref_Constraint
    From ALL_CONSTRAINTS a, ALL_CONSTRAINTS b
    where a.r_constraint_name = b.constraint_name
    and a.constraint_type = 'R'
    and b.constraint_type = 'P'
    and b.table_name = 'TABLE_NAME';
    null

  • HOW TO  GET COUNT IN OF COMPOSITE PRIMARY KEYS USING ECLIPSELINK

    Hi all,
    We are currently migrating our application form oracle 10g to 11 g and hence migrating from toplink to eclipselink.
    we are unable to fire the count query and getting the following exception ...
    Error Code: 909
    Call: SELECT COUNT() FROM T_USER_MESSAGE t0, T_USER t2, T_MESSAGE_RECIPIENT t1 WHERE ((((t2.PERSISTENT_ID = ?) AND (t2.SITE_CODE = ?)) AND (t1.DELETED_BY_RECIPIENT = ?)) AND (((t2.PERSISTENT_ID = t1.RECIPIENT_ID) AND (t2.SITE_CODE = t1.RECIPIENT_SITE)) AND ((t0.PERSISTENT_ID = t1.MESSAGE_ID) AND (t0.SITE_CODE = t1.MESSAGE_SITE))))
         bind => [13398610, 1, F]
    please advise .
    we suspect that this could be because of the composite primary key in one of the tables .
    any pointers to specify how count(*) could be used in this scenario would be of great help ..
    Thanks in advance

    What is the query being used, include the JPQL/expression code.
    What is the error message (I assume this is a database error?).
    What version are you using, can you try the latest EclipseLink 2.1 release.
    James : http://www.eclipselink.org

  • How do I let user enter a primary key value on a form

    I'm creating my first APEX application. I have a simple table called HOSTS with 2 columns HOSTNAME and IP_ADDRESS. HOSTNAME is the primary key for the table. HOSTNAME is a perfectly acceptable primary key and I don’t wish to create an additional column to be populated by a sequence.
    What are my options for creating a form on the table without using "Existing trigger", "Custom PL/SQL function" or "Existing Sequence" to populate the primary key column, i.e. HOSTNAME, so that the user can enter a value for the primary key?
    Any assistance greatly appreciated.
    Gavin

    The debate about natural keys versus surrogate keys
    will no doubt continue with advocates for both sides.
    However there is also a difference between
    'making your life easier' for APEX development and
    'making your life more difficult' by having to
    analyse, implement and deploy a surrogate key only
    approach to an existing database which employs both
    natural keys and surrogate keys.
    hould we be forced to change the database design
    because a development tool does not cater for natural
    primary keys?The application development product is TRYING to save you from shooting yourself in the foot. The idea is to separate the primary key from being accessed by the user or ANY carbon based unit.. The key is mainly used by the system to join and lookup data rows, not for people to change whenever they decide that the key is WRONG.
    Think about this, if you use Last Name as a key in your system (a bad idea to begin with since this is NOT a unique id when you have two Smiths). When a person needs to change this because Jimmy Smith is NOT the only Smith working for Acme Toys, you have to cascade that change through all the child tables related to the main person table.
    If instead you use a system generated key, no change will be required since the key has NO relation to the data other than it represents a pointer to that row of data.
    Works for me, since I do not want to write all the supporting code when APEX builds it for you...
    Thank you,
    Tony Miller
    UTMB/EHN

  • Insert record and return the primary key

    Okay, I need to insert a record into a MSSQL database and return the primary key of that record. Im using the following code which is obviously wrong as I'm getting either 'NULL' or 'com.microsoft.jdbc.base.BaseResultSet@1d520c4' returned depending on the ways I've tried. The primary key is an int value called clientID which is incremented by one each time a new record is added.
    // set the prepared statement
                String sql="INSERT INTO Client(username, country, clientIP, browser, os) VALUES(?,?,?,?,?)";
                PreparedStatement pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, inUserName);
                pstmt.setString(2, inCountry);
                pstmt.setString(3, inClientIP);
                pstmt.setString(4, inBrowser);
                pstmt.setString(5, inOS);
                // Insert the row
                pstmt.executeUpdate();
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT SCOPE_IDENTITY()");
                System.out.println("Result "+rs);The primary key value is needed so that it can be used as a foregin key in another table. Am I going about this the correct way? Any help, pointers or code fixing would be appreciated.....

    Yes. I tried this way but I only ever get the answer
    of 0 when i print our the result! Not really sure
    whats happening.That's because you don't print a ResultSet like that. In order to get the key out, you have to do this:
    int key = 0;
    while (rs.next())
        key = rs.getInt(1);What were you thinking with your code?
    You might want to do this in a transaction. If the INSERT fails, you'll want to roll back.
    The "select @@identity" is correct for M$ Access, SQL Server, and Sybase. I believe it's also correct for MySQL, but I'm not 100% certain of that.
    %

  • Does JDBC insert a value into the Primary Key?

    Hi,
    I'm using a servlet to input data froma n html form ,into an ACCESS Database.I'm using SQL statements i t he servlet ,and i'm confronted with the question:
    ALL database records are indexed with B_ID as the "Primary Key".
    I want to know: If I add the fields without a B_ID ..will SQL/JDBC/Access automatically add one for me?
    Or must I create the system that will count the records before adding a new B_ID?
    Hope you can help me.Thanks!
    Aesh83

    Access has a datatype claus for this autoincrement feature.
    I just can't remember its name.
    If you have such a primary key column in your table, you would simply insert values in each column except that, so this would automatically generate its value by incrementing the key.
    Your INSERT had to enumerate all columns you explicitely fill with values and skip this key column and those ones which shall be set to NULL btw. the defined default value (is there a DEFAULT clause in Access?)

Maybe you are looking for

  • Throwing error in PR User Exit even after Error is corrected

    Hi all, I have created a User Exit in Purchase Requisition in which User Write a Dept Code in PR Header and against that Dept Code only those User ID can create a PR whose ID and Dept code are inserted in Z table. When I write a Dept code in PR Heade

  • Lost wireless connection with mx860

    i lost my wireless connection with my mx860 - please help, i have tried it all thank you

  • How to remove focus from a Ring Control in a PDA application?

    Hello,     In a PDA application, i have observed that when we select a pull-down Ring control, the focus is retained in the control and the text of the control appears highlighted. The only way out is to tap an empty portion of the PDA application sc

  • FCC sender Conversion

    Hi, I have a source file like this. "5000010234123","100026","3120","Test for Material Description", The conversion happens fine in the xml, but the only problem is that the beginning field and end field gets accommodated with double quotes Look at m

  • ATV Not Showing in iTunes - Solution?

    I was just reading this, I have never had the problem, but maybe this could help some of the posters with this issue? http://www.macosxhints.com/article.php?story=20080825103711292 Brian.