What to use in jpa from self generated primary key ?

Is it described somewhere what strategy to use with JPA when primary key are self generated by a trigger into the table ?
Thank You

Please see this link http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_Triggers

Similar Messages

  • How to use Oracle DB Sequence to Generate Primary Key Values?

    Dear Members,
    I am using Oracle JDev V 11.1.2.1.0 and Oracle 11g XE Database.
    I have followed the below steps:-
    1/ Created an EmployeesEO
    2/ Created an EmployeesVO
    3/ Created a JSPX Page
    4/ On the JSPX Page I have dragged the EmployeesVO and created it in ADF Table Format.
    On this page when I create a new record, I want to generate employee id automatically based on a sequence which is created in the database of the HR Schema.
    Please let me know how to achieve the above requirement.
    Many thanks in advance.
    Regards.

    check [url http://mjabr.wordpress.com/2011/03/11/make-sequence-number-as-default-value/]Set an attribute’s default value with a sequence number

  • How generate primary key atumatically in jdeveloper 10g

    Hi,
    I am using jdev 10g. I created a fusion web applicaton.
    I am not getting any option to generate primary key from sequence automatically.
    In Jdev11g we can create by trigger easily.
    Please help
    Thanks
    Raj

    Hi Raj,
    Check this link
    [http://download.oracle.com/docs/html/B25947_01/bcentities006.htm#sm0147|http://download.oracle.com/docs/html/B25947_01/bcentities006.htm#sm0147]
    Regards,
    Vikram

  • What is the diffrence between Row id and primary key ?

    dear all
    my question is about creating materialized views parameters (With Rowid and
    With Primary kry)
    my master table contains a primary key
    and i created my materialized view as follow:
    CREATE MATERIALIZED VIEW LV_BULLETIN_MV
    TABLESPACE USERS
    NOCACHE
    LOGGING
    NOCOMPRESS
    NOPARALLEL
    REFRESH FAST ON DEMAND
    WITH PRIMARY KEY
    AS
    SELECT
    BCODE ID, BTYPE BTYPE_ID,
    BDATE THE_DATE,SYMBOL_CODE STOCK_CODE,
    BHEAD DESC_E, BHEADARB DESC_A,
    BMSG TEXT_E, BMSGARB TEXT_A,
    BURL URL, BTIME THE_TIME
    FROM BULLETIN@egid_sefit;
    I need to know is there a diffrence between using (with row id) and (with primary key) on the performance of the query?

    Hi again,
    fast refreshing complex views based on rowids, according to the previous subject.
    (You're example shows that) are not possible.
    Complex remote (replication) snapshots cannot be based on Rowid too.
    for 10.1
    http://download-west.oracle.com/docs/cd/B14117_01/server.101/b10759/statements_6002.htm#sthref5054
    for 10.2
    http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_6002.htm#sthref6873
    So I guess (didn't check it) that this applies ONLY to replication snapshots.
    This is not documented clearly though (documentation bug ?!)
    Documentation states that the following is generally not possible with Rowid MVIEWS:
    Distinct or aggregate functions
    GROUP BY or CONNECT BY clauses
    Subqueries
    Joins
    Set operations
    Rowid materialized views are not eligible for fast refresh after a master table reorganization until a complete refresh has been performed.
    The main purpose of my statements was to try to give a few tips how to avoid common problems with this complex subject, like for example: being able to CREATE an MVIEW with fast refresh clause does not really guarantee that it will refresh fast in the long run (reorganisation, partition changes) if ROWID based, further the rowid mviews have limitations according to the documentation (no group by, no connect by, link see above) plus fast refresh means only to use filter columnns of the mview logs, plus for aggregates you need additional count (*) pseudo columns.
    kind regards
    Karsten

  • 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.

  • Generate  primary key automatically

    Hi, I'd like to know how to generate primary keys automatically with JHeadStart because when I try to make an insert into a table, the page gives me the option of insert the primary key of the register.
    Thanks a lot

    I have a table which have 2 fields, one of those is the primary key, the other is the description.
    I have established the primary key as a DBSequence, but when I try to insert a new record testing the service, appears a negative number in the primary key and instead of that I want to appear the correspondent key, or if doesn't appear the correct value, the insert be done correctly.
    At least I change manually the value if this key, the insert can't be done.

  • Help required to generate primary key sequence

    Hello All,
    I need your help in generating a sequence for primary key in my db table created using java dictionary project in my NWDS 7.3.
    The table column EMPL_ID is a primary and needs to be a sequence. The code in the JPA entity is as below. The underlying database is DB2 on Linux. Kindly help me resolve this issue.
    * The persistent class for the TMP_EMPL_DATA database table.
    @Entity
    @Table(name="TMP_EMPL_DATA")
    public class TmpEmplData implements Serializable {
         private static final long serialVersionUID = 1L;
         @Id
         @SequenceGenerator(name="EMPLID_GENERATOR", sequenceName="EMPID_SEQ", initialValue = 10000, allocationSize = 1)
         @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="EMPLID_GENERATOR")
         @Column(name="EMPL_ID")
         private String _emplId_;
    My bean class contains a public method as follows.
    public TmpEmplData createEmployee(String employeeName, int age, String location)
             TmpEmplData emplData = new TmpEmplData();
             emplData.set_emplName_(employeeName);
             emplData.setAge(age);
             emplData.setLocation(location);
             entityManager.persist(emplData);
             entityManager.find(TmpEmplData.class, emplData.get_emplId_());
             return emplData;
    During execution, i am getting an error as below.
    Caused by: javax.persistence.PersistenceException: The generated SQL statement is not valid for the underlying database platform (platform no. 99). For more details see attached exception. SQL statement is SELECT NEXT VALUE FOR "EMPID_SEQ" FROM ( VALUES (1) )
    at com.sap.engine.services.orpersistence.sqlmapper.mapping.JPASQLMapperImpl.createSequenceIDGeneratorSelectText(JPASQLMapperImpl.java:1239)
    at com.sap.engine.services.orpersistence.entitymanager.CachedJPASQLMapper.createSequenceIDGeneratorSelectText(CachedJPASQLMapper.java:259)
    at com.sap.engine.services.orpersistence.generator.GeneratorFactory.<init>(GeneratorFactory.java:156)
    at com.sap.engine.services.orpersistence.entitymanager.EntityManagerFactoryImpl$MetaDataImpl.<init>(EntityManagerFactoryImpl.java:323)
    at com.sap.engine.services.orpersistence.entitymanager.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:137)
    at com.sap.engine.services.orpersistence.entitymanager.JtaEntityManagerFactoryImpl.<init>(JtaEntityManagerFactoryImpl.java:39)
    at com.sap.engine.services.orpersistence.provider.PersistenceProviderImpl.createJtaEntityManagerFactory(PersistenceProviderImpl.java:251)
    at com.sap.engine.services.orpersistence.provider.PersistenceProviderImpl.createContainerEntityManagerFactory(PersistenceProviderImpl.java:236)
    at com.sap.engine.services.orpersistence.container.EMFInstanceCreator.getEntityManagerFactory(EMFInstanceCreator.java:134)
    at com.sap.engine.services.orpersistence.container.ORPersistenceObjectFactory.getEMF(ORPersistenceObjectFactory.java:300)
    at com.sap.engine.services.orpersistence.container.ORPersistenceObjectFactory.getObjectInstance(ORPersistenceObjectFactory.java:73)
    at com.sap.engine.lib.injection.ReferenceObjectFactory.getObject(ReferenceObjectFactory.java:96)
    at com.sap.engine.lib.injection.FieldInjector.inject(FieldInjector.java:113)
    ... 122 more
    Caused by: com.sap.engine.services.orpersistence.sqlmapper.generate.SQLMappingException: SQL statement is not valid for underlying database platform.
    at com.sap.engine.services.orpersistence.sqlmapper.common.CommonSQLMappingResult.getStatementString(CommonSQLMappingResult.java:237)
    at com.sap.engine.services.orpersistence.sqlmapper.mapping.JPASQLMapperImpl.createSequenceIDGeneratorSelectText(JPASQLMapperImpl.java:1237)
    ... 134 more
    Caused by: com.sap.sql.tree.StringRepresentationFailureException: Cannot represent next value expression as string.
    at com.sap.sql.tree.impl.OpenSqlTextExpert.nextValueExpressionToText(OpenSqlTextExpert.java:185)
    at com.sap.sql.tree.impl.NextValueExpressionBuilderImpl$NextValueExpressionImpl.toSqlTxt(NextValueExpressionBuilderImpl.java:140)
    at com.sap.sql.tree.impl.AbstractSqlTextExpert.selectSublistToText(AbstractSqlTextExpert.java:130)
    at com.sap.sql.tree.impl.SelectSublistImpl.toSqlTxt(SelectSublistImpl.java:150)
    at com.sap.sql.tree.impl.QuerySpecificationImpl.toSqlTxt(QuerySpecificationImpl.java:361)
    at com.sap.sql.tree.impl.SelectStatementImpl.toSqlTxt(SelectStatementImpl.java:139)
    at com.sap.sql.tree.impl.SQLStatementImpl.toSqlString(SQLStatementImpl.java:75)
    at com.sap.engine.services.orpersistence.sqlmapper.common.CommonSQLMappingResult.getStatementString(CommonSQLMappingResult.java:233)
    ... 135 more

    Hi,
    does the sequence exist? SAP JPA does not support creation of sequences, you have to create it manually.
    Maybe SAP JPA also does not support DB2 sequences with "Open SQL" correctly.
    - Tryp to set your data source to "native" or "vendor".
    - Try to turn on oracle compatibility:
    db2set DB2_COMPATIBILITY_VECTOR=ORA
    Regards
    Rolf

  • Master-detail with auto-generated primary key(master)

    Hello,
    I have the following master-detail setup:
    Master - block A primary key is: codeA
    Detail - block B
    codeA is genrated only at commit time and is obtained from a sequence.
    User needs to add detail records. This is easy to do since he has to click on the insert icon on the toolbar. At commit time, use commit_form.
    Prob: the requirements as asked by the client is to add a button (which we will label INSERT DETAIL). When the user click on the button, it opens a window where he can enter the detail info then click on save. This should bring him back to the master-detail form and the record in the detail block is inserted.
    What is the problem here ? since the detail block has the foreign key tied to the master primary key, the window-form (with the call_form) that we opened for the detail entry won't be able to save since at this point we still have not assigned a value for the primary key (and hence a value for the foreign key).
    Possible Suggestions:
    -Use a temp database table to hold the detail record from the second form and use it to transfer values to the detail record in the master-detail
    -Use a global record group
    -We can't use parameter list to pass back these values.
    So my question is:
    What would be the most efficient way to have an insert button on the detail block that would allow the user to have a pop up where he can insert his values and then be brought back to the master-detail.
    Thanks.

    Hello again,
    May be I was not clear enough.
    Scenario 1: We use the master-detail form as is with the default oolbar. In this case, the user can insert the detail records one by one without needing the primary-foreign key value since this is handled by default.
    Once we save the form (commit_form), I use the pre-insert trigger to get the master block primary key generated from the sequence and since the detail block key is copied from this value, both are saved correctly and it is the end of the story.
    Scenario 2: As explained in the initial post, the user will populate the detail records one by one by clicking on the -INSERT DETAIL- button and hence has a window where he can insert the detail info and then be brought back to the master-detail form every time he enters a new detail record.
    The problem here is that I can't generate the primary key for the master block since the client has the following requirement:
    The user can always change his mind and not complete, meaning save the form, his process
    As such, the key should be generated in the last step before Commit.

  • Parameters in Url..how do I use login information to insert the primary key

    Uggg, it is 3 am, I am so tired. Please help.
    I have made a registration page for my site. Hurray it works.
    Login Page. It works
    Protected some pages. Works
    Now I am trying to make a page that the users can go to and update their user information. User name, password, email ect.
    I can get it to prepopulate if I put ?id=3, or someother primary key in the url by hand.....and it does update the data.... but I can't, for the life of me, figure out how to make it use the users login information to get and insert the primary key in the url from the link to the update page.
    I have used the hyperlink box and chose the updateaccount.php file, then went to parameters and selected Name: id Value: I chose id from the dropdown from the data base. This puts in an echo that looks like it should work. NO SUCH LUCK.
    Pleeeese!!! What am I doing wrong.
    I am a total novice. Done a few static sites. So please speak slowly.
    Thanks sooooo much

    I really can´t recommend exposing critical stuff like e.g. the user´s login_id in the URL, because once it´s visible, it can be changed by anyone. Better insert the Session Variable kt_login_id, which will only be availabe on a custom PHP page when inserting...
    <?php session_start(); ?>
    ...on line 1 of this document.
    Cheers,
    Günter

  • Is this good approach for generating Primary Keys ?

    Hi,
    All our EJBs are state less Session Beans.
    We have created a state less Session(name SequenceEJB) for getting Primary Key.
    Thre is a method,
    int getSequenceNumber(String tableName,String fieldName) in SequenceEJB. And the following query is used in the above said method.
    SELECT MAX("+fieldName+") ID FROM "+tableName
    Each EJB will lookup SequenceEJB, and call the above said method for getting sequence number.
    Is this approach sclable ?
    Can we proceed by this approach ?
    Thanks in advance
    Srinivas

    As long as you are in EJB, synchronization won't help you because it is not permitted by the EJB spec.
    If you can go with JDBC 3.0 / Java 1.4, the statement interface supportes generated keys. See http://java.sun.com/j2se/1.4/docs/api/java/sql/Statement.html.
    If you cannot go with JDBC 3.0 / Java 1.4, you can implement the key-generation db-specific (e.g. using oracle sequences for oracle tables, and whatever exists for DB2, SQL Server etc.) That of course requires special support for all databases, but at least you can run your app with different databases.
    Or you can try to do it the following way, using a separate table for the keys.
    ResultSet rs = statement.executeQuery("select id from mySequences");
    oldId = rs.getInt(1);
    newId = oldId + 1
    int updatedRows = statement.executeQuery("update mySequences set id = newId where id = oldId");
    if(updatedRows == 1) {
      // succesful
    } else {
      // not sucessful, somebody else has already retrieve this id; do something like Thread.sleep() and retry
    }This way, the database does the actual synchronization between the processes (each process sees the same data in the tables), and you implement the retry logic.

  • How to obtain automatically generated primary key

    Are there any ways to obtain the value of a primary key which is generated automatically by a server?
    Thanks.

    Are there any ways to obtain the value of a primary
    key which is generated automatically by a server?Yes, if you are using JDBC 3.0 and a driver that supports it.
    You do something like this (from the JDBC getting started guid at http://java.sun.com/j2se/1.4/docs/guide/jdbc/getstart/statement.html#1000569):
    String sql = "INSERT INTO AUTHORS (LAST, FIRST, HOME) VALUES " +
                                                      "'PARKER', 'DOROTHY', 'USA', keyColumn";
    int rows = stmt.executeUpdate(sql,
                                                                    Statement.RETURN_GENERATED_KEYS);
    ResultSet rs = stmt.getGeneratedKeys();
    if (rs.next()) {
            ResultSetMetaData rsmd = rs.getMetaData();
            int colCount = rsmd.getColumnCount();
            do {
                    for (int i = 1; i <= colCount; i++) {
                            String key = rs.getString(i);
                            System.out.println("key " + i + "is " + key);
            while (rs.next();)
    else {
            System.out.println("There are no generated keys.");
    }

  • How to "auto" generate "Primary Key" in custom table?

    Hi Folks,
    Requirement:
    I need a function module or program that can create automatically a primary key.
    Scenario:
    I have a program that creates an entries and save it to a custom table at the same time, but a primary key should always be generated respective to the entries saved.
    Example:
    Material(MATNR) 4001001, Plant(WERKS) XX01, ID[Primary Key-auto generated]
    (I'm thinking of a similar concept/logic on how a unique IDOC number is being generated or how SAP standard creates a unique entry)
    I try to look for any SAP FM that can generate a PK, but there's no luck.
    Thanks.
    Regards,
    Jun

    Hi Keshu and All,
    The links are helpful, however:
    #1. I don't have authorization to create a new object in transaction SNRO, but the way I see the objects in SNRO is just for defining the length(number of characters) for the ranges that will be use if I'm not mistaken.
    #2. FM NUMBER_GET_NEXT - yes it can populate incremental unique entries but it's only occurring at runtime ?? So when the program get terminated it's not being saved nowhere.
    So after if I use FM NUMBER_GET_NEXT, I always have to look for all the last primary key in my custom table, then target it as my starting point for creating a new PK.  I think this will give a performance issue, any comments?
    For better visualization, I have scenario:
    1.  (ZQ_CREATE_PK) Create unique incremental PK for material, batch, so on..
    2.  Append line/entries to ZQ_TABLE
    3.  Repeat #1 and #2
    4.  User exits the program
    5.  Back to 1 --> At this point, I need to get the "LATEST" PK then start this as a starting point again to generate PK and append it to ZQ_TABLE
    I'm assuming that SAP has other SAP FMs related in creating this scenario.   Similar to IDOC # creation..
    Thanks.

  • What is faster to search an alpha numeric primary key or number datatype

    hi all,
    I am looking for the answer to a question. What provides a faster and or efficient search for a primary key in any RDBMS is it alpha numeric or number? and why?I would appreciate you replies please.

    Several years ago an Oracle support analyst posted the results of a test for a single column PK with where he compared the results for using a number data type verse a character data type. The analyst results showed you needed more than 100K accesses to measure any significant difference where the number data type showed a small performance advantage. Note that Oracle stores the number data type internally as a form of scientific notation and library math is necessary to work with the numbers. Most of the claims for using a number instead of character go back to the days where native binary words were used as the key. The test only covered signle column keys.
    Use the data type that matches your natural business keys and call it a day. If you try to substitute an artificial numeric key you are likely to have to go through a business character value to locate the artificial key so any performance benefit you think you can get by using a numeric key will be imaginary due to increased overhead of maintaining multiple indexes.
    You can set up and run your own tests.
    HTH -- Mark D Powell --

  • How can I use the SQL to create a primary key for a existing table?

    create table a(bm number,mc varchar2(20));
    when the table was created,i want to make the column bm as
    the primary key and my SQL is "alter table a enable primary key bm",the system show
    me error,how can I write the right one?

    create table a(bm number,mc varchar2(20));
    when the table was created,i want to make the column bm as
    the primary key and my SQL is "alter table a enable primary key bm",the system show
    me error,how can I write the right one? You do not have any primary key defined on your table yet, so, it does not make sense to enable it (if at all possible) !
    You need to add PRIMARY KEY using something like this:
    SQL> alter table a add constraint pk_a_bm primary key (bm) ;

  • Creating a New Row Using an ADF Iterator Binding without primary key value

    I dropped a Create action onto a DataAction which forwards to a UIX entry page which contains an enabled Commit button. Part of the primary key value is held in a session bean and it is also current in another view on the model side, but I am unable to access this value to set the EntityImpl primary key attribute.
    Upon submission the following error message is returned from the model:
    ORA-01400: cannot insert NULL into ("GTR"."EMPLOYMENT"."ACCOUNT")
    I would like to accomplish this with databinding and not create a custom create method on the application model. Is there a way to update the binding value for the new row in cache before the submission? Any advice would be welcome.

    I should add that I want the user to enter every attribute value, except for the account number. It must be possible to create a new row and have the account number supplied to the bindings another way.

Maybe you are looking for

  • Role of SLD in message processing

    What role does the SLD play in the integration engine processing of messages?    For example, we have one SLD and for some reason a component changed accidentally, and it was used by a production interface.   Would the interface then fail? If the pro

  • Playing songs in iTunes

    Does anyone know if its possible to play songs in iTunes and not have it scroll back up to the next song. For instance, if I am playing a song at the top of my library and have scrolled down to the bottom of my library is it possible for it to go to

  • Itunes crashes when i attatch new nano.. works on another compuetr though.

    i have done everything that i heave read... help! my nan crashed itunes instantly. and sends an error report to microsoft.

  • Form4.5 For update clause in cursor problem

    Hi, I am putting this code in my forms4.5 pl/sql block and get the error when compile the pl/sql block. "Encountered ";" when expecting "of"..... Code is: Select null INTO dummy from mytable where id = 1456 for update nowait; If I remove for update c

  • Configuration needed for SOA call to create PO in classic scenario

    Dear Experts, We are working in the SAP SRM 7.01 with backend system on ecc 6.0 Enhancement pack 5. The scenario configured is classic scenario. I want to know what are the configurations needed to use SOA calls to create a purchase order in the back