Auto populating application identity primary key?

I'm sure this has been asked before but I couldn't find anything by many
searches.
I have some classes with int or long as their primary key. I prefer using
application identity so the application can have direct access to the
primary key.
I would like to have the primary key automatically populated by Kodo from
a sequence such that I can do:
MyObject test = new MyObject();
pm.makePersistent(test);
assertTrue(test.getId() > 0);
Is this possible in Kodo? I haven't been able to find it. I know I can do
it with datastore identity but I would really like to avoid that.
Thank you,
Joel Shellman

Hi Joel,
before you may consider to use auto-incremented appid PK's let me tell
some things from my own experience.
If you have auto-incremented primary key fields you have consider that
their values will be finally set when you commit the transaction.
So if you access the pk fields during a transaction their values will be
NOT set until you call explicitly KodoPersistenceManager.flush() or commit
the transaction.
If you use applications identity and if you have a compound PK's which one
its fields presents a foreign key from a relation, you have to consider
this behavior and maybe run into problems.
I had many problems with it and finally build a wrapper around the
sequence generator instance from KodoHelper.getSequenceHelper ().
Greetings,
Matthias
Stephen Kim wrote:
Joel, there is not, unless you are using auto-incrementing primary keys.
You can do it in application code by calling
KodoHelper.getSequenceHelper (). Note that you should not have this in
an empty constructor as it may interfere with integration with JDO's
registration system.
Joel Shellman wrote:
I'm sure this has been asked before but I couldn't find anything by many
searches.
I have some classes with int or long as their primary key. I prefer using
application identity so the application can have direct access to the
primary key.
I would like to have the primary key automatically populated by Kodo from
a sequence such that I can do:
MyObject test = new MyObject();
pm.makePersistent(test);
assertTrue(test.getId() > 0);
Is this possible in Kodo? I haven't been able to find it. I know I can do
it with datastore identity but I would really like to avoid that.
Thank you,
Joel Shellman
Steve Kim
[email protected]
SolarMetric Inc.
http://www.solarmetric.com

Similar Messages

  • 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

  • Primary key violation when inserting records with insert_identity and ident_current+x

    My problem is this: I have data in a couple of temporary tables including
    relations (one table referencing records from another table by using
    temporary keys).
    Next, I would like to insert the data from the temp tables to my productive tables which have the same structure but their own identity keys. Hence, I need to translate the 'temporary' keys to regular identity keys in my productive tables.
    This is even more difficult because the system is highly concurrent, i.e. multiple sessions may try to insert
    data that way simultaneously.
    So far we were running the following solution, using a combination of
    identity_insert and ident_current:
    create table doc(id int identity primary key, number varchar(100))
    create table pos (id int identity primary key, docid int references doc(id), qty int)
    create table #doc(idx int, number varchar(100))
    create table #pos (docidx int, qty int)
    insert #doc select 1, 'D1'
    insert #doc select 2, 'D2'
    insert #pos select 1, 10
    insert #pos select 1, 12
    insert #pos select 2, 32
    insert #pos select 2, 9
    declare @docids table(ID int)
    set identity_insert doc on
    insert doc (id,number)
    output inserted.ID into @docids
    select ident_current('doc')+idx,number from #doc
    set identity_insert doc off
    -- Since scope_identity() is not reliable, we get the inserted identity values this way:
    declare @docID int = (select min(ID) from @docids)
    insert pos (docid,qty) select @docID+docidx-1, qty from #pos
    Since the request to ident_current() is located directly in the insert statement, we always have an implicit transaction which should be thread safe to a certain extend.
    We never had a problem with this solution for years until recently when we were running in occasional primary key violations. After some reasearch it turned out, that there were concurrent sessions trying to insert records in this way.
    Does anybody have an explanation for the primary key violations or an alternative solution for the problem?
    Thank you
    David

    >> My problem is this: I have data in a couple of temporary tables including relations (one table referencing records [sic] from another table by using temporary keys [sic]). <<
    NO, your problem is that you have no idea how RDBMS and SQL work. 
    1. Rows are not anything like records; this is a basic concept.
    2. Temp tables are how old magnetic tape file mimic scratch tapes. SQL programmers use CTEs, views, derived tables, etc. 
    3. Keys are a subset of attributes of an entity, fundamental characteristics of them! A key cannot be temporary by definition. 
    >> Next, I would like to insert the data from the temp tables to my production tables which have the same structure but their own IDENTITY keys. Hence, I need to translate the 'temporary' keys to regular IDENTITY keys in my productive tables. <<
    NO, you just get worse. IDENTITY is a 1970's Sybase/UNIX dialect, based on the sequential file structure used on 16-bit mini computers back then. It counts the physical insertion attempts (not even successes!) and has nothing to with a logical data model. This
    is a mag tape drive model of 1960's EDP, and not RDBMS.
    >> This is even more difficult because the system is highly concurrent, i.e. multiple sessions may try to insert data that way simultaneously. <<
    Gee, that is how magnetic tapes work, with queues. This is one of many reasons competent SQL programers do not use IDENTITY. 
    >> So far we were running the following solution, using a combination of IDENTITY_INSERT and IDENT_CURRENT: <<
    This is a kludge, not a solution. 
    There is no such thing as a generic “id” in RDBMS; it has to be “<something in particular>_id” to be valid. You have no idea what the ISO-11179 rules are. Even worse, your generic “id” changes names from table to table! By magic, it starts as a “Doc”,
    then becomes a “Pos” in the next table! Does it wind up as a “doc-id”? Can it become a automobile? A squid? Lady Gaga? 
    This is the first principle of any data model; it is based on the Law of Identity; remember that from Freshman Logic 101? A data element has one and only one name in a model. 
    And finally, you do not know the correct syntax for INSERT INTO, so you use the 1970's Sybase/UNIX dialect! The ANSI/ISO Standard uses a table consrtuctor: 
    INSERT INTO Doc VALUES (1, 'D1'), (2, 'D2'); 
    >> We never had a problem with this solution for years until recently when we were running in occasional PRIMARY KEY violations. After some research it turned out, that there were concurrent sessions trying to insert records [sic] in this way. <<
    “No matter how far you have gone down the wrong road, turn around.” -- Turkish proverb. 
    You have been mimicking a mag tape file system and have not written correct SQL. It has caught up with you in a way you can see. Throw out this garbage and do it right. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Autonumber for Primary Key in Z Table

    Hi,
      I want to use an auto generated number as primary key for a Z table that i want to create. Is there some exiting data element tht I can use, so that I dont have to explicitly enter the primary key everytime i enter a record in SM30

    Hi,
    There is no automatically way of generating number...
    But You can create a number range object in the transaction SNRO.
    Then use the FM NUMBER_GET_NEXT to get the next number....
    Then assign that number using the event 05 "new entries" which you can set in the view TVIMF.
    Thanks,
    Naren

  • Utilizing auto-increment/identity fields for primary key with "application" identity

    Is it possible to utilise an auto-increment (identity in MS SQL Server)
    field for the primary key field when using "application" identity?

    To the best of my knowledge, you cannot use auto-increment. Due to the
    differences in the way that identities are generated at the datastore
    (upon insert) vs. JDO (upon makePersistent), this feature of SQLServer is
    not supported yet.
    However, we do provide a variety of other ways of generating identity
    which may provide a closer fit to what you want, and
    our users may have some experience in solving your problem.
    On Tue, 28 Jan 2003 09:56:08 +0000, Sean Ryan wrote:
    Is it possible to utilise an auto-increment (identity in MS SQL Server)
    field for the primary key field when using "application" identity?--
    Stephen Kim
    [email protected]
    SolarMetric, Inc.
    http://www.solarmetric.com

  • CMP with auto-increment primary key.Please help

    Hi all,
    I new with EJB technology so please bear with me.
    Env: 2k Server, SQL 2k Server
    Sun One(Forte EE) to develop and deploy CMP
    I got the servlet to load the data from CMP's business mehods
    is fine. Calling the findPrimaryKey is OK too. Even when I try to insert the row into DB is OK. At this time I make key PK is int AND NOT
    AUTO INCREMENT everything is OK. In the ejbCreate method
    I called setPK, setName ...It's fine.
    The problem comes when I try to make the PK(still int) to be auto-increment field.In ejbCreate not call setPK because of in SunOne IDE, under the J2EE RI tab of EJB Module property, the Auto generate SQL I set to false so that I can
    modify the SQL statement under SQL Deployment.createRow not taking the PK. I thought that will do it but it doesnot like it at all (I got Exception with transaction rollback)I just want to insert a single row with ID and name that's all.
    Then I changed the SQL statment take PK and changed the Auto Generate SQL to True and in ejbCreate the PK as one of the args and called setPK this time with null object. It doesn't like neither.(Exception Cannot set the primary key with null. That is reasonable.)
    I thought using EJB fast and clean technique would help developer to develop application with easiness.
    So I realy stuck with this, I wonder ejb 2.0 support for auto increment at all because I would like to take advantage of the auto increment feature of the DB without writing the PrimaryKeySequence generator at all.
    Am I missing something with this? May be just config thing to tell
    that my PK is auto-increment field so that when the ejbCreate called it knows not taking the PK or even not asking to call setPK in ejbCreate.
    Any help would appreciated.

    Check out this thread, there's a bunch of good info:
    http://www.theserverside.com/patterns/thread.jsp?thread_id=4976

  • Primary key column auto increment

    Hello,
    In my Azure SQL Database I noticed that weird thing is happening. I have table with primary key column with auto increment, and all works fine, on new insert that value automatically increment, but every now and then, that value, for no reason, increments
    for 1000.
    For instance i have in DB values in this order: 1, 2, 3, 4, 1001, 1002, 1003, 2004,  2005, 3001, 3002...
    Why is this happening? 

    Hello ,
    you can see this thread :
    http://stackoverflow.com/questions/17012339/windows-azure-sql-database-identity-auto-increment-column-skips-values
    It's seems that SQL Server work with sequence and block 1000 values. In the cloud, your SQL Azure Database can be move from one server to an other or restarted and so a new sequence is used. That's why you jump from 4 to 1001.
    Regards

  • DB Adapter - PostgreSQL - Primary key - auto increment handling

    Hi,
    I have to connect to a PostgreSQL DB. I have a table in which has a primary key called seq_id. This seq_id is being incremented using a sequence.
    I have to configure the DB adapter for this table. The problem is that while creating the adapter it does not allow me to deselect the primary key (seq_id). Because of this I have to supply a value for the seq_id while inseting the data using the adapter. But this defeats the purpose of sequence (auto increment).
    Is there a way to get around this and to avoid specifying the value for seq_id while using the DB Adapter and let it get inserted using the sequence of the DB?
    Thanks,
    Sanjay

    Hello ,
    you can see this thread :
    http://stackoverflow.com/questions/17012339/windows-azure-sql-database-identity-auto-increment-column-skips-values
    It's seems that SQL Server work with sequence and block 1000 values. In the cloud, your SQL Azure Database can be move from one server to an other or restarted and so a new sequence is used. That's why you jump from 4 to 1001.
    Regards

  • Auto Increment Primary Keys

    I am trying to migrate from SQL Server. I want to setup tables which generate sequencial Primary keys on adding records to the table. I have a VB application which is using ADO with an ODBC connection. How does one use the Oracle Enterprise Console Manager to set a Primary Key to increment on the adding of new records automatically. In SQL Server one just needs to set an Identity, Identity Seed and Identitiy Increment. In Access there is a datatype called AutoNumber. Help would be greatly appreciated. I am using 9i with a standalone Enterprise Console Manager. Thanks in Advance.

    You first have to create a sequence and then the trigger below:
    Instead of data in single quotes(') you must specify the appropriate for your db names
    CREATE OR REPLACE TRIGGER 'Schema'.'trigger_name' BEFORE
    INSERT ON 'table_name'
    FOR EACH ROW
    BEGIN
    SELECT 'sequence_name'.nextval into :new.'column_name' from dual;
    END
    ;

  • Primary key violation exception in auto increment column

    Hi All,
    I am facing one issue in Multi threaded environment.
    I am getting Primary key violation exception in auto increment column. I have a table and the primary key is the auto increment column, and I have a trigger which is populating this column.
    5 threads are running and inserting the data in the table and throwing Primary key violation exception randomly.
    create table example (
    id number not null,
    name varchar2(30)
    alter table example
    add constraint PK1example primary key (id);
    create sequence example_id_seq start with 1 increment by 1;
    create or replace trigger example_insert
    before insert on example
    for each row
    begin
    select example_id_seq.nextval into :new.id from dual;
    end;
    Any idea how to handle auto increment column(trigger) in Multi threaded environment??
    Thanks,

    user13566109 wrote:
    Thanks All,
    Problem was in approach; removed the trigger and placed a seq.nextval in insert query. It has resolved the issue.I very much suspect that that was not the issue.
    The trigger would execute for each insertion and the nextval would have been unique for each insertion (that's how sequences work in oracle), so that wouldn't have been causing duplicates.
    I suspect, more likely, that you had some other code somewhere that was using another sequence or some other method of generating the keys that was also inserting into the same table, so there was a conflict in the sources of the sequences being generated.
    The way you showed you had coded above, was a perfectly normal way to assign primary keys from a sequence, and is not a problem in a multi user/threaded environment.

  • Insert into table returning primary key (auto number) in resultset

    Hi,
    I'm connecting to Oracle 10g via JDBC (ojdbc14.jar).
    My SQL statement is as follows:
    INSERT into Student (studentName, phone, email, address) values ('Jason', '12345678', 'test', 'test');
    SELECT Student_studentId_SEQ.NEXTVAL FROM DUAL;
    Fyi -The Student table has a trigger to support the generation of a primary key (integer) based on a sequence when a new record is inserted.
    What the above will do (from the Java app point of view) is to create a Student record and automatically select the student ID so that the student ID can be accessed via the resultset in Java.
    I'm getting error "ORA-00911: invalid character". Can you please help?
    Regards,
    Jason
    Edited by: user10394130 on Oct 13, 2008 2:40 AM

    Yes, I'm referring to the studentId, which is generated via the Student table trigger on insert of a new record.
    I've now verified that the following SQL works and it is "printing" the correct studentId.
    DECLARE seqNbr_studentId NUMBER(12) := 0;
    BEGIN
    INSERT into Student (studentName, phone, email, address) values ('Jason', '12345678', 'test', 'test')
    RETURNING studentId INTO seqNbr_studentId;
    dbms_output.put_line(seqNbr_studentId);
    END;
    --> This prints the correct value of seqNbr_studentId that has been generated by the trigger. This is good.
    However, I would like the studentId to be in a resultset (so that I can access this via Java Resultset.getInt(1) ), for example:
    DECLARE seqNbr_studentId NUMBER(12) := 0;
    BEGIN
    INSERT into Student (studentName, phone, email, address) values ('Jason', '12345678', 'test', 'test')
    RETURNING studentId INTO seqNbr_studentId;
    SELECT seqNbr_studentId FROM DUMMYTABLE;
    END;
    Is this possible?
    What I'm trying to do is to achieve the effect in SQL Server where I can simply do an SQL command "SELECT @@IDENTITY" where it returns the auto number from the newly inserted record.
    Regards,
    Jason
    Edited by: user10394130 on Oct 13, 2008 2:08 AM
    Edited by: user10394130 on Oct 13, 2008 2:56 AM

  • Application Translation Not Working - Primary Key Error

    I had created an application translation to Spanish but it wasn't displaying my Spanish translation. I was going to try and redo it so I tried creating a new mapping and then seeding the translatable text. I got a primary key error "ORA-20001: Seed insert error: WWV_FLOW_TOPLEVEL_TABS.TAB_TEXT ORA-00001: unique constraint (FLOWS_030100.WWV_FLOW_TRANSLATABLE_TEXT_PK) violated".
    I went in and deleted what I had done through APEX for this app and tried to create a new application but still get the primary key error when I try to seed it. I gave it a new translated application ID but that doesn't seem to help. Anyone have this problem or no of the reason I'm having this issue?
    Thanks.

    Hi David,
    Thanks for reporting this. This was an interesting problem to solve.
    As it turns out, it was a logic error in Application Express (i.e., bug). When deleting a translation mapping, the associated strings in the translation repository would be deleted for that application, but if and only if you had actually published the application.
    I think this is why you could never get Spanish working properly - you had never actually published the application the first time. So I'll bet what you did is deleted the original mapping, then you recreated the mapping for the same language but with a different translated application ID. Since you had never published the application from the original translation mapping, and there were orphaned rows in the translation repository, you encountered a "collision" when you tried to seed the second time with the different translated application ID.
    Your action of deleting rows from WWV_FLOW_TRANSLATABLE_TEXT$ cleaned up these orphaned rows. As you stated, this isn't recommended to perform DML on the underlying APEX tables. A couple alternatives could have been:
    1) Before deleting the translated application mapping, actually publish the application and then delete the mapping.
    2) If you had deleted the mapping already, you could recreate the mapping for the same language and with the original translated application ID. Then, publish the application and then go back and delete the mapping.
    I realize all this sounds crazy. But it was only an issue because you had not actually published the application. Not your fault, though, as this is a bug in APEX.
    This bug will be fixed in Application Express 4.0. This way, you won't have to worry about if you published or didn't publish. The orphaned rows will be cleaned up when you delete a mapping.
    Thanks again for reporting this.
    Joel

  • Creating entity beans with auto numbered primary key

    I have two entity bean with a CMR between them. I am successfully creating the first one but when I try and create the child entity bean I get a NullPointerException.
    Now I think this is because the gernerated code tries to get the primary key of the created entity bean and this is not set as it is set using a auto number in the database (An oracle sequence and trigger).
    Is there anyway i can get round this problem?
    Thanks in advance,
    Adrian

    This is the auto generated code:
         public dmd.sync.ejbs.entity.AppliancePackInfoLocal create_Local(dmd.sync.dataobjects.dto.AppliancePackInfoDTO appliancePackInfoDTO, dmd.sync.ejbs.entity.AmppLocal amppLocal) throws javax.ejb.CreateException, java.rmi.RemoteException {
              BeanO beanO = null;
              dmd.sync.ejbs.entity.AppliancePackInfoLocal result = null;
              boolean createFailed = false;
              boolean preCreateFlag = false;
              try {
                   beanO = super.createBeanO();
                   dmd.sync.ejbs.entity.AppliancePackInfoBean bean = (dmd.sync.ejbs.entity.AppliancePackInfoBean) beanO.getEnterpriseBean();
                   preCreateFlag = super.preEjbCreate(beanO);
                   bean.ejbCreate(appliancePackInfoDTO, amppLocal);
                   Object ejsKey = keyFromBean(bean);
                   result = (dmd.sync.ejbs.entity.AppliancePackInfoLocal) super.postCreate_Local(beanO, ejsKey, true);
                   bean.ejbPostCreate(appliancePackInfoDTO, amppLocal);
                   super.afterPostCreate(beanO, ejsKey);
    It must be falling over on the last line as it calls the ejbPostCreate fine.

  • Hacking application id equals() to allow more than one row per "primary key"

    I have a read only entity whose primary key is not the real primary key
    on the underlying table. The result is that I get more than one row per
    "primary key". This is what I want. However KODO will not allow me do
    it, because I am storing the collection in a HashSet() and the equals()
    method on the application id object ensures that this set contains no
    duplicates (as defined by the application id). At least thats how it
    seems to behave.
    So, I have hacked the equals() method to do this:
    public boolean equals (Object ob)
    if (this == ob)
    return true;
    // Doing this because we expect more than one row from
    // REF_CODES for the same domain/shortCode combination.
    // This is ok to do (I guess?) as long as we are only
    // doing selects using this class.
    return false;
    Will this hack have any side effects? Is there another option? Like
    using a list collection? Is so, which collections are supported?
    Thanks,
    Mike.

    The "primary key" I am using it already a compound key of two columns.
    The real key on the underlying table is a three column key. But the
    problem is that the table represents two different application level
    entities. I could deal with it when I was hand-writing SQL (I could do
    a distinct for example) but now I am relying on foreign key
    relationships since I moved to JDO. Not sure what to do. Best solution
    is to rework the table, but there is a lot of legacy code (that other
    teams use and maintain) relying on this table. I guess I'll use the
    weekend for inspiration ;-)
    Steve Kim wrote:
    This sounds like a dangerous operation. Even if this works now, I
    cannot promise future compatibility... and in fact may result in bad
    data (for example in caching both at the PM and PMF level) Is there no
    other field that you can reference as part of the primary key? Primary
    Keys can be multi columned (e.g. last_name, soc_sec_number)
    Mike Hogan wrote:
    I have a read only entity whose primary key is not the real primary
    key on the underlying table. The result is that I get more than one
    row per "primary key". This is what I want. However KODO will not
    allow me do it, because I am storing the collection in a HashSet() and
    the equals() method on the application id object ensures that this set
    contains no duplicates (as defined by the application id). At least
    thats how it seems to behave.
    So, I have hacked the equals() method to do this:
    public boolean equals (Object ob)
    if (this == ob)
    return true;
    // Doing this because we expect more than one row from
    // REF_CODES for the same domain/shortCode combination.
    // This is ok to do (I guess?) as long as we are only
    // doing selects using this class.
    return false;
    Will this hack have any side effects? Is there another option? Like
    using a list collection? Is so, which collections are supported?
    Thanks,
    Mike.

  • How to have an auto increment primary key in HDBDD

    Hello,
    Using a HDBDD file I am creating a table in which I need a primary key(recordId) which is auto generated by the DB.
    What would be the way to do this?
    My hdbdd file:
    namespace sap.mobile.data;
            @Schema : 'SAP_TEST'
    context Sample {
    @Catalog.tableType : #COLUMN
      entity Details {
      text : LargeString;
      level : String(10);
      timestamp : UTCTimestamp;
      recordId : ?

    Such syntax for calculated columns isn't supported yet by CDS/HDBDD. The work around people would use today is to use a Sequence in any logic that does an insert into this table.

Maybe you are looking for