[hibernate-commits] Hibernate SVN: r19469 - in core/branches/Branch_3_5/core/src: main/java/org/hibernate/id/enhanced and 1 other directories.

hibernate-commits at lists.jboss.org hibernate-commits at lists.jboss.org
Tue May 11 15:24:54 EDT 2010


Author: steve.ebersole at jboss.com
Date: 2010-05-11 15:24:54 -0400 (Tue, 11 May 2010)
New Revision: 19469

Added:
   core/branches/Branch_3_5/core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorTest.java
Modified:
   core/branches/Branch_3_5/core/src/main/java/org/hibernate/id/MultipleHiLoPerTableGenerator.java
   core/branches/Branch_3_5/core/src/main/java/org/hibernate/id/SequenceGenerator.java
   core/branches/Branch_3_5/core/src/main/java/org/hibernate/id/SequenceHiLoGenerator.java
   core/branches/Branch_3_5/core/src/main/java/org/hibernate/id/enhanced/OptimizerFactory.java
Log:
HHH-5042 - TableGenerator does not increment hibernate_sequences.next_hi_value anymore after having exhausted the current lo-range

Modified: core/branches/Branch_3_5/core/src/main/java/org/hibernate/id/MultipleHiLoPerTableGenerator.java
===================================================================
--- core/branches/Branch_3_5/core/src/main/java/org/hibernate/id/MultipleHiLoPerTableGenerator.java	2010-05-11 18:44:39 UTC (rev 19468)
+++ core/branches/Branch_3_5/core/src/main/java/org/hibernate/id/MultipleHiLoPerTableGenerator.java	2010-05-11 19:24:54 UTC (rev 19469)
@@ -37,6 +37,8 @@
 import org.hibernate.LockMode;
 import org.hibernate.MappingException;
 import org.hibernate.cfg.ObjectNameNormalizer;
+import org.hibernate.id.enhanced.AccessCallback;
+import org.hibernate.id.enhanced.OptimizerFactory;
 import org.hibernate.jdbc.util.FormatStyle;
 import org.hibernate.dialect.Dialect;
 import org.hibernate.engine.SessionImplementor;
@@ -62,7 +64,7 @@
  * <p/>
  * <p>This implementation is not compliant with a user connection</p>
  * <p/>
- * 
+ *
  * <p>Allowed parameters (all of them are optional):</p>
  * <ul>
  * <li>table: table name (default <tt>hibernate_sequences</tt>)</li>
@@ -76,12 +78,12 @@
  * @author Emmanuel Bernard
  * @author <a href="mailto:kr at hbt.de">Klaus Richarz</a>.
  */
-public class MultipleHiLoPerTableGenerator 
+public class MultipleHiLoPerTableGenerator
 	extends TransactionHelper
 	implements PersistentIdentifierGenerator, Configurable {
-	
+
 	private static final Logger log = LoggerFactory.getLogger(MultipleHiLoPerTableGenerator.class);
-	
+
 	public static final String ID_TABLE = "table";
 	public static final String PK_COLUMN_NAME = "primary_key_column";
 	public static final String PK_VALUE_NAME = "primary_key_value";
@@ -92,7 +94,7 @@
 	public static final String DEFAULT_TABLE = "hibernate_sequences";
 	private static final String DEFAULT_PK_COLUMN = "sequence_name";
 	private static final String DEFAULT_VALUE_COLUMN = "sequence_next_hi_value";
-	
+
 	private String tableName;
 	private String pkColumnName;
 	private String valueColumnName;
@@ -104,8 +106,7 @@
 	public static final String MAX_LO = "max_lo";
 
 	private int maxLo;
-	private int lo;
-	private IntegralDataTypeHolder value;
+	private OptimizerFactory.LegacyHiLoAlgorithmOptimizer hiloOptimizer;
 
 	private Class returnClass;
 	private int keySize;
@@ -149,19 +150,15 @@
 		IntegralDataTypeHolder value = IdentifierGeneratorHelper.getIntegralDataTypeHolder( returnClass );
 		int rows;
 		do {
-			// The loop ensures atomicity of the
-			// select + update even for no transaction
-			// or read committed isolation level
-
-			//sql = query;
-			SQL_STATEMENT_LOGGER.logStatement( sql, FormatStyle.BASIC );
-			PreparedStatement qps = conn.prepareStatement(query);
+			SQL_STATEMENT_LOGGER.logStatement( query, FormatStyle.BASIC );
+			PreparedStatement qps = conn.prepareStatement( query );
 			PreparedStatement ips = null;
 			try {
 				ResultSet rs = qps.executeQuery();
 				boolean isInitialized = rs.next();
 				if ( !isInitialized ) {
 					value.initialize( 0 );
+					SQL_STATEMENT_LOGGER.logStatement( insert, FormatStyle.BASIC );
 					ips = conn.prepareStatement( insert );
 					value.bind( ips, 1 );
 					ips.execute();
@@ -182,7 +179,8 @@
 				qps.close();
 			}
 
-			PreparedStatement ups = conn.prepareStatement(update);
+			SQL_STATEMENT_LOGGER.logStatement( update, FormatStyle.BASIC );
+			PreparedStatement ups = conn.prepareStatement( update );
 			try {
 				value.copy().increment().bind( ups, 1 );
 				value.bind( ups, 2 );
@@ -195,12 +193,12 @@
 			finally {
 				ups.close();
 			}
-		}
-		while (rows==0);
+		} while ( rows==0 );
+
 		return value;
 	}
 
-	public synchronized Serializable generate(SessionImplementor session, Object obj)
+	public synchronized Serializable generate(final SessionImplementor session, Object obj)
 		throws HibernateException {
 		// maxLo < 1 indicates a hilo generator with no hilo :?
 		if ( maxLo < 1 ) {
@@ -212,15 +210,13 @@
 			return value.makeValue();
 		}
 
-		if ( lo > maxLo ) {
-			IntegralDataTypeHolder hiVal = (IntegralDataTypeHolder) doWorkInNewTransaction( session );
-			lo = ( hiVal.eq( 0 ) ) ? 1 : 0;
-			value = hiVal.copy().multiplyBy( maxLo+1 ).add( lo );
-			if ( log.isDebugEnabled() ) {
-				log.debug("new hi value: " + hiVal);
-			}
-		}
-		return value.makeValueThenIncrement();
+		return hiloOptimizer.generate(
+				new AccessCallback() {
+					public IntegralDataTypeHolder getNextValue() {
+						return (IntegralDataTypeHolder) doWorkInNewTransaction( session );
+					}
+				}
+		);
 	}
 
 	public void configure(Type type, Properties params, Dialect dialect) throws MappingException {
@@ -270,10 +266,10 @@
 			valueColumnName +
 			" = ? and " +
 			pkColumnName +
-			" = '" + 
-			keyValue 
+			" = '" +
+			keyValue
 			+ "'";
-		
+
 		insert = "insert into " + tableName +
 			"(" + pkColumnName + ", " +	valueColumnName + ") " +
 			"values('"+ keyValue +"', ?)";
@@ -281,7 +277,8 @@
 
 		//hilo config
 		maxLo = PropertiesHelper.getInt(MAX_LO, params, Short.MAX_VALUE);
-		lo = maxLo + 1; // so we "clock over" on the first invocation
 		returnClass = type.getReturnedClass();
+
+		hiloOptimizer = new OptimizerFactory.LegacyHiLoAlgorithmOptimizer( returnClass, maxLo );
 	}
 }

Modified: core/branches/Branch_3_5/core/src/main/java/org/hibernate/id/SequenceGenerator.java
===================================================================
--- core/branches/Branch_3_5/core/src/main/java/org/hibernate/id/SequenceGenerator.java	2010-05-11 18:44:39 UTC (rev 19468)
+++ core/branches/Branch_3_5/core/src/main/java/org/hibernate/id/SequenceGenerator.java	2010-05-11 19:24:54 UTC (rev 19469)
@@ -72,6 +72,10 @@
 	private Type identifierType;
 	private String sql;
 
+	public Type getIdentifierType() {
+		return identifierType;
+	}
+
 	public void configure(Type type, Properties params, Dialect dialect) throws MappingException {
 		ObjectNameNormalizer normalizer = ( ObjectNameNormalizer ) params.get( IDENTIFIER_NORMALIZER );
 		sequenceName = normalizer.normalizeIdentifierQuoting(

Modified: core/branches/Branch_3_5/core/src/main/java/org/hibernate/id/SequenceHiLoGenerator.java
===================================================================
--- core/branches/Branch_3_5/core/src/main/java/org/hibernate/id/SequenceHiLoGenerator.java	2010-05-11 18:44:39 UTC (rev 19468)
+++ core/branches/Branch_3_5/core/src/main/java/org/hibernate/id/SequenceHiLoGenerator.java	2010-05-11 19:24:54 UTC (rev 19469)
@@ -26,11 +26,11 @@
 import java.io.Serializable;
 import java.util.Properties;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.hibernate.MappingException;
 import org.hibernate.dialect.Dialect;
 import org.hibernate.engine.SessionImplementor;
+import org.hibernate.id.enhanced.AccessCallback;
+import org.hibernate.id.enhanced.OptimizerFactory;
 import org.hibernate.type.Type;
 import org.hibernate.util.PropertiesHelper;
 
@@ -50,23 +50,24 @@
  * @author Gavin King
  */
 public class SequenceHiLoGenerator extends SequenceGenerator {
-
 	public static final String MAX_LO = "max_lo";
 
-	private static final Logger log = LoggerFactory.getLogger(SequenceHiLoGenerator.class);
-
 	private int maxLo;
-	private int lo;
 
-	private IntegralDataTypeHolder value;
+	private OptimizerFactory.LegacyHiLoAlgorithmOptimizer hiloOptimizer;
 
 	public void configure(Type type, Properties params, Dialect d) throws MappingException {
 		super.configure(type, params, d);
-		maxLo = PropertiesHelper.getInt(MAX_LO, params, 9);
-		lo = maxLo + 1; // so we "clock over" on the first invocation
+
+		maxLo = PropertiesHelper.getInt( MAX_LO, params, 9 );
+
+		hiloOptimizer = new OptimizerFactory.LegacyHiLoAlgorithmOptimizer(
+				getIdentifierType().getReturnedClass(),
+				maxLo
+		);
 	}
 
-	public synchronized Serializable generate(SessionImplementor session, Object obj) {
+	public synchronized Serializable generate(final SessionImplementor session, Object obj) {
 		// maxLo < 1 indicates a hilo generator with no hilo :?
 		if ( maxLo < 1 ) {
 			//keep the behavior consistent even for boundary usages
@@ -77,16 +78,16 @@
 			return value.makeValue();
 		}
 
-		if ( lo > maxLo ) {
-			IntegralDataTypeHolder hiVal = generateHolder( session );
-			lo = ( hiVal.eq( 0 ) ) ? 1 : 0;
-			value = hiVal.copy().multiplyBy( maxLo+1 ).add( lo );
-			if ( log.isDebugEnabled() ) {
-				log.debug("new hi value: " + hiVal);
-			}
-		}
+		return hiloOptimizer.generate(
+				new AccessCallback() {
+					public IntegralDataTypeHolder getNextValue() {
+						return generateHolder( session );
+					}
+				}
+		);
+	}
 
-		return value.makeValueThenIncrement();
+	public OptimizerFactory.LegacyHiLoAlgorithmOptimizer getHiloOptimizer() {
+		return hiloOptimizer;
 	}
-
 }

Modified: core/branches/Branch_3_5/core/src/main/java/org/hibernate/id/enhanced/OptimizerFactory.java
===================================================================
--- core/branches/Branch_3_5/core/src/main/java/org/hibernate/id/enhanced/OptimizerFactory.java	2010-05-11 18:44:39 UTC (rev 19468)
+++ core/branches/Branch_3_5/core/src/main/java/org/hibernate/id/enhanced/OptimizerFactory.java	2010-05-11 19:24:54 UTC (rev 19469)
@@ -265,6 +265,67 @@
 		}
 	}
 
+	public static class LegacyHiLoAlgorithmOptimizer extends OptimizerSupport {
+		private long maxLo;
+		private long lo;
+		private IntegralDataTypeHolder hi;
+
+		private IntegralDataTypeHolder lastSourceValue;
+		private IntegralDataTypeHolder value;
+
+
+		public LegacyHiLoAlgorithmOptimizer(Class returnClass, int incrementSize) {
+			super( returnClass, incrementSize );
+			if ( incrementSize < 1 ) {
+				throw new HibernateException( "increment size cannot be less than 1" );
+			}
+			if ( log.isTraceEnabled() ) {
+				log.trace( "creating hilo optimizer (legacy) with [incrementSize=" + incrementSize + "; returnClass="  + returnClass.getName() + "]" );
+			}
+
+			maxLo = incrementSize;
+			lo = maxLo+1;
+		}
+
+		/**
+		 * {@inheritDoc}
+		 */
+		public synchronized Serializable generate(AccessCallback callback) {
+			if ( lo > maxLo ) {
+				lastSourceValue = callback.getNextValue();
+				lo = lastSourceValue.eq( 0 ) ? 1 : 0;
+				hi = lastSourceValue.copy().multiplyBy( maxLo+1 );
+			}
+			value = hi.copy().add( lo++ );
+			return value.makeValue();
+		}
+
+		/**
+		 * {@inheritDoc}
+		 */
+		public IntegralDataTypeHolder getLastSourceValue() {
+			return lastSourceValue.copy();
+		}
+
+		/**
+		 * {@inheritDoc}
+		 */
+		public boolean applyIncrementSizeToSourceValues() {
+			return false;
+		}
+
+		/**
+		 * Getter for property 'lastValue'.
+		 * <p/>
+		 * Exposure intended for testing purposes.
+		 *
+		 * @return Value for property 'lastValue'.
+		 */
+		public IntegralDataTypeHolder getLastValue() {
+			return value;
+		}
+	}
+
 	/**
 	 * Optimizer which uses a pool of values, storing the next low value of the
 	 * range in the database.

Added: core/branches/Branch_3_5/core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorTest.java
===================================================================
--- core/branches/Branch_3_5/core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorTest.java	                        (rev 0)
+++ core/branches/Branch_3_5/core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorTest.java	2010-05-11 19:24:54 UTC (rev 19469)
@@ -0,0 +1,148 @@
+/*
+ * Hibernate, Relational Persistence for Idiomatic Java
+ *
+ * Copyright (c) 2010, Red Hat Inc. or third-party contributors as
+ * indicated by the @author tags or express copyright attribution
+ * statements applied by the authors.  All third-party contributions are
+ * distributed under license by Red Hat Inc.
+ *
+ * This copyrighted material is made available to anyone wishing to use, modify,
+ * copy, or redistribute it subject to the terms and conditions of the GNU
+ * Lesser General Public License, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
+ * for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this distribution; if not, write to:
+ * Free Software Foundation, Inc.
+ * 51 Franklin Street, Fifth Floor
+ * Boston, MA  02110-1301  USA
+ */
+package org.hibernate.id;
+
+import java.util.Properties;
+
+import junit.framework.TestCase;
+
+import org.hibernate.Hibernate;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.cfg.Environment;
+import org.hibernate.cfg.NamingStrategy;
+import org.hibernate.cfg.ObjectNameNormalizer;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.dialect.HSQLDialect;
+import org.hibernate.engine.SessionFactoryImplementor;
+import org.hibernate.impl.SessionImpl;
+import org.hibernate.mapping.SimpleAuxiliaryDatabaseObject;
+
+/**
+ * I went back to 3.3 source and grabbed the code/logic as it existed back then and crafted this
+ * unit test so that we can make sure the value keep being generated in the expected manner
+ *
+ * @author Steve Ebersole
+ */
+public class SequenceHiLoGeneratorTest extends TestCase {
+	private static final String TEST_SEQUENCE = "test_sequence";
+
+	private Configuration cfg;
+	private SessionFactoryImplementor sessionFactory;
+	private SequenceHiLoGenerator generator;
+
+	protected void setUp() throws Exception {
+		super.setUp();
+
+		Properties properties = new Properties();
+		properties.setProperty( SequenceGenerator.SEQUENCE, TEST_SEQUENCE );
+		properties.setProperty( SequenceHiLoGenerator.MAX_LO, "3" );
+		properties.setProperty( SequenceGenerator.PARAMETERS, "start with 1" );  // hsqldb sequences start with 0 by default :?
+		properties.put(
+				PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER,
+				new ObjectNameNormalizer() {
+					protected boolean isUseQuotedIdentifiersGlobally() {
+						return false;
+					}
+
+					protected NamingStrategy getNamingStrategy() {
+						return cfg.getNamingStrategy();
+					}
+				}
+		);
+
+		Dialect dialect = new HSQLDialect();
+
+		generator = new SequenceHiLoGenerator();
+		//noinspection deprecation
+		generator.configure( Hibernate.LONG, properties, dialect );
+
+		cfg = new Configuration()
+				.setProperty( Environment.DRIVER, "org.hsqldb.jdbcDriver" )
+				.setProperty( Environment.URL, "jdbc:hsqldb:." )
+				.setProperty( Environment.USER, "sa" )
+				.setProperty( Environment.HBM2DDL_AUTO, "create-drop" );
+		cfg.addAuxiliaryDatabaseObject(
+				new SimpleAuxiliaryDatabaseObject(
+						generator.sqlCreateStrings( dialect )[0],
+						generator.sqlDropStrings( dialect )[0]
+				)
+		);
+
+		sessionFactory = (SessionFactoryImplementor) cfg.buildSessionFactory();
+	}
+
+	protected void tearDown() throws Exception {
+		if ( sessionFactory != null ) {
+			sessionFactory.close();
+		}
+
+		super.tearDown();
+	}
+
+	public void testHiLoAlgorithm() {
+		SessionImpl session = (SessionImpl) sessionFactory.openSession();
+		session.beginTransaction();
+
+		// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+		// initially sequence should be uninitialized
+//		assertEquals( 1L, generator.getHiloOptimizer().getLastSourceValue().makeValue().longValue() );
+// we have to assume here since in this branch we are testing with hsqldb which does not allow access to the
+// current sequence value and the optimizer does not yet know the value.  On trunk (3.6), against H2, we physically
+// check the sequence value in the database
+
+		// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+		// historically the hilo generators skipped the initial block of values;
+		// 		so the first generated id value is maxlo + 1, here be 4
+		Long generatedValue = (Long) generator.generate( session, null );
+		assertEquals( 4L, generatedValue.longValue() );
+		// which should also perform the first read on the sequence which should set it to its "start with" value (1)
+		assertEquals( 1L, generator.getHiloOptimizer().getLastSourceValue().makeValue().longValue() );
+
+		// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+		generatedValue = (Long) generator.generate( session, null );
+		assertEquals( 5L, generatedValue.longValue() );
+		assertEquals( 1L, generator.getHiloOptimizer().getLastSourceValue().makeValue().longValue() );
+
+		// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+		generatedValue = (Long) generator.generate( session, null );
+		assertEquals( 6L, generatedValue.longValue() );
+		assertEquals( 1L, generator.getHiloOptimizer().getLastSourceValue().makeValue().longValue() );
+
+		// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+		generatedValue = (Long) generator.generate( session, null );
+		assertEquals( 7L, generatedValue.longValue() );
+		// unlike the newer strategies, the db value will not get update here.  It gets updated on the next invocation
+		// 	after a clock over
+		assertEquals( 1L, generator.getHiloOptimizer().getLastSourceValue().makeValue().longValue() );
+
+		// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+		generatedValue = (Long) generator.generate( session, null );
+		assertEquals( 8L, generatedValue.longValue() );
+		// this should force an increment in the sequence value
+		assertEquals( 2L, generator.getHiloOptimizer().getLastSourceValue().makeValue().longValue() );
+
+		session.getTransaction().commit();
+		session.close();
+	}
+}



More information about the hibernate-commits mailing list