db-ojb-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From arm...@apache.org
Subject cvs commit: db-ojb/src/java/org/apache/ojb/broker/platforms PlatformMySQLImpl.java PlatformHsqldbImpl.java PlatformDefaultImpl.java Platform.java
Date Fri, 09 May 2003 23:58:19 GMT
arminw      2003/05/09 16:58:18

  Modified:    src/test/org/apache/ojb repository_junit.xml
               src/test/org/apache/ojb/broker AllTests.java
               src/java/org/apache/ojb/broker/platforms
                        PlatformMySQLImpl.java PlatformHsqldbImpl.java
                        PlatformDefaultImpl.java Platform.java
  Added:       src/test/org/apache/ojb/broker/sequence
                        NativeIdentifierTest.java
               src/java/org/apache/ojb/broker/util/sequence
                        SequenceManagerNativeImpl.java
  Log:
  add first version of a sequence manager
  implementation supports identity columns
  (hsql, mysql, ...)
  requirements see javadoc
  
  Revision  Changes    Path
  1.64      +63 -0     db-ojb/src/test/org/apache/ojb/repository_junit.xml
  
  Index: repository_junit.xml
  ===================================================================
  RCS file: /home/cvs/db-ojb/src/test/org/apache/ojb/repository_junit.xml,v
  retrieving revision 1.63
  retrieving revision 1.64
  diff -u -r1.63 -r1.64
  --- repository_junit.xml	8 May 2003 14:54:51 -0000	1.63
  +++ repository_junit.xml	9 May 2003 23:58:18 -0000	1.64
  @@ -3183,6 +3183,69 @@
           />
       </class-descriptor>
   
  +    <!-- NOTE: This test class is specific for hsql, the database table was
  +    generated at runtime
  +    -->
  +    <class-descriptor
  +      class="org.apache.ojb.broker.sequence.NativeIdentifierTest$SMNativeObject"
  +      table="NATIVE_TEST"
  +    >
  +        <field-descriptor
  +        name="identifier"
  +        column="NATIVE_ID"
  +        jdbc-type="BIGINT"
  +        primarykey="true"
  +        autoincrement="true"
  +        access="readonly"
  +        />
  +
  +        <field-descriptor
  +        name="name"
  +        column="NAME"
  +        jdbc-type="VARCHAR"
  +        />
  +
  +        <collection-descriptor
  +         name="allReferences"
  +         element-class-ref="org.apache.ojb.broker.sequence.NativeIdentifierTest$SMNativeReference"
  +         auto-retrieve="true"
  +         auto-update="true"
  +         auto-delete="true"
  +      >
  +         <orderby name="refIdentifier" sort="DESC"/>
  +         <inverse-foreignkey field-ref="fkIdentifier"/>
  +      </collection-descriptor>
  +    </class-descriptor>
  +
  +<!-- NOTE: This test class is specific for hsql, the database table was
  +    generated at runtime
  +    -->
  +    <class-descriptor
  +      class="org.apache.ojb.broker.sequence.NativeIdentifierTest$SMNativeReference"
  +      table="NATIVE_REF_TEST"
  +    >
  +        <field-descriptor
  +        name="refIdentifier"
  +        column="NATIVE_ID"
  +        jdbc-type="BIGINT"
  +        primarykey="true"
  +        autoincrement="true"
  +        access="readonly"
  +        />
  +
  +        <field-descriptor
  +        name="refName"
  +        column="NAME"
  +        jdbc-type="VARCHAR"
  +        />
  +
  +        <field-descriptor
  +        name="fkIdentifier"
  +        column="FK_ID"
  +        jdbc-type="BIGINT"
  +        />
  +    </class-descriptor>
  +
   
   
   
  
  
  
  1.27      +2 -0      db-ojb/src/test/org/apache/ojb/broker/AllTests.java
  
  Index: AllTests.java
  ===================================================================
  RCS file: /home/cvs/db-ojb/src/test/org/apache/ojb/broker/AllTests.java,v
  retrieving revision 1.26
  retrieving revision 1.27
  diff -u -r1.26 -r1.27
  --- AllTests.java	9 May 2003 12:50:37 -0000	1.26
  +++ AllTests.java	9 May 2003 23:58:18 -0000	1.27
  @@ -7,6 +7,7 @@
   import org.apache.ojb.broker.metadata.RepositoryPersistorTest;
   import org.apache.ojb.broker.metadata.RepositoryElementsTest;
   import org.apache.ojb.broker.sequence.SequenceManagerTest;
  +import org.apache.ojb.broker.sequence.NativeIdentifierTest;
   
   /**
    * the facade to all TestCases in this package.
  @@ -75,6 +76,7 @@
           suite.addTest(new TestSuite(ExtentAwarePathExpressionsTest.class));
           suite.addTest(new TestSuite(RepositoryElementsTest.class));
           suite.addTest(new TestSuite(ConnectionFactoryTest.class));
  +        suite.addTest(new TestSuite(NativeIdentifierTest.class));
           return suite;
       }
   
  
  
  
  1.1                  db-ojb/src/test/org/apache/ojb/broker/sequence/NativeIdentifierTest.java
  
  Index: NativeIdentifierTest.java
  ===================================================================
  package org.apache.ojb.broker.sequence;
  
  import junit.framework.TestCase;
  import org.apache.commons.lang.builder.ToStringBuilder;
  import org.apache.ojb.broker.Identity;
  import org.apache.ojb.broker.PersistenceBroker;
  import org.apache.ojb.broker.PersistenceBrokerFactory;
  import org.apache.ojb.broker.metadata.MetadataManager;
  import org.apache.ojb.broker.metadata.SequenceDescriptor;
  import org.apache.ojb.broker.platforms.PlatformHsqldbImpl;
  import org.apache.ojb.broker.query.Criteria;
  import org.apache.ojb.broker.query.QueryByCriteria;
  import org.apache.ojb.broker.query.QueryFactory;
  import org.apache.ojb.broker.util.sequence.SequenceManagerNativeImpl;
  
  import java.io.Serializable;
  import java.sql.Connection;
  import java.sql.Statement;
  import java.util.ArrayList;
  import java.util.Iterator;
  import java.util.List;
  
  /**
   *
   * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>
   * @version $Id: NativeIdentifierTest.java,v 1.1 2003/05/09 23:58:18 arminw Exp $
   */
  public class NativeIdentifierTest extends TestCase
  {
      private static final String SELECT = "select * from NATIVE_TABLE";
      private static final String DROP = "DROP TABLE NATIVE_TEST";
      private static final String CREATE =
              "CREATE TABLE NATIVE_TEST(NATIVE_ID IDENTITY NOT NULL PRIMARY KEY,NAME VARCHAR(250))";
      private static final String INSERT_DUMMY = "INSERT INTO NATIVE_TEST (NAME) VALUES ('Dummy_1')";
  
      private static final String CREATE_REF =
              "CREATE TABLE NATIVE_REF_TEST(NATIVE_ID IDENTITY NOT NULL PRIMARY KEY,NAME VARCHAR(250),
FK_ID BIGINT)";
      private static final String DROP_REF = "DROP TABLE NATIVE_REF_TEST";
      private static final String INSERT_DUMMY_REF = "INSERT INTO NATIVE_REF_TEST (NAME) VALUES
('Dummy_2')";
  
  
      private PersistenceBroker broker;
      private Class oldSequenceManager;
  
      public NativeIdentifierTest(String s)
      {
          super(s);
      }
  
      public static void main(String[] args)
      {
          String[] arr = {NativeIdentifierTest.class.getName()};
          junit.textui.TestRunner.main(arr);
      }
  
      private boolean skipTest() throws Exception
      {
          PersistenceBroker pb = PersistenceBrokerFactory.defaultPersistenceBroker();
          boolean skip = !(pb.serviceConnectionManager().getSupportedPlatform() instanceof
PlatformHsqldbImpl);
          pb.close();
          return skip;
      }
  
      protected void setUp() throws Exception
      {
          super.setUp();
          if (skipTest()) return;
  
          PersistenceBroker pb = PersistenceBrokerFactory.defaultPersistenceBroker();
          Connection con;
          Statement stmt;
          boolean needTableCreation = false;
  
          try
          {
              con = pb.serviceConnectionManager().getConnection();
              stmt = con.createStatement();
              stmt.executeQuery(CREATE);
              stmt.close();
  
              stmt = con.createStatement();
              stmt.execute(INSERT_DUMMY);
              stmt.close();
  
              stmt = con.createStatement();
              stmt.executeQuery(CREATE_REF);
              stmt.close();
  
              stmt = con.createStatement();
              stmt.execute(INSERT_DUMMY_REF);
              stmt.close();
  
              SequenceDescriptor sd = MetadataManager.getInstance().connectionRepository().
                      getDescriptor(pb.getPBKey()).getSequenceDescriptor();
              oldSequenceManager = sd.getSequenceManagerClass();
              sd.setSequenceManagerClass(SequenceManagerNativeImpl.class);
          }
          finally
          {
              if (pb != null) pb.close();
          }
  
          PersistenceBrokerFactory.releaseAllInstances();
  
          broker = PersistenceBrokerFactory.defaultPersistenceBroker();
          SequenceDescriptor sd = MetadataManager.getInstance().connectionRepository().
                  getDescriptor(broker.getPBKey()).getSequenceDescriptor();
          assertEquals(SequenceManagerNativeImpl.class, sd.getSequenceManagerClass());
      }
  
      protected void tearDown() throws Exception
      {
          super.tearDown();
          if (skipTest()) return;
  
          try
          {
              broker.close();
          }
          catch (Exception e)
          {
          }
          Connection con;
          Statement stmt;
          boolean needTableCreation = false;
          PersistenceBroker pb = PersistenceBrokerFactory.defaultPersistenceBroker();
          try
          {
              con = pb.serviceConnectionManager().getConnection();
              stmt = con.createStatement();
              stmt.executeQuery(DROP);
              stmt.close();
  
              stmt = con.createStatement();
              stmt.executeQuery(DROP_REF);
              stmt.close();
  
              SequenceDescriptor sd = MetadataManager.getInstance().connectionRepository().
                      getDescriptor(broker.getPBKey()).getSequenceDescriptor();
              sd.setSequenceManagerClass(oldSequenceManager);
          }
          finally
          {
              if (pb != null) pb.close();
          }
  
          PersistenceBrokerFactory.releaseAllInstances();
          broker = PersistenceBrokerFactory.defaultPersistenceBroker();
          SequenceDescriptor sd = MetadataManager.getInstance().connectionRepository().
                  getDescriptor(broker.getPBKey()).getSequenceDescriptor();
          assertEquals(oldSequenceManager, sd.getSequenceManagerClass());
          broker.close();
      }
  
      public void testSimpleInsert() throws Exception
      {
          long timestamp = System.currentTimeMillis();
          String name = "testSimpleInsert_" + timestamp;
  
          if (skipTest()) return;
  
          SMNativeObject obj_1 = new SMNativeObject(null, name);
          SMNativeObject obj_2 = new SMNativeObject(null, name);
          SMNativeObject obj_3 = new SMNativeObject(null, name);
  
          broker.beginTransaction();
          broker.store(obj_1);
  //        System.out.println("obj_1: "+obj_1);
          broker.store(obj_2);
  //        System.out.println("obj_2: "+obj_2);
          broker.store(obj_3);
  //        System.out.println("obj_3: "+obj_3);
          broker.commitTransaction();
  
          Criteria crit = new Criteria();
          crit.addEqualTo("name", name);
          QueryByCriteria query = QueryFactory.newQuery(SMNativeObject.class, crit);
          int result = broker.getCount(query);
          assertEquals("Not all objects created", 3, result);
          assertNotNull(obj_1.getIdentifier());
      }
  
      public void testReferenceInsert() throws Exception
      {
          if (skipTest()) return;
          long timestamp = System.currentTimeMillis();
          String name = "testReferenceInsert_main_" + timestamp;
          String nameRef = "testReferenceInsert_reference_" + timestamp;
  
          SMNativeObject obj_1 = new SMNativeObject(null, name);
          SMNativeObject obj_2 = new SMNativeObject(null, name);
          SMNativeReference ref_1 = new SMNativeReference(null, nameRef);
          SMNativeReference ref_2 = new SMNativeReference(null, nameRef);
          SMNativeReference ref_3 = new SMNativeReference(null, nameRef);
          SMNativeReference ref_4 = new SMNativeReference(null, nameRef);
          obj_1.addReference(ref_1);
          obj_1.addReference(ref_2);
          obj_1.addReference(ref_3);
          obj_1.addReference(ref_4);
  
          broker.beginTransaction();
          // maybe first store a reference
          broker.store(ref_1);
  //        System.out.println("ref_1: "+ref_1);
          // then store main object
          broker.store(obj_1);
  //        System.out.println("obj_1: "+obj_1);
          broker.store(obj_2);
  //        System.out.println("obj_2: "+obj_2);
          broker.commitTransaction();
  
          Criteria crit = new Criteria();
          crit.addEqualTo("name", name);
          QueryByCriteria query = QueryFactory.newQuery(SMNativeObject.class, crit);
          int result = broker.getCount(query);
          assertEquals("Not all objects created", 2, result);
          assertNotNull(obj_1.getIdentifier());
          broker.clearCache();
          obj_1 = (SMNativeObject) broker.getObjectByIdentity(new Identity(obj_1, broker));
          List references = obj_1.getAllReferences();
          assertNotNull(references);
          Iterator it = references.iterator();
          while (it.hasNext())
          {
              SMNativeReference ref = (SMNativeReference) it.next();
              assertEquals("Main object fk expected", obj_1.getIdentifier(), ref.fkIdentifier);
              assertTrue("Currently we expect a positive value", (ref.getRefIdentifier().longValue()
> 0));
          }
  
          Criteria crit_2 = new Criteria();
          crit_2.addEqualTo("refName", nameRef);
          QueryByCriteria query_2 = QueryFactory.newQuery(SMNativeReference.class, crit_2);
          int result_2 = broker.getCount(query_2);
          assertEquals("Not all objects created", 4, result_2);
          assertNotNull(ref_3.getRefIdentifier());
  
          broker.clearCache();
          Identity id = new Identity(obj_1, broker);
          SMNativeObject retObj = (SMNativeObject) broker.getObjectByIdentity(id);
          List refList = retObj.getAllReferences();
          assertNotNull(refList);
      }
  
      public static class SMNativeObject implements Serializable
      {
          private Long identifier;
          private String name;
          private List allReferences;
  
          public SMNativeObject()
          {
          }
  
          public SMNativeObject(Long identifier, String name)
          {
              this.identifier = identifier;
              this.name = name;
          }
  
          public List getAllReferences()
          {
              return allReferences;
          }
  
          public void addReference(SMNativeReference reference)
          {
              if (allReferences == null)
              {
                  allReferences = new ArrayList();
              }
              allReferences.add(reference);
          }
  
          public void setAllReferences(List allReferences)
          {
              this.allReferences = allReferences;
          }
  
          public Long getIdentifier()
          {
              return identifier;
          }
  
          public void setIdentifier(Long identifier)
          {
              this.identifier = identifier;
          }
  
          public String getName()
          {
              return name;
          }
  
          public void setName(String name)
          {
              this.name = name;
          }
  
          public String toString()
          {
              return ToStringBuilder.reflectionToString(this);
          }
      }
  
      public static class SMNativeReference implements Serializable
      {
          private Long refIdentifier;
          private String refName;
          private Long fkIdentifier;
  
          public SMNativeReference()
          {
          }
  
          public SMNativeReference(Long refIdentifier, String refName)
          {
              this.refIdentifier = refIdentifier;
              this.refName = refName;
          }
  
          public Long getRefIdentifier()
          {
              return refIdentifier;
          }
  
          public void setRefIdentifier(Long refIdentifier)
          {
              this.refIdentifier = refIdentifier;
          }
  
          public String getRefName()
          {
              return refName;
          }
  
          public void setRefName(String refName)
          {
              this.refName = refName;
          }
  
          public String toString()
          {
              return ToStringBuilder.reflectionToString(this);
          }
      }
  }
  
  
  
  1.1                  db-ojb/src/java/org/apache/ojb/broker/util/sequence/SequenceManagerNativeImpl.java
  
  Index: SequenceManagerNativeImpl.java
  ===================================================================
  package org.apache.ojb.broker.util.sequence;
  /* ====================================================================
   * The Apache Software License, Version 1.1
   *
   * Copyright (c) 2001 The Apache Software Foundation.  All rights
   * reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. The end-user documentation included with the redistribution,
   *    if any, must include the following acknowledgment:
   *       "This product includes software developed by the
   *        Apache Software Foundation (http://www.apache.org/)."
   *    Alternately, this acknowledgment may appear in the software itself,
   *    if and wherever such third-party acknowledgments normally appear.
   *
   * 4. The names "Apache" and "Apache Software Foundation" and
   *    "Apache ObjectRelationalBridge" must not be used to endorse or promote products
   *    derived from this software without prior written permission. For
   *    written permission, please contact apache@apache.org.
   *
   * 5. Products derived from this software may not be called "Apache",
   *    "Apache ObjectRelationalBridge", nor may "Apache" appear in their name, without
   *    prior written permission of the Apache Software Foundation.
   *
   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   */
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  import org.apache.ojb.broker.PersistenceBroker;
  import org.apache.ojb.broker.PersistenceBrokerException;
  import org.apache.ojb.broker.accesslayer.JdbcAccess;
  import org.apache.ojb.broker.accesslayer.ResultSetAndStatement;
  import org.apache.ojb.broker.metadata.ClassDescriptor;
  import org.apache.ojb.broker.metadata.FieldDescriptor;
  import org.apache.ojb.broker.metadata.ObjectReferenceDescriptor;
  import org.apache.ojb.broker.metadata.fieldaccess.PersistentField;
  import org.apache.ojb.broker.query.Query;
  import org.apache.ojb.broker.util.ProxyHelper;
  
  import java.math.BigDecimal;
  import java.sql.Date;
  import java.sql.SQLException;
  import java.sql.Time;
  import java.sql.Timestamp;
  import java.sql.Types;
  import java.sql.Statement;
  import java.sql.ResultSet;
  import java.util.Iterator;
  import java.util.Vector;
  
  
  /**
   * Sequence manager implementation using native database sequence
   * generation.
   * <p>
   * <b>Note:</b>
   * The database identity column must not start with value '0' or
   * use negative values. So make sure oid generation starts with '1'
   * or higher.
   * </p>
   * <p>
   * Implementation configuration properties:
   * <table cellspacing="2" cellpadding="2" border="3" frame="box">
   * <tr>
   *     <td><strong>Property Key</strong></td>
   *     <td><strong>Property Values</strong></td>
   * </tr>
   * <tr>
   *     <td>none</td>
   *     <td>
   *
   *    </td>
   * </tr>
   * </table>
   * </p>
   *
   * <p>
   * <b>Limitations:</b>
   * <ul>
   * <li>native key generation is not extent aware,
   * when extent classes span several tables! Please
   * see more in shipped docs 'extents and polymorphism'.
   * </li>
   * </ul>
   * </p>
   * <br/>
   * <br/>
   *
   * @author <a href="mailto:travis@spaceprogram.com">Travis Reeder</a>
   * @author <a href="mailto:armin@codeAuLait.de">Armin Waibel</a>
   * @version $Id: SequenceManagerNativeImpl.java,v 1.1 2003/05/09 23:58:18 arminw Exp $
   */
  public class SequenceManagerNativeImpl extends AbstractSequenceManager
  {
      private Log log = LogFactory.getLog(SequenceManagerNativeImpl.class);
      /*
       TODO: find a better solution for this problem
       We need this dummy field to return a negative long value
       on getUniqueLong(...) call. If we return always the same
       value, the resulting Identity object was found on cache.
  
       Second problem is that generated oid (by Identity column)
       must not begin with 0.
       */
      private static long idDummy;
  
      public SequenceManagerNativeImpl(PersistenceBroker broker)
      {
          super(broker);
      }
  
      public void afterStore(JdbcAccess dbAccess, ClassDescriptor cld, Object obj) throws
SequenceManagerException
      {
          FieldDescriptor fd = cld.getAutoIncrementField();
          long newId = getLastInsert(dbAccess, cld);
          setFieldValue(obj, fd, new Long(newId));
      }
  
  
  
      public void setReferenceFKs(Object obj, ClassDescriptor cld) throws SequenceManagerException
      {
          Vector objectReferenceDescriptors = cld.getObjectReferenceDescriptors();
          // get all members of obj that are references and assign FKs
          Iterator i = objectReferenceDescriptors.iterator();
          while (i.hasNext())
          {
              ObjectReferenceDescriptor rds =
                      (ObjectReferenceDescriptor) i.next();
              Object ref = rds.getPersistentField().get(obj);
              if (ref != null)
              { // make sure the ref object actually exists
                  assertFkAssignment(obj, cld, ref, rds);
              }
          }
      }
  
      /**
       *
       */
      private void assertFkAssignment(Object obj, ClassDescriptor cld, Object ref, ObjectReferenceDescriptor
rds)
      {
          // avoid problems with proxy instances
          Class refClass = ProxyHelper.getRealClass(ref);
  
          // get ClassDescriptor for RefDescriptor object
          ClassDescriptor refCld =
                  getBrokerForClass().getDescriptorRepository().getDescriptorFor(refClass);
  
          // get all the fielddescriptors in the objects that reference this one so we can
set the new id
          FieldDescriptor[] objFkFields =
                  rds.getForeignKeyFieldDescriptors(cld);
          if (objFkFields != null)
          {
              FieldDescriptor refFld = refCld.getAutoIncrementField();
              FieldDescriptor fld = null;
              for (int i = 0; i < objFkFields.length; i++)
              {
                  fld = objFkFields[i];
                  fld.getPersistentField().set(obj, refFld.getPersistentField().get(ref));
              }
          }
      }
  
      private long getLastInsert(JdbcAccess dbAccess, ClassDescriptor cld) throws SequenceManagerException
      {
          FieldDescriptor fd = cld.getAutoIncrementField();
          long newId = 0;
          Statement stmt = null;
          if (fd != null)
          { // an autoinc column exists
              try
              {
                  stmt = getBrokerForClass().serviceConnectionManager().getConnection().createStatement();
                  ResultSet rs = stmt.executeQuery(lastInsertSelect(cld.getFullTableName()));
                  if (!rs.next())
                  {
                      throw new SequenceManagerException("Could not found native identifier");
                  }
                  newId = rs.getLong(1);
                  rs.close();
                  if (log.isDebugEnabled()) log.debug("After store - newid=" + newId);
              }
              catch (Exception e)
              {
                  throw new SequenceManagerException(e);
              }
              finally
              {
                  try
                  {
                      if(stmt != null) stmt.close();
                  }
                  catch (SQLException e)
                  {
                  }
              }
          }
          else
          {
              throw new SequenceManagerException(
                      "Field does not support autoincrement, please check repository: "+fd);
          }
          return newId;
      }
  
      /*
       * query for the last insert id. Depends on the used database,
       * thus we sould move this to Platform classes in further versions
       */
      protected String lastInsertSelect(String tableName)
      {
          return getBrokerForClass().serviceConnectionManager().
                  getSupportedPlatform().getLastInsertIdentityQuery(tableName);
      }
  
      private void setFieldValue(Object obj, FieldDescriptor field, Long identifier)
              throws SequenceManagerException
      {
          Object result = null;
          switch (field.getColumnJdbcType())
          {
              case Types.ARRAY:
                  {
                      Object[] arr = {identifier.toString()};
                      result = arr;
                      break;
                  }
              case Types.BIGINT:
                  {
                      result = identifier;
                      break;
                  }
              case Types.BINARY:
                  {
                      result = identifier.toString().getBytes();
                      break;
                  }
              case Types.CHAR:
                  {
                      result = identifier.toString();
                      break;
                  }
              case Types.DATE:
                  {
                      result = new Date(identifier.longValue());
                      break;
                  }
              case Types.DECIMAL:
                  {
                      result = new BigDecimal(identifier.longValue());
                      break;
                  }
              case Types.DOUBLE:
                  {
                      result = new Double(identifier.doubleValue());
                      break;
                  }
              case Types.FLOAT:
                  {
                      result = new Double(identifier.doubleValue());
                      break;
                  }
              case Types.INTEGER:
                  {
                      result = new Integer(identifier.intValue());
                      break;
                  }
              case Types.JAVA_OBJECT:
                  {
                      result = identifier;
                      break;
                  }
              case Types.LONGVARBINARY:
                  {
                      result = identifier.toString().getBytes();
                      break;
                  }
              case Types.LONGVARCHAR:
                  {
                      result = identifier.toString();
                      break;
                  }
              case Types.NUMERIC:
                  {
                      result = new BigDecimal(identifier.longValue());
                      break;
                  }
              case Types.REAL:
                  {
                      result = new Float(identifier.floatValue());
                      break;
                  }
              case Types.SMALLINT:
                  {
                      result = new Short(identifier.shortValue());
                      break;
                  }
              case Types.TIME:
                  {
                      result = new Time(identifier.longValue());
                      break;
                  }
              case Types.TIMESTAMP:
                  {
                      result = new Timestamp(identifier.longValue());
                      break;
                  }
              case Types.TINYINT:
                  {
                      result = new Byte(identifier.byteValue());
                      break;
                  }
              case Types.VARBINARY:
                  {
                      result = (byte[]) identifier.toString().getBytes();
                      break;
                  }
              case Types.VARCHAR:
                  {
                      result = identifier.toString();
                      break;
                  }
              default:
                  {
                      result = identifier;
                      break;
                  }
          }
          result = field.getFieldConversion().sqlToJava(result);
          PersistentField pf = field.getPersistentField();
          pf.set(obj, result);
      }
  
      /**
       * returns a negative value
       */
      protected long getUniqueLong(FieldDescriptor field) throws SequenceManagerException
      {
          return --idDummy;
      }
  }
  
  
  
  1.3       +5 -0      db-ojb/src/java/org/apache/ojb/broker/platforms/PlatformMySQLImpl.java
  
  Index: PlatformMySQLImpl.java
  ===================================================================
  RCS file: /home/cvs/db-ojb/src/java/org/apache/ojb/broker/platforms/PlatformMySQLImpl.java,v
  retrieving revision 1.2
  retrieving revision 1.3
  diff -u -r1.2 -r1.3
  --- PlatformMySQLImpl.java	17 Jun 2002 19:34:11 -0000	1.2
  +++ PlatformMySQLImpl.java	9 May 2003 23:58:18 -0000	1.3
  @@ -64,6 +64,7 @@
    */
   public class PlatformMySQLImpl extends PlatformDefaultImpl
   {
  +    private static final String LAST_INSERT = "SELECT LAST_INSERT_ID() ";
   
       /*
        * @see Platform#setObjectForStatement(PreparedStatement, int, Object, int)
  @@ -85,4 +86,8 @@
           return SQL92_NOPAREN_JOIN_SYNTAX;
       }
   
  +    public String getLastInsertIdentityQuery(String tableName)
  +    {
  +        return LAST_INSERT + tableName;
  +    }
   }
  
  
  
  1.4       +6 -2      db-ojb/src/java/org/apache/ojb/broker/platforms/PlatformHsqldbImpl.java
  
  Index: PlatformHsqldbImpl.java
  ===================================================================
  RCS file: /home/cvs/db-ojb/src/java/org/apache/ojb/broker/platforms/PlatformHsqldbImpl.java,v
  retrieving revision 1.3
  retrieving revision 1.4
  diff -u -r1.3 -r1.4
  --- PlatformHsqldbImpl.java	21 Sep 2002 15:54:15 -0000	1.3
  +++ PlatformHsqldbImpl.java	9 May 2003 23:58:18 -0000	1.4
  @@ -64,7 +64,7 @@
    */
   public class PlatformHsqldbImpl extends PlatformDefaultImpl
   {
  -
  +    private static final String LAST_INSERT = "CALL IDENTITY()";
   
       /**
        * Get join syntax type for this RDBMS - one on of the constants from JoinSyntaxType
interface
  @@ -74,4 +74,8 @@
           return SQL92_NOPAREN_JOIN_SYNTAX;
       }
   
  +    public String getLastInsertIdentityQuery(String tableName)
  +    {
  +        return LAST_INSERT;
  +    }
   }
  
  
  
  1.15      +22 -16    db-ojb/src/java/org/apache/ojb/broker/platforms/PlatformDefaultImpl.java
  
  Index: PlatformDefaultImpl.java
  ===================================================================
  RCS file: /home/cvs/db-ojb/src/java/org/apache/ojb/broker/platforms/PlatformDefaultImpl.java,v
  retrieving revision 1.14
  retrieving revision 1.15
  diff -u -r1.14 -r1.15
  --- PlatformDefaultImpl.java	7 Apr 2003 17:59:40 -0000	1.14
  +++ PlatformDefaultImpl.java	9 May 2003 23:58:18 -0000	1.15
  @@ -80,15 +80,15 @@
   public class PlatformDefaultImpl implements Platform, JoinSyntaxTypes
   {
       protected Logger log = LoggerFactory.getLogger(PlatformDefaultImpl.class);
  -    
  +
       protected boolean m_batchUpdatesChecked = false;
       protected boolean m_supportsBatchUpdates = false;
  -    
  +
       public boolean supportsBatchOperations()
       {
           return m_supportsBatchUpdates;
       }
  -    
  +
       public void checkForBatchSupport(Connection conn)
       {
           if (!m_batchUpdatesChecked)
  @@ -110,12 +110,12 @@
               }
           }
       }
  -    
  +
       public void afterStatementCreate(Statement stmt) throws PlatformException
       {
           //noop
       }
  -    
  +
       public void beforeStatementClose(Statement stmt, ResultSet rs) throws PlatformException
       {
           if (rs != null)
  @@ -130,12 +130,12 @@
               }
           }
       }
  -    
  +
       public void afterStatementClose(Statement stmt, ResultSet rs) throws PlatformException
       {
           //nothing
       }
  -    
  +
       /**
        * @see Platform#initializeJdbcConnection
        */
  @@ -185,7 +185,7 @@
                   break;
           }
       }
  -    
  +
       public void changeAutoCommitState(JdbcConnectionDescriptor jcd, Connection con, boolean
newState)
       {
           if (con == null)
  @@ -213,7 +213,7 @@
               }
           }
       }
  -    
  +
       /*
        * @see Platform#setObject(PreparedStatement, int, Object, int)
        */
  @@ -230,7 +230,7 @@
               ps.setObject(index, value, sqlType);
           }
       }
  -    
  +
       /*
        * @see Platform#setNullForStatement(PreparedStatement, int, int)
        */
  @@ -238,7 +238,7 @@
       {
           ps.setNull(index, sqlType);
       }
  -    
  +
       //    /*
       //     * @see Platform#ignoreAutocommitExceptions()
       //     */
  @@ -254,7 +254,7 @@
       //    {
       //        return useAutoCommit;
       //    }
  -    
  +
       /**
        * Get join syntax type for this RDBMS - one on of the constants from JoinSyntaxType
interface
        * @see Platform#getJoinSyntaxType
  @@ -263,7 +263,7 @@
       {
           return SQL92_JOIN_SYNTAX;
       }
  -    
  +
       /**
        * Override default ResultSet size determination (rs.last();rs.getRow())
        * with select count(*) operation
  @@ -273,7 +273,7 @@
       {
           return false;
       }
  -    
  +
       /**
        * Override this method to enable database based sequence generation
        */
  @@ -282,7 +282,7 @@
           /*default implementation does not support this*/
           throw new UnsupportedOperationException("This feature is not supported by this
implementation");
       }
  -    
  +
       /**
        * Override this method to enable database based sequence generation
        */
  @@ -291,7 +291,7 @@
           /*default implementation does not support this*/
           throw new UnsupportedOperationException("This feature is not supported by this
implementation");
       }
  -    
  +
       /**
        * Override this method to enable database based sequence generation
        */
  @@ -307,4 +307,10 @@
           /*@todo implementation*/
           throw new UnsupportedOperationException("Not supported by this implementation");
   	}
  +
  +    public String getLastInsertIdentityQuery(String tableName)
  +    {
  +        /*@todo implementation*/
  +        throw new UnsupportedOperationException("This feature is not supported by this
implementation");
  +    }
   }
  
  
  
  1.14      +7 -1      db-ojb/src/java/org/apache/ojb/broker/platforms/Platform.java
  
  Index: Platform.java
  ===================================================================
  RCS file: /home/cvs/db-ojb/src/java/org/apache/ojb/broker/platforms/Platform.java,v
  retrieving revision 1.13
  retrieving revision 1.14
  diff -u -r1.13 -r1.14
  --- Platform.java	2 Apr 2003 22:56:36 -0000	1.13
  +++ Platform.java	9 May 2003 23:58:18 -0000	1.14
  @@ -185,4 +185,10 @@
        */
       public CallableStatement prepareNextValProcedureStatement(Connection con, String procedureName,
                                                                 String sequenceName) throws
PlatformException;
  +
  +    /**
  +     * If database supports native key generation via identity column, this
  +     * method should return the sql-query to obtain the last generated id.
  +     */
  +    public String getLastInsertIdentityQuery(String tableName);
   }
  
  
  

Mime
View raw message