List of usage examples for org.hibernate.id IdentifierGenerationException IdentifierGenerationException
public IdentifierGenerationException(String msg)
From source file:com.enonic.cms.store.hibernate.id.IntegerBasedCustomIdentifierGenerator.java
License:Open Source License
private Integer selectLastKey(Connection conn, String tableName) throws SQLException { PreparedStatement ps = conn.prepareStatement(SELECT_LASTKEY); try {//from w w w . j av a 2 s. c om ps.setString(1, tableName); ResultSet rs = ps.executeQuery(); if (!rs.next()) { String msg = "Failed to read next key value for table '" + tableName + "', no row."; throw new IdentifierGenerationException(msg); } Integer lastKey = rs.getInt(1); if (rs.wasNull()) { String msg = "Failed to read next key value for table '" + tableName + "', key_llastkey was null."; throw new IdentifierGenerationException(msg); } closeResultSet(rs); return lastKey; } finally { closeStatement(ps); } }
From source file:com.farmafene.commons.hibernate.generators.WorkInOther.java
License:Open Source License
/** * {@inheritDoc}//from w w w . j a va 2 s . co m * * @since 1.0.0 */ private Serializable getNextValue(Connection conn, Object[] theKey) throws SQLException { PreparedStatement qps = null; PreparedStatement qps2 = null; ResultSet rs = null; ResultSet rs2 = null; String result = null; String sql = null; Serializable id = null; try { sql = getSelectQuery(dialectoBBDD); logger.debug(sql); qps = conn.prepareStatement(sql); cargaValores(qps, 1, theKey); rs = qps.executeQuery(); if (!rs.next()) { logger.info("No se puede leer el siguiente valor - es necesario introducir valores en la tabla: " + db.getNombreSecuencia()); qps2 = conn.prepareStatement(getInsertQuery(dialectoBBDD)); int index = cargaValores(qps2, 1, theKey); cargaValores(qps2, index, theKey); qps2.executeUpdate(); rs2 = qps.executeQuery(); if (rs2.next()) { result = rs2.getString(1); } else { throw new IdentifierGenerationException("No se ha podido generar el identificador"); } } else { result = rs.getString(1); } if (result == null) { throw new IdentifierGenerationException("Identificador no encontrado"); } try { id = (Serializable) campos.getTarget().getType().getConstructor(String.class).newInstance(result); if ("0".equals(id.toString())) { throw new SQLException("Error en la generacin del identificador"); } } catch (IllegalArgumentException e) { throw new IdentifierGenerationException(e.getMessage(), e); } catch (SecurityException e) { throw new IdentifierGenerationException(e.getMessage(), e); } catch (InstantiationException e) { throw new IdentifierGenerationException(e.getMessage(), e); } catch (IllegalAccessException e) { throw new IdentifierGenerationException(e.getMessage(), e); } catch (InvocationTargetException e) { throw new IdentifierGenerationException(e.getMessage(), e); } catch (NoSuchMethodException e) { throw new IdentifierGenerationException(e.getMessage(), e); } return id; } catch (SQLException e) { throw new SQLException("Identificador no encontrado", e); } finally { if (rs2 != null) { try { rs2.close(); } catch (Exception e) { } } if (rs != null) { try { rs.close(); } catch (Exception e) { } } if (qps2 != null) { try { qps2.close(); } catch (Exception e) { } } if (qps != null) { try { qps.close(); } catch (Exception e) { } } } }
From source file:com.literatejava.hibernate.allocator.LinearBlockAllocator.java
License:Open Source License
public void configure(Type type, Properties params, Dialect dialect) { ObjectNameNormalizer normalizer = (ObjectNameNormalizer) params.get(IDENTIFIER_NORMALIZER); this.tableName = ConfigurationHelper.getString(ALLOC_TABLE, params, DEFAULT_TABLE); this.sequenceColumn = ConfigurationHelper.getString(SEQUENCE_COLUMN, params, DEFAULT_SEQUENCE_COLUMN); this.allocColumn = ConfigurationHelper.getString(ALLOC_COLUMN, params, DEFAULT_ALLOC_COLUMN); // get SequenceName; default to Entities' TableName. // -//from w ww . j a v a 2s. c om this.sequenceName = ConfigurationHelper.getString(SEQUENCE_NAME, params, params.getProperty(PersistentIdentifierGenerator.TABLE)); if (sequenceName == null) { throw new IdentifierGenerationException( "LinearBlockAllocator: '" + SEQUENCE_NAME + "' must be specified"); } this.blockSize = ConfigurationHelper.getInt(BLOCK_SIZE, params, DEFAULT_BLOCK_SIZE); if (blockSize < 1) { blockSize = 1; } // qualify Table Name, if necessary; // -- if (tableName.indexOf('.') < 0) { String schemaName = normalizer.normalizeIdentifierQuoting(params.getProperty(SCHEMA)); String catalogName = normalizer.normalizeIdentifierQuoting(params.getProperty(CATALOG)); this.tableName = Table.qualify(catalogName, schemaName, tableName); } // build SQL strings; // -- use appendLockHint(LockMode) for now, as that is how Hibernate's generators do it. // this.query = "select " + allocColumn + " from " + dialect.appendLockHint(LockMode.PESSIMISTIC_WRITE, tableName) + " where " + sequenceColumn + " = ?" + dialect.getForUpdateString(); this.update = "update " + tableName + " set " + allocColumn + " = ? where " + sequenceColumn + " = ? and " + allocColumn + " = ?"; // setup Return Type & Result Holder. // -- this.returnType = type; this.returnClass = type.getReturnedClass(); this.resultFactory = IdentifierGeneratorHelper.getIntegralDataTypeHolder(returnClass); // done. }
From source file:com.literatejava.hibernate.allocator.LinearBlockAllocator.java
License:Open Source License
protected long allocateBlock(final SessionImplementor session) { AbstractReturningWork<Long> work = new AbstractReturningWork<Long>() { @Override/*from www . j av a2 s .co m*/ public Long execute(Connection conn) throws SQLException { final SqlStatementLogger statementLogger = session.getFactory().getServiceRegistry() .getService(JdbcServices.class).getSqlStatementLogger(); long result; int rows; do { // The loop ensures atomicity of the // select + update even for no transaction // or read committed isolation level statementLogger.logStatement(query, FormatStyle.BASIC.getFormatter()); PreparedStatement qps = conn.prepareStatement(query); try { qps.setString(1, sequenceName); ResultSet rs = qps.executeQuery(); if (!rs.next()) { String err = "could not read a hi value - you need to populate the table: " + tableName + ", " + sequenceName; log.error(err); throw new IdentifierGenerationException(err); } result = rs.getLong(1); rs.close(); } catch (SQLException sqle) { log.error("could not read a hi value", sqle); throw sqle; } finally { qps.close(); } statementLogger.logStatement(update, FormatStyle.BASIC.getFormatter()); PreparedStatement ups = conn.prepareStatement(update); try { ups.setLong(1, result + blockSize); ups.setString(2, sequenceName); ups.setLong(3, result); rows = ups.executeUpdate(); } catch (SQLException sqle) { log.error("could not update hi value in: " + tableName, sqle); throw sqle; } finally { ups.close(); } } while (rows == 0); // success; // -- allocated a Block. // statisticsTableAccessCount++; return new Long(result); } }; // perform in an isolated Transaction. long allocated = session.getTransactionCoordinator().getTransaction().createIsolationDelegate() .delegateWork(work, true); return allocated; }
From source file:org.intelligentsia.utility.generator.TableGenerator.java
License:Apache License
/** * Populate initiale value./*from www . jav a 2 s . com*/ * * @param conn * @throws SQLException */ private void populate(final Connection conn) throws SQLException, IdentifierGenerationException { final PreparedStatement ips = conn.prepareStatement(insert); try { ips.executeUpdate(); } catch (final SQLException sqle) { final String err = "could not populate initiale hi value in: " + tableName; log.error(err, sqle); throw new IdentifierGenerationException(err); } finally { ips.close(); } }
From source file:org.jboss.ejb3.entity.JTATableIdGenerator.java
License:Open Source License
public synchronized Serializable generate(SessionImplementor session, Object object) throws HibernateException { // get TransactionManager from JNDI // no JNDI properties provided -> we are in the container TransactionManager tm = transactionManagerLookup.getTransactionManager(new Properties()); Transaction surroundingTransaction = null; // for resuming in finally block Connection conn = null; // for ressource cleanup String sql = null; // for exception try {/*w ww .j ava 2 s.co m*/ long result; // holds the resulting sequence value // prepare a new transaction context for the generator surroundingTransaction = tm.suspend(); if (log.isDebugEnabled()) { log.debug("surrounding tx suspended"); } tm.begin(); // get connection from managed environment conn = session.getBatcher().openConnection(); // execute fetching of current sequence value sql = query; PreparedStatement qps = conn.prepareStatement(query); try { ResultSet rs = qps.executeQuery(); if (!rs.next()) { String err = "could not read sequence value - you need to populate the table: " + tableName; log.error(err); throw new IdentifierGenerationException(err); } result = rs.getLong(1); rs.close(); } catch (SQLException sqle) { log.error("could not read a sequence value", sqle); throw sqle; } finally { qps.close(); } // increment sequence value sql = update; long sequence = result + 1; PreparedStatement ups = conn.prepareStatement(update); try { ups.setLong(1, sequence); ups.setLong(2, result); ups.executeUpdate(); } catch (SQLException sqle) { log.error("could not update sequence value in: " + tableName, sqle); throw sqle; } finally { ups.close(); } // commit transaction to ensure updated sequence is not rolled back tm.commit(); // transform sequence to the desired type and return the value Number typedSequence = IdentifierGeneratorFactory.createNumber(sequence, returnClass); if (log.isDebugEnabled()) { log.debug("generate() returned: " + typedSequence); } return typedSequence; } catch (SQLException sqle) { throw JDBCExceptionHelper.convert(session.getFactory().getSQLExceptionConverter(), sqle, "could not get or update next value", sql); } catch (Exception e) { try { tm.rollback(); throw new HibernateException(e); } catch (SystemException e1) { throw new HibernateException(e1); } } finally { if (conn != null) try { conn.close(); } catch (SQLException e) { // ignore exception } // switch back to surrounding transaction context if (surroundingTransaction != null) { try { tm.resume(surroundingTransaction); if (log.isDebugEnabled()) { log.debug("surrounding tx resumed"); } } catch (Exception e) { throw new HibernateException(e); } } } }