Hibernate SVN: r18790 - in core/trunk/cache-infinispan/src: main/java/org/hibernate/cache/infinispan/query and 2 other directories.
by hibernate-commits@lists.jboss.org
Author: galder.zamarreno(a)jboss.com
Date: 2010-02-12 07:21:43 -0500 (Fri, 12 Feb 2010)
New Revision: 18790
Modified:
core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java
core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/query/QueryResultsRegionImpl.java
core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampsRegionImpl.java
core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/BasicTransactionalTestCase.java
Log:
[HHH-4836] (Infinispan: 2L QueryCache don't considers cached queries which belong to current transaction) Fixed by not suspending transactions on get any more, since no locks are aquired on get.
Modified: core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java
===================================================================
--- core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java 2010-02-12 06:22:52 UTC (rev 18789)
+++ core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java 2010-02-12 12:21:43 UTC (rev 18790)
@@ -194,28 +194,21 @@
}
/**
- * Performs a JBoss Cache <code>get(Fqn, Object)</code> after first
- * {@link #suspend suspending any ongoing transaction}. Wraps any exception
- * in a {@link CacheException}. Ensures any ongoing transaction is resumed.
- *
+ * Performs a Infinispan <code>get(Fqn, Object)</code>
+ *
* @param key The key of the item to get
* @param opt any option to add to the get invocation. May be <code>null</code>
* @param suppressTimeout should any TimeoutException be suppressed?
* @return The retrieved object
* @throws CacheException issue managing transaction or talking to cache
*/
- protected Object suspendAndGet(Object key, FlagAdapter opt, boolean suppressTimeout) throws CacheException {
- Transaction tx = suspend();
- try {
- if (suppressTimeout)
- return cacheAdapter.getAllowingTimeout(key);
- else
- return cacheAdapter.get(key);
- } finally {
- resume(tx);
- }
+ protected Object get(Object key, FlagAdapter opt, boolean suppressTimeout) throws CacheException {
+ if (suppressTimeout)
+ return cacheAdapter.getAllowingTimeout(key);
+ else
+ return cacheAdapter.get(key);
}
-
+
public Object getOwnerForPut() {
Transaction tx = null;
try {
Modified: core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/query/QueryResultsRegionImpl.java
===================================================================
--- core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/query/QueryResultsRegionImpl.java 2010-02-12 06:22:52 UTC (rev 18789)
+++ core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/query/QueryResultsRegionImpl.java 2010-02-12 12:21:43 UTC (rev 18790)
@@ -50,12 +50,13 @@
if (!checkValid())
return null;
- // Don't hold the JBC node lock throughout the tx, as that
- // prevents updates
+ // In Infinispan get doesn't acquire any locks, so no need to suspend the tx.
+ // In the past, when get operations acquired locks, suspending the tx was a way
+ // to avoid holding locks that would prevent updates.
// Add a zero (or low) timeout option so we don't block
// waiting for tx's that did a put to commit
- return suspendAndGet(key, FlagAdapter.ZERO_LOCK_ACQUISITION_TIMEOUT, true);
- }
+ return get(key, FlagAdapter.ZERO_LOCK_ACQUISITION_TIMEOUT, true);
+ }
public void put(Object key, Object value) throws CacheException {
if (checkValid()) {
Modified: core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampsRegionImpl.java
===================================================================
--- core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampsRegionImpl.java 2010-02-12 06:22:52 UTC (rev 18789)
+++ core/trunk/cache-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampsRegionImpl.java 2010-02-12 12:21:43 UTC (rev 18790)
@@ -58,7 +58,7 @@
public Object get(Object key) throws CacheException {
Object value = localCache.get(key);
if (value == null && checkValid()) {
- value = suspendAndGet(key, null, false);
+ value = get(key, null, false);
if (value != null)
localCache.put(key, value);
}
Modified: core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/BasicTransactionalTestCase.java
===================================================================
--- core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/BasicTransactionalTestCase.java 2010-02-12 06:22:52 UTC (rev 18789)
+++ core/trunk/cache-infinispan/src/test/java/org/hibernate/test/cache/infinispan/functional/BasicTransactionalTestCase.java 2010-02-12 12:21:43 UTC (rev 18790)
@@ -287,4 +287,47 @@
commitOrRollbackTx();
}
}
+
+ public void testQueryCacheHitInSameTransaction() throws Exception {
+ Session s = null;
+ Item item = new Item("galder", "Galder's Item");
+
+ beginTx();
+ try {
+ s = openSession();
+ s.getTransaction().begin();
+ s.persist(item);
+ s.getTransaction().commit();
+ s.close();
+ } catch (Exception e) {
+ setRollbackOnlyTx(e);
+ } finally {
+ commitOrRollbackTx();
+ }
+
+ beginTx();
+ try {
+ s = openSession();
+ Statistics stats = s.getSessionFactory().getStatistics();
+ s.createQuery("from Item").setCacheable(true).list();
+ s.createQuery("from Item").setCacheable(true).list();
+ assertEquals(1, stats.getQueryCacheHitCount());
+ s.close();
+ } catch (Exception e) {
+ setRollbackOnlyTx(e);
+ } finally {
+ commitOrRollbackTx();
+ }
+
+ beginTx();
+ try {
+ s = openSession();
+ s.createQuery("delete from Item").executeUpdate();
+ s.close();
+ } catch (Exception e) {
+ setRollbackOnlyTx(e);
+ } finally {
+ commitOrRollbackTx();
+ }
+ }
}
14 years, 3 months
Hibernate SVN: r18789 - in core/trunk: core/src/main/java/org/hibernate/id and 11 other directories.
by hibernate-commits@lists.jboss.org
Author: steve.ebersole(a)jboss.com
Date: 2010-02-12 01:22:52 -0500 (Fri, 12 Feb 2010)
New Revision: 18789
Added:
core/trunk/core/src/main/java/org/hibernate/id/IntegralDataTypeHolder.java
core/trunk/core/src/test/java/org/hibernate/id/
core/trunk/core/src/test/java/org/hibernate/id/AbstractHolderTest.java
core/trunk/core/src/test/java/org/hibernate/id/BigDecimalHolderTest.java
core/trunk/core/src/test/java/org/hibernate/id/BigIntegerHolderTest.java
core/trunk/core/src/test/java/org/hibernate/id/LongHolderTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/increment/
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/increment/BigIntegerIncrementGeneratorTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/increment/Entity.java
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/increment/Mapping.hbm.xml
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/sequence/
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/sequence/BigIntegerSequenceGeneratorTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/sequence/Entity.java
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/sequence/Mapping.hbm.xml
Modified:
core/trunk/core/src/main/java/org/hibernate/engine/VersionValue.java
core/trunk/core/src/main/java/org/hibernate/id/IdentifierGeneratorHelper.java
core/trunk/core/src/main/java/org/hibernate/id/IncrementGenerator.java
core/trunk/core/src/main/java/org/hibernate/id/MultipleHiLoPerTableGenerator.java
core/trunk/core/src/main/java/org/hibernate/id/SequenceGenerator.java
core/trunk/core/src/main/java/org/hibernate/id/SequenceHiLoGenerator.java
core/trunk/core/src/main/java/org/hibernate/id/TableGenerator.java
core/trunk/core/src/main/java/org/hibernate/id/TableHiLoGenerator.java
core/trunk/core/src/main/java/org/hibernate/id/enhanced/AccessCallback.java
core/trunk/core/src/main/java/org/hibernate/id/enhanced/Optimizer.java
core/trunk/core/src/main/java/org/hibernate/id/enhanced/OptimizerFactory.java
core/trunk/core/src/main/java/org/hibernate/id/enhanced/SequenceStructure.java
core/trunk/core/src/main/java/org/hibernate/id/enhanced/SequenceStyleGenerator.java
core/trunk/core/src/main/java/org/hibernate/id/enhanced/TableGenerator.java
core/trunk/core/src/main/java/org/hibernate/id/enhanced/TableStructure.java
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/OptimizerUnitTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/forcedtable/BasicForcedTableSequenceTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/forcedtable/HiLoForcedTableSequenceTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/forcedtable/PooledForcedTableSequenceTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/sequence/BasicSequenceTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/sequence/HiLoSequenceTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/sequence/PooledSequenceTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/table/BasicTableTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/table/HiLoTableTest.java
core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/table/PooledTableTest.java
Log:
HHH-4905 - Allow consistent handling of numeric primary key values by any integral data type
Modified: core/trunk/core/src/main/java/org/hibernate/engine/VersionValue.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/engine/VersionValue.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/core/src/main/java/org/hibernate/engine/VersionValue.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -91,7 +91,9 @@
}
}
public Object getDefaultValue(Object currentValue) {
- return IdentifierGeneratorHelper.createNumber( -1l, currentValue.getClass() );
+ return IdentifierGeneratorHelper.getIntegralDataTypeHolder( currentValue.getClass() )
+ .initialize( -1L )
+ .makeValue();
}
public String toString() {
return "VERSION_NEGATIVE";
Modified: core/trunk/core/src/main/java/org/hibernate/id/IdentifierGeneratorHelper.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/IdentifierGeneratorHelper.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/core/src/main/java/org/hibernate/id/IdentifierGeneratorHelper.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -25,6 +25,9 @@
package org.hibernate.id;
import java.io.Serializable;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@@ -119,10 +122,17 @@
else if ( clazz == String.class ) {
return rs.getString( 1 );
}
+ else if ( clazz == BigInteger.class ) {
+ return rs.getBigDecimal( 1 ).setScale( 0, BigDecimal.ROUND_UNNECESSARY ).toBigInteger();
+ }
+ else if ( clazz == BigDecimal.class ) {
+ return rs.getBigDecimal( 1 ).setScale( 0, BigDecimal.ROUND_UNNECESSARY );
+ }
else {
- throw new IdentifierGenerationException( "this id generator generates long, integer, short or string" );
+ throw new IdentifierGenerationException(
+ "unrecognized id type : " + type.getName() + " -> " + clazz.getName()
+ );
}
-
}
/**
@@ -130,8 +140,12 @@
*
* @param value The primitive value to wrap.
* @param clazz The Java numeric type in which to wrap the value.
+ *
* @return The wrapped type.
+ *
* @throws IdentifierGenerationException Indicates an unhandled 'clazz'.
+ *
+ * @deprecated Use the {@link #getIntegralDataTypeHolder holders} instead.
*/
public static Number createNumber(long value, Class clazz) throws IdentifierGenerationException {
if ( clazz == Long.class ) {
@@ -144,10 +158,513 @@
return new Short( ( short ) value );
}
else {
- throw new IdentifierGenerationException( "this id generator generates long, integer, short" );
+ throw new IdentifierGenerationException( "unrecognized id type : " + clazz.getName() );
}
}
+ public static IntegralDataTypeHolder getIntegralDataTypeHolder(Class integralType) {
+ if ( integralType == Long.class
+ || integralType == Integer.class
+ || integralType == Short.class ) {
+ return new BasicHolder( integralType );
+ }
+ else if ( integralType == BigInteger.class ) {
+ return new BigIntegerHolder();
+ }
+ else if ( integralType == BigDecimal.class ) {
+ return new BigDecimalHolder();
+ }
+ else {
+ throw new IdentifierGenerationException(
+ "Unknown integral data type for ids : " + integralType.getName()
+ );
+ }
+ }
+
+ public static long extractLong(IntegralDataTypeHolder holder) {
+ if ( holder.getClass() == BasicHolder.class ) {
+ ( (BasicHolder) holder ).checkInitialized();
+ return ( (BasicHolder) holder ).value;
+ }
+ else if ( holder.getClass() == BigIntegerHolder.class ) {
+ ( (BigIntegerHolder) holder ).checkInitialized();
+ return ( (BigIntegerHolder) holder ).value.longValue();
+ }
+ else if ( holder.getClass() == BigDecimalHolder.class ) {
+ ( (BigDecimalHolder) holder ).checkInitialized();
+ return ( (BigDecimalHolder) holder ).value.longValue();
+ }
+ throw new IdentifierGenerationException( "Unknown IntegralDataTypeHolder impl [" + holder + "]" );
+ }
+
+ public static BigInteger extractBigInteger(IntegralDataTypeHolder holder) {
+ if ( holder.getClass() == BasicHolder.class ) {
+ ( (BasicHolder) holder ).checkInitialized();
+ return BigInteger.valueOf( ( (BasicHolder) holder ).value );
+ }
+ else if ( holder.getClass() == BigIntegerHolder.class ) {
+ ( (BigIntegerHolder) holder ).checkInitialized();
+ return ( (BigIntegerHolder) holder ).value;
+ }
+ else if ( holder.getClass() == BigDecimalHolder.class ) {
+ ( (BigDecimalHolder) holder ).checkInitialized();
+ // scale should already be set...
+ return ( (BigDecimalHolder) holder ).value.toBigInteger();
+ }
+ throw new IdentifierGenerationException( "Unknown IntegralDataTypeHolder impl [" + holder + "]" );
+ }
+
+ public static BigDecimal extractBigDecimal(IntegralDataTypeHolder holder) {
+ if ( holder.getClass() == BasicHolder.class ) {
+ ( (BasicHolder) holder ).checkInitialized();
+ return BigDecimal.valueOf( ( (BasicHolder) holder ).value );
+ }
+ else if ( holder.getClass() == BigIntegerHolder.class ) {
+ ( (BigIntegerHolder) holder ).checkInitialized();
+ return new BigDecimal( ( (BigIntegerHolder) holder ).value );
+ }
+ else if ( holder.getClass() == BigDecimalHolder.class ) {
+ ( (BigDecimalHolder) holder ).checkInitialized();
+ // scale should already be set...
+ return ( (BigDecimalHolder) holder ).value;
+ }
+ throw new IdentifierGenerationException( "Unknown IntegralDataTypeHolder impl [" + holder + "]" );
+ }
+
+ public static class BasicHolder implements IntegralDataTypeHolder {
+ private final Class exactType;
+ private long value = Long.MIN_VALUE;
+
+ public BasicHolder(Class exactType) {
+ this.exactType = exactType;
+ if ( exactType != Long.class && exactType != Integer.class && exactType != Short.class ) {
+ throw new IdentifierGenerationException( "Invalid type for basic integral holder : " + exactType );
+ }
+ }
+
+ public long getActualLongValue() {
+ return value;
+ }
+
+ public IntegralDataTypeHolder initialize(long value) {
+ this.value = value;
+ return this;
+ }
+
+ public IntegralDataTypeHolder initialize(ResultSet resultSet, long defaultValue) throws SQLException {
+ long value = resultSet.getLong( 1 );
+ if ( resultSet.wasNull() ) {
+ value = defaultValue;
+ }
+ return initialize( value );
+ }
+
+ public void bind(PreparedStatement preparedStatement, int position) throws SQLException {
+ // TODO : bind it as 'exact type'? Not sure if that gains us anything...
+ preparedStatement.setLong( position, value );
+ }
+
+ public IntegralDataTypeHolder increment() {
+ checkInitialized();
+ value++;
+ return this;
+ }
+
+ private void checkInitialized() {
+ if ( value == Long.MIN_VALUE ) {
+ throw new IdentifierGenerationException( "integral holder was not initialized" );
+ }
+ }
+
+ public IntegralDataTypeHolder add(long addend) {
+ checkInitialized();
+ value += addend;
+ return this;
+ }
+
+ public IntegralDataTypeHolder decrement() {
+ checkInitialized();
+ value--;
+ return this;
+ }
+
+ public IntegralDataTypeHolder subtract(long subtrahend) {
+ checkInitialized();
+ value -= subtrahend;
+ return this;
+ }
+
+ public IntegralDataTypeHolder multiplyBy(IntegralDataTypeHolder factor) {
+ return multiplyBy( extractLong( factor ) );
+ }
+
+ public IntegralDataTypeHolder multiplyBy(long factor) {
+ checkInitialized();
+ value *= factor;
+ return this;
+ }
+
+ public boolean eq(IntegralDataTypeHolder other) {
+ return eq( extractLong( other ) );
+ }
+
+ public boolean eq(long value) {
+ checkInitialized();
+ return this.value == value;
+ }
+
+ public boolean lt(IntegralDataTypeHolder other) {
+ return lt( extractLong( other ) );
+ }
+
+ public boolean lt(long value) {
+ checkInitialized();
+ return this.value < value;
+ }
+
+ public boolean gt(IntegralDataTypeHolder other) {
+ return gt( extractLong( other ) );
+ }
+
+ public boolean gt(long value) {
+ checkInitialized();
+ return this.value > value;
+ }
+
+ public IntegralDataTypeHolder copy() {
+ BasicHolder copy = new BasicHolder( exactType );
+ copy.value = value;
+ return copy;
+ }
+
+ public Number makeValue() {
+ // TODO : should we check for truncation?
+ checkInitialized();
+ if ( exactType == Long.class ) {
+ return new Long( value );
+ }
+ else if ( exactType == Integer.class ) {
+ return new Integer( ( int ) value );
+ }
+ else {
+ return new Short( ( short ) value );
+ }
+ }
+
+ public Number makeValueThenIncrement() {
+ final Number result = makeValue();
+ value++;
+ return result;
+ }
+
+ public Number makeValueThenAdd(long addend) {
+ final Number result = makeValue();
+ value += addend;
+ return result;
+ }
+
+ public String toString() {
+ return "BasicHolder[" + exactType.getName() + "[" + value + "]]";
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) {
+ return true;
+ }
+ if ( o == null || getClass() != o.getClass() ) {
+ return false;
+ }
+
+ BasicHolder that = (BasicHolder) o;
+
+ return value == that.value;
+ }
+
+ public int hashCode() {
+ return (int) ( value ^ ( value >>> 32 ) );
+ }
+ }
+
+ public static class BigIntegerHolder implements IntegralDataTypeHolder {
+ private BigInteger value;
+
+ public IntegralDataTypeHolder initialize(long value) {
+ this.value = BigInteger.valueOf( value );
+ return this;
+ }
+
+ public IntegralDataTypeHolder initialize(ResultSet resultSet, long defaultValue) throws SQLException {
+ final BigDecimal rsValue = resultSet.getBigDecimal( 1 );
+ if ( resultSet.wasNull() ) {
+ return initialize( defaultValue );
+ }
+ this.value = rsValue.setScale( 0, BigDecimal.ROUND_UNNECESSARY ).toBigInteger();
+ return this;
+ }
+
+ public void bind(PreparedStatement preparedStatement, int position) throws SQLException {
+ preparedStatement.setBigDecimal( position, new BigDecimal( value ) );
+ }
+
+ public IntegralDataTypeHolder increment() {
+ checkInitialized();
+ value = value.add( BigInteger.ONE );
+ return this;
+ }
+
+ private void checkInitialized() {
+ if ( value == null ) {
+ throw new IdentifierGenerationException( "integral holder was not initialized" );
+ }
+ }
+
+ public IntegralDataTypeHolder add(long increment) {
+ checkInitialized();
+ value = value.add( BigInteger.valueOf( increment ) );
+ return this;
+ }
+
+ public IntegralDataTypeHolder decrement() {
+ checkInitialized();
+ value = value.subtract( BigInteger.ONE );
+ return this;
+ }
+
+ public IntegralDataTypeHolder subtract(long subtrahend) {
+ checkInitialized();
+ value = value.subtract( BigInteger.valueOf( subtrahend ) );
+ return this;
+ }
+
+ public IntegralDataTypeHolder multiplyBy(IntegralDataTypeHolder factor) {
+ checkInitialized();
+ value = value.multiply( extractBigInteger( factor ) );
+ return this;
+ }
+
+ public IntegralDataTypeHolder multiplyBy(long factor) {
+ checkInitialized();
+ value = value.multiply( BigInteger.valueOf( factor ) );
+ return this;
+ }
+
+ public boolean eq(IntegralDataTypeHolder other) {
+ checkInitialized();
+ return value.compareTo( extractBigInteger( other ) ) == 0;
+ }
+
+ public boolean eq(long value) {
+ checkInitialized();
+ return this.value.compareTo( BigInteger.valueOf( value ) ) == 0;
+ }
+
+ public boolean lt(IntegralDataTypeHolder other) {
+ checkInitialized();
+ return value.compareTo( extractBigInteger( other ) ) < 0;
+ }
+
+ public boolean lt(long value) {
+ checkInitialized();
+ return this.value.compareTo( BigInteger.valueOf( value ) ) < 0;
+ }
+
+ public boolean gt(IntegralDataTypeHolder other) {
+ checkInitialized();
+ return value.compareTo( extractBigInteger( other ) ) > 0;
+ }
+
+ public boolean gt(long value) {
+ checkInitialized();
+ return this.value.compareTo( BigInteger.valueOf( value ) ) > 0;
+ }
+
+ public IntegralDataTypeHolder copy() {
+ BigIntegerHolder copy = new BigIntegerHolder();
+ copy.value = value;
+ return copy;
+ }
+
+ public Number makeValue() {
+ checkInitialized();
+ return value;
+ }
+
+ public Number makeValueThenIncrement() {
+ final Number result = makeValue();
+ value = value.add( BigInteger.ONE );
+ return result;
+ }
+
+ public Number makeValueThenAdd(long addend) {
+ final Number result = makeValue();
+ value = value.add( BigInteger.valueOf( addend ) );
+ return result;
+ }
+
+ public String toString() {
+ return "BigIntegerHolder[" + value + "]";
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) {
+ return true;
+ }
+ if ( o == null || getClass() != o.getClass() ) {
+ return false;
+ }
+
+ BigIntegerHolder that = (BigIntegerHolder) o;
+
+ return this.value == null
+ ? that.value == null
+ : value.equals( that.value );
+ }
+
+ public int hashCode() {
+ return value != null ? value.hashCode() : 0;
+ }
+ }
+
+ public static class BigDecimalHolder implements IntegralDataTypeHolder {
+ private BigDecimal value;
+
+ public IntegralDataTypeHolder initialize(long value) {
+ this.value = BigDecimal.valueOf( value );
+ return this;
+ }
+
+ public IntegralDataTypeHolder initialize(ResultSet resultSet, long defaultValue) throws SQLException {
+ final BigDecimal rsValue = resultSet.getBigDecimal( 1 );
+ if ( resultSet.wasNull() ) {
+ return initialize( defaultValue );
+ }
+ this.value = rsValue.setScale( 0, BigDecimal.ROUND_UNNECESSARY );
+ return this;
+ }
+
+ public void bind(PreparedStatement preparedStatement, int position) throws SQLException {
+ preparedStatement.setBigDecimal( position, value );
+ }
+
+ public IntegralDataTypeHolder increment() {
+ checkInitialized();
+ value = value.add( BigDecimal.ONE );
+ return this;
+ }
+
+ private void checkInitialized() {
+ if ( value == null ) {
+ throw new IdentifierGenerationException( "integral holder was not initialized" );
+ }
+ }
+
+ public IntegralDataTypeHolder add(long increment) {
+ checkInitialized();
+ value = value.add( BigDecimal.valueOf( increment ) );
+ return this;
+ }
+
+ public IntegralDataTypeHolder decrement() {
+ checkInitialized();
+ value = value.subtract( BigDecimal.ONE );
+ return this;
+ }
+
+ public IntegralDataTypeHolder subtract(long subtrahend) {
+ checkInitialized();
+ value = value.subtract( BigDecimal.valueOf( subtrahend ) );
+ return this;
+ }
+
+ public IntegralDataTypeHolder multiplyBy(IntegralDataTypeHolder factor) {
+ checkInitialized();
+ value = value.multiply( extractBigDecimal( factor ) );
+ return this;
+ }
+
+ public IntegralDataTypeHolder multiplyBy(long factor) {
+ checkInitialized();
+ value = value.multiply( BigDecimal.valueOf( factor ) );
+ return this;
+ }
+
+ public boolean eq(IntegralDataTypeHolder other) {
+ checkInitialized();
+ return value.compareTo( extractBigDecimal( other ) ) == 0;
+ }
+
+ public boolean eq(long value) {
+ checkInitialized();
+ return this.value.compareTo( BigDecimal.valueOf( value ) ) == 0;
+ }
+
+ public boolean lt(IntegralDataTypeHolder other) {
+ checkInitialized();
+ return value.compareTo( extractBigDecimal( other ) ) < 0;
+ }
+
+ public boolean lt(long value) {
+ checkInitialized();
+ return this.value.compareTo( BigDecimal.valueOf( value ) ) < 0;
+ }
+
+ public boolean gt(IntegralDataTypeHolder other) {
+ checkInitialized();
+ return value.compareTo( extractBigDecimal( other ) ) > 0;
+ }
+
+ public boolean gt(long value) {
+ checkInitialized();
+ return this.value.compareTo( BigDecimal.valueOf( value ) ) > 0;
+ }
+
+ public IntegralDataTypeHolder copy() {
+ BigDecimalHolder copy = new BigDecimalHolder();
+ copy.value = value;
+ return copy;
+ }
+
+ public Number makeValue() {
+ checkInitialized();
+ return value;
+ }
+
+ public Number makeValueThenIncrement() {
+ final Number result = makeValue();
+ value = value.add( BigDecimal.ONE );
+ return result;
+ }
+
+ public Number makeValueThenAdd(long addend) {
+ final Number result = makeValue();
+ value = value.add( BigDecimal.valueOf( addend ) );
+ return result;
+ }
+
+ public String toString() {
+ return "BigDecimalHolder[" + value + "]";
+ }
+
+ public boolean equals(Object o) {
+ if ( this == o ) {
+ return true;
+ }
+ if ( o == null || getClass() != o.getClass() ) {
+ return false;
+ }
+
+ BigDecimalHolder that = (BigDecimalHolder) o;
+
+ return this.value == null
+ ? that.value == null
+ : this.value.equals( that.value );
+ }
+
+ public int hashCode() {
+ return value != null ? value.hashCode() : 0;
+ }
+ }
+
/**
* Disallow instantiation of IdentifierGeneratorHelper.
*/
Modified: core/trunk/core/src/main/java/org/hibernate/id/IncrementGenerator.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/IncrementGenerator.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/core/src/main/java/org/hibernate/id/IncrementGenerator.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * 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 Middleware LLC.
+ * 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
@@ -20,7 +20,6 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
- *
*/
package org.hibernate.id;
@@ -53,20 +52,21 @@
* (The tables parameter specified a comma-separated list of table names.)
*
* @author Gavin King
+ * @author Steve Ebersole
*/
public class IncrementGenerator implements IdentifierGenerator, Configurable {
-
private static final Logger log = LoggerFactory.getLogger(IncrementGenerator.class);
- private long next;
+ private Class returnClass;
private String sql;
- private Class returnClass;
+ private IntegralDataTypeHolder previousValueHolder;
+
public synchronized Serializable generate(SessionImplementor session, Object object) throws HibernateException {
if ( sql != null ) {
- getNext( session );
+ initializePreviousValueHolder( session );
}
- return IdentifierGeneratorHelper.createNumber( next++, returnClass );
+ return previousValueHolder.makeValueThenIncrement();
}
public void configure(Type type, Properties params, Dialect dialect) throws MappingException {
@@ -117,22 +117,23 @@
sql = "select max(" + column + ") from " + buf.toString();
}
- private void getNext( SessionImplementor session ) {
+ private void initializePreviousValueHolder(SessionImplementor session) {
+ previousValueHolder = IdentifierGeneratorHelper.getIntegralDataTypeHolder( returnClass );
+
log.debug( "fetching initial value: " + sql );
try {
- PreparedStatement st = session.getBatcher().prepareSelectStatement(sql);
+ PreparedStatement st = session.getBatcher().prepareSelectStatement( sql );
try {
ResultSet rs = st.executeQuery();
try {
if ( rs.next() ) {
- next = rs.getLong(1) + 1;
- if ( rs.wasNull() ) next = 1;
+ previousValueHolder.initialize( rs, 0L ).increment();
}
else {
- next = 1;
+ previousValueHolder.initialize( 1L );
}
- sql=null;
- log.debug("first free id: " + next);
+ sql = null;
+ log.debug( "first free id: " + previousValueHolder.makeValue() );
}
finally {
rs.close();
@@ -141,7 +142,6 @@
finally {
session.getBatcher().closeStatement(st);
}
-
}
catch (SQLException sqle) {
throw JDBCExceptionHelper.convert(
Added: core/trunk/core/src/main/java/org/hibernate/id/IntegralDataTypeHolder.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/IntegralDataTypeHolder.java (rev 0)
+++ core/trunk/core/src/main/java/org/hibernate/id/IntegralDataTypeHolder.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -0,0 +1,206 @@
+/*
+ * 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.io.Serializable;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+/**
+ * Defines a common api for dealing with data of integral data type.
+ *
+ * @author Steve Ebersole
+ */
+public interface IntegralDataTypeHolder extends Serializable {
+ /**
+ * Initialize the internal value from the given primitive long.
+ *
+ * @param value The primitive integral value.
+ *
+ * @return <tt>this</tt>, for method chaining
+ */
+ public IntegralDataTypeHolder initialize(long value);
+
+ /**
+ * Initialize the internal value from the given result set, using the specified default value
+ * if we could not get a value from the result set (aka result was null).
+ *
+ * @param resultSet The JDBC result set
+ * @param defaultValue The default value to use if we did not get a result set value.
+ *
+ * @return <tt>this</tt>, for method chaining
+ *
+ * @throws SQLException Any exception from accessing the result set
+ */
+ public IntegralDataTypeHolder initialize(ResultSet resultSet, long defaultValue) throws SQLException;
+
+ /**
+ * Bind this holders internal value to the given result set.
+ *
+ * @param preparedStatement The JDBC prepared statement
+ * @param position The position at which to bind
+ *
+ * @throws SQLException Any exception from accessing the statement
+ */
+ public void bind(PreparedStatement preparedStatement, int position) throws SQLException;
+
+ /**
+ * Equivalent to a ++ operation
+ *
+ * @return <tt>this</tt>, for method chaining
+ */
+ public IntegralDataTypeHolder increment();
+
+ /**
+ * Perform an addition
+ *
+ * @param addend The value to add to this integral.
+ *
+ * @return <tt>this</tt>, for method chaining
+ */
+ public IntegralDataTypeHolder add(long addend);
+
+ /**
+ * Equivalent to a -- operation
+ *
+ * @return <tt>this</tt>, for method chaining
+ */
+ public IntegralDataTypeHolder decrement();
+
+ /**
+ * Perform a subtraction
+ *
+ * @param subtrahend The value to subtract from this integral.
+ *
+ * @return <tt>this</tt>, for method chaining
+ */
+ public IntegralDataTypeHolder subtract(long subtrahend);
+
+ /**
+ * Perform a multiplication.
+ *
+ * @param factor The factor by which to multiple this integral
+ *
+ * @return <tt>this</tt>, for method chaining
+ */
+ public IntegralDataTypeHolder multiplyBy(IntegralDataTypeHolder factor);
+
+ /**
+ * Perform a multiplication.
+ *
+ * @param factor The factor by which to multiple this integral
+ *
+ * @return <tt>this</tt>, for method chaining
+ */
+ public IntegralDataTypeHolder multiplyBy(long factor);
+
+ /**
+ * Perform an equality comparison check
+ *
+ * @param other The other value to check against our internal state
+ *
+ * @return True if the two are equal
+ */
+ public boolean eq(IntegralDataTypeHolder other);
+
+ /**
+ * Perform an equality comparison check
+ *
+ * @param other The other value to check against our internal state
+ *
+ * @return True if the two are equal
+ */
+ public boolean eq(long other);
+
+ /**
+ * Perform a "less than" comparison check. We check to see if our value is less than
+ * the incoming value...
+ *
+ * @param other The other value to check against our internal state
+ *
+ * @return True if our value is less than the 'other' value.
+ */
+ public boolean lt(IntegralDataTypeHolder other);
+
+ /**
+ * Perform a "less than" comparison check. We check to see if our value is less than
+ * the incoming value...
+ *
+ * @param other The other value to check against our internal state
+ *
+ * @return True if our value is less than the 'other' value.
+ */
+ public boolean lt(long other);
+
+ /**
+ * Perform a "greater than" comparison check. We check to see if our value is greater
+ * than the incoming value...
+ *
+ * @param other The other value to check against our internal state
+ *
+ * @return True if our value is greater than the 'other' value.
+ */
+ public boolean gt(IntegralDataTypeHolder other);
+
+ /**
+ * Perform a "greater than" comparison check. We check to see if our value is greater
+ * than the incoming value...
+ *
+ * @param other The other value to check against our internal state
+ *
+ * @return True if our value is greater than the 'other' value.
+ */
+ public boolean gt(long other);
+
+ /**
+ * Make a copy of this holder.
+ *
+ * @return The copy.
+ */
+ public IntegralDataTypeHolder copy();
+
+ /**
+ * Return the internal value.
+ *
+ * @return The current internal value
+ */
+ public Number makeValue();
+
+ /**
+ * Increment the internal state, but return the pre-incremented value.
+ *
+ * @return The pre-incremented internal value
+ */
+ public Number makeValueThenIncrement();
+
+ /**
+ * Increment the internal state by the given addend, but return the pre-incremented value.
+ *
+ * @param addend The value to be added to our internal state
+ *
+ * @return The pre-incremented internal value
+ */
+ public Number makeValueThenAdd(long addend);
+}
Modified: core/trunk/core/src/main/java/org/hibernate/id/MultipleHiLoPerTableGenerator.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/MultipleHiLoPerTableGenerator.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/core/src/main/java/org/hibernate/id/MultipleHiLoPerTableGenerator.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * 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 Middleware LLC.
+ * 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
@@ -20,7 +20,6 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
- *
*/
package org.hibernate.id;
@@ -104,9 +103,10 @@
//hilo params
public static final String MAX_LO = "max_lo";
- private long hi;
+ private int maxLo;
private int lo;
- private int maxLo;
+ private IntegralDataTypeHolder value;
+
private Class returnClass;
private int keySize;
@@ -146,7 +146,7 @@
}
public Serializable doWorkInCurrentTransaction(Connection conn, String sql) throws SQLException {
- int result;
+ IntegralDataTypeHolder value = IdentifierGeneratorHelper.getIntegralDataTypeHolder( returnClass );
int rows;
do {
// The loop ensures atomicity of the
@@ -158,18 +158,16 @@
PreparedStatement qps = conn.prepareStatement(query);
PreparedStatement ips = null;
try {
- //qps.setString(1, key);
ResultSet rs = qps.executeQuery();
boolean isInitialized = rs.next();
if ( !isInitialized ) {
- result = 0;
- ips = conn.prepareStatement(insert);
- //ips.setString(1, key);
- ips.setInt(1, result);
+ value.initialize( 0 );
+ ips = conn.prepareStatement( insert );
+ value.bind( ips, 1 );
ips.execute();
}
else {
- result = rs.getInt(1);
+ value.initialize( rs, 0 );
}
rs.close();
}
@@ -184,12 +182,10 @@
qps.close();
}
- //sql = update;
PreparedStatement ups = conn.prepareStatement(update);
try {
- ups.setInt( 1, result + 1 );
- ups.setInt( 2, result );
- //ups.setString( 3, key );
+ value.copy().increment().bind( ups, 1 );
+ value.bind( ups, 2 );
rows = ups.executeUpdate();
}
catch (SQLException sqle) {
@@ -201,24 +197,30 @@
}
}
while (rows==0);
- return new Integer(result);
+ return value;
}
public synchronized Serializable generate(SessionImplementor session, Object obj)
throws HibernateException {
- if (maxLo < 1) {
+ // maxLo < 1 indicates a hilo generator with no hilo :?
+ if ( maxLo < 1 ) {
//keep the behavior consistent even for boundary usages
- int val = ( (Integer) doWorkInNewTransaction(session) ).intValue();
- if (val == 0) val = ( (Integer) doWorkInNewTransaction(session) ).intValue();
- return IdentifierGeneratorHelper.createNumber( val, returnClass );
+ IntegralDataTypeHolder value = null;
+ while ( value == null || value.lt( 1 ) ) {
+ value = (IntegralDataTypeHolder) doWorkInNewTransaction( session );
+ }
+ return value.makeValue();
}
- if (lo>maxLo) {
- int hival = ( (Integer) doWorkInNewTransaction(session) ).intValue();
- lo = (hival == 0) ? 1 : 0;
- hi = hival * (maxLo+1);
- log.debug("new hi value: " + hival);
+
+ 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 IdentifierGeneratorHelper.createNumber( hi + lo++, returnClass );
+ return value.makeValueThenIncrement();
}
public void configure(Type type, Properties params, Dialect dialect) throws MappingException {
Modified: core/trunk/core/src/main/java/org/hibernate/id/SequenceGenerator.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/SequenceGenerator.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/core/src/main/java/org/hibernate/id/SequenceGenerator.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * 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 Middleware LLC.
+ * 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
@@ -20,7 +20,6 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
- *
*/
package org.hibernate.id;
@@ -98,19 +97,19 @@
sql = dialect.getSequenceNextValString( sequenceName );
}
- public Serializable generate(SessionImplementor session, Object obj)
- throws HibernateException {
-
+ public Serializable generate(SessionImplementor session, Object obj) {
+ return generateHolder( session ).makeValue();
+ }
+
+ protected IntegralDataTypeHolder generateHolder(SessionImplementor session) {
try {
-
PreparedStatement st = session.getBatcher().prepareSelectStatement(sql);
try {
ResultSet rs = st.executeQuery();
try {
rs.next();
- Serializable result = IdentifierGeneratorHelper.get(
- rs, identifierType
- );
+ IntegralDataTypeHolder result = buildHolder();
+ result.initialize( rs, 1 );
if ( log.isDebugEnabled() ) {
log.debug("Sequence identifier generated: " + result);
}
@@ -123,7 +122,7 @@
finally {
session.getBatcher().closeStatement(st);
}
-
+
}
catch (SQLException sqle) {
throw JDBCExceptionHelper.convert(
@@ -131,9 +130,12 @@
sqle,
"could not get next sequence value",
sql
- );
+ );
}
+ }
+ protected IntegralDataTypeHolder buildHolder() {
+ return IdentifierGeneratorHelper.getIntegralDataTypeHolder( identifierType.getReturnedClass() );
}
public String[] sqlCreateStrings(Dialect dialect) throws HibernateException {
Modified: core/trunk/core/src/main/java/org/hibernate/id/SequenceHiLoGenerator.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/SequenceHiLoGenerator.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/core/src/main/java/org/hibernate/id/SequenceHiLoGenerator.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -1,10 +1,10 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
- * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
+ * 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 Middleware LLC.
+ * 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
@@ -20,7 +20,6 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
- *
*/
package org.hibernate.id;
@@ -29,7 +28,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionImplementor;
@@ -59,33 +57,36 @@
private int maxLo;
private int lo;
- private long hi;
- private Class returnClass;
+ private IntegralDataTypeHolder value;
+
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
- returnClass = type.getReturnedClass();
}
- public synchronized Serializable generate(SessionImplementor session, Object obj)
- throws HibernateException {
- if (maxLo < 1) {
+ public synchronized Serializable generate(SessionImplementor session, Object obj) {
+ // maxLo < 1 indicates a hilo generator with no hilo :?
+ if ( maxLo < 1 ) {
//keep the behavior consistent even for boundary usages
- long val = ( (Number) super.generate(session, obj) ).longValue();
- if (val == 0) val = ( (Number) super.generate(session, obj) ).longValue();
- return IdentifierGeneratorHelper.createNumber( val, returnClass );
+ IntegralDataTypeHolder value = null;
+ while ( value == null || value.lt( 0 ) ) {
+ value = super.generateHolder( session );
+ }
+ return value.makeValue();
}
- if ( lo>maxLo ) {
- long hival = ( (Number) super.generate(session, obj) ).longValue();
- lo = (hival == 0) ? 1 : 0;
- hi = hival * ( maxLo+1 );
- if ( log.isDebugEnabled() )
- log.debug("new hi value: " + hival);
+
+ 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 IdentifierGeneratorHelper.createNumber( hi + lo++, returnClass );
+ return value.makeValueThenIncrement();
}
}
Modified: core/trunk/core/src/main/java/org/hibernate/id/TableGenerator.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/TableGenerator.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/core/src/main/java/org/hibernate/id/TableGenerator.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -50,17 +50,21 @@
* table to store the last generated value. It is not
* intended that applications use this strategy directly.
* However, it may be used to build other (efficient)
- * strategies. The returned type is <tt>Integer</tt>.<br>
- * <br>
- * The hi value MUST be fetched in a seperate transaction
- * to the <tt>Session</tt> transaction so the generator must
- * be able to obtain a new connection and commit it. Hence
- * this implementation may not be used when Hibernate is
- * fetching connections when the user is supplying
- * connections.<br>
- * <br>
- * The returned value is of type <tt>integer</tt>.<br>
- * <br>
+ * strategies. The returned type is any supported by
+ * {@link IntegralDataTypeHolder}
+ * <p/>
+ * The value MUST be fetched in a separate transaction
+ * from that of the main {@link SessionImplementor session}
+ * transaction so the generator must be able to obtain a new
+ * connection and commit it. Hence this implementation may only
+ * be used when Hibernate is fetching connections, not when the
+ * user is supplying connections.
+ * <p/>
+ * Again, the return types supported here are any of the ones
+ * supported by {@link IntegralDataTypeHolder}. This is new
+ * as of 3.5. Prior to that this generator only returned {@link Integer}
+ * values.
+ * <p/>
* Mapping parameters supported: table, column
*
* @see TableHiLoGenerator
@@ -83,12 +87,15 @@
private static final Logger log = LoggerFactory.getLogger(TableGenerator.class);
+ private Type identifierType;
private String tableName;
private String columnName;
private String query;
private String update;
public void configure(Type type, Properties params, Dialect dialect) {
+ identifierType = type;
+
ObjectNameNormalizer normalizer = ( ObjectNameNormalizer ) params.get( IDENTIFIER_NORMALIZER );
tableName = PropertiesHelper.getString( TABLE, params, DEFAULT_TABLE_NAME );
@@ -127,12 +134,13 @@
" = ?";
}
- public synchronized Serializable generate(SessionImplementor session, Object object)
- throws HibernateException {
- int result = ( (Integer) doWorkInNewTransaction(session) ).intValue();
- return new Integer(result);
+ public synchronized Serializable generate(SessionImplementor session, Object object) {
+ return generateHolder( session ).makeValue();
}
+ protected IntegralDataTypeHolder generateHolder(SessionImplementor session) {
+ return (IntegralDataTypeHolder) doWorkInNewTransaction( session );
+ }
public String[] sqlCreateStrings(Dialect dialect) throws HibernateException {
return new String[] {
@@ -157,8 +165,19 @@
return tableName;
}
+ /**
+ * Get the next value.
+ *
+ * @param conn The sql connection to use.
+ * @param sql n/a
+ *
+ * @return Prior to 3.5 this method returned an {@link Integer}. Since 3.5 it now
+ * returns a {@link IntegralDataTypeHolder}
+ *
+ * @throws SQLException
+ */
public Serializable doWorkInCurrentTransaction(Connection conn, String sql) throws SQLException {
- int result;
+ IntegralDataTypeHolder value = buildHolder();
int rows;
do {
// The loop ensures atomicity of the
@@ -175,7 +194,7 @@
log.error(err);
throw new IdentifierGenerationException(err);
}
- result = rs.getInt(1);
+ value.initialize( rs, 1 );
rs.close();
}
catch (SQLException sqle) {
@@ -190,8 +209,8 @@
SQL_STATEMENT_LOGGER.logStatement( sql, FormatStyle.BASIC );
PreparedStatement ups = conn.prepareStatement(update);
try {
- ups.setInt( 1, result + 1 );
- ups.setInt( 2, result );
+ value.copy().increment().bind( ups, 1 );
+ value.bind( ups, 2 );
rows = ups.executeUpdate();
}
catch (SQLException sqle) {
@@ -203,6 +222,10 @@
}
}
while (rows==0);
- return new Integer(result);
+ return value;
}
+
+ protected IntegralDataTypeHolder buildHolder() {
+ return IdentifierGeneratorHelper.getIntegralDataTypeHolder( identifierType.getReturnedClass() );
+ }
}
Modified: core/trunk/core/src/main/java/org/hibernate/id/TableHiLoGenerator.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/TableHiLoGenerator.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/core/src/main/java/org/hibernate/id/TableHiLoGenerator.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -29,7 +29,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.hibernate.HibernateException;
import org.hibernate.dialect.Dialect;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.type.Type;
@@ -58,37 +57,40 @@
*/
public static final String MAX_LO = "max_lo";
- private long hi;
+ private int maxLo;
private int lo;
- private int maxLo;
- private Class returnClass;
+ private IntegralDataTypeHolder value;
+
private static final Logger log = LoggerFactory.getLogger(TableHiLoGenerator.class);
public void configure(Type type, Properties params, Dialect d) {
super.configure(type, params, d);
maxLo = PropertiesHelper.getInt(MAX_LO, params, Short.MAX_VALUE);
lo = maxLo + 1; // so we "clock over" on the first invocation
- returnClass = type.getReturnedClass();
}
- public synchronized Serializable generate(SessionImplementor session, Object obj)
- throws HibernateException {
- if (maxLo < 1) {
+ public synchronized Serializable generate(SessionImplementor session, Object obj) {
+ // maxLo < 1 indicates a hilo generator with no hilo :?
+ if ( maxLo < 1 ) {
//keep the behavior consistent even for boundary usages
- long val = ( (Number) super.generate(session, obj) ).longValue();
- if (val == 0) val = ( (Number) super.generate(session, obj) ).longValue();
- return IdentifierGeneratorHelper.createNumber( val, returnClass );
+ IntegralDataTypeHolder value = null;
+ while ( value == null || value.lt( 0 ) ) {
+ value = generateHolder( session );
+ }
+ return value.makeValue();
}
- if (lo>maxLo) {
- long hival = ( (Number) super.generate(session, obj) ).longValue();
- lo = (hival == 0) ? 1 : 0;
- hi = hival * (maxLo+1);
- log.debug("new hi value: " + hival);
+
+ 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 IdentifierGeneratorHelper.createNumber( hi + lo++, returnClass );
-
+ return value.makeValueThenIncrement();
}
}
Modified: core/trunk/core/src/main/java/org/hibernate/id/enhanced/AccessCallback.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/enhanced/AccessCallback.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/core/src/main/java/org/hibernate/id/enhanced/AccessCallback.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -24,6 +24,8 @@
*/
package org.hibernate.id.enhanced;
+import org.hibernate.id.IntegralDataTypeHolder;
+
/**
* Contract for providing callback access to a {@link DatabaseStructure},
* typically from the {@link Optimizer}.
@@ -36,5 +38,5 @@
*
* @return The next value.
*/
- public long getNextValue();
+ public IntegralDataTypeHolder getNextValue();
}
Modified: core/trunk/core/src/main/java/org/hibernate/id/enhanced/Optimizer.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/enhanced/Optimizer.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/core/src/main/java/org/hibernate/id/enhanced/Optimizer.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -26,6 +26,8 @@
import java.io.Serializable;
+import org.hibernate.id.IntegralDataTypeHolder;
+
/**
* Performs optimization on an optimizable identifier generator. Typically
* this optimization takes the form of trying to ensure we do not have to
@@ -51,12 +53,12 @@
/**
* A common means to access the last value obtained from the underlying
* source. This is intended for testing purposes, since accessing the
- * unerlying database source directly is much more difficult.
+ * underlying database source directly is much more difficult.
*
* @return The last value we obtained from the underlying source;
- * -1 indicates we have not yet consulted with the source.
+ * null indicates we have not yet consulted with the source.
*/
- public long getLastSourceValue();
+ public IntegralDataTypeHolder getLastSourceValue();
/**
* Retrieves the defined increment size.
Modified: core/trunk/core/src/main/java/org/hibernate/id/enhanced/OptimizerFactory.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/enhanced/OptimizerFactory.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/core/src/main/java/org/hibernate/id/enhanced/OptimizerFactory.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -31,8 +31,8 @@
import org.slf4j.LoggerFactory;
import org.hibernate.HibernateException;
+import org.hibernate.id.IntegralDataTypeHolder;
import org.hibernate.util.ReflectHelper;
-import org.hibernate.id.IdentifierGeneratorHelper;
/**
* Factory for {@link Optimizer} instances.
@@ -98,17 +98,6 @@
}
/**
- * Take the primitive long value and "make" (or wrap) it into the
- * {@link #getReturnClass id type}.
- *
- * @param value The primitive value to make/wrap.
- * @return The wrapped value.
- */
- protected final Serializable make(long value) {
- return IdentifierGeneratorHelper.createNumber( value, returnClass );
- }
-
- /**
* Getter for property 'returnClass'. This is the Java
* class which is used to represent the id (e.g. {@link java.lang.Long}).
*
@@ -131,7 +120,7 @@
* every request.
*/
public static class NoopOptimizer extends OptimizerSupport {
- private long lastSourceValue = -1;
+ private IntegralDataTypeHolder lastSourceValue;
public NoopOptimizer(Class returnClass, int incrementSize) {
super( returnClass, incrementSize );
@@ -141,21 +130,21 @@
* {@inheritDoc}
*/
public Serializable generate(AccessCallback callback) {
- if ( lastSourceValue == -1 ) {
- while( lastSourceValue <= 0 ) {
+ if ( lastSourceValue == null ) {
+ do {
lastSourceValue = callback.getNextValue();
- }
+ } while ( lastSourceValue.lt( 1 ) );
}
else {
lastSourceValue = callback.getNextValue();
}
- return make( lastSourceValue );
+ return lastSourceValue.makeValue();
}
/**
* {@inheritDoc}
*/
- public long getLastSourceValue() {
+ public IntegralDataTypeHolder getLastSourceValue() {
return lastSourceValue;
}
@@ -170,11 +159,40 @@
/**
* Optimizer which applies a 'hilo' algorithm in memory to achieve
* optimization.
+ * <p/>
+ * A 'hilo' algorithm is simply a means for a single value stored in the
+ * database to represent a "bucket" of possible, contiguous values. The
+ * database value identifies which particular bucket we are on.
+ * <p/>
+ * This database value must be paired with another value that defines the
+ * size of the bucket; the number of possible values available.
+ * The {@link #getIncrementSize() incrementSize} serves this purpose. The
+ * naming here is meant more for consistency in that this value serves the
+ * same purpose as the increment supplied to the {@link PooledOptimizer}.
+ * <p/>
+ * The general algorithms used to determine the bucket are:<ol>
+ * <li>{@code upperLimit = (databaseValue * incrementSize) + 1}</li>
+ * <li>{@code lowerLimit = upperLimit - 1}</li>
+ * </ol>
+ * As an example, consider a case with incrementSize of 10. Initially the
+ * database holds 1:<ol>
+ * <li>{@code upperLimit = (1 * 20) + 1 = 21}</li>
+ * <li>{@code lowerLimit = 21 - 20 = 1}</li>
+ * </ol>
+ * From there we increment the value from lowerLimit until we reach the
+ * upperLimit, at which point we would define a new bucket. The database
+ * now contains 2, though incrementSize remains unchanged:<ol>
+ * <li>{@code upperLimit = (2 * 20) + 1 = 41}</li>
+ * <li>{@code lowerLimit = 41 - 20 = 21}</li>
+ * </ol>
+ * And so on...
+ * <p/>
+ * Note, 'value' always (after init) holds the next value to return
*/
public static class HiLoOptimizer extends OptimizerSupport {
- private long lastSourceValue = -1;
- private long value;
- private long hiValue;
+ private IntegralDataTypeHolder lastSourceValue;
+ private IntegralDataTypeHolder upperLimit;
+ private IntegralDataTypeHolder value;
public HiLoOptimizer(Class returnClass, int incrementSize) {
super( returnClass, incrementSize );
@@ -190,26 +208,30 @@
* {@inheritDoc}
*/
public synchronized Serializable generate(AccessCallback callback) {
- if ( lastSourceValue < 0 ) {
+ if ( lastSourceValue == null ) {
+ // first call, so initialize ourselves. we need to read the database
+ // value and set up the 'bucket' boundaries
lastSourceValue = callback.getNextValue();
- while ( lastSourceValue <= 0 ) {
+ while ( lastSourceValue.lt( 1 ) ) {
lastSourceValue = callback.getNextValue();
}
- hiValue = ( lastSourceValue * incrementSize ) + 1;
- value = hiValue - incrementSize;
+ // upperLimit defines the upper end of the bucket values
+ upperLimit = lastSourceValue.copy().multiplyBy( incrementSize ).increment();
+ // initialize value to the low end of the bucket
+ value = upperLimit.copy().subtract( incrementSize );
}
- else if ( value >= hiValue ) {
+ else if ( ! upperLimit.gt( value ) ) {
lastSourceValue = callback.getNextValue();
- hiValue = ( lastSourceValue * incrementSize ) + 1;
+ upperLimit = lastSourceValue.copy().multiplyBy( incrementSize ).increment();
}
- return make( value++ );
+ return value.makeValueThenIncrement();
}
/**
* {@inheritDoc}
*/
- public long getLastSourceValue() {
+ public IntegralDataTypeHolder getLastSourceValue() {
return lastSourceValue;
}
@@ -222,30 +244,38 @@
/**
* Getter for property 'lastValue'.
+ * <p/>
+ * Exposure intended for testing purposes.
*
* @return Value for property 'lastValue'.
*/
- public long getLastValue() {
- return value - 1;
+ public IntegralDataTypeHolder getLastValue() {
+ return value.copy().decrement();
}
/**
- * Getter for property 'hiValue'.
+ * Getter for property 'upperLimit'.
+ * <p/>
+ * Exposure intended for testing purposes.
*
- * @return Value for property 'hiValue'.
+ * @return Value for property 'upperLimit'.
*/
- public long getHiValue() {
- return hiValue;
+ public IntegralDataTypeHolder getHiValue() {
+ return upperLimit;
}
}
/**
* Optimizer which uses a pool of values, storing the next low value of the
* range in the database.
+ * <p/>
+ * Note that this optimizer works essentially the same as the
+ * {@link HiLoOptimizer} except that here the bucket ranges are actually
+ * encoded into the database structures.
*/
public static class PooledOptimizer extends OptimizerSupport {
- private long value;
- private long hiValue = -1;
+ private IntegralDataTypeHolder hiValue;
+ private IntegralDataTypeHolder value;
public PooledOptimizer(Class returnClass, int incrementSize) {
super( returnClass, incrementSize );
@@ -261,9 +291,9 @@
* {@inheritDoc}
*/
public synchronized Serializable generate(AccessCallback callback) {
- if ( hiValue < 0 ) {
+ if ( hiValue == null ) {
value = callback.getNextValue();
- if ( value < 1 ) {
+ if ( value.lt( 1 ) ) {
// unfortunately not really safe to normalize this
// to 1 as an initial value like we do the others
// because we would not be able to control this if
@@ -272,17 +302,17 @@
}
hiValue = callback.getNextValue();
}
- else if ( value >= hiValue ) {
+ else if ( ! hiValue.gt( value ) ) {
hiValue = callback.getNextValue();
- value = hiValue - incrementSize;
+ value = hiValue.copy().subtract( incrementSize );
}
- return make( value++ );
+ return value.makeValueThenIncrement();
}
/**
* {@inheritDoc}
*/
- public long getLastSourceValue() {
+ public IntegralDataTypeHolder getLastSourceValue() {
return hiValue;
}
@@ -295,11 +325,13 @@
/**
* Getter for property 'lastValue'.
+ * <p/>
+ * Exposure intended for testing purposes.
*
* @return Value for property 'lastValue'.
*/
- public long getLastValue() {
- return value - 1;
+ public IntegralDataTypeHolder getLastValue() {
+ return value.copy().decrement();
}
}
}
Modified: core/trunk/core/src/main/java/org/hibernate/id/enhanced/SequenceStructure.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/enhanced/SequenceStructure.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/core/src/main/java/org/hibernate/id/enhanced/SequenceStructure.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -35,6 +35,8 @@
import org.hibernate.engine.SessionImplementor;
import org.hibernate.exception.JDBCExceptionHelper;
import org.hibernate.HibernateException;
+import org.hibernate.id.IdentifierGeneratorHelper;
+import org.hibernate.id.IntegralDataTypeHolder;
/**
* Describes a sequence.
@@ -47,14 +49,21 @@
private final String sequenceName;
private final int initialValue;
private final int incrementSize;
+ private final Class numberType;
private final String sql;
private boolean applyIncrementSizeToSourceValues;
private int accessCounter;
- public SequenceStructure(Dialect dialect, String sequenceName, int initialValue, int incrementSize) {
+ public SequenceStructure(
+ Dialect dialect,
+ String sequenceName,
+ int initialValue,
+ int incrementSize,
+ Class numberType) {
this.sequenceName = sequenceName;
this.initialValue = initialValue;
this.incrementSize = incrementSize;
+ this.numberType = numberType;
sql = dialect.getSequenceNextValString( sequenceName );
}
@@ -91,7 +100,7 @@
*/
public AccessCallback buildCallback(final SessionImplementor session) {
return new AccessCallback() {
- public long getNextValue() {
+ public IntegralDataTypeHolder getNextValue() {
accessCounter++;
try {
PreparedStatement st = session.getBatcher().prepareSelectStatement( sql );
@@ -99,11 +108,12 @@
ResultSet rs = st.executeQuery();
try {
rs.next();
- long result = rs.getLong( 1 );
+ IntegralDataTypeHolder value = IdentifierGeneratorHelper.getIntegralDataTypeHolder( numberType );
+ value.initialize( rs, 1 );
if ( log.isDebugEnabled() ) {
- log.debug("Sequence identifier generated: " + result);
+ log.debug( "Sequence value obtained: " + value.makeValue() );
}
- return result;
+ return value;
}
finally {
try {
Modified: core/trunk/core/src/main/java/org/hibernate/id/enhanced/SequenceStyleGenerator.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/enhanced/SequenceStyleGenerator.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/core/src/main/java/org/hibernate/id/enhanced/SequenceStyleGenerator.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -178,7 +178,15 @@
}
}
- this.databaseStructure = buildDatabaseStructure( params, dialect, forceTableUse, sequenceName, initialValue, incrementSize );
+ this.databaseStructure = buildDatabaseStructure(
+ type,
+ params,
+ dialect,
+ forceTableUse,
+ sequenceName,
+ initialValue,
+ incrementSize
+ );
this.optimizer = OptimizerFactory.buildOptimizer( optimizationStrategy, identifierType.getReturnedClass(), incrementSize );
this.databaseStructure.prepare( optimizer );
@@ -291,15 +299,16 @@
/**
* Build the database structure.
*
+ * @param type The Hibernate type of the identifier property
* @param params The params supplied in the generator config (plus some standard useful extras).
* @param dialect The dialect being used.
* @param forceTableUse Should a table be used even if the dialect supports sequences?
* @param sequenceName The name to use for the sequence or table.
* @param initialValue The initial value.
- * @param incrementSize the increment size to use (after any adjustments).
- * @return The db structure representation
+ * @param incrementSize the increment size to use (after any adjustments). @return The db structure representation
*/
protected DatabaseStructure buildDatabaseStructure(
+ Type type,
Properties params,
Dialect dialect,
boolean forceTableUse,
@@ -308,11 +317,11 @@
int incrementSize) {
boolean useSequence = dialect.supportsSequences() && !forceTableUse;
if ( useSequence ) {
- return new SequenceStructure( dialect, sequenceName, initialValue, incrementSize );
+ return new SequenceStructure( dialect, sequenceName, initialValue, incrementSize, type.getReturnedClass() );
}
else {
String valueColumnName = determineValueColumnName( params, dialect );
- return new TableStructure( dialect, sequenceName, valueColumnName, initialValue, incrementSize );
+ return new TableStructure( dialect, sequenceName, valueColumnName, initialValue, incrementSize, type.getReturnedClass() );
}
}
Modified: core/trunk/core/src/main/java/org/hibernate/id/enhanced/TableGenerator.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/enhanced/TableGenerator.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/core/src/main/java/org/hibernate/id/enhanced/TableGenerator.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -39,6 +39,8 @@
import org.hibernate.engine.TransactionHelper;
import org.hibernate.engine.SessionImplementor;
+import org.hibernate.id.IdentifierGeneratorHelper;
+import org.hibernate.id.IntegralDataTypeHolder;
import org.hibernate.id.PersistentIdentifierGenerator;
import org.hibernate.id.Configurable;
import org.hibernate.type.Type;
@@ -287,7 +289,7 @@
public void configure(Type type, Properties params, Dialect dialect) throws MappingException {
identifierType = type;
- tableName = determneGeneratorTableName( params, dialect );
+ tableName = determineGeneratorTableName( params, dialect );
segmentColumnName = determineSegmentColumnName( params, dialect );
valueColumnName = determineValueColumnName( params, dialect );
@@ -316,7 +318,7 @@
* @param dialect The dialect in effect
* @return The table name to use.
*/
- protected String determneGeneratorTableName(Properties params, Dialect dialect) {
+ protected String determineGeneratorTableName(Properties params, Dialect dialect) {
String name = PropertiesHelper.getString( TABLE_PARAM, params, DEF_TABLE );
boolean isGivenNameUnqualified = name.indexOf( '.' ) < 0;
if ( isGivenNameUnqualified ) {
@@ -450,8 +452,8 @@
public synchronized Serializable generate(final SessionImplementor session, Object obj) {
return optimizer.generate(
new AccessCallback() {
- public long getNextValue() {
- return ( ( Number ) doWorkInNewTransaction( session ) ).longValue();
+ public IntegralDataTypeHolder getNextValue() {
+ return ( IntegralDataTypeHolder ) doWorkInNewTransaction( session );
}
}
);
@@ -461,7 +463,7 @@
* {@inheritDoc}
*/
public Serializable doWorkInCurrentTransaction(Connection conn, String sql) throws SQLException {
- int result;
+ IntegralDataTypeHolder value = IdentifierGeneratorHelper.getIntegralDataTypeHolder( identifierType.getReturnedClass() );
int rows;
do {
SQL_STATEMENT_LOGGER.logStatement( selectQuery, FormatStyle.BASIC );
@@ -470,13 +472,13 @@
selectPS.setString( 1, segmentValue );
ResultSet selectRS = selectPS.executeQuery();
if ( !selectRS.next() ) {
+ value.initialize( initialValue );
PreparedStatement insertPS = null;
try {
- result = initialValue;
SQL_STATEMENT_LOGGER.logStatement( insertQuery, FormatStyle.BASIC );
insertPS = conn.prepareStatement( insertQuery );
insertPS.setString( 1, segmentValue );
- insertPS.setLong( 2, result );
+ value.bind( insertPS, 2 );
insertPS.execute();
}
finally {
@@ -486,7 +488,7 @@
}
}
else {
- result = selectRS.getInt( 1 );
+ value.initialize( selectRS, 1 );
}
selectRS.close();
}
@@ -501,10 +503,15 @@
SQL_STATEMENT_LOGGER.logStatement( updateQuery, FormatStyle.BASIC );
PreparedStatement updatePS = conn.prepareStatement( updateQuery );
try {
- long newValue = optimizer.applyIncrementSizeToSourceValues()
- ? result + incrementSize : result + 1;
- updatePS.setLong( 1, newValue );
- updatePS.setLong( 2, result );
+ final IntegralDataTypeHolder updateValue = value.copy();
+ if ( optimizer.applyIncrementSizeToSourceValues() ) {
+ updateValue.add( incrementSize );
+ }
+ else {
+ updateValue.increment();
+ }
+ updateValue.bind( updatePS, 1 );
+ value.bind( updatePS, 2 );
updatePS.setString( 3, segmentValue );
rows = updatePS.executeUpdate();
}
@@ -520,7 +527,7 @@
accessCount++;
- return new Integer( result );
+ return value;
}
/**
Modified: core/trunk/core/src/main/java/org/hibernate/id/enhanced/TableStructure.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/id/enhanced/TableStructure.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/core/src/main/java/org/hibernate/id/enhanced/TableStructure.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -40,6 +40,8 @@
import org.hibernate.engine.SessionImplementor;
import org.hibernate.engine.TransactionHelper;
import org.hibernate.id.IdentifierGenerationException;
+import org.hibernate.id.IdentifierGeneratorHelper;
+import org.hibernate.id.IntegralDataTypeHolder;
import org.hibernate.jdbc.util.FormatStyle;
import org.hibernate.jdbc.util.SQLStatementLogger;
@@ -56,17 +58,25 @@
private final String valueColumnName;
private final int initialValue;
private final int incrementSize;
+ private final Class numberType;
private final String selectQuery;
private final String updateQuery;
private boolean applyIncrementSizeToSourceValues;
private int accessCounter;
- public TableStructure(Dialect dialect, String tableName, String valueColumnName, int initialValue, int incrementSize) {
+ public TableStructure(
+ Dialect dialect,
+ String tableName,
+ String valueColumnName,
+ int initialValue,
+ int incrementSize,
+ Class numberType) {
this.tableName = tableName;
this.initialValue = initialValue;
this.incrementSize = incrementSize;
this.valueColumnName = valueColumnName;
+ this.numberType = numberType;
selectQuery = "select " + valueColumnName + " as id_val" +
" from " + dialect.appendLockHint( LockMode.PESSIMISTIC_WRITE, tableName ) +
@@ -117,8 +127,8 @@
*/
public AccessCallback buildCallback(final SessionImplementor session) {
return new AccessCallback() {
- public long getNextValue() {
- return ( ( Number ) doWorkInNewTransaction( session ) ).longValue();
+ public IntegralDataTypeHolder getNextValue() {
+ return ( IntegralDataTypeHolder ) doWorkInNewTransaction( session );
}
};
}
@@ -152,7 +162,7 @@
* {@inheritDoc}
*/
protected Serializable doWorkInCurrentTransaction(Connection conn, String sql) throws SQLException {
- long result;
+ IntegralDataTypeHolder value = IdentifierGeneratorHelper.getIntegralDataTypeHolder( numberType );
int rows;
do {
SQL_STATEMENT_LOGGER.logStatement( selectQuery, FormatStyle.BASIC );
@@ -164,7 +174,7 @@
log.error( err );
throw new IdentifierGenerationException( err );
}
- result = selectRS.getLong( 1 );
+ value.initialize( selectRS, 1 );
selectRS.close();
}
catch ( SQLException sqle ) {
@@ -178,9 +188,10 @@
SQL_STATEMENT_LOGGER.logStatement( updateQuery, FormatStyle.BASIC );
PreparedStatement updatePS = conn.prepareStatement( updateQuery );
try {
- int increment = applyIncrementSizeToSourceValues ? incrementSize : 1;
- updatePS.setLong( 1, result + increment );
- updatePS.setLong( 2, result );
+ final int increment = applyIncrementSizeToSourceValues ? incrementSize : 1;
+ final IntegralDataTypeHolder updateValue = value.copy().add( increment );
+ updateValue.bind( updatePS, 1 );
+ value.bind( updatePS, 2 );
rows = updatePS.executeUpdate();
}
catch ( SQLException sqle ) {
@@ -194,7 +205,7 @@
accessCounter++;
- return new Long( result );
+ return value;
}
}
Added: core/trunk/core/src/test/java/org/hibernate/id/AbstractHolderTest.java
===================================================================
--- core/trunk/core/src/test/java/org/hibernate/id/AbstractHolderTest.java (rev 0)
+++ core/trunk/core/src/test/java/org/hibernate/id/AbstractHolderTest.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -0,0 +1,167 @@
+/*
+ * 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 junit.framework.TestCase;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+public abstract class AbstractHolderTest extends TestCase {
+ protected abstract IntegralDataTypeHolder makeHolder();
+
+ public void testInitializationChecking() {
+ IntegralDataTypeHolder holder = makeHolder();
+ try {
+ holder.increment();
+ fail();
+ }
+ catch ( IdentifierGenerationException expected ) {
+ }
+
+ try {
+ holder.add( 1 );
+ fail();
+ }
+ catch ( IdentifierGenerationException expected ) {
+ }
+
+ try {
+ holder.decrement();
+ fail();
+ }
+ catch ( IdentifierGenerationException expected ) {
+ }
+
+ try {
+ holder.subtract( 1 );
+ fail();
+ }
+ catch ( IdentifierGenerationException expected ) {
+ }
+
+ try {
+ holder.multiplyBy( holder );
+ fail();
+ }
+ catch ( IdentifierGenerationException expected ) {
+ }
+
+ try {
+ holder.multiplyBy( 1 );
+ fail();
+ }
+ catch ( IdentifierGenerationException expected ) {
+ }
+
+ try {
+ holder.eq( holder );
+ fail();
+ }
+ catch ( IdentifierGenerationException expected ) {
+ }
+
+ try {
+ holder.eq( 1 );
+ fail();
+ }
+ catch ( IdentifierGenerationException expected ) {
+ }
+
+ try {
+ holder.lt( holder );
+ fail();
+ }
+ catch ( IdentifierGenerationException expected ) {
+ }
+
+ try {
+ holder.lt( 1 );
+ fail();
+ }
+ catch ( IdentifierGenerationException expected ) {
+ }
+
+ try {
+ holder.gt( holder );
+ fail();
+ }
+ catch ( IdentifierGenerationException expected ) {
+ }
+
+ try {
+ holder.gt( 1 );
+ fail();
+ }
+ catch ( IdentifierGenerationException expected ) {
+ }
+
+ try {
+ holder.makeValue();
+ fail();
+ }
+ catch ( IdentifierGenerationException expected ) {
+ }
+ }
+
+ public void testIncrement() {
+ IntegralDataTypeHolder holder = makeHolder();
+ holder.initialize( 0 );
+ int i = 0;
+ for ( ; i < 5008; i++ ) {
+ holder.increment();
+ }
+ assertEquals( holder.copy().initialize( i ), holder );
+ }
+
+ public void testBasicHiloAlgorithm() {
+ // mimic an initialValue of 1 and increment of 20
+ final long initialValue = 1;
+ final long incrementSize = 2;
+
+ // initialization
+ IntegralDataTypeHolder lastSourceValue = makeHolder().initialize( 1 );
+ IntegralDataTypeHolder upperLimit = lastSourceValue.copy().multiplyBy( incrementSize ).increment();
+ IntegralDataTypeHolder value = upperLimit.copy().subtract( incrementSize );
+
+ assertEquals( 1, lastSourceValue.makeValue().longValue() );
+ assertEquals( 3, upperLimit.makeValue().longValue() );
+ assertEquals( 1, value.makeValue().longValue() );
+
+ value.increment();
+ value.increment();
+
+ assertFalse( upperLimit.gt( value ) );
+
+ // at which point we would "clock over"
+ lastSourceValue.increment();
+ upperLimit = lastSourceValue.copy().multiplyBy( incrementSize ).increment();
+
+ assertEquals( 2, lastSourceValue.makeValue().longValue() );
+ assertEquals( 5, upperLimit.makeValue().longValue() );
+ assertEquals( 3, value.makeValue().longValue() );
+ }
+}
Added: core/trunk/core/src/test/java/org/hibernate/id/BigDecimalHolderTest.java
===================================================================
--- core/trunk/core/src/test/java/org/hibernate/id/BigDecimalHolderTest.java (rev 0)
+++ core/trunk/core/src/test/java/org/hibernate/id/BigDecimalHolderTest.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -0,0 +1,37 @@
+/*
+ * 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.math.BigDecimal;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+public class BigDecimalHolderTest extends AbstractHolderTest {
+ protected IntegralDataTypeHolder makeHolder() {
+ return IdentifierGeneratorHelper.getIntegralDataTypeHolder( BigDecimal.class );
+ }
+}
\ No newline at end of file
Added: core/trunk/core/src/test/java/org/hibernate/id/BigIntegerHolderTest.java
===================================================================
--- core/trunk/core/src/test/java/org/hibernate/id/BigIntegerHolderTest.java (rev 0)
+++ core/trunk/core/src/test/java/org/hibernate/id/BigIntegerHolderTest.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -0,0 +1,37 @@
+/*
+ * 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.math.BigInteger;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+public class BigIntegerHolderTest extends AbstractHolderTest {
+ protected IntegralDataTypeHolder makeHolder() {
+ return IdentifierGeneratorHelper.getIntegralDataTypeHolder( BigInteger.class );
+ }
+}
Added: core/trunk/core/src/test/java/org/hibernate/id/LongHolderTest.java
===================================================================
--- core/trunk/core/src/test/java/org/hibernate/id/LongHolderTest.java (rev 0)
+++ core/trunk/core/src/test/java/org/hibernate/id/LongHolderTest.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -0,0 +1,35 @@
+/*
+ * 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;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+public class LongHolderTest extends AbstractHolderTest {
+ protected IntegralDataTypeHolder makeHolder() {
+ return IdentifierGeneratorHelper.getIntegralDataTypeHolder( Long.class );
+ }
+}
Copied: core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/increment/BigIntegerIncrementGeneratorTest.java (from rev 18771, core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/forcedtable/BasicForcedTableSequenceTest.java)
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/increment/BigIntegerIncrementGeneratorTest.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/increment/BigIntegerIncrementGeneratorTest.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -0,0 +1,73 @@
+/*
+ * 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.test.idgen.biginteger.increment;
+
+import java.math.BigInteger;
+
+import junit.framework.Test;
+
+import org.hibernate.Session;
+import org.hibernate.junit.functional.FunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class BigIntegerIncrementGeneratorTest extends FunctionalTestCase {
+ public BigIntegerIncrementGeneratorTest(String string) {
+ super( string );
+ }
+
+ public String[] getMappings() {
+ return new String[] { "idgen/biginteger/increment/Mapping.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( BigIntegerIncrementGeneratorTest.class );
+ }
+
+ public void testBasics() {
+ Session s = openSession();
+ s.beginTransaction();
+ Entity entity = new Entity( "BigInteger + increment #1" );
+ s.save( entity );
+ Entity entity2 = new Entity( "BigInteger + increment #2" );
+ s.save( entity2 );
+ s.getTransaction().commit();
+ s.close();
+
+ assertEquals( BigInteger.valueOf( 1 ), entity.getId() );
+ assertEquals( BigInteger.valueOf( 2 ), entity2.getId() );
+
+ s = openSession();
+ s.beginTransaction();
+ s.delete( entity );
+ s.delete( entity2 );
+ s.getTransaction().commit();
+ s.close();
+
+ }
+}
\ No newline at end of file
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/increment/Entity.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/increment/Entity.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/increment/Entity.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -0,0 +1,59 @@
+/*
+ * 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.test.idgen.biginteger.increment;
+
+import java.math.BigInteger;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+public class Entity {
+ private BigInteger id;
+ private String name;
+
+ public Entity() {
+ }
+
+ public Entity(String name) {
+ this.name = name;
+ }
+
+ public BigInteger getId() {
+ return id;
+ }
+
+ public void setId(BigInteger id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
Copied: core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/increment/Mapping.hbm.xml (from rev 18771, core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/forcedtable/Basic.hbm.xml)
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/increment/Mapping.hbm.xml (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/increment/Mapping.hbm.xml 2010-02-12 06:22:52 UTC (rev 18789)
@@ -0,0 +1,42 @@
+<?xml version="1.0"?>
+<!--
+ ~ 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
+ -->
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<!--
+ Demonstrates use of simple increment generator on a BigInteger property.
+-->
+
+<hibernate-mapping package="org.hibernate.test.idgen.biginteger.increment">
+
+ <class name="Entity">
+ <id name="id" column="ID" type="big_integer">
+ <generator class="increment" />
+ </id>
+ <property name="name" type="string"/>
+ </class>
+
+</hibernate-mapping>
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/sequence/BigIntegerSequenceGeneratorTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/sequence/BigIntegerSequenceGeneratorTest.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/sequence/BigIntegerSequenceGeneratorTest.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -0,0 +1,79 @@
+/*
+ * 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.test.idgen.biginteger.sequence;
+
+import junit.framework.Test;
+
+import org.hibernate.Session;
+import org.hibernate.dialect.Dialect;
+import org.hibernate.junit.functional.DatabaseSpecificFunctionalTestCase;
+import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
+
+/**
+ * {@inheritDoc}
+ *
+ * @author Steve Ebersole
+ */
+public class BigIntegerSequenceGeneratorTest extends DatabaseSpecificFunctionalTestCase {
+ public BigIntegerSequenceGeneratorTest(String string) {
+ super( string );
+ }
+
+ public String[] getMappings() {
+ return new String[] { "idgen/biginteger/sequence/Mapping.hbm.xml" };
+ }
+
+ public static Test suite() {
+ return new FunctionalTestClassTestSuite( BigIntegerSequenceGeneratorTest.class );
+ }
+
+ @Override
+ public boolean appliesTo(Dialect dialect) {
+ return dialect.supportsSequences();
+ }
+
+ public void testBasics() {
+ Session s = openSession();
+ s.beginTransaction();
+ Entity entity = new Entity( "BigInteger + sequence #1" );
+ s.save( entity );
+ Entity entity2 = new Entity( "BigInteger + sequence #2" );
+ s.save( entity2 );
+ s.getTransaction().commit();
+ s.close();
+
+// hsqldb defines different behavior for the initial select from a sequence
+// then say oracle
+// assertEquals( BigInteger.valueOf( 1 ), entity.getId() );
+// assertEquals( BigInteger.valueOf( 2 ), entity2.getId() );
+
+ s = openSession();
+ s.beginTransaction();
+ s.delete( entity );
+ s.delete( entity2 );
+ s.getTransaction().commit();
+ s.close();
+
+ }
+}
\ No newline at end of file
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/sequence/Entity.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/sequence/Entity.java (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/sequence/Entity.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -0,0 +1,59 @@
+/*
+ * 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.test.idgen.biginteger.sequence;
+
+import java.math.BigInteger;
+
+/**
+ * TODO : javadoc
+ *
+ * @author Steve Ebersole
+ */
+public class Entity {
+ private BigInteger id;
+ private String name;
+
+ public Entity() {
+ }
+
+ public Entity(String name) {
+ this.name = name;
+ }
+
+ public BigInteger getId() {
+ return id;
+ }
+
+ public void setId(BigInteger id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
\ No newline at end of file
Added: core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/sequence/Mapping.hbm.xml
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/sequence/Mapping.hbm.xml (rev 0)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/biginteger/sequence/Mapping.hbm.xml 2010-02-12 06:22:52 UTC (rev 18789)
@@ -0,0 +1,43 @@
+<?xml version="1.0"?>
+<!--
+ ~ 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
+ -->
+<!DOCTYPE hibernate-mapping PUBLIC
+ "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
+ "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
+
+<!--
+ Demonstrates use of a sequence generator on a BigInteger property.
+-->
+
+<hibernate-mapping package="org.hibernate.test.idgen.biginteger.sequence">
+
+ <class name="Entity">
+ <id name="id" column="ID" type="big_integer">
+ <generator class="sequence">
+ </generator>
+ </id>
+ <property name="name" type="string"/>
+ </class>
+
+</hibernate-mapping>
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/OptimizerUnitTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/OptimizerUnitTest.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/OptimizerUnitTest.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -3,6 +3,8 @@
import junit.framework.Test;
import junit.framework.TestSuite;
+import org.hibernate.id.IdentifierGeneratorHelper;
+import org.hibernate.id.IntegralDataTypeHolder;
import org.hibernate.junit.UnitTestCase;
import org.hibernate.id.enhanced.Optimizer;
import org.hibernate.id.enhanced.OptimizerFactory;
@@ -88,7 +90,7 @@
next = ( Long ) optimizer.generate( sequence );
assertEquals( i, next.intValue() );
}
- assertEquals( 2, sequence.getTimesCalled() ); // twice to initialze state
+ assertEquals( 2, sequence.getTimesCalled() ); // twice to initialize state
assertEquals( 11, sequence.getCurrentValue() );
// force a "clock over"
next = ( Long ) optimizer.generate( sequence );
@@ -98,7 +100,7 @@
}
private static class SourceMock implements AccessCallback {
- private long value;
+ private IdentifierGeneratorHelper.BasicHolder value = new IdentifierGeneratorHelper.BasicHolder( Long.class );
private int increment;
private int timesCalled = 0;
@@ -108,12 +110,12 @@
public SourceMock(long initialValue, int increment) {
this.increment = increment;
- this.value = initialValue - increment;
+ this.value.initialize( initialValue - increment );
}
- public long getNextValue() {
+ public IntegralDataTypeHolder getNextValue() {
timesCalled++;
- return ( value += increment );
+ return value.add( increment ).copy();
}
public int getTimesCalled() {
@@ -121,7 +123,7 @@
}
public long getCurrentValue() {
- return value;
+ return value.getActualLongValue();
}
}
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/forcedtable/BasicForcedTableSequenceTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/forcedtable/BasicForcedTableSequenceTest.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/forcedtable/BasicForcedTableSequenceTest.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -2,14 +2,16 @@
import junit.framework.Test;
+import org.hibernate.Session;
+import org.hibernate.id.enhanced.OptimizerFactory;
+import org.hibernate.id.enhanced.SequenceStyleGenerator;
+import org.hibernate.id.enhanced.TableStructure;
import org.hibernate.junit.functional.DatabaseSpecificFunctionalTestCase;
import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
import org.hibernate.persister.entity.EntityPersister;
-import org.hibernate.id.enhanced.SequenceStyleGenerator;
-import org.hibernate.id.enhanced.TableStructure;
-import org.hibernate.id.enhanced.OptimizerFactory;
-import org.hibernate.Session;
+import static org.hibernate.id.IdentifierGeneratorHelper.BasicHolder;
+
/**
* {@inheritDoc}
*
@@ -54,7 +56,7 @@
long expectedId = i + 1;
assertEquals( expectedId, entities[i].getId().longValue() );
assertEquals( expectedId, generator.getDatabaseStructure().getTimesAccessed() );
- assertEquals( expectedId, generator.getOptimizer().getLastSourceValue() );
+ assertEquals( expectedId, ( (BasicHolder) generator.getOptimizer().getLastSourceValue() ).getActualLongValue() );
}
s.getTransaction().commit();
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/forcedtable/HiLoForcedTableSequenceTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/forcedtable/HiLoForcedTableSequenceTest.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/forcedtable/HiLoForcedTableSequenceTest.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -2,14 +2,16 @@
import junit.framework.Test;
+import org.hibernate.Session;
+import org.hibernate.id.enhanced.OptimizerFactory;
+import org.hibernate.id.enhanced.SequenceStyleGenerator;
+import org.hibernate.id.enhanced.TableStructure;
import org.hibernate.junit.functional.DatabaseSpecificFunctionalTestCase;
import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
import org.hibernate.persister.entity.EntityPersister;
-import org.hibernate.id.enhanced.OptimizerFactory;
-import org.hibernate.id.enhanced.SequenceStyleGenerator;
-import org.hibernate.id.enhanced.TableStructure;
-import org.hibernate.Session;
+import static org.hibernate.id.IdentifierGeneratorHelper.BasicHolder;
+
/**
* {@inheritDoc}
*
@@ -54,18 +56,18 @@
s.save( entities[i] );
long expectedId = i + 1;
assertEquals( expectedId, entities[i].getId().longValue() );
- assertEquals( 1, generator.getOptimizer().getLastSourceValue() );
- assertEquals( i + 1, optimizer.getLastValue() );
- assertEquals( increment + 1, optimizer.getHiValue() );
+ assertEquals( 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() );
+ assertEquals( i + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() );
+ assertEquals( increment + 1, ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() );
}
// now force a "clock over"
entities[ increment ] = new Entity( "" + increment );
s.save( entities[ increment ] );
long expectedId = optimizer.getIncrementSize() + 1;
assertEquals( expectedId, entities[ optimizer.getIncrementSize() ].getId().longValue() );
- assertEquals( 2, optimizer.getLastSourceValue() ); // initialization + clokc-over
- assertEquals( increment + 1, optimizer.getLastValue() );
- assertEquals( ( increment * 2 ) + 1, optimizer.getHiValue() );
+ assertEquals( 2, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization + clock-over
+ assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() );
+ assertEquals( ( increment * 2 ) + 1, ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() );
s.getTransaction().commit();
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/forcedtable/PooledForcedTableSequenceTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/forcedtable/PooledForcedTableSequenceTest.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/forcedtable/PooledForcedTableSequenceTest.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -2,14 +2,16 @@
import junit.framework.Test;
+import org.hibernate.Session;
+import org.hibernate.id.enhanced.OptimizerFactory;
+import org.hibernate.id.enhanced.SequenceStyleGenerator;
+import org.hibernate.id.enhanced.TableStructure;
import org.hibernate.junit.functional.DatabaseSpecificFunctionalTestCase;
import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
import org.hibernate.persister.entity.EntityPersister;
-import org.hibernate.id.enhanced.OptimizerFactory;
-import org.hibernate.id.enhanced.SequenceStyleGenerator;
-import org.hibernate.id.enhanced.TableStructure;
-import org.hibernate.Session;
+import static org.hibernate.id.IdentifierGeneratorHelper.BasicHolder;
+
/**
* {@inheritDoc}
*
@@ -54,19 +56,21 @@
s.save( entities[i] );
long expectedId = i + 1;
assertEquals( expectedId, entities[i].getId().longValue() );
- assertEquals( 2, generator.getDatabaseStructure().getTimesAccessed() ); // initialization calls table twice
- assertEquals( increment + 1, optimizer.getLastSourceValue() ); // initialization calls table twice
- assertEquals( i + 1, optimizer.getLastValue() );
- assertEquals( increment + 1, optimizer.getLastSourceValue() );
+ // NOTE : initialization calls table twice
+ assertEquals( 2, generator.getDatabaseStructure().getTimesAccessed() );
+ assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() );
+ assertEquals( i + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() );
+ assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() );
}
// now force a "clock over"
entities[ increment ] = new Entity( "" + increment );
s.save( entities[ increment ] );
long expectedId = optimizer.getIncrementSize() + 1;
assertEquals( expectedId, entities[ optimizer.getIncrementSize() ].getId().longValue() );
- assertEquals( 3, generator.getDatabaseStructure().getTimesAccessed() ); // initialization (2) + clock over
- assertEquals( ( increment * 2 ) + 1, optimizer.getLastSourceValue() ); // initialization (2) + clock over
- assertEquals( increment + 1, optimizer.getLastValue() );
+ // initialization (2) + clock over
+ assertEquals( 3, generator.getDatabaseStructure().getTimesAccessed() );
+ assertEquals( ( increment * 2 ) + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() );
+ assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() );
s.getTransaction().commit();
s.beginTransaction();
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/sequence/BasicSequenceTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/sequence/BasicSequenceTest.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/sequence/BasicSequenceTest.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -8,6 +8,8 @@
import org.hibernate.id.enhanced.SequenceStyleGenerator;
import org.hibernate.persister.entity.EntityPersister;
+import static org.hibernate.id.IdentifierGeneratorHelper.BasicHolder;
+
/**
* {@inheritDoc}
*
@@ -41,7 +43,7 @@
long expectedId = i + 1;
assertEquals( expectedId, entities[i].getId().longValue() );
assertEquals( expectedId, generator.getDatabaseStructure().getTimesAccessed() );
- assertEquals( expectedId, generator.getOptimizer().getLastSourceValue() );
+ assertEquals( expectedId, ( (BasicHolder) generator.getOptimizer().getLastSourceValue() ).getActualLongValue() );
}
s.getTransaction().commit();
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/sequence/HiLoSequenceTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/sequence/HiLoSequenceTest.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/sequence/HiLoSequenceTest.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -9,6 +9,9 @@
import org.hibernate.id.enhanced.SequenceStyleGenerator;
import org.hibernate.persister.entity.EntityPersister;
+import static org.hibernate.id.IdentifierGeneratorHelper.BasicHolder;
+
+
/**
* {@inheritDoc}
*
@@ -42,17 +45,17 @@
entities[i] = new Entity( "" + ( i + 1 ) );
s.save( entities[i] );
assertEquals( 1, generator.getDatabaseStructure().getTimesAccessed() ); // initialization
- assertEquals( 1, optimizer.getLastSourceValue() ); // initialization
- assertEquals( i + 1, optimizer.getLastValue() );
- assertEquals( increment + 1, optimizer.getHiValue() );
+ assertEquals( 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization
+ assertEquals( i + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() );
+ assertEquals( increment + 1, ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() );
}
// now force a "clock over"
entities[ increment ] = new Entity( "" + increment );
s.save( entities[ increment ] );
assertEquals( 2, generator.getDatabaseStructure().getTimesAccessed() ); // initialization
- assertEquals( 2, optimizer.getLastSourceValue() ); // initialization
- assertEquals( increment + 1, optimizer.getLastValue() );
- assertEquals( ( increment * 2 ) + 1, optimizer.getHiValue() );
+ assertEquals( 2, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization
+ assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() );
+ assertEquals( ( increment * 2 ) + 1, ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() );
s.getTransaction().commit();
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/sequence/PooledSequenceTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/sequence/PooledSequenceTest.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/sequence/PooledSequenceTest.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -9,6 +9,8 @@
import org.hibernate.id.enhanced.SequenceStyleGenerator;
import org.hibernate.Session;
+import static org.hibernate.id.IdentifierGeneratorHelper.BasicHolder;
+
/**
* {@inheritDoc}
*
@@ -42,16 +44,16 @@
entities[i] = new Entity( "" + ( i + 1 ) );
s.save( entities[i] );
assertEquals( 2, generator.getDatabaseStructure().getTimesAccessed() ); // initialization calls seq twice
- assertEquals( increment + 1, optimizer.getLastSourceValue() ); // initialization calls seq twice
- assertEquals( i + 1, optimizer.getLastValue() );
- assertEquals( increment + 1, optimizer.getLastSourceValue() );
+ assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization calls seq twice
+ assertEquals( i + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() );
+ assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() );
}
// now force a "clock over"
entities[ increment ] = new Entity( "" + increment );
s.save( entities[ increment ] );
assertEquals( 3, generator.getDatabaseStructure().getTimesAccessed() ); // initialization (2) + clock over
- assertEquals( ( increment * 2 ) + 1, optimizer.getLastSourceValue() ); // initialization (2) + clock over
- assertEquals( increment + 1, optimizer.getLastValue() );
+ assertEquals( ( increment * 2 ) + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization (2) + clock over
+ assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() );
s.getTransaction().commit();
s.beginTransaction();
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/table/BasicTableTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/table/BasicTableTest.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/table/BasicTableTest.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -8,6 +8,8 @@
import org.hibernate.id.enhanced.TableGenerator;
import org.hibernate.Session;
+import static org.hibernate.id.IdentifierGeneratorHelper.BasicHolder;
+
/**
* {@inheritDoc}
*
@@ -41,7 +43,7 @@
long expectedId = i + 1;
assertEquals( expectedId, entities[i].getId().longValue() );
assertEquals( expectedId, generator.getTableAccessCount() );
- assertEquals( expectedId, generator.getOptimizer().getLastSourceValue() );
+ assertEquals( expectedId, ( (BasicHolder) generator.getOptimizer().getLastSourceValue() ).getActualLongValue() );
}
s.getTransaction().commit();
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/table/HiLoTableTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/table/HiLoTableTest.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/table/HiLoTableTest.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -9,6 +9,8 @@
import org.hibernate.id.enhanced.TableGenerator;
import org.hibernate.Session;
+import static org.hibernate.id.IdentifierGeneratorHelper.BasicHolder;
+
/**
* {@inheritDoc}
*
@@ -42,17 +44,17 @@
entities[i] = new Entity( "" + ( i + 1 ) );
s.save( entities[i] );
assertEquals( 1, generator.getTableAccessCount() ); // initialization
- assertEquals( 1, optimizer.getLastSourceValue() ); // initialization
- assertEquals( i + 1, optimizer.getLastValue() );
- assertEquals( increment + 1, optimizer.getHiValue() );
+ assertEquals( 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization
+ assertEquals( i + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() );
+ assertEquals( increment + 1, ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() );
}
// now force a "clock over"
entities[ increment ] = new Entity( "" + increment );
s.save( entities[ increment ] );
assertEquals( 2, generator.getTableAccessCount() ); // initialization
- assertEquals( 2, optimizer.getLastSourceValue() ); // initialization
- assertEquals( increment + 1, optimizer.getLastValue() );
- assertEquals( ( increment * 2 ) + 1, optimizer.getHiValue() );
+ assertEquals( 2, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization
+ assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() );
+ assertEquals( ( increment * 2 ) + 1, ( (BasicHolder) optimizer.getHiValue() ).getActualLongValue() );
s.getTransaction().commit();
Modified: core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/table/PooledTableTest.java
===================================================================
--- core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/table/PooledTableTest.java 2010-02-11 21:08:01 UTC (rev 18788)
+++ core/trunk/testsuite/src/test/java/org/hibernate/test/idgen/enhanced/table/PooledTableTest.java 2010-02-12 06:22:52 UTC (rev 18789)
@@ -9,6 +9,8 @@
import org.hibernate.id.enhanced.TableGenerator;
import org.hibernate.Session;
+import static org.hibernate.id.IdentifierGeneratorHelper.BasicHolder;
+
/**
* {@inheritDoc}
*
@@ -42,16 +44,16 @@
entities[i] = new Entity( "" + ( i + 1 ) );
s.save( entities[i] );
assertEquals( 2, generator.getTableAccessCount() ); // initialization calls seq twice
- assertEquals( increment + 1, optimizer.getLastSourceValue() ); // initialization calls seq twice
- assertEquals( i + 1, optimizer.getLastValue() );
- assertEquals( increment + 1, optimizer.getLastSourceValue() );
+ assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization calls seq twice
+ assertEquals( i + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() );
+ assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() );
}
// now force a "clock over"
entities[ increment ] = new Entity( "" + increment );
s.save( entities[ increment ] );
assertEquals( 3, generator.getTableAccessCount() ); // initialization (2) + clock over
- assertEquals( ( increment * 2 ) + 1, optimizer.getLastSourceValue() ); // initialization (2) + clock over
- assertEquals( increment + 1, optimizer.getLastValue() );
+ assertEquals( ( increment * 2 ) + 1, ( (BasicHolder) optimizer.getLastSourceValue() ).getActualLongValue() ); // initialization (2) + clock over
+ assertEquals( increment + 1, ( (BasicHolder) optimizer.getLastValue() ).getActualLongValue() );
s.getTransaction().commit();
s.beginTransaction();
14 years, 3 months
Hibernate SVN: r18788 - in jpamodelgen/trunk/src: main/java/org/hibernate/jpamodelgen/util and 4 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-02-11 16:08:01 -0500 (Thu, 11 Feb 2010)
New Revision: 18788
Added:
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaMap.java
jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/Hostel.java
jpamodelgen/trunk/src/test/resources/org/hibernate/jpamodelgen/test/elementcollection/
jpamodelgen/trunk/src/test/resources/org/hibernate/jpamodelgen/test/elementcollection/hostel.xml
Modified:
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationEmbeddable.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaEntity.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaMap.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/util/TypeUtils.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaAttribute.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java
jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/Cleaner.java
jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/ElementCollectionTest.java
jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/Hotel.java
Log:
METAGEN-22 - Some cleanup and optimisatons prior adding new functionality
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationEmbeddable.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationEmbeddable.java 2010-02-11 19:37:09 UTC (rev 18787)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationEmbeddable.java 2010-02-11 21:08:01 UTC (rev 18788)
@@ -44,7 +44,7 @@
public List<MetaAttribute> getMembers() {
if ( !initialized ) {
- context.logMessage( Diagnostic.Kind.OTHER, "Entity " + getQualifiedName() + "was lazily initialised." );
+ context.logMessage( Diagnostic.Kind.OTHER, "Entity " + getQualifiedName() + " was lazily initialised." );
init();
initialized = true;
}
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaEntity.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaEntity.java 2010-02-11 19:37:09 UTC (rev 18787)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaEntity.java 2010-02-11 21:08:01 UTC (rev 18788)
@@ -306,7 +306,7 @@
keyType = typeMirror.toString();
}
else {
- keyType = getKeyType( declaredType );
+ keyType = TypeUtils.getKeyType( declaredType, context );
}
return new AnnotationMetaMap(
parent,
@@ -341,14 +341,6 @@
}
}
- private String getKeyType(DeclaredType t) {
- List<? extends TypeMirror> typeArguments = t.getTypeArguments();
- if ( typeArguments.size() == 0 ) {
- context.logMessage( Diagnostic.Kind.ERROR, "Entity: " + getQualifiedName() );
- }
- return TypeUtils.extractClosestRealTypeAsString( typeArguments.get( 0 ), context );
- }
-
/**
* @param annotations list of annotation mirrors.
*
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaMap.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaMap.java 2010-02-11 19:37:09 UTC (rev 18787)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/annotation/AnnotationMetaMap.java 2010-02-11 21:08:01 UTC (rev 18788)
@@ -20,7 +20,6 @@
import javax.lang.model.element.Element;
/**
- *
* @author Max Andersen
* @author Hardy Ferentschik
* @author Emmanuel Bernard
@@ -30,13 +29,13 @@
private final String keyType;
public AnnotationMetaMap(AnnotationMetaEntity parent, Element element, String collectionType,
- String keyType, String elementType) {
- super(parent, element, collectionType, elementType);
- this.keyType = keyType;
+ String keyType, String elementType) {
+ super( parent, element, collectionType, elementType );
+ this.keyType = keyType;
}
public String getDeclarationString() {
- return "public static volatile " + parent.importType(getMetaType()) + "<" + parent.importType(parent.getQualifiedName()) + ", " + parent.importType(keyType) + ", " + parent.importType(getTypeDeclaration()) + "> " + getPropertyName() + ";";
+ return "public static volatile " + parent.importType( getMetaType() ) + "<" + parent.importType( parent.getQualifiedName() ) + ", " + parent
+ .importType( keyType ) + ", " + parent.importType( getTypeDeclaration() ) + "> " + getPropertyName() + ";";
}
-
}
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/util/TypeUtils.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/util/TypeUtils.java 2010-02-11 19:37:09 UTC (rev 18787)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/util/TypeUtils.java 2010-02-11 21:08:01 UTC (rev 18788)
@@ -380,8 +380,15 @@
}
}
+ public static String getKeyType(DeclaredType t, Context context) {
+ List<? extends TypeMirror> typeArguments = t.getTypeArguments();
+ if ( typeArguments.size() == 0 ) {
+ context.logMessage( Diagnostic.Kind.ERROR, "Unable to determine type argument for " + t );
+ }
+ return extractClosestRealTypeAsString( typeArguments.get( 0 ), context );
+ }
+
static class EmbeddedAttributeVisitor extends SimpleTypeVisitor6<String, Element> {
-
private Context context;
EmbeddedAttributeVisitor(Context context) {
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaAttribute.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaAttribute.java 2010-02-11 19:37:09 UTC (rev 18787)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaAttribute.java 2010-02-11 21:08:01 UTC (rev 18788)
@@ -25,33 +25,34 @@
*/
public abstract class XmlMetaAttribute implements MetaAttribute {
- private XmlMetaEntity parentEntity;
+ protected final XmlMetaEntity parentEntity;
+ private final String propertyName;
+ private final String type;
- private String propertyName;
+ XmlMetaAttribute(XmlMetaEntity parent, String propertyName, String type) {
+ this.parentEntity = parent;
+ this.propertyName = propertyName;
+ this.type = type;
+ }
- private String type;
-
- XmlMetaAttribute(XmlMetaEntity parent, String propertyName, String type) {
- this.parentEntity = parent;
- this.propertyName = propertyName;
- this.type = type;
- }
-
@Override
- public String getDeclarationString() {
- return "public static volatile " + parentEntity.importType(getMetaType()) + "<" + parentEntity.importType(parentEntity.getQualifiedName()) + ", " + parentEntity.importType(getTypeDeclaration()) + "> " + getPropertyName() + ";";
- }
+ public String getDeclarationString() {
+ return "public static volatile " + parentEntity.importType( getMetaType() )
+ + "<" + parentEntity.importType( parentEntity.getQualifiedName() )
+ + ", " + parentEntity.importType( getTypeDeclaration() )
+ + "> " + getPropertyName() + ";";
+ }
- public String getPropertyName() {
- return propertyName;
- }
+ public String getPropertyName() {
+ return propertyName;
+ }
- public String getTypeDeclaration() {
+ public String getTypeDeclaration() {
return type;
}
- @Override
- abstract public String getMetaType();
+ @Override
+ abstract public String getMetaType();
@Override
public String toString() {
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java 2010-02-11 19:37:09 UTC (rev 18787)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java 2010-02-11 21:08:01 UTC (rev 18788)
@@ -48,6 +48,7 @@
import org.hibernate.jpamodelgen.xml.jaxb.Id;
import org.hibernate.jpamodelgen.xml.jaxb.ManyToMany;
import org.hibernate.jpamodelgen.xml.jaxb.ManyToOne;
+import org.hibernate.jpamodelgen.xml.jaxb.MapKeyClass;
import org.hibernate.jpamodelgen.xml.jaxb.MappedSuperclass;
import org.hibernate.jpamodelgen.xml.jaxb.OneToMany;
import org.hibernate.jpamodelgen.xml.jaxb.OneToOne;
@@ -182,8 +183,8 @@
return context.isPersistenceUnitCompletelyXmlConfigured() || Boolean.TRUE.equals( metadataComplete );
}
- private String[] getCollectionType(String propertyName, String explicitTargetEntity, ElementKind expectedElementKind) {
- String types[] = new String[2];
+ private String[] getCollectionTypes(String propertyName, String explicitTargetEntity, String explicitMapKeyClass, ElementKind expectedElementKind) {
+ String types[] = new String[3];
for ( Element elem : element.getEnclosedElements() ) {
if ( expectedElementKind.equals( elem.getKind() ) ) {
continue;
@@ -194,25 +195,45 @@
}
DeclaredType type = ( ( DeclaredType ) elem.asType() );
- List<? extends TypeMirror> typeArguments = type.getTypeArguments();
-
- if ( typeArguments.size() == 0 && explicitTargetEntity == null ) {
- throw new MetaModelGenerationException( "Unable to determine target entity type for " + clazzName + "." + propertyName + "." );
+ determineTargetType( type, propertyName, explicitTargetEntity, types );
+ determineCollectionType( type, types );
+ if ( types[1].equals( "javax.persistence.metamodel.MapAttribute" ) ) {
+ determineMapType( type, explicitMapKeyClass, types );
}
-
- if ( explicitTargetEntity == null ) {
- types[0] = TypeUtils.extractClosestRealTypeAsString( typeArguments.get( 0 ), context );
- }
- else {
- types[0] = explicitTargetEntity;
- }
- types[1] = COLLECTIONS.get( type.asElement().toString() );
return types;
}
return null;
}
+ private void determineMapType(DeclaredType type, String explicitMapKeyClass, String[] types) {
+ if ( explicitMapKeyClass != null ) {
+ types[2] = explicitMapKeyClass;
+ }
+ else {
+ types[2] = TypeUtils.getKeyType( type, context );
+ }
+ }
+
+ private void determineCollectionType(DeclaredType type, String[] types) {
+ types[1] = COLLECTIONS.get( type.asElement().toString() );
+ }
+
+ private void determineTargetType(DeclaredType type, String propertyName, String explicitTargetEntity, String[] types) {
+ List<? extends TypeMirror> typeArguments = type.getTypeArguments();
+
+ if ( typeArguments.size() == 0 && explicitTargetEntity == null ) {
+ throw new MetaModelGenerationException( "Unable to determine target entity type for " + clazzName + "." + propertyName + "." );
+ }
+
+ if ( explicitTargetEntity == null ) {
+ types[0] = TypeUtils.extractClosestRealTypeAsString( typeArguments.get( 0 ), context );
+ }
+ else {
+ types[0] = explicitTargetEntity;
+ }
+ }
+
/**
* Returns the entity type for a property.
*
@@ -302,157 +323,186 @@
}
for ( Basic basic : attributes.getBasic() ) {
- ElementKind elementKind = getElementKind( basic.getAccess() );
- String type = getType( basic.getName(), null, elementKind );
- if ( type != null ) {
- attribute = new XmlMetaSingleAttribute( this, basic.getName(), type );
- members.add( attribute );
- }
+ parseBasic( basic );
}
for ( ManyToOne manyToOne : attributes.getManyToOne() ) {
- ElementKind elementKind = getElementKind( manyToOne.getAccess() );
- String type = getType( manyToOne.getName(), manyToOne.getTargetEntity(), elementKind );
- if ( type != null ) {
- attribute = new XmlMetaSingleAttribute( this, manyToOne.getName(), type );
- members.add( attribute );
- }
+ parseManyToOne( manyToOne );
}
for ( OneToOne oneToOne : attributes.getOneToOne() ) {
- ElementKind elementKind = getElementKind( oneToOne.getAccess() );
- String type = getType( oneToOne.getName(), oneToOne.getTargetEntity(), elementKind );
- if ( type != null ) {
- attribute = new XmlMetaSingleAttribute( this, oneToOne.getName(), type );
- members.add( attribute );
- }
+ parseOneToOne( oneToOne );
}
- XmlMetaCollection metaCollection;
- String[] types;
for ( ManyToMany manyToMany : attributes.getManyToMany() ) {
- ElementKind elementKind = getElementKind( manyToMany.getAccess() );
- try {
- types = getCollectionType( manyToMany.getName(), manyToMany.getTargetEntity(), elementKind );
- }
- catch ( MetaModelGenerationException e ) {
- logMetaModelException( manyToMany.getName(), e );
+ if ( parseManyToMany( manyToMany ) ) {
break;
}
- if ( types != null ) {
- metaCollection = new XmlMetaCollection( this, manyToMany.getName(), types[0], types[1] );
- members.add( metaCollection );
- }
}
for ( OneToMany oneToMany : attributes.getOneToMany() ) {
- ElementKind elementKind = getElementKind( oneToMany.getAccess() );
- try {
- types = getCollectionType( oneToMany.getName(), oneToMany.getTargetEntity(), elementKind );
- }
- catch ( MetaModelGenerationException e ) {
- logMetaModelException( oneToMany.getName(), e );
+ if ( parseOneToMany( oneToMany ) ) {
break;
}
- if ( types != null ) {
- metaCollection = new XmlMetaCollection( this, oneToMany.getName(), types[0], types[1] );
- members.add( metaCollection );
- }
}
for ( ElementCollection collection : attributes.getElementCollection() ) {
- ElementKind elementKind = getElementKind( collection.getAccess() );
- try {
- types = getCollectionType( collection.getName(), collection.getTargetClass(), elementKind );
- }
- catch ( MetaModelGenerationException e ) {
- logMetaModelException( collection.getName(), e );
+ if ( parseElementCollection( collection ) ) {
break;
}
- if ( types != null ) {
- metaCollection = new XmlMetaCollection( this, collection.getName(), types[0], types[1] );
- members.add( metaCollection );
- }
}
}
private void parseEmbeddableAttributes(EmbeddableAttributes attributes) {
- XmlMetaSingleAttribute attribute;
for ( Basic basic : attributes.getBasic() ) {
- ElementKind elementKind = getElementKind( basic.getAccess() );
- String type = getType( basic.getName(), null, elementKind );
- if ( type != null ) {
- attribute = new XmlMetaSingleAttribute( this, basic.getName(), type );
- members.add( attribute );
- }
+ parseBasic( basic );
}
for ( ManyToOne manyToOne : attributes.getManyToOne() ) {
- ElementKind elementKind = getElementKind( manyToOne.getAccess() );
- String type = getType( manyToOne.getName(), manyToOne.getTargetEntity(), elementKind );
- if ( type != null ) {
- attribute = new XmlMetaSingleAttribute( this, manyToOne.getName(), type );
- members.add( attribute );
- }
+ parseManyToOne( manyToOne );
}
for ( OneToOne oneToOne : attributes.getOneToOne() ) {
- ElementKind elementKind = getElementKind( oneToOne.getAccess() );
- String type = getType( oneToOne.getName(), oneToOne.getTargetEntity(), elementKind );
- if ( type != null ) {
- attribute = new XmlMetaSingleAttribute( this, oneToOne.getName(), type );
- members.add( attribute );
- }
+ parseOneToOne( oneToOne );
}
- XmlMetaCollection metaCollection;
- String[] types;
for ( ManyToMany manyToMany : attributes.getManyToMany() ) {
- ElementKind elementKind = getElementKind( manyToMany.getAccess() );
- try {
- types = getCollectionType( manyToMany.getName(), manyToMany.getTargetEntity(), elementKind );
- }
- catch ( MetaModelGenerationException e ) {
- logMetaModelException( manyToMany.getName(), e );
+ if ( parseManyToMany( manyToMany ) ) {
break;
}
- if ( types != null ) {
- metaCollection = new XmlMetaCollection( this, manyToMany.getName(), types[0], types[1] );
- members.add( metaCollection );
- }
}
for ( OneToMany oneToMany : attributes.getOneToMany() ) {
- ElementKind elementKind = getElementKind( oneToMany.getAccess() );
- try {
- types = getCollectionType( oneToMany.getName(), oneToMany.getTargetEntity(), elementKind );
- }
- catch ( MetaModelGenerationException e ) {
- logMetaModelException( oneToMany.getName(), e );
+ if ( parseOneToMany( oneToMany ) ) {
break;
}
- if ( types != null ) {
- metaCollection = new XmlMetaCollection( this, oneToMany.getName(), types[0], types[1] );
- members.add( metaCollection );
- }
}
for ( ElementCollection collection : attributes.getElementCollection() ) {
- ElementKind elementKind = getElementKind( collection.getAccess() );
- try {
- types = getCollectionType( collection.getName(), collection.getTargetClass(), elementKind );
- }
- catch ( MetaModelGenerationException e ) {
- logMetaModelException( collection.getName(), e );
+ if ( parseElementCollection( collection ) ) {
break;
}
- if ( types != null ) {
+ }
+ }
+
+ private boolean parseElementCollection(ElementCollection collection) {
+ String[] types;
+ XmlMetaCollection metaCollection;
+ ElementKind elementKind = getElementKind( collection.getAccess() );
+ MapKeyClass mapKeyClass = collection.getMapKeyClass();
+ String explicitMapKey = null;
+ if ( mapKeyClass != null ) {
+ explicitMapKey = mapKeyClass.getClazz();
+ }
+ try {
+ types = getCollectionTypes(
+ collection.getName(), collection.getTargetClass(), explicitMapKey, elementKind
+ );
+ }
+ catch ( MetaModelGenerationException e ) {
+ logMetaModelException( collection.getName(), e );
+ return true;
+ }
+ if ( types != null ) {
+ if ( types[2] == null ) {
metaCollection = new XmlMetaCollection( this, collection.getName(), types[0], types[1] );
- members.add( metaCollection );
}
+ else {
+ metaCollection = new XmlMetaMap( this, collection.getName(), types[0], types[1], types[2] );
+ }
+ members.add( metaCollection );
}
+ return false;
}
+ private boolean parseOneToMany(OneToMany oneToMany) {
+ String[] types;
+ XmlMetaCollection metaCollection;
+ ElementKind elementKind = getElementKind( oneToMany.getAccess() );
+ MapKeyClass mapKeyClass = oneToMany.getMapKeyClass();
+ String explicitMapKey = null;
+ if ( mapKeyClass != null ) {
+ explicitMapKey = mapKeyClass.getClazz();
+ }
+ try {
+ types = getCollectionTypes( oneToMany.getName(), oneToMany.getTargetEntity(), explicitMapKey, elementKind );
+ }
+ catch ( MetaModelGenerationException e ) {
+ logMetaModelException( oneToMany.getName(), e );
+ return true;
+ }
+ if ( types != null ) {
+ if ( types[2] == null ) {
+ metaCollection = new XmlMetaCollection( this, oneToMany.getName(), types[0], types[1] );
+ }
+ else {
+ metaCollection = new XmlMetaMap( this, oneToMany.getName(), types[0], types[1], types[2] );
+ }
+ members.add( metaCollection );
+ }
+ return false;
+ }
+
+ private boolean parseManyToMany(ManyToMany manyToMany) {
+ String[] types;
+ XmlMetaCollection metaCollection;
+ ElementKind elementKind = getElementKind( manyToMany.getAccess() );
+ MapKeyClass mapKeyClass = manyToMany.getMapKeyClass();
+ String explicitMapKey = null;
+ if ( mapKeyClass != null ) {
+ explicitMapKey = mapKeyClass.getClazz();
+ }
+ try {
+ types = getCollectionTypes(
+ manyToMany.getName(), manyToMany.getTargetEntity(), explicitMapKey, elementKind
+ );
+ }
+ catch ( MetaModelGenerationException e ) {
+ logMetaModelException( manyToMany.getName(), e );
+ return true;
+ }
+ if ( types != null ) {
+ if ( types[2] == null ) {
+ metaCollection = new XmlMetaCollection( this, manyToMany.getName(), types[0], types[1] );
+ }
+ else {
+ metaCollection = new XmlMetaMap( this, manyToMany.getName(), types[0], types[1], types[2] );
+ }
+ members.add( metaCollection );
+ }
+ return false;
+ }
+
+ private void parseOneToOne(OneToOne oneToOne) {
+ XmlMetaSingleAttribute attribute;
+ ElementKind elementKind = getElementKind( oneToOne.getAccess() );
+ String type = getType( oneToOne.getName(), oneToOne.getTargetEntity(), elementKind );
+ if ( type != null ) {
+ attribute = new XmlMetaSingleAttribute( this, oneToOne.getName(), type );
+ members.add( attribute );
+ }
+ }
+
+ private void parseManyToOne(ManyToOne manyToOne) {
+ XmlMetaSingleAttribute attribute;
+ ElementKind elementKind = getElementKind( manyToOne.getAccess() );
+ String type = getType( manyToOne.getName(), manyToOne.getTargetEntity(), elementKind );
+ if ( type != null ) {
+ attribute = new XmlMetaSingleAttribute( this, manyToOne.getName(), type );
+ members.add( attribute );
+ }
+ }
+
+ private void parseBasic(Basic basic) {
+ XmlMetaSingleAttribute attribute;
+ ElementKind elementKind = getElementKind( basic.getAccess() );
+ String type = getType( basic.getName(), null, elementKind );
+ if ( type != null ) {
+ attribute = new XmlMetaSingleAttribute( this, basic.getName(), type );
+ members.add( attribute );
+ }
+ }
+
private void logMetaModelException(String name, MetaModelGenerationException e) {
StringBuilder builder = new StringBuilder();
builder.append( "Error processing xml for " );
Copied: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaMap.java (from rev 18690, jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaCollection.java)
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaMap.java (rev 0)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaMap.java 2010-02-11 21:08:01 UTC (rev 18788)
@@ -0,0 +1,40 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* 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.hibernate.jpamodelgen.xml;
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class XmlMetaMap extends XmlMetaCollection {
+
+ private final String keyType;
+
+ public XmlMetaMap(XmlMetaEntity parent, String propertyName, String type, String collectionType, String keyType) {
+ super( parent, propertyName, type, collectionType );
+ this.keyType = keyType;
+ }
+
+ public String getDeclarationString() {
+ return "public static volatile "
+ + parentEntity.importType( getMetaType() )
+ + "<" + parentEntity.importType( parentEntity.getQualifiedName() )
+ + ", " + parentEntity.importType( keyType ) + ", "
+ + parentEntity.importType( getTypeDeclaration() )
+ + "> " + getPropertyName() + ";";
+ }
+}
\ No newline at end of file
Modified: jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/Cleaner.java
===================================================================
--- jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/Cleaner.java 2010-02-11 19:37:09 UTC (rev 18787)
+++ jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/Cleaner.java 2010-02-11 21:08:01 UTC (rev 18788)
@@ -18,6 +18,7 @@
package org.hibernate.jpamodelgen.test.elementcollection;
import javax.persistence.Entity;
+import javax.persistence.Id;
/**
* @author Hardy Ferentschik
@@ -28,6 +29,7 @@
private String name;
+ @Id
public int getId() {
return id;
}
Modified: jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/ElementCollectionTest.java
===================================================================
--- jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/ElementCollectionTest.java 2010-02-11 19:37:09 UTC (rev 18787)
+++ jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/ElementCollectionTest.java 2010-02-11 21:08:01 UTC (rev 18788)
@@ -17,9 +17,14 @@
*/
package org.hibernate.jpamodelgen.test.elementcollection;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
import org.testng.annotations.Test;
import org.hibernate.jpamodelgen.test.util.CompilationTest;
+import org.hibernate.jpamodelgen.test.util.TestUtil;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMapAttributesInMetaModelFor;
import static org.hibernate.jpamodelgen.test.util.TestUtil.assertMetamodelClassGeneratedFor;
@@ -55,8 +60,30 @@
);
}
+ /**
+ * METAGEN-22
+ */
+ @Test
+ public void testMapKeyClassXmlConfigured() {
+ assertMetamodelClassGeneratedFor( Hostel.class );
+ assertMapAttributesInMetaModelFor(
+ Hostel.class, "roomsByName", String.class, Room.class, "Wrong type in map attribute."
+ );
+
+ assertMapAttributesInMetaModelFor(
+ Hostel.class, "cleaners", Room.class, Cleaner.class, "Wrong type in map attribute."
+ );
+ }
+
@Override
protected String getPackageNameOfTestSources() {
return ElementCollectionTest.class.getPackage().getName();
}
+
+ @Override
+ protected Collection<String> getOrmFiles() {
+ List<String> ormFiles = new ArrayList<String>();
+ ormFiles.add( TestUtil.fcnToPath( ElementCollectionTest.class.getPackage().getName() ) + "/hostel.xml" );
+ return ormFiles;
+ }
}
\ No newline at end of file
Copied: jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/Hostel.java (from rev 18677, jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/Hotel.java)
===================================================================
--- jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/Hostel.java (rev 0)
+++ jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/Hostel.java 2010-02-11 21:08:01 UTC (rev 18788)
@@ -0,0 +1,52 @@
+// $Id$
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* 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.hibernate.jpamodelgen.test.elementcollection;
+
+import java.util.Map;
+import javax.persistence.ElementCollection;
+import javax.persistence.Entity;
+import javax.persistence.MapKeyClass;
+import javax.persistence.OneToMany;
+
+
+/**
+ * @author Hardy Ferentschik
+ */
+public class Hostel {
+ private Map roomsByName;
+
+ private Map cleaners;
+
+ @ElementCollection(targetClass = Room.class)
+ @MapKeyClass(String.class)
+ public Map getRoomsByName() {
+ return roomsByName;
+ }
+
+ public void setRoomsByName(Map roomsByName) {
+ this.roomsByName = roomsByName;
+ }
+
+ public Map getCleaners() {
+ return cleaners;
+ }
+
+ public void setCleaners(Map cleaners) {
+ this.cleaners = cleaners;
+ }
+}
\ No newline at end of file
Modified: jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/Hotel.java
===================================================================
--- jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/Hotel.java 2010-02-11 19:37:09 UTC (rev 18787)
+++ jpamodelgen/trunk/src/test/java/org/hibernate/jpamodelgen/test/elementcollection/Hotel.java 2010-02-11 21:08:01 UTC (rev 18788)
@@ -20,6 +20,8 @@
import java.util.Map;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
import javax.persistence.MapKeyClass;
import javax.persistence.OneToMany;
@@ -29,10 +31,20 @@
*/
@Entity
public class Hotel {
+ private int id;
private Map roomsByName;
-
private Map cleaners;
+ @Id
+ @GeneratedValue
+ public int getId() {
+ return id;
+ }
+
+ public void setId(int id) {
+ this.id = id;
+ }
+
@ElementCollection(targetClass = Room.class)
@MapKeyClass(String.class)
public Map getRoomsByName() {
Copied: jpamodelgen/trunk/src/test/resources/org/hibernate/jpamodelgen/test/elementcollection/hostel.xml (from rev 18734, jpamodelgen/trunk/src/test/resources/org/hibernate/jpamodelgen/test/mixedmode/car.xml)
===================================================================
--- jpamodelgen/trunk/src/test/resources/org/hibernate/jpamodelgen/test/elementcollection/hostel.xml (rev 0)
+++ jpamodelgen/trunk/src/test/resources/org/hibernate/jpamodelgen/test/elementcollection/hostel.xml 2010-02-11 21:08:01 UTC (rev 18788)
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
+ version="2.0"
+ >
+ <entity class="org.hibernate.jpamodelgen.test.elementcollection.Hostel">
+ <attributes>
+ <one-to-many name="cleaners" target-entity="org.hibernate.jpamodelgen.test.elementcollection.Cleaner">
+ <map-key-class class="org.hibernate.jpamodelgen.test.elementcollection.Room"/>
+ </one-to-many>
+ <element-collection name="roomsByName"
+ target-class="org.hibernate.jpamodelgen.test.elementcollection.Room">
+ <map-key-class class="java.lang.String"/>
+ </element-collection>
+ </attributes>
+ </entity>
+</entity-mappings>
+
14 years, 3 months
Hibernate SVN: r18787 - in jpamodelgen/trunk/src: main/java/org/hibernate/jpamodelgen/util and 2 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-02-11 14:37:09 -0500 (Thu, 11 Feb 2010)
New Revision: 18787
Removed:
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaMappedSuperClass.java
Modified:
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ClassWriter.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/Context.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/JPAMetaModelEntityProcessor.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/util/Constants.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java
jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlParser.java
jpamodelgen/trunk/src/test/resources/org/hibernate/jpamodelgen/test/xmlmapped/building.xml
Log:
METAGEN-22 - Some cleanup and optimisatons prior adding new functionality
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ClassWriter.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ClassWriter.java 2010-02-11 19:16:42 UTC (rev 18786)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/ClassWriter.java 2010-02-11 19:37:09 UTC (rev 18787)
@@ -116,7 +116,7 @@
final Element superClassElement = ( ( DeclaredType ) superClass ).asElement();
String superClassName = ( ( TypeElement ) superClassElement ).getQualifiedName().toString();
if ( context.containsMetaEntity( superClassName )
- || context.containsMetaSuperclassOrEmbeddable( superClassName ) ) {
+ || context.containsMetaEmbeddable( superClassName ) ) {
pw.print( " extends " + superClassName + "_" );
}
}
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/Context.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/Context.java 2010-02-11 19:16:42 UTC (rev 18786)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/Context.java 2010-02-11 19:37:09 UTC (rev 18787)
@@ -31,6 +31,7 @@
import javax.tools.Diagnostic;
import org.hibernate.jpamodelgen.model.MetaEntity;
+import org.hibernate.jpamodelgen.util.Constants;
/**
* @author Max Andersen
@@ -38,10 +39,19 @@
* @author Emmanuel Bernard
*/
public class Context {
- private static final String PATH_SEPARATOR = System.getProperty( "file.separator" );
private static final String DEFAULT_PERSISTENCE_XML_LOCATION = "/META-INF/persistence.xml";
+
+ /**
+ * Used for keeping track of parsed entities and mapped super classes (xml + annotations).
+ */
private final Map<String, MetaEntity> metaEntities = new HashMap<String, MetaEntity>();
- private final Map<String, MetaEntity> metaSuperclassAndEmbeddable = new HashMap<String, MetaEntity>();
+
+ /**
+ * Used for keeping track of parsed embeddable entities. These entities have to be kept separate since
+ * they are lazily initialized.
+ */
+ private final Map<String, MetaEntity> metaEmbeddables = new HashMap<String, MetaEntity>();
+
private final Map<String, AccessTypeInformation> accessTypeInformation = new HashMap<String, AccessTypeInformation>();
private final ProcessingEnvironment pe;
@@ -57,8 +67,8 @@
if ( pe.getOptions().get( JPAMetaModelEntityProcessor.PERSISTENCE_XML_OPTION ) != null ) {
String tmp = pe.getOptions().get( JPAMetaModelEntityProcessor.PERSISTENCE_XML_OPTION );
- if ( !tmp.startsWith( PATH_SEPARATOR ) ) {
- tmp = PATH_SEPARATOR + tmp;
+ if ( !tmp.startsWith( Constants.PATH_SEPARATOR ) ) {
+ tmp = Constants.PATH_SEPARATOR + tmp;
}
persistenceXmlLocation = tmp;
}
@@ -70,8 +80,8 @@
String tmp = pe.getOptions().get( JPAMetaModelEntityProcessor.ORM_XML_OPTION );
ormXmlFiles = new ArrayList<String>();
for ( String ormFile : tmp.split( "," ) ) {
- if ( !ormFile.startsWith( PATH_SEPARATOR ) ) {
- ormFile = PATH_SEPARATOR + ormFile;
+ if ( !ormFile.startsWith( Constants.PATH_SEPARATOR ) ) {
+ ormFile = Constants.PATH_SEPARATOR + ormFile;
}
ormXmlFiles.add( ormFile );
}
@@ -81,7 +91,6 @@
}
logDebug = Boolean.parseBoolean( pe.getOptions().get( JPAMetaModelEntityProcessor.DEBUG_OPTION ) );
-
}
public ProcessingEnvironment getProcessingEnvironment() {
@@ -120,20 +129,20 @@
metaEntities.put( fcqn, metaEntity );
}
- public boolean containsMetaSuperclassOrEmbeddable(String fqcn) {
- return metaSuperclassAndEmbeddable.containsKey( fqcn );
+ public boolean containsMetaEmbeddable(String fqcn) {
+ return metaEmbeddables.containsKey( fqcn );
}
- public MetaEntity getMetaSuperclassOrEmbeddable(String fqcn) {
- return metaSuperclassAndEmbeddable.get( fqcn );
+ public MetaEntity getMetaEmbeddable(String fqcn) {
+ return metaEmbeddables.get( fqcn );
}
- public void addMetaSuperclassOrEmbeddable(String fcqn, MetaEntity metaEntity) {
- metaSuperclassAndEmbeddable.put( fcqn, metaEntity );
+ public void addMetaEmbeddable(String fqcn, MetaEntity metaEntity) {
+ metaEmbeddables.put( fqcn, metaEntity );
}
- public Collection<MetaEntity> getMetaSuperclassOrEmbeddable() {
- return metaSuperclassAndEmbeddable.values();
+ public Collection<MetaEntity> getMetaEmbeddables() {
+ return metaEmbeddables.values();
}
public void addAccessTypeInformation(String fqcn, AccessTypeInformation info) {
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/JPAMetaModelEntityProcessor.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/JPAMetaModelEntityProcessor.java 2010-02-11 19:16:42 UTC (rev 18786)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/JPAMetaModelEntityProcessor.java 2010-02-11 19:37:09 UTC (rev 18787)
@@ -128,7 +128,7 @@
// we cannot process the delayed entities in any order. There might be dependencies between them.
// we need to process the top level entities first
// TODO make sure that we don't run into circular dependencies here
- Collection<MetaEntity> toProcessEntities = context.getMetaSuperclassOrEmbeddable();
+ Collection<MetaEntity> toProcessEntities = context.getMetaEmbeddables();
while ( !toProcessEntities.isEmpty() ) {
Set<MetaEntity> processedEntities = new HashSet<MetaEntity>();
for ( MetaEntity entity : toProcessEntities ) {
@@ -218,7 +218,7 @@
}
else if ( TypeUtils.isAnnotationMirrorOfType( mirror, MappedSuperclass.class )
|| TypeUtils.isAnnotationMirrorOfType( mirror, Embeddable.class ) ) {
- alreadyExistingMetaEntity = context.getMetaSuperclassOrEmbeddable( fqn );
+ alreadyExistingMetaEntity = context.getMetaEmbeddable( fqn );
}
return alreadyExistingMetaEntity;
}
@@ -228,10 +228,10 @@
context.addMetaEntity( metaEntity.getQualifiedName(), metaEntity );
}
else if ( TypeUtils.isAnnotationMirrorOfType( mirror, MappedSuperclass.class ) ) {
- context.addMetaSuperclassOrEmbeddable( metaEntity.getQualifiedName(), metaEntity );
+ context.addMetaEntity( metaEntity.getQualifiedName(), metaEntity );
}
else if ( TypeUtils.isAnnotationMirrorOfType( mirror, Embeddable.class ) ) {
- context.addMetaSuperclassOrEmbeddable( metaEntity.getQualifiedName(), metaEntity );
+ context.addMetaEmbeddable( metaEntity.getQualifiedName(), metaEntity );
}
}
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/util/Constants.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/util/Constants.java 2010-02-11 19:16:42 UTC (rev 18786)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/util/Constants.java 2010-02-11 19:37:09 UTC (rev 18787)
@@ -63,7 +63,10 @@
BASIC_ARRAY_TYPES.add( "java.lang.Byte" );
}
- private Constants(){}
+ public static final String PATH_SEPARATOR = "/";
+
+ private Constants() {
+ }
}
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java 2010-02-11 19:16:42 UTC (rev 18786)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java 2010-02-11 19:37:09 UTC (rev 18787)
@@ -90,6 +90,8 @@
this( mappedSuperclass.getClazz(), packageName, element, context, mappedSuperclass.isMetadataComplete() );
this.attributes = mappedSuperclass.getAttributes();
this.embeddableAttributes = null;
+ // entities can be directly initialised
+ init();
}
protected XmlMetaEntity(Embeddable embeddable, String packageName, TypeElement element, Context context) {
Deleted: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaMappedSuperClass.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaMappedSuperClass.java 2010-02-11 19:16:42 UTC (rev 18786)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaMappedSuperClass.java 2010-02-11 19:37:09 UTC (rev 18787)
@@ -1,74 +0,0 @@
-// $Id$
-/*
-* JBoss, Home of Professional Open Source
-* Copyright 2008, Red Hat Middleware LLC, and individual contributors
-* by the @authors tag. See the copyright.txt in the distribution for a
-* full listing of individual contributors.
-*
-* 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.hibernate.jpamodelgen.xml;
-
-import java.util.List;
-import javax.lang.model.element.ElementKind;
-import javax.lang.model.element.TypeElement;
-import javax.tools.Diagnostic;
-
-import org.hibernate.jpamodelgen.Context;
-import org.hibernate.jpamodelgen.MetaModelGenerationException;
-import org.hibernate.jpamodelgen.model.MetaAttribute;
-import org.hibernate.jpamodelgen.xml.jaxb.Basic;
-import org.hibernate.jpamodelgen.xml.jaxb.ElementCollection;
-import org.hibernate.jpamodelgen.xml.jaxb.EmbeddableAttributes;
-import org.hibernate.jpamodelgen.xml.jaxb.ManyToMany;
-import org.hibernate.jpamodelgen.xml.jaxb.ManyToOne;
-import org.hibernate.jpamodelgen.xml.jaxb.MappedSuperclass;
-import org.hibernate.jpamodelgen.xml.jaxb.OneToMany;
-import org.hibernate.jpamodelgen.xml.jaxb.OneToOne;
-
-/**
- * @author Hardy Ferentschik
- */
-public class XmlMetaMappedSuperClass extends XmlMetaEntity {
- private boolean initialized;
-
- public XmlMetaMappedSuperClass(MappedSuperclass mappedSuperclass, String packageName, TypeElement element, Context context) {
- super( mappedSuperclass, packageName, element, context );
- }
-
- public List<MetaAttribute> getMembers() {
- if ( !initialized ) {
- context.logMessage( Diagnostic.Kind.OTHER, "Entity " + getQualifiedName() + "was lazily initialised." );
- init();
- initialized = true;
- }
- return members;
- }
-
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder();
- sb.append( "XmlMetaEntity" );
- sb.append( "{accessTypeInfo=" ).append( accessTypeInfo );
- sb.append( ", clazzName='" ).append( clazzName ).append( '\'' );
- sb.append( ", members=" );
- if ( initialized ) {
- sb.append( members );
- }
- else {
- sb.append( "[un-initalized]" );
- }
- sb.append( ", isMetaComplete=" ).append( isMetaComplete );
- sb.append( '}' );
- return sb.toString();
- }
-}
\ No newline at end of file
Modified: jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlParser.java
===================================================================
--- jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlParser.java 2010-02-11 19:16:42 UTC (rev 18786)
+++ jpamodelgen/trunk/src/main/java/org/hibernate/jpamodelgen/xml/XmlParser.java 2010-02-11 19:37:09 UTC (rev 18787)
@@ -39,6 +39,7 @@
import org.hibernate.jpamodelgen.AccessTypeInformation;
import org.hibernate.jpamodelgen.Context;
+import org.hibernate.jpamodelgen.util.Constants;
import org.hibernate.jpamodelgen.util.StringUtil;
import org.hibernate.jpamodelgen.util.TypeUtils;
import org.hibernate.jpamodelgen.xml.jaxb.Entity;
@@ -55,7 +56,6 @@
private static final String ORM_XML = "/META-INF/orm.xml";
private static final String PERSISTENCE_XML_XSD = "persistence_2_0.xsd";
private static final String ORM_XSD = "orm_2_0.xsd";
- private static final String PATH_SEPARATOR = "/";
private Context context;
private List<EntityMappings> entityMappings;
@@ -154,13 +154,13 @@
}
XmlMetaEntity metaEntity = new XmlMetaEmbeddable( embeddable, pkg, getXmlMappedType( fqcn ), context );
- if ( context.containsMetaSuperclassOrEmbeddable( fqcn ) ) {
+ if ( context.containsMetaEmbeddable( fqcn ) ) {
context.logMessage(
Diagnostic.Kind.WARNING,
fqcn + " was already processed once. Skipping second occurance."
);
}
- context.addMetaSuperclassOrEmbeddable( fqcn, metaEntity );
+ context.addMetaEmbeddable( fqcn, metaEntity );
}
}
@@ -180,17 +180,17 @@
continue;
}
- XmlMetaEntity metaEntity = new XmlMetaMappedSuperClass(
+ XmlMetaEntity metaEntity = new XmlMetaEntity(
mappedSuperClass, pkg, getXmlMappedType( fqcn ), context
);
- if ( context.containsMetaSuperclassOrEmbeddable( fqcn ) ) {
+ if ( context.containsMetaEmbeddable( fqcn ) ) {
context.logMessage(
Diagnostic.Kind.WARNING,
fqcn + " was already processed once. Skipping second occurance."
);
}
- context.addMetaSuperclassOrEmbeddable( fqcn, metaEntity );
+ context.addMetaEntity( fqcn, metaEntity );
}
}
@@ -263,7 +263,7 @@
ormStream = fileObject.openInputStream();
}
catch ( IOException e1 ) {
- // TODO
+ // TODO - METAGEN-12
// unfortunately, the Filer.getResource API seems not to be able to load from /META-INF. One gets a
// FilerException with the message with "Illegal name /META-INF". This means that we have to revert to
// using the classpath. This might mean that we find a persistence.xml which is 'part of another jar.
@@ -274,20 +274,20 @@
}
private String getPackage(String resourceName) {
- if ( !resourceName.contains( PATH_SEPARATOR ) ) {
+ if ( !resourceName.contains( Constants.PATH_SEPARATOR ) ) {
return "";
}
else {
- return resourceName.substring( 0, resourceName.lastIndexOf( PATH_SEPARATOR ) );
+ return resourceName.substring( 0, resourceName.lastIndexOf( Constants.PATH_SEPARATOR ) );
}
}
private String getRelativeName(String resourceName) {
- if ( !resourceName.contains( PATH_SEPARATOR ) ) {
+ if ( !resourceName.contains( Constants.PATH_SEPARATOR ) ) {
return resourceName;
}
else {
- return resourceName.substring( resourceName.lastIndexOf( PATH_SEPARATOR ) + 1 );
+ return resourceName.substring( resourceName.lastIndexOf( Constants.PATH_SEPARATOR ) + 1 );
}
}
@@ -329,11 +329,11 @@
context.addAccessTypeInformation( fqcn, accessInfo );
}
- for ( org.hibernate.jpamodelgen.xml.jaxb.Embeddable embeddable : mappings.getEmbeddable() ) {
- String name = embeddable.getClazz();
+ for ( org.hibernate.jpamodelgen.xml.jaxb.MappedSuperclass mappedSuperClass : mappings.getMappedSuperclass() ) {
+ String name = mappedSuperClass.getClazz();
fqcn = StringUtil.determineFullyQualifiedClassName( packageName, name );
AccessType explicitAccessType = null;
- org.hibernate.jpamodelgen.xml.jaxb.AccessType type = embeddable.getAccess();
+ org.hibernate.jpamodelgen.xml.jaxb.AccessType type = mappedSuperClass.getAccess();
if ( type != null ) {
explicitAccessType = mapXmlAccessTypeToJpaAccessType( type );
}
@@ -341,14 +341,13 @@
fqcn, explicitAccessType, defaultAccessType
);
context.addAccessTypeInformation( fqcn, accessInfo );
-
}
- for ( org.hibernate.jpamodelgen.xml.jaxb.MappedSuperclass mappedSuperClass : mappings.getMappedSuperclass() ) {
- String name = mappedSuperClass.getClazz();
+ for ( org.hibernate.jpamodelgen.xml.jaxb.Embeddable embeddable : mappings.getEmbeddable() ) {
+ String name = embeddable.getClazz();
fqcn = StringUtil.determineFullyQualifiedClassName( packageName, name );
AccessType explicitAccessType = null;
- org.hibernate.jpamodelgen.xml.jaxb.AccessType type = mappedSuperClass.getAccess();
+ org.hibernate.jpamodelgen.xml.jaxb.AccessType type = embeddable.getAccess();
if ( type != null ) {
explicitAccessType = mapXmlAccessTypeToJpaAccessType( type );
}
Modified: jpamodelgen/trunk/src/test/resources/org/hibernate/jpamodelgen/test/xmlmapped/building.xml
===================================================================
--- jpamodelgen/trunk/src/test/resources/org/hibernate/jpamodelgen/test/xmlmapped/building.xml 2010-02-11 19:16:42 UTC (rev 18786)
+++ jpamodelgen/trunk/src/test/resources/org/hibernate/jpamodelgen/test/xmlmapped/building.xml 2010-02-11 19:37:09 UTC (rev 18787)
@@ -5,10 +5,11 @@
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
version="2.0"
>
- <package>org.hibernate.jpamodelgen.test.xmlmapped</package>
- <mapped-superclass class="Building" access="FIELD" metadata-complete="true"> <!--means ignore annotations-->
+ <mapped-superclass class="org.hibernate.jpamodelgen.test.xmlmapped.Building"
+ access="FIELD"
+ metadata-complete="true">
<attributes>
- <one-to-one name="address" fetch="LAZY"/>
+ <one-to-one name="address"/>
</attributes>
</mapped-superclass>
</entity-mappings>
14 years, 3 months
Hibernate SVN: r18786 - annotations/branches/v3_4_0_GA_CP.
by hibernate-commits@lists.jboss.org
Author: stliu
Date: 2010-02-11 14:16:42 -0500 (Thu, 11 Feb 2010)
New Revision: 18786
Modified:
annotations/branches/v3_4_0_GA_CP/pom.xml
Log:
JBPAPP-3379 default hibernate.jdbc.use_streams_for_binary cause two test cases fail on db2
Modified: annotations/branches/v3_4_0_GA_CP/pom.xml
===================================================================
--- annotations/branches/v3_4_0_GA_CP/pom.xml 2010-02-11 18:43:21 UTC (rev 18785)
+++ annotations/branches/v3_4_0_GA_CP/pom.xml 2010-02-11 19:16:42 UTC (rev 18786)
@@ -275,7 +275,11 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
+<version>2.5</version>
<configuration>
+<systemPropertyVariables>
+<hibernate.jdbc.use_streams_for_binary>${hibernate.jdbc.use_streams_for_binary}</hibernate.jdbc.use_streams_for_binary>
+</systemPropertyVariables>
<redirectTestOutputToFile>true</redirectTestOutputToFile>
</configuration>
</plugin>
14 years, 3 months
Hibernate SVN: r18785 - in annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations: entity and 1 other directories.
by hibernate-commits@lists.jboss.org
Author: stliu
Date: 2010-02-11 13:43:21 -0500 (Thu, 11 Feb 2010)
New Revision: 18785
Removed:
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/SystemLevelPropertyUtil.java
Modified:
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/PropertyDefaultMappingsTest.java
annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/LobTest.java
Log:
JBPAPP-3379 remove the fix I did, it does not work on hudson
Deleted: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/SystemLevelPropertyUtil.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/SystemLevelPropertyUtil.java 2010-02-11 17:50:02 UTC (rev 18784)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/SystemLevelPropertyUtil.java 2010-02-11 18:43:21 UTC (rev 18785)
@@ -1,118 +0,0 @@
-/*
- * Hibernate, Relational Persistence for Idiomatic Java
- *
- * Copyright (c) 2009, Red Hat Middleware LLC 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 Middleware LLC.
- *
- * 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.test.annotations;
-
-import java.io.IOException;
-import java.net.URL;
-import java.util.Properties;
-
-import org.hibernate.util.ConfigHelper;
-
-/**
- * This util class is for setting some system-level properties It is used before
- * Environment be loaded into jvm.
- *
- * @author Strong Liu <stliu(a)redhat.com>
- */
-public class SystemLevelPropertyUtil {
- /**
- * find is the property <tt>prop</tt> is in System properties or in
- * hibernate.properties.
- *
- *
- * @param prop
- * @return
- */
- public static boolean isPropertyExist( Object prop ) {
- if ( System.getProperties().containsKey( prop ) ) {
- return true;
- }
- return getHibernateProperties().containsKey( prop );
- }
-
- /**
- * get the property <tt>prop</tt> value
- * @param prop
- * @return
- */
- public static Object getSystemLevelProperty( Object prop ) {
- if ( !isPropertyExist( prop ) ) {
- return null;
- }
- if ( System.getProperties().containsKey( prop ) ) {
- return System.getProperties().get( prop );
- }
- if ( getHibernateProperties().containsKey( prop ) ) {
- return getHibernateProperties().get( prop );
- }
- return null;
- }
-
- private static Properties getHibernateProperties() {
- Properties properties = new Properties();
- try {
- properties.load( findAsResource( "hibernate.properties" )
- .openStream() );
- } catch (IOException e) {
-
- }
- return properties;
- }
-
- /**
- * Try to locate a local URL representing the incoming path. This method
- * <b>only</b> attempts to locate this URL as a java system resource.
- *
- * @param path
- * The path representing the config location.
- * @return An appropriate URL or null.
- */
- private static final URL findAsResource( final String path ) {
- URL url = null;
-
- // First, try to locate this resource through the current
- // context classloader.
- ClassLoader contextClassLoader = Thread.currentThread()
- .getContextClassLoader();
- if ( contextClassLoader != null ) {
- url = contextClassLoader.getResource( path );
- }
- if ( url != null )
- return url;
-
- // Next, try to locate this resource through this class's classloader
- url = ConfigHelper.class.getClassLoader().getResource( path );
- if ( url != null )
- return url;
-
- // Next, try to locate this resource through the system classloader
- url = ClassLoader.getSystemClassLoader().getResource( path );
-
- // Anywhere else we should look?
- return url;
- }
-}
Modified: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/PropertyDefaultMappingsTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/PropertyDefaultMappingsTest.java 2010-02-11 17:50:02 UTC (rev 18784)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/entity/PropertyDefaultMappingsTest.java 2010-02-11 18:43:21 UTC (rev 18785)
@@ -6,7 +6,6 @@
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.DB2Dialect;
-import org.hibernate.test.annotations.SystemLevelPropertyUtil;
import org.hibernate.test.annotations.TestCase;
import org.hibernate.util.ConfigHelper;
@@ -18,15 +17,6 @@
super( x );
}
- //https://jira.jboss.org/jira/browse/JBPAPP-3379
- @Override
- protected void setUp() throws Exception {
- String dialect = (String)SystemLevelPropertyUtil.getSystemLevelProperty( "hibernate.dialect" );
- if(dialect.equals( "org.hibernate.dialect.DB2Dialect" )){
- System.setProperty( "hibernate.jdbc.use_streams_for_binary" , "false" );
- }
- super.setUp();
- }
public void testSerializableObject() throws Exception {
Session s;
Modified: annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/LobTest.java
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/LobTest.java 2010-02-11 17:50:02 UTC (rev 18784)
+++ annotations/branches/v3_4_0_GA_CP/src/test/java/org/hibernate/test/annotations/lob/LobTest.java 2010-02-11 18:43:21 UTC (rev 18785)
@@ -3,24 +3,12 @@
import org.hibernate.Session;
import org.hibernate.Transaction;
-import org.hibernate.test.annotations.SystemLevelPropertyUtil;
import org.hibernate.test.annotations.TestCase;
/**
* @author Emmanuel Bernard
*/
public class LobTest extends TestCase {
-
-
- //https://jira.jboss.org/jira/browse/JBPAPP-3379
- @Override
- protected void setUp() throws Exception {
- String dialect = (String)SystemLevelPropertyUtil.getSystemLevelProperty( "hibernate.dialect" );
- if(dialect.equals( "org.hibernate.dialect.DB2Dialect" )){
- System.setProperty( "hibernate.jdbc.use_streams_for_binary" , "false" );
- }
- super.setUp();
- }
public void testSerializableToBlob() throws Exception {
Book book = new Book();
14 years, 3 months
Hibernate SVN: r18784 - in jpamodelgen/trunk: src/main and 3 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-02-11 12:50:02 -0500 (Thu, 11 Feb 2010)
New Revision: 18784
Added:
jpamodelgen/trunk/src/main/docbook/
jpamodelgen/trunk/src/main/docbook/en-US/
jpamodelgen/trunk/src/main/docbook/en-US/images/
jpamodelgen/trunk/src/main/docbook/en-US/images/eclipse-annotation-processor-config.png
jpamodelgen/trunk/src/main/docbook/en-US/images/idea-annotation-processor-config.png
jpamodelgen/trunk/src/main/docbook/en-US/master.xml
Modified:
jpamodelgen/trunk/pom.xml
Log:
METAGEN-4 Added a start for the documentation
Modified: jpamodelgen/trunk/pom.xml
===================================================================
--- jpamodelgen/trunk/pom.xml 2010-02-11 16:16:21 UTC (rev 18783)
+++ jpamodelgen/trunk/pom.xml 2010-02-11 17:50:02 UTC (rev 18784)
@@ -1,4 +1,6 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
@@ -28,13 +30,13 @@
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.6</version>
- </dependency>
+ </dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<scope>test</scope>
<version>1.5.6</version>
- </dependency>
+ </dependency>
</dependencies>
<licenses>
@@ -161,7 +163,7 @@
<artifactId>maven-surefire-plugin</artifactId>
<version>2.4.3</version>
<configuration>
- <redirectTestOutputToFile>true</redirectTestOutputToFile>
+ <redirectTestOutputToFile>true</redirectTestOutputToFile>
<systemProperties>
<property>
<name>sourceBaseDir</name>
@@ -255,6 +257,70 @@
<goals>package deploy</goals>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.jboss.maven.plugins</groupId>
+ <artifactId>maven-jdocbook-plugin</artifactId>
+ <version>2.2.0</version>
+ <extensions>true</extensions>
+ <dependencies>
+ <dependency>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-jdocbook-style</artifactId>
+ <version>2.0.0</version>
+ <type>jdocbook-style</type>
+ </dependency>
+ </dependencies>
+ <configuration>
+ <sourceDocumentName>master.xml</sourceDocumentName>
+ <sourceDirectory>${basedir}/src/main/docbook</sourceDirectory>
+ <masterTranslation>en-US</masterTranslation>
+ <imageResource>
+ <directory>${basedir}/src/main/docbook/en-US/images</directory>
+ </imageResource>
+ <formats>
+ <format>
+ <formatName>pdf</formatName>
+ <stylesheetResource>classpath:/xslt/org/hibernate/jdocbook/xslt/pdf.xsl</stylesheetResource>
+ <finalName>hibernate-metamodel-generator-reference.pdf</finalName>
+ </format>
+ <format>
+ <formatName>html_single</formatName>
+ <stylesheetResource>classpath:/xslt/org/hibernate/jdocbook/xslt/xhtml-single.xsl
+ </stylesheetResource>
+ <finalName>index.html</finalName>
+ </format>
+ <format>
+ <formatName>html</formatName>
+ <stylesheetResource>classpath:/xslt/org/hibernate/jdocbook/xslt/xhtml.xsl
+ </stylesheetResource>
+ <finalName>index.html</finalName>
+ </format>
+ </formats>
+ <options>
+ <xincludeSupported>true</xincludeSupported>
+ <xmlTransformerType>saxon</xmlTransformerType>
+ <!-- needed for uri-resolvers; can be ommitted if using 'current' uri scheme -->
+ <!-- could also locate the docbook dependency and inspect its version... -->
+ <docbookVersion>1.72.0</docbookVersion>
+ <localeSeparator>-</localeSeparator>
+ </options>
+ </configuration>
+ <executions>
+ <execution>
+ <id>make-doc</id>
+ <phase>site</phase>
+ <goals>
+ <goal>resources</goal>
+ <goal>generate</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.jboss.maven.plugins</groupId>
+ <artifactId>maven-jdocbook-style-plugin</artifactId>
+ <version>2.0.0</version>
+ </plugin>
</plugins>
<extensions>
Added: jpamodelgen/trunk/src/main/docbook/en-US/images/eclipse-annotation-processor-config.png
===================================================================
(Binary files differ)
Property changes on: jpamodelgen/trunk/src/main/docbook/en-US/images/eclipse-annotation-processor-config.png
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: jpamodelgen/trunk/src/main/docbook/en-US/images/idea-annotation-processor-config.png
===================================================================
(Binary files differ)
Property changes on: jpamodelgen/trunk/src/main/docbook/en-US/images/idea-annotation-processor-config.png
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: jpamodelgen/trunk/src/main/docbook/en-US/master.xml
===================================================================
--- jpamodelgen/trunk/src/main/docbook/en-US/master.xml (rev 0)
+++ jpamodelgen/trunk/src/main/docbook/en-US/master.xml 2010-02-11 17:50:02 UTC (rev 18784)
@@ -0,0 +1,283 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- $Id$ -->
+<!--
+ ~ JBoss, Home of Professional Open Source
+ ~ Copyright 2010, Red Hat, Inc. and/or its affiliates, and individual contributors
+ ~ by the @authors tag. See the copyright.txt in the distribution for a
+ ~ full listing of individual contributors.
+ ~
+ ~ 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.
+-->
+<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
+"http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
+<!ENTITY versionNumber "1.0.0">
+<!ENTITY copyrightYear "2010">
+<!ENTITY copyrightHolder "Red Hat Middleware, LLC.">
+]>
+<book lang="en">
+ <bookinfo>
+ <title>Hibernate Metamodel Generator</title>
+
+ <subtitle>JPA 2 Static Metamodel Annotation Processor</subtitle>
+
+ <subtitle>Reference Guide</subtitle>
+
+ <releaseinfo>&versionNumber;</releaseinfo>
+
+ <productnumber>&versionNumber;</productnumber>
+
+ <copyright>
+ <year>©rightYear;</year>
+
+ <holder>©rightHolder;</holder>
+ </copyright>
+ </bookinfo>
+
+ <toc></toc>
+
+ <chapter id="introduction">
+ <title>Introduction</title>
+
+ <section id="whatisit" revision="1">
+ <title>What is it about?</title>
+
+ <para>Hibernate Static Metamodel Generator is an annotation processor
+ with the task of creating the static metamodel classes for JPA 2
+ entities. In the following I will show how to integrate the annotation
+ processor into your build environment.</para>
+ </section>
+
+ <section id="installation" revision="1">
+ <title>Installation</title>
+
+ <para><section revision="1">
+ <title>Prerequisites</title>
+
+ <para />
+ </section></para>
+ </section>
+ </chapter>
+
+ <chapter>
+ <title>Usage</title>
+
+ <para>In most cases the annotation processor will automatically run
+ provided the annotation processor jar is on the classpath. This happens
+ due to Java's Service Provider contract and the fact the the Hibernate
+ Static Metamodel Generator jar files contains the file
+ <classname>javax.annotation.processing.Processor</classname> in the
+ <filename>META-INF/services</filename> listing
+ <classname>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</classname>
+ as annotation processor.</para>
+
+ <section>
+ <title>Usage from the command line</title>
+
+ <para><section revision="1">
+ <title>Usage with Ant</title>
+ </section>As mentioned before, the annotation processor will run
+ automatically in a Java 6 environment. In case you want configure the
+ processor explicitly or disable it you can use the compilerarg option of
+ the Javac Task. The supported command javac line options are listed
+ here. <section revision="1">
+ <title>Usage with Maven</title>
+ </section>There are several ways of running the annotation processor
+ as part of a Maven build. It will automatically run if you are using a
+ JDK 6 compiler and the annotation processor jar is on the classpath. In
+ case you have more than one annotation processors on your classpath you
+ can explicitly pass the processor option to the compiler plugin:</para>
+
+ <para><example>
+ <title>Maven compiler plugin configuration - direct
+ execution</title>
+
+ <programlisting><plugin>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ <compilerArguments>
+ <processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
+ </compilerArguments>
+ </configuration>
+</plugin></programlisting>
+ </example></para>
+
+ <para>The maven-compiler-plugin approach has the disadvantage that the
+ maven compiler plugin does currently not allow to specify multiple
+ compiler arguments (MCOMPILER-62) and that messages from the Messenger
+ API are suppressed (MCOMPILER-66). A better approach is to disable
+ annotation processing for the compiler plugin:</para>
+
+ <example>
+ <title>Maven compiler plugin configuration - indirect
+ execution</title>
+
+ <programlisting><plugin>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.6</source>
+ <target>1.6</target>
+ <compilerArgument>-proc:none</compilerArgument>
+ </configuration>
+</plugin></programlisting>
+ </example>
+
+ <para>and use the maven-annotation-plugin for annotation processing (you
+ will need the following additional maven repositories -
+ maven-annotation-plugin and jfrog):</para>
+
+ <example>
+ <title>Maven compiler plugin configuration with
+ maven-annotation-plugin</title>
+
+ <programlisting><plugin>
+ <groupId>org.bsc.maven</groupId>
+ <artifactId>maven-processor-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>process</id>
+ <goals>
+ <goal>process</goal>
+ </goals>
+ <phase>generate-sources</phase>
+ <configuration>
+ <!-- source output directory -->
+ <outputDirectory>target/metamodel</outputDirectory>
+ </configuration>
+ </execution>
+ </executions>
+</plugin>
+<plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>build-helper-maven-plugin</artifactId>
+ <version>1.3</version>
+ <executions>
+ <execution>
+ <id>add-source</id>
+ <phase>generate-sources</phase>
+ <goals>
+ <goal>add-source</goal>
+ </goals>
+ <configuration>
+ <sources>
+ <source>target/metamodel</source>
+ </sources>
+ </configuration>
+ </execution>
+ </executions>
+</plugin></programlisting>
+ </example>
+ </section>
+
+ <section>
+ <title>Usage within the IDE</title>
+
+ <section>
+ <title>Idea</title>
+
+ <mediaobject>
+ <imageobject role="fo">
+ <imagedata align="center" contentdepth="" contentwidth="150mm"
+ fileref="idea-annotation-processor-config.png"
+ scalefit="" />
+ </imageobject>
+
+ <imageobject role="html">
+ <imagedata depth="" fileref="idea-annotation-processor-config.png"
+ scalefit="1" />
+ </imageobject>
+ </mediaobject>
+
+ <para></para>
+ </section>
+
+ <section>
+ <title>Eclipse</title>
+
+ <mediaobject>
+ <imageobject role="fo">
+ <imagedata align="center" contentdepth="" contentwidth="150mm"
+ fileref="eclipse-annotation-processor-config.png"
+ scalefit="" />
+ </imageobject>
+
+ <imageobject role="html">
+ <imagedata depth=""
+ fileref="eclipse-annotation-processor-config.png"
+ scalefit="1" />
+ </imageobject>
+ </mediaobject>
+ </section>
+
+ <section>
+ <title>NetBeans</title>
+
+ <para>Of course you also want to have annotation processing available
+ in your favorite IDE. In Eclipse (at least since the latest Galileo
+ release) exists an additional configuration section under Java
+ Compiler where you can configure all kinds of aspects of annotation
+ processing. Just check the "Enable annotation processing" option,
+ configure the directory for the generated sources and finally add the
+ Hibernate Static Metamodel Generator and JPA 2 jar files to the
+ factory path.</para>
+ </section>
+ </section>
+
+ <section>
+ <title>Options</title>
+
+ <para>The annotaton processor accepts a series of custom properties
+ which can be passed to the processor execution in the format
+ <literal>-A[property]=[value]</literal>. The supported properties
+ are:<table>
+ <title>Annotation processor options (passed via
+ -A[property]=[value])</title>
+
+ <tgroup cols="2">
+ <tbody>
+ <row>
+ <entry>Option name</entry>
+
+ <entry>Option value and usage</entry>
+ </row>
+
+ <row>
+ <entry>debug</entry>
+
+ <entry>if set to <literal>true</literal> additional trace
+ information will be outputted by the processor</entry>
+ </row>
+
+ <row>
+ <entry>persistenceXml</entry>
+
+ <entry>Per default the processor looks in
+ <filename>/META-INF</filename> for persistence.xml. Specifying
+ this option a <filename>persitence.xml</filename> file from a
+ different location can be specified (has to be on the
+ classpath)</entry>
+ </row>
+
+ <row>
+ <entry>ormXml</entry>
+
+ <entry>Allows to specify additional entity mapping files. The
+ specified value for this option is a comma separated string of
+ mapping file names. Even when this option is specified
+ <filename>/META-INF/orm.xml</filename> is implicit.</entry>
+ </row>
+ </tbody>
+ </tgroup>
+ </table></para>
+ </section>
+ </chapter>
+</book>
Property changes on: jpamodelgen/trunk/src/main/docbook/en-US/master.xml
___________________________________________________________________
Name: svn:keywords
+ Id
14 years, 3 months
Hibernate SVN: r18783 - in validator/trunk: hibernate-validator/src/main/java/org/hibernate/validator/constraints and 4 other directories.
by hibernate-commits@lists.jboss.org
Author: hardy.ferentschik
Date: 2010-02-11 11:16:21 -0500 (Thu, 11 Feb 2010)
New Revision: 18783
Added:
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/constraints/Url.java
validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/constraints/impl/UrlValidator.java
validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/constraints/impl/UrlValidatorTest.java
Modified:
validator/trunk/hibernate-validator-archetype/pom.xml
validator/trunk/hibernate-validator-legacy/pom.xml
validator/trunk/pom.xml
Log:
HV-283
Added: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/constraints/Url.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/constraints/Url.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/constraints/Url.java 2010-02-11 16:16:21 UTC (rev 18783)
@@ -0,0 +1,48 @@
+// $Id: Length.java 17427 2009-08-27 09:47:28Z hardy.ferentschik $
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* 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.hibernate.validator.constraints;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+import javax.validation.Constraint;
+import javax.validation.Payload;
+
+import org.hibernate.validator.constraints.impl.URLValidator;
+
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+import static java.lang.annotation.ElementType.TYPE;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+/**
+ * Validate that the string is a valid URL.
+ *
+ * @author Hardy Ferentschik
+ */
+@Documented
+@Constraint(validatedBy = URLValidator.class)
+@Target({ METHOD, FIELD, TYPE })
+@Retention(RUNTIME)
+public @interface URL {
+ public abstract String message() default "{org.hibernate.validator.constraints.URL.message}";
+
+ public abstract Class<?>[] groups() default { };
+
+ public abstract Class<? extends Payload>[] payload() default { };
+}
\ No newline at end of file
Added: validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/constraints/impl/UrlValidator.java
===================================================================
--- validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/constraints/impl/UrlValidator.java (rev 0)
+++ validator/trunk/hibernate-validator/src/main/java/org/hibernate/validator/constraints/impl/UrlValidator.java 2010-02-11 16:16:21 UTC (rev 18783)
@@ -0,0 +1,47 @@
+// $Id: LengthValidator.java 17521 2009-09-16 12:50:41Z hardy.ferentschik $
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* 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.hibernate.validator.constraints.impl;
+
+import java.net.MalformedURLException;
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+
+import org.hibernate.validator.constraints.URL;
+
+/**
+ * Validate that the string is a valid URL.
+ *
+ * @author Hardy Ferentschik
+ */
+public class URLValidator implements ConstraintValidator<URL, String> {
+ public void initialize(URL url) {
+ }
+
+ public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
+ if ( value == null ) {
+ return true;
+ }
+ try {
+ new java.net.URL( value );
+ return true;
+ }
+ catch ( MalformedURLException e ) {
+ return false;
+ }
+ }
+}
\ No newline at end of file
Added: validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/constraints/impl/UrlValidatorTest.java
===================================================================
--- validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/constraints/impl/UrlValidatorTest.java (rev 0)
+++ validator/trunk/hibernate-validator/src/test/java/org/hibernate/validator/constraints/impl/UrlValidatorTest.java 2010-02-11 16:16:21 UTC (rev 18783)
@@ -0,0 +1,48 @@
+// $Id: LengthValidatorTest.java 17521 2009-09-16 12:50:41Z hardy.ferentschik $
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2008, Red Hat Middleware LLC, and individual contributors
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* 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.hibernate.validator.constraints.impl;
+
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertTrue;
+import org.testng.annotations.Test;
+
+import org.hibernate.validator.constraints.URL;
+import org.hibernate.validator.util.annotationfactory.AnnotationDescriptor;
+import org.hibernate.validator.util.annotationfactory.AnnotationFactory;
+
+/**
+ * Tests the {@code Url} constraint.
+ *
+ * @author Hardy Ferentschik
+ */
+public class URLValidatorTest {
+
+ @Test
+ public void testIsValidUrl() {
+ AnnotationDescriptor<URL> descriptor = new AnnotationDescriptor<URL>( URL.class );
+ descriptor.setValue( "message", "{org.hibernate.validator.constraints.URL.message}" );
+ URL url = AnnotationFactory.create( descriptor );
+ URLValidator validator = new URLValidator();
+ validator.initialize( url );
+ assertTrue( validator.isValid( null, null ) );
+ assertFalse( validator.isValid( "", null ) );
+ assertFalse( validator.isValid( "http", null ) );
+ assertFalse( validator.isValid( "ftp//abc.de", null ) );
+ assertTrue( validator.isValid( "ftp://abc.de", null ) );
+ }
+}
\ No newline at end of file
Modified: validator/trunk/hibernate-validator-archetype/pom.xml
===================================================================
--- validator/trunk/hibernate-validator-archetype/pom.xml 2010-02-11 15:51:25 UTC (rev 18782)
+++ validator/trunk/hibernate-validator-archetype/pom.xml 2010-02-11 16:16:21 UTC (rev 18783)
@@ -54,6 +54,12 @@
<target>1.5</target>
</configuration>
</plugin>
+ <plugin>
+ <artifactId>maven-deploy-plugin</artifactId>
+ <configuration>
+ <skip>true</skip>
+ </configuration>
+ </plugin>
</plugins>
</build>
<repositories>
Modified: validator/trunk/hibernate-validator-legacy/pom.xml
===================================================================
--- validator/trunk/hibernate-validator-legacy/pom.xml 2010-02-11 15:51:25 UTC (rev 18782)
+++ validator/trunk/hibernate-validator-legacy/pom.xml 2010-02-11 16:16:21 UTC (rev 18783)
@@ -106,6 +106,17 @@
</dependency>
</dependencies>
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-deploy-plugin</artifactId>
+ <configuration>
+ <skip>true</skip>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
<profiles>
<profile>
<id>dist</id>
Modified: validator/trunk/pom.xml
===================================================================
--- validator/trunk/pom.xml 2010-02-11 15:51:25 UTC (rev 18782)
+++ validator/trunk/pom.xml 2010-02-11 16:16:21 UTC (rev 18783)
@@ -240,6 +240,11 @@
</configuration>
</plugin>
<plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-deploy-plugin</artifactId>
+ <version>2.5</version>
+ </plugin>
+ <plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.1.1</version>
14 years, 3 months
Hibernate SVN: r18782 - in core/trunk/core/src/main/java/org/hibernate: sql and 1 other directory.
by hibernate-commits@lists.jboss.org
Author: smarlow(a)redhat.com
Date: 2010-02-11 10:51:25 -0500 (Thu, 11 Feb 2010)
New Revision: 18782
Modified:
core/trunk/core/src/main/java/org/hibernate/dialect/AbstractTransactSQLDialect.java
core/trunk/core/src/main/java/org/hibernate/dialect/Dialect.java
core/trunk/core/src/main/java/org/hibernate/dialect/MySQLDialect.java
core/trunk/core/src/main/java/org/hibernate/sql/ForUpdateFragment.java
Log:
HHH-4765 Enhance Dialect support for JPA-2 locking. MySQL pessimistic locking and Dialect.getForUpdateString(String aliases, LockOptions lockOptions)
Modified: core/trunk/core/src/main/java/org/hibernate/dialect/AbstractTransactSQLDialect.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/AbstractTransactSQLDialect.java 2010-02-11 15:16:38 UTC (rev 18781)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/AbstractTransactSQLDialect.java 2010-02-11 15:51:25 UTC (rev 18782)
@@ -170,6 +170,7 @@
}
public String applyLocksToSql(String sql, LockOptions aliasedLockOptions, Map keyColumnNames) {
+ // TODO: merge additional lockoptions support in Dialect.applyLocksToSql
Iterator itr = aliasedLockOptions.getAliasLockIterator();
StringBuffer buffer = new StringBuffer( sql );
int correction = 0;
Modified: core/trunk/core/src/main/java/org/hibernate/dialect/Dialect.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/Dialect.java 2010-02-11 15:16:38 UTC (rev 18781)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/Dialect.java 2010-02-11 15:51:25 UTC (rev 18782)
@@ -1095,6 +1095,20 @@
}
/**
+ * Get the <tt>FOR UPDATE OF column_list</tt> fragment appropriate for this
+ * dialect given the aliases of the columns to be write locked.
+ *
+ * @param aliases The columns to be write locked.
+ * @param lockOptions
+ * @return The appropriate <tt>FOR UPDATE OF column_list</tt> clause string.
+ */
+ public String getForUpdateString(String aliases, LockOptions lockOptions) {
+ // by default we simply return the getForUpdateString() result since
+ // the default is to say no support for "FOR UPDATE OF ..."
+ return getForUpdateString(lockOptions);
+ }
+
+ /**
* Retrieves the <tt>FOR UPDATE NOWAIT</tt> syntax specific to this dialect.
*
* @return The appropriate <tt>FOR UPDATE NOWAIT</tt> clause string.
Modified: core/trunk/core/src/main/java/org/hibernate/dialect/MySQLDialect.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/dialect/MySQLDialect.java 2010-02-11 15:16:38 UTC (rev 18781)
+++ core/trunk/core/src/main/java/org/hibernate/dialect/MySQLDialect.java 2010-02-11 15:51:25 UTC (rev 18782)
@@ -30,6 +30,7 @@
import java.sql.Types;
import org.hibernate.Hibernate;
+import org.hibernate.LockOptions;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.function.NoArgSQLFunction;
import org.hibernate.dialect.function.StandardSQLFunction;
@@ -334,6 +335,21 @@
}
+ // locking support
+
+ public String getForUpdateString() {
+ return " for update";
+ }
+
+ public String getWriteLockString(int timeout) {
+ return " for update";
+ }
+
+ public String getReadLockString(int timeout) {
+ return " lock in share mode";
+ }
+
+
// Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public boolean supportsEmptyInList() {
Modified: core/trunk/core/src/main/java/org/hibernate/sql/ForUpdateFragment.java
===================================================================
--- core/trunk/core/src/main/java/org/hibernate/sql/ForUpdateFragment.java 2010-02-11 15:16:38 UTC (rev 18781)
+++ core/trunk/core/src/main/java/org/hibernate/sql/ForUpdateFragment.java 2010-02-11 15:51:25 UTC (rev 18782)
@@ -101,14 +101,13 @@
}
public String toFragmentString() {
-
- if ( aliases.length() == 0) {
- if ( lockOptions != null ) {
- return dialect.getForUpdateString(lockOptions);
+ if ( lockOptions!= null ) {
+ return dialect.getForUpdateString( aliases.toString(), lockOptions );
+ }
+ else if ( aliases.length() == 0) {
+ if ( lockMode != null ) {
+ return dialect.getForUpdateString( lockMode );
}
- else if ( lockMode != null ) {
- return dialect.getForUpdateString(lockMode);
- }
return "";
}
// TODO: pass lockmode
14 years, 3 months
Hibernate SVN: r18781 - annotations/branches/v3_4_0_GA_CP/src/test/resources.
by hibernate-commits@lists.jboss.org
Author: stliu
Date: 2010-02-11 10:16:38 -0500 (Thu, 11 Feb 2010)
New Revision: 18781
Modified:
annotations/branches/v3_4_0_GA_CP/src/test/resources/log4j.properties
Log:
no code change, enable the type and sql package log output
Modified: annotations/branches/v3_4_0_GA_CP/src/test/resources/log4j.properties
===================================================================
--- annotations/branches/v3_4_0_GA_CP/src/test/resources/log4j.properties 2010-02-11 14:49:24 UTC (rev 18780)
+++ annotations/branches/v3_4_0_GA_CP/src/test/resources/log4j.properties 2010-02-11 15:16:38 UTC (rev 18781)
@@ -28,3 +28,6 @@
log4j.logger.org.hibernate.hql.ast.HqlSqlWalker=trace
log4j.logger.org.hibernate.hql.ast.SqlGenerator=trace
log4j.logger.org.hibernate.hql.ast.AST=trace
+
+log4j.logger.org.hibernate.SQL=debug
+log4j.logger.org.hibernate.type=trace
14 years, 3 months