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

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

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

  • Knowing the Primary Key Sequence Generator of a table

    Hello All,
    I'm working on an application that uses Oracle toplinks/JPA for persistence. The entity classes in the application have primary key fields with annotations @Id and @GeneratedValue(strategy = GenerationType.AUTO). Per our understanding, this means the primary key generation is done by JPA/Top-links. When we see our database, we notice only one SEQUENCE table available and that table has only one row, while in the application, we are getting different sequence numbers for the primary key of each entity. So, not clear on how this sequence number is generated. Could anybody share information on where the sequence number is stored for each entity/table? Really appreciate your help here. Our database is MSSQL.
    Thank you,
    Venkatesh

    EclipseLink/TopLink uses Table sequencing for GenerationType.AUTO because it is more portable between databases. My understanding of your issue is from
    http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Table_sequencing
    Each row in the table represents one sequence generator, and your entities are all using the same default sequence generator and so all use the same row.
    To use multiple rows I believe you need to define multiple TableGenerators.
    Best Regards,
    Chris

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

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

  • JDO Auto Generate Primary Key

    Hi
    I am working with JDO.
    I want to auto generate the primary key value that should increment for each entry into database.
    How can i do it, please guide me.
    Any link or doc will be appreciated.
    Regards
    Osman

    There is only one answer to "how I do this" questions: read the manual.
    Any link or doc will be appreciated.Google. Seriously dude, a forum is not your personal information service - go make some effort yourself. Come back when you have an actual problem that you need help with.

  • 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.");
    }

  • Need to manually update an automatic primary key sequence

    EDIT:  I think this is actually a privileges issue not letting me see the sequences.  Sorry for the trouble
    Hi everyone. I actually didn't know this was possible until I came across this table. This table has a primary key that autoupdates without a trigger or a sequence. so...
    id name
    1 jim
    2 mark
    insert into t1 (name) values ('bob') :
    id name
    1 jim
    2 mark
    3 bob
    My problem is that I manually inserted some rows into this table with the id's as part of the insert statement and now the old way doesn't work. I am assuming because wherever this sequence is it still thinks 3 is the next value. Does anyone know how i can update this value so that the bob-style insert will work again? There are no triggers or sequences in this database (according to what I'm looking at in SQL Navigator. Thanks!
    Edited by: samspot on Feb 4, 2009 12:08 PM

    Can you please run following query and send us the output?
    select *
    from all_triggers
    where table_name = 'T1' ;Edited by: arpit_shah4u on Feb 4, 2009 3:07 PM

  • 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

  • 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

  • Help with sys_guid and Primary Keys

    I am trying to use sys_guid to create unique PK_ID in my tables (see below). This works fine in oracle, but when I try to insert into a remote DB I get a precision error. Is there a way to control the length/format of sys_guid? Is there something easier to use for automaticall creating PK Id's
    CREATE TABLE TEST
    ( PK_ID NUMBER default to_number(sys_guid(),'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')

    This works fine in oracle, but when I try to insert into a remote DB I get a precision error.What sort of "remote DB"? Oracle or non-Oracle?
    Another thing occur. SYS_GUID includes some element generated by the host or the thread process - does a straightforward SYS_GUID call (i.e. without the TO_NUMBER bit) work in your set-up?
    Cheers, APC
    Blog : http://radiofreetooting.blogspot.com/

  • Help required in generating the following query

    Hi all,
    i need solution regarding the following problem.
    we got many number of groups ,each group containg many number of names,each name containing some items under that
    i had written a query stating that select item where grp  =[0%] and name =[1%] from a table
    it will execute and dispaly a window with two fields at the first field i entered group and in the second field when i select for existing values it shows all the items of all groups
    but we need only items that belong to the group that we enter in the first field
    any one tell me the query regarding this requirement

    HI,
    The alternative solution is: develop your add-on, which get the filtering window, and connects the 2 parameters inside, then runs the query and displays it in a matrix/Grid.
    It is not takes so many time.
    Regards,
    J.

Maybe you are looking for

  • MacBook Pro port icons disappearing from Unibody...

    Hi, I was wondering if the following issue is normal. I have a mid 2010 MacBook Pro and today I looked at the ports of the computer and noticed that both the icons that indetify the ethernet and magsafe ports are fading away.  Most of the time the Ma

  • How to select a particular row in a JTable?

    I want to select a particular row in a JTable. i.e something like table.setSelectedRow(arg)how can i do it.

  • Tabular Form with Popup List Error

    hi, am using javascript to display Department Name when Deptno is changed in the Popup List am getting message from Popup Item (DEPTNO) (Htlm Form Element Attributes -> onchange="getDname(this); ") but am not getting message from popup Item in the Ta

  • Strange problem with my build JAR

    Hiii everybody... I'm having a strange problem with my build (JAR file)... when I work with the Eclipse and I click in the table that returns the clients stored in my PostGre database it works fine, but when I build my application and it generates my

  • ITunes crashes when syncing iPhone 4

    Im on windows 7, have itunes 10.5.3.3 version and now im trying to sync my iphone 4 to get my music and everything else, but everytime I try to sync my phone, itunes crashes. I didn't have this problem before, but after I upgraded it won't let me syn