protected long getUniqueLong ( FieldDescriptor field ) throws SequenceManagerException { boolean needsCommit = false ; long result = 0 ; /* arminw: use the associated broker instance, check if broker was in tx or we need to commit used connection. */ PersistenceBroker targetBroker = getBrokerForClass ( ) ; if ( ! targetBroker . isInTransaction ( ) ) { targetBroker . beginTransaction ( ) ; needsCommit = true ; } try { // lookup sequence name String sequenceName = calculateSequenceName ( field ) ; try { result = buildNextSequence ( targetBroker , field . getClassDescriptor ( ) , sequenceName ) ; /* if 0 was returned we assume that the stored procedure did not work properly. */ if ( result == 0 ) { throw new SequenceManagerException ( "No incremented value retrieved" ) ; } } catch ( Exception e ) { // maybe the sequence was not created log . info ( "Could not grab next key, message was " + e . getMessage ( ) + " - try to write a new sequence entry to database" ) ; try { // on create, make sure to get the max key for the table first long maxKey = SequenceManagerHelper . getMaxForExtent ( targetBroker , field ) ; createSequence ( targetBroker , field , sequenceName , maxKey ) ; } catch ( Exception e1 ) { String eol = SystemUtils . LINE_SEPARATOR ; throw new SequenceManagerException ( eol + "Could not grab next id, failed with " + eol + e . getMessage ( ) + eol + "Creation of new sequence failed with " + eol + e1 . getMessage ( ) + eol , e1 ) ; } try { result = buildNextSequence ( targetBroker , field . getClassDescriptor ( ) , sequenceName ) ; } catch ( Exception e1 ) { throw new SequenceManagerException ( "Could not grab next id although a sequence seems to exist" , e ) ; } } } finally { if ( targetBroker != null && needsCommit ) { targetBroker . commitTransaction ( ) ; } } return result ; }
Gets the actual key - will create a new row with the max key of table if it does not exist .