Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   *  Copyright 2009-2014 Pavel Ponec
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  *  Unless required by applicable law or agreed to in writing, software
  *  distributed under the License is distributed on an "AS IS" BASIS,
  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  */
 
 package org.ujorm.orm;
 
The default sequence provider. A result value is recieved from a special database table.

Author(s):
Pavel Ponec
 
 public class UjoSequencer {

    
Logger
 
     private static final UjoLogger LOGGER = UjoLoggerFactory.getLogger(UjoSequencer.class);

    
DB field: seqLimit
 
     public static final int SEQ_LIMIT = 1;
    
DB field: step
 
     public static final int SEQ_STEP = 1 + ;
    
DB field: maxValue
 
     public static final int SEQ_MAX_VALUE = 1 + ;

    
Basic table.
 
     final protected MetaTable table;
    
Current sequence value
 
     protected long sequence = 0;
    
Buffer limit
 
     protected long seqLimit = 0;
    
Total limit, zero means no restriction
 
     protected long maxValue = 0;
 
     public UjoSequencer(MetaTable table) {
         this. = table;
     }

    
Returns the next sequence value by a synchronized method.
 
     public synchronized long nextValue(final Session session) {
 
         if (<) {
             return ++;
         } else {
 
             final MetaDatabase db = ..of();
             Connection connection = null;
             String sql = null;
             StringBuilder out = new StringBuilder(64);
             try {
                 connection = session.getSeqConnection(db);
                 String tableName = db.getDialect().printFullTableName(getTable(), trueout).toString();
 
                 // UPDATE the next sequence:
                 out.setLength(0);
                 sql = db.getDialect().printSequenceNextValue(thisout).toString();
 
                 if (.isLoggable(.)) {
                     .log(.sql + "; [" + tableName + ']');
                 }
                 final int i = executeSql(connectionsqltableName);
                 if (i==0) {
                     // INSERT the new sequence:
                     out.setLength(0);
                     sql = db.getDialect().printSequenceInit(thisout).toString();
                     if (.isLoggable(.)) {
                         .log(.sql + "; ["+tableName+']');
                     }
                     executeSql(connectionsqltableName);
                 }
 
                 // SELECT UPDATE:
                 long[] seqMap = getCurrentDBSequence(connectionout);
                  = seqMap[];
                 int step = (intseqMap[];
                  = seqMap[];
                  = ( - step) + 1; // Get the last assigned number + 1;
 
                 if (!=0L) {
                    if (>) {
                        =;
                        if (>) {
                            String msg = "The sequence '" + tableName + "' needs to raise the maximum value: " + ;
                            throw new IllegalStateException(msg);
                        }
                        out.setLength(0);
                        sql = db.getDialect().printSequenceNextValue(thisout).toString();
                        if (.isLoggable(.)) {
                            .log(.sql + "; [" + tableName + ']');
                        }
                        executeSql(connectionsqltableName);
                    }
                    if (>.-step) {
                        String msg = "The sequence attribute '"
                            + tableName
                            + ".maxValue' is too hight,"
                            + " the recommended maximal value is: "
                            +   (.-step)
                            + " (Long.MAX_VALUE-step)"
                            ;
                        .log(.msg);
                    }
                }
                connection.commit();
            } catch (Throwable e) {
                if (connection!=nulltry {
                    connection.rollback();
                } catch (SQLException ex) {
                    .log(."Rollback fails");
                }
                IllegalStateException exception = e instanceof IllegalStateException
                    ? (IllegalStateExceptione
                    : new IllegalStateException("ILLEGAL SQL: " + sqle);
                throw exception;
            }
            return ;
        }
    }

    
Returns the database schema
    public String getDatabaseSchema() {
        return ..of(getDatabase());
    }

    
The UJO cache is the number of pre-allocated numbers inside the OrmUjo framework.
    public int getIncrement() {
        final int result = ..of(.getDatabase().getParams());
        return result;
    }

    
The cache of a database sequence is zero by default.
    public int getInitDbCache() {
        return 1;
    }

    
Returns model of the database
    public MetaDatabase getDatabase() {
        return ..of();
    }

    
Returns a related table or null if sequence is general for the all MetaDatabase space
    public MetaTable getTable() {
        return ;
    }

    
Method returns true because the internal table 'ujorm_pk_support' is required to get a next sequence value. In case you have a different imlementation, there is possible overwrite this method and return an another value.
    public boolean isSequenceTableRequired() {
        return true;
    }

    
Forces to reload sequence from db on next call for nextValue.
    public synchronized void reset() {
         = 0;
         = 0;
         = 0;
    }

    
Returns current db sequence for an actual table with a performance optimizations.

Parameters:
connection Connection
sql Temporarry buffer for a better performance. The value can be null a not null will be cleaned always.
Returns:
Returns current db sequence for an actual table with a value order:
[SEQ_LIMIT, SEQ_STEP, SEQ_MAX_VALUE].
If no sequence is found then the method returns the value null.
Throws:
java.lang.Exception
    public long[] getCurrentDBSequence(final Connection connectionStringBuilder sqlthrows Exception {
        if (sql != null) {
            sql.setLength(0);
        } else {
            sql = new StringBuilder(64);
        }
        final MetaDatabase db = ..of();
        final String tableName = db.getDialect().printFullTableName(getTable(), truesql).toString();
        sql.setLength(0);
        db.getDialect().printSequenceCurrentValue(thissql);
        PreparedStatement statement = null;
        ResultSet res = null;
        try {
            statement = connection.prepareStatement(sql.toString());
            statement.setString(1, tableName);
            res = statement.executeQuery();
            if (res.next()) {
                long[] result = new long[1 + ];
                result[] = res.getLong();
                result[] = res.getLong();
                result[] = res.getLong();
                return result;
            } else {
                return null;
            }
        } finally {
            MetaDatabase.close(nullstatementrestrue);
        }
    }

    
Executes UPDATE for required parameters
    protected int executeSql
            ( final Connection connection
            , final String sql
            , final String tableNamethrows SQLException {
        PreparedStatement statement = null;
        try {
            statement = connection.prepareStatement(sql);
            statement.setString(1, tableName);
            return statement.executeUpdate();
        } finally {
            MetaDatabase.close(nullstatementnulltrue);
        }
    }
New to GrepCode? Check out our FAQ X