Primary Key Generation/Usage Strategy

This topic might have already been discussed here but when I searched the forum I did not get the answers for the following, if some one know or have better understanding of this topic please let me know.
The thing is we the DB is shared among many applications and EJB app is one among them. So we decied to use the Oracle Database Sequences to generate the PK for the tables. Now that it has been decided to use the Oracle Sequence what is the best strategy to use it? there are couple of options here
Option 1. Create a State less session bean to access the DB and get the next value from the corresponding for each table
Option 2. Create a simple java class that queries the database and gets the corresponding sequence's next value and call this function from the ejbCreate method.
or do we have any other option here? if so which one is the best among them?
Thank you
Mallik

Avi,
Thank you for the information.
Actually I am looking for PK solution for CMP EJBs. We have decided to use the Oracle Sequences and now the question is do I use a State less session bean or just use a static helper method in a helper class to get this PK value ?
Does any one know which one is better?
If I use a static method in a class to get this PK value, the class is loaded into the memory once and then I can keep calling from various EJB's or from a Super Class of all CMP EBJ's and each call is executing the same code in its own thread.
Else If I ues SLSB, then each CMP EJB or the code in the Super class of all CMP EJB's has to look for this SLSB and create the local and then execute the getNextPK method on the SLSB, it looks like little more work.
Also just to get PK value which does not include any transactions it would be over burden to use a SLSBean.
Its just my thoughts ...
Please let me know if some one has a good reason to use a SLSB to get a PK value while using Oracle Sequences.
Thank you
Mallik

Similar Messages

  • Primary key generation: Using CounterHome?

    I can't find any documentation that talks about automatic primary key generation support on OC4J. I noticed the article on the Orion Support page that mentions their "Counter" bean. Is this the extent of support for automatic primary key generation in OC4J? When I searched for this class in the distribution, I only found it in a demo application in JDeveloper.
    Is this something that is handled directly in the Oracle DB, which is why OC4J doesn't bother to support it?

    Sorry I wasn't specific. By "going nowhere", I meant it went to an error page on the orion site. I don't know why it couldn't find it, because when I just now searched for the article with the title you just gave, the resulting URL was identical to what you gave me originally.
    As to the "counter faq", I think I've seen that before, but I can't get to it right now (server overloaded or something). The one problem I remember with trying to pursue the "counter" solution was somewhat simple. I couldn't find the code. I didn't notice a download for the "Counter" class, and I can't find it in either the jdeveloper or oc4j distributions.
    In any case, I ended up implementing the UUID solution, based on Floyd Marinescu's example in "EJB Design Patterns". I think this will work fine for our application.
    I'd still like to know more about Orion's "Counter" solution, if there's any real code available to see.

  • Primary key generation

    How do use primary keys generated by database within entity bean?

    DBMS primary key generation uses a set of deployment descriptors that
    are specified at compile time to generate container code which is used
    in conjunction with a supported database to provide key generation
    support. Specify the name of the supported DBMS and the generator name,
    if required by the database. Generated primary key support for Oracle
    databases use Oracle's SEQUENCE. Once the SEQUENCE already exists in the
    database, you specify automatic key generation in the XML deployment
    descriptors. In the weblogic-cmp-rdbms-jar.xml file
    <automatic-key-generation>
    <generator-type>ORACLE</generator-type>
    <generator_name>test_sequence</generator-name>
    <key-cache-size>10</key-cache-size>
    </automatic-key-generator>
    You need to specify the name of the ORACLE SEQUENCE to be used in the
    generator-name element. If the ORACLE SEQUENCE was created with an
    INCREMENT value, then you must specify a key-cache-size. This value must
    match the Oracle SEQUENCE INCREMENT value.
    Owen wrote:
    How do use primary keys generated by database within entity bean?

  • ADF BC Primary key generation with SQL Server DB

    Hi,
    I am using ADF 11.1.1.6 to develop a small application that will do some very basic CRUD operations on a SQL Server DB.
    I read through http://www.oracle.com/technetwork/developer-tools/jdev/multidatabaseapp-085183.html before I'm starting to implement the Entity objects.
    This document describes a way to do primary key generation using a table created in the DB and instructs to create an application connection to the Database :
    +2. Create a Connection to the Table+
    In your application, create a database connection named ROWIDAM_DB that points to the database containing your S_ROW_ID table. Alternatively, edit your BC project's properties and add the following Java option to the project's run configuration:
    -Djbo.rowid_am_conn_name= appconnection
    where appconnection is the name of a database connection that points to the S_ROW_ID table.
    My question is how do we do this when we mve to a production environment ?
    Also I'll be interested to hear if anyone has any pointers for developing ADF apps with SQL Server. (gotchas, performance pitfalls etc. )
    -Jeevan
    Upadte : This is SQL Server 2005
    Edited by: Jeevan Joseph on May 2, 2012 9:04 AM

    my apologies to everyone ... This should have been very simple. I just need to provide the config in my AM configuration(bc4j.xml)
    jbo.rowid_am_conn_name* should be set to the connection name you create. For production deployments, theres a similar
    jbo.rowid_am_datasource_name* that should work just fine (though I havent tried if it has any hiccups).
    I'd like to point out one thing though, for whoever might stumble upon this thread and find it useful later on...
    After I did the steps above, everything seemed to work when I tested the app from the AM tester. But when I built a UI for it in ADF Faces, I started getting an exception on Create/CreateInsert :
    java.lang.ClassCastException: com.microsoft.sqlserver.jdbc.SQLServerConnection cannot be cast to oracle.jdbc.OracleConnection
         at oracle.jbo.server.OracleSQLBuilderImpl.setSessionTimeZone(OracleSQLBuilderImpl.java:5533)
         at oracle.jbo.server.DBTransactionImpl.refreshConnectionMetadata(DBTransactionImpl.java:5311)
         at oracle.jbo.server.DBTransactionImpl.initTransaction(DBTransactionImpl.java:1194)
         at oracle.jbo.server.DBTransactionImpl.initTxn(DBTransactionImpl.java:6826)
         at oracle.jbo.server.DBTransactionImpl2.connect(DBTransactionImpl2.java:136)
         at oracle.jbo.common.ampool.DefaultConnectionStrategy.connect(DefaultConnectionStrategy.java:213)The trouble is that the ADF Faces adf-config.xml overrides the AM configuration. Oracle is the default, and it overrides the SQL flavor I set when initializing the Model project.
    This was not mentioned in the original document probably because ADF faces was out of scope for that document.
    I also found this thread extremely useful, and its what reminded me of the ADF Faces AM config overrides : Re: Locking mode 'optupdate' with SQL92
    Cheers !
    Jeevan

  • Cluster DuplicateKeyExecption and primary key generation

    Hi
    I have 2 applications servers working in a cluster.
    I'm using for primary key generation The pattern "sequence blocks" taken from the book ejb design patterns.
    However when i have something like 5 threads that are trying to create new entities then i get DuplikateKeyException on the primary key. (with only 1 jboss server not in a cluster everything is fine).
    I was wondering if anybody could help me pin out the problem, following is my code:
    I estimated it might be an Isolation level problem, however i have updated the isolation level to be serializable in that way in mysql ds and the problem still happend...
    Code:
    <user-name>root</user-name>
    <password></password>
    <TransactionIsolation>TRANSACTION_SERIALIZABLE</TransactionIsolation>
    Sequence entity bean
    Code:
    import javax.ejb.*;
    abstract public class SequenceBean implements EntityBean {
    EntityContext entityContext;
    public java.lang.String ejbCreate(java.lang.String name) throws CreateException {
    setName(name);
    return null;
    public void ejbPostCreate(java.lang.String name) throws CreateException {
    setSIndex(ConfigContainer.getJMXPropertiesFacade().getSequenceSessionBeanStartIndex());
    public void ejbRemove() throws RemoveException {
    public abstract void setName(java.lang.String name);
    public abstract void setSIndex(int sIndex);
    public abstract java.lang.String getName();
    public abstract int getSIndex();
    public void ejbLoad() {
    public void ejbStore() {
    public void ejbActivate() {
    public void ejbPassivate() {
    public void unsetEntityContext() {
    this.entityContext = null;
    public void setEntityContext(EntityContext entityContext) {
    this.entityContext = entityContext;
    public int getValueAfterIncrementingBy(int blockSize) {
    this.setSIndex(this.getSIndex()+ blockSize);
    return this.getSIndex();
    sequence session bean
    Code:
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import javax.ejb.CreateException;
    import javax.ejb.FinderException;
    import javax.ejb.SessionBean;
    import javax.ejb.SessionContext;
    import javax.naming.Context;
    import javax.naming.NamingException;
    import org.apache.log4j.Category;
    public class SequenceSessionBean implements SessionBean {
    SessionContext sessionContext;
    private Category _log;
    private class Entry {
    Sequence sequence;
    int last;
    private java.util.HashMap _entries = new java.util.HashMap();
    private int _blockSize;
    private int _retryCount;
    private SequenceHome _sequenceHome;
    public void ejbCreate() throws CreateException {
    _log = Category.getInstance(getClass());
    public void ejbRemove() {
    public void ejbActivate() {
    public void ejbPassivate() {
    public void setSessionContext(SessionContext sessionContext) {
    this.sessionContext = sessionContext;
    Context namingContext = null;
    try {
    namingContext = new javax.naming.InitialContext();
    _blockSize = JMXPropertiesFacade.getInstance().getSequenceSessionBeanBlockSize();
    _retryCount = JMXPropertiesFacade.getInstance().getSequenceSessionBeanRetryCount();
    _sequenceHome = (SequenceHome) namingContext.lookup("SequenceLocalHome");
    catch (NamingException e) {
    _log.error(e.getMessage(), e);
    public void synch() throws InternalException {
    Connection connection = null;
    ResultSet resultSet = null;
    Statement statement = null;
    int maxObjectID = 0, maxUID = 0, maxShareID = 0;
    try {
    connection = MASConnectionManager.getInstance().createConnection();
    String sql = "select max(" + AlbumElementHome.FIELD_NAME_OBJECT_ID + ") maxObjectID from " + AlbumElementHome.TABLE_NAME;
    statement = connection.createStatement();
    _log.debug("SQL : " + sql);
    statement.execute(sql);
    resultSet = statement.getResultSet();
    if (resultSet.next()) {
    maxObjectID = resultSet.getInt("maxObjectID");
    _log.debug(String.valueOf(maxObjectID));
    resultSet.close();
    statement.close();
    ((Sequence) sequenceHome.findByPrimaryKey(AlbumElementHome.JNDINAME)).setSIndex(maxObjectID
    + 1);
    sql = "select max(" + UserHome.FIELD_UID + ") maxUID from " + UserHome.TABLE_NAME;
    statement = connection.createStatement();
    _log.debug("SQL : " + sql);
    statement.execute(sql);
    resultSet = statement.getResultSet();
    if (resultSet.next()) {
    maxUID = resultSet.getInt("maxUID");
    _log.debug(String.valueOf(maxUID));
    resultSet.close();
    statement.close();
    ((Sequence) sequenceHome.findByPrimaryKey(UserHome.JNDINAME)).setSIndex(maxUID + 1);
    sql = "select max(" + AlbumElementShareHome.FIELD_SHARE_ID + ") maxShareID from " + AlbumElementShareHome.TABLE_NAME;
    statement = connection.createStatement();
    _log.debug("SQL : " + sql);
    statement.execute(sql);
    resultSet = statement.getResultSet();
    if (resultSet.next()) {
    maxShareID = resultSet.getInt("maxShareID");
    _log.debug(String.valueOf(maxShareID));
    resultSet.close();
    statement.close();
    ((Sequence) sequenceHome.findByPrimaryKey(AlbumElementShareHome.JNDINAME)).setSIndex(maxShar
    eID + 1);
    } catch (SQLException e1) {
    _log.error(e1.getMessage(), e1);
    } catch (FinderException e) {
    throw new InternalException(e);
    } finally {
         try {
         if (connection != null && !connection.isClosed()) connection.close();
         } catch (SQLException e) {
         _log.error(e.getMessage(), e);
    public int getNextSequenceNumber(String name) {
    try
    Entry entry = (Entry) _entries.get(name);
    if (entry == null)
    // add an entry to the sequence table
    entry = new Entry();
    try
    entry.sequence = _sequenceHome.findByPrimaryKey(name);
    catch (javax.ejb.FinderException e)
    _log.info("can't find sequence: " + name + " trying to create it");
    // if we couldn't find it, then create it...
    entry.sequence = _sequenceHome.create(name);
    _log.info("sequence: " + name + " created");
    _entries.put(name, entry);
    if (entry.last % _blockSize == 0)
    for (int retry = 0; true; retry++)
    try
    entry.last = entry.sequence.getValueAfterIncrementingBy(_blockSize);
    break;
    catch (javax.ejb.TransactionRolledbackLocalException e)
    if (retry < _retryCount)
    // we hit a concurrency exception, so try again...
    _log.info("RETRYING");
    continue;
    else
    // we tried too many times, so fail...
    throw new javax.ejb.EJBException(e);
    return entry.last++;
    catch (javax.ejb.CreateException e)
    throw new javax.ejb.EJBException(e);
    from ejb-jar.xml
    Code:
    <container-transaction>
    <method>
    <description />
    <ejb-name>SequenceSession</ejb-name>
    <method-name>getNextSequenceNumber</method-name>
    <method-params>
    <method-param>java.lang.String</method-param>
    </method-params>
    </method>
    <trans-attribute>RequiresNew</trans-attribute>
    </container-transaction>
    jboss.xml
    Code:
    <container-configurations>
    <container-configuration>
    <container-name>Standard CMP 2.x EntityBean with cache invalidation</container-name>
              <commit-option>A</commit-option>
              <cache-invalidation>True</cache-invalidation>
    </container-configuration>
    </container-configurations>
    <entity>
    <ejb-name>Sequence</ejb-name>
    <local-jndi-name>SequenceLocalHome</local-jndi-name>
    <!-- no cache for this entity bean -->
    </entity>
    anybody can help with what the problem might be?
    did i update the isolation level correctly?

    _blocksize may be returning 0                                                                                                                                                                                                                                   

  • Automatic primary key generation for pointbase

    Hello friends,
    I was wondering whether it is possible to automatically generate primary keys for a pointbase database. Just like the SQL Server pointbase also has a indentity property. I have used weblogic builder to specify automatic key generation. Through the pointbase console I can see that all the columns for all the tables are marked as nullable except the primary key columns. However when I try to insert data into the database using ejb. I get the exception :
    javax.ejb.EJBException: EJB Exception:: java.sql.SQLException: Data exception -- null value not allowed. .
         at com.pointbase.net.netJDBCPrimitives.handleResponse(Unknown Source)
         at com.pointbase.net.netJDBCPrimitives.handlePrimitiveResponse(Unknown Source)
         at com.pointbase.net.netJDBCPreparedStatement.executeUpdate(Unknown Source)
         at weblogic.jdbc.wrapper.PreparedStatement.executeUpdate(PreparedStatement.java:94)
         at yellowpages.ejb.DirectoryItem.DirectoryItem_lh4yf1__WebLogic_CMP_RDBMS.__WL_create(DirectoryItem_lh4yf1__WebLogic_CMP_RDBMS.java:3177)
         at yellowpages.ejb.DirectoryItem.DirectoryItem_lh4yf1__WebLogic_CMP_RDBMS.ejbPostCreate(DirectoryItem_lh4yf1__WebLogic_CMP_RDBMS.java:3094)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at weblogic.ejb20.manager.DBManager.create(DBManager.java:1151)
         at weblogic.ejb20.manager.DBManager.localCreate(DBManager.java:1100)
         at weblogic.ejb20.internal.EntityEJBLocalHome.create(EntityEJBLocalHome.java:171)
         at yellowpages.ejb.DirectoryItem.DirectoryItem_lh4yf1_LocalHomeImpl.create(DirectoryItem_lh4yf1_LocalHomeImpl.java:94)
         at yellowpages.web.controller.AddEntryAction.execute(Unknown Source)
         at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
         at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
         at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
         at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:971)
         at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:402)
         at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:305)
         at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:6350)
         at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:317)
         at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:118)
         at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3635)
         at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2585)
         at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
         at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)
    ; nested exception is: java.sql.SQLException: Data exception -- null value not allowed. .
    java.sql.SQLException: Data exception -- null value not allowed. .
         at com.pointbase.net.netJDBCPrimitives.handleResponse(Unknown Source)
         at com.pointbase.net.netJDBCPrimitives.handlePrimitiveResponse(Unknown Source)
         at com.pointbase.net.netJDBCPreparedStatement.executeUpdate(Unknown Source)
         at weblogic.jdbc.wrapper.PreparedStatement.executeUpdate(PreparedStatement.java:94)
         at yellowpages.ejb.DirectoryItem.DirectoryItem_lh4yf1__WebLogic_CMP_RDBMS.__WL_create(DirectoryItem_lh4yf1__WebLogic_CMP_RDBMS.java:3177)
         at yellowpages.ejb.DirectoryItem.DirectoryItem_lh4yf1__WebLogic_CMP_RDBMS.ejbPostCreate(DirectoryItem_lh4yf1__WebLogic_CMP_RDBMS.java:3094)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at weblogic.ejb20.manager.DBManager.create(DBManager.java:1151)
         at weblogic.ejb20.manager.DBManager.localCreate(DBManager.java:1100)
         at weblogic.ejb20.internal.EntityEJBLocalHome.create(EntityEJBLocalHome.java:171)
         at yellowpages.ejb.DirectoryItem.DirectoryItem_lh4yf1_LocalHomeImpl.create(DirectoryItem_lh4yf1_LocalHomeImpl.java:94)
         at yellowpages.web.controller.AddEntryAction.execute(Unknown Source)
         at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
         at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
         at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
         at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at weblogic.servlet.internal.ServletStubImpl$ServletInvocationAction.run(ServletStubImpl.java:971)
         at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:402)
         at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java:305)
         at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:6350)
         at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:317)
         at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:118)
         at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppServletContext.java:3635)
         at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestImpl.java:2585)
         at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
         at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)

    I am not sure whether I understand your question.
    The 'NamedSequenceTable' method is independent of data base type.
    <from-docs>
    Create a table named SEQUENCE to hold the current primary key value. The
    table consists of a single row with a single column, as defined by the
    following statement:
    CREATE table_name (SEQUENCE int)
    INSERT into table_name VALUES (0)
    </from-docs>
    Then, you can add the following in the DD -
    <automatic-key-generation>
    <generator-type>NamedSequenceTable</generator-type>
    <generator_name>table_name</generator-name>
    <key-cache-size>100</key-cache-size>
    </automatic-key-generation>
    The PK type should be set to java.lang.Integer or java.lang.Long
    --Sathish
    <Panduranga Swamy> wrote in message news:[email protected]..
    Hi,
    With named sequecne table,I am able to develop the application. What I
    wanted is Say Table 1 having Identity column as Primary key in the table
    Pointbase database.
    With Automatic primary key generation in Deployment descriptor, We
    generally specify SQL_SERVER or Named Sequencetable for Primary key
    generation.
    For pointbase database, I dont know how to configure this?
    Could you help me in this regard,
    Thanks,
    Pandu

  • Help Primary Key generation

    According to article "Generating Primary Key Values in CMP Beans" (http://www.netbeans.org/kb/41/generated-primary-keys.html) you can specifiy automatic primary key generation.
    The following fragment describes a key issue when you have a existing database schema.
    If the database schema is not created during deployment, the primary key column in the mapped table must be of type NUMERIC with a precision of 19 or more, and must not be mapped to any CMP field. The Sun Java System Application Server generates unique values for the primary key column at runtime.
    In the used sample for how to set up a MySql database the creation of the customer table must be as follows:
    CREATE TABLE customer (
    id BIGINT(19) NOT NULL auto_increment, -- this column will be automat. generated
    lastName varchar(25) NOT NULL,
    firstName varchar(30) default NULL,
    PRIMARY KEY (id));
    My question is:
    Is it nescesary to have the field id to be decleared auto incremented?
    The first fragment says that the AS will create new values for the primary key. Or does the generation of primary keys only work if the pk field in the database table is auto incremented by the database?
    Please help. Thanks!
    Johan.

    Hello Johan,
    no, as i remember it does not work if you specify the id column as auto_increment. The J2EE bean container does manage the generation of the primary key, so the database must have a column type int(19) or bigint and primary key, not more.
    Hope this helps, more information is in the J2EE documentation from Sun, page 1012.
    Kind regards,
    marc.

  • Marinescu Primary Key Generation

    Hi
    i'm using Marinescus Primary Key Generation schema, but i'm having a problem
    As i see it in EJB Design Patterns (Marinescus Book), he uses a Hashtable to store the values so that the Bean doesn't have to access the database everytime
    My problem is that this Hashtable is not working, because each client when access the Bean, this creates a new bean (just like in the pattern) and thus there is never info on the Hashtable, thus the application has to go to the Database.
    If i put the Hashtable as static, i will have Concurrency Problems
    But my real problem is that i've seen various implementations of this pattern, and no one seems to talk about this problem
    Am i missing something ?
    I've thought maybe Marinescus uses only one static SessionBean (resolving the problem), but he create one Bean for each request also
    Thanks

    So, i found the problem
    I had the SessionBean configured as a Stateful Session Bean
    But if i change it to Stateless it starts working
    I still didn't figured out why (as no Load, Store, Passivation or Activation code exists to keep or get the Hashtable)
    So if any one could explain it to me, it would be nice :)
    Thanks

  • Error in primary key generation

    Hello,
    I am using Postgresql database with jboss. I am using sequence block pattern for generating automatic primary key using source code provided by ejbdesignpattern book. but when i use transaction attribute of RequiresNew for method getValueAfterIncrementingBy I get following exception. excpetion disappear when transaction attribute is changed to Required but book recommends using RequiresNew attribute for the mehtod
    can sombody tell y this exception is being raised and workaround.
    15:57:23,507 WARN [TxCapsule] Transaction XidImpl [FormatId=257, GlobalId=c40//
    1, BranchQual=] timed out. status=STATUS_ACTIVE
    15:57:23,707 WARN [TxCapsule] Transaction XidImpl [FormatId=257, GlobalId=c40//
    2, BranchQual=] timed out. status=STATUS_ACTIVE
    15:57:23,707 WARN [BeanLock] wait() interrupted in txLock, possibly a timeout
    15:57:23,707 ERROR [BeanLock] Thread[RMI TCP Connection(2)-192.168.0.46,5,RMI Ru
    ntime]Saw rolled back tx=TransactionImpl:XidImpl [FormatId=257, GlobalId=c40//2,
    BranchQual=] waiting for txLock
    15:57:23,707 WARN [TxCapsule] Lock contention, tx=XidImpl [FormatId=257, Global
    Id=c40//2, BranchQual=]
    15:57:23,727 ERROR [LogInterceptor] RuntimeException:
    java.lang.RuntimeException: Transaction marked for rollback, possibly a timeout
    at org.jboss.ejb.plugins.lock.QueuedPessimisticEJBLock.waitForTx(QueuedP
    essimisticEJBLock.java:339)
    at org.jboss.ejb.plugins.lock.QueuedPessimisticEJBLock.doSchedule(Queued
    PessimisticEJBLock.java:211)
    at org.jboss.ejb.plugins.lock.QueuedPessimisticEJBLock.schedule(QueuedPe
    ssimisticEJBLock.java:159)
    at org.jboss.ejb.plugins.EntityLockInterceptor.invoke(EntityLockIntercep
    tor.java:103)
    at org.jboss.ejb.plugins.EntityCreationInterceptor.invoke(EntityCreation
    Interceptor.java:69)
    at org.jboss.ejb.plugins.AbstractTxInterceptor.invokeNext(AbstractTxInte
    rceptor.java:107)
    at org.jboss.ejb.plugins.TxInterceptorCMT.runWithTransactions(TxIntercep
    torCMT.java:291)
    at org.jboss.ejb.plugins.TxInterceptorCMT.invoke(TxInterceptorCMT.java:9
    8)
    at org.jboss.ejb.plugins.SecurityInterceptor.invoke(SecurityInterceptor.
    java:130)
    at org.jboss.ejb.plugins.LogInterceptor.invoke(LogInterceptor.java:208)
    at org.jboss.ejb.EntityContainer.invoke(EntityContainer.java:493)
    at org.jboss.ejb.plugins.local.BaseLocalContainerInvoker.invoke(BaseLoca
    lContainerInvoker.java:301)
    at org.jboss.ejb.plugins.local.EntityProxy.invoke(EntityProxy.java:38)
    at $Proxy34.getValueAfterIncrementingBy(Unknown Source)
    at com.gmi.mportal.SequenceSessionBean.getNextSequenceNumber(SequenceSes
    sionBean.java:62)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
    java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
    sorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:324)
    at org.jboss.ejb.StatelessSessionContainer$ContainerInterceptor.invoke(S
    tatelessSessionContainer.java:660)
    at org.jboss.resource.connectionmanager.CachedConnectionInterceptor.invo
    ke(CachedConnectionInterceptor.java:186)
    at org.jboss.ejb.plugins.StatelessSessionInstanceInterceptor.invoke(Stat
    elessSessionInstanceInterceptor.java:77)
    at org.jboss.ejb.plugins.AbstractTxInterceptor.invokeNext(AbstractTxInte
    rceptor.java:107)
    at org.jboss.ejb.plugins.TxInterceptorCMT.runWithTransactions(TxIntercep
    torCMT.java:237)
    at org.jboss.ejb.plugins.TxInterceptorCMT.invoke(TxInterceptorCMT.java:9
    8)
    at org.jboss.ejb.plugins.SecurityInterceptor.invoke(SecurityInterceptor.
    java:130)
    at org.jboss.ejb.plugins.LogInterceptor.invoke(LogInterceptor.java:208)
    at org.jboss.ejb.StatelessSessionContainer.invoke(StatelessSessionContai
    ner.java:313)
    at org.jboss.ejb.Container.invoke(Container.java:738)
    at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:517)
    at org.jboss.invocation.jrmp.server.JRMPInvoker.invoke(JRMPInvoker.java:
    383)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
    java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
    sorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:324)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:261)
    at sun.rmi.transport.Transport$1.run(Transport.java:148)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:144)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:4
    60)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport
    .java:701)
    at java.lang.Thread.run(Thread.java:536)
    15:57:23,747 ERROR [LogInterceptor] EJBException, causedBy:
    java.lang.RuntimeException: Transaction marked for rollback, possibly a timeout
    at org.jboss.ejb.plugins.lock.QueuedPessimisticEJBLock.waitForTx(QueuedP
    essimisticEJBLock.java:339)
    at org.jboss.ejb.plugins.lock.QueuedPessimisticEJBLock.doSchedule(Queued
    PessimisticEJBLock.java:211)
    at org.jboss.ejb.plugins.lock.QueuedPessimisticEJBLock.schedule(QueuedPe
    ssimisticEJBLock.java:159)
    at org.jboss.ejb.plugins.EntityLockInterceptor.invoke(EntityLockIntercep
    tor.java:103)
    at org.jboss.ejb.plugins.EntityCreationInterceptor.invoke(EntityCreation
    Interceptor.java:69)
    at org.jboss.ejb.plugins.AbstractTxInterceptor.invokeNext(AbstractTxInte
    rceptor.java:107)
    at org.jboss.ejb.plugins.TxInterceptorCMT.runWithTransactions(TxIntercep
    torCMT.java:291)
    at org.jboss.ejb.plugins.TxInterceptorCMT.invoke(TxInterceptorCMT.java:9
    8)
    at org.jboss.ejb.plugins.SecurityInterceptor.invoke(SecurityInterceptor.
    java:130)
    at org.jboss.ejb.plugins.LogInterceptor.invoke(LogInterceptor.java:208)
    at org.jboss.ejb.EntityContainer.invoke(EntityContainer.java:493)
    at org.jboss.ejb.plugins.local.BaseLocalContainerInvoker.invoke(BaseLoca
    lContainerInvoker.java:301)
    at org.jboss.ejb.plugins.local.EntityProxy.invoke(EntityProxy.java:38)
    at $Proxy34.getValueAfterIncrementingBy(Unknown Source)
    at com.gmi.mportal.SequenceSessionBean.getNextSequenceNumber(SequenceSes
    sionBean.java:62)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
    java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
    sorImpl.java:25)

    I'm experiencing the exact same problem.
    I do have a piece of information to add, though.
    This problem only occurs when I run the code (generating a PK for a given table) the FIRST time. Once a row exists in the sequence table for a table, the code works.
    On the first run, the problem occurs after the row is inserted into the table. If the row already exists, you're all set.
    Still a problem, but at least you can work around it by prepopulating your sequence table.
    --- Matt

  • Database Deferred Primary Key generation

    Does anyone know how to configure 9iAS J2EE/OC4J to defer the creation of the Primary to the Database? For example, I have a table that is mapped to a CMP bean and the primary key is generated by a trigger in the database. I want the bean to use this database generated value but I can't figure out how to make it happen. I have tried setting the <prim-key-class> to java.lang.Object but that doesn't appear to be enough to get 9iAS to figure out that the primary key field is to come from the database.
    Regards,
    Nigel

    you should set in your entity object the attribute as DBSequence and then create a before insert trigger in the db table to get the pk from a sequence or so, something like:
    CREATE OR REPLACE TRIGGER trigger_name
    BEFORE INSERT
    ON table_name
    FOR EACH ROW
    begin
    select seq_name.nextval into :new.pk_id from dual;
    end;

  • CMP with Primary key generation in Oracle

    I need to know how can I from my Entity Beans use Oracle sequences to automatically create my primary key.
    I know that Weblogic lets to define with sequence to use in the deployment descriptor, but the problem is that I am using Websphere Application Server.
    Does anyone have any suggestion doing this.
    Very Thanks!!

    See if this link helps - http://theserverside.com/patterns/thread.jsp?thread_id=220

  • A challenging primary key generation problem..

    Hi !
    I have the following problem (this is in theory, not (yet) in practice):
    I have this set of entities with its respective primary keys in the database.. 0,1,2,3,4,5,...............,N
    In a certain moment in the future X, a transaction deletes record (for example) n < N.
    In a certain moment in the future Y after X, a transaction persists new entity Q.
    What primary key does it get ?
    Is it Q=n or is it Q=N+1 ?
    In case the latter, how can I achieve the former ? Is there JPA specified way to do it, or I shall use the "stupid" way.
    I.e. In general I want the gaps in the sequence (caused by deletion of entities), to be filled with the newly persisted ones.
    All suggestions are welcome :)
    P.S. If someone knows the actual difference between the PrimaryKeyGenerationTypes in JPA (SEQUENTIAL, IDENTITY, etc...) please, tell me :P
    Edited by: javaUserMuser on Aug 7, 2008 5:37 PM

    javaUserMuser wrote:
    Well 2^63 = 9 billion billion.. well, thats a lot really. but anyway using the gaps is preferable for me ;]You've still said nothing to support this view except "because I said so". I don't think you need it. Here's why:
    Assume there are 2^63 = 9 billion billion keys available to you. If your application consumes them at the rate of 1 key per millisecond, it'll take you ~36 billion years to exhaust all those keys. Since science estimates the age of the universe as 13-14 billion years, and creationists say it's 6000 years, I'd say you're safe if you throw away a key or two.
    You know your app. Adjust accordingly. Calculate how fast you'd have to consume keys to exhaust them all in 100 years for fun and compare it to your real requirements.
    Well there can be involved more than one db... In general how does a rdbms scale horizontally ? Can N-count physical nodes serve one logical DB ?Depends on the product. Consult the database you're using. Which product will you use?
    What kind of them ?See the calculation above.
    >
    I got what those IDENTITY etc. things mean, but.... anyway how do those differ not in the perspective of the database, rather of that of the developer <-- that is my question :PAs a developer, it means that I'd have to use a different id generator scheme in my configuration.
    In general, I like your posts :) Discussion is the mother of progressThank you, I'm glad you find them to be helpful.
    %

  • Primary key generation by insert trigger.

    I have a table and wish to automatically create a unique sequence number for use as the primary key.
    In PL/SQL I do something like this:
    create sequence personnel_seq;
    create or replace trigger personnel_insert
    before insert on personnel
    for each row
    declare seqNo NUMBER;
    begin
    select personnel_seq.NextVal into seqNo from dual;
    :new.vc_personnel_reference := seqNo;
    end personnel_insert;
    column personnel.vc_personnel_reference is the primary key of table personnel, and not null.
    What's the recommended way to do something similar in BC4J?
    At present I'm using the trigger but BC4J doesn't know it exists, and insists on a value for vc_personnel_reference being provided. It also insists on adding the primary key to the ViewObject's attributes.
    I can provide a dummy value in ViewObjectRowImpl.insertRow() but this seems cumbersome.
    Is there a better way?
    In fact can I do this kind of thing entirely in BC4J without the trigger?
    Tony.

    But be carefull with DBSequences.
    There's a "problem" because the DBSequencs is a Domain and a "domained" field is not equal to any other field.
    In that case if have an Entity with Id = 1 (where d comes out from a DbSequence) and You look for Id = n where n is a Number containing 1, You will not find Your record !!!
    As 9.0.2.; I don't know in 9.0.3.
    Bye
    Tullio

  • 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

  • Problem with automatic key generation

    Hi,
    I'm getting an exception when creating entity EJB's that use automatic primary key
    generation (I'm using MS SQL Server as the db). The data is being inserted correctly
    onto the database (including the auto generated key), but the auto generated primary
    key field in the EJB is being set to zero rather than the correct value. This causes
    a NoSuchEntityException.
    The db table has an identity set on the auto generated field, but this field is not
    the primary key.
    Does anyone have an idea as to what the problem is?
    thanks,
    Andy

    Make sure you are using a TX DataSource
    "Andy Pearson" <[email protected]> wrote in message
    news:3ccead40$[email protected]..
    >
    Hi,
    I'm getting an exception when creating entity EJB's that use automaticprimary key
    generation (I'm using MS SQL Server as the db). The data is being insertedcorrectly
    onto the database (including the auto generated key), but the autogenerated primary
    key field in the EJB is being set to zero rather than the correct value.This causes
    a NoSuchEntityException.
    The db table has an identity set on the auto generated field, but thisfield is not
    the primary key.
    Does anyone have an idea as to what the problem is?
    thanks,
    Andy

Maybe you are looking for