From 11464ea0976343a27ddada0af4d0bca7182ce498 Mon Sep 17 00:00:00 2001 From: Strong Liu Date: Mon, 22 Apr 2013 18:41:02 +0800 Subject: [PATCH 01/57] HHH-8127 OutOfMemoryError when running tests --- .../testing/junit4/CustomRunner.java | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/junit4/CustomRunner.java b/hibernate-testing/src/main/java/org/hibernate/testing/junit4/CustomRunner.java index 2e3b8a6ac0..6dc6b197c0 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/junit4/CustomRunner.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/junit4/CustomRunner.java @@ -100,7 +100,24 @@ public class CustomRunner extends BlockJUnit4ClassRunner { return isAllTestsIgnored; } - @Override + + @Override + public void run(RunNotifier notifier) { + super.run( notifier ); + + cleanup(); + } + + private void cleanup() { + if ( computedTestMethods != null && !computedTestMethods.isEmpty() ) { + computedTestMethods.clear(); + computedTestMethods = null; + } + testInstance = null; + testClassMetadata = null; + } + + @Override protected Statement withBeforeClasses(Statement statement) { if ( isAllTestsIgnored() ) { return super.withBeforeClasses( statement ); From 63093dbfd9f227f059b38f33806a6882e3e34200 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Mon, 22 Apr 2013 17:14:29 -0500 Subject: [PATCH 02/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../action/internal/EntityInsertAction.java | 3 +- .../javassist/TransformingClassLoader.java | 2 +- .../internal/CacheDataDescriptionImpl.java | 80 ++-- .../internal/NoCachingRegionFactory.java | 18 +- .../internal/RegionFactoryInitiator.java | 41 +- .../cache/internal/StandardQueryCache.java | 158 ++++--- .../internal/StandardQueryCacheFactory.java | 8 +- .../cache/internal/package-info.java | 28 ++ .../cache/spi/UpdateTimestampsCache.java | 1 - .../spi/entry/StructuredMapCacheEntry.java | 5 +- .../java/org/hibernate/classic/Lifecycle.java | 12 +- .../AbstractPersistentCollection.java | 300 +++++++------ .../internal/PersistentArrayHolder.java | 181 +++++--- .../collection/internal/PersistentBag.java | 380 +++++++++-------- .../internal/PersistentElementHolder.java | 218 ++++++---- .../internal/PersistentIdentifierBag.java | 295 ++++++++----- .../PersistentIndexedElementHolder.java | 221 ++++++---- .../collection/internal/PersistentList.java | 402 ++++++++++-------- .../internal/PersistentListElementHolder.java | 58 ++- .../collection/internal/PersistentMap.java | 345 ++++++++++----- .../internal/PersistentMapElementHolder.java | 78 ++-- .../collection/internal/PersistentSet.java | 259 ++++++----- .../internal/PersistentSortedMap.java | 208 +++++---- .../internal/PersistentSortedSet.java | 131 +++--- .../collection/internal/package-info.java | 28 ++ .../collection/spi/PersistentCollection.java | 220 ++++++++-- .../collection/spi/package-info.java | 28 ++ 27 files changed, 2269 insertions(+), 1439 deletions(-) create mode 100644 hibernate-core/src/main/java/org/hibernate/cache/internal/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/collection/internal/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/collection/spi/package-info.java diff --git a/hibernate-core/src/main/java/org/hibernate/action/internal/EntityInsertAction.java b/hibernate-core/src/main/java/org/hibernate/action/internal/EntityInsertAction.java index fba5c3e6ef..9c17828b15 100644 --- a/hibernate-core/src/main/java/org/hibernate/action/internal/EntityInsertAction.java +++ b/hibernate-core/src/main/java/org/hibernate/action/internal/EntityInsertAction.java @@ -48,7 +48,6 @@ import org.hibernate.persister.entity.EntityPersister; * @see EntityIdentityInsertAction */ public final class EntityInsertAction extends AbstractEntityInsertAction { - private Object version; private Object cacheEntry; @@ -130,7 +129,7 @@ public final class EntityInsertAction extends AbstractEntityInsertAction { version, session ); - cacheEntry = persister.getCacheEntryStructure().structure(ce); + cacheEntry = persister.getCacheEntryStructure().structure( ce ); final CacheKey ck = session.generateCacheKey( id, persister.getIdentifierType(), persister.getRootEntityName() ); final boolean put = persister.getCacheAccessStrategy().insert( ck, cacheEntry, version ); diff --git a/hibernate-core/src/main/java/org/hibernate/bytecode/internal/javassist/TransformingClassLoader.java b/hibernate-core/src/main/java/org/hibernate/bytecode/internal/javassist/TransformingClassLoader.java index 96661cb461..53ad74fdd7 100644 --- a/hibernate-core/src/main/java/org/hibernate/bytecode/internal/javassist/TransformingClassLoader.java +++ b/hibernate-core/src/main/java/org/hibernate/bytecode/internal/javassist/TransformingClassLoader.java @@ -63,7 +63,7 @@ public class TransformingClassLoader extends ClassLoader { try { final CtClass cc = classPool.get( name ); // todo : modify the class definition if not already transformed... - byte[] b = cc.toBytecode(); + final byte[] b = cc.toBytecode(); return defineClass( name, b, 0, b.length ); } catch (NotFoundException e) { diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/CacheDataDescriptionImpl.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/CacheDataDescriptionImpl.java index aa365cb5bf..e4917d1200 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/internal/CacheDataDescriptionImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/CacheDataDescriptionImpl.java @@ -30,10 +30,11 @@ import org.hibernate.mapping.Collection; import org.hibernate.mapping.PersistentClass; import org.hibernate.metamodel.binding.EntityBinding; import org.hibernate.metamodel.binding.PluralAttributeBinding; -import org.hibernate.persister.entity.EntityPersister; import org.hibernate.type.VersionType; /** + * Standard CacheDataDescription implementation. + * * @author Steve Ebersole */ public class CacheDataDescriptionImpl implements CacheDataDescription { @@ -41,48 +42,87 @@ public class CacheDataDescriptionImpl implements CacheDataDescription { private final boolean versioned; private final Comparator versionComparator; + /** + * Constructs a CacheDataDescriptionImpl instance. Generally speaking, code should use one of the + * overloaded {@link #decode} methods rather than direct instantiation. + * + * @param mutable Is the described data mutable? + * @param versioned Is the described data versioned? + * @param versionComparator The described data's version value comparator (if versioned). + */ public CacheDataDescriptionImpl(boolean mutable, boolean versioned, Comparator versionComparator) { this.mutable = mutable; this.versioned = versioned; this.versionComparator = versionComparator; } + @Override public boolean isMutable() { return mutable; } + @Override public boolean isVersioned() { return versioned; } + @Override public Comparator getVersionComparator() { return versionComparator; } + /** + * Builds a CacheDataDescriptionImpl from the mapping model of an entity class. + * + * @param model The mapping model. + * + * @return The constructed CacheDataDescriptionImpl + */ public static CacheDataDescriptionImpl decode(PersistentClass model) { return new CacheDataDescriptionImpl( model.isMutable(), model.isVersioned(), - model.isVersioned() ? ( ( VersionType ) model.getVersion().getType() ).getComparator() : null + model.isVersioned() + ? ( (VersionType) model.getVersion().getType() ).getComparator() + : null ); } + /** + * Builds a CacheDataDescriptionImpl from the mapping model of an entity class (using the new metamodel code). + * + * @param model The mapping model. + * + * @return The constructed CacheDataDescriptionImpl + */ public static CacheDataDescriptionImpl decode(EntityBinding model) { - return new CacheDataDescriptionImpl( - model.isMutable(), - model.isVersioned(), - getVersionComparator( model ) - ); + return new CacheDataDescriptionImpl( model.isMutable(), model.isVersioned(), getVersionComparator( model ) ); } + /** + * Builds a CacheDataDescriptionImpl from the mapping model of a collection + * + * @param model The mapping model. + * + * @return The constructed CacheDataDescriptionImpl + */ public static CacheDataDescriptionImpl decode(Collection model) { return new CacheDataDescriptionImpl( model.isMutable(), model.getOwner().isVersioned(), - model.getOwner().isVersioned() ? ( ( VersionType ) model.getOwner().getVersion().getType() ).getComparator() : null + model.getOwner().isVersioned() + ? ( (VersionType) model.getOwner().getVersion().getType() ).getComparator() + : null ); } + /** + * Builds a CacheDataDescriptionImpl from the mapping model of a collection (using the new metamodel code). + * + * @param model The mapping model. + * + * @return The constructed CacheDataDescriptionImpl + */ public static CacheDataDescriptionImpl decode(PluralAttributeBinding model) { return new CacheDataDescriptionImpl( model.isMutable(), @@ -91,24 +131,16 @@ public class CacheDataDescriptionImpl implements CacheDataDescription { ); } - public static CacheDataDescriptionImpl decode(EntityPersister persister) { - return new CacheDataDescriptionImpl( - !persister.getEntityMetamodel().hasImmutableNaturalId(), - false, - null - ); - } - private static Comparator getVersionComparator(EntityBinding model ) { - Comparator versionComparator = null; if ( model.isVersioned() ) { - versionComparator = ( - ( VersionType ) model.getHierarchyDetails() - .getVersioningAttributeBinding() - .getHibernateTypeDescriptor() - .getResolvedTypeMapping() - ).getComparator(); + final VersionType versionType = (VersionType) model.getHierarchyDetails() + .getVersioningAttributeBinding() + .getHibernateTypeDescriptor() + .getResolvedTypeMapping(); + + return versionType.getComparator(); } - return versionComparator; + + return null; } } diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/NoCachingRegionFactory.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/NoCachingRegionFactory.java index 7d16fb3e5a..1d52e51630 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/internal/NoCachingRegionFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/NoCachingRegionFactory.java @@ -43,48 +43,64 @@ import org.hibernate.cfg.Settings; * @author Steve Ebersole */ public class NoCachingRegionFactory implements RegionFactory { + /** + * Singleton access + */ public static final NoCachingRegionFactory INSTANCE = new NoCachingRegionFactory(); + /** + * Constructs a NoCachingRegionFactory. Although access should generally use {@link #INSTANCE} + */ public NoCachingRegionFactory() { } + @Override public void start(Settings settings, Properties properties) throws CacheException { } + @Override public void stop() { } + @Override public boolean isMinimalPutsEnabledByDefault() { return false; } + @Override public AccessType getDefaultAccessType() { return null; } + @Override public long nextTimestamp() { return System.currentTimeMillis() / 100; } + @Override public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException { throw new NoCacheRegionFactoryAvailableException(); } - + + @Override public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException { throw new NoCacheRegionFactoryAvailableException(); } + @Override public CollectionRegion buildCollectionRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException { throw new NoCacheRegionFactoryAvailableException(); } + @Override public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException { throw new NoCacheRegionFactoryAvailableException(); } + @Override public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException { throw new NoCacheRegionFactoryAvailableException(); } diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java index 65b13cb453..ffa33b8e72 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java @@ -28,8 +28,6 @@ import java.util.Map; import org.hibernate.boot.registry.StandardServiceInitiator; import org.hibernate.boot.registry.selector.spi.StrategySelector; import org.hibernate.cache.spi.RegionFactory; -import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; -import org.hibernate.service.spi.ServiceException; import org.hibernate.service.spi.ServiceRegistryImplementor; /** @@ -38,6 +36,9 @@ import org.hibernate.service.spi.ServiceRegistryImplementor; * @author Hardy Ferentschik */ public class RegionFactoryInitiator implements StandardServiceInitiator { + /** + * Singleton access + */ public static final RegionFactoryInitiator INSTANCE = new RegionFactoryInitiator(); /** @@ -59,35 +60,17 @@ public class RegionFactoryInitiator implements StandardServiceInitiator customImplClass = null; -// if ( Class.class.isInstance( setting ) ) { -// customImplClass = (Class) setting; -// } -// else { -// customImplClass = registry.getService( ClassLoaderService.class ) -// .classForName( mapLegacyNames( setting.toString() ) ); -// } -// -// try { -// return customImplClass.newInstance(); -// } -// catch ( Exception e ) { -// throw new ServiceException( -// "Could not initialize custom RegionFactory impl [" + customImplClass.getName() + "]", e -// ); -// } } - // todo this shouldn't be public (nor really static): - // hack for org.hibernate.cfg.SettingsFactory.createRegionFactory() + /** + * Map legacy names unto the new corollary. + * + * todo this shouldn't be public, nor really static. hack for org.hibernate.cfg.SettingsFactory.createRegionFactory() + * + * @param name The (possibly legacy) factory name + * + * @return The factory name to use. + */ public static String mapLegacyNames(final String name) { if ( "org.hibernate.cache.EhCacheRegionFactory".equals( name ) ) { return "org.hibernate.cache.ehcache.EhCacheRegionFactory"; diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/StandardQueryCache.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/StandardQueryCache.java index 9cb2c7daa7..9d2abf41fb 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/internal/StandardQueryCache.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/StandardQueryCache.java @@ -48,14 +48,13 @@ import org.hibernate.type.TypeHelper; /** * The standard implementation of the Hibernate QueryCache interface. This * implementation is very good at recognizing stale query results and - * and re-running queries when it detects this condition, recaching the new + * and re-running queries when it detects this condition, re-caching the new * results. * * @author Gavin King * @author Steve Ebersole */ public class StandardQueryCache implements QueryCache { - private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, StandardQueryCache.class.getName() @@ -67,28 +66,54 @@ public class StandardQueryCache implements QueryCache { private QueryResultsRegion cacheRegion; private UpdateTimestampsCache updateTimestampsCache; - public void clear() throws CacheException { - cacheRegion.evictAll(); - } - + /** + * Constructs a StandardQueryCache instance + * + * @param settings The SessionFactory settings. + * @param props Any properties + * @param updateTimestampsCache The update-timestamps cache to use. + * @param regionName The base query cache region name + */ public StandardQueryCache( final Settings settings, final Properties props, final UpdateTimestampsCache updateTimestampsCache, - String regionName) throws HibernateException { - if ( regionName == null ) { - regionName = StandardQueryCache.class.getName(); + final String regionName) { + String regionNameToUse = regionName; + if ( regionNameToUse == null ) { + regionNameToUse = StandardQueryCache.class.getName(); } - String prefix = settings.getCacheRegionPrefix(); + final String prefix = settings.getCacheRegionPrefix(); if ( prefix != null ) { - regionName = prefix + '.' + regionName; + regionNameToUse = prefix + '.' + regionNameToUse; } - LOG.startingQueryCache( regionName ); + LOG.startingQueryCache( regionNameToUse ); - this.cacheRegion = settings.getRegionFactory().buildQueryResultsRegion( regionName, props ); + this.cacheRegion = settings.getRegionFactory().buildQueryResultsRegion( regionNameToUse, props ); this.updateTimestampsCache = updateTimestampsCache; } + @Override + public QueryResultsRegion getRegion() { + return cacheRegion; + } + + @Override + public void destroy() { + try { + cacheRegion.destroy(); + } + catch ( Exception e ) { + LOG.unableToDestroyQueryCache( cacheRegion.getName(), e.getMessage() ); + } + } + + @Override + public void clear() throws CacheException { + cacheRegion.evictAll(); + } + + @Override @SuppressWarnings({ "unchecked" }) public boolean put( final QueryKey key, @@ -99,20 +124,21 @@ public class StandardQueryCache implements QueryCache { if ( isNaturalKeyLookup && result.isEmpty() ) { return false; } - long ts = cacheRegion.nextTimestamp(); + final long ts = cacheRegion.nextTimestamp(); - if ( DEBUGGING ) LOG.debugf( "Caching query results in region: %s; timestamp=%s", cacheRegion.getName(), ts ); + if ( DEBUGGING ) { + LOG.debugf( "Caching query results in region: %s; timestamp=%s", cacheRegion.getName(), ts ); + } - List cacheable = new ArrayList( result.size() + 1 ); + final List cacheable = new ArrayList( result.size() + 1 ); logCachedResultDetails( key, null, returnTypes, cacheable ); cacheable.add( ts ); - final boolean singleResult = returnTypes.length == 1; + + final boolean isSingleResult = returnTypes.length == 1; for ( Object aResult : result ) { - Serializable cacheItem = singleResult ? returnTypes[0].disassemble( - aResult, - session, - null - ) : TypeHelper.disassemble( (Object[]) aResult, returnTypes, null, session, null ); + final Serializable cacheItem = isSingleResult + ? returnTypes[0].disassemble( aResult, session, null ) + : TypeHelper.disassemble( (Object[]) aResult, returnTypes, null, session, null ); cacheable.add( cacheItem ); logCachedResultRowDetails( returnTypes, aResult ); } @@ -121,6 +147,7 @@ public class StandardQueryCache implements QueryCache { return true; } + @Override @SuppressWarnings({ "unchecked" }) public List get( final QueryKey key, @@ -128,23 +155,31 @@ public class StandardQueryCache implements QueryCache { final boolean isNaturalKeyLookup, final Set spaces, final SessionImplementor session) throws HibernateException { - if ( DEBUGGING ) LOG.debugf( "Checking cached query results in region: %s", cacheRegion.getName() ); + if ( DEBUGGING ) { + LOG.debugf( "Checking cached query results in region: %s", cacheRegion.getName() ); + } - List cacheable = (List) cacheRegion.get( key ); + final List cacheable = (List) cacheRegion.get( key ); logCachedResultDetails( key, spaces, returnTypes, cacheable ); if ( cacheable == null ) { - if ( DEBUGGING ) LOG.debug( "Query results were not found in cache" ); + if ( DEBUGGING ) { + LOG.debug( "Query results were not found in cache" ); + } return null; } - Long timestamp = (Long) cacheable.get( 0 ); + final Long timestamp = (Long) cacheable.get( 0 ); if ( !isNaturalKeyLookup && !isUpToDate( spaces, timestamp ) ) { - if ( DEBUGGING ) LOG.debug( "Cached query results were not up-to-date" ); + if ( DEBUGGING ) { + LOG.debug( "Cached query results were not up-to-date" ); + } return null; } - if ( DEBUGGING ) LOG.debug( "Returning cached query results" ); + if ( DEBUGGING ) { + LOG.debug( "Returning cached query results" ); + } final boolean singleResult = returnTypes.length == 1; for ( int i = 1; i < cacheable.size(); i++ ) { if ( singleResult ) { @@ -154,7 +189,8 @@ public class StandardQueryCache implements QueryCache { TypeHelper.beforeAssemble( (Serializable[]) cacheable.get( i ), returnTypes, session ); } } - List result = new ArrayList( cacheable.size() - 1 ); + + final List result = new ArrayList( cacheable.size() - 1 ); for ( int i = 1; i < cacheable.size(); i++ ) { try { if ( singleResult ) { @@ -168,16 +204,18 @@ public class StandardQueryCache implements QueryCache { logCachedResultRowDetails( returnTypes, result.get( i - 1 ) ); } catch ( RuntimeException ex ) { - if ( isNaturalKeyLookup && - ( UnresolvableObjectException.class.isInstance( ex ) || - EntityNotFoundException.class.isInstance( ex ) ) ) { - //TODO: not really completely correct, since - // the uoe could occur while resolving - // associations, leaving the PC in an - // inconsistent state - if ( DEBUGGING ) LOG.debug( "Unable to reassemble cached result set" ); - cacheRegion.evict( key ); - return null; + if ( isNaturalKeyLookup ) { + // potentially perform special handling for natural-id look ups. + if ( UnresolvableObjectException.class.isInstance( ex ) + || EntityNotFoundException.class.isInstance( ex ) ) { + if ( DEBUGGING ) { + LOG.debug( "Unable to reassemble cached natural-id query result" ); + } + cacheRegion.evict( key ); + + // EARLY EXIT !!!!! + return null; + } } throw ex; } @@ -186,23 +224,12 @@ public class StandardQueryCache implements QueryCache { } protected boolean isUpToDate(final Set spaces, final Long timestamp) { - if ( DEBUGGING ) LOG.debugf( "Checking query spaces are up-to-date: %s", spaces ); + if ( DEBUGGING ) { + LOG.debugf( "Checking query spaces are up-to-date: %s", spaces ); + } return updateTimestampsCache.isUpToDate( spaces, timestamp ); } - public void destroy() { - try { - cacheRegion.destroy(); - } - catch ( Exception e ) { - LOG.unableToDestroyQueryCache( cacheRegion.getName(), e.getMessage() ); - } - } - - public QueryResultsRegion getRegion() { - return cacheRegion; - } - @Override public String toString() { return "StandardQueryCache(" + cacheRegion.getName() + ')'; @@ -222,12 +249,13 @@ public class StandardQueryCache implements QueryCache { ); } else { - StringBuilder returnTypeInfo = new StringBuilder(); - for ( int i = 0; i < returnTypes.length; i++ ) { + final StringBuilder returnTypeInfo = new StringBuilder(); + for ( Type returnType : returnTypes ) { returnTypeInfo.append( "typename=" ) - .append( returnTypes[i].getName() ) + .append( returnType.getName() ) .append( " class=" ) - .append( returnTypes[i].getReturnedClass().getName() ).append( ' ' ); + .append( returnType.getReturnedClass().getName() ) + .append( ' ' ); } LOG.trace( "unexpected returnTypes is " + returnTypeInfo.toString() + "! result" ); } @@ -248,7 +276,10 @@ public class StandardQueryCache implements QueryCache { return; } if ( tuple == null ) { - LOG.trace( " tuple is null; returnTypes is " + returnTypes == null ? "null" : "Type[" + returnTypes.length + "]" ); + LOG.tracef( + "tuple is null; returnTypes is %s", + returnTypes == null ? "null" : "Type[" + returnTypes.length + "]" + ); if ( returnTypes != null && returnTypes.length > 1 ) { LOG.trace( "Unexpected result tuple! tuple is null; should be Object[" @@ -263,8 +294,12 @@ public class StandardQueryCache implements QueryCache { + ( returnTypes == null ? "null" : "empty" ) ); } - LOG.trace( " tuple is Object[" + tuple.length + "]; returnTypes is Type[" + returnTypes.length + "]" ); - if ( tuple.length != returnTypes.length ) { + LOG.tracef( + "tuple is Object[%s]; returnTypes is %s", + tuple.length, + returnTypes == null ? "null" : "Type[" + returnTypes.length + "]" + ); + if ( returnTypes != null && tuple.length != returnTypes.length ) { LOG.trace( "Unexpected tuple length! transformer= expected=" + returnTypes.length + " got=" + tuple.length @@ -272,7 +307,8 @@ public class StandardQueryCache implements QueryCache { } else { for ( int j = 0; j < tuple.length; j++ ) { - if ( tuple[j] != null && !returnTypes[j].getReturnedClass().isInstance( tuple[j] ) ) { + if ( tuple[j] != null && returnTypes != null + && ! returnTypes[j].getReturnedClass().isInstance( tuple[j] ) ) { LOG.trace( "Unexpected tuple value type! transformer= expected=" + returnTypes[j].getReturnedClass().getName() diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/StandardQueryCacheFactory.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/StandardQueryCacheFactory.java index 26f742dc5f..7b584d0be6 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/internal/StandardQueryCacheFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/StandardQueryCacheFactory.java @@ -38,10 +38,10 @@ import org.hibernate.cfg.Settings; public class StandardQueryCacheFactory implements QueryCacheFactory { @Override public QueryCache getQueryCache( - final String regionName, - final UpdateTimestampsCache updateTimestampsCache, - final Settings settings, - final Properties props) throws HibernateException { + final String regionName, + final UpdateTimestampsCache updateTimestampsCache, + final Settings settings, + final Properties props) throws HibernateException { return new StandardQueryCache(settings, props, updateTimestampsCache, regionName); } } diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/package-info.java new file mode 100644 index 0000000000..39a20475e8 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/package-info.java @@ -0,0 +1,28 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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 + */ + +/** + * Internal implementations and support for second-level caching. + */ +package org.hibernate.cache.internal; diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/UpdateTimestampsCache.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/UpdateTimestampsCache.java index 59d7c637cb..470174044c 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/spi/UpdateTimestampsCache.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/UpdateTimestampsCache.java @@ -29,7 +29,6 @@ import java.util.Set; import org.jboss.logging.Logger; -import org.hibernate.HibernateException; import org.hibernate.cache.CacheException; import org.hibernate.cfg.Settings; import org.hibernate.engine.spi.SessionFactoryImplementor; diff --git a/hibernate-core/src/main/java/org/hibernate/cache/spi/entry/StructuredMapCacheEntry.java b/hibernate-core/src/main/java/org/hibernate/cache/spi/entry/StructuredMapCacheEntry.java index a896e09b44..d7bb2c786a 100755 --- a/hibernate-core/src/main/java/org/hibernate/cache/spi/entry/StructuredMapCacheEntry.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/spi/entry/StructuredMapCacheEntry.java @@ -45,8 +45,9 @@ public class StructuredMapCacheEntry implements CacheEntryStructure { public Object structure(Object item) { final CollectionCacheEntry entry = (CollectionCacheEntry) item; final Serializable[] state = entry.getState(); - final Map map = new HashMap(state.length); - for ( int i=0; i() { @Override public Boolean doWork() { - CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this ); + final CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this ); if ( entry != null ) { - CollectionPersister persister = entry.getLoadedPersister(); + final CollectionPersister persister = entry.getLoadedPersister(); if ( persister.isExtraLazy() ) { if ( hasQueuedOperations() ) { session.flush(); @@ -168,7 +184,17 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers return false; } + /** + * TBH not sure why this is public + * + * @param The java type of the return for this LazyInitializationWork + */ public static interface LazyInitializationWork { + /** + * Do the represented work and return the result. + * + * @return The result + */ public T doWork(); } @@ -221,7 +247,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers // be created even if a current session and transaction are // open (ex: session.clear() was used). We must prevent // multiple transactions. - ( ( Session) session ).beginTransaction(); + ( (Session) session ).beginTransaction(); } session.getPersistenceContext().addUninitializedDetachedCollection( @@ -238,7 +264,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers // make sure the just opened temp session gets closed! try { if ( !isJTA ) { - ( ( Session) session ).getTransaction().commit(); + ( (Session) session ).getTransaction().commit(); } ( (Session) session ).close(); } @@ -255,19 +281,19 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers throwLazyInitializationException( "SessionFactory UUID not known to create temporary Session for loading" ); } - SessionFactoryImplementor sf = (SessionFactoryImplementor) + final SessionFactoryImplementor sf = (SessionFactoryImplementor) SessionFactoryRegistry.INSTANCE.getSessionFactory( sessionFactoryUuid ); return (SessionImplementor) sf.openSession(); } protected Boolean readIndexExistence(final Object index) { if ( !initialized ) { - Boolean extraLazyExistenceCheck = withTemporarySessionIfNeeded( + final Boolean extraLazyExistenceCheck = withTemporarySessionIfNeeded( new LazyInitializationWork() { @Override public Boolean doWork() { - CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this ); - CollectionPersister persister = entry.getLoadedPersister(); + final CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this ); + final CollectionPersister persister = entry.getLoadedPersister(); if ( persister.isExtraLazy() ) { if ( hasQueuedOperations() ) { session.flush(); @@ -290,12 +316,12 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers protected Boolean readElementExistence(final Object element) { if ( !initialized ) { - Boolean extraLazyExistenceCheck = withTemporarySessionIfNeeded( + final Boolean extraLazyExistenceCheck = withTemporarySessionIfNeeded( new LazyInitializationWork() { @Override public Boolean doWork() { - CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this ); - CollectionPersister persister = entry.getLoadedPersister(); + final CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this ); + final CollectionPersister persister = entry.getLoadedPersister(); if ( persister.isExtraLazy() ) { if ( hasQueuedOperations() ) { session.flush(); @@ -326,8 +352,8 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers @Override public Object doWork() { - CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this ); - CollectionPersister persister = entry.getLoadedPersister(); + final CollectionEntry entry = session.getPersistenceContext().getCollectionEntry( AbstractPersistentCollection.this ); + final CollectionPersister persister = entry.getLoadedPersister(); isExtraLazy = persister.isExtraLazy(); if ( isExtraLazy ) { if ( hasQueuedOperations() ) { @@ -342,7 +368,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers } } - ExtraLazyElementByIndexReader reader = new ExtraLazyElementByIndexReader(); + final ExtraLazyElementByIndexReader reader = new ExtraLazyElementByIndexReader(); //noinspection unchecked withTemporarySessionIfNeeded( reader ); if ( reader.isExtraLazy ) { @@ -358,9 +384,9 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers } private boolean isConnectedToSession() { - return session != null && - session.isOpen() && - session.getPersistenceContext().containsCollection( this ); + return session != null + && session.isOpen() + && session.getPersistenceContext().containsCollection( this ); } /** @@ -377,9 +403,9 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers */ @SuppressWarnings({"JavaDoc"}) protected boolean isOperationQueueEnabled() { - return !initialized && - isConnectedToSession() && - isInverseCollection(); + return !initialized + && isConnectedToSession() + && isInverseCollection(); } /** @@ -389,9 +415,9 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers */ @SuppressWarnings({"JavaDoc"}) protected boolean isPutQueueEnabled() { - return !initialized && - isConnectedToSession() && - isInverseOneToManyOrNoOrphanDelete(); + return !initialized + && isConnectedToSession() + && isInverseOneToManyOrNoOrphanDelete(); } /** @@ -401,9 +427,9 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers */ @SuppressWarnings({"JavaDoc"}) protected boolean isClearQueueEnabled() { - return !initialized && - isConnectedToSession() && - isInverseCollectionNoOrphanDelete(); + return !initialized + && isConnectedToSession() + && isInverseCollectionNoOrphanDelete(); } /** @@ -411,7 +437,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers */ @SuppressWarnings({"JavaDoc"}) private boolean isInverseCollection() { - CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this ); + final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this ); return ce != null && ce.getLoadedPersister().isInverse(); } @@ -421,8 +447,9 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers */ @SuppressWarnings({"JavaDoc"}) private boolean isInverseCollectionNoOrphanDelete() { - CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this ); - return ce != null && + final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this ); + return ce != null + && ce.getLoadedPersister().isInverse() && !ce.getLoadedPersister().hasOrphanDelete(); } @@ -433,11 +460,10 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers */ @SuppressWarnings({"JavaDoc"}) private boolean isInverseOneToManyOrNoOrphanDelete() { - CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this ); - return ce != null && ce.getLoadedPersister().isInverse() && ( - ce.getLoadedPersister().isOneToMany() || - !ce.getLoadedPersister().hasOrphanDelete() - ); + final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this ); + return ce != null + && ce.getLoadedPersister().isInverse() + && ( ce.getLoadedPersister().isOneToMany() || !ce.getLoadedPersister().hasOrphanDelete() ); } /** @@ -449,7 +475,8 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers operationQueue = new ArrayList( 10 ); } operationQueue.add( operation ); - dirty = true; //needed so that we remove this collection from the second-level cache + //needed so that we remove this collection from the second-level cache + dirty = true; } /** @@ -462,59 +489,38 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers } } - /** - * After flushing, re-init snapshot state. - */ + @Override public void setSnapshot(Serializable key, String role, Serializable snapshot) { this.key = key; this.role = role; this.storedSnapshot = snapshot; } - /** - * After flushing, clear any "queued" additions, since the - * database state is now synchronized with the memory state. - */ + @Override public void postAction() { operationQueue = null; cachedSize = -1; clearDirty(); } - /** - * Not called by Hibernate, but used by non-JDK serialization, - * eg. SOAP libraries. - */ - public AbstractPersistentCollection() { - } - - protected AbstractPersistentCollection(SessionImplementor session) { - this.session = session; - } - - /** - * return the user-visible collection (or array) instance - */ + @Override public Object getValue() { return this; } - /** - * Called just before reading any rows from the JDBC result set - */ + @Override public void beginRead() { // override on some subclasses initializing = true; } - /** - * Called after reading all rows from the JDBC result set - */ + @Override public boolean endRead() { //override on some subclasses return afterInitialize(); } + @Override public boolean afterInitialize() { setInitialized(); //do this bit after setting initialized to true or it will recurse @@ -579,19 +585,12 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers this.directlyAccessible = directlyAccessible; } - /** - * Could the application possibly have a direct reference to - * the underlying collection implementation? - */ + @Override public boolean isDirectlyAccessible() { return directlyAccessible; } - /** - * Disassociate this collection from the given session. - * - * @return true if this was currently associated with the given session - */ + @Override public final boolean unsetSession(SessionImplementor currentSession) { prepareForPossibleSpecialSpecjInitialization(); if ( currentSession == this.session ) { @@ -619,21 +618,14 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers } - /** - * Associate the collection with the given session. - * - * @return false if the collection was already associated with the session - * - * @throws HibernateException if the collection was already associated - * with another open session - */ + @Override public final boolean setCurrentSession(SessionImplementor session) throws HibernateException { if ( session == this.session ) { return false; } else { if ( isConnectedToSession() ) { - CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this ); + final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( this ); if ( ce == null ) { throw new HibernateException( "Illegal attempt to associate a collection with two open sessions" @@ -656,17 +648,12 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers } } - /** - * Do we need to completely recreate this collection when it changes? - */ + @Override public boolean needsRecreate(CollectionPersister persister) { return false; } - /** - * To be called internally by the session, forcing - * immediate initialization. - */ + @Override public final void forceInitialization() throws HibernateException { if ( !initialized ) { if ( initializing ) { @@ -691,40 +678,38 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers return session.getPersistenceContext().getSnapshot( this ); } - /** - * Is this instance initialized? - */ + @Override public final boolean wasInitialized() { return initialized; } + @Override public boolean isRowUpdatePossible() { return true; } - /** - * Does this instance have any "queued" additions? - */ + @Override public final boolean hasQueuedOperations() { return operationQueue != null; } - /** - * Iterate the "queued" additions - */ + @Override public final Iterator queuedAdditionIterator() { if ( hasQueuedOperations() ) { return new Iterator() { - int i = 0; + private int index; + @Override public Object next() { - return operationQueue.get( i++ ).getAddedInstance(); + return operationQueue.get( index++ ).getAddedInstance(); } + @Override public boolean hasNext() { - return i < operationQueue.size(); + return index < operationQueue.size(); } + @Override public void remove() { throw new UnsupportedOperationException(); } @@ -735,14 +720,12 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers } } - /** - * Iterate the "queued" additions - */ + @Override @SuppressWarnings({"unchecked"}) public final Collection getQueuedOrphans(String entityName) { if ( hasQueuedOperations() ) { - Collection additions = new ArrayList( operationQueue.size() ); - Collection removals = new ArrayList( operationQueue.size() ); + final Collection additions = new ArrayList( operationQueue.size() ); + final Collection removals = new ArrayList( operationQueue.size() ); for ( DelayedOperation operation : operationQueue ) { additions.add( operation.getAddedInstance() ); removals.add( operation.getOrphan() ); @@ -754,28 +737,22 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers } } - /** - * Called before inserting rows, to ensure that any surrogate keys - * are fully generated - */ + @Override public void preInsert(CollectionPersister persister) throws HibernateException { } - /** - * Called after inserting a row, to fetch the natively generated id - */ + @Override public void afterRowInsert(CollectionPersister persister, Object entry, int i) throws HibernateException { } - /** - * get all "orphaned" elements - */ + @Override public abstract Collection getOrphans(Serializable snapshot, String entityName) throws HibernateException; /** - * Get the current session + * Get the session currently associated with this collection. + * + * @return The session */ - @SuppressWarnings({"JavaDoc"}) public final SessionImplementor getSession() { return session; } @@ -787,19 +764,21 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers this.itr = itr; } + @Override public boolean hasNext() { return itr.hasNext(); } + @Override public Object next() { return itr.next(); } + @Override public void remove() { write(); itr.remove(); } - } protected final class ListIteratorProxy implements ListIterator { @@ -809,47 +788,55 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers this.itr = itr; } + @Override @SuppressWarnings({"unchecked"}) public void add(Object o) { write(); itr.add( o ); } + @Override public boolean hasNext() { return itr.hasNext(); } + @Override public boolean hasPrevious() { return itr.hasPrevious(); } + @Override public Object next() { return itr.next(); } + @Override public int nextIndex() { return itr.nextIndex(); } + @Override public Object previous() { return itr.previous(); } + @Override public int previousIndex() { return itr.previousIndex(); } + @Override public void remove() { write(); itr.remove(); } + @Override @SuppressWarnings({"unchecked"}) public void set(Object o) { write(); itr.set( o ); } - } protected class SetProxy implements java.util.Set { @@ -859,67 +846,82 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers this.set = set; } + @Override @SuppressWarnings({"unchecked"}) public boolean add(Object o) { write(); return set.add( o ); } + @Override @SuppressWarnings({"unchecked"}) public boolean addAll(Collection c) { write(); return set.addAll( c ); } + @Override public void clear() { write(); set.clear(); } + @Override public boolean contains(Object o) { return set.contains( o ); } + @Override + @SuppressWarnings("unchecked") public boolean containsAll(Collection c) { return set.containsAll( c ); } + @Override public boolean isEmpty() { return set.isEmpty(); } + @Override public Iterator iterator() { return new IteratorProxy( set.iterator() ); } + @Override public boolean remove(Object o) { write(); return set.remove( o ); } + @Override + @SuppressWarnings("unchecked") public boolean removeAll(Collection c) { write(); return set.removeAll( c ); } + @Override + @SuppressWarnings("unchecked") public boolean retainAll(Collection c) { write(); return set.retainAll( c ); } + @Override public int size() { return set.size(); } + @Override public Object[] toArray() { return set.toArray(); } + @Override @SuppressWarnings({"unchecked"}) public Object[] toArray(Object[] array) { return set.toArray( array ); } - } protected final class ListProxy implements java.util.List { @@ -969,6 +971,7 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers } @Override + @SuppressWarnings("unchecked") public boolean containsAll(Collection c) { return list.containsAll( c ); } @@ -1021,12 +1024,14 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers } @Override + @SuppressWarnings("unchecked") public boolean removeAll(Collection c) { write(); return list.removeAll( c ); } @Override + @SuppressWarnings("unchecked") public boolean retainAll(Collection c) { write(); return list.retainAll( c ); @@ -1087,34 +1092,36 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers // short-circuit(s) if ( currentElements.size() == 0 ) { - return oldElements; // no new elements, the old list contains only Orphans + // no new elements, the old list contains only Orphans + return oldElements; } if ( oldElements.size() == 0 ) { - return oldElements; // no old elements, so no Orphans neither + // no old elements, so no Orphans neither + return oldElements; } final EntityPersister entityPersister = session.getFactory().getEntityPersister( entityName ); final Type idType = entityPersister.getIdentifierType(); // create the collection holding the Orphans - Collection res = new ArrayList(); + final Collection res = new ArrayList(); // collect EntityIdentifier(s) of the *current* elements - add them into a HashSet for fast access - java.util.Set currentIds = new HashSet(); - java.util.Set currentSaving = new IdentitySet(); + final java.util.Set currentIds = new HashSet(); + final java.util.Set currentSaving = new IdentitySet(); for ( Object current : currentElements ) { if ( current != null && ForeignKeys.isNotTransient( entityName, current, null, session ) ) { - EntityEntry ee = session.getPersistenceContext().getEntry( current ); + final EntityEntry ee = session.getPersistenceContext().getEntry( current ); if ( ee != null && ee.getStatus() == Status.SAVING ) { currentSaving.add( current ); } else { - Serializable currentId = ForeignKeys.getEntityIdentifierIfNotUnsaved( + final Serializable currentId = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, current, session ); - currentIds.add( new TypedValue( idType, currentId, entityPersister.getEntityMode() ) ); + currentIds.add( new TypedValue( idType, currentId ) ); } } } @@ -1122,8 +1129,8 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers // iterate over the *old* list for ( Object old : oldElements ) { if ( !currentSaving.contains( old ) ) { - Serializable oldId = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, old, session ); - if ( !currentIds.contains( new TypedValue( idType, oldId, entityPersister.getEntityMode() ) ) ) { + final Serializable oldId = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, old, session ); + if ( !currentIds.contains( new TypedValue( idType, oldId ) ) ) { res.add( old ); } } @@ -1132,20 +1139,28 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers return res; } + /** + * Removes entity entries that have an equal identifier with the incoming entity instance + * + * @param list The list containing the entity instances + * @param entityInstance The entity instance to match elements. + * @param entityName The entity name + * @param session The session + */ public static void identityRemove( Collection list, - Object object, + Object entityInstance, String entityName, - SessionImplementor session) throws HibernateException { + SessionImplementor session) { - if ( object != null && ForeignKeys.isNotTransient( entityName, object, null, session ) ) { + if ( entityInstance != null && ForeignKeys.isNotTransient( entityName, entityInstance, null, session ) ) { final EntityPersister entityPersister = session.getFactory().getEntityPersister( entityName ); - Type idType = entityPersister.getIdentifierType(); + final Type idType = entityPersister.getIdentifierType(); - Serializable idOfCurrent = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, object, session ); - Iterator itr = list.iterator(); + final Serializable idOfCurrent = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, entityInstance, session ); + final Iterator itr = list.iterator(); while ( itr.hasNext() ) { - Serializable idOfOld = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, itr.next(), session ); + final Serializable idOfOld = ForeignKeys.getEntityIdentifierIfNotUnsaved( entityName, itr.next(), session ); if ( idType.isEqual( idOfCurrent, idOfOld, session.getFactory() ) ) { itr.remove(); break; @@ -1155,14 +1170,17 @@ public abstract class AbstractPersistentCollection implements Serializable, Pers } } + @Override public Object getIdentifier(Object entry, int i) { throw new UnsupportedOperationException(); } + @Override public Object getOwner() { return owner; } + @Override public void setOwner(Object owner) { this.owner = owner; } diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentArrayHolder.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentArrayHolder.java index 9ddd1d21aa..8243f08562 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentArrayHolder.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentArrayHolder.java @@ -29,6 +29,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.Iterator; import org.jboss.logging.Logger; @@ -48,27 +49,52 @@ import org.hibernate.type.Type; * @author Gavin King */ public class PersistentArrayHolder extends AbstractPersistentCollection { - protected Object array; + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + PersistentArrayHolder.class.getName() + ); - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, PersistentArrayHolder.class.getName()); + protected Object array; //just to help out during the load (ugly, i know) private transient Class elementClass; private transient java.util.List tempList; + /** + * Constructs a PersistentCollection instance for holding an array. + * + * @param session The session + * @param array The array (the persistent "collection"). + */ public PersistentArrayHolder(SessionImplementor session, Object array) { - super(session); + super( session ); this.array = array; setInitialized(); } + /** + * Constructs a PersistentCollection instance for holding an array. + * + * @param session The session + * @param persister The persister for the array + */ + public PersistentArrayHolder(SessionImplementor session, CollectionPersister persister) { + super( session ); + elementClass = persister.getElementClass(); + } + + + + @Override public Serializable getSnapshot(CollectionPersister persister) throws HibernateException { - int length = /*(array==null) ? tempList.size() :*/ Array.getLength(array); - Serializable result = (Serializable) Array.newInstance( persister.getElementClass(), length ); +// final int length = (array==null) ? tempList.size() : Array.getLength( array ); + final int length = Array.getLength( array ); + final Serializable result = (Serializable) Array.newInstance( persister.getElementClass(), length ); for ( int i=0; i deletes = new ArrayList(); - Serializable sn = getSnapshot(); - int snSize = Array.getLength(sn); - int arraySize = Array.getLength(array); + final java.util.List deletes = new ArrayList(); + final Serializable sn = getSnapshot(); + final int snSize = Array.getLength( sn ); + final int arraySize = Array.getLength( array ); int end; if ( snSize > arraySize ) { - for ( int i=arraySize; i= Array.getLength(sn) || Array.get(sn, i)==null ); + final Serializable sn = getSnapshot(); + return Array.get( array, i ) != null && ( i >= Array.getLength( sn ) || Array.get( sn, i ) == null ); } + @Override public boolean needsUpdating(Object entry, int i, Type elemType) throws HibernateException { - Serializable sn = getSnapshot(); - return i semantics for a // ! + @Override + @SuppressWarnings("unchecked") public Iterator getDeletes(CollectionPersister persister, boolean indexIsFormula) throws HibernateException { - //if ( !persister.isOneToMany() ) throw new AssertionFailure("Not implemented for Bags"); - Type elementType = persister.getElementType(); - ArrayList deletes = new ArrayList(); - List sn = (List) getSnapshot(); - Iterator olditer = sn.iterator(); + final Type elementType = persister.getElementType(); + final ArrayList deletes = new ArrayList(); + final List sn = (List) getSnapshot(); + final Iterator olditer = sn.iterator(); int i=0; while ( olditer.hasNext() ) { - Object old = olditer.next(); - Iterator newiter = bag.iterator(); + final Object old = olditer.next(); + final Iterator newiter = bag.iterator(); boolean found = false; - if ( bag.size()>i && elementType.isSame( old, bag.get(i++) ) ) { + if ( bag.size()>i && elementType.isSame( old, bag.get( i++ ) ) ) { //a shortcut if its location didn't change! found = true; } @@ -202,104 +237,91 @@ public class PersistentBag extends AbstractPersistentCollection implements List } } } - if (!found) deletes.add(old); + if ( !found ) { + deletes.add( old ); + } } return deletes.iterator(); } + @Override public boolean needsInserting(Object entry, int i, Type elemType) throws HibernateException { - //if ( !persister.isOneToMany() ) throw new AssertionFailure("Not implemented for Bags"); - List sn = (List) getSnapshot(); - if ( sn.size()>i && elemType.isSame( sn.get(i), entry ) ) { - //a shortcut if its location didn't change! + final List sn = (List) getSnapshot(); + if ( sn.size() > i && elemType.isSame( sn.get( i ), entry ) ) { + //a shortcut if its location didn't change! return false; } else { //search for it //note that this code is incorrect for other than one-to-many - Iterator olditer = sn.iterator(); - while ( olditer.hasNext() ) { - Object old = olditer.next(); - if ( elemType.isSame( old, entry ) ) return false; + for ( Object old : sn ) { + if ( elemType.isSame( old, entry ) ) { + return false; + } } return true; } } + @Override public boolean isRowUpdatePossible() { return false; } + @Override public boolean needsUpdating(Object entry, int i, Type elemType) { - //if ( !persister.isOneToMany() ) throw new AssertionFailure("Not implemented for Bags"); return false; } - /** - * @see java.util.Collection#size() - */ + @Override public int size() { return readSize() ? getCachedSize() : bag.size(); } - /** - * @see java.util.Collection#isEmpty() - */ + @Override public boolean isEmpty() { return readSize() ? getCachedSize()==0 : bag.isEmpty(); } - /** - * @see java.util.Collection#contains(Object) - */ + @Override + @SuppressWarnings("UnnecessaryUnboxing") public boolean contains(Object object) { - Boolean exists = readElementExistence(object); - return exists==null ? - bag.contains(object) : - exists.booleanValue(); + final Boolean exists = readElementExistence( object ); + return exists == null ? bag.contains( object ) : exists.booleanValue(); } - /** - * @see java.util.Collection#iterator() - */ + @Override public Iterator iterator() { read(); return new IteratorProxy( bag.iterator() ); } - /** - * @see java.util.Collection#toArray() - */ + @Override public Object[] toArray() { read(); return bag.toArray(); } - /** - * @see java.util.Collection#toArray(Object[]) - */ + @Override public Object[] toArray(Object[] a) { read(); - return bag.toArray(a); + return bag.toArray( a ); } - /** - * @see java.util.Collection#add(Object) - */ + @Override + @SuppressWarnings("unchecked") public boolean add(Object object) { if ( !isOperationQueueEnabled() ) { write(); - return bag.add(object); + return bag.add( object ); } else { - queueOperation( new SimpleAdd(object) ); + queueOperation( new SimpleAdd( object ) ); return true; } } - /** - * @see java.util.Collection#remove(Object) - */ + @Override public boolean remove(Object o) { initialize( true ); if ( bag.remove( o ) ) { @@ -311,35 +333,33 @@ public class PersistentBag extends AbstractPersistentCollection implements List } } - /** - * @see java.util.Collection#containsAll(Collection) - */ + @Override + @SuppressWarnings("unchecked") public boolean containsAll(Collection c) { read(); - return bag.containsAll(c); + return bag.containsAll( c ); } - /** - * @see java.util.Collection#addAll(Collection) - */ + @Override + @SuppressWarnings("unchecked") public boolean addAll(Collection values) { - if ( values.size()==0 ) return false; + if ( values.size()==0 ) { + return false; + } if ( !isOperationQueueEnabled() ) { write(); - return bag.addAll(values); + return bag.addAll( values ); } else { - Iterator iter = values.iterator(); - while ( iter.hasNext() ) { - queueOperation( new SimpleAdd( iter.next() ) ); + for ( Object value : values ) { + queueOperation( new SimpleAdd( value ) ); } return values.size()>0; } } - /** - * @see java.util.Collection#removeAll(Collection) - */ + @Override + @SuppressWarnings("unchecked") public boolean removeAll(Collection c) { if ( c.size()>0 ) { initialize( true ); @@ -356,9 +376,8 @@ public class PersistentBag extends AbstractPersistentCollection implements List } } - /** - * @see java.util.Collection#retainAll(Collection) - */ + @Override + @SuppressWarnings("unchecked") public boolean retainAll(Collection c) { initialize( true ); if ( bag.retainAll( c ) ) { @@ -370,9 +389,8 @@ public class PersistentBag extends AbstractPersistentCollection implements List } } - /** - * @see java.util.Collection#clear() - */ + @Override + @SuppressWarnings("unchecked") public void clear() { if ( isClearQueueEnabled() ) { queueOperation( new Clear() ); @@ -386,160 +404,161 @@ public class PersistentBag extends AbstractPersistentCollection implements List } } + @Override public Object getIndex(Object entry, int i, CollectionPersister persister) { throw new UnsupportedOperationException("Bags don't have indexes"); } + @Override public Object getElement(Object entry) { return entry; } + @Override public Object getSnapshotElement(Object entry, int i) { - List sn = (List) getSnapshot(); - return sn.get(i); + final List sn = (List) getSnapshot(); + return sn.get( i ); } + /** + * Count how many times the given object occurs in the elements + * + * @param o The object to check + * + * @return The number of occurences. + */ + @SuppressWarnings("UnusedDeclaration") public int occurrences(Object o) { read(); - Iterator iter = bag.iterator(); - int result=0; - while ( iter.hasNext() ) { - if ( o.equals( iter.next() ) ) result++; + final Iterator itr = bag.iterator(); + int result = 0; + while ( itr.hasNext() ) { + if ( o.equals( itr.next() ) ) { + result++; + } } return result; } // List OPERATIONS: - /** - * @see java.util.List#add(int, Object) - */ + @Override + @SuppressWarnings("unchecked") public void add(int i, Object o) { write(); - bag.add(i, o); + bag.add( i, o ); } - /** - * @see java.util.List#addAll(int, Collection) - */ + @Override + @SuppressWarnings("unchecked") public boolean addAll(int i, Collection c) { - if ( c.size()>0 ) { + if ( c.size() > 0 ) { write(); - return bag.addAll(i, c); + return bag.addAll( i, c ); } else { return false; } } - /** - * @see java.util.List#get(int) - */ + @Override + @SuppressWarnings("unchecked") public Object get(int i) { read(); - return bag.get(i); + return bag.get( i ); } - /** - * @see java.util.List#indexOf(Object) - */ + @Override + @SuppressWarnings("unchecked") public int indexOf(Object o) { read(); - return bag.indexOf(o); + return bag.indexOf( o ); } - /** - * @see java.util.List#lastIndexOf(Object) - */ + @Override + @SuppressWarnings("unchecked") public int lastIndexOf(Object o) { read(); - return bag.lastIndexOf(o); + return bag.lastIndexOf( o ); } - /** - * @see java.util.List#listIterator() - */ + @Override + @SuppressWarnings("unchecked") public ListIterator listIterator() { read(); return new ListIteratorProxy( bag.listIterator() ); } - /** - * @see java.util.List#listIterator(int) - */ + @Override + @SuppressWarnings("unchecked") public ListIterator listIterator(int i) { read(); - return new ListIteratorProxy( bag.listIterator(i) ); + return new ListIteratorProxy( bag.listIterator( i ) ); } - /** - * @see java.util.List#remove(int) - */ + @Override + @SuppressWarnings("unchecked") public Object remove(int i) { write(); - return bag.remove(i); + return bag.remove( i ); } - /** - * @see java.util.List#set(int, Object) - */ + @Override + @SuppressWarnings("unchecked") public Object set(int i, Object o) { write(); - return bag.set(i, o); + return bag.set( i, o ); } - /** - * @see java.util.List#subList(int, int) - */ + @Override + @SuppressWarnings("unchecked") public List subList(int start, int end) { read(); - return new ListProxy( bag.subList(start, end) ); + return new ListProxy( bag.subList( start, end ) ); } + @Override + public boolean entryExists(Object entry, int i) { + return entry!=null; + } + + @Override public String toString() { read(); return bag.toString(); } - /*public boolean equals(Object other) { - read(); - return bag.equals(other); - } - - public int hashCode(Object other) { - read(); - return bag.hashCode(); - }*/ - - public boolean entryExists(Object entry, int i) { - return entry!=null; - } - /** * Bag does not respect the collection API and do an * JVM instance comparison to do the equals. * The semantic is broken not to have to initialize a * collection for a simple equals() operation. * @see java.lang.Object#equals(java.lang.Object) + * + * {@inheritDoc} */ + @Override public boolean equals(Object obj) { - return super.equals(obj); + return super.equals( obj ); } - /** - * @see java.lang.Object#hashCode() - */ + @Override public int hashCode() { return super.hashCode(); } final class Clear implements DelayedOperation { + @Override public void operate() { bag.clear(); } + + @Override public Object getAddedInstance() { return null; } + + @Override public Object getOrphan() { throw new UnsupportedOperationException("queued clear cannot be used with orphan delete"); } @@ -551,12 +570,19 @@ public class PersistentBag extends AbstractPersistentCollection implements List public SimpleAdd(Object value) { this.value = value; } + + @Override + @SuppressWarnings("unchecked") public void operate() { - bag.add(value); + bag.add( value ); } + + @Override public Object getAddedInstance() { return value; } + + @Override public Object getOrphan() { return null; } diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentElementHolder.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentElementHolder.java index 6719fec238..0519943f49 100755 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentElementHolder.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentElementHolder.java @@ -52,191 +52,227 @@ import org.hibernate.type.Type; * HHH-7783 for more information. */ @Deprecated +@SuppressWarnings("UnusedDeclaration") public class PersistentElementHolder extends AbstractPersistentCollection { protected Element element; + /** + * Constructs a PersistentElementHolder + * + * @param session The session + * @param element The DOM element + */ + @SuppressWarnings("UnusedDeclaration") public PersistentElementHolder(SessionImplementor session, Element element) { - super(session); + super( session ); this.element = element; setInitialized(); } - public Serializable getSnapshot(CollectionPersister persister) - throws HibernateException { + /** + * Constructs a PersistentElementHolder + * + * @param session The session + * @param persister The collection persister + * @param key The collection key (the fk value) + */ + @SuppressWarnings("UnusedDeclaration") + public PersistentElementHolder(SessionImplementor session, CollectionPersister persister, Serializable key) { + super( session ); + final Element owner = (Element) session.getPersistenceContext().getCollectionOwner( key, persister ); + if ( owner == null ) { + throw new AssertionFailure("null owner"); + } + final String nodeName = persister.getNodeName(); + if ( ".".equals( nodeName ) ) { + element = owner; + } + else { + element = owner.element( nodeName ); + if ( element == null ) { + element = owner.addElement( nodeName ); + } + } + } + + @Override + @SuppressWarnings({"unchecked", "deprecation"}) + public Serializable getSnapshot(CollectionPersister persister) throws HibernateException { final Type elementType = persister.getElementType(); - List elements = element.elements( persister.getElementNodeName() ); - ArrayList snapshot = new ArrayList( elements.size() ); - for ( int i=0; i= elements.size() ) { - result.add(old); + result.add( old ); } else { - Element elem = (Element) elements.get(i); - Object object = elementType.fromXMLNode( elem, persister.getFactory() ); - if ( elementType.isDirty( old, object, getSession() ) ) result.add(old); + final Element elem = (Element) elements.get( i ); + final Object object = elementType.fromXMLNode( elem, persister.getFactory() ); + if ( elementType.isDirty( old, object, getSession() ) ) { + result.add( old ); + } } } return result.iterator(); - } - public boolean needsInserting(Object entry, int i, Type elementType) - throws HibernateException { - ArrayList snapshot = (ArrayList) getSnapshot(); - return i>=snapshot.size() || elementType.isDirty( snapshot.get(i), entry, getSession() ); + @Override + public boolean needsInserting(Object entry, int i, Type elementType) throws HibernateException { + final ArrayList snapshot = (ArrayList) getSnapshot(); + return i >= snapshot.size() + || elementType.isDirty( snapshot.get( i ), entry, getSession() ); } - public boolean needsUpdating(Object entry, int i, Type elementType) - throws HibernateException { + @Override + public boolean needsUpdating(Object entry, int i, Type elementType) throws HibernateException { return false; } + @Override public Object getIndex(Object entry, int i, CollectionPersister persister) { throw new UnsupportedOperationException(); } + @Override public Object getElement(Object entry) { return entry; } + @Override public Object getSnapshotElement(Object entry, int i) { throw new UnsupportedOperationException(); } + @Override public boolean entryExists(Object entry, int i) { return entry!=null; } - } diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentIdentifierBag.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentIdentifierBag.java index beac3d457b..bacd39429f 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentIdentifierBag.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentIdentifierBag.java @@ -53,37 +53,53 @@ import org.hibernate.type.Type; * @author Gavin King */ public class PersistentIdentifierBag extends AbstractPersistentCollection implements List { + protected List values; + protected Map identifiers; - protected List values; //element - protected Map identifiers; //index -> id - - public PersistentIdentifierBag(SessionImplementor session) { - super(session); + /** + * Constructs a PersistentIdentifierBag. This form needed for SOAP libraries, etc + */ + @SuppressWarnings("UnusedDeclaration") + public PersistentIdentifierBag() { } - public PersistentIdentifierBag() {} //needed for SOAP libraries, etc + /** + * Constructs a PersistentIdentifierBag. + * + * @param session The session + */ + public PersistentIdentifierBag(SessionImplementor session) { + super( session ); + } + /** + * Constructs a PersistentIdentifierBag. + * + * @param session The session + * @param coll The base elements + */ + @SuppressWarnings("unchecked") public PersistentIdentifierBag(SessionImplementor session, Collection coll) { - super(session); + super( session ); if (coll instanceof List) { - values = (List) coll; + values = (List) coll; } else { - values = new ArrayList(); - Iterator iter = coll.iterator(); - while ( iter.hasNext() ) { - values.add( iter.next() ); + values = new ArrayList(); + for ( Object element : coll ) { + values.add( element ); } } setInitialized(); - setDirectlyAccessible(true); - identifiers = new HashMap(); + setDirectlyAccessible( true ); + identifiers = new HashMap(); } + @Override public void initializeFromCache(CollectionPersister persister, Serializable disassembled, Object owner) - throws HibernateException { - Serializable[] array = (Serializable[]) disassembled; - int size = array.length; + throws HibernateException { + final Serializable[] array = (Serializable[]) disassembled; + final int size = array.length; beforeInitialize( persister, size ); for ( int i = 0; i < size; i+=2 ) { identifiers.put( @@ -94,20 +110,24 @@ public class PersistentIdentifierBag extends AbstractPersistentCollection implem } } + @Override public Object getIdentifier(Object entry, int i) { return identifiers.get( i ); } + @Override public boolean isWrapper(Object collection) { return values==collection; } + @Override public boolean add(Object o) { write(); - values.add(o); + values.add( o ); return true; } + @Override public void clear() { initialize( true ); if ( ! values.isEmpty() || ! identifiers.isEmpty() ) { @@ -117,31 +137,36 @@ public class PersistentIdentifierBag extends AbstractPersistentCollection implem } } + @Override public boolean contains(Object o) { read(); - return values.contains(o); + return values.contains( o ); } + @Override public boolean containsAll(Collection c) { read(); - return values.containsAll(c); + return values.containsAll( c ); } + @Override public boolean isEmpty() { return readSize() ? getCachedSize()==0 : values.isEmpty(); } + @Override public Iterator iterator() { read(); return new IteratorProxy( values.iterator() ); } + @Override public boolean remove(Object o) { initialize( true ); - int index = values.indexOf(o); - if (index>=0) { - beforeRemove(index); - values.remove(index); + final int index = values.indexOf( o ); + if ( index >= 0 ) { + beforeRemove( index ); + values.remove( index ); dirty(); return true; } @@ -150,12 +175,14 @@ public class PersistentIdentifierBag extends AbstractPersistentCollection implem } } + @Override public boolean removeAll(Collection c) { if ( c.size() > 0 ) { boolean result = false; - Iterator iter = c.iterator(); - while ( iter.hasNext() ) { - if ( remove( iter.next() ) ) result=true; + for ( Object element : c ) { + if ( remove( element ) ) { + result = true; + } } return result; } @@ -164,6 +191,7 @@ public class PersistentIdentifierBag extends AbstractPersistentCollection implem } } + @Override public boolean retainAll(Collection c) { initialize( true ); if ( values.retainAll( c ) ) { @@ -175,168 +203,210 @@ public class PersistentIdentifierBag extends AbstractPersistentCollection implem } } + @Override public int size() { return readSize() ? getCachedSize() : values.size(); } + @Override public Object[] toArray() { read(); return values.toArray(); } + @Override public Object[] toArray(Object[] a) { read(); - return values.toArray(a); + return values.toArray( a ); } + @Override public void beforeInitialize(CollectionPersister persister, int anticipatedSize) { - identifiers = anticipatedSize <= 0 ? new HashMap() : new HashMap( anticipatedSize + 1 + (int)( anticipatedSize * .75f ), .75f ); - values = anticipatedSize <= 0 ? new ArrayList() : new ArrayList( anticipatedSize ); + identifiers = anticipatedSize <= 0 + ? new HashMap() + : new HashMap( anticipatedSize + 1 + (int)( anticipatedSize * .75f ), .75f ); + values = anticipatedSize <= 0 + ? new ArrayList() + : new ArrayList( anticipatedSize ); } + @Override public Serializable disassemble(CollectionPersister persister) throws HibernateException { - Serializable[] result = new Serializable[ values.size() * 2 ]; - int i=0; - for (int j=0; j< values.size(); j++) { - Object value = values.get(j); + final Serializable[] result = new Serializable[ values.size() * 2 ]; + int i = 0; + for ( int j=0; j< values.size(); j++ ) { + final Object value = values.get( j ); result[i++] = persister.getIdentifierType().disassemble( identifiers.get( j ), getSession(), null ); result[i++] = persister.getElementType().disassemble( value, getSession(), null ); } return result; } + @Override public boolean empty() { return values.isEmpty(); } + @Override public Iterator entries(CollectionPersister persister) { return values.iterator(); } + @Override public boolean entryExists(Object entry, int i) { return entry!=null; } + @Override public boolean equalsSnapshot(CollectionPersister persister) throws HibernateException { - Type elementType = persister.getElementType(); - Map snap = (Map) getSnapshot(); - if ( snap.size()!= values.size() ) return false; + final Type elementType = persister.getElementType(); + final Map snap = (Map) getSnapshot(); + if ( snap.size()!= values.size() ) { + return false; + } for ( int i=0; i 0 ) { - Iterator iter = c.iterator(); - while ( iter.hasNext() ) { - add( index++, iter.next() ); + for ( Object element : c ) { + add( index++, element ); } return true; } @@ -345,42 +415,47 @@ public class PersistentIdentifierBag extends AbstractPersistentCollection implem } } + @Override public Object get(int index) { read(); - return values.get(index); + return values.get( index ); } + @Override public int indexOf(Object o) { read(); - return values.indexOf(o); + return values.indexOf( o ); } + @Override public int lastIndexOf(Object o) { read(); - return values.lastIndexOf(o); + return values.lastIndexOf( o ); } + @Override public ListIterator listIterator() { read(); return new ListIteratorProxy( values.listIterator() ); } + @Override public ListIterator listIterator(int index) { read(); - return new ListIteratorProxy( values.listIterator(index) ); + return new ListIteratorProxy( values.listIterator( index ) ); } private void beforeRemove(int index) { - Object removedId = identifiers.get( index ); - int last = values.size()-1; + final Object removedId = identifiers.get( index ); + final int last = values.size()-1; for ( int i=index; i 0 ) { write(); - return values.addAll(c); + return values.addAll( c ); } else { return false; } } + @Override public void afterRowInsert( - CollectionPersister persister, - Object entry, - int i) - throws HibernateException { + CollectionPersister persister, + Object entry, + int i) throws HibernateException { //TODO: if we are using identity columns, fetch the identifier } diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentIndexedElementHolder.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentIndexedElementHolder.java index 8d1cdf72a6..5fca1d28dc 100755 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentIndexedElementHolder.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentIndexedElementHolder.java @@ -57,16 +57,52 @@ import org.hibernate.type.XmlRepresentableType; @Deprecated public abstract class PersistentIndexedElementHolder extends AbstractPersistentCollection { protected Element element; - + + /** + * Constructs a PersistentIndexedElementHolder. + * + * @param session The session + * @param element The DOM element being wrapped + */ public PersistentIndexedElementHolder(SessionImplementor session, Element element) { - super(session); + super( session ); this.element = element; setInitialized(); } - + + /** + * Constructs a PersistentIndexedElementHolder. + * + * @param session The session + * @param persister The collection persister + * @param key The collection key (fk value)@throws HibernateException + */ + public PersistentIndexedElementHolder(SessionImplementor session, CollectionPersister persister, Serializable key) { + super( session ); + final Element owner = (Element) session.getPersistenceContext().getCollectionOwner( key, persister ); + if ( owner == null ) { + throw new AssertionFailure( "null owner" ); + } + + final String nodeName = persister.getNodeName(); + if ( ".".equals( nodeName ) ) { + element = owner; + } + else { + element = owner.element( nodeName ); + if ( element == null ) { + element = owner.addElement( nodeName ); + } + } + } + + /** + * A struct representing the index/value pair. + */ public static final class IndexedValue { - String index; - Object value; + final String index; + final Object value; + IndexedValue(String index, Object value) { this.index = index; this.value = value; @@ -74,182 +110,189 @@ public abstract class PersistentIndexedElementHolder extends AbstractPersistentC } protected static String getIndex(Element element, String indexNodeName, int i) { - if (indexNodeName!=null) { - return element.attributeValue(indexNodeName); + if ( indexNodeName != null ) { + return element.attributeValue( indexNodeName ); } else { - return Integer.toString(i); + return Integer.toString( i ); } } protected static void setIndex(Element element, String indexNodeName, String index) { - if (indexNodeName!=null) element.addAttribute(indexNodeName, index); + if ( indexNodeName != null ) { + element.addAttribute( indexNodeName, index ); + } } - + protected static String getIndexAttributeName(CollectionPersister persister) { - String node = persister.getIndexNodeName(); - return node==null ? null : node.substring(1); + final String node = persister.getIndexNodeName(); + return node == null ? null : node.substring( 1 ); } - - public Serializable getSnapshot(CollectionPersister persister) - throws HibernateException { - + + @Override + @SuppressWarnings({"unchecked", "deprecation"}) + public Serializable getSnapshot(CollectionPersister persister) throws HibernateException { final Type elementType = persister.getElementType(); - String indexNode = getIndexAttributeName(persister); - List elements = element.elements( persister.getElementNodeName() ); - HashMap snapshot = new HashMap( elements.size() ); + final String indexNode = getIndexAttributeName( persister ); + final List elements = element.elements( persister.getElementNodeName() ); + final HashMap snapshot = new HashMap( elements.size() ); for ( int i=0; i0; } } - /** - * @see java.util.List#addAll(int, Collection) - */ + @Override + @SuppressWarnings("unchecked") public boolean addAll(int index, Collection coll) { if ( coll.size()>0 ) { write(); - return list.addAll(index, coll); + return list.addAll( index, coll ); } else { return false; } } - /** - * @see java.util.List#removeAll(Collection) - */ + @Override + @SuppressWarnings("unchecked") public boolean removeAll(Collection coll) { if ( coll.size()>0 ) { initialize( true ); @@ -251,9 +253,8 @@ public class PersistentList extends AbstractPersistentCollection implements List } } - /** - * @see java.util.List#retainAll(Collection) - */ + @Override + @SuppressWarnings("unchecked") public boolean retainAll(Collection coll) { initialize( true ); if ( list.retainAll( coll ) ) { @@ -265,9 +266,8 @@ public class PersistentList extends AbstractPersistentCollection implements List } } - /** - * @see java.util.List#clear() - */ + @Override + @SuppressWarnings("unchecked") public void clear() { if ( isClearQueueEnabled() ) { queueOperation( new Clear() ); @@ -281,166 +281,167 @@ public class PersistentList extends AbstractPersistentCollection implements List } } - /** - * @see java.util.List#get(int) - */ + @Override + @SuppressWarnings("unchecked") public Object get(int index) { - if (index<0) { - throw new ArrayIndexOutOfBoundsException("negative index"); + if ( index < 0 ) { + throw new ArrayIndexOutOfBoundsException( "negative index" ); } - Object result = readElementByIndex( index ); - return result==UNKNOWN ? list.get(index) : result; + final Object result = readElementByIndex( index ); + return result == UNKNOWN ? list.get( index ) : result; } - /** - * @see java.util.List#set(int, Object) - */ + @Override + @SuppressWarnings("unchecked") public Object set(int index, Object value) { if (index<0) { throw new ArrayIndexOutOfBoundsException("negative index"); } - Object old = isPutQueueEnabled() ? readElementByIndex( index ) : UNKNOWN; + + final Object old = isPutQueueEnabled() ? readElementByIndex( index ) : UNKNOWN; + if ( old==UNKNOWN ) { write(); - return list.set(index, value); + return list.set( index, value ); } else { - queueOperation( new Set(index, value, old) ); + queueOperation( new Set( index, value, old ) ); return old; } } - /** - * @see java.util.List#add(int, Object) - */ + @Override + @SuppressWarnings("unchecked") + public Object remove(int index) { + if ( index < 0 ) { + throw new ArrayIndexOutOfBoundsException( "negative index" ); + } + final Object old = isPutQueueEnabled() ? readElementByIndex( index ) : UNKNOWN; + if ( old == UNKNOWN ) { + write(); + return list.remove( index ); + } + else { + queueOperation( new Remove( index, old ) ); + return old; + } + } + + @Override + @SuppressWarnings("unchecked") public void add(int index, Object value) { - if (index<0) { - throw new ArrayIndexOutOfBoundsException("negative index"); + if ( index < 0 ) { + throw new ArrayIndexOutOfBoundsException( "negative index" ); } if ( !isOperationQueueEnabled() ) { write(); - list.add(index, value); + list.add( index, value ); } else { - queueOperation( new Add(index, value) ); + queueOperation( new Add( index, value ) ); } } - /** - * @see java.util.List#remove(int) - */ - public Object remove(int index) { - if (index<0) { - throw new ArrayIndexOutOfBoundsException("negative index"); - } - Object old = isPutQueueEnabled() ? - readElementByIndex( index ) : UNKNOWN; - if ( old==UNKNOWN ) { - write(); - return list.remove(index); - } - else { - queueOperation( new Remove(index, old) ); - return old; - } - } - - /** - * @see java.util.List#indexOf(Object) - */ + @Override + @SuppressWarnings("unchecked") public int indexOf(Object value) { read(); - return list.indexOf(value); + return list.indexOf( value ); } - /** - * @see java.util.List#lastIndexOf(Object) - */ + @Override + @SuppressWarnings("unchecked") public int lastIndexOf(Object value) { read(); - return list.lastIndexOf(value); + return list.lastIndexOf( value ); } - /** - * @see java.util.List#listIterator() - */ + @Override + @SuppressWarnings("unchecked") public ListIterator listIterator() { read(); return new ListIteratorProxy( list.listIterator() ); } - /** - * @see java.util.List#listIterator(int) - */ + @Override + @SuppressWarnings("unchecked") public ListIterator listIterator(int index) { read(); - return new ListIteratorProxy( list.listIterator(index) ); + return new ListIteratorProxy( list.listIterator( index ) ); } - /** - * @see java.util.List#subList(int, int) - */ + @Override + @SuppressWarnings("unchecked") public java.util.List subList(int from, int to) { read(); - return new ListProxy( list.subList(from, to) ); + return new ListProxy( list.subList( from, to ) ); } + @Override public boolean empty() { return list.isEmpty(); } + @Override public String toString() { read(); return list.toString(); } + @Override + @SuppressWarnings("unchecked") public Object readFrom(ResultSet rs, CollectionPersister persister, CollectionAliases descriptor, Object owner) - throws HibernateException, SQLException { - Object element = persister.readElement( rs, owner, descriptor.getSuffixedElementAliases(), getSession() ) ; - int index = (Integer) persister.readIndex( rs, descriptor.getSuffixedIndexAliases(), getSession() ); + throws HibernateException, SQLException { + final Object element = persister.readElement( rs, owner, descriptor.getSuffixedElementAliases(), getSession() ) ; + final int index = (Integer) persister.readIndex( rs, descriptor.getSuffixedIndexAliases(), getSession() ); //pad with nulls from the current last element up to the new index for ( int i = list.size(); i<=index; i++) { - list.add(i, null); + list.add( i, null ); } - list.set(index, element); + list.set( index, element ); return element; } + @Override + @SuppressWarnings("unchecked") public Iterator entries(CollectionPersister persister) { return list.iterator(); } + @Override + @SuppressWarnings("unchecked") public void initializeFromCache(CollectionPersister persister, Serializable disassembled, Object owner) - throws HibernateException { - Serializable[] array = ( Serializable[] ) disassembled; - int size = array.length; + throws HibernateException { + final Serializable[] array = (Serializable[]) disassembled; + final int size = array.length; beforeInitialize( persister, size ); - for ( int i = 0; i < size; i++ ) { - list.add( persister.getElementType().assemble( array[i], getSession(), owner ) ); + for ( Serializable arrayElement : array ) { + list.add( persister.getElementType().assemble( arrayElement, getSession(), owner ) ); } } - public Serializable disassemble(CollectionPersister persister) - throws HibernateException { - - int length = list.size(); - Serializable[] result = new Serializable[length]; + @Override + @SuppressWarnings("unchecked") + public Serializable disassemble(CollectionPersister persister) throws HibernateException { + final int length = list.size(); + final Serializable[] result = new Serializable[length]; for ( int i=0; i list.size() ) { for ( int i=list.size(); i= sn.size() || sn.get(i)==null ); + return list.get( i ) != null && ( i >= sn.size() || sn.get( i ) == null ); } + @Override public boolean needsUpdating(Object entry, int i, Type elemType) throws HibernateException { final List sn = (List) getSnapshot(); - return iHHH-7783 for more information. */ @Deprecated +@SuppressWarnings({"UnusedDeclaration", "deprecation"}) public class PersistentListElementHolder extends PersistentIndexedElementHolder { + /** + * Constructs a PersistentListElementHolder. + * + * @param session The session + * @param element The owning DOM element + */ + @SuppressWarnings("UnusedDeclaration") public PersistentListElementHolder(SessionImplementor session, Element element) { super( session, element ); } - public PersistentListElementHolder(SessionImplementor session, CollectionPersister persister, - Serializable key) throws HibernateException { + /** + * Constructs a PersistentListElementHolder. + * + * @param session The session + * @param persister The collection persister + * @param key The collection key (fk value) + */ + @SuppressWarnings("UnusedDeclaration") + public PersistentListElementHolder(SessionImplementor session, CollectionPersister persister, Serializable key) { super( session, persister, key ); } + @Override + @SuppressWarnings("deprecation") public void initializeFromCache(CollectionPersister persister, Serializable disassembled, Object owner) - throws HibernateException { - - Type elementType = persister.getElementType(); - final String indexNodeName = getIndexAttributeName(persister); - Serializable[] cached = (Serializable[]) disassembled; + throws HibernateException { + final Type elementType = persister.getElementType(); + final String indexNodeName = getIndexAttributeName( persister ); + final Serializable[] cached = (Serializable[]) disassembled; for ( int i=0; i0 ) { + if ( puts.size() > 0 ) { initialize( true ); - Iterator itr = puts.entrySet().iterator(); - while ( itr.hasNext() ) { - Map.Entry entry = ( Entry ) itr.next(); + for ( Object o : puts.entrySet() ) { + final Entry entry = (Entry) o; put( entry.getKey(), entry.getValue() ); } } } - /** - * @see java.util.Map#clear() - */ + @Override + @SuppressWarnings("unchecked") public void clear() { if ( isClearQueueEnabled() ) { queueOperation( new Clear() ); @@ -238,34 +236,35 @@ public class PersistentMap extends AbstractPersistentCollection implements Map { } } - /** - * @see java.util.Map#keySet() - */ + @Override + @SuppressWarnings("unchecked") public Set keySet() { read(); return new SetProxy( map.keySet() ); } - /** - * @see java.util.Map#values() - */ + @Override + @SuppressWarnings("unchecked") public Collection values() { read(); return new SetProxy( map.values() ); } - /** - * @see java.util.Map#entrySet() - */ + @Override + @SuppressWarnings("unchecked") public Set entrySet() { read(); return new EntrySetProxy( map.entrySet() ); } + @Override + @SuppressWarnings("unchecked") public boolean empty() { return map.isEmpty(); } + @Override + @SuppressWarnings("unchecked") public String toString() { read(); return map.toString(); @@ -273,6 +272,8 @@ public class PersistentMap extends AbstractPersistentCollection implements Map { private transient List loadingEntries; + @Override + @SuppressWarnings("unchecked") public Object readFrom( ResultSet rs, CollectionPersister persister, @@ -296,80 +297,134 @@ public class PersistentMap extends AbstractPersistentCollection implements Map { for ( Object[] entry : loadingEntries ) { map.put( entry[0], entry[1] ); } - loadingEntries = null; + loadingEntries = null; } return super.endRead(); } + @Override + @SuppressWarnings("unchecked") public Iterator entries(CollectionPersister persister) { return map.entrySet().iterator(); } - /** a wrapper for Map.Entry sets */ + /** + * a wrapper for Map.Entry sets + */ class EntrySetProxy implements Set { private final Set set; EntrySetProxy(Set set) { this.set=set; } + + @Override + @SuppressWarnings("unchecked") public boolean add(Object entry) { //write(); -- doesn't - return set.add(entry); + return set.add( entry ); } + + @Override + @SuppressWarnings("unchecked") public boolean addAll(Collection entries) { //write(); -- doesn't - return set.addAll(entries); + return set.addAll( entries ); } + + @Override + @SuppressWarnings("unchecked") public void clear() { write(); set.clear(); } + + @Override + @SuppressWarnings("unchecked") public boolean contains(Object entry) { - return set.contains(entry); + return set.contains( entry ); } + + @Override + @SuppressWarnings("unchecked") public boolean containsAll(Collection entries) { - return set.containsAll(entries); + return set.containsAll( entries ); } + + @Override + @SuppressWarnings("unchecked") public boolean isEmpty() { return set.isEmpty(); } + + @Override + @SuppressWarnings("unchecked") public Iterator iterator() { return new EntryIteratorProxy( set.iterator() ); } + + @Override + @SuppressWarnings("unchecked") public boolean remove(Object entry) { write(); - return set.remove(entry); + return set.remove( entry ); } + + @Override + @SuppressWarnings("unchecked") public boolean removeAll(Collection entries) { write(); - return set.removeAll(entries); + return set.removeAll( entries ); } + + @Override + @SuppressWarnings("unchecked") public boolean retainAll(Collection entries) { write(); - return set.retainAll(entries); + return set.retainAll( entries ); } + + @Override + @SuppressWarnings("unchecked") public int size() { return set.size(); } + // amazingly, these two will work because AbstractCollection // uses iterator() to fill the array + + @Override + @SuppressWarnings("unchecked") public Object[] toArray() { return set.toArray(); } + + @Override + @SuppressWarnings("unchecked") public Object[] toArray(Object[] array) { - return set.toArray(array); + return set.toArray( array ); } } + final class EntryIteratorProxy implements Iterator { private final Iterator iter; EntryIteratorProxy(Iterator iter) { this.iter=iter; } + + @Override + @SuppressWarnings("unchecked") public boolean hasNext() { return iter.hasNext(); } + + @Override + @SuppressWarnings("unchecked") public Object next() { return new MapEntryProxy( (Map.Entry) iter.next() ); } + + @Override + @SuppressWarnings("unchecked") public void remove() { write(); iter.remove(); @@ -381,37 +436,63 @@ public class PersistentMap extends AbstractPersistentCollection implements Map { MapEntryProxy( Map.Entry me ) { this.me = me; } - public Object getKey() { return me.getKey(); } - public Object getValue() { return me.getValue(); } - public boolean equals(Object o) { return me.equals(o); } - public int hashCode() { return me.hashCode(); } + + @Override + @SuppressWarnings("unchecked") + public Object getKey() { + return me.getKey(); + } + + @Override + @SuppressWarnings("unchecked") + public Object getValue() { + return me.getValue(); + } + + @Override + @SuppressWarnings({"unchecked", "EqualsWhichDoesntCheckParameterClass"}) + public boolean equals(Object o) { + return me.equals( o ); + } + + @Override + @SuppressWarnings("unchecked") + public int hashCode() { + return me.hashCode(); + } + // finally, what it's all about... + @Override + @SuppressWarnings("unchecked") public Object setValue(Object value) { write(); - return me.setValue(value); + return me.setValue( value ); } } + @Override + @SuppressWarnings("unchecked") public void initializeFromCache(CollectionPersister persister, Serializable disassembled, Object owner) - throws HibernateException { - Serializable[] array = ( Serializable[] ) disassembled; - int size = array.length; + throws HibernateException { + final Serializable[] array = (Serializable[]) disassembled; + final int size = array.length; beforeInitialize( persister, size ); for ( int i = 0; i < size; i+=2 ) { map.put( persister.getIndexType().assemble( array[i], getSession(), owner ), persister.getElementType().assemble( array[i+1], getSession(), owner ) - ); + ); } } + @Override + @SuppressWarnings("unchecked") public Serializable disassemble(CollectionPersister persister) throws HibernateException { - - Serializable[] result = new Serializable[ map.size() * 2 ]; - Iterator iter = map.entrySet().iterator(); + final Serializable[] result = new Serializable[ map.size() * 2 ]; + final Iterator itr = map.entrySet().iterator(); int i=0; - while ( iter.hasNext() ) { - Map.Entry e = (Map.Entry) iter.next(); + while ( itr.hasNext() ) { + final Map.Entry e = (Map.Entry) itr.next(); result[i++] = persister.getIndexType().disassemble( e.getKey(), getSession(), null ); result[i++] = persister.getElementType().disassemble( e.getValue(), getSession(), null ); } @@ -419,74 +500,92 @@ public class PersistentMap extends AbstractPersistentCollection implements Map { } - public Iterator getDeletes(CollectionPersister persister, boolean indexIsFormula) - throws HibernateException { - List deletes = new ArrayList(); - Iterator iter = ( (Map) getSnapshot() ).entrySet().iterator(); - while ( iter.hasNext() ) { - Map.Entry e = (Map.Entry) iter.next(); - Object key = e.getKey(); - if ( e.getValue()!=null && map.get(key)==null ) { + @Override + @SuppressWarnings("unchecked") + public Iterator getDeletes(CollectionPersister persister, boolean indexIsFormula) throws HibernateException { + final List deletes = new ArrayList(); + for ( Object o : ((Map) getSnapshot()).entrySet() ) { + final Entry e = (Entry) o; + final Object key = e.getKey(); + if ( e.getValue() != null && map.get( key ) == null ) { deletes.add( indexIsFormula ? e.getValue() : key ); } } return deletes.iterator(); } - public boolean needsInserting(Object entry, int i, Type elemType) - throws HibernateException { + @Override + @SuppressWarnings("unchecked") + public boolean needsInserting(Object entry, int i, Type elemType) throws HibernateException { final Map sn = (Map) getSnapshot(); - Map.Entry e = (Map.Entry) entry; - return e.getValue()!=null && sn.get( e.getKey() )==null; + final Map.Entry e = (Map.Entry) entry; + return e.getValue() != null && sn.get( e.getKey() ) == null; } - public boolean needsUpdating(Object entry, int i, Type elemType) - throws HibernateException { + @Override + @SuppressWarnings("unchecked") + public boolean needsUpdating(Object entry, int i, Type elemType) throws HibernateException { final Map sn = (Map) getSnapshot(); - Map.Entry e = (Map.Entry) entry; - Object snValue = sn.get( e.getKey() ); - return e.getValue()!=null && - snValue!=null && - elemType.isDirty( snValue, e.getValue(), getSession() ); + final Map.Entry e = (Map.Entry) entry; + final Object snValue = sn.get( e.getKey() ); + return e.getValue() != null + && snValue != null + && elemType.isDirty( snValue, e.getValue(), getSession() ); } - + @Override + @SuppressWarnings("unchecked") public Object getIndex(Object entry, int i, CollectionPersister persister) { return ( (Map.Entry) entry ).getKey(); } + @Override + @SuppressWarnings("unchecked") public Object getElement(Object entry) { return ( (Map.Entry) entry ).getValue(); } + @Override + @SuppressWarnings("unchecked") public Object getSnapshotElement(Object entry, int i) { final Map sn = (Map) getSnapshot(); return sn.get( ( (Map.Entry) entry ).getKey() ); } + @Override + @SuppressWarnings({"unchecked", "EqualsWhichDoesntCheckParameterClass"}) public boolean equals(Object other) { read(); - return map.equals(other); + return map.equals( other ); } + @Override + @SuppressWarnings("unchecked") public int hashCode() { read(); return map.hashCode(); } + @Override + @SuppressWarnings("unchecked") public boolean entryExists(Object entry, int i) { - return ( (Map.Entry) entry ).getValue()!=null; + return ( (Map.Entry) entry ).getValue() != null; } final class Clear implements DelayedOperation { + @Override public void operate() { map.clear(); } + + @Override public Object getAddedInstance() { return null; } + + @Override public Object getOrphan() { - throw new UnsupportedOperationException("queued clear cannot be used with orphan delete"); + throw new UnsupportedOperationException( "queued clear cannot be used with orphan delete" ); } } @@ -500,12 +599,21 @@ public class PersistentMap extends AbstractPersistentCollection implements Map { this.value = value; this.old = old; } + + @Override + @SuppressWarnings("unchecked") public void operate() { - map.put(index, value); + map.put( index, value ); } + + @Override + @SuppressWarnings("unchecked") public Object getAddedInstance() { return value; } + + @Override + @SuppressWarnings("unchecked") public Object getOrphan() { return old; } @@ -519,12 +627,19 @@ public class PersistentMap extends AbstractPersistentCollection implements Map { this.index = index; this.old = old; } + + @Override + @SuppressWarnings("unchecked") public void operate() { - map.remove(index); + map.remove( index ); } + + @Override public Object getAddedInstance() { return null; } + + @Override public Object getOrphan() { return old; } diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentMapElementHolder.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentMapElementHolder.java index 4ce5e02c26..d532ae3485 100755 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentMapElementHolder.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentMapElementHolder.java @@ -35,60 +35,76 @@ import org.hibernate.type.Type; import org.hibernate.type.XmlRepresentableType; /** + * Wraps a collection of DOM sub-elements as a Map + * * @author Gavin King * * @deprecated To be removed in 5. Removed as part of removing the notion of DOM entity-mode. See Jira issues * HHH-7782 and * HHH-7783 for more information. */ +@SuppressWarnings({"UnusedDeclaration", "deprecation"}) @Deprecated public class PersistentMapElementHolder extends PersistentIndexedElementHolder { + /** + * Constructs a PersistentMapElementHolder. + * + * @param session The session + * @param element The owning DOM element + */ public PersistentMapElementHolder(SessionImplementor session, Element element) { super( session, element ); } - public PersistentMapElementHolder(SessionImplementor session, CollectionPersister persister, - Serializable key) throws HibernateException { + /** + * Constructs a PersistentMapElementHolder. + * + * @param session The session + * @param persister The collection persister + * @param key The collection key (fk value) + */ + public PersistentMapElementHolder(SessionImplementor session, CollectionPersister persister, Serializable key) { super( session, persister, key ); } - public void initializeFromCache(CollectionPersister persister, Serializable disassembled, Object owner) - throws HibernateException { - - Type elementType = persister.getElementType(); - Type indexType = persister.getIndexType(); - final String indexNodeName = getIndexAttributeName(persister); + @Override + @SuppressWarnings("unchecked") + public void initializeFromCache(CollectionPersister persister, Serializable disassembled, Object owner) { + final Type elementType = persister.getElementType(); + final Type indexType = persister.getIndexType(); + final String indexNodeName = getIndexAttributeName( persister ); - Serializable[] cached = (Serializable[]) disassembled; + final Serializable[] cached = (Serializable[]) disassembled; + int i = 0; + while ( i < cached.length ) { + final Object index = indexType.assemble( cached[i++], getSession(), owner ); + final Object object = elementType.assemble( cached[i++], getSession(), owner ); - for ( int i=0; i 0 ) { initialize( true ); @@ -272,9 +267,8 @@ public class PersistentSet extends AbstractPersistentCollection implements java. } } - /** - * @see java.util.Set#retainAll(Collection) - */ + @Override + @SuppressWarnings("unchecked") public boolean retainAll(Collection coll) { initialize( true ); if ( set.retainAll( coll ) ) { @@ -286,9 +280,8 @@ public class PersistentSet extends AbstractPersistentCollection implements java. } } - /** - * @see java.util.Set#removeAll(Collection) - */ + @Override + @SuppressWarnings("unchecked") public boolean removeAll(Collection coll) { if ( coll.size() > 0 ) { initialize( true ); @@ -305,9 +298,8 @@ public class PersistentSet extends AbstractPersistentCollection implements java. } } - /** - * @see java.util.Set#clear() - */ + @Override + @SuppressWarnings("unchecked") public void clear() { if ( isClearQueueEnabled() ) { queueOperation( new Clear() ); @@ -321,129 +313,168 @@ public class PersistentSet extends AbstractPersistentCollection implements java. } } + @Override + @SuppressWarnings("unchecked") public String toString() { - //if (needLoading) return "asleep"; read(); return set.toString(); } + @Override + @SuppressWarnings("unchecked") public Object readFrom( - ResultSet rs, - CollectionPersister persister, - CollectionAliases descriptor, - Object owner) throws HibernateException, SQLException { - Object element = persister.readElement( rs, owner, descriptor.getSuffixedElementAliases(), getSession() ); - if (element!=null) tempList.add(element); + ResultSet rs, + CollectionPersister persister, + CollectionAliases descriptor, + Object owner) throws HibernateException, SQLException { + final Object element = persister.readElement( rs, owner, descriptor.getSuffixedElementAliases(), getSession() ); + if ( element != null ) { + tempList.add( element ); + } return element; } + @Override + @SuppressWarnings("unchecked") public void beginRead() { super.beginRead(); tempList = new ArrayList(); } + @Override + @SuppressWarnings("unchecked") public boolean endRead() { - set.addAll(tempList); + set.addAll( tempList ); tempList = null; setInitialized(); return true; } + @Override + @SuppressWarnings("unchecked") public Iterator entries(CollectionPersister persister) { return set.iterator(); } - public Serializable disassemble(CollectionPersister persister) - throws HibernateException { - - Serializable[] result = new Serializable[ set.size() ]; - Iterator iter = set.iterator(); + @Override + @SuppressWarnings("unchecked") + public Serializable disassemble(CollectionPersister persister) throws HibernateException { + final Serializable[] result = new Serializable[ set.size() ]; + final Iterator itr = set.iterator(); int i=0; - while ( iter.hasNext() ) { - result[i++] = persister.getElementType().disassemble( iter.next(), getSession(), null ); + while ( itr.hasNext() ) { + result[i++] = persister.getElementType().disassemble( itr.next(), getSession(), null ); } return result; - } + @Override + @SuppressWarnings("unchecked") public Iterator getDeletes(CollectionPersister persister, boolean indexIsFormula) throws HibernateException { - Type elementType = persister.getElementType(); + final Type elementType = persister.getElementType(); final java.util.Map sn = (java.util.Map) getSnapshot(); - ArrayList deletes = new ArrayList( sn.size() ); - Iterator iter = sn.keySet().iterator(); - while ( iter.hasNext() ) { - Object test = iter.next(); - if ( !set.contains(test) ) { + final ArrayList deletes = new ArrayList( sn.size() ); + + Iterator itr = sn.keySet().iterator(); + while ( itr.hasNext() ) { + final Object test = itr.next(); + if ( !set.contains( test ) ) { // the element has been removed from the set - deletes.add(test); + deletes.add( test ); } } - iter = set.iterator(); - while ( iter.hasNext() ) { - Object test = iter.next(); - Object oldValue = sn.get(test); + + itr = set.iterator(); + while ( itr.hasNext() ) { + final Object test = itr.next(); + final Object oldValue = sn.get( test ); if ( oldValue!=null && elementType.isDirty( test, oldValue, getSession() ) ) { // the element has changed - deletes.add(oldValue); + deletes.add( oldValue ); } } + return deletes.iterator(); } + @Override + @SuppressWarnings("unchecked") public boolean needsInserting(Object entry, int i, Type elemType) throws HibernateException { - final java.util.Map sn = (java.util.Map) getSnapshot(); - Object oldValue = sn.get(entry); + final Object oldValue = ( (java.util.Map) getSnapshot() ).get( entry ); // note that it might be better to iterate the snapshot but this is safe, // assuming the user implements equals() properly, as required by the Set // contract! - return oldValue==null || elemType.isDirty( oldValue, entry, getSession() ); + return oldValue == null || elemType.isDirty( oldValue, entry, getSession() ); } + @Override + @SuppressWarnings("unchecked") public boolean needsUpdating(Object entry, int i, Type elemType) { return false; } + @Override + @SuppressWarnings("unchecked") public boolean isRowUpdatePossible() { return false; } + @Override + @SuppressWarnings("unchecked") public Object getIndex(Object entry, int i, CollectionPersister persister) { throw new UnsupportedOperationException("Sets don't have indexes"); } + @Override + @SuppressWarnings("unchecked") public Object getElement(Object entry) { return entry; } + @Override + @SuppressWarnings("unchecked") public Object getSnapshotElement(Object entry, int i) { throw new UnsupportedOperationException("Sets don't support updating by element"); } + @Override + @SuppressWarnings({"unchecked", "EqualsWhichDoesntCheckParameterClass"}) public boolean equals(Object other) { read(); - return set.equals(other); + return set.equals( other ); } + @Override + @SuppressWarnings("unchecked") public int hashCode() { read(); return set.hashCode(); } + @Override + @SuppressWarnings("unchecked") public boolean entryExists(Object key, int i) { return true; } + @Override + @SuppressWarnings("unchecked") public boolean isWrapper(Object collection) { return set==collection; } final class Clear implements DelayedOperation { + @Override public void operate() { set.clear(); } + + @Override public Object getAddedInstance() { return null; } + + @Override public Object getOrphan() { throw new UnsupportedOperationException("queued clear cannot be used with orphan delete"); } @@ -455,12 +486,19 @@ public class PersistentSet extends AbstractPersistentCollection implements java. public SimpleAdd(Object value) { this.value = value; } + + @Override + @SuppressWarnings("unchecked") public void operate() { - set.add(value); + set.add( value ); } + + @Override public Object getAddedInstance() { return value; } + + @Override public Object getOrphan() { return null; } @@ -472,12 +510,19 @@ public class PersistentSet extends AbstractPersistentCollection implements java. public SimpleRemove(Object value) { this.value = value; } + + @Override + @SuppressWarnings("unchecked") public void operate() { - set.remove(value); + set.remove( value ); } + + @Override public Object getAddedInstance() { return null; } + + @Override public Object getOrphan() { return value; } diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentSortedMap.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentSortedMap.java index 7975ad5e58..0be01cf2d9 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentSortedMap.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentSortedMap.java @@ -26,7 +26,6 @@ package org.hibernate.collection.internal; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; -import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; @@ -45,167 +44,212 @@ import org.hibernate.persister.collection.BasicCollectionPersister; * @author e */ public class PersistentSortedMap extends PersistentMap implements SortedMap { - protected Comparator comparator; + /** + * Constructs a PersistentSortedMap. This form needed for SOAP libraries, etc + */ + @SuppressWarnings("UnusedDeclaration") + public PersistentSortedMap() { + } + + /** + * Constructs a PersistentSortedMap. + * + * @param session The session + */ + public PersistentSortedMap(SessionImplementor session) { + super( session ); + } + + /** + * Constructs a PersistentSortedMap. + * + * @param session The session + * @param map The underlying map data + */ + public PersistentSortedMap(SessionImplementor session, SortedMap map) { + super( session, map ); + comparator = map.comparator(); + } + + @SuppressWarnings({"unchecked", "UnusedParameters"}) protected Serializable snapshot(BasicCollectionPersister persister, EntityMode entityMode) throws HibernateException { - TreeMap clonedMap = new TreeMap(comparator); - Iterator iter = map.entrySet().iterator(); - while ( iter.hasNext() ) { - Map.Entry e = (Map.Entry) iter.next(); + final TreeMap clonedMap = new TreeMap( comparator ); + for ( Object o : map.entrySet() ) { + final Entry e = (Entry) o; clonedMap.put( e.getKey(), persister.getElementType().deepCopy( e.getValue(), persister.getFactory() ) ); } return clonedMap; } - public PersistentSortedMap(SessionImplementor session) { - super(session); - } - public void setComparator(Comparator comparator) { this.comparator = comparator; } - public PersistentSortedMap(SessionImplementor session, SortedMap map) { - super(session, map); - comparator = map.comparator(); - } - - public PersistentSortedMap() {} //needed for SOAP libraries, etc - - /** - * @see PersistentSortedMap#comparator() - */ + @Override public Comparator comparator() { return comparator; } - /** - * @see PersistentSortedMap#subMap(Object, Object) - */ + @Override + @SuppressWarnings("unchecked") public SortedMap subMap(Object fromKey, Object toKey) { read(); - SortedMap m = ( (SortedMap) map ).subMap(fromKey, toKey); - return new SortedSubMap(m); + final SortedMap subMap = ( (SortedMap) map ).subMap( fromKey, toKey ); + return new SortedSubMap( subMap ); } - /** - * @see PersistentSortedMap#headMap(Object) - */ + @Override + @SuppressWarnings("unchecked") public SortedMap headMap(Object toKey) { read(); - SortedMap m; - m = ( (SortedMap) map ).headMap(toKey); - return new SortedSubMap(m); + final SortedMap headMap = ( (SortedMap) map ).headMap( toKey ); + return new SortedSubMap( headMap ); } - /** - * @see PersistentSortedMap#tailMap(Object) - */ + @Override + @SuppressWarnings("unchecked") public SortedMap tailMap(Object fromKey) { read(); - SortedMap m; - m = ( (SortedMap) map ).tailMap(fromKey); - return new SortedSubMap(m); + final SortedMap tailMap = ( (SortedMap) map ).tailMap( fromKey ); + return new SortedSubMap( tailMap ); } - /** - * @see PersistentSortedMap#firstKey() - */ + @Override + @SuppressWarnings("unchecked") public Object firstKey() { read(); return ( (SortedMap) map ).firstKey(); } - /** - * @see PersistentSortedMap#lastKey() - */ + @Override + @SuppressWarnings("unchecked") public Object lastKey() { read(); return ( (SortedMap) map ).lastKey(); } class SortedSubMap implements SortedMap { + SortedMap subMap; - SortedMap submap; - - SortedSubMap(SortedMap m) { - this.submap = m; + SortedSubMap(SortedMap subMap) { + this.subMap = subMap; } - // from Map + + @Override + @SuppressWarnings("unchecked") public int size() { - return submap.size(); + return subMap.size(); } + + @Override + @SuppressWarnings("unchecked") public boolean isEmpty() { - return submap.isEmpty(); + return subMap.isEmpty(); } + + @Override + @SuppressWarnings("unchecked") public boolean containsKey(Object key) { - return submap.containsKey(key); + return subMap.containsKey( key ); } + + @Override + @SuppressWarnings("unchecked") public boolean containsValue(Object key) { - return submap.containsValue(key) ; + return subMap.containsValue( key ) ; } + + @Override + @SuppressWarnings("unchecked") public Object get(Object key) { - return submap.get(key); + return subMap.get( key ); } + + @Override + @SuppressWarnings("unchecked") public Object put(Object key, Object value) { write(); - return submap.put(key, value); + return subMap.put( key, value ); } + + @Override + @SuppressWarnings("unchecked") public Object remove(Object key) { write(); - return submap.remove(key); + return subMap.remove( key ); } + + @Override + @SuppressWarnings("unchecked") public void putAll(Map other) { write(); - submap.putAll(other); + subMap.putAll( other ); } + + @Override + @SuppressWarnings("unchecked") public void clear() { write(); - submap.clear(); + subMap.clear(); } + + @Override + @SuppressWarnings("unchecked") public Set keySet() { - return new SetProxy( submap.keySet() ); + return new SetProxy( subMap.keySet() ); } + + @Override + @SuppressWarnings("unchecked") public Collection values() { - return new SetProxy( submap.values() ); + return new SetProxy( subMap.values() ); } + + @Override + @SuppressWarnings("unchecked") public Set entrySet() { - return new EntrySetProxy( submap.entrySet() ); + return new EntrySetProxy( subMap.entrySet() ); } - // from SortedMap + + @Override + @SuppressWarnings("unchecked") public Comparator comparator() { - return submap.comparator(); + return subMap.comparator(); } + + @Override + @SuppressWarnings("unchecked") public SortedMap subMap(Object fromKey, Object toKey) { - SortedMap m; - m = submap.subMap(fromKey, toKey); - return new SortedSubMap( m ); + final SortedMap subMap = this.subMap.subMap( fromKey, toKey ); + return new SortedSubMap( subMap ); } + + @Override + @SuppressWarnings("unchecked") public SortedMap headMap(Object toKey) { - SortedMap m; - m = submap.headMap(toKey); - return new SortedSubMap(m); + final SortedMap headMap = subMap.headMap( toKey ); + return new SortedSubMap( headMap ); } + + @Override + @SuppressWarnings("unchecked") public SortedMap tailMap(Object fromKey) { - SortedMap m; - m = submap.tailMap(fromKey); - return new SortedSubMap(m); + final SortedMap tailMap = subMap.tailMap( fromKey ); + return new SortedSubMap( tailMap ); } + + @Override + @SuppressWarnings("unchecked") public Object firstKey() { - return submap.firstKey(); + return subMap.firstKey(); } + + @Override + @SuppressWarnings("unchecked") public Object lastKey() { - return submap.lastKey(); + return subMap.lastKey(); } - } - } - - - - - - - diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentSortedSet.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentSortedSet.java index 3fb127db2c..3e07821b2d 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentSortedSet.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentSortedSet.java @@ -25,7 +25,6 @@ package org.hibernate.collection.internal; import java.io.Serializable; import java.util.Comparator; -import java.util.Iterator; import java.util.SortedSet; import java.util.TreeMap; @@ -42,17 +41,42 @@ import org.hibernate.persister.collection.BasicCollectionPersister; * @author e */ public class PersistentSortedSet extends PersistentSet implements SortedSet { - protected Comparator comparator; - protected Serializable snapshot(BasicCollectionPersister persister, EntityMode entityMode) - throws HibernateException { - //if (set==null) return new Set(session); - TreeMap clonedSet = new TreeMap(comparator); - Iterator iter = set.iterator(); - while ( iter.hasNext() ) { - Object copy = persister.getElementType().deepCopy( iter.next(), persister.getFactory() ); - clonedSet.put(copy, copy); + /** + * Constructs a PersistentSortedSet. This form needed for SOAP libraries, etc + */ + @SuppressWarnings("UnusedDeclaration") + public PersistentSortedSet() { + } + + /** + * Constructs a PersistentSortedSet + * + * @param session The session + */ + public PersistentSortedSet(SessionImplementor session) { + super( session ); + } + + /** + * Constructs a PersistentSortedSet + * + * @param session The session + * @param set The underlying set data + */ + public PersistentSortedSet(SessionImplementor session, SortedSet set) { + super( session, set ); + comparator = set.comparator(); + } + + @SuppressWarnings({"unchecked", "UnusedParameters"}) + protected Serializable snapshot(BasicCollectionPersister persister, EntityMode entityMode) + throws HibernateException { + final TreeMap clonedSet = new TreeMap( comparator ); + for ( Object setElement : set ) { + final Object copy = persister.getElementType().deepCopy( setElement, persister.getFactory() ); + clonedSet.put( copy, copy ); } return clonedSet; } @@ -61,106 +85,91 @@ public class PersistentSortedSet extends PersistentSet implements SortedSet { this.comparator = comparator; } - public PersistentSortedSet(SessionImplementor session) { - super(session); - } - - public PersistentSortedSet(SessionImplementor session, SortedSet set) { - super(session, set); - comparator = set.comparator(); - } - - public PersistentSortedSet() {} //needed for SOAP libraries, etc - - /** - * @see PersistentSortedSet#comparator() - */ + @Override public Comparator comparator() { return comparator; } - /** - * @see PersistentSortedSet#subSet(Object,Object) - */ + @Override + @SuppressWarnings("unchecked") public SortedSet subSet(Object fromElement, Object toElement) { read(); - SortedSet s; - s = ( (SortedSet) set ).subSet(fromElement, toElement); - return new SubSetProxy(s); + final SortedSet subSet = ( (SortedSet) set ).subSet( fromElement, toElement ); + return new SubSetProxy( subSet ); } - /** - * @see PersistentSortedSet#headSet(Object) - */ + @Override + @SuppressWarnings("unchecked") public SortedSet headSet(Object toElement) { read(); - SortedSet s = ( (SortedSet) set ).headSet(toElement); - return new SubSetProxy(s); + final SortedSet headSet = ( (SortedSet) set ).headSet(toElement); + return new SubSetProxy( headSet ); } - /** - * @see PersistentSortedSet#tailSet(Object) - */ + @Override + @SuppressWarnings("unchecked") public SortedSet tailSet(Object fromElement) { read(); - SortedSet s = ( (SortedSet) set ).tailSet(fromElement); - return new SubSetProxy(s); + final SortedSet tailSet = ( (SortedSet) set ).tailSet( fromElement ); + return new SubSetProxy( tailSet ); } - /** - * @see PersistentSortedSet#first() - */ + @Override + @SuppressWarnings("unchecked") public Object first() { read(); return ( (SortedSet) set ).first(); } - /** - * @see PersistentSortedSet#last() - */ + @Override + @SuppressWarnings("unchecked") public Object last() { read(); return ( (SortedSet) set ).last(); } - /** wrapper for subSets to propagate write to its backing set */ + /** + * wrapper for subSets to propagate write to its backing set + */ class SubSetProxy extends SetProxy implements SortedSet { - SubSetProxy(SortedSet s) { - super(s); + super( s ); } + @Override + @SuppressWarnings("unchecked") public Comparator comparator() { return ( (SortedSet) this.set ).comparator(); } + @Override + @SuppressWarnings("unchecked") public Object first() { return ( (SortedSet) this.set ).first(); } + @Override + @SuppressWarnings("unchecked") public SortedSet headSet(Object toValue) { - return new SubSetProxy( ( (SortedSet) this.set ).headSet(toValue) ); + return new SubSetProxy( ( (SortedSet) this.set ).headSet( toValue ) ); } + @Override + @SuppressWarnings("unchecked") public Object last() { return ( (SortedSet) this.set ).last(); } + @Override + @SuppressWarnings("unchecked") public SortedSet subSet(Object fromValue, Object toValue) { - return new SubSetProxy( ( (SortedSet) this.set ).subSet(fromValue, toValue) ); + return new SubSetProxy( ( (SortedSet) this.set ).subSet( fromValue, toValue ) ); } + @Override + @SuppressWarnings("unchecked") public SortedSet tailSet(Object fromValue) { - return new SubSetProxy( ( (SortedSet) this.set ).tailSet(fromValue) ); + return new SubSetProxy( ( (SortedSet) this.set ).tailSet( fromValue ) ); } - } - } - - - - - - - diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/package-info.java new file mode 100644 index 0000000000..c7a5babaf6 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/package-info.java @@ -0,0 +1,28 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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 + */ + +/** + * Internal implementations and support for persistent collections + */ +package org.hibernate.collection.internal; diff --git a/hibernate-core/src/main/java/org/hibernate/collection/spi/PersistentCollection.java b/hibernate-core/src/main/java/org/hibernate/collection/spi/PersistentCollection.java index 63bda8a1f8..3d710c835d 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/spi/PersistentCollection.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/spi/PersistentCollection.java @@ -63,28 +63,38 @@ import org.hibernate.type.Type; * @author Gavin King */ public interface PersistentCollection { - /** * Get the owning entity. Note that the owner is only * set during the flush cycle, and when a new collection * wrapper is created while loading an entity. + * + * @return The owner */ public Object getOwner(); + /** * Set the reference to the owning entity + * + * @param entity The owner */ public void setOwner(Object entity); - + /** * Is the collection empty? (don't try to initialize the collection) + * + * @return {@code false} if the collection is non-empty; {@code true} otherwise. */ public boolean empty(); /** * After flushing, re-init snapshot state. + * + * @param key The collection instance key (fk value). + * @param role The collection role + * @param snapshot The snapshot state */ public void setSnapshot(Serializable key, String role, Serializable snapshot); - + /** * After flushing, clear any "queued" additions, since the * database state is now synchronized with the memory state. @@ -92,7 +102,9 @@ public interface PersistentCollection { public void postAction(); /** - * return the user-visible collection (or array) instance + * Return the user-visible collection (or array) instance + * + * @return The underlying collection/array */ public Object getValue(); @@ -103,70 +115,121 @@ public interface PersistentCollection { /** * Called after reading all rows from the JDBC result set + * + * @return Whether to end the read. */ public boolean endRead(); /** * Called after initializing from cache + * + * @return ?? */ public boolean afterInitialize(); /** * Could the application possibly have a direct reference to * the underlying collection implementation? + * + * @return {@code true} indicates that the application might have access to the underlying collection/array. */ public boolean isDirectlyAccessible(); /** * Disassociate this collection from the given session. + * + * @param currentSession The session we are disassociating from. Used for validations. + * * @return true if this was currently associated with the given session */ public boolean unsetSession(SessionImplementor currentSession); /** * Associate the collection with the given session. + * + * @param session The session to associate with + * * @return false if the collection was already associated with the session + * * @throws HibernateException if the collection was already associated * with another open session */ - public boolean setCurrentSession(SessionImplementor session) - throws HibernateException; + public boolean setCurrentSession(SessionImplementor session) throws HibernateException; /** * Read the state of the collection from a disassembled cached value + * + * @param persister The collection persister + * @param disassembled The disassembled cached state + * @param owner The collection owner */ - public void initializeFromCache(CollectionPersister persister, - Serializable disassembled, Object owner) throws HibernateException; + public void initializeFromCache(CollectionPersister persister, Serializable disassembled, Object owner); /** * Iterate all collection entries, during update of the database + * + * @param persister The collection persister. + * + * @return The iterator */ public Iterator entries(CollectionPersister persister); /** * Read a row from the JDBC result set + * + * @param rs The JDBC ResultSet + * @param role The collection role + * @param descriptor The aliases used for the columns making up the collection + * @param owner The collection owner + * + * @return The read object + * + * @throws HibernateException Generally indicates a problem resolving data read from the ResultSet + * @throws SQLException Indicates a problem accessing the ResultSet */ public Object readFrom(ResultSet rs, CollectionPersister role, CollectionAliases descriptor, Object owner) throws HibernateException, SQLException; /** - * Get the index of the given collection entry + * Get the identifier of the given collection entry. This refers to the collection identifier, not the + * identifier of the (possibly) entity elements. This is only valid for invocation on the + * {@code idbag} collection. + * + * @param entry The collection entry/element + * @param i The assumed identifier (?) + * + * @return The identifier value */ public Object getIdentifier(Object entry, int i); /** * Get the index of the given collection entry + * + * @param entry The collection entry/element + * @param i The assumed index * @param persister it was more elegant before we added this... + * + * @return The index value */ public Object getIndex(Object entry, int i, CollectionPersister persister); /** - * Get the value of the given collection entry + * Get the value of the given collection entry. Generally the given entry parameter value will just be returned. + * Might get a different value for a duplicate entries in a Set. + * + * @param entry The object instance for which to get the collection element instance. + * + * @return The corresponding object that is part of the collection elements. */ public Object getElement(Object entry); /** * Get the snapshot value of the given collection entry + * + * @param entry The entry + * @param i The index + * + * @return The snapshot state for that element */ public Object getSnapshotElement(Object entry, int i); @@ -175,106 +238,168 @@ public interface PersistentCollection { * allowing appropriate initializations to occur. * * @param persister The underlying collection persister. - * @param anticipatedSize The anticipated size of the collection after initilization is complete. + * @param anticipatedSize The anticipated size of the collection after initialization is complete. */ public void beforeInitialize(CollectionPersister persister, int anticipatedSize); /** * Does the current state exactly match the snapshot? + * + * @param persister The collection persister + * + * @return {@code true} if the current state and the snapshot state match. + * */ - public boolean equalsSnapshot(CollectionPersister persister) - throws HibernateException; + public boolean equalsSnapshot(CollectionPersister persister); /** * Is the snapshot empty? + * + * @param snapshot The snapshot to check + * + * @return {@code true} if the given snapshot is empty */ public boolean isSnapshotEmpty(Serializable snapshot); /** - * Disassemble the collection, ready for the cache + * Disassemble the collection to get it ready for the cache + * + * @param persister The collection persister + * + * @return The disassembled state */ - public Serializable disassemble(CollectionPersister persister) - throws HibernateException; + public Serializable disassemble(CollectionPersister persister) ; /** * Do we need to completely recreate this collection when it changes? + * + * @param persister The collection persister + * + * @return {@code true} if a change requires a recreate. */ public boolean needsRecreate(CollectionPersister persister); /** * Return a new snapshot of the current state of the collection + * + * @param persister The collection persister + * + * @return The snapshot */ - public Serializable getSnapshot(CollectionPersister persister) - throws HibernateException; + public Serializable getSnapshot(CollectionPersister persister); /** - * To be called internally by the session, forcing - * immediate initialization. + * To be called internally by the session, forcing immediate initialization. */ - public void forceInitialization() throws HibernateException; + public void forceInitialization(); /** - * Does an element exist at this entry in the collection? + * Does the given element/entry exist in the collection? + * + * @param entry The object to check if it exists as a collection element + * @param i Unused + * + * @return {@code true} if the given entry is a collection element */ - public boolean entryExists(Object entry, int i); //note that i parameter is now unused (delete it?) + public boolean entryExists(Object entry, int i); /** * Do we need to insert this element? + * + * @param entry The collection element to check + * @param i The index (for indexed collections) + * @param elemType The type for the element + * + * @return {@code true} if the element needs inserting */ - public boolean needsInserting(Object entry, int i, Type elemType) - throws HibernateException; + public boolean needsInserting(Object entry, int i, Type elemType); /** * Do we need to update this element? + * + * @param entry The collection element to check + * @param i The index (for indexed collections) + * @param elemType The type for the element + * + * @return {@code true} if the element needs updating + */ + public boolean needsUpdating(Object entry, int i, Type elemType); + + /** + * Can each element in the collection be mapped unequivocally to a single row in the database? Generally + * bags and sets are the only collections that cannot be. + * + * @return {@code true} if the row for each element is known */ - public boolean needsUpdating(Object entry, int i, Type elemType) - throws HibernateException; - public boolean isRowUpdatePossible(); /** * Get all the elements that need deleting + * + * @param persister The collection persister + * @param indexIsFormula For indexed collections, tells whether the index is a formula (calculated value) mapping + * + * @return An iterator over the elements to delete */ - public Iterator getDeletes(CollectionPersister persister, boolean indexIsFormula) - throws HibernateException; + public Iterator getDeletes(CollectionPersister persister, boolean indexIsFormula); /** - * Is this the wrapper for the given underlying collection instance? + * Is this the wrapper for the given collection instance? + * + * @param collection The collection to check whether this is wrapping it + * + * @return {@code true} if this is a wrapper around that given collection instance. */ public boolean isWrapper(Object collection); /** * Is this instance initialized? + * + * @return Was this collection initialized? Or is its data still not (fully) loaded? */ public boolean wasInitialized(); /** - * Does this instance have any "queued" additions? + * Does this instance have any "queued" operations? + * + * @return {@code true} indicates there are pending, queued, delayed operations */ public boolean hasQueuedOperations(); /** - * Iterate the "queued" additions + * Iterator over the "queued" additions + * + * @return The iterator */ public Iterator queuedAdditionIterator(); /** * Get the "queued" orphans + * + * @param entityName The name of the entity that makes up the elements + * + * @return The orphaned elements */ public Collection getQueuedOrphans(String entityName); /** * Get the current collection key value + * + * @return the current collection key value */ public Serializable getKey(); /** * Get the current role name + * + * @return the collection role name */ public String getRole(); /** * Is the collection unreferenced? + * + * @return {@code true} if the collection is no longer referenced by an owner */ public boolean isUnreferenced(); @@ -283,6 +408,8 @@ public interface PersistentCollection { * reliable during the flush cycle, after the * collection elements are dirty checked against * the snapshot. + * + * @return {@code true} if the collection is dirty */ public boolean isDirty(); @@ -293,8 +420,9 @@ public interface PersistentCollection { public void clearDirty(); /** - * Get the snapshot cached by the collection - * instance + * Get the snapshot cached by the collection instance + * + * @return The internally stored snapshot state */ public Serializable getStoredSnapshot(); @@ -306,20 +434,28 @@ public interface PersistentCollection { /** * Called before inserting rows, to ensure that any surrogate keys * are fully generated + * + * @param persister The collection persister */ - public void preInsert(CollectionPersister persister) - throws HibernateException; + public void preInsert(CollectionPersister persister); /** * Called after inserting a row, to fetch the natively generated id + * + * @param persister The collection persister + * @param entry The collection element just inserted + * @param i The element position/index */ - public void afterRowInsert(CollectionPersister persister, Object entry, int i) - throws HibernateException; + public void afterRowInsert(CollectionPersister persister, Object entry, int i); /** * get all "orphaned" elements + * + * @param snapshot The snapshot state + * @param entityName The name of the entity that are the elements of the collection + * + * @return The orphans */ - public Collection getOrphans(Serializable snapshot, String entityName) - throws HibernateException; + public Collection getOrphans(Serializable snapshot, String entityName); -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/collection/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/collection/spi/package-info.java new file mode 100644 index 0000000000..c754f3abd7 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/collection/spi/package-info.java @@ -0,0 +1,28 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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 + */ + +/** + * SPI definitions for persistent collections + */ +package org.hibernate.collection.spi; From 8c7dfc9d285260b88ce95f25bf7b743650cb1631 Mon Sep 17 00:00:00 2001 From: Gail Badner Date: Mon, 22 Apr 2013 15:50:35 -0700 Subject: [PATCH 03/57] HHH-7841 - Redesign Loader --- .../spi/MetadataDrivenModelGraphVisitor.java | 24 +++++++++++++------ .../EntityBasedAssociationAttribute.java | 2 +- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/persister/walking/spi/MetadataDrivenModelGraphVisitor.java b/hibernate-core/src/main/java/org/hibernate/persister/walking/spi/MetadataDrivenModelGraphVisitor.java index f22d172bec..8a9ceb77a9 100644 --- a/hibernate-core/src/main/java/org/hibernate/persister/walking/spi/MetadataDrivenModelGraphVisitor.java +++ b/hibernate-core/src/main/java/org/hibernate/persister/walking/spi/MetadataDrivenModelGraphVisitor.java @@ -113,7 +113,15 @@ public class MetadataDrivenModelGraphVisitor { final PropertyPath subPath = currentPropertyPath.append( attributeDefinition.getName() ); log.debug( "Visiting attribute path : " + subPath.getFullPath() ); - final boolean continueWalk = strategy.startingAttribute( attributeDefinition ); + final boolean continueWalk; + if ( attributeDefinition.getType().isAssociationType() ) { + continueWalk = + ! isDuplicateAssociation( ( (AssociationAttributeDefinition) attributeDefinition ).getAssociationKey() ) && + strategy.startingAttribute( attributeDefinition ); + } + else { + continueWalk = strategy.startingAttribute( attributeDefinition ); + } if ( continueWalk ) { final PropertyPath old = currentPropertyPath; currentPropertyPath = subPath; @@ -135,11 +143,6 @@ public class MetadataDrivenModelGraphVisitor { private void visitAssociation(AssociationAttributeDefinition attribute) { // todo : do "too deep" checks; but see note about adding depth to PropertyPath - if ( isDuplicateAssociation( attribute.getAssociationKey() ) ) { - log.debug( "Property path deemed to be circular : " + currentPropertyPath.getFullPath() ); - return; - } - if ( attribute.isCollection() ) { visitCollectionDefinition( attribute.toCollectionDefinition() ); } @@ -210,7 +213,14 @@ public class MetadataDrivenModelGraphVisitor { private final Set visitedAssociationKeys = new HashSet(); protected boolean isDuplicateAssociation(AssociationKey associationKey) { - return !visitedAssociationKeys.add( associationKey ); + boolean isDuplicate = !visitedAssociationKeys.add( associationKey ); + if ( isDuplicate ) { + log.debug( "Property path deemed to be circular : " + currentPropertyPath.getFullPath() ); + return true; + } + else { + return false; + } } } diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityBasedAssociationAttribute.java b/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityBasedAssociationAttribute.java index d5641ebd87..88405553db 100644 --- a/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityBasedAssociationAttribute.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityBasedAssociationAttribute.java @@ -93,7 +93,7 @@ public class EntityBasedAssociationAttribute lhsColumnNames = collectionPersister.getElementColumnNames(); } else { - final OuterJoinLoadable entityPersister = (OuterJoinLoadable) joinable; + final OuterJoinLoadable entityPersister = (OuterJoinLoadable) source(); lhsTableName = getLHSTableName( type, attributeNumber(), entityPersister ); lhsColumnNames = getLHSColumnNames( type, attributeNumber(), entityPersister, sessionFactory() ); } From 900ad4be11ae008c1ed87fed190cb132e206ea1f Mon Sep 17 00:00:00 2001 From: Gail Badner Date: Mon, 22 Apr 2013 15:53:09 -0700 Subject: [PATCH 04/57] HHH-7841 - Redesign Loader --- ...tyWithOneToManyResultSetProcessorTest.java | 234 ++++++++++++++++++ 1 file changed, 234 insertions(+) create mode 100644 hibernate-core/src/test/java/org/hibernate/loader/EntityWithOneToManyResultSetProcessorTest.java diff --git a/hibernate-core/src/test/java/org/hibernate/loader/EntityWithOneToManyResultSetProcessorTest.java b/hibernate-core/src/test/java/org/hibernate/loader/EntityWithOneToManyResultSetProcessorTest.java new file mode 100644 index 0000000000..23b3e860ee --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/loader/EntityWithOneToManyResultSetProcessorTest.java @@ -0,0 +1,234 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.loader; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import javax.persistence.CascadeType; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.OneToMany; + +import org.junit.Test; + +import org.hibernate.Hibernate; +import org.hibernate.Session; +import org.hibernate.engine.spi.LoadQueryInfluencers; +import org.hibernate.engine.spi.QueryParameters; +import org.hibernate.engine.spi.SessionImplementor; +import org.hibernate.jdbc.Work; +import org.hibernate.loader.internal.EntityLoadQueryBuilderImpl; +import org.hibernate.loader.internal.LoadQueryAliasResolutionContextImpl; +import org.hibernate.loader.internal.ResultSetProcessorImpl; +import org.hibernate.loader.plan.internal.SingleRootReturnLoadPlanBuilderStrategy; +import org.hibernate.loader.plan.spi.LoadPlan; +import org.hibernate.loader.plan.spi.build.LoadPlanBuilder; +import org.hibernate.loader.spi.LoadQueryAliasResolutionContext; +import org.hibernate.loader.spi.NamedParameterContext; +import org.hibernate.loader.spi.NoOpLoadPlanAdvisor; +import org.hibernate.persister.entity.EntityPersister; +import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.hibernate.testing.junit4.ExtraAssertions; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/** + * @author Gail Badner + */ +public class EntityWithOneToManyResultSetProcessorTest extends BaseCoreFunctionalTestCase { + + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { Poster.class, Message.class }; + } + + @Test + public void testEntityWithSet() throws Exception { + final EntityPersister entityPersister = sessionFactory().getEntityPersister( Poster.class.getName() ); + + // create some test data + Session session = openSession(); + session.beginTransaction(); + Poster poster = new Poster(); + poster.pid = 0; + poster.name = "John Doe"; + Message message1 = new Message(); + message1.mid = 1; + message1.msgTxt = "Howdy!"; + message1.poster = poster; + poster.messages.add( message1 ); + Message message2 = new Message(); + message2.mid = 2; + message2.msgTxt = "Bye!"; + message2.poster = poster; + poster.messages.add( message2 ); + session.save( poster ); + session.getTransaction().commit(); + session.close(); + + session = openSession(); + session.beginTransaction(); + Poster posterGotten = (Poster) session.get( Poster.class, poster.pid ); + assertEquals( 0, posterGotten.pid.intValue() ); + assertEquals( poster.name, posterGotten.name ); + assertTrue( Hibernate.isInitialized( posterGotten.messages ) ); + assertEquals( 2, posterGotten.messages.size() ); + for ( Message message : posterGotten.messages ) { + if ( message.mid == 1 ) { + assertEquals( message1.msgTxt, message.msgTxt ); + } + else if ( message.mid == 2 ) { + assertEquals( message2.msgTxt, message.msgTxt ); + } + else { + fail( "unexpected message id." ); + } + assertSame( posterGotten, message.poster ); + } + session.getTransaction().commit(); + session.close(); + + { + final SingleRootReturnLoadPlanBuilderStrategy strategy = new SingleRootReturnLoadPlanBuilderStrategy( + sessionFactory(), + LoadQueryInfluencers.NONE + ); + final LoadPlan plan = LoadPlanBuilder.buildRootEntityLoadPlan( strategy, entityPersister ); + final LoadQueryAliasResolutionContext aliasResolutionContext = + new LoadQueryAliasResolutionContextImpl( + sessionFactory(), + 0, + Collections.singletonMap( plan.getReturns().get( 0 ), new String[] { "abc" } ) + ); + final EntityLoadQueryBuilderImpl queryBuilder = new EntityLoadQueryBuilderImpl( + LoadQueryInfluencers.NONE, + plan + ); + final String sql = queryBuilder.generateSql( 1, sessionFactory(), aliasResolutionContext ); + + final ResultSetProcessorImpl resultSetProcessor = new ResultSetProcessorImpl( plan ); + final List results = new ArrayList(); + + final Session workSession = openSession(); + workSession.beginTransaction(); + workSession.doWork( + new Work() { + @Override + public void execute(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement( sql ); + ps.setInt( 1, 0 ); + ResultSet resultSet = ps.executeQuery(); + results.addAll( + resultSetProcessor.extractResults( + NoOpLoadPlanAdvisor.INSTANCE, + resultSet, + (SessionImplementor) workSession, + new QueryParameters(), + new NamedParameterContext() { + @Override + public int[] getNamedParameterLocations(String name) { + return new int[0]; + } + }, + aliasResolutionContext, + true, + false, + null, + null + ) + ); + resultSet.close(); + ps.close(); + } + } + ); + assertEquals( 2, results.size() ); + Object result1 = results.get( 0 ); + assertNotNull( result1 ); + assertSame( result1, results.get( 1 ) ); + + Poster workPoster = ExtraAssertions.assertTyping( Poster.class, result1 ); + assertEquals( 0, workPoster.pid.intValue() ); + assertEquals( poster.name, workPoster.name ); + assertTrue( Hibernate.isInitialized( workPoster.messages ) ); + assertEquals( 2, workPoster.messages.size() ); + assertTrue( Hibernate.isInitialized( posterGotten.messages ) ); + assertEquals( 2, workPoster.messages.size() ); + for ( Message message : workPoster.messages ) { + if ( message.mid == 1 ) { + assertEquals( message1.msgTxt, message.msgTxt ); + } + else if ( message.mid == 2 ) { + assertEquals( message2.msgTxt, message.msgTxt ); + } + else { + fail( "unexpected message id." ); + } + assertSame( workPoster, message.poster ); + } + workSession.getTransaction().commit(); + workSession.close(); + } + + // clean up test data + session = openSession(); + session.beginTransaction(); + session.delete( poster ); + session.getTransaction().commit(); + session.close(); + } + + @Entity( name = "Message" ) + public static class Message { + @Id + private Integer mid; + private String msgTxt; + @ManyToOne + @JoinColumn + private Poster poster; + } + + @Entity( name = "Poster" ) + public static class Poster { + @Id + private Integer pid; + private String name; + @OneToMany(mappedBy = "poster", fetch = FetchType.EAGER, cascade = CascadeType.ALL ) + private Set messages = new HashSet(); + } +} From 8c28ba84633982c9cb889b8d8375979f0035b56e Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Tue, 23 Apr 2013 18:13:41 -0500 Subject: [PATCH 05/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../hibernate/boot/registry/package-info.java | 14 +- .../TenantIdentifierMismatchException.java | 15 +- .../context/internal/JTASessionContext.java | 78 +- .../internal/ManagedSessionContext.java | 24 +- .../internal/ThreadLocalSessionContext.java | 144 ++-- .../context/internal/package-info.java | 4 + .../org/hibernate/context/package-info.java | 4 + .../spi/AbstractCurrentSessionContext.java | 5 + .../hibernate/context/spi/package-info.java | 4 + .../AbstractEmptinessExpression.java | 58 +- .../criterion/AggregateProjection.java | 20 +- .../criterion/AliasedProjection.java | 72 +- .../hibernate/criterion/AvgProjection.java | 8 +- .../criterion/BetweenExpression.java | 30 +- .../org/hibernate/criterion/Conjunction.java | 12 + .../hibernate/criterion/CountProjection.java | 54 +- .../hibernate/criterion/CriteriaQuery.java | 174 +++-- .../criterion/CriteriaSpecification.java | 23 +- .../hibernate/criterion/DetachedCriteria.java | 481 ++++++++---- .../org/hibernate/criterion/Disjunction.java | 12 + .../org/hibernate/criterion/Distinct.java | 74 +- .../hibernate/criterion/EmptyExpression.java | 18 +- .../criterion/EnhancedProjection.java | 6 +- .../java/org/hibernate/criterion/Example.java | 533 +++++++------ .../criterion/ExistsSubqueryExpression.java | 25 +- .../org/hibernate/criterion/Expression.java | 106 +-- .../criterion/IdentifierEqExpression.java | 41 +- .../criterion/IdentifierProjection.java | 79 +- .../hibernate/criterion/IlikeExpression.java | 21 +- .../org/hibernate/criterion/InExpression.java | 98 +-- .../org/hibernate/criterion/Junction.java | 58 +- .../hibernate/criterion/LikeExpression.java | 41 +- .../criterion/LogicalExpression.java | 43 +- .../org/hibernate/criterion/MatchMode.java | 15 +- .../criterion/NaturalIdentifier.java | 28 +- .../criterion/NotEmptyExpression.java | 17 +- .../hibernate/criterion/NotExpression.java | 24 +- .../criterion/NotNullExpression.java | 27 +- .../hibernate/criterion/NullExpression.java | 28 +- .../java/org/hibernate/criterion/Order.java | 167 ++-- .../org/hibernate/criterion/Projection.java | 7 +- .../hibernate/criterion/ProjectionList.java | 246 +++--- .../org/hibernate/criterion/Projections.java | 220 ++++-- .../PropertiesSubqueryExpression.java | 26 +- .../org/hibernate/criterion/Property.java | 623 +++++++++++++-- .../criterion/PropertyExpression.java | 56 +- .../criterion/PropertyProjection.java | 60 +- .../criterion/PropertySubqueryExpression.java | 16 +- .../org/hibernate/criterion/Restrictions.java | 714 ++++++++++++------ .../criterion/RowCountProjection.java | 30 +- .../org/hibernate/criterion/SQLCriterion.java | 53 +- .../hibernate/criterion/SQLProjection.java | 67 +- .../hibernate/criterion/SimpleExpression.java | 105 +-- .../hibernate/criterion/SimpleProjection.java | 58 +- .../criterion/SimpleSubqueryExpression.java | 31 +- .../hibernate/criterion/SizeExpression.java | 64 +- .../org/hibernate/criterion/Subqueries.java | 691 ++++++++++++++--- .../criterion/SubqueryExpression.java | 70 +- .../hibernate/internal/util/StringHelper.java | 2 +- .../criteria/CriteriaQueryTranslator.java | 26 +- .../java/org/hibernate/sql/JoinFragment.java | 146 +++- 61 files changed, 4083 insertions(+), 1913 deletions(-) create mode 100644 hibernate-core/src/main/java/org/hibernate/context/internal/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/context/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/context/spi/package-info.java diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/package-info.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/package-info.java index 88b77afdc4..962c27b4e9 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/package-info.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/package-info.java @@ -2,6 +2,18 @@ * Defines service registry contracts application are likely to want to utilize for * configuring Hibernate behavior. * - * {@link BootstrapServiceRegistry} is the + * Service registries are designed to be hierarchical. This works in 2 fashions. First registries can "hide" or + * "override" services from parent registries. It also allows granular building of registries as services + * become available. + * + * {@link BootstrapServiceRegistry} is the base service registry, intended to be built via + * {@link BootstrapServiceRegistryBuilder} if you need customization. For non-customized + * {@link BootstrapServiceRegistry} usage, the {@link BootstrapServiceRegistryBuilder} and + * {@link BootstrapServiceRegistry} can be bypassed altogether. + * + * Usually the next level in a standard registry set up is the {@link StandardServiceRegistry}, intended to be built + * by the {@link StandardServiceRegistryBuilder} if you need customization. The builder optionally takes the + * {@link BootstrapServiceRegistry} to use as a base; if none is provided a default one is generated assuming sensible + * defaults in Java SE and EE environments, particularly in respect to Class loading. */ package org.hibernate.boot.registry; diff --git a/hibernate-core/src/main/java/org/hibernate/context/TenantIdentifierMismatchException.java b/hibernate-core/src/main/java/org/hibernate/context/TenantIdentifierMismatchException.java index afea9d35ec..41bb0427ab 100644 --- a/hibernate-core/src/main/java/org/hibernate/context/TenantIdentifierMismatchException.java +++ b/hibernate-core/src/main/java/org/hibernate/context/TenantIdentifierMismatchException.java @@ -33,11 +33,22 @@ import org.hibernate.HibernateException; * @author Steve Ebersole */ public class TenantIdentifierMismatchException extends HibernateException{ + /** + * Constructs a TenantIdentifierMismatchException. + * + * @param message Message explaining the exception condition + */ public TenantIdentifierMismatchException(String message) { super( message ); } - public TenantIdentifierMismatchException(String message, Throwable root) { - super( message, root ); + /** + * Constructs a TenantIdentifierMismatchException. + * + * @param message Message explaining the exception condition + * @param cause The underlying cause + */ + public TenantIdentifierMismatchException(String message, Throwable cause) { + super( message, cause ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/context/internal/JTASessionContext.java b/hibernate-core/src/main/java/org/hibernate/context/internal/JTASessionContext.java index 997732f133..2aea50e033 100644 --- a/hibernate-core/src/main/java/org/hibernate/context/internal/JTASessionContext.java +++ b/hibernate-core/src/main/java/org/hibernate/context/internal/JTASessionContext.java @@ -23,12 +23,11 @@ */ package org.hibernate.context.internal; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - import javax.transaction.Synchronization; import javax.transaction.Transaction; import javax.transaction.TransactionManager; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.jboss.logging.Logger; @@ -36,40 +35,44 @@ import org.hibernate.ConnectionReleaseMode; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.context.spi.AbstractCurrentSessionContext; -import org.hibernate.context.spi.CurrentSessionContext; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.transaction.internal.jta.JtaStatusHelper; -import org.hibernate.internal.CoreMessageLogger; import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform; +import org.hibernate.internal.CoreMessageLogger; /** - * An implementation of {@link CurrentSessionContext} which scopes the notion - * of a current session to a JTA transaction. Because JTA gives us a nice - * tie-in to clean up after ourselves, this implementation will generate - * Sessions as needed provided a JTA transaction is in effect. If a session - * is not already associated with the current JTA transaction at the time - * {@link #currentSession()} is called, a new session will be opened and it - * will be associated with that JTA transaction. - *

- * Note that the sessions returned from this method are automatically configured with - * both the {@link org.hibernate.cfg.Environment#FLUSH_BEFORE_COMPLETION auto-flush} and - * {@link org.hibernate.cfg.Environment#AUTO_CLOSE_SESSION auto-close} attributes set to - * true, meaning that the Session will be automatically flushed and closed - * as part of the lifecycle for the JTA transaction to which it is associated. - * Additionally, it will also be configured to aggressively release JDBC - * connections after each statement is executed. These settings are governed - * by the {@link #isAutoFlushEnabled()}, {@link #isAutoCloseEnabled()}, and - * {@link #getConnectionReleaseMode()} methods; these are provided (along with - * the {@link #buildOrObtainSession()} method) for easier subclassing for custom - * JTA-based session tracking logic (like maybe long-session semantics). + * An implementation of {@link org.hibernate.context.spi.CurrentSessionContext} which scopes the notion + * of a current session to a JTA transaction. Because JTA gives us a nice tie-in to clean up after + * ourselves, this implementation will generate Sessions as needed provided a JTA transaction is in + * effect. If a session is not already associated with the current JTA transaction at the time + * {@link #currentSession()} is called, a new session will be opened and it will be associated with that + * JTA transaction. + * + * Note that the sessions returned from this method are automatically configured with both the + * {@link org.hibernate.cfg.Environment#FLUSH_BEFORE_COMPLETION auto-flush} and + * {@link org.hibernate.cfg.Environment#AUTO_CLOSE_SESSION auto-close} attributes set to true, meaning + * that the Session will be automatically flushed and closed as part of the lifecycle for the JTA + * transaction to which it is associated. Additionally, it will also be configured to aggressively + * release JDBC connections after each statement is executed. These settings are governed by the + * {@link #isAutoFlushEnabled()}, {@link #isAutoCloseEnabled()}, and {@link #getConnectionReleaseMode()} + * methods; these are provided (along with the {@link #buildOrObtainSession()} method) for easier + * subclassing for custom JTA-based session tracking logic (like maybe long-session semantics). * * @author Steve Ebersole */ public class JTASessionContext extends AbstractCurrentSessionContext { - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, JTASessionContext.class.getName()); + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + JTASessionContext.class.getName() + ); private transient Map currentSessionMap = new ConcurrentHashMap(); + /** + * Constructs a JTASessionContext + * + * @param factory The factory this context will service + */ public JTASessionContext(SessionFactoryImplementor factory) { super( factory ); } @@ -132,24 +135,23 @@ public class JTASessionContext extends AbstractCurrentSessionContext { } /** - * Builds a {@link CleanupSynch} capable of cleaning up the the current session map as an after transaction + * Builds a {@link org.hibernate.context.internal.JTASessionContext.CleanupSync} capable of cleaning up the the current session map as an after transaction * callback. * * @param transactionIdentifier The transaction identifier under which the current session is registered. * @return The cleanup synch. */ - private CleanupSynch buildCleanupSynch(Object transactionIdentifier) { - return new CleanupSynch( transactionIdentifier, this ); + private CleanupSync buildCleanupSynch(Object transactionIdentifier) { + return new CleanupSync( transactionIdentifier, this ); } /** * Strictly provided for subclassing purposes; specifically to allow long-session - * support. - *

- * This implementation always just opens a new session. + * support. This implementation always just opens a new session. * * @return the built or (re)obtained session. */ + @SuppressWarnings("deprecation") protected Session buildOrObtainSession() { return baseSessionBuilder() .autoClose( isAutoCloseEnabled() ) @@ -186,26 +188,22 @@ public class JTASessionContext extends AbstractCurrentSessionContext { } /** - * JTA transaction synch used for cleanup of the internal session map. + * JTA transaction sync used for cleanup of the internal session map. */ - protected static class CleanupSynch implements Synchronization { + protected static class CleanupSync implements Synchronization { private Object transactionIdentifier; private JTASessionContext context; - public CleanupSynch(Object transactionIdentifier, JTASessionContext context) { + public CleanupSync(Object transactionIdentifier, JTASessionContext context) { this.transactionIdentifier = transactionIdentifier; this.context = context; } - /** - * {@inheritDoc} - */ + @Override public void beforeCompletion() { } - /** - * {@inheritDoc} - */ + @Override public void afterCompletion(int i) { context.currentSessionMap.remove( transactionIdentifier ); } diff --git a/hibernate-core/src/main/java/org/hibernate/context/internal/ManagedSessionContext.java b/hibernate-core/src/main/java/org/hibernate/context/internal/ManagedSessionContext.java index 13fd5a8d16..b6ad360631 100644 --- a/hibernate-core/src/main/java/org/hibernate/context/internal/ManagedSessionContext.java +++ b/hibernate-core/src/main/java/org/hibernate/context/internal/ManagedSessionContext.java @@ -57,16 +57,20 @@ import org.hibernate.engine.spi.SessionFactoryImplementor; * @author Steve Ebersole */ public class ManagedSessionContext extends AbstractCurrentSessionContext { + private static final ThreadLocal> CONTEXT_TL = new ThreadLocal>(); - private static final ThreadLocal> context = new ThreadLocal>(); - + /** + * Constructs a new ManagedSessionContext + * + * @param factory The factory this context will service + */ public ManagedSessionContext(SessionFactoryImplementor factory) { super( factory ); } @Override public Session currentSession() { - Session current = existingSession( factory() ); + final Session current = existingSession( factory() ); if ( current == null ) { throw new HibernateException( "No session currently bound to execution context" ); } @@ -106,8 +110,8 @@ public class ManagedSessionContext extends AbstractCurrentSessionContext { * @return The bound session if one, else null. */ public static Session unbind(SessionFactory factory) { + final Map sessionMap = sessionMap(); Session existing = null; - Map sessionMap = sessionMap(); if ( sessionMap != null ) { existing = sessionMap.remove( factory ); doCleanup(); @@ -116,12 +120,12 @@ public class ManagedSessionContext extends AbstractCurrentSessionContext { } private static Session existingSession(SessionFactory factory) { - Map sessionMap = sessionMap(); + final Map sessionMap = sessionMap(); if ( sessionMap == null ) { return null; } else { - return ( Session ) sessionMap.get( factory ); + return (Session) sessionMap.get( factory ); } } @@ -130,19 +134,19 @@ public class ManagedSessionContext extends AbstractCurrentSessionContext { } private static synchronized Map sessionMap(boolean createMap) { - Map sessionMap = context.get(); + Map sessionMap = CONTEXT_TL.get(); if ( sessionMap == null && createMap ) { sessionMap = new HashMap(); - context.set( sessionMap ); + CONTEXT_TL.set( sessionMap ); } return sessionMap; } private static synchronized void doCleanup() { - Map sessionMap = sessionMap( false ); + final Map sessionMap = sessionMap( false ); if ( sessionMap != null ) { if ( sessionMap.isEmpty() ) { - context.set( null ); + CONTEXT_TL.set( null ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/context/internal/ThreadLocalSessionContext.java b/hibernate-core/src/main/java/org/hibernate/context/internal/ThreadLocalSessionContext.java index 4ee7ebac03..c4765cfd24 100644 --- a/hibernate-core/src/main/java/org/hibernate/context/internal/ThreadLocalSessionContext.java +++ b/hibernate-core/src/main/java/org/hibernate/context/internal/ThreadLocalSessionContext.java @@ -42,7 +42,6 @@ import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.context.spi.AbstractCurrentSessionContext; -import org.hibernate.context.spi.CurrentSessionContext; import org.hibernate.engine.jdbc.LobCreationContext; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionImplementor; @@ -51,39 +50,37 @@ import org.hibernate.event.spi.EventSource; import org.hibernate.internal.CoreMessageLogger; /** - * A {@link CurrentSessionContext} impl which scopes the notion of current - * session by the current thread of execution. Unlike the JTA counterpart, - * threads do not give us a nice hook to perform any type of cleanup making - * it questionable for this impl to actually generate Session instances. In - * the interest of usability, it was decided to have this default impl - * actually generate a session upon first request and then clean it up - * after the {@link org.hibernate.Transaction} associated with that session - * is committed/rolled-back. In order for ensuring that happens, the sessions - * generated here are unusable until after {@link Session#beginTransaction()} - * has been called. If close() is called on a session managed by - * this class, it will be automatically unbound. - *

- * Additionally, the static {@link #bind} and {@link #unbind} methods are - * provided to allow application code to explicitly control opening and - * closing of these sessions. This, with some from of interception, - * is the preferred approach. It also allows easy framework integration - * and one possible approach for implementing long-sessions. - *

- * The {@link #buildOrObtainSession}, {@link #isAutoCloseEnabled}, - * {@link #isAutoFlushEnabled}, {@link #getConnectionReleaseMode}, and - * {@link #buildCleanupSynch} methods are all provided to allow easy + * A {@link org.hibernate.context.spi.CurrentSessionContext} impl which scopes the notion of current + * session by the current thread of execution. Unlike the JTA counterpart, threads do not give us a nice + * hook to perform any type of cleanup making it questionable for this impl to actually generate Session + * instances. In the interest of usability, it was decided to have this default impl actually generate + * a session upon first request and then clean it up after the {@link org.hibernate.Transaction} + * associated with that session is committed/rolled-back. In order for ensuring that happens, the + * sessions generated here are unusable until after {@link Session#beginTransaction()} has been + * called. If close() is called on a session managed by this class, it will be automatically + * unbound. + * + * Additionally, the static {@link #bind} and {@link #unbind} methods are provided to allow application + * code to explicitly control opening and closing of these sessions. This, with some from of interception, + * is the preferred approach. It also allows easy framework integration and one possible approach for + * implementing long-sessions. + * + * The {@link #buildOrObtainSession}, {@link #isAutoCloseEnabled}, {@link #isAutoFlushEnabled}, + * {@link #getConnectionReleaseMode}, and {@link #buildCleanupSynch} methods are all provided to allow easy * subclassing (for long-running session scenarios, for example). * * @author Steve Ebersole */ public class ThreadLocalSessionContext extends AbstractCurrentSessionContext { + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + ThreadLocalSessionContext.class.getName() + ); - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, - ThreadLocalSessionContext.class.getName()); private static final Class[] SESSION_PROXY_INTERFACES = new Class[] { Session.class, - SessionImplementor.class, - EventSource.class, + SessionImplementor.class, + EventSource.class, TransactionContext.class, LobCreationContext.class }; @@ -91,11 +88,16 @@ public class ThreadLocalSessionContext extends AbstractCurrentSessionContext { /** * A ThreadLocal maintaining current sessions for the given execution thread. * The actual ThreadLocal variable is a java.util.Map to account for - * the possibility for multiple SessionFactorys being used during execution + * the possibility for multiple SessionFactory instances being used during execution * of the given thread. */ - private static final ThreadLocal context = new ThreadLocal(); + private static final ThreadLocal CONTEXT_TL = new ThreadLocal(); + /** + * Constructs a ThreadLocal + * + * @param factory The factory this context will service + */ public ThreadLocalSessionContext(SessionFactoryImplementor factory) { super( factory ); } @@ -122,10 +124,15 @@ public class ThreadLocalSessionContext extends AbstractCurrentSessionContext { private boolean needsWrapping(Session session) { // try to make sure we don't wrap and already wrapped session - return session != null - && ! Proxy.isProxyClass( session.getClass() ) - || ( Proxy.getInvocationHandler( session ) != null - && ! ( Proxy.getInvocationHandler( session ) instanceof TransactionProtectionWrapper ) ); + if ( session != null ) { + if ( Proxy.isProxyClass( session.getClass() ) ) { + final InvocationHandler invocationHandler = Proxy.getInvocationHandler( session ); + if ( invocationHandler != null && TransactionProtectionWrapper.class.isInstance( invocationHandler ) ) { + return false; + } + } + } + return true; } /** @@ -138,13 +145,14 @@ public class ThreadLocalSessionContext extends AbstractCurrentSessionContext { } /** - * Strictly provided for subclassing purposes; specifically to allow long-session + * Strictly provided for sub-classing purposes; specifically to allow long-session * support. *

* This implementation always just opens a new session. * * @return the built or (re)obtained session. */ + @SuppressWarnings("deprecation") protected Session buildOrObtainSession() { return baseSessionBuilder() .autoClose( isAutoCloseEnabled() ) @@ -153,8 +161,8 @@ public class ThreadLocalSessionContext extends AbstractCurrentSessionContext { .openSession(); } - protected CleanupSynch buildCleanupSynch() { - return new CleanupSynch( factory() ); + protected CleanupSync buildCleanupSynch() { + return new CleanupSync( factory() ); } /** @@ -185,12 +193,12 @@ public class ThreadLocalSessionContext extends AbstractCurrentSessionContext { } protected Session wrap(Session session) { - TransactionProtectionWrapper wrapper = new TransactionProtectionWrapper( session ); - Session wrapped = ( Session ) Proxy.newProxyInstance( + final TransactionProtectionWrapper wrapper = new TransactionProtectionWrapper( session ); + final Session wrapped = (Session) Proxy.newProxyInstance( Session.class.getClassLoader(), SESSION_PROXY_INTERFACES, - wrapper - ); + wrapper + ); // yick! need this for proper serialization/deserialization handling... wrapper.setWrapped( wrapped ); return wrapped; @@ -202,13 +210,13 @@ public class ThreadLocalSessionContext extends AbstractCurrentSessionContext { * @param session The session to bind. */ public static void bind(org.hibernate.Session session) { - SessionFactory factory = session.getSessionFactory(); + final SessionFactory factory = session.getSessionFactory(); cleanupAnyOrphanedSession( factory ); doBind( session, factory ); } private static void cleanupAnyOrphanedSession(SessionFactory factory) { - Session orphan = doUnbind( factory, false ); + final Session orphan = doUnbind( factory, false ); if ( orphan != null ) { LOG.alreadySessionBound(); try { @@ -239,7 +247,7 @@ public class ThreadLocalSessionContext extends AbstractCurrentSessionContext { } private static Session existingSession(SessionFactory factory) { - Map sessionMap = sessionMap(); + final Map sessionMap = sessionMap(); if ( sessionMap == null ) { return null; } @@ -247,7 +255,7 @@ public class ThreadLocalSessionContext extends AbstractCurrentSessionContext { } protected static Map sessionMap() { - return context.get(); + return CONTEXT_TL.get(); } @SuppressWarnings({"unchecked"}) @@ -255,42 +263,38 @@ public class ThreadLocalSessionContext extends AbstractCurrentSessionContext { Map sessionMap = sessionMap(); if ( sessionMap == null ) { sessionMap = new HashMap(); - context.set( sessionMap ); + CONTEXT_TL.set( sessionMap ); } sessionMap.put( factory, session ); } private static Session doUnbind(SessionFactory factory, boolean releaseMapIfEmpty) { - Map sessionMap = sessionMap(); Session session = null; + final Map sessionMap = sessionMap(); if ( sessionMap != null ) { - session = ( Session ) sessionMap.remove( factory ); + session = (Session) sessionMap.remove( factory ); if ( releaseMapIfEmpty && sessionMap.isEmpty() ) { - context.set( null ); + CONTEXT_TL.set( null ); } } return session; } /** - * JTA transaction synch used for cleanup of the internal session map. + * Transaction sync used for cleanup of the internal session map. */ - protected static class CleanupSynch implements Synchronization, Serializable { + protected static class CleanupSync implements Synchronization, Serializable { protected final SessionFactory factory; - public CleanupSynch(SessionFactory factory) { + public CleanupSync(SessionFactory factory) { this.factory = factory; } - /** - * {@inheritDoc} - */ + @Override public void beforeCompletion() { } - /** - * {@inheritDoc} - */ + @Override public void afterCompletion(int i) { unbind( factory ); } @@ -304,9 +308,7 @@ public class ThreadLocalSessionContext extends AbstractCurrentSessionContext { this.realSession = realSession; } - /** - * {@inheritDoc} - */ + @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { final String methodName = method.getName(); try { @@ -315,13 +317,13 @@ public class ThreadLocalSessionContext extends AbstractCurrentSessionContext { unbind( realSession.getSessionFactory() ); } else if ( "toString".equals( methodName ) - || "equals".equals( methodName ) - || "hashCode".equals( methodName ) - || "getStatistics".equals( methodName ) - || "isOpen".equals( methodName ) - || "getListeners".equals( methodName ) - ) { + || "equals".equals( methodName ) + || "hashCode".equals( methodName ) + || "getStatistics".equals( methodName ) + || "isOpen".equals( methodName ) + || "getListeners".equals( methodName ) ) { // allow these to go through the the real session no matter what + LOG.tracef( "Allowing invocation [%s] to proceed to real session", methodName ); } else if ( !realSession.isOpen() ) { // essentially, if the real session is closed allow any @@ -329,6 +331,7 @@ public class ThreadLocalSessionContext extends AbstractCurrentSessionContext { // will complain by throwing an appropriate exception; // NOTE that allowing close() above has the same basic effect, // but we capture that there simply to doAfterTransactionCompletion the unbind... + LOG.tracef( "Allowing invocation [%s] to proceed to real (closed) session", methodName ); } else if ( !realSession.getTransaction().isActive() ) { // limit the methods available if no transaction is active @@ -339,21 +342,24 @@ public class ThreadLocalSessionContext extends AbstractCurrentSessionContext { || "getFactory".equals( methodName ) || "getSessionFactory".equals( methodName ) || "getTenantIdentifier".equals( methodName ) ) { - LOG.tracev( "Allowing method [{0}] in non-transacted context", methodName ); + LOG.tracef( "Allowing invocation [%s] to proceed to real (non-transacted) session", methodName ); } else if ( "reconnect".equals( methodName ) || "disconnect".equals( methodName ) ) { // allow these (deprecated) methods to pass through + LOG.tracef( "Allowing invocation [%s] to proceed to real (non-transacted) session - deprecated methods", methodName ); } else { throw new HibernateException( methodName + " is not valid without active transaction" ); } } - LOG.tracev( "Allowing proxied method [{0}] to proceed to real session", methodName ); + LOG.tracef( "Allowing proxy invocation [%s] to proceed to real session", methodName ); return method.invoke( realSession, args ); } catch ( InvocationTargetException e ) { - if (e.getTargetException() instanceof RuntimeException) throw (RuntimeException)e.getTargetException(); - throw e; + if (e.getTargetException() instanceof RuntimeException) { + throw (RuntimeException)e.getTargetException(); + } + throw e; } } diff --git a/hibernate-core/src/main/java/org/hibernate/context/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/context/internal/package-info.java new file mode 100644 index 0000000000..03452df764 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/context/internal/package-info.java @@ -0,0 +1,4 @@ +/** + * Internal implementations and support around "current session" handling. + */ +package org.hibernate.context.internal; diff --git a/hibernate-core/src/main/java/org/hibernate/context/package-info.java b/hibernate-core/src/main/java/org/hibernate/context/package-info.java new file mode 100644 index 0000000000..ed1d98f2ac --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/context/package-info.java @@ -0,0 +1,4 @@ +/** + * Defines support for "current session" feature. + */ +package org.hibernate.context; diff --git a/hibernate-core/src/main/java/org/hibernate/context/spi/AbstractCurrentSessionContext.java b/hibernate-core/src/main/java/org/hibernate/context/spi/AbstractCurrentSessionContext.java index 4ec693e79a..e848dc0aa1 100644 --- a/hibernate-core/src/main/java/org/hibernate/context/spi/AbstractCurrentSessionContext.java +++ b/hibernate-core/src/main/java/org/hibernate/context/spi/AbstractCurrentSessionContext.java @@ -41,6 +41,11 @@ public abstract class AbstractCurrentSessionContext implements CurrentSessionCon this.factory = factory; } + /** + * Access to the SessionFactory + * + * @return The SessionFactory being serviced by this context + */ public SessionFactoryImplementor factory() { return factory; } diff --git a/hibernate-core/src/main/java/org/hibernate/context/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/context/spi/package-info.java new file mode 100644 index 0000000000..102dcbacc1 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/context/spi/package-info.java @@ -0,0 +1,4 @@ +/** + * SPI level contracts around "current session" support. + */ +package org.hibernate.context.spi; diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/AbstractEmptinessExpression.java b/hibernate-core/src/main/java/org/hibernate/criterion/AbstractEmptinessExpression.java index a4f2047ccf..87723ecb62 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/AbstractEmptinessExpression.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/AbstractEmptinessExpression.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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.criterion; import org.hibernate.Criteria; @@ -37,7 +36,7 @@ import org.hibernate.type.CollectionType; import org.hibernate.type.Type; /** - * Implementation of AbstractEmptinessExpression. + * Base expression implementation for (not) emptiness checking of collection properties * * @author Steve Ebersole */ @@ -51,43 +50,50 @@ public abstract class AbstractEmptinessExpression implements Criterion { this.propertyName = propertyName; } + /** + * Should empty rows be excluded? + * + * @return {@code true} Indicates the expression should be 'exists'; {@code false} indicates 'not exists' + */ protected abstract boolean excludeEmpty(); + @Override public final String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { - String entityName = criteriaQuery.getEntityName( criteria, propertyName ); - String actualPropertyName = criteriaQuery.getPropertyName( propertyName ); - String sqlAlias = criteriaQuery.getSQLAlias( criteria, propertyName ); + final String entityName = criteriaQuery.getEntityName( criteria, propertyName ); + final String actualPropertyName = criteriaQuery.getPropertyName( propertyName ); + final String sqlAlias = criteriaQuery.getSQLAlias( criteria, propertyName ); - SessionFactoryImplementor factory = criteriaQuery.getFactory(); - QueryableCollection collectionPersister = getQueryableCollection( entityName, actualPropertyName, factory ); + final SessionFactoryImplementor factory = criteriaQuery.getFactory(); + final QueryableCollection collectionPersister = getQueryableCollection( entityName, actualPropertyName, factory ); - String[] collectionKeys = collectionPersister.getKeyColumnNames(); - String[] ownerKeys = ( ( Loadable ) factory.getEntityPersister( entityName ) ).getIdentifierColumnNames(); + final String[] collectionKeys = collectionPersister.getKeyColumnNames(); + final String[] ownerKeys = ( (Loadable) factory.getEntityPersister( entityName ) ).getIdentifierColumnNames(); - String innerSelect = "(select 1 from " + collectionPersister.getTableName() - + " where " - + new ConditionFragment().setTableAlias( sqlAlias ).setCondition( ownerKeys, collectionKeys ).toFragmentString() - + ")"; + final String innerSelect = "(select 1 from " + collectionPersister.getTableName() + " where " + + new ConditionFragment().setTableAlias( sqlAlias ).setCondition( ownerKeys, collectionKeys ).toFragmentString() + + ")"; return excludeEmpty() - ? "exists " + innerSelect - : "not exists " + innerSelect; + ? "exists " + innerSelect + : "not exists " + innerSelect; } - protected QueryableCollection getQueryableCollection(String entityName, String propertyName, SessionFactoryImplementor factory) - throws HibernateException { - PropertyMapping ownerMapping = ( PropertyMapping ) factory.getEntityPersister( entityName ); - Type type = ownerMapping.toType( propertyName ); + protected QueryableCollection getQueryableCollection( + String entityName, + String propertyName, + SessionFactoryImplementor factory) throws HibernateException { + final PropertyMapping ownerMapping = (PropertyMapping) factory.getEntityPersister( entityName ); + final Type type = ownerMapping.toType( propertyName ); if ( !type.isCollectionType() ) { throw new MappingException( - "Property path [" + entityName + "." + propertyName + "] does not reference a collection" + "Property path [" + entityName + "." + propertyName + "] does not reference a collection" ); } - String role = ( ( CollectionType ) type ).getRole(); + final String role = ( (CollectionType) type ).getRole(); try { - return ( QueryableCollection ) factory.getCollectionPersister( role ); + return (QueryableCollection) factory.getCollectionPersister( role ); } catch ( ClassCastException cce ) { throw new QueryException( "collection role is not queryable: " + role ); @@ -97,11 +103,13 @@ public abstract class AbstractEmptinessExpression implements Criterion { } } + @Override public final TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { + throws HibernateException { return NO_VALUES; } + @Override public final String toString() { return propertyName + ( excludeEmpty() ? " is not empty" : " is empty" ); } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/AggregateProjection.java b/hibernate-core/src/main/java/org/hibernate/criterion/AggregateProjection.java index 42f7744c57..c4528b55d1 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/AggregateProjection.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/AggregateProjection.java @@ -52,13 +52,7 @@ public class AggregateProjection extends SimpleProjection { return propertyName; } - public String toString() { - return functionName + "(" + propertyName + ')'; - } - - /** - * {@inheritDoc} - */ + @Override public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { return new Type[] { getFunction( criteriaQuery ).getReturnType( @@ -68,9 +62,7 @@ public class AggregateProjection extends SimpleProjection { }; } - /** - * {@inheritDoc} - */ + @Override public String toSqlString(Criteria criteria, int loc, CriteriaQuery criteriaQuery) throws HibernateException { final String functionFragment = getFunction( criteriaQuery ).render( criteriaQuery.getType( criteria, getPropertyName() ), @@ -85,7 +77,7 @@ public class AggregateProjection extends SimpleProjection { } protected SQLFunction getFunction(String functionName, CriteriaQuery criteriaQuery) { - SQLFunction function = criteriaQuery.getFactory() + final SQLFunction function = criteriaQuery.getFactory() .getSqlFunctionRegistry() .findSQLFunction( functionName ); if ( function == null ) { @@ -101,4 +93,10 @@ public class AggregateProjection extends SimpleProjection { protected List buildFunctionParameterList(String column) { return Collections.singletonList( column ); } + + @Override + public String toString() { + return functionName + "(" + propertyName + ')'; + } + } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/AliasedProjection.java b/hibernate-core/src/main/java/org/hibernate/criterion/AliasedProjection.java index 20d6af7634..164f63db4b 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/AliasedProjection.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/AliasedProjection.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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.criterion; import org.hibernate.Criteria; @@ -28,71 +27,80 @@ import org.hibernate.HibernateException; import org.hibernate.type.Type; /** + * Represents a projection that specifies an alias + * * @author Gavin King */ public class AliasedProjection implements EnhancedProjection { - private final Projection projection; private final String alias; - - public String toString() { - return projection.toString() + " as " + alias; - } - + protected AliasedProjection(Projection projection, String alias) { this.projection = projection; this.alias = alias; } - public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery) - throws HibernateException { - return projection.toSqlString(criteria, position, criteriaQuery); + @Override + public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery) throws HibernateException { + return projection.toSqlString( criteria, position, criteriaQuery ); } + @Override public String toGroupSqlString(Criteria criteria, CriteriaQuery criteriaQuery) { - return projection.toGroupSqlString(criteria, criteriaQuery); + return projection.toGroupSqlString( criteria, criteriaQuery ); } - public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - return projection.getTypes(criteria, criteriaQuery); + @Override + public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { + return projection.getTypes( criteria, criteriaQuery ); } + @Override public String[] getColumnAliases(int loc) { - return projection.getColumnAliases(loc); + return projection.getColumnAliases( loc ); } + @Override public String[] getColumnAliases(int loc, Criteria criteria, CriteriaQuery criteriaQuery) { - return projection instanceof EnhancedProjection ? - ( ( EnhancedProjection ) projection ).getColumnAliases( loc, criteria, criteriaQuery ) : - getColumnAliases( loc ); + return projection instanceof EnhancedProjection + ? ( (EnhancedProjection) projection ).getColumnAliases( loc, criteria, criteriaQuery ) + : getColumnAliases( loc ); } - public Type[] getTypes(String alias, Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - return this.alias.equals(alias) ? - getTypes(criteria, criteriaQuery) : - null; + @Override + public Type[] getTypes(String alias, Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { + return this.alias.equals( alias ) + ? getTypes( criteria, criteriaQuery ) + : null; } + @Override public String[] getColumnAliases(String alias, int loc) { - return this.alias.equals(alias) ? - getColumnAliases(loc) : - null; + return this.alias.equals( alias ) + ? getColumnAliases( loc ) + : null; } + @Override public String[] getColumnAliases(String alias, int loc, Criteria criteria, CriteriaQuery criteriaQuery) { - return this.alias.equals(alias) ? - getColumnAliases( loc, criteria, criteriaQuery ) : - null; + return this.alias.equals( alias ) + ? getColumnAliases( loc, criteria, criteriaQuery ) + : null; } + @Override public String[] getAliases() { - return new String[]{ alias }; + return new String[] { alias }; } + @Override public boolean isGrouped() { return projection.isGrouped(); } + @Override + public String toString() { + return projection.toString() + " as " + alias; + } + } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/AvgProjection.java b/hibernate-core/src/main/java/org/hibernate/criterion/AvgProjection.java index d10dfbc7f6..fee6a732a5 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/AvgProjection.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/AvgProjection.java @@ -23,14 +23,18 @@ */ package org.hibernate.criterion; - /** * An avg() projection * * @author Gavin King */ public class AvgProjection extends AggregateProjection { + /** + * Constructs the AvgProjection + * + * @param propertyName The name of the property to average + */ public AvgProjection(String propertyName) { - super("avg", propertyName); + super( "avg", propertyName ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/BetweenExpression.java b/hibernate-core/src/main/java/org/hibernate/criterion/BetweenExpression.java index 5c62161421..ba755db02c 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/BetweenExpression.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/BetweenExpression.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,9 +20,9 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; + import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.engine.spi.TypedValue; @@ -30,10 +30,10 @@ import org.hibernate.internal.util.StringHelper; /** * Constrains a property to between two values + * * @author Gavin King */ public class BetweenExpression implements Criterion { - private final String propertyName; private final Object lo; private final Object hi; @@ -44,24 +44,22 @@ public class BetweenExpression implements Criterion { this.hi = hi; } - public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - return StringHelper.join( - " and ", - StringHelper.suffix( criteriaQuery.findColumns(propertyName, criteria), " between ? and ?" ) - ); - - //TODO: get SQL rendering out of this package! + @Override + public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { + final String[] columns = criteriaQuery.findColumns( propertyName, criteria ); + final String[] expressions = StringHelper.suffix( columns, " between ? and ?" ); + return StringHelper.join( " and ", expressions ); } - public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { + @Override + public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { return new TypedValue[] { - criteriaQuery.getTypedValue(criteria, propertyName, lo), - criteriaQuery.getTypedValue(criteria, propertyName, hi) + criteriaQuery.getTypedValue( criteria, propertyName, lo ), + criteriaQuery.getTypedValue( criteria, propertyName, hi ) }; } + @Override public String toString() { return propertyName + " between " + lo + " and " + hi; } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/Conjunction.java b/hibernate-core/src/main/java/org/hibernate/criterion/Conjunction.java index d804a0d556..77bb514647 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/Conjunction.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/Conjunction.java @@ -24,10 +24,22 @@ package org.hibernate.criterion; /** + * Defines a conjunction (AND series). + * * @author Gavin King + * @author Steve Ebersole + * + * @see Disjunction */ public class Conjunction extends Junction { + /** + * Constructs a Conjunction + */ public Conjunction() { super( Nature.AND ); } + + protected Conjunction(Criterion... criterion) { + super( Nature.AND, criterion ); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/CountProjection.java b/hibernate-core/src/main/java/org/hibernate/criterion/CountProjection.java index 9ad6da6996..3367df3457 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/CountProjection.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/CountProjection.java @@ -29,16 +29,50 @@ import java.util.List; import org.hibernate.Criteria; /** - * A count + * A count projection + * * @author Gavin King */ public class CountProjection extends AggregateProjection { private boolean distinct; + /** + * Constructs the count projection. + * + * @param prop The property name + * + * @see Projections#count(String) + * @see Projections#countDistinct(String) + */ protected CountProjection(String prop) { - super("count", prop); + super( "count", prop ); } + @Override + protected List buildFunctionParameterList(Criteria criteria, CriteriaQuery criteriaQuery) { + final String[] cols = criteriaQuery.getColumns( propertyName, criteria ); + return ( distinct ? buildCountDistinctParameterList( cols ) : Arrays.asList( cols ) ); + } + + @SuppressWarnings("unchecked") + private List buildCountDistinctParameterList(String[] cols) { + final List params = new ArrayList( cols.length + 1 ); + params.add( "distinct" ); + params.addAll( Arrays.asList( cols ) ); + return params; + } + + /** + * Sets the count as being distinct + * + * @return {@code this}, for method chaining + */ + public CountProjection setDistinct() { + distinct = true; + return this; + } + + @Override public String toString() { if ( distinct ) { return "distinct " + super.toString(); @@ -48,20 +82,4 @@ public class CountProjection extends AggregateProjection { } } - protected List buildFunctionParameterList(Criteria criteria, CriteriaQuery criteriaQuery) { - String cols[] = criteriaQuery.getColumns( propertyName, criteria ); - return ( distinct ? buildCountDistinctParameterList( cols ) : Arrays.asList( cols ) ); - } - - private List buildCountDistinctParameterList(String[] cols) { - List params = new ArrayList( cols.length + 1 ); - params.add( "distinct" ); - params.addAll( Arrays.asList( cols ) ); - return params; - } - - public CountProjection setDistinct() { - distinct = true; - return this; - } } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/CriteriaQuery.java b/hibernate-core/src/main/java/org/hibernate/criterion/CriteriaQuery.java index 10c967d9c2..8e82720202 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/CriteriaQuery.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/CriteriaQuery.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,9 +20,9 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; + import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SessionFactoryImplementor; @@ -38,93 +38,183 @@ import org.hibernate.type.Type; * @author Gavin King */ public interface CriteriaQuery { + /** + * Provides access to the SessionFactory + * + * @return The SessionFactory + */ public SessionFactoryImplementor getFactory(); /** - * Get the names of the columns mapped by a property path, - * ignoring projection aliases - * @throws org.hibernate.QueryException if the property maps to more than 1 column + * Resolve a property path to the name of the column it maps to. Ignores projection aliases. + * + * @param criteria The overall criteria + * @param propertyPath The property path to resolve + * + * @return The column name + * + * @throws HibernateException if the property maps to more than 1 column, or if the property could not be resolved + * + * @see #getColumns */ - public String getColumn(Criteria criteria, String propertyPath) - throws HibernateException; - - /** - * Get the names of the columns mapped by a property path, - * ignoring projection aliases - */ - public String[] getColumns(String propertyPath, Criteria criteria) - throws HibernateException; + public String getColumn(Criteria criteria, String propertyPath) throws HibernateException; /** - * Get the names of the columns mapped by a property path; if the - * property path is not found in criteria, try the "outer" query. - * Projection aliases are ignored. + * Resolve a property path to the names of the columns it maps to. Ignores projection aliases + * + * @param criteria The criteria + * @param propertyPath The property path to resolve + * + * @return The column names + * + * @throws HibernateException if the property maps to more than 1 column, or if the property could not be resolved */ - public String[] findColumns(String propertyPath, Criteria criteria) - throws HibernateException; + public String[] getColumns(String propertyPath, Criteria criteria) throws HibernateException; /** - * Get the type of a property path, ignoring projection aliases + * Get the names of the columns mapped by a property path; if the property path is not found in criteria, try + * the "outer" query. Projection aliases are ignored. + * + * @param criteria The criteria + * @param propertyPath The property path to resolve + * + * @return The column names + * + * @throws HibernateException if the property could not be resolved */ - public Type getType(Criteria criteria, String propertyPath) - throws HibernateException; + public String[] findColumns(String propertyPath, Criteria criteria) throws HibernateException; /** - * Get the names of the columns mapped by a property path + * Get the type of a property path. + * + * @param criteria The criteria + * @param propertyPath The property path to resolve + * + * @return The type + * + * @throws HibernateException if the property could not be resolved */ - public String[] getColumnsUsingProjection(Criteria criteria, String propertyPath) - throws HibernateException; + public Type getType(Criteria criteria, String propertyPath) throws HibernateException; /** - * Get the type of a property path + * Get the names of the columns mapped by a property path. Here, the property path can refer to + * a projection alias. + * + * @param criteria The criteria + * @param propertyPath The property path to resolve or projection alias + * + * @return The column names + * + * @throws HibernateException if the property/alias could not be resolved */ - public Type getTypeUsingProjection(Criteria criteria, String propertyPath) - throws HibernateException; + public String[] getColumnsUsingProjection(Criteria criteria, String propertyPath) throws HibernateException; /** - * Get the a typed value for the given property value. + * Get the type of a property path. Here, the property path can refer to a projection alias. + * + * @param criteria The criteria + * @param propertyPath The property path to resolve or projection alias + * + * @return The type + * + * @throws HibernateException if the property/alias could not be resolved */ - public TypedValue getTypedValue(Criteria criteria, String propertyPath, Object value) - throws HibernateException; - + public Type getTypeUsingProjection(Criteria criteria, String propertyPath) throws HibernateException; + + /** + * Build a typed-value for the property/value combo. Essentially the same as manually building a TypedValue + * using the given value and the resolved type using {@link #getTypeUsingProjection}. + * + * @param criteria The criteria query + * @param propertyPath The property path/alias to resolve to type. + * @param value The value + * + * @return The TypedValue + * + * @throws HibernateException if the property/alias could not be resolved + */ + public TypedValue getTypedValue(Criteria criteria, String propertyPath, Object value) throws HibernateException; + /** * Get the entity name of an entity + * + * @param criteria The criteria + * + * @return The entity name */ public String getEntityName(Criteria criteria); /** - * Get the entity name of an entity, taking into account - * the qualifier of the property path + * Get the entity name of an entity, taking into account the qualifier of the property path + * + * @param criteria The criteria + * @param propertyPath The property path that (supposedly) references an entity + * + * @return The entity name */ public String getEntityName(Criteria criteria, String propertyPath); /** * Get the root table alias of an entity + * + * @param criteria The criteria + * + * @return The SQL table alias for the given criteria */ - public String getSQLAlias(Criteria subcriteria); + public String getSQLAlias(Criteria criteria); /** * Get the root table alias of an entity, taking into account * the qualifier of the property path + * + * @param criteria The criteria + * @param propertyPath The property path whose SQL alias should be returned. + * + * @return The SQL table alias for the given criteria */ public String getSQLAlias(Criteria criteria, String propertyPath); /** * Get the property name, given a possibly qualified property name + * + * @param propertyName The (possibly qualified) property name + * + * @return The simple property name */ public String getPropertyName(String propertyName); /** * Get the identifier column names of this entity + * + * @param criteria The criteria + * + * @return The identifier column names */ - public String[] getIdentifierColumns(Criteria subcriteria); + public String[] getIdentifierColumns(Criteria criteria); /** * Get the identifier type of this entity + * + * @param criteria The criteria + * + * @return The identifier type. + */ + public Type getIdentifierType(Criteria criteria); + + /** + * Build a TypedValue for the given identifier value. + * + * @param criteria The criteria whose identifier is referenced. + * @param value The identifier value + * + * @return The TypedValue + */ + public TypedValue getTypedIdentifierValue(Criteria criteria, Object value); + + /** + * Generate a unique SQL alias + * + * @return The generated alias */ - public Type getIdentifierType(Criteria subcriteria); - - public TypedValue getTypedIdentifierValue(Criteria subcriteria, Object value); - public String generateSQLAlias(); -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/CriteriaSpecification.java b/hibernate-core/src/main/java/org/hibernate/criterion/CriteriaSpecification.java index de097e63c7..980754d2b1 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/CriteriaSpecification.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/CriteriaSpecification.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,9 +20,9 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; + import org.hibernate.sql.JoinType; import org.hibernate.transform.AliasToEntityMapResultTransformer; import org.hibernate.transform.DistinctRootEntityResultTransformer; @@ -31,6 +31,8 @@ import org.hibernate.transform.ResultTransformer; import org.hibernate.transform.RootEntityResultTransformer; /** + * Commonality between different types of Criteria. + * * @author Gavin King */ public interface CriteriaSpecification { @@ -62,24 +64,27 @@ public interface CriteriaSpecification { /** * Specifies joining to an entity based on an inner join. - * @deprecated use {@link JoinType#INNER_JOIN} + * + * @deprecated use {@link org.hibernate.sql.JoinType#INNER_JOIN} */ @Deprecated - public static final int INNER_JOIN = org.hibernate.sql.JoinFragment.INNER_JOIN; + public static final int INNER_JOIN = JoinType.INNER_JOIN.getJoinTypeValue(); /** * Specifies joining to an entity based on a full join. - * @deprecated use {@link JoinType#FULL_JOIN} + * + * @deprecated use {@link org.hibernate.sql.JoinType#FULL_JOIN} */ @Deprecated - public static final int FULL_JOIN = org.hibernate.sql.JoinFragment.FULL_JOIN; + public static final int FULL_JOIN = JoinType.FULL_JOIN.getJoinTypeValue(); /** * Specifies joining to an entity based on a left outer join. - * @deprecated use {@link JoinType#LEFT_OUTER_JOIN} + * + * @deprecated use {@link org.hibernate.sql.JoinType#LEFT_OUTER_JOIN} */ @Deprecated - public static final int LEFT_JOIN = org.hibernate.sql.JoinFragment.LEFT_OUTER_JOIN; + public static final int LEFT_JOIN = JoinType.LEFT_OUTER_JOIN.getJoinTypeValue(); } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/DetachedCriteria.java b/hibernate-core/src/main/java/org/hibernate/criterion/DetachedCriteria.java index 57c93799ed..c4074107c5 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/DetachedCriteria.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/DetachedCriteria.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,14 +20,13 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; + import java.io.Serializable; import org.hibernate.Criteria; import org.hibernate.FetchMode; -import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.Session; import org.hibernate.engine.spi.SessionImplementor; @@ -36,186 +35,412 @@ import org.hibernate.sql.JoinType; import org.hibernate.transform.ResultTransformer; /** - * Some applications need to create criteria queries in "detached - * mode", where the Hibernate session is not available. This class - * may be instantiated anywhere, and then a Criteria - * may be obtained by passing a session to - * getExecutableCriteria(). All methods have the - * same semantics and behavior as the corresponding methods of the - * Criteria interface. - * - * @see org.hibernate.Criteria + * Models a detached form of a Criteria (not associated with a Session). + * + * Some applications need to create criteria queries in "detached mode", where the Hibernate Session is + * not available. Applications would create a DetachableCriteria to describe the query, and then later + * associated it with a Session to obtain the "executable" Criteria: + * + * DetachedCriteria detached = new DetachedCriteria(); + * ... + * Criteria criteria = detached.getExecutableCriteria( session ); + * ... + * criteria.list(); + * + * + * All methods have the same semantics and behavior as the corresponding methods of the Criteria interface. + * * @author Gavin King + * + * @see org.hibernate.Criteria */ public class DetachedCriteria implements CriteriaSpecification, Serializable { - private final CriteriaImpl impl; private final Criteria criteria; - + protected DetachedCriteria(String entityName) { - impl = new CriteriaImpl(entityName, null); + impl = new CriteriaImpl( entityName, null ); criteria = impl; } - + protected DetachedCriteria(String entityName, String alias) { - impl = new CriteriaImpl(entityName, alias, null); + impl = new CriteriaImpl( entityName, alias, null ); criteria = impl; } - + protected DetachedCriteria(CriteriaImpl impl, Criteria criteria) { this.impl = impl; this.criteria = criteria; } - + /** - * Get an executable instance of Criteria, - * to actually run the query. + * Get an executable instance of Criteria to actually run the query. + * + * @param session The session to associate the built Criteria with + * + * @return The "executable" Criteria */ public Criteria getExecutableCriteria(Session session) { - impl.setSession( ( SessionImplementor ) session ); + impl.setSession( (SessionImplementor) session ); return impl; } - - public static DetachedCriteria forEntityName(String entityName) { - return new DetachedCriteria(entityName); - } - - public static DetachedCriteria forEntityName(String entityName, String alias) { - return new DetachedCriteria(entityName, alias); - } - - public static DetachedCriteria forClass(Class clazz) { - return new DetachedCriteria( clazz.getName() ); - } - - public static DetachedCriteria forClass(Class clazz, String alias) { - return new DetachedCriteria( clazz.getName() , alias ); - } - - public DetachedCriteria add(Criterion criterion) { - criteria.add(criterion); - return this; - } - - public DetachedCriteria addOrder(Order order) { - criteria.addOrder(order); - return this; - } - - public DetachedCriteria createAlias(String associationPath, String alias) - throws HibernateException { - criteria.createAlias(associationPath, alias); - return this; - } - - public DetachedCriteria createCriteria(String associationPath, String alias) - throws HibernateException { - return new DetachedCriteria( impl, criteria.createCriteria(associationPath, alias) ); - } - - public DetachedCriteria createCriteria(String associationPath) - throws HibernateException { - return new DetachedCriteria( impl, criteria.createCriteria(associationPath) ); - } + /** + * Obtain the alias associated with this DetachedCriteria + * + * @return The alias + */ public String getAlias() { return criteria.getAlias(); } - public DetachedCriteria setFetchMode(String associationPath, FetchMode mode) - throws HibernateException { - criteria.setFetchMode(associationPath, mode); - return this; - } - - public DetachedCriteria setProjection(Projection projection) { - criteria.setProjection(projection); - return this; - } - - public DetachedCriteria setResultTransformer(ResultTransformer resultTransformer) { - criteria.setResultTransformer(resultTransformer); - return this; - } - - public String toString() { - return "DetachableCriteria(" + criteria.toString() + ')'; - } - + /** + * Retrieve the CriteriaImpl used internally to hold the DetachedCriteria state + * + * @return The internally maintained CriteriaImpl + */ CriteriaImpl getCriteriaImpl() { return impl; } - public DetachedCriteria createAlias(String associationPath, String alias, JoinType joinType) throws HibernateException { - criteria.createAlias(associationPath, alias, joinType); - return this; - } - - public DetachedCriteria createAlias(String associationPath, String alias, JoinType joinType, Criterion withClause) throws HibernateException { - criteria.createAlias(associationPath, alias, joinType, withClause); - return this; - } - - public DetachedCriteria createCriteria(String associationPath, JoinType joinType) throws HibernateException { - return new DetachedCriteria(impl, criteria.createCriteria(associationPath, joinType)); - } - - public DetachedCriteria createCriteria(String associationPath, String alias, JoinType joinType) throws HibernateException { - return new DetachedCriteria(impl, criteria.createCriteria(associationPath, alias, joinType)); - } - - public DetachedCriteria createCriteria(String associationPath, String alias, JoinType joinType, Criterion withClause) throws HibernateException { - return new DetachedCriteria(impl, criteria.createCriteria(associationPath, alias, joinType, withClause)); + /** + * Static builder to create a DetachedCriteria for the given entity. + * + * @param entityName The name of the entity to create a DetachedCriteria for + * + * @return The DetachedCriteria + */ + @SuppressWarnings("UnusedDeclaration") + public static DetachedCriteria forEntityName(String entityName) { + return new DetachedCriteria( entityName ); } /** + * Static builder to create a DetachedCriteria for the given entity. + * + * @param entityName The name of the entity to create a DetachedCriteria for + * @param alias The alias to apply to the entity + * + * @return The DetachedCriteria + */ + @SuppressWarnings("UnusedDeclaration") + public static DetachedCriteria forEntityName(String entityName, String alias) { + return new DetachedCriteria( entityName, alias ); + } + + /** + * Static builder to create a DetachedCriteria for the given entity, by its Class. + * + * @param clazz The entity class + * + * @return The DetachedCriteria + */ + public static DetachedCriteria forClass(Class clazz) { + return new DetachedCriteria( clazz.getName() ); + } + + /** + * Static builder to create a DetachedCriteria for the given entity, by its Class. + * + * @param clazz The entity class + * @param alias The alias to apply to the entity + * + * @return The DetachedCriteria + */ + public static DetachedCriteria forClass(Class clazz, String alias) { + return new DetachedCriteria( clazz.getName() , alias ); + } + + /** + * Add a restriction + * + * @param criterion The restriction + * + * @return {@code this}, for method chaining + */ + public DetachedCriteria add(Criterion criterion) { + criteria.add( criterion ); + return this; + } + + /** + * Adds an ordering + * + * @param order The ordering + * + * @return {@code this}, for method chaining + */ + public DetachedCriteria addOrder(Order order) { + criteria.addOrder( order ); + return this; + } + + /** + * Set the fetch mode for a given association + * + * @param associationPath The association path + * @param mode The fetch mode to apply + * + * @return {@code this}, for method chaining + */ + public DetachedCriteria setFetchMode(String associationPath, FetchMode mode) { + criteria.setFetchMode( associationPath, mode ); + return this; + } + + /** + * Set the projection to use. + * + * @param projection The projection to use + * + * @return {@code this}, for method chaining + */ + public DetachedCriteria setProjection(Projection projection) { + criteria.setProjection( projection ); + return this; + } + + /** + * Set the result transformer to use. + * + * @param resultTransformer The result transformer to use + * + * @return {@code this}, for method chaining + */ + public DetachedCriteria setResultTransformer(ResultTransformer resultTransformer) { + criteria.setResultTransformer( resultTransformer ); + return this; + } + + /** + * Creates an association path alias within this DetachedCriteria. The alias can then be used in further + * alias creations or restrictions, etc. + * + * @param associationPath The association path + * @param alias The alias to apply to that association path + * + * @return {@code this}, for method chaining + */ + public DetachedCriteria createAlias(String associationPath, String alias) { + criteria.createAlias( associationPath, alias ); + return this; + } + + /** + * Creates an association path alias within this DetachedCriteria specifying the type of join. The alias + * can then be used in further alias creations or restrictions, etc. + * + * @param associationPath The association path + * @param alias The alias to apply to that association path + * @param joinType The type of join to use + * + * @return {@code this}, for method chaining + */ + public DetachedCriteria createAlias(String associationPath, String alias, JoinType joinType) { + criteria.createAlias( associationPath, alias, joinType ); + return this; + } + + /** + * Creates an association path alias within this DetachedCriteria specifying the type of join. The alias + * can then be used in further alias creations or restrictions, etc. + * + * @param associationPath The association path + * @param alias The alias to apply to that association path + * @param joinType The type of join to use + * @param withClause An additional restriction on the join + * + * @return {@code this}, for method chaining + */ + public DetachedCriteria createAlias(String associationPath, String alias, JoinType joinType, Criterion withClause) { + criteria.createAlias( associationPath, alias, joinType, withClause ); + return this; + } + + /** + * Deprecated! + * + * @param associationPath The association path + * @param alias The alias to apply to that association path + * @param joinType The type of join to use + * + * @return {@code this}, for method chaining + * * @deprecated use {@link #createAlias(String, String, JoinType)} */ @Deprecated - public DetachedCriteria createAlias(String associationPath, String alias, int joinType) throws HibernateException { - return createAlias( associationPath, alias, JoinType.parse( joinType ) ); - } + public DetachedCriteria createAlias(String associationPath, String alias, int joinType) { + return createAlias( associationPath, alias, JoinType.parse( joinType ) ); + } + /** + * Deprecated! + * + * @param associationPath The association path + * @param alias The alias to apply to that association path + * @param joinType The type of join to use + * @param withClause An additional restriction on the join + * + * @return {@code this}, for method chaining + * * @deprecated use {@link #createAlias(String, String, JoinType, Criterion)} */ @Deprecated - public DetachedCriteria createAlias(String associationPath, String alias, int joinType, Criterion withClause) throws HibernateException { + public DetachedCriteria createAlias(String associationPath, String alias, int joinType, Criterion withClause) { return createAlias( associationPath, alias, JoinType.parse( joinType ), withClause ); } + /** + * Creates an nested DetachedCriteria representing the association path. + * + * @param associationPath The association path + * @param alias The alias to apply to that association path + * + * @return the newly created, nested DetachedCriteria + */ + public DetachedCriteria createCriteria(String associationPath, String alias) { + return new DetachedCriteria( impl, criteria.createCriteria( associationPath, alias ) ); + } + + /** + * Creates an nested DetachedCriteria representing the association path. + * + * @param associationPath The association path + * + * @return the newly created, nested DetachedCriteria + */ + public DetachedCriteria createCriteria(String associationPath) { + return new DetachedCriteria( impl, criteria.createCriteria( associationPath ) ); + } + + /** + * Creates an nested DetachedCriteria representing the association path, specifying the type of join to use. + * + * @param associationPath The association path + * @param joinType The type of join to use + * + * @return the newly created, nested DetachedCriteria + */ + public DetachedCriteria createCriteria(String associationPath, JoinType joinType) { + return new DetachedCriteria( impl, criteria.createCriteria( associationPath, joinType ) ); + } + + /** + * Creates an nested DetachedCriteria representing the association path, specifying the type of join to use. + * + * @param associationPath The association path + * @param alias The alias to associate with this "join". + * @param joinType The type of join to use + * + * @return the newly created, nested DetachedCriteria + */ + public DetachedCriteria createCriteria(String associationPath, String alias, JoinType joinType) { + return new DetachedCriteria( impl, criteria.createCriteria( associationPath, alias, joinType ) ); + } + + /** + * Creates an nested DetachedCriteria representing the association path, specifying the type of join to use and + * an additional join restriction. + * + * @param associationPath The association path + * @param alias The alias to associate with this "join". + * @param joinType The type of join to use + * @param withClause The additional join restriction + * + * @return the newly created, nested DetachedCriteria + */ + public DetachedCriteria createCriteria(String associationPath, String alias, JoinType joinType, Criterion withClause) { + return new DetachedCriteria(impl, criteria.createCriteria( associationPath, alias, joinType, withClause ) ); + } + + /** + * Deprecated! + * + * @param associationPath The association path + * @param joinType The type of join to use + * + * @return the newly created, nested DetachedCriteria + * * @deprecated use {@link #createCriteria(String, JoinType)} */ @Deprecated - public DetachedCriteria createCriteria(String associationPath, int joinType) throws HibernateException { - return createCriteria( associationPath, JoinType.parse( joinType ) ); - } + public DetachedCriteria createCriteria(String associationPath, int joinType) { + return createCriteria( associationPath, JoinType.parse( joinType ) ); + } + /** + * Deprecated! + * + * @param associationPath The association path + * @param alias The alias + * @param joinType The type of join to use + * + * @return the newly created, nested DetachedCriteria + * * @deprecated use {@link #createCriteria(String, String, JoinType)} */ @Deprecated - public DetachedCriteria createCriteria(String associationPath, String alias, int joinType) throws HibernateException { - return createCriteria( associationPath, alias, JoinType.parse( joinType ) ); - } + public DetachedCriteria createCriteria(String associationPath, String alias, int joinType) { + return createCriteria( associationPath, alias, JoinType.parse( joinType ) ); + } + /** + * Deprecated! + * + * @param associationPath The association path + * @param alias The alias to associate with this "join". + * @param joinType The type of join to use + * @param withClause The additional join restriction + * + * @return the newly created, nested DetachedCriteria + * * @deprecated use {@link #createCriteria(String, String, JoinType, Criterion)} */ @Deprecated - public DetachedCriteria createCriteria(String associationPath, String alias, int joinType, Criterion withClause) throws HibernateException { + public DetachedCriteria createCriteria(String associationPath, String alias, int joinType, Criterion withClause) { return createCriteria( associationPath, alias, JoinType.parse( joinType ), withClause ); } - + + /** + * Set the SQL comment to use. + * + * @param comment The SQL comment to use + * + * @return {@code this}, for method chaining + */ public DetachedCriteria setComment(String comment) { - criteria.setComment(comment); - return this; - } + criteria.setComment( comment ); + return this; + } - public DetachedCriteria setLockMode(LockMode lockMode) { - criteria.setLockMode(lockMode); - return this; - } + /** + * Set the lock mode to use. + * + * @param lockMode The lock mode to use + * + * @return {@code this}, for method chaining + */ + public DetachedCriteria setLockMode(LockMode lockMode) { + criteria.setLockMode( lockMode ); + return this; + } + + /** + * Set an alias-specific lock mode. The specified lock mode applies only to that alias. + * + * @param alias The alias to apply the lock to + * @param lockMode The lock mode to use. + * + * @return {@code this}, for method chaining + */ + public DetachedCriteria setLockMode(String alias, LockMode lockMode) { + criteria.setLockMode( alias, lockMode ); + return this; + } + + @Override + public String toString() { + return "DetachableCriteria(" + criteria.toString() + ')'; + } - public DetachedCriteria setLockMode(String alias, LockMode lockMode) { - criteria.setLockMode(alias, lockMode); - return this; - } } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/Disjunction.java b/hibernate-core/src/main/java/org/hibernate/criterion/Disjunction.java index 4c2032c1bf..3ffa5ab2ce 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/Disjunction.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/Disjunction.java @@ -24,10 +24,22 @@ package org.hibernate.criterion; /** + * Defines a disjunction (OR series). + * * @author Gavin King + * @author Steve Ebersole + * + * @see Conjunction */ public class Disjunction extends Junction { + /** + * Constructs a Disjunction + */ protected Disjunction() { super( Nature.OR ); } + + protected Disjunction(Criterion[] conditions) { + super( Nature.OR, conditions ); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/Distinct.java b/hibernate-core/src/main/java/org/hibernate/criterion/Distinct.java index 1237a8a462..457fb68ead 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/Distinct.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/Distinct.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,73 +20,85 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; + import org.hibernate.Criteria; -import org.hibernate.HibernateException; import org.hibernate.type.Type; /** + * A wrappedProjection that is a wrapper around other projections to apply distinction. + * * @author Gavin King */ public class Distinct implements EnhancedProjection { + private final Projection wrappedProjection; - private final Projection projection; - - public Distinct(Projection proj) { - this.projection = proj; + /** + * Constructs a Distinct + * + * @param wrappedProjection The wrapped projection + */ + public Distinct(Projection wrappedProjection) { + this.wrappedProjection = wrappedProjection; } - public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery) - throws HibernateException { - return "distinct " + projection.toSqlString(criteria, position, criteriaQuery); + @Override + public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery) { + return "distinct " + wrappedProjection.toSqlString( criteria, position, criteriaQuery ); } - public String toGroupSqlString(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - return projection.toGroupSqlString(criteria, criteriaQuery); + @Override + public String toGroupSqlString(Criteria criteria, CriteriaQuery criteriaQuery) { + return wrappedProjection.toGroupSqlString( criteria, criteriaQuery ); } - public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - return projection.getTypes(criteria, criteriaQuery); + @Override + public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery) { + return wrappedProjection.getTypes( criteria, criteriaQuery ); } - public Type[] getTypes(String alias, Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - return projection.getTypes(alias, criteria, criteriaQuery); + @Override + public Type[] getTypes(String alias, Criteria criteria, CriteriaQuery criteriaQuery) { + return wrappedProjection.getTypes( alias, criteria, criteriaQuery ); } + @Override public String[] getColumnAliases(int loc) { - return projection.getColumnAliases(loc); + return wrappedProjection.getColumnAliases( loc ); } + @Override public String[] getColumnAliases(int loc, Criteria criteria, CriteriaQuery criteriaQuery) { - return projection instanceof EnhancedProjection ? - ( ( EnhancedProjection ) projection ).getColumnAliases( loc, criteria, criteriaQuery ) : - getColumnAliases( loc ); + return wrappedProjection instanceof EnhancedProjection + ? ( (EnhancedProjection) wrappedProjection).getColumnAliases( loc, criteria, criteriaQuery ) + : getColumnAliases( loc ); } + @Override public String[] getColumnAliases(String alias, int loc) { - return projection.getColumnAliases(alias, loc); + return wrappedProjection.getColumnAliases( alias, loc ); } + @Override public String[] getColumnAliases(String alias, int loc, Criteria criteria, CriteriaQuery criteriaQuery) { - return projection instanceof EnhancedProjection ? - ( ( EnhancedProjection ) projection ).getColumnAliases( alias, loc, criteria, criteriaQuery ) : - getColumnAliases( alias, loc ); + return wrappedProjection instanceof EnhancedProjection + ? ( (EnhancedProjection) wrappedProjection).getColumnAliases( alias, loc, criteria, criteriaQuery ) + : getColumnAliases( alias, loc ); } + @Override public String[] getAliases() { - return projection.getAliases(); + return wrappedProjection.getAliases(); } + @Override public boolean isGrouped() { - return projection.isGrouped(); + return wrappedProjection.isGrouped(); } + @Override public String toString() { - return "distinct " + projection.toString(); + return "distinct " + wrappedProjection.toString(); } } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/EmptyExpression.java b/hibernate-core/src/main/java/org/hibernate/criterion/EmptyExpression.java index b1bf13eb64..c9df93d033 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/EmptyExpression.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/EmptyExpression.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,22 +20,28 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; - /** + * An expression asserting that a collection property is empty + * * @author Gavin King */ public class EmptyExpression extends AbstractEmptinessExpression implements Criterion { - + /** + * Constructs an EmptyExpression + * + * @param propertyName The collection property name + * + * @see Restrictions#isEmpty + */ protected EmptyExpression(String propertyName) { super( propertyName ); } + @Override protected boolean excludeEmpty() { return false; } - } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/EnhancedProjection.java b/hibernate-core/src/main/java/org/hibernate/criterion/EnhancedProjection.java index 5c375e01eb..57a5e67a70 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/EnhancedProjection.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/EnhancedProjection.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,9 +20,9 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; + import org.hibernate.Criteria; /** diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/Example.java b/hibernate-core/src/main/java/org/hibernate/criterion/Example.java index d35d86deb7..44a9abc6fe 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/Example.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/Example.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.criterion; + import java.io.Serializable; import java.util.ArrayList; import java.util.HashSet; @@ -30,7 +31,6 @@ import java.util.Set; import org.hibernate.Criteria; import org.hibernate.EntityMode; -import org.hibernate.HibernateException; import org.hibernate.engine.spi.TypedValue; import org.hibernate.internal.util.StringHelper; import org.hibernate.persister.entity.EntityPersister; @@ -39,6 +39,7 @@ import org.hibernate.type.Type; /** * Support for query by example. + * *

  * List results = session.createCriteria(Parent.class)
  *     .add( Example.create(parent).ignoreCase() )
@@ -46,68 +47,57 @@ import org.hibernate.type.Type;
  *         .add( Example.create( parent.getChild() ) )
  *     .list();
  * 
- * "Examples" may be mixed and matched with "Expressions" in the same Criteria. + * + * "Examples" may be mixed and matched with "Expressions" in the same Criteria. + * * @see org.hibernate.Criteria * @author Gavin King */ public class Example implements Criterion { - - private final Object entity; - private final Set excludedProperties = new HashSet(); + private final Object exampleEntity; private PropertySelector selector; + private boolean isLikeEnabled; private Character escapeCharacter; private boolean isIgnoreCaseEnabled; private MatchMode matchMode; + private final Set excludedProperties = new HashSet(); + /** - * A strategy for choosing property values for inclusion in the query - * criteria + * Create a new Example criterion instance, which includes all non-null properties by default + * + * @param exampleEntity The example bean to use. + * + * @return a new instance of Example */ - - public static interface PropertySelector extends Serializable { - public boolean include(Object propertyValue, String propertyName, Type type); - } - - private static final PropertySelector NOT_NULL = new NotNullPropertySelector(); - private static final PropertySelector ALL = new AllPropertySelector(); - private static final PropertySelector NOT_NULL_OR_ZERO = new NotNullOrZeroPropertySelector(); - - static final class AllPropertySelector implements PropertySelector { - public boolean include(Object object, String propertyName, Type type) { - return true; - } - - private Object readResolve() { - return ALL; - } - } - - static final class NotNullPropertySelector implements PropertySelector { - public boolean include(Object object, String propertyName, Type type) { - return object!=null; - } - - private Object readResolve() { - return NOT_NULL; - } - } - - static final class NotNullOrZeroPropertySelector implements PropertySelector { - public boolean include(Object object, String propertyName, Type type) { - return object!=null && ( - !(object instanceof Number) || ( (Number) object ).longValue()!=0 - ); - } - - private Object readResolve() { - return NOT_NULL_OR_ZERO; + public static Example create(Object exampleEntity) { + if ( exampleEntity == null ) { + throw new NullPointerException( "null example entity" ); } + return new Example( exampleEntity, NotNullPropertySelector.INSTANCE ); } /** - * Set escape character for "like" clause + * Allow subclasses to instantiate as needed. + * + * @param exampleEntity The example bean + * @param selector The property selector to use + */ + protected Example(Object exampleEntity, PropertySelector selector) { + this.exampleEntity = exampleEntity; + this.selector = selector; + } + + /** + * Set escape character for "like" clause if like matching was enabled + * + * @param escapeCharacter The escape character + * + * @return {@code this}, for method chaining + * + * @see #enableLike */ public Example setEscapeCharacter(Character escapeCharacter) { this.escapeCharacter = escapeCharacter; @@ -115,7 +105,47 @@ public class Example implements Criterion { } /** - * Set the property selector + * Use the "like" operator for all string-valued properties. This form implicitly uses {@link MatchMode#EXACT} + * + * @return {@code this}, for method chaining + */ + public Example enableLike() { + return enableLike( MatchMode.EXACT ); + } + + /** + * Use the "like" operator for all string-valued properties + * + * @param matchMode The match mode to use. + * + * @return {@code this}, for method chaining + */ + public Example enableLike(MatchMode matchMode) { + this.isLikeEnabled = true; + this.matchMode = matchMode; + return this; + } + + /** + * Ignore case for all string-valued properties + * + * @return {@code this}, for method chaining + */ + public Example ignoreCase() { + this.isIgnoreCaseEnabled = true; + return this; + } + + /** + * Set the property selector to use. + * + * The property selector operates separate from excluding a property. + * + * @param selector The selector to use + * + * @return {@code this}, for method chaining + * + * @see #excludeProperty */ public Example setPropertySelector(PropertySelector selector) { this.selector = selector; @@ -123,95 +153,63 @@ public class Example implements Criterion { } /** - * Exclude zero-valued properties + * Exclude zero-valued properties. + * + * Equivalent to calling {@link #setPropertySelector} passing in {@link NotNullOrZeroPropertySelector#INSTANCE} + * + * @return {@code this}, for method chaining + * + * @see #setPropertySelector */ public Example excludeZeroes() { - setPropertySelector(NOT_NULL_OR_ZERO); + setPropertySelector( NotNullOrZeroPropertySelector.INSTANCE ); return this; } /** - * Don't exclude null or zero-valued properties + * Include all properties. + * + * Equivalent to calling {@link #setPropertySelector} passing in {@link AllPropertySelector#INSTANCE} + * + * @return {@code this}, for method chaining + * + * @see #setPropertySelector */ public Example excludeNone() { - setPropertySelector(ALL); + setPropertySelector( AllPropertySelector.INSTANCE ); return this; } /** - * Use the "like" operator for all string-valued properties - */ - public Example enableLike(MatchMode matchMode) { - isLikeEnabled = true; - this.matchMode = matchMode; - return this; - } - - /** - * Use the "like" operator for all string-valued properties - */ - public Example enableLike() { - return enableLike(MatchMode.EXACT); - } - - /** - * Ignore case for all string-valued properties - */ - public Example ignoreCase() { - isIgnoreCaseEnabled = true; - return this; - } - - /** - * Exclude a particular named property + * Exclude a particular property by name. + * + * @param name The name of the property to exclude + * + * @return {@code this}, for method chaining + * + * @see #setPropertySelector */ public Example excludeProperty(String name) { - excludedProperties.add(name); + excludedProperties.add( name ); return this; } - /** - * Create a new instance, which includes all non-null properties - * by default - * @param entity - * @return a new instance of Example - */ - public static Example create(Object entity) { - if (entity==null) throw new NullPointerException("null example"); - return new Example(entity, NOT_NULL); - } + @Override + public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) { + final StringBuilder buf = new StringBuilder().append( '(' ); + final EntityPersister meta = criteriaQuery.getFactory().getEntityPersister( + criteriaQuery.getEntityName( criteria ) + ); + final String[] propertyNames = meta.getPropertyNames(); + final Type[] propertyTypes = meta.getPropertyTypes(); - protected Example(Object entity, PropertySelector selector) { - this.entity = entity; - this.selector = selector; - } + final Object[] propertyValues = meta.getPropertyValues( exampleEntity ); + for ( int i=0; i list = new ArrayList(); + for ( int i=0; i list) { + if ( value != null ) { if ( value instanceof String ) { String string = (String) value; - if (isIgnoreCaseEnabled) string = string.toLowerCase(); - if (isLikeEnabled) string = matchMode.toMatchString(string); + if ( isIgnoreCaseEnabled ) { + string = string.toLowerCase(); + } + if ( isLikeEnabled ) { + string = matchMode.toMatchString( string ); + } value = string; } - list.add( new TypedValue(type, value, null) ); + list.add( new TypedValue( type, value ) ); } } @@ -295,101 +304,197 @@ public class Example implements Criterion { String path, Object component, CompositeType type, - List list, + List list, Criteria criteria, - CriteriaQuery criteriaQuery) - throws HibernateException { - - if (component!=null) { - String[] propertyNames = type.getPropertyNames(); - Type[] subtypes = type.getSubtypes(); - Object[] values = type.getPropertyValues( component, getEntityMode(criteria, criteriaQuery) ); - for (int i=0; i 0 ) { + if ( buf.length() > 1 ) { + buf.append( " and " ); + } + buf.append( conditionFragment ); } - String critCondition = crit.toSqlString(criteria, cq); - if ( buf.length()>1 && critCondition.trim().length()>0 ) buf.append(" and "); - buf.append(critCondition); } protected void appendComponentCondition( - String path, - Object component, - CompositeType type, - Criteria criteria, - CriteriaQuery criteriaQuery, - StringBuilder buf) - throws HibernateException { - - if (component!=null) { - String[] propertyNames = type.getPropertyNames(); - Object[] values = type.getPropertyValues( component, getEntityMode(criteria, criteriaQuery) ); - Type[] subtypes = type.getSubtypes(); - for (int i=0; iRestrictions. - * @see Restrictions + * Factory for Criterion objects. Deprecated! + * * @author Gavin King + * + * @see Restrictions + * + * @deprecated Use {@link Restrictions} instead */ @Deprecated public final class Expression extends Restrictions { + /** + * Apply a constraint expressed in SQL, with JDBC parameters. Any occurrences of {alias} will be + * replaced by the table alias. + * + * @param sql The sql + * @param values The parameter values + * @param types The parameter types + * + * @return Criterion + * + * @deprecated use {@link org.hibernate.criterion.Restrictions#sqlRestriction(String, Object[], Type[])} + */ + @Deprecated + public static Criterion sql(String sql, Object[] values, Type[] types) { + return new SQLCriterion( sql, values, types ); + } + + /** + * Apply a constraint expressed in SQL, with a JDBC parameter. Any occurrences of {alias} will be + * replaced by the table alias. + * + * @param sql The sql + * @param value The parameter value + * @param type The parameter type + * + * @return Criterion + * + * @deprecated use {@link org.hibernate.criterion.Restrictions#sqlRestriction(String, Object, Type)} + */ + @Deprecated + public static Criterion sql(String sql, Object value, Type type) { + return new SQLCriterion( sql, value, type ); + } + + /** + * Apply a constraint expressed in SQL with no parameters. Any occurrences of {alias} will be + * replaced by the table alias. + * + * @param sql The sql + * + * @return Criterion + * + * @deprecated use {@link org.hibernate.criterion.Restrictions#sqlRestriction(String)} + */ + @Deprecated + public static Criterion sql(String sql) { + return new SQLCriterion( sql ); + } private Expression() { //cannot be instantiated } - - /** - * Apply a constraint expressed in SQL, with the given JDBC - * parameters. Any occurrences of {alias} will be - * replaced by the table alias. - * - * @deprecated use {@link org.hibernate.criterion.Restrictions#sqlRestriction(String, Object[], Type[])} - * @param sql - * @param values - * @param types - * @return Criterion - */ - @Deprecated - public static Criterion sql(String sql, Object[] values, Type[] types) { - return new SQLCriterion(sql, values, types); - } - /** - * Apply a constraint expressed in SQL, with the given JDBC - * parameter. Any occurrences of {alias} will be replaced - * by the table alias. - * - * @deprecated use {@link org.hibernate.criterion.Restrictions#sqlRestriction(String, Object, Type)} - * @param sql - * @param value - * @param type - * @return Criterion - */ - @Deprecated - public static Criterion sql(String sql, Object value, Type type) { - return new SQLCriterion(sql, new Object[] { value }, new Type[] { type } ); - } - /** - * Apply a constraint expressed in SQL. Any occurrences of {alias} - * will be replaced by the table alias. - * - * @deprecated use {@link org.hibernate.criterion.Restrictions#sqlRestriction(String)} - * @param sql - * @return Criterion - */ - @Deprecated - public static Criterion sql(String sql) { - return new SQLCriterion(sql, ArrayHelper.EMPTY_OBJECT_ARRAY, ArrayHelper.EMPTY_TYPE_ARRAY); - } - } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/IdentifierEqExpression.java b/hibernate-core/src/main/java/org/hibernate/criterion/IdentifierEqExpression.java index 5c89a2445a..1fb625a1dc 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/IdentifierEqExpression.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/IdentifierEqExpression.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,46 +20,49 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; + import org.hibernate.Criteria; -import org.hibernate.HibernateException; import org.hibernate.engine.spi.TypedValue; import org.hibernate.internal.util.StringHelper; /** * An identifier constraint + * * @author Gavin King */ public class IdentifierEqExpression implements Criterion { - private final Object value; + /** + * Constructs an IdentifierEqExpression + * + * @param value The identifier value + * + * @see Restrictions#idEq + */ protected IdentifierEqExpression(Object value) { this.value = value; } - public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { + @Override + public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) { + final String[] columns = criteriaQuery.getIdentifierColumns( criteria ); - String[] columns = criteriaQuery.getIdentifierColumns(criteria); - - String result = StringHelper.join( - " and ", - StringHelper.suffix( columns, " = ?" ) - ); - if (columns.length>1) result = '(' + result + ')'; + String result = StringHelper.join( " and ", StringHelper.suffix( columns, " = ?" ) ); + if ( columns.length > 1) { + result = '(' + result + ')'; + } return result; - - //TODO: get SQL rendering out of this package! } - public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - return new TypedValue[] { criteriaQuery.getTypedIdentifierValue(criteria, value) }; + @Override + public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) { + return new TypedValue[] { criteriaQuery.getTypedIdentifierValue( criteria, value ) }; } + @Override public String toString() { return "id = " + value; } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/IdentifierProjection.java b/hibernate-core/src/main/java/org/hibernate/criterion/IdentifierProjection.java index e44c638c8e..d494f24cb5 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/IdentifierProjection.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/IdentifierProjection.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,66 +20,77 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; + import org.hibernate.Criteria; -import org.hibernate.HibernateException; import org.hibernate.internal.util.StringHelper; import org.hibernate.type.Type; /** * A property value, or grouped property value + * * @author Gavin King */ public class IdentifierProjection extends SimpleProjection { - private boolean grouped; - - protected IdentifierProjection(boolean grouped) { + + /** + * Constructs a non-grouped identifier projection + * + * @see Projections#id + */ + protected IdentifierProjection() { + this( false ); + } + + /** + * + * Not used externally + */ + private IdentifierProjection(boolean grouped) { this.grouped = grouped; } - - protected IdentifierProjection() { - this(false); - } - - public String toString() { - return "id"; + + @Override + public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery) { + return new Type[] { criteriaQuery.getIdentifierType( criteria ) }; } - public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - return new Type[] { criteriaQuery.getIdentifierType(criteria) }; - } - - public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery) - throws HibernateException { - StringBuilder buf = new StringBuilder(); - String[] cols = criteriaQuery.getIdentifierColumns(criteria); + @Override + public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery) { + final StringBuilder buf = new StringBuilder(); + final String[] cols = criteriaQuery.getIdentifierColumns( criteria ); for ( int i=0; i 1 ) { + singleValueParam = '(' + singleValueParam + ')'; + } + final String params = values.length > 0 + ? StringHelper.repeat( singleValueParam + ", ", values.length - 1 ) + singleValueParam + : ""; + String cols = StringHelper.join( ", ", columns ); + if ( columns.length > 1 ) { + cols = '(' + cols + ')'; + } + return cols + " in (" + params + ')'; + } + else { + String cols = " ( " + StringHelper.join( " = ? and ", columns ) + "= ? ) "; + cols = values.length > 0 + ? StringHelper.repeat( cols + "or ", values.length - 1 ) + cols + : ""; + cols = " ( " + cols + " ) "; + return cols; + } + } - String singleValueParam = StringHelper.repeat( "?, ", - columns.length - 1 ) - + "?"; - if ( columns.length > 1 ) - singleValueParam = '(' + singleValueParam + ')'; - String params = values.length > 0 ? StringHelper.repeat( - singleValueParam + ", ", values.length - 1 ) - + singleValueParam : ""; - String cols = StringHelper.join( ", ", columns ); - if ( columns.length > 1 ) - cols = '(' + cols + ')'; - return cols + " in (" + params + ')'; - } else { - String cols = " ( " + StringHelper.join( " = ? and ", columns ) + "= ? ) "; - cols = values.length > 0 ? StringHelper.repeat( cols - + "or ", values.length - 1 ) - + cols : ""; - cols = " ( " + cols + " ) "; - return cols; - } - } - - public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - ArrayList list = new ArrayList(); - Type type = criteriaQuery.getTypeUsingProjection(criteria, propertyName); + @Override + public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) { + final ArrayList list = new ArrayList(); + final Type type = criteriaQuery.getTypeUsingProjection( criteria, propertyName ); if ( type.isComponentType() ) { - CompositeType actype = (CompositeType) type; - Type[] types = actype.getSubtypes(); - for ( int j=0; j conditions() { return conditions; } @Override public TypedValue[] getTypedValues(Criteria crit, CriteriaQuery criteriaQuery) throws HibernateException { - ArrayList typedValues = new ArrayList(); + final ArrayList typedValues = new ArrayList(); for ( Criterion condition : conditions ) { - TypedValue[] subValues = condition.getTypedValues( crit, criteriaQuery ); + final TypedValue[] subValues = condition.getTypedValues( crit, criteriaQuery ); Collections.addAll( typedValues, subValues ); } return typedValues.toArray( new TypedValue[ typedValues.size() ] ); @@ -76,15 +94,18 @@ public class Junction implements Criterion { return "1=1"; } - StringBuilder buffer = new StringBuilder().append( '(' ); - Iterator itr = conditions.iterator(); + final StringBuilder buffer = new StringBuilder().append( '(' ); + final Iterator itr = conditions.iterator(); while ( itr.hasNext() ) { buffer.append( ( (Criterion) itr.next() ).toSqlString( crit, criteriaQuery ) ); if ( itr.hasNext() ) { - buffer.append(' ').append( nature.getOperator() ).append(' '); + buffer.append( ' ' ) + .append( nature.getOperator() ) + .append( ' ' ); } } - return buffer.append(')').toString(); + + return buffer.append( ')' ).toString(); } @Override @@ -92,11 +113,24 @@ public class Junction implements Criterion { return '(' + StringHelper.join( ' ' + nature.getOperator() + ' ', conditions.iterator() ) + ')'; } + /** + * The type of junction + */ public static enum Nature { + /** + * An AND + */ AND, - OR - ; + /** + * An OR + */ + OR; + /** + * The corresponding SQL operator + * + * @return SQL operator + */ public String getOperator() { return name().toLowerCase(); } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/LikeExpression.java b/hibernate-core/src/main/java/org/hibernate/criterion/LikeExpression.java index 22a89cf993..eb71480ab2 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/LikeExpression.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/LikeExpression.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,9 +20,9 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; + import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.dialect.Dialect; @@ -51,16 +51,12 @@ public class LikeExpression implements Criterion { this.ignoreCase = ignoreCase; } - protected LikeExpression( - String propertyName, - String value) { + protected LikeExpression(String propertyName, String value) { this( propertyName, value, null, false ); } - protected LikeExpression( - String propertyName, - String value, - MatchMode matchMode) { + @SuppressWarnings("UnusedDeclaration") + protected LikeExpression(String propertyName, String value, MatchMode matchMode) { this( propertyName, matchMode.toMatchString( value ) ); } @@ -73,16 +69,16 @@ public class LikeExpression implements Criterion { this( propertyName, matchMode.toMatchString( value ), escapeChar, ignoreCase ); } - public String toSqlString( - Criteria criteria, - CriteriaQuery criteriaQuery) throws HibernateException { - Dialect dialect = criteriaQuery.getFactory().getDialect(); - String[] columns = criteriaQuery.findColumns(propertyName, criteria); + @Override + public String toSqlString(Criteria criteria,CriteriaQuery criteriaQuery) { + final Dialect dialect = criteriaQuery.getFactory().getDialect(); + final String[] columns = criteriaQuery.findColumns( propertyName, criteria ); if ( columns.length != 1 ) { throw new HibernateException( "Like may only be used with single-column properties" ); } - String escape = escapeChar == null ? "" : " escape \'" + escapeChar + "\'"; - String column = columns[0]; + + final String escape = escapeChar == null ? "" : " escape \'" + escapeChar + "\'"; + final String column = columns[0]; if ( ignoreCase ) { if ( dialect.supportsCaseInsensitiveLike() ) { return column +" " + dialect.getCaseInsensitiveLike() + " ?" + escape; @@ -96,11 +92,10 @@ public class LikeExpression implements Criterion { } } - public TypedValue[] getTypedValues( - Criteria criteria, - CriteriaQuery criteriaQuery) throws HibernateException { - return new TypedValue[] { - criteriaQuery.getTypedValue( criteria, propertyName, ignoreCase ? value.toString().toLowerCase() : value.toString() ) - }; + @Override + public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) { + final String matchValue = ignoreCase ? value.toString().toLowerCase() : value.toString(); + + return new TypedValue[] { criteriaQuery.getTypedValue( criteria, propertyName, matchValue ) }; } } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/LogicalExpression.java b/hibernate-core/src/main/java/org/hibernate/criterion/LogicalExpression.java index 442eff8e69..7216b12272 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/LogicalExpression.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/LogicalExpression.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,19 +20,18 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; + import org.hibernate.Criteria; -import org.hibernate.HibernateException; import org.hibernate.engine.spi.TypedValue; /** * Superclass of binary logical expressions + * * @author Gavin King */ public class LogicalExpression implements Criterion { - private final Criterion lhs; private final Criterion rhs; private final String op; @@ -43,33 +42,33 @@ public class LogicalExpression implements Criterion { this.op = op; } - public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { + @Override + public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) { + final TypedValue[] lhsTypedValues = lhs.getTypedValues( criteria, criteriaQuery ); + final TypedValue[] rhsTypedValues = rhs.getTypedValues( criteria, criteriaQuery ); - TypedValue[] lhstv = lhs.getTypedValues(criteria, criteriaQuery); - TypedValue[] rhstv = rhs.getTypedValues(criteria, criteriaQuery); - TypedValue[] result = new TypedValue[ lhstv.length + rhstv.length ]; - System.arraycopy(lhstv, 0, result, 0, lhstv.length); - System.arraycopy(rhstv, 0, result, lhstv.length, rhstv.length); + final TypedValue[] result = new TypedValue[ lhsTypedValues.length + rhsTypedValues.length ]; + System.arraycopy( lhsTypedValues, 0, result, 0, lhsTypedValues.length ); + System.arraycopy( rhsTypedValues, 0, result, lhsTypedValues.length, rhsTypedValues.length ); return result; } - public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - - return '(' + - lhs.toSqlString(criteria, criteriaQuery) + - ' ' + - getOp() + - ' ' + - rhs.toSqlString(criteria, criteriaQuery) + - ')'; + @Override + public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) { + return '(' + + lhs.toSqlString( criteria, criteriaQuery ) + + ' ' + + getOp() + + ' ' + + rhs.toSqlString( criteria, criteriaQuery ) + + ')'; } public String getOp() { return op; } + @Override public String toString() { return lhs.toString() + ' ' + getOp() + ' ' + rhs.toString(); } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/MatchMode.java b/hibernate-core/src/main/java/org/hibernate/criterion/MatchMode.java index 6b834c3f60..00c29052af 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/MatchMode.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/MatchMode.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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.criterion; @@ -36,6 +35,7 @@ public enum MatchMode { * Match the entire string to the pattern */ EXACT { + @Override public String toMatchString(String pattern) { return pattern; } @@ -45,6 +45,7 @@ public enum MatchMode { * Match the start of the string to the pattern */ START { + @Override public String toMatchString(String pattern) { return pattern + '%'; } @@ -54,6 +55,7 @@ public enum MatchMode { * Match the end of the string to the pattern */ END { + @Override public String toMatchString(String pattern) { return '%' + pattern; } @@ -63,13 +65,18 @@ public enum MatchMode { * Match the pattern anywhere in the string */ ANYWHERE { + @Override public String toMatchString(String pattern) { return '%' + pattern + '%'; } }; /** - * convert the pattern, by appending/prepending "%" + * Convert the pattern, by appending/prepending "%" + * + * @param pattern The pattern for convert according to the mode + * + * @return The converted pattern */ public abstract String toMatchString(String pattern); diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/NaturalIdentifier.java b/hibernate-core/src/main/java/org/hibernate/criterion/NaturalIdentifier.java index c98ba83f5d..51ec35cf7b 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/NaturalIdentifier.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/NaturalIdentifier.java @@ -28,27 +28,37 @@ import java.util.concurrent.ConcurrentHashMap; import org.hibernate.Criteria; import org.hibernate.HibernateException; -import org.hibernate.Session; import org.hibernate.engine.spi.TypedValue; /** + * An expression pertaining to an entity's defined natural identifier + * * @author Gavin King - * @see Session#byNaturalId(Class) - * @see Session#byNaturalId(String) - * @see Session#bySimpleNaturalId(Class) - * @see Session#bySimpleNaturalId(String) + * + * @see org.hibernate.Session#byNaturalId(Class) + * @see org.hibernate.Session#byNaturalId(String) + * @see org.hibernate.Session#bySimpleNaturalId(Class) + * @see org.hibernate.Session#bySimpleNaturalId(String) */ public class NaturalIdentifier implements Criterion { private final Conjunction conjunction = new Conjunction(); + @Override public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { return conjunction.getTypedValues( criteria, criteriaQuery ); } + @Override public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { return conjunction.toSqlString( criteria, criteriaQuery ); } + /** + * Get a map of set of the natural identifier values set on this criterion (for composite natural identifiers + * this need not be the full set of properties). + * + * @return The value map. + */ public Map getNaturalIdValues() { final Map naturalIdValueMap = new ConcurrentHashMap(); for ( Criterion condition : conjunction.conditions() ) { @@ -65,6 +75,14 @@ public class NaturalIdentifier implements Criterion { return naturalIdValueMap; } + /** + * Set a natural identifier value for this expression + * + * @param property The specific property name + * @param value The value to use + * + * @return {@code this}, for method chaining + */ public NaturalIdentifier set(String property, Object value) { conjunction.add( Restrictions.eq( property, value ) ); return this; diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/NotEmptyExpression.java b/hibernate-core/src/main/java/org/hibernate/criterion/NotEmptyExpression.java index f3bf90ce93..aec3b7c1af 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/NotEmptyExpression.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/NotEmptyExpression.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,20 +20,27 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; - /** + * An expression asserting that a collection property is empty + * * @author Gavin King */ public class NotEmptyExpression extends AbstractEmptinessExpression implements Criterion { - + /** + * Constructs an EmptyExpression + * + * @param propertyName The collection property name + * + * @see Restrictions#isNotEmpty + */ protected NotEmptyExpression(String propertyName) { super( propertyName ); } + @Override protected boolean excludeEmpty() { return true; } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/NotExpression.java b/hibernate-core/src/main/java/org/hibernate/criterion/NotExpression.java index 35bf4e5346..83d49063db 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/NotExpression.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/NotExpression.java @@ -28,29 +28,37 @@ import org.hibernate.HibernateException; import org.hibernate.engine.spi.TypedValue; /** - * Negates another criterion + * A criterion that is a wrapper for another, negating the wrapped one. + * * @author Gavin King - * @author Brett Meyer */ public class NotExpression implements Criterion { - private Criterion criterion; + /** + * Constructs a NotExpression + * + * @param criterion The expression to wrap and negate + * + * @see Restrictions#not + */ protected NotExpression(Criterion criterion) { this.criterion = criterion; } + @Override public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { return criteriaQuery.getFactory().getDialect().getNotExpression( - criterion.toSqlString( criteria, criteriaQuery ) ); + criterion.toSqlString( criteria, criteriaQuery ) + ); } - public TypedValue[] getTypedValues( - Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - return criterion.getTypedValues(criteria, criteriaQuery); + @Override + public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { + return criterion.getTypedValues( criteria, criteriaQuery ); } + @Override public String toString() { return "not " + criterion.toString(); } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/NotNullExpression.java b/hibernate-core/src/main/java/org/hibernate/criterion/NotNullExpression.java index 0f1c3abf56..5788af8431 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/NotNullExpression.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/NotNullExpression.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,9 +20,9 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; + import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.engine.spi.TypedValue; @@ -30,36 +30,37 @@ import org.hibernate.internal.util.StringHelper; /** * Constrains a property to be non-null + * * @author Gavin King */ public class NotNullExpression implements Criterion { + private static final TypedValue[] NO_VALUES = new TypedValue[0]; private final String propertyName; - private static final TypedValue[] NO_VALUES = new TypedValue[0]; - protected NotNullExpression(String propertyName) { this.propertyName = propertyName; } - public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - String[] columns = criteriaQuery.findColumns(propertyName, criteria); + @Override + public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { + final String[] columns = criteriaQuery.findColumns( propertyName, criteria ); String result = StringHelper.join( " or ", StringHelper.suffix( columns, " is not null" ) ); - if (columns.length>1) result = '(' + result + ')'; + if ( columns.length > 1 ) { + result = '(' + result + ')'; + } return result; - - //TODO: get SQL rendering out of this package! } - public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { + @Override + public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { return NO_VALUES; } + @Override public String toString() { return propertyName + " is not null"; } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/NullExpression.java b/hibernate-core/src/main/java/org/hibernate/criterion/NullExpression.java index 1d22ef121a..2a451f91dd 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/NullExpression.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/NullExpression.java @@ -30,36 +30,44 @@ import org.hibernate.internal.util.StringHelper; /** * Constrains a property to be null + * * @author Gavin King */ public class NullExpression implements Criterion { + private static final TypedValue[] NO_VALUES = new TypedValue[0]; private final String propertyName; - private static final TypedValue[] NO_VALUES = new TypedValue[0]; - + /** + * Constructs a NullExpression + * + * @param propertyName The name of the property to check for null + * + * @see Restrictions#isNull + */ protected NullExpression(String propertyName) { this.propertyName = propertyName; } - public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - String[] columns = criteriaQuery.findColumns(propertyName, criteria); + @Override + public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { + final String[] columns = criteriaQuery.findColumns( propertyName, criteria ); String result = StringHelper.join( " and ", StringHelper.suffix( columns, " is null" ) ); - if (columns.length>1) result = '(' + result + ')'; + if ( columns.length > 1 ) { + result = '(' + result + ')'; + } return result; - - //TODO: get SQL rendering out of this package! } - public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { + @Override + public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { return NO_VALUES; } + @Override public String toString() { return propertyName + " is null"; } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/Order.java b/hibernate-core/src/main/java/org/hibernate/criterion/Order.java index 9888d76400..c7feea418c 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/Order.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/Order.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,122 +20,153 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; + import java.io.Serializable; import java.sql.Types; import org.hibernate.Criteria; -import org.hibernate.HibernateException; import org.hibernate.NullPrecedence; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.type.Type; /** - * Represents an order imposed upon a Criteria result set + * Represents an ordering imposed upon the results of a Criteria * * @author Gavin King * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) - * @author Brett Meyer */ public class Order implements Serializable { private boolean ascending; private boolean ignoreCase; private String propertyName; private NullPrecedence nullPrecedence; - - public String toString() { - return propertyName + ' ' + ( ascending ? "asc" : "desc" ) + ( nullPrecedence != null ? ' ' + nullPrecedence.name().toLowerCase() : "" ); - } - - public Order ignoreCase() { - ignoreCase = true; - return this; - } - public Order nulls(NullPrecedence nullPrecedence) { - this.nullPrecedence = nullPrecedence; - return this; + /** + * Ascending order + * + * @param propertyName The property to order on + * + * @return The build Order instance + */ + public static Order asc(String propertyName) { + return new Order( propertyName, true ); } /** - * Constructor for Order. + * Descending order. + * + * @param propertyName The property to order on + * + * @return The build Order instance + */ + public static Order desc(String propertyName) { + return new Order( propertyName, false ); + } + + /** + * Constructor for Order. Order instances are generally created by factory methods. + * + * @see #asc + * @see #desc */ protected Order(String propertyName, boolean ascending) { this.propertyName = propertyName; this.ascending = ascending; } + /** + * Should this ordering ignore case? Has no effect on non-character properties. + * + * @return {@code this}, for method chaining + */ + public Order ignoreCase() { + ignoreCase = true; + return this; + } + + /** + * Defines precedence for nulls. + * + * @param nullPrecedence The null precedence to use + * + * @return {@code this}, for method chaining + */ + public Order nulls(NullPrecedence nullPrecedence) { + this.nullPrecedence = nullPrecedence; + return this; + } + + public String getPropertyName() { + return propertyName; + } + + @SuppressWarnings("UnusedDeclaration") + public boolean isAscending() { + return ascending; + } + + @SuppressWarnings("UnusedDeclaration") + public boolean isIgnoreCase() { + return ignoreCase; + } + + /** * Render the SQL fragment * + * @param criteria The criteria + * @param criteriaQuery The overall query + * + * @return The ORDER BY fragment for this ordering */ - public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - String[] columns = criteriaQuery.getColumnsUsingProjection(criteria, propertyName); - Type type = criteriaQuery.getTypeUsingProjection(criteria, propertyName); - StringBuilder fragment = new StringBuilder(); + public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) { + final String[] columns = criteriaQuery.getColumnsUsingProjection( criteria, propertyName ); + final Type type = criteriaQuery.getTypeUsingProjection( criteria, propertyName ); + final SessionFactoryImplementor factory = criteriaQuery.getFactory(); + final int[] sqlTypes = type.sqlTypes( factory ); + + final StringBuilder fragment = new StringBuilder(); for ( int i=0; i elements = new ArrayList(); + + /** + * Constructs a ProjectionList + * + * @see Projections#projectionList() + */ + protected ProjectionList() { + } + + /** + * Lol + * + * @return duh + * + * @deprecated an instance factory method does not make sense + * + * @see Projections#projectionList() + */ + @Deprecated public ProjectionList create() { return new ProjectionList(); } - - public ProjectionList add(Projection proj) { - elements.add(proj); + + /** + * Add a projection to this list of projections + * + * @param projection The projection to add + * + * @return {@code this}, for method chaining + */ + public ProjectionList add(Projection projection) { + elements.add( projection ); return this; } + /** + * Adds a projection to this list of projections after wrapping it with an alias + * + * @param projection The projection to add + * @param alias The alias to apply to the projection + * + * @return {@code this}, for method chaining + * + * @see Projections#alias + */ public ProjectionList add(Projection projection, String alias) { return add( Projections.alias( projection, alias ) ); } - public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - List types = new ArrayList( getLength() ); - for ( int i=0; i2 ) buf.setLength( buf.length()-2 ); //pull off the last ", " + return false; + } + + @Override + public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { + final List types = new ArrayList( getLength() ); + for ( Projection projection : elements ) { + final Type[] elemTypes = projection.getTypes( criteria, criteriaQuery ); + Collections.addAll( types, elemTypes ); + } + return types.toArray( new Type[types.size()] ); + } + + @Override + public String toSqlString(Criteria criteria, int loc, CriteriaQuery criteriaQuery) throws HibernateException { + final StringBuilder buf = new StringBuilder(); + String separator = ""; + + for ( Projection projection : elements ) { + buf.append( separator ).append( projection.toSqlString( criteria, loc, criteriaQuery ) ); + loc += getColumnAliases( loc, criteria, criteriaQuery, projection ).length; + separator = ", "; + } return buf.toString(); } - - public String[] getColumnAliases(int loc) { - List result = new ArrayList( getLength() ); - for ( int i=0; i result = new ArrayList( getLength() ); + for ( Projection projection : elements ) { + final String[] aliases = projection.getColumnAliases( position ); + Collections.addAll( result, aliases ); + position += aliases.length; } - return ArrayHelper.toStringArray(result); + return result.toArray( new String[ result.size() ] ); } - public String[] getColumnAliases(String alias, int loc) { - for ( int i=0; i result = new ArrayList( getLength() ); + for ( Projection projection : elements ) { + final String[] aliases = getColumnAliases( position, criteria, criteriaQuery, projection ); + Collections.addAll( result, aliases ); + position += aliases.length; + } + return result.toArray( new String[result.size()] ); + } + + @Override + public String[] getColumnAliases(String alias, final int loc) { + int position = loc; + for ( Projection projection : elements ) { + final String[] aliases = projection.getColumnAliases( alias, position ); + if ( aliases != null ) { + return aliases; + } + position += projection.getColumnAliases( position ).length; } return null; } + @Override public String[] getColumnAliases(String alias, int loc, Criteria criteria, CriteriaQuery criteriaQuery) { - for ( int i=0; i result = new ArrayList( getLength() ); + for ( Projection projection : elements ) { + final String[] aliases = projection.getAliases(); + Collections.addAll( result, aliases ); } - return ArrayHelper.toStringArray(result); + return result.toArray( new String[result.size()] ); + } - } - + /** + * Access a wrapped projection by index + * + * @param i The index of the projection to return + * + * @return The projection + */ + @SuppressWarnings("UnusedDeclaration") public Projection getProjection(int i) { - return (Projection) elements.get(i); + return elements.get( i ); } - + public int getLength() { return elements.size(); } + @Override public String toString() { return elements.toString(); } - public boolean isGrouped() { - for ( int i=0; icriterion package may be used by applications as a framework for building * new kinds of Projection. However, it is intended that most applications will - * simply use the built-in projection types via the static factory methods of this class.
- *
+ * simply use the built-in projection types via the static factory methods of this class. + * * The factory methods that take an alias allow the projected value to be referred to by * criterion and order instances. * - * @see org.hibernate.Criteria - * @see Restrictions factory methods for Criterion instances + * See also the {@link Restrictions} factory methods for generating {@link Criterion} instances + * * @author Gavin King + * @author Steve Ebersole + * + * @see org.hibernate.Criteria */ public final class Projections { - - private Projections() { - //cannot be instantiated - } - /** - * Create a distinct projection from a projection + * A property value projection + * + * @param propertyName The name of the property whose values should be projected + * + * @return The property projection + * + * @see PropertyProjection */ - public static Projection distinct(Projection proj) { - return new Distinct(proj); + public static PropertyProjection property(String propertyName) { + return new PropertyProjection( propertyName ); + } + + /** + * A grouping property value projection + * + * @param propertyName The name of the property to group + * + * @return The grouped projection + * + * @see PropertyProjection + */ + public static PropertyProjection groupProperty(String propertyName) { + return new PropertyProjection( propertyName, true ); + } + + /** + * An identifier value projection. + * + * @return The identifier projection + * + * @see IdentifierProjection + */ + public static IdentifierProjection id() { + return new IdentifierProjection(); + } + + /** + * Create a distinct projection from a projection. + * + * @param projection The project to treat distinctly + * + * @return The distinct projection + * + * @see Distinct + */ + public static Projection distinct(Projection projection) { + return new Distinct( projection ); } /** - * Create a new projection list + * Create a new projection list. + * + * @return The projection list */ public static ProjectionList projectionList() { return new ProjectionList(); @@ -59,92 +102,141 @@ public final class Projections { /** * The query row count, ie. count(*) + * + * @return The projection representing the row count + * + * @see RowCountProjection */ public static Projection rowCount() { return new RowCountProjection(); } /** - * A property value count + * A property value count projection + * + * @param propertyName The name of the property to count over + * + * @return The count projection + * + * @see CountProjection */ public static CountProjection count(String propertyName) { - return new CountProjection(propertyName); + return new CountProjection( propertyName ); } /** - * A distinct property value count + * A distinct property value count projection + * + * @param propertyName The name of the property to count over + * + * @return The count projection + * + * @see CountProjection */ public static CountProjection countDistinct(String propertyName) { - return new CountProjection(propertyName).setDistinct(); + return new CountProjection( propertyName ).setDistinct(); } /** - * A property maximum value + * A property maximum value projection + * + * @param propertyName The property for which to find the max + * + * @return the max projection + * + * @see AggregateProjection */ public static AggregateProjection max(String propertyName) { - return new AggregateProjection("max", propertyName); + return new AggregateProjection( "max", propertyName ); } /** - * A property minimum value + * A property minimum value projection + * + * @param propertyName The property for which to find the min + * + * @return the min projection + * + * @see AggregateProjection */ public static AggregateProjection min(String propertyName) { - return new AggregateProjection("min", propertyName); + return new AggregateProjection( "min", propertyName ); } /** - * A property average value + * A property average value projection + * + * @param propertyName The property over which to find the average + * + * @return the avg projection + * + * @see AvgProjection */ public static AggregateProjection avg(String propertyName) { - return new AvgProjection(propertyName); + return new AvgProjection( propertyName ); } /** - * A property value sum + * A property value sum projection + * + * @param propertyName The property over which to sum + * + * @return the sum projection + * + * @see AggregateProjection */ public static AggregateProjection sum(String propertyName) { - return new AggregateProjection("sum", propertyName); - } - - /** - * A SQL projection, a typed select clause fragment - */ - public static Projection sqlProjection(String sql, String[] columnAliases, Type[] types) { - return new SQLProjection(sql, columnAliases, types); - } - - /** - * A grouping SQL projection, specifying both select clause and group by clause fragments - */ - public static Projection sqlGroupProjection(String sql, String groupBy, String[] columnAliases, Type[] types) { - return new SQLProjection(sql, groupBy, columnAliases, types); - } - - /** - * A grouping property value - */ - public static PropertyProjection groupProperty(String propertyName) { - return new PropertyProjection(propertyName, true); - } - - /** - * A projected property value - */ - public static PropertyProjection property(String propertyName) { - return new PropertyProjection(propertyName); - } - - /** - * A projected identifier value - */ - public static IdentifierProjection id() { - return new IdentifierProjection(); + return new AggregateProjection( "sum", propertyName ); } /** * Assign an alias to a projection, by wrapping it + * + * @param projection The projection to be aliased + * @param alias The alias to apply + * + * @return The aliased projection + * + * @see AliasedProjection */ public static Projection alias(Projection projection, String alias) { - return new AliasedProjection(projection, alias); + return new AliasedProjection( projection, alias ); } + + /** + * A SQL projection, a typed select clause fragment + * + * @param sql The SQL fragment + * @param columnAliases The column aliases + * @param types The resulting types + * + * @return The SQL projection + * + * @see SQLProjection + */ + public static Projection sqlProjection(String sql, String[] columnAliases, Type[] types) { + return new SQLProjection( sql, columnAliases, types ); + } + + /** + * A grouping SQL projection, specifying both select clause and group by clause fragments + * + * @param sql The SQL SELECT fragment + * @param groupBy The SQL GROUP BY fragment + * @param columnAliases The column aliases + * @param types The resulting types + * + * @return The SQL projection + * + * @see SQLProjection + */ + @SuppressWarnings("UnusedDeclaration") + public static Projection sqlGroupProjection(String sql, String groupBy, String[] columnAliases, Type[] types) { + return new SQLProjection(sql, groupBy, columnAliases, types); + } + + private Projections() { + //cannot be instantiated + } + } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/PropertiesSubqueryExpression.java b/hibernate-core/src/main/java/org/hibernate/criterion/PropertiesSubqueryExpression.java index 69df2e56e9..cb1b1b4089 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/PropertiesSubqueryExpression.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/PropertiesSubqueryExpression.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.criterion; import org.hibernate.Criteria; @@ -5,6 +28,7 @@ import org.hibernate.internal.util.StringHelper; /** * A comparison between several properties value in the outer query and the result of a multicolumn subquery. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class PropertiesSubqueryExpression extends SubqueryExpression { @@ -17,7 +41,7 @@ public class PropertiesSubqueryExpression extends SubqueryExpression { @Override protected String toLeftSqlString(Criteria criteria, CriteriaQuery outerQuery) { - StringBuilder left = new StringBuilder( "(" ); + final StringBuilder left = new StringBuilder( "(" ); final String[] sqlColumnNames = new String[propertyNames.length]; for ( int i = 0; i < sqlColumnNames.length; ++i ) { sqlColumnNames[i] = outerQuery.getColumn( criteria, propertyNames[i] ); diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/Property.java b/hibernate-core/src/main/java/org/hibernate/criterion/Property.java index ef50ae62d8..129ebd21d9 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/Property.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/Property.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,244 +20,737 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; + import java.util.Collection; /** * A factory for property-specific criterion and projection instances + * * @author Gavin King + * @author Steve Ebersole */ public class Property extends PropertyProjection { - //private String propertyName; + /** + * Factory for Property instances. + * + * @param propertyName The name of the property. + * + * @return The Property instance + */ + public static Property forName(String propertyName) { + return new Property( propertyName ); + } + + /** + * Constructs a Property. non-private to allow subclassing. + * + * @param propertyName The property name. + */ protected Property(String propertyName) { - super(propertyName); + super( propertyName ); } + /** + * Creates a BETWEEN restriction for this property between the given min and max + * + * @param min The minimum + * @param max The maximum + * + * @return The BETWEEN restriction + * + * @see Restrictions#between(String, Object, Object) + */ public Criterion between(Object min, Object max) { - return Restrictions.between(getPropertyName(), min, max); + return Restrictions.between( getPropertyName(), min, max ); } + /** + * Creates an IN restriction for this property based on the given list of literals + * + * @param values The literal values + * + * @return The IN restriction + * + * @see Restrictions#in(String, Collection) + */ public Criterion in(Collection values) { - return Restrictions.in(getPropertyName(), values); + return Restrictions.in( getPropertyName(), values ); } + /** + * Creates an IN restriction for this property based on the given list of literals + * + * @param values The literal values + * + * @return The IN restriction + * + * @see Restrictions#in(String, Object[]) + */ public Criterion in(Object[] values) { - return Restrictions.in(getPropertyName(), values); + return Restrictions.in( getPropertyName(), values ); } + /** + * Creates a LIKE restriction for this property + * + * @param value The value to like compare with + * + * @return The LIKE restriction + * + * @see Restrictions#like(String, Object) + */ public SimpleExpression like(Object value) { - return Restrictions.like(getPropertyName(), value); + return Restrictions.like( getPropertyName(), value ); } + /** + * Creates a LIKE restriction for this property + * + * @param value The value to like compare with + * @param matchMode The match mode to apply to the LIKE + * + * @return The LIKE restriction + * + * @see Restrictions#like(String, String, MatchMode) + */ public SimpleExpression like(String value, MatchMode matchMode) { - return Restrictions.like(getPropertyName(), value, matchMode); + return Restrictions.like( getPropertyName(), value, matchMode ); } + /** + * Creates an equality restriction. + * + * @param value The value to check against + * + * @return The equality restriction. + * + * @see Restrictions#eq(String, Object) + */ public SimpleExpression eq(Object value) { - return Restrictions.eq(getPropertyName(), value); + return Restrictions.eq( getPropertyName(), value ); } + /** + * Creates an equality restriction capable of also rendering as IS NULL if the given value is {@code null} + * + * @param value The value to check against + * + * @return The equality restriction. + * + * @see Restrictions#eqOrIsNull(String, Object) + * @see #eq + * @see #isNull + */ + @SuppressWarnings("UnusedDeclaration") public Criterion eqOrIsNull(Object value) { - return Restrictions.eqOrIsNull(getPropertyName(), value); + return Restrictions.eqOrIsNull( getPropertyName(), value ); } + /** + * Creates an non-equality restriction. + * + * @param value The value to check against + * + * @return The non-equality restriction. + * + * @see Restrictions#ne(String, Object) + */ public SimpleExpression ne(Object value) { - return Restrictions.ne(getPropertyName(), value); + return Restrictions.ne( getPropertyName(), value ); } + /** + * Creates an non-equality restriction capable of also rendering as IS NOT NULL if the given value is {@code null} + * + * @param value The value to check against + * + * @return The non-equality restriction. + * + * @see Restrictions#neOrIsNotNull(String, Object) + * @see #ne + * @see #isNotNull + */ + @SuppressWarnings("UnusedDeclaration") public Criterion neOrIsNotNull(Object value) { - return Restrictions.neOrIsNotNull(getPropertyName(), value); + return Restrictions.neOrIsNotNull( getPropertyName(), value ); } + /** + * Create a greater-than restriction based on this property + * + * @param value The value to check against + * + * @return The greater-than restriction + * + * @see Restrictions#gt(String, Object) + */ public SimpleExpression gt(Object value) { - return Restrictions.gt(getPropertyName(), value); + return Restrictions.gt( getPropertyName(), value ); } + /** + * Create a less-than restriction based on this property + * + * @param value The value to check against + * + * @return The less-than restriction + * + * @see Restrictions#lt(String, Object) + */ public SimpleExpression lt(Object value) { - return Restrictions.lt(getPropertyName(), value); + return Restrictions.lt( getPropertyName(), value ); } + /** + * Create a less-than-or-equal-to restriction based on this property + * + * @param value The value to check against + * + * @return The less-than-or-equal-to restriction + * + * @see Restrictions#le(String, Object) + */ public SimpleExpression le(Object value) { - return Restrictions.le(getPropertyName(), value); + return Restrictions.le( getPropertyName(), value ); } + /** + * Create a greater-than-or-equal-to restriction based on this property + * + * @param value The value to check against + * + * @return The greater-than-or-equal-to restriction + * + * @see Restrictions#ge(String, Object) + */ public SimpleExpression ge(Object value) { - return Restrictions.ge(getPropertyName(), value); + return Restrictions.ge( getPropertyName(), value ); } + /** + * Creates an equality restriction between 2 properties + * + * @param other The other property to compare against + * + * @return The restriction + * + * @see Restrictions#eqProperty(String, String) + */ + @SuppressWarnings("UnusedDeclaration") public PropertyExpression eqProperty(Property other) { return Restrictions.eqProperty( getPropertyName(), other.getPropertyName() ); } - public PropertyExpression neProperty(Property other) { - return Restrictions.neProperty( getPropertyName(), other.getPropertyName() ); - } - - public PropertyExpression leProperty(Property other) { - return Restrictions.leProperty( getPropertyName(), other.getPropertyName() ); - } - - public PropertyExpression geProperty(Property other) { - return Restrictions.geProperty( getPropertyName(), other.getPropertyName() ); - } - - public PropertyExpression ltProperty(Property other) { - return Restrictions.ltProperty( getPropertyName(), other.getPropertyName() ); - } - - public PropertyExpression gtProperty(Property other) { - return Restrictions.gtProperty( getPropertyName(), other.getPropertyName() ); - } - + /** + * Creates an equality restriction between 2 properties + * + * @param other The other property to compare against + * + * @return The restriction + * + * @see Restrictions#eqProperty(String, String) + */ + @SuppressWarnings("UnusedDeclaration") public PropertyExpression eqProperty(String other) { return Restrictions.eqProperty( getPropertyName(), other ); } + /** + * Creates an non-equality restriction between 2 properties + * + * @param other The other property to compare against + * + * @return The restriction + * + * @see Restrictions#neProperty(String, String) + */ + @SuppressWarnings("UnusedDeclaration") + public PropertyExpression neProperty(Property other) { + return Restrictions.neProperty( getPropertyName(), other.getPropertyName() ); + } + + /** + * Creates an non-equality restriction between 2 properties + * + * @param other The other property to compare against + * + * @return The restriction + * + * @see Restrictions#neProperty(String, String) + */ + @SuppressWarnings("UnusedDeclaration") public PropertyExpression neProperty(String other) { return Restrictions.neProperty( getPropertyName(), other ); } - + + /** + * Creates an less-than-or-equal-to restriction between 2 properties + * + * @param other The other property to compare against + * + * @return The restriction + * + * @see Restrictions#leProperty(String, String) + */ + @SuppressWarnings("UnusedDeclaration") + public PropertyExpression leProperty(Property other) { + return Restrictions.leProperty( getPropertyName(), other.getPropertyName() ); + } + + /** + * Creates an less-than-or-equal-to restriction between 2 properties + * + * @param other The other property to compare against + * + * @return The restriction + * + * @see Restrictions#leProperty(String, String) + */ + @SuppressWarnings("UnusedDeclaration") public PropertyExpression leProperty(String other) { return Restrictions.leProperty( getPropertyName(), other ); } + /** + * Creates an greater-than-or-equal-to restriction between 2 properties + * + * @param other The other property to compare against + * + * @return The restriction + * + * @see Restrictions#geProperty(String, String) + */ + @SuppressWarnings("UnusedDeclaration") + public PropertyExpression geProperty(Property other) { + return Restrictions.geProperty( getPropertyName(), other.getPropertyName() ); + } + + /** + * Creates an greater-than-or-equal-to restriction between 2 properties + * + * @param other The other property to compare against + * + * @return The restriction + * + * @see Restrictions#geProperty(String, String) + */ + @SuppressWarnings("UnusedDeclaration") public PropertyExpression geProperty(String other) { return Restrictions.geProperty( getPropertyName(), other ); } - + + /** + * Creates an less-than restriction between 2 properties + * + * @param other The other property to compare against + * + * @return The restriction + * + * @see Restrictions#ltProperty(String, String) + */ + @SuppressWarnings("UnusedDeclaration") + public PropertyExpression ltProperty(Property other) { + return Restrictions.ltProperty( getPropertyName(), other.getPropertyName() ); + } + + /** + * Creates an less-than restriction between 2 properties + * + * @param other The other property to compare against + * + * @return The restriction + * + * @see Restrictions#ltProperty(String, String) + */ + @SuppressWarnings("UnusedDeclaration") public PropertyExpression ltProperty(String other) { return Restrictions.ltProperty( getPropertyName(), other ); } + /** + * Creates an greater-than restriction between 2 properties + * + * @param other The other property to compare against + * + * @return The restriction + * + * @see Restrictions#geProperty(String, String) + */ + @SuppressWarnings("UnusedDeclaration") + public PropertyExpression gtProperty(Property other) { + return Restrictions.gtProperty( getPropertyName(), other.getPropertyName() ); + } + + /** + * Creates an greater-than restriction between 2 properties + * + * @param other The other property to compare against + * + * @return The restriction + * + * @see Restrictions#geProperty(String, String) + */ + @SuppressWarnings("UnusedDeclaration") public PropertyExpression gtProperty(String other) { return Restrictions.gtProperty( getPropertyName(), other ); } - + + /** + * Creates a NULL restriction + * + * @return The restriction + * + * @see Restrictions#isNull(String) + */ public Criterion isNull() { - return Restrictions.isNull(getPropertyName()); + return Restrictions.isNull( getPropertyName() ); } + /** + * Creates a NOT NULL restriction + * + * @return The restriction + * + * @see Restrictions#isNotNull(String) + */ public Criterion isNotNull() { - return Restrictions.isNotNull(getPropertyName()); + return Restrictions.isNotNull( getPropertyName() ); } + /** + * Creates a restriction to check that a collection is empty + * + * @return The restriction + * + * @see Restrictions#isEmpty(String) + */ public Criterion isEmpty() { - return Restrictions.isEmpty(getPropertyName()); + return Restrictions.isEmpty( getPropertyName() ); } + /** + * Creates a restriction to check that a collection is not empty + * + * @return The restriction + * + * @see Restrictions#isNotEmpty(String) + */ public Criterion isNotEmpty() { - return Restrictions.isNotEmpty(getPropertyName()); + return Restrictions.isNotEmpty( getPropertyName() ); } - + + /** + * Creates a property count projection + * + * @return The projection + * + * @see Projections#count + */ public CountProjection count() { - return Projections.count(getPropertyName()); + return Projections.count( getPropertyName() ); } - + + /** + * Creates a property max projection + * + * @return The projection + * + * @see Projections#max + */ public AggregateProjection max() { - return Projections.max(getPropertyName()); + return Projections.max( getPropertyName() ); } + /** + * Creates a property min projection + * + * @return The projection + * + * @see Projections#min + */ public AggregateProjection min() { - return Projections.min(getPropertyName()); + return Projections.min( getPropertyName() ); } + /** + * Creates a property avg projection + * + * @return The projection + * + * @see Projections#avg + */ public AggregateProjection avg() { - return Projections.avg(getPropertyName()); + return Projections.avg( getPropertyName() ); } - - /*public PropertyProjection project() { - return Projections.property(getPropertyName()); - }*/ + /** + * Creates a projection for this property as a group expression + * + * @return The group projection + * + * @see Projections#groupProperty + */ public PropertyProjection group() { - return Projections.groupProperty(getPropertyName()); + return Projections.groupProperty( getPropertyName() ); } - + + /** + * Creates an ascending ordering for this property + * + * @return The order + */ public Order asc() { - return Order.asc(getPropertyName()); + return Order.asc( getPropertyName() ); } + /** + * Creates a descending ordering for this property + * + * @return The order + */ public Order desc() { - return Order.desc(getPropertyName()); - } - - public static Property forName(String propertyName) { - return new Property(propertyName); + return Order.desc( getPropertyName() ); } /** - * Get a component attribute of this property + * Get a component attribute of this property. + * + * @param propertyName The sub property name + * + * @return The property */ public Property getProperty(String propertyName) { return forName( getPropertyName() + '.' + propertyName ); } - + + /** + * Creates a sub-query equality expression for this property + * + * @param subselect The sub-query + * + * @return The expression + * + * @see Subqueries#propertyEq(String, DetachedCriteria) + */ public Criterion eq(DetachedCriteria subselect) { return Subqueries.propertyEq( getPropertyName(), subselect ); } + /** + * Creates a sub-query non-equality expression for this property + * + * @param subselect The sub-query + * + * @return The expression + * + * @see Subqueries#propertyNe(String, DetachedCriteria) + */ public Criterion ne(DetachedCriteria subselect) { return Subqueries.propertyNe( getPropertyName(), subselect ); } + /** + * Creates a sub-query less-than expression for this property + * + * @param subselect The sub-query + * + * @return The expression + * + * @see Subqueries#propertyLt(String, DetachedCriteria) + */ public Criterion lt(DetachedCriteria subselect) { return Subqueries.propertyLt( getPropertyName(), subselect ); } + /** + * Creates a sub-query less-than-or-equal-to expression for this property + * + * @param subselect The sub-query + * + * @return The expression + * + * @see Subqueries#propertyLe(String, DetachedCriteria) + */ public Criterion le(DetachedCriteria subselect) { return Subqueries.propertyLe( getPropertyName(), subselect ); } + /** + * Creates a sub-query greater-than expression for this property + * + * @param subselect The sub-query + * + * @return The expression + * + * @see Subqueries#propertyGt(String, DetachedCriteria) + */ public Criterion gt(DetachedCriteria subselect) { return Subqueries.propertyGt( getPropertyName(), subselect ); } + /** + * Creates a sub-query greater-than-or-equal-to expression for this property + * + * @param subselect The sub-query + * + * @return The expression + * + * @see Subqueries#propertyGe(String, DetachedCriteria) + */ public Criterion ge(DetachedCriteria subselect) { return Subqueries.propertyGe( getPropertyName(), subselect ); } + /** + * Creates a sub-query NOT IN expression for this property. I.e., {@code [prop] NOT IN [subquery]} + * + * @param subselect The sub-query + * + * @return The expression + * + * @see Subqueries#propertyNotIn(String, DetachedCriteria) + */ + @SuppressWarnings("UnusedDeclaration") public Criterion notIn(DetachedCriteria subselect) { return Subqueries.propertyNotIn( getPropertyName(), subselect ); } + /** + * Creates a sub-query IN expression for this property. I.e., {@code [prop] IN [subquery]} + * + * @param subselect The sub-query + * + * @return The expression + * + * @see Subqueries#propertyIn(String, DetachedCriteria) + */ public Criterion in(DetachedCriteria subselect) { return Subqueries.propertyIn( getPropertyName(), subselect ); } + /** + * Creates a equals-all sub-query expression for this property. I.e., {@code [prop] = ALL [subquery]} + * + * @param subselect The sub-query + * + * @return The expression + * + * @see Subqueries#propertyEqAll(String, DetachedCriteria) + */ public Criterion eqAll(DetachedCriteria subselect) { return Subqueries.propertyEqAll( getPropertyName(), subselect ); } + /** + * Creates a greater-than-all sub-query expression for this property. I.e., {@code [prop] > ALL [subquery]} + * + * @param subselect The sub-query + * + * @return The expression + * + * @see Subqueries#propertyGtAll(String, DetachedCriteria) + */ + @SuppressWarnings("UnusedDeclaration") public Criterion gtAll(DetachedCriteria subselect) { return Subqueries.propertyGtAll( getPropertyName(), subselect ); } + /** + * Creates a less-than-all sub-query expression for this property. I.e., {@code [prop] < ALL [subquery]} + * + * @param subselect The sub-query + * + * @return The expression + * + * @see Subqueries#propertyLtAll(String, DetachedCriteria) + */ + @SuppressWarnings("UnusedDeclaration") public Criterion ltAll(DetachedCriteria subselect) { return Subqueries.propertyLtAll( getPropertyName(), subselect ); } + /** + * Creates a less-than-or-equal-to-all sub-query expression for this property. I.e., {@code [prop] <= ALL [subquery]} + * + * @param subselect The sub-query + * + * @return The expression + * + * @see Subqueries#propertyLeAll(String, DetachedCriteria) + */ + @SuppressWarnings("UnusedDeclaration") public Criterion leAll(DetachedCriteria subselect) { return Subqueries.propertyLeAll( getPropertyName(), subselect ); } + /** + * Creates a greater-than-or-equal-to-all sub-query expression for this property. I.e., {@code [prop] >= ALL [subquery]} + * + * @param subselect The sub-query + * + * @return The expression + * + * @see Subqueries#propertyGeAll(String, DetachedCriteria) + */ + @SuppressWarnings("UnusedDeclaration") public Criterion geAll(DetachedCriteria subselect) { return Subqueries.propertyGeAll( getPropertyName(), subselect ); } + /** + * Creates a greater-than-some sub-query expression for this property. I.e., {@code [prop] > SOME [subquery]} + * + * @param subselect The sub-query + * + * @return The expression + * + * @see Subqueries#propertyGtSome(String, DetachedCriteria) + */ + @SuppressWarnings("UnusedDeclaration") public Criterion gtSome(DetachedCriteria subselect) { return Subqueries.propertyGtSome( getPropertyName(), subselect ); } + /** + * Creates a less-than-some sub-query expression for this property. I.e., {@code [prop] < SOME [subquery]} + * + * @param subselect The sub-query + * + * @return The expression + * + * @see Subqueries#propertyLtSome(String, DetachedCriteria) + */ + @SuppressWarnings("UnusedDeclaration") public Criterion ltSome(DetachedCriteria subselect) { return Subqueries.propertyLtSome( getPropertyName(), subselect ); } + /** + * Creates a less-than-or-equal-to-some sub-query expression for this property. I.e., {@code [prop] <= SOME [subquery]} + * + * @param subselect The sub-query + * + * @return The expression + * + * @see Subqueries#propertyLeSome(String, DetachedCriteria) + */ + @SuppressWarnings("UnusedDeclaration") public Criterion leSome(DetachedCriteria subselect) { return Subqueries.propertyLeSome( getPropertyName(), subselect ); } + /** + * Creates a greater-than-or-equal-to-some sub-query expression for this property. I.e., {@code [prop] >= SOME [subquery]} + * + * @param subselect The sub-query + * + * @return The expression + * + * @see Subqueries#propertyGeSome(String, DetachedCriteria) + */ + @SuppressWarnings("UnusedDeclaration") public Criterion geSome(DetachedCriteria subselect) { return Subqueries.propertyGeSome( getPropertyName(), subselect ); } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/PropertyExpression.java b/hibernate-core/src/main/java/org/hibernate/criterion/PropertyExpression.java index 359696b5d3..c9b5701168 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/PropertyExpression.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/PropertyExpression.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,9 +20,9 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; + import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.engine.spi.TypedValue; @@ -30,46 +30,48 @@ import org.hibernate.internal.util.StringHelper; /** * superclass for comparisons between two properties (with SQL binary operators) + * * @author Gavin King */ public class PropertyExpression implements Criterion { + private static final TypedValue[] NO_TYPED_VALUES = new TypedValue[0]; private final String propertyName; private final String otherPropertyName; private final String op; - private static final TypedValue[] NO_TYPED_VALUES = new TypedValue[0]; - protected PropertyExpression(String propertyName, String otherPropertyName, String op) { this.propertyName = propertyName; this.otherPropertyName = otherPropertyName; this.op = op; } - public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - String[] xcols = criteriaQuery.findColumns(propertyName, criteria); - String[] ycols = criteriaQuery.findColumns(otherPropertyName, criteria); - String result = StringHelper.join( - " and ", - StringHelper.add( xcols, getOp(), ycols ) - ); - if (xcols.length>1) result = '(' + result + ')'; - return result; - //TODO: get SQL rendering out of this package! - } - - public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - return NO_TYPED_VALUES; - } - - public String toString() { - return propertyName + getOp() + otherPropertyName; - } - public String getOp() { return op; } + @Override + public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { + final String[] lhsColumns = criteriaQuery.findColumns( propertyName, criteria ); + final String[] rhsColumns = criteriaQuery.findColumns( otherPropertyName, criteria ); + + final String[] comparisons = StringHelper.add( lhsColumns, getOp(), rhsColumns ); + if ( comparisons.length > 1 ) { + return '(' + StringHelper.join( " and ", comparisons ) + ')'; + } + else { + return comparisons[0]; + } + } + + @Override + public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) { + return NO_TYPED_VALUES; + } + + @Override + public String toString() { + return propertyName + getOp() + otherPropertyName; + } + } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/PropertyProjection.java b/hibernate-core/src/main/java/org/hibernate/criterion/PropertyProjection.java index 00fe0a9324..44832d7928 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/PropertyProjection.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/PropertyProjection.java @@ -30,62 +30,66 @@ import org.hibernate.type.Type; /** * A property value, or grouped property value + * * @author Gavin King + * @author Steve Ebersole */ public class PropertyProjection extends SimpleProjection { - private String propertyName; private boolean grouped; - + protected PropertyProjection(String prop, boolean grouped) { this.propertyName = prop; this.grouped = grouped; } - + protected PropertyProjection(String prop) { this(prop, false); } + @Override + public boolean isGrouped() { + return grouped; + } + public String getPropertyName() { return propertyName; } - - public String toString() { - return propertyName; + + @Override + public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { + return new Type[] { criteriaQuery.getType( criteria, propertyName ) }; } - public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - return new Type[] { criteriaQuery.getType(criteria, propertyName) }; - } - - public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery) - throws HibernateException { - StringBuilder buf = new StringBuilder(); - String[] cols = criteriaQuery.getColumns( propertyName, criteria ); + @Override + public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery) throws HibernateException { + final StringBuilder buf = new StringBuilder(); + final String[] cols = criteriaQuery.getColumns( propertyName, criteria ); for ( int i=0; iCriterion. However, it is intended that most applications will * simply use the built-in criterion types via the static factory methods of this class. * - * @see org.hibernate.Criteria - * @see Projections factory methods for Projection instances + * See also the {@link Projections} factory methods for generating {@link Projection} instances + * * @author Gavin King + * @author Steve Ebersole + * + * @see org.hibernate.Criteria */ public class Restrictions { - - Restrictions() { - //cannot be instantiated - } - /** * Apply an "equal" constraint to the identifier property - * @param value + * + * @param value The value to use in comparison + * * @return Criterion + * + * @see IdentifierEqExpression */ public static Criterion idEq(Object value) { - return new IdentifierEqExpression(value); + return new IdentifierEqExpression( value ); } /** * Apply an "equal" constraint to the named property - * @param propertyName - * @param value + * + * @param propertyName The name of the property + * @param value The value to use in comparison + * * @return SimpleExpression + * + * @see SimpleExpression */ public static SimpleExpression eq(String propertyName, Object value) { - return new SimpleExpression(propertyName, value, "="); - } - /** - * Apply an "equal" constraint to the named property. If the value - * is null, instead apply "is null". - * @param propertyName - * @param value - * @return Criterion - */ - public static Criterion eqOrIsNull(String propertyName, Object value) { - if (value == null) { - return isNull(propertyName); - } - return new SimpleExpression(propertyName, value, "="); - } - /** - * Apply a "not equal" constraint to the named property - * @param propertyName - * @param value - * @return SimpleExpression - */ - public static SimpleExpression ne(String propertyName, Object value) { - return new SimpleExpression(propertyName, value, "<>"); - } - /** - * Apply a "not equal" constraint to the named property. If the value - * is null, instead apply "is not null". - * @param propertyName - * @param value - * @return Criterion - */ - public static Criterion neOrIsNotNull(String propertyName, Object value) { - if (value == null) { - return isNotNull(propertyName); - } - return new SimpleExpression(propertyName, value, "<>"); - } - /** - * Apply a "like" constraint to the named property - * @param propertyName - * @param value - * @return Criterion - */ - public static SimpleExpression like(String propertyName, Object value) { - return new SimpleExpression(propertyName, value, " like "); - } - /** - * Apply a "like" constraint to the named property - * @param propertyName - * @param value - * @return Criterion - */ - public static SimpleExpression like(String propertyName, String value, MatchMode matchMode) { - return new SimpleExpression(propertyName, matchMode.toMatchString(value), " like " ); + return new SimpleExpression( propertyName, value, "=" ); } /** - * A case-insensitive "like", similar to Postgres ilike - * operator + * Apply an "equal" constraint to the named property. If the value + * is null, instead apply "is null". * - * @param propertyName - * @param value - * @return Criterion + * @param propertyName The name of the property + * @param value The value to use in comparison + * + * @return The Criterion + * + * @see #eq + * @see #isNull */ - public static Criterion ilike(String propertyName, String value, MatchMode matchMode) { - return new LikeExpression(propertyName, value, matchMode, null, true); + public static Criterion eqOrIsNull(String propertyName, Object value) { + return value == null + ? isNull( propertyName ) + : eq( propertyName, value ); } + /** - * A case-insensitive "like", similar to Postgres ilike - * operator + * Apply a "not equal" constraint to the named property * - * @param propertyName - * @param value - * @return Criterion + * @param propertyName The name of the property + * @param value The value to use in comparison + * + * @return The Criterion + + * @see SimpleExpression + */ + public static SimpleExpression ne(String propertyName, Object value) { + return new SimpleExpression( propertyName, value, "<>" ); + } + + /** + * Apply a "not equal" constraint to the named property. If the value + * is null, instead apply "is not null". + * + * @param propertyName The name of the property + * @param value The value to use in comparison + * + * @return The Criterion + * + * @see #ne + * @see #isNotNull + */ + public static Criterion neOrIsNotNull(String propertyName, Object value) { + return value == null + ? isNotNull( propertyName ) + : ne( propertyName, value ); + } + + /** + * Apply a "like" constraint to the named property + * + * @param propertyName The name of the property + * @param value The value to use in comparison + * + * @return The Criterion + * + * @see SimpleExpression + */ + public static SimpleExpression like(String propertyName, Object value) { + // todo : update this to use LikeExpression + return new SimpleExpression( propertyName, value, " like " ); + } + + /** + * Apply a "like" constraint to the named property using the provided match mode + * + * @param propertyName The name of the property + * @param value The value to use in comparison + * @param matchMode The match mode to use in comparison + * + * @return The Criterion + * + * @see SimpleExpression + */ + public static SimpleExpression like(String propertyName, String value, MatchMode matchMode) { + // todo : update this to use LikeExpression + return new SimpleExpression( propertyName, matchMode.toMatchString( value ), " like " ); + } + + /** + * A case-insensitive "like" (similar to Postgres ilike operator) + * + * @param propertyName The name of the property + * @param value The value to use in comparison + * + * @return The Criterion + * + * @see LikeExpression */ public static Criterion ilike(String propertyName, Object value) { if ( value == null ) { @@ -144,126 +165,239 @@ public class Restrictions { return ilike( propertyName, value.toString(), MatchMode.EXACT ); } + /** + * A case-insensitive "like" (similar to Postgres ilike operator) using the provided match mode + * + * @param propertyName The name of the property + * @param value The value to use in comparison + * @param matchMode The match mode to use in comparison + * + * @return The Criterion + * + * @see LikeExpression + */ + public static Criterion ilike(String propertyName, String value, MatchMode matchMode) { + if ( value == null ) { + throw new IllegalArgumentException( "Comparison value passed to ilike cannot be null" ); + } + return new LikeExpression( propertyName, value, matchMode, null, true ); + } + /** * Apply a "greater than" constraint to the named property - * @param propertyName - * @param value - * @return Criterion + * + * @param propertyName The name of the property + * @param value The value to use in comparison + * + * @return The Criterion + * + * @see SimpleExpression */ public static SimpleExpression gt(String propertyName, Object value) { - return new SimpleExpression(propertyName, value, ">"); + return new SimpleExpression( propertyName, value, ">" ); } + /** * Apply a "less than" constraint to the named property - * @param propertyName - * @param value - * @return Criterion + * + * @param propertyName The name of the property + * @param value The value to use in comparison + * + * @return The Criterion + * + * @see SimpleExpression */ public static SimpleExpression lt(String propertyName, Object value) { - return new SimpleExpression(propertyName, value, "<"); + return new SimpleExpression( propertyName, value, "<" ); } + /** * Apply a "less than or equal" constraint to the named property - * @param propertyName - * @param value - * @return Criterion + * + * @param propertyName The name of the property + * @param value The value to use in comparison + * + * @return The Criterion + * + * @see SimpleExpression */ public static SimpleExpression le(String propertyName, Object value) { - return new SimpleExpression(propertyName, value, "<="); + return new SimpleExpression( propertyName, value, "<=" ); } /** * Apply a "greater than or equal" constraint to the named property - * @param propertyName - * @param value - * @return Criterion + * + * @param propertyName The name of the property + * @param value The value to use in comparison + * + * @return The Criterion + * + * @see SimpleExpression */ public static SimpleExpression ge(String propertyName, Object value) { - return new SimpleExpression(propertyName, value, ">="); + return new SimpleExpression( propertyName, value, ">=" ); } + /** * Apply a "between" constraint to the named property - * @param propertyName - * @param lo value - * @param hi value - * @return Criterion + * + * @param propertyName The name of the property + * @param lo The low value + * @param hi The high value + * + * @return The Criterion + * + * @see BetweenExpression */ public static Criterion between(String propertyName, Object lo, Object hi) { - return new BetweenExpression(propertyName, lo, hi); + return new BetweenExpression( propertyName, lo, hi ); } + /** - * Apply an "in" constraint to the named property - * @param propertyName - * @param values - * @return Criterion + * Apply an "in" constraint to the named property. + * + * @param propertyName The name of the property + * @param values The literal values to use in the IN restriction + * + * @return The Criterion + * + * @see InExpression */ public static Criterion in(String propertyName, Object[] values) { - return new InExpression(propertyName, values); + return new InExpression( propertyName, values ); } + /** - * Apply an "in" constraint to the named property - * @param propertyName - * @param values - * @return Criterion + * Apply an "in" constraint to the named property. + * + * @param propertyName The name of the property + * @param values The literal values to use in the IN restriction + * + * @return The Criterion + * + * @see InExpression */ public static Criterion in(String propertyName, Collection values) { return new InExpression( propertyName, values.toArray() ); } + /** * Apply an "is null" constraint to the named property + * + * @param propertyName The name of the property + * * @return Criterion + * + * @see NullExpression */ public static Criterion isNull(String propertyName) { - return new NullExpression(propertyName); - } - /** - * Apply an "equal" constraint to two properties - */ - public static PropertyExpression eqProperty(String propertyName, String otherPropertyName) { - return new PropertyExpression(propertyName, otherPropertyName, "="); - } - /** - * Apply a "not equal" constraint to two properties - */ - public static PropertyExpression neProperty(String propertyName, String otherPropertyName) { - return new PropertyExpression(propertyName, otherPropertyName, "<>"); - } - /** - * Apply a "less than" constraint to two properties - */ - public static PropertyExpression ltProperty(String propertyName, String otherPropertyName) { - return new PropertyExpression(propertyName, otherPropertyName, "<"); - } - /** - * Apply a "less than or equal" constraint to two properties - */ - public static PropertyExpression leProperty(String propertyName, String otherPropertyName) { - return new PropertyExpression(propertyName, otherPropertyName, "<="); - } - /** - * Apply a "greater than" constraint to two properties - */ - public static PropertyExpression gtProperty(String propertyName, String otherPropertyName) { - return new PropertyExpression(propertyName, otherPropertyName, ">"); - } - /** - * Apply a "greater than or equal" constraint to two properties - */ - public static PropertyExpression geProperty(String propertyName, String otherPropertyName) { - return new PropertyExpression(propertyName, otherPropertyName, ">="); + return new NullExpression( propertyName ); } + /** * Apply an "is not null" constraint to the named property - * @return Criterion + * + * @param propertyName The property name + * + * @return The Criterion + * + * @see NotNullExpression */ public static Criterion isNotNull(String propertyName) { - return new NotNullExpression(propertyName); + return new NotNullExpression( propertyName ); } + + /** + * Apply an "equal" constraint to two properties + * + * @param propertyName One property name + * @param otherPropertyName The other property name + * + * @return The Criterion + * + * @see PropertyExpression + */ + public static PropertyExpression eqProperty(String propertyName, String otherPropertyName) { + return new PropertyExpression( propertyName, otherPropertyName, "=" ); + } + + /** + * Apply a "not equal" constraint to two properties + * + * @param propertyName One property name + * @param otherPropertyName The other property name + * + * @return The Criterion + * + * @see PropertyExpression + */ + public static PropertyExpression neProperty(String propertyName, String otherPropertyName) { + return new PropertyExpression( propertyName, otherPropertyName, "<>" ); + } + + /** + * Apply a "less than" constraint to two properties + * + * @param propertyName One property name + * @param otherPropertyName The other property name + * + * @return The Criterion + * + * @see PropertyExpression + */ + public static PropertyExpression ltProperty(String propertyName, String otherPropertyName) { + return new PropertyExpression( propertyName, otherPropertyName, "<" ); + } + + /** + * Apply a "less than or equal" constraint to two properties + * + * @param propertyName One property name + * @param otherPropertyName The other property name + * + * @return The Criterion + * + * @see PropertyExpression + */ + public static PropertyExpression leProperty(String propertyName, String otherPropertyName) { + return new PropertyExpression( propertyName, otherPropertyName, "<=" ); + } + + /** + * Apply a "greater than" constraint to two properties + * + * @param propertyName One property name + * @param otherPropertyName The other property name + * + * @return The Criterion + * + * @see PropertyExpression + */ + public static PropertyExpression gtProperty(String propertyName, String otherPropertyName) { + return new PropertyExpression( propertyName, otherPropertyName, ">" ); + } + + /** + * Apply a "greater than or equal" constraint to two properties + * + * @param propertyName One property name + * @param otherPropertyName The other property name + * + * @return The Criterion + * + * @see PropertyExpression + */ + public static PropertyExpression geProperty(String propertyName, String otherPropertyName) { + return new PropertyExpression( propertyName, otherPropertyName, ">=" ); + } + /** * Return the conjuction of two expressions * - * @param lhs - * @param rhs - * @return Criterion + * @param lhs One expression + * @param rhs The other expression + * + * @return The Criterion */ public static LogicalExpression and(Criterion lhs, Criterion rhs) { return new LogicalExpression(lhs, rhs, "and"); @@ -276,24 +410,21 @@ public class Restrictions { * @return The conjunction */ public static Conjunction and(Criterion... predicates) { - Conjunction conjunction = conjunction(); - if ( predicates != null ) { - for ( Criterion predicate : predicates ) { - conjunction.add( predicate ); - } - } - return conjunction; + return conjunction( predicates ); } + /** * Return the disjuction of two expressions * - * @param lhs - * @param rhs - * @return Criterion + * @param lhs One expression + * @param rhs The other expression + * + * @return The Criterion */ public static LogicalExpression or(Criterion lhs, Criterion rhs) { - return new LogicalExpression(lhs, rhs, "or"); + return new LogicalExpression( lhs, rhs, "or" ); } + /** * Return the disjuction of multiple expressions * @@ -302,62 +433,72 @@ public class Restrictions { * @return The conjunction */ public static Disjunction or(Criterion... predicates) { - Disjunction disjunction = disjunction(); - if ( predicates != null ) { - for ( Criterion predicate : predicates ) { - disjunction.add( predicate ); - } - } - return disjunction; - } - /** - * Return the negation of an expression - * - * @param expression - * @return Criterion - */ - public static Criterion not(Criterion expression) { - return new NotExpression(expression); - } - /** - * Apply a constraint expressed in SQL, with the given JDBC - * parameters. Any occurrences of {alias} will be - * replaced by the table alias. - * - * @param sql - * @param values - * @param types - * @return Criterion - */ - public static Criterion sqlRestriction(String sql, Object[] values, Type[] types) { - return new SQLCriterion(sql, values, types); - } - /** - * Apply a constraint expressed in SQL, with the given JDBC - * parameter. Any occurrences of {alias} will be replaced - * by the table alias. - * - * @param sql - * @param value - * @param type - * @return Criterion - */ - public static Criterion sqlRestriction(String sql, Object value, Type type) { - return new SQLCriterion(sql, new Object[] { value }, new Type[] { type } ); - } - /** - * Apply a constraint expressed in SQL. Any occurrences of {alias} - * will be replaced by the table alias. - * - * @param sql - * @return Criterion - */ - public static Criterion sqlRestriction(String sql) { - return new SQLCriterion(sql, ArrayHelper.EMPTY_OBJECT_ARRAY, ArrayHelper.EMPTY_TYPE_ARRAY); + return disjunction( predicates ); } /** - * Group expressions together in a single conjunction (A and B and C...) + * Return the negation of an expression + * + * @param expression The expression to be negated + * + * @return Criterion + * + * @see NotExpression + */ + public static Criterion not(Criterion expression) { + return new NotExpression( expression ); + } + + /** + * Create a restriction expressed in SQL with JDBC parameters. Any occurrences of {alias} will be + * replaced by the table alias. + * + * @param sql The SQL restriction + * @param values The parameter values + * @param types The parameter types + * + * @return The Criterion + * + * @see SQLCriterion + */ + public static Criterion sqlRestriction(String sql, Object[] values, Type[] types) { + return new SQLCriterion( sql, values, types ); + } + + /** + * Create a restriction expressed in SQL with one JDBC parameter. Any occurrences of {alias} will be + * replaced by the table alias. + * + * @param sql The SQL restriction + * @param value The parameter value + * @param type The parameter type + * + * @return The Criterion + * + * @see SQLCriterion + */ + public static Criterion sqlRestriction(String sql, Object value, Type type) { + return new SQLCriterion( sql, value, type ); + } + + /** + * Apply a constraint expressed in SQL with no JDBC parameters. Any occurrences of {alias} will be + * replaced by the table alias. + * + * @param sql The SQL restriction + * + * @return The Criterion + * + * @see SQLCriterion + */ + public static Criterion sqlRestriction(String sql) { + return new SQLCriterion( sql ); + } + + /** + * Group expressions together in a single conjunction (A and B and C...). + * + * This form creates an empty conjunction. See {@link Conjunction#add(Criterion)} * * @return Conjunction */ @@ -366,7 +507,20 @@ public class Restrictions { } /** - * Group expressions together in a single disjunction (A or B or C...) + * Group expressions together in a single conjunction (A and B and C...). + * + * @param conditions The initial set of conditions to put into the Conjunction + * + * @return Conjunction + */ + public static Conjunction conjunction(Criterion... conditions) { + return new Conjunction( conditions ); + } + + /** + * Group expressions together in a single disjunction (A or B or C...). + * + * This form creates an empty disjunction. See {@link Disjunction#add(Criterion)} * * @return Conjunction */ @@ -375,89 +529,169 @@ public class Restrictions { } /** - * Apply an "equals" constraint to each property in the - * key set of a Map + * Group expressions together in a single disjunction (A or B or C...). + * + * @param conditions The initial set of conditions to put into the Disjunction + * + * @return Conjunction + */ + public static Disjunction disjunction(Criterion... conditions) { + return new Disjunction( conditions ); + } + + /** + * Apply an "equals" constraint to each property in the key set of a Map * * @param propertyNameValues a map from property names to values + * * @return Criterion + * + * @see Conjunction */ - public static Criterion allEq(Map propertyNameValues) { - Conjunction conj = conjunction(); - Iterator iter = propertyNameValues.entrySet().iterator(); - while ( iter.hasNext() ) { - Map.Entry me = (Map.Entry) iter.next(); - conj.add( eq( (String) me.getKey(), me.getValue() ) ); + @SuppressWarnings("UnusedDeclaration") + public static Criterion allEq(Map propertyNameValues) { + final Conjunction conj = conjunction(); + + for ( Map.Entry entry : propertyNameValues.entrySet() ) { + conj.add( eq( entry.getKey(), entry.getValue() ) ); } return conj; } /** * Constrain a collection valued property to be empty + * + * @param propertyName The name of the collection property + * + * @return The Criterion + * + * @see EmptyExpression */ public static Criterion isEmpty(String propertyName) { - return new EmptyExpression(propertyName); + return new EmptyExpression( propertyName ); } /** * Constrain a collection valued property to be non-empty + * + * @param propertyName The name of the collection property + * + * @return The Criterion + * + * @see NotEmptyExpression */ public static Criterion isNotEmpty(String propertyName) { - return new NotEmptyExpression(propertyName); + return new NotEmptyExpression( propertyName ); } /** * Constrain a collection valued property by size + * + * @param propertyName The name of the collection property + * @param size The size to use in comparison + * + * @return The Criterion + * + * @see SizeExpression */ public static Criterion sizeEq(String propertyName, int size) { - return new SizeExpression(propertyName, size, "="); + return new SizeExpression( propertyName, size, "=" ); } /** * Constrain a collection valued property by size + * + * @param propertyName The name of the collection property + * @param size The size to use in comparison + * + * @return The Criterion + * + * @see SizeExpression */ + @SuppressWarnings("UnusedDeclaration") public static Criterion sizeNe(String propertyName, int size) { - return new SizeExpression(propertyName, size, "<>"); + return new SizeExpression( propertyName, size, "<>" ); } /** * Constrain a collection valued property by size + * + * @param propertyName The name of the collection property + * @param size The size to use in comparison + * + * @return The Criterion + * + * @see SizeExpression */ + @SuppressWarnings("UnusedDeclaration") public static Criterion sizeGt(String propertyName, int size) { - return new SizeExpression(propertyName, size, "<"); + return new SizeExpression( propertyName, size, "<" ); } /** * Constrain a collection valued property by size + * + * @param propertyName The name of the collection property + * @param size The size to use in comparison + * + * @return The Criterion + * + * @see SizeExpression */ + @SuppressWarnings("UnusedDeclaration") public static Criterion sizeLt(String propertyName, int size) { - return new SizeExpression(propertyName, size, ">"); + return new SizeExpression( propertyName, size, ">" ); } /** * Constrain a collection valued property by size + * + * @param propertyName The name of the collection property + * @param size The size to use in comparison + * + * @return The Criterion + * + * @see SizeExpression */ + @SuppressWarnings("UnusedDeclaration") public static Criterion sizeGe(String propertyName, int size) { - return new SizeExpression(propertyName, size, "<="); + return new SizeExpression( propertyName, size, "<=" ); } /** * Constrain a collection valued property by size + * + * @param propertyName The name of the collection property + * @param size The size to use in comparison + * + * @return The Criterion + * + * @see SizeExpression */ + @SuppressWarnings("UnusedDeclaration") public static Criterion sizeLe(String propertyName, int size) { - return new SizeExpression(propertyName, size, ">="); + return new SizeExpression( propertyName, size, ">=" ); } /** * Consider using any of the natural id based loading stuff from session instead, especially in cases * where the restriction is the full set of natural id values. * - * @see Session#byNaturalId(Class) - * @see Session#byNaturalId(String) - * @see Session#bySimpleNaturalId(Class) - * @see Session#bySimpleNaturalId(String) + * @return The Criterion + * + * @see NaturalIdentifier + * + * @see org.hibernate.Session#byNaturalId(Class) + * @see org.hibernate.Session#byNaturalId(String) + * @see org.hibernate.Session#bySimpleNaturalId(Class) + * @see org.hibernate.Session#bySimpleNaturalId(String) */ public static NaturalIdentifier naturalId() { return new NaturalIdentifier(); } + protected Restrictions() { + // cannot be instantiated, but needs to be protected so Expression can extend it + } + } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/RowCountProjection.java b/hibernate-core/src/main/java/org/hibernate/criterion/RowCountProjection.java index 14027d6588..3ce0dba2b7 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/RowCountProjection.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/RowCountProjection.java @@ -1,7 +1,7 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2010, Red Hat Inc. or third-party contributors as + * Copyright (c) 2010, 2013, 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. @@ -22,11 +22,13 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.criterion; + import java.util.List; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.dialect.function.SQLFunction; +import org.hibernate.dialect.function.SQLFunctionRegistry; import org.hibernate.type.Type; /** @@ -35,30 +37,30 @@ import org.hibernate.type.Type; * @author Gavin King */ public class RowCountProjection extends SimpleProjection { - private static List ARGS = java.util.Collections.singletonList( "*" ); - - public String toString() { - return "count(*)"; - } + private static final List ARGS = java.util.Collections.singletonList( "*" ); + @Override public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { - return new Type[] { - getFunction( criteriaQuery ).getReturnType( null, criteriaQuery.getFactory() ) - }; + final Type countFunctionReturnType = getFunction( criteriaQuery ).getReturnType( null, criteriaQuery.getFactory() ); + return new Type[] { countFunctionReturnType }; } + @Override public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery) throws HibernateException { - return getFunction( criteriaQuery ).render( null, ARGS, criteriaQuery.getFactory() ) - + " as y" + position + '_'; + return getFunction( criteriaQuery ).render( null, ARGS, criteriaQuery.getFactory() ) + " as y" + position + '_'; } protected SQLFunction getFunction(CriteriaQuery criteriaQuery) { - SQLFunction function = criteriaQuery.getFactory() - .getSqlFunctionRegistry() - .findSQLFunction( "count" ); + final SQLFunctionRegistry sqlFunctionRegistry = criteriaQuery.getFactory().getSqlFunctionRegistry(); + final SQLFunction function = sqlFunctionRegistry.findSQLFunction( "count" ); if ( function == null ) { throw new HibernateException( "Unable to locate count function mapping" ); } return function; } + + @Override + public String toString() { + return "count(*)"; + } } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/SQLCriterion.java b/hibernate-core/src/main/java/org/hibernate/criterion/SQLCriterion.java index c44bac5ecb..60171d1cd3 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/SQLCriterion.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/SQLCriterion.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,12 +20,10 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; + import org.hibernate.Criteria; -import org.hibernate.EntityMode; -import org.hibernate.HibernateException; import org.hibernate.engine.spi.TypedValue; import org.hibernate.internal.util.StringHelper; import org.hibernate.type.Type; @@ -35,32 +33,39 @@ import org.hibernate.type.Type; * alias of the root entity. */ public class SQLCriterion implements Criterion { - private final String sql; private final TypedValue[] typedValues; - public String toSqlString( - Criteria criteria, - CriteriaQuery criteriaQuery) - throws HibernateException { - return StringHelper.replace( sql, "{alias}", criteriaQuery.getSQLAlias( criteria ) ); - } - - public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - return typedValues; - } - - public String toString() { - return sql; - } - protected SQLCriterion(String sql, Object[] values, Type[] types) { this.sql = sql; - typedValues = new TypedValue[values.length]; + this.typedValues = new TypedValue[values.length]; for ( int i=0; i 1 ) { - fragment.append( '(' ); - } - SessionFactoryImplementor factory = criteriaQuery.getFactory(); - int[] sqlTypes = type.sqlTypes( factory ); - for ( int i = 0; i < columns.length; i++ ) { - boolean lower = ignoreCase && - (sqlTypes[i] == Types.VARCHAR || sqlTypes[i] == Types.CHAR); - if ( lower ) { - fragment.append( factory.getDialect().getLowercaseFunction() ) - .append( '(' ); - } - fragment.append( columns[i] ); - if ( lower ) { - fragment.append( ')' ); - } - fragment.append( getOp() ).append( "?" ); - if ( i < columns.length - 1 ) { - fragment.append( " and " ); - } - } - if ( columns.length > 1 ) { - fragment.append( ')' ); - } - return fragment.toString(); - - } - - public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { - Object icvalue = ignoreCase ? value.toString().toLowerCase() : value; - return new TypedValue[] {criteriaQuery.getTypedValue( criteria, propertyName, icvalue )}; - } - - public String toString() { - return propertyName + getOp() + value; - } - protected final String getOp() { return op; } @@ -115,4 +66,58 @@ public class SimpleExpression implements Criterion { public Object getValue() { return value; } + + /** + * Make case insensitive. No effect for non-String values + * + * @return {@code this}, for method chaining + */ + public SimpleExpression ignoreCase() { + ignoreCase = true; + return this; + } + + @Override + public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { + final String[] columns = criteriaQuery.findColumns( propertyName, criteria ); + final Type type = criteriaQuery.getTypeUsingProjection( criteria, propertyName ); + final StringBuilder fragment = new StringBuilder(); + + if ( columns.length > 1 ) { + fragment.append( '(' ); + } + final SessionFactoryImplementor factory = criteriaQuery.getFactory(); + final int[] sqlTypes = type.sqlTypes( factory ); + for ( int i = 0; i < columns.length; i++ ) { + final boolean lower = ignoreCase && (sqlTypes[i] == Types.VARCHAR || sqlTypes[i] == Types.CHAR); + if ( lower ) { + fragment.append( factory.getDialect().getLowercaseFunction() ).append( '(' ); + } + fragment.append( columns[i] ); + if ( lower ) { + fragment.append( ')' ); + } + + fragment.append( getOp() ).append( "?" ); + if ( i < columns.length - 1 ) { + fragment.append( " and " ); + } + } + if ( columns.length > 1 ) { + fragment.append( ')' ); + } + return fragment.toString(); + } + + @Override + public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { + final Object casedValue = ignoreCase ? value.toString().toLowerCase() : value; + return new TypedValue[] { criteriaQuery.getTypedValue( criteria, propertyName, casedValue ) }; + } + + @Override + public String toString() { + return propertyName + getOp() + value; + } + } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/SimpleProjection.java b/hibernate-core/src/main/java/org/hibernate/criterion/SimpleProjection.java index b9a9062f3b..135298ce97 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/SimpleProjection.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/SimpleProjection.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,28 +20,23 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; + import org.hibernate.Criteria; import org.hibernate.type.Type; - /** * A single-column projection that may be aliased + * * @author Gavin King */ public abstract class SimpleProjection implements EnhancedProjection { - private static final int NUM_REUSABLE_ALIASES = 40; - private static final String[] reusableAliases = initializeReusableAliases(); - - public Projection as(String alias) { - return Projections.alias(this, alias); - } + private static final String[] REUSABLE_ALIASES = initializeReusableAliases(); private static String[] initializeReusableAliases() { - String[] aliases = new String[NUM_REUSABLE_ALIASES]; + final String[] aliases = new String[NUM_REUSABLE_ALIASES]; for ( int i = 0; i < NUM_REUSABLE_ALIASES; i++ ) { aliases[i] = aliasForLocation( i ); } @@ -57,38 +52,62 @@ public abstract class SimpleProjection implements EnhancedProjection { return aliasForLocation( loc ); } else { - return reusableAliases[loc]; + return REUSABLE_ALIASES[loc]; } } + /** + * Create an aliased form of this projection + * + * @param alias The alias to apply + * + * @return The aliased projection + */ + public Projection as(String alias) { + return Projections.alias( this, alias ); + } + + @Override public String[] getColumnAliases(String alias, int loc) { return null; } + @Override public String[] getColumnAliases(String alias, int loc, Criteria criteria, CriteriaQuery criteriaQuery) { return getColumnAliases( alias, loc ); } + @Override public Type[] getTypes(String alias, Criteria criteria, CriteriaQuery criteriaQuery) { return null; } + @Override public String[] getColumnAliases(int loc) { return new String[] { getAliasForLocation( loc ) }; } + /** + * Count the number of columns this projection uses. + * + * @param criteria The criteria + * @param criteriaQuery The query + * + * @return The number of columns + */ public int getColumnCount(Criteria criteria, CriteriaQuery criteriaQuery) { - Type types[] = getTypes( criteria, criteriaQuery ); + final Type[] types = getTypes( criteria, criteriaQuery ); int count = 0; - for ( int i=0; i", "all", dc ); + } + + /** + * Creates a criterion which checks that the value of a given property is less-than ALL the values in the + * subquery result. + * + * @param propertyName The name of the property to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertySubqueryExpression + */ + public static Criterion propertyLtAll(String propertyName, DetachedCriteria dc) { + return new PropertySubqueryExpression( propertyName, "<", "all", dc ); + } + + /** + * Creates a criterion which checks that the value of a given property is greater-than-or-equal-to ALL the + * values in the subquery result. + * + * @param propertyName The name of the property to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertySubqueryExpression + */ + public static Criterion propertyGeAll(String propertyName, DetachedCriteria dc) { + return new PropertySubqueryExpression( propertyName, ">=", "all", dc ); + } + + /** + * Creates a criterion which checks that the value of a given property is less-than-or-equal-to ALL the + * values in the subquery result. + * + * @param propertyName The name of the property to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertySubqueryExpression + */ + public static Criterion propertyLeAll(String propertyName, DetachedCriteria dc) { + return new PropertySubqueryExpression( propertyName, "<=", "all", dc ); + } + + /** + * Creates a criterion which checks that the value of a given property is greater-than SOME of the + * values in the subquery result. + * + * @param propertyName The name of the property to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertySubqueryExpression + */ + public static Criterion propertyGtSome(String propertyName, DetachedCriteria dc) { + return new PropertySubqueryExpression( propertyName, ">", "some", dc ); + } + + /** + * Creates a criterion which checks that the value of a given property is less-than SOME of the + * values in the subquery result. + * + * @param propertyName The name of the property to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertySubqueryExpression + */ + public static Criterion propertyLtSome(String propertyName, DetachedCriteria dc) { + return new PropertySubqueryExpression( propertyName, "<", "some", dc ); + } + + /** + * Creates a criterion which checks that the value of a given property is greater-than-or-equal-to SOME of the + * values in the subquery result. + * + * @param propertyName The name of the property to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertySubqueryExpression + */ + public static Criterion propertyGeSome(String propertyName, DetachedCriteria dc) { + return new PropertySubqueryExpression( propertyName, ">=", "some", dc ); + } + + /** + * Creates a criterion which checks that the value of a given property is less-than-or-equal-to SOME of the + * values in the subquery result. + * + * @param propertyName The name of the property to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertySubqueryExpression + */ + public static Criterion propertyLeSome(String propertyName, DetachedCriteria dc) { + return new PropertySubqueryExpression( propertyName, "<=", "some", dc ); + } + + /** + * Creates a criterion which checks that the value of a given property is in the set of values in the + * subquery result. + * + * @param propertyName The name of the property to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertySubqueryExpression + */ public static Criterion propertyIn(String propertyName, DetachedCriteria dc) { - return new PropertySubqueryExpression(propertyName, "in", null, dc); + return new PropertySubqueryExpression( propertyName, "in", null, dc ); } - + + /** + * Creates a criterion which checks that the value of a given property is not-in the set of values in + * the subquery result. + * + * @param propertyName The name of the property to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertySubqueryExpression + */ public static Criterion propertyNotIn(String propertyName, DetachedCriteria dc) { - return new PropertySubqueryExpression(propertyName, "not in", null, dc); + return new PropertySubqueryExpression( propertyName, "not in", null, dc ); } - + + /** + * Creates a criterion which checks that the value of a given property as being equal to the set of values in + * the subquery result. The implication is that the subquery returns a single result.. + * + * @param propertyName The name of the property to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertySubqueryExpression + */ public static Criterion propertyEq(String propertyName, DetachedCriteria dc) { - return new PropertySubqueryExpression(propertyName, "=", null, dc); + return new PropertySubqueryExpression( propertyName, "=", null, dc ); } - public static Criterion propertiesEq(String[] propertyNames, DetachedCriteria dc) { - return new PropertiesSubqueryExpression(propertyNames, "=", dc); - } - - public static Criterion propertiesNotEq(String[] propertyNames, DetachedCriteria dc) { - return new PropertiesSubqueryExpression(propertyNames, "<>", dc); - } - - public static Criterion propertiesIn(String[] propertyNames, DetachedCriteria dc) { - return new PropertiesSubqueryExpression(propertyNames, "in", dc); - } - - public static Criterion propertiesNotIn(String[] propertyNames, DetachedCriteria dc) { - return new PropertiesSubqueryExpression(propertyNames, "not in", dc); - } - + /** + * Creates a criterion which checks that the value of a given property is not equal to the value in the + * subquery result. The assumption is that the subquery returns a single result. + * + * @param propertyName The name of the property to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertySubqueryExpression + */ public static Criterion propertyNe(String propertyName, DetachedCriteria dc) { return new PropertySubqueryExpression(propertyName, "<>", null, dc); } - + + /** + * Creates a criterion which checks that the value of a given property is greater-than the value in the + * subquery result. The assumption is that the subquery returns a single result. + * + * @param propertyName The name of the property to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertySubqueryExpression + * @see #propertyGtAll + * @see #propertyGtSome + */ public static Criterion propertyGt(String propertyName, DetachedCriteria dc) { - return new PropertySubqueryExpression(propertyName, ">", null, dc); + return new PropertySubqueryExpression( propertyName, ">", null, dc ); } - + + /** + * Creates a criterion which checks that the value of a given property is less-than the value in the + * subquery result. The assumption is that the subquery returns a single result. + * + * @param propertyName The name of the property to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertySubqueryExpression + * @see #propertyLtAll + * @see #propertyLtSome + */ public static Criterion propertyLt(String propertyName, DetachedCriteria dc) { - return new PropertySubqueryExpression(propertyName, "<", null, dc); + return new PropertySubqueryExpression( propertyName, "<", null, dc ); } - + + /** + * Creates a criterion which checks that the value of a given property is greater-than-or-equal-to the value + * in the subquery result. The assumption is that the subquery returns a single result. + * + * @param propertyName The name of the property to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertySubqueryExpression + * @see #propertyGeAll + * @see #propertyGeSome + */ public static Criterion propertyGe(String propertyName, DetachedCriteria dc) { - return new PropertySubqueryExpression(propertyName, ">=", null, dc); + return new PropertySubqueryExpression( propertyName, ">=", null, dc ); } - + + /** + * Creates a criterion which checks that the value of a given property is less-than-or-equal-to the value + * in the subquery result. The assumption is that the subquery returns a single result. + * + * @param propertyName The name of the property to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertySubqueryExpression + * @see #propertyLeAll + * @see #propertyLeSome + */ public static Criterion propertyLe(String propertyName, DetachedCriteria dc) { - return new PropertySubqueryExpression(propertyName, "<=", null, dc); + return new PropertySubqueryExpression( propertyName, "<=", null, dc ); } - - public static Criterion propertyGtAll(String propertyName, DetachedCriteria dc) { - return new PropertySubqueryExpression(propertyName, ">", "all", dc); + + /** + * Creates a criterion which checks that the value of multiple given properties as being equal to the set of + * values in the subquery result. The implication is that the subquery returns a single result. This form is + * however implicitly using tuple comparisons + * + * @param propertyNames The names of the properties to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertiesSubqueryExpression + */ + public static Criterion propertiesEq(String[] propertyNames, DetachedCriteria dc) { + return new PropertiesSubqueryExpression( propertyNames, "=", dc ); } - - public static Criterion propertyLtAll(String propertyName, DetachedCriteria dc) { - return new PropertySubqueryExpression(propertyName, "<", "all", dc); + + /** + * Creates a criterion which checks that the value of multiple given properties as being not-equal to the set of + * values in the subquery result. The assumption is that the subquery returns a single result. This form is + * however implicitly using tuple comparisons + * + * @param propertyNames The names of the properties to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertiesSubqueryExpression + */ + public static Criterion propertiesNotEq(String[] propertyNames, DetachedCriteria dc) { + return new PropertiesSubqueryExpression( propertyNames, "<>", dc ); } - - public static Criterion propertyGeAll(String propertyName, DetachedCriteria dc) { - return new PropertySubqueryExpression(propertyName, ">=", "all", dc); + + /** + * Creates a criterion which checks that the value of multiple given properties as being in to the set of + * values in the subquery result. This form is implicitly using tuple comparisons + * + * @param propertyNames The names of the properties to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertiesSubqueryExpression + */ + public static Criterion propertiesIn(String[] propertyNames, DetachedCriteria dc) { + return new PropertiesSubqueryExpression( propertyNames, "in", dc ); } - - public static Criterion propertyLeAll(String propertyName, DetachedCriteria dc) { - return new PropertySubqueryExpression(propertyName, "<=", "all", dc); + + /** + * Creates a criterion which checks that the value of multiple given properties as being not-in to the set of + * values in the subquery result. This form is implicitly using tuple comparisons + * + * @param propertyNames The names of the properties to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see PropertiesSubqueryExpression + */ + public static Criterion propertiesNotIn(String[] propertyNames, DetachedCriteria dc) { + return new PropertiesSubqueryExpression( propertyNames, "not in", dc ); } - - public static Criterion propertyGtSome(String propertyName, DetachedCriteria dc) { - return new PropertySubqueryExpression(propertyName, ">", "some", dc); - } - - public static Criterion propertyLtSome(String propertyName, DetachedCriteria dc) { - return new PropertySubqueryExpression(propertyName, "<", "some", dc); - } - - public static Criterion propertyGeSome(String propertyName, DetachedCriteria dc) { - return new PropertySubqueryExpression(propertyName, ">=", "some", dc); - } - - public static Criterion propertyLeSome(String propertyName, DetachedCriteria dc) { - return new PropertySubqueryExpression(propertyName, "<=", "some", dc); - } - + + /** + * Creates a criterion which checks that the value of a literal equals ALL the values in the + * subquery result. + * + * @param value The literal value to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see SimpleSubqueryExpression + */ public static Criterion eqAll(Object value, DetachedCriteria dc) { - return new SimpleSubqueryExpression(value, "=", "all", dc); + return new SimpleSubqueryExpression( value, "=", "all", dc ); } - + + /** + * Creates a criterion which checks that the value of a literal is greater-than ALL the values in the + * subquery result. + * + * @param value The literal value to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see SimpleSubqueryExpression + */ + public static Criterion gtAll(Object value, DetachedCriteria dc) { + return new SimpleSubqueryExpression( value, ">", "all", dc ); + } + + /** + * Creates a criterion which checks that the value of a literal is less-than ALL the values in the + * subquery result. + * + * @param value The literal value to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see SimpleSubqueryExpression + */ + public static Criterion ltAll(Object value, DetachedCriteria dc) { + return new SimpleSubqueryExpression( value, "<", "all", dc ); + } + + /** + * Creates a criterion which checks that the value of a literal is greater-than-or-equal-to ALL the values in the + * subquery result. + * + * @param value The literal value to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see SimpleSubqueryExpression + */ + public static Criterion geAll(Object value, DetachedCriteria dc) { + return new SimpleSubqueryExpression( value, ">=", "all", dc ); + } + + /** + * Creates a criterion which checks that the value of a literal is less-than-or-equal-to ALL the values in the + * subquery result. + * + * @param value The literal value to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see SimpleSubqueryExpression + */ + public static Criterion leAll(Object value, DetachedCriteria dc) { + return new SimpleSubqueryExpression( value, "<=", "all", dc ); + } + + /** + * Creates a criterion which checks that the value of a literal is greater-than SOME of the values in the + * subquery result. + * + * @param value The literal value to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see SimpleSubqueryExpression + */ + public static Criterion gtSome(Object value, DetachedCriteria dc) { + return new SimpleSubqueryExpression( value, ">", "some", dc ); + } + + /** + * Creates a criterion which checks that the value of a literal is less-than SOME of the values in the + * subquery result. + * + * @param value The literal value to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see SimpleSubqueryExpression + */ + public static Criterion ltSome(Object value, DetachedCriteria dc) { + return new SimpleSubqueryExpression( value, "<", "some", dc ); + } + + /** + * Creates a criterion which checks that the value of a literal is greater-than-or-equal-to SOME of the values + * in the subquery result. + * + * @param value The literal value to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see SimpleSubqueryExpression + */ + public static Criterion geSome(Object value, DetachedCriteria dc) { + return new SimpleSubqueryExpression( value, ">=", "some", dc ); + } + + /** + * Creates a criterion which checks that the value of a literal is less-than-or-equal-to SOME of the values + * in the subquery result. + * + * @param value The literal value to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see SimpleSubqueryExpression + */ + public static Criterion leSome(Object value, DetachedCriteria dc) { + return new SimpleSubqueryExpression( value, "<=", "some", dc ); + } + + /** + * Creates a criterion which checks that the value of a literal is IN the values in the + * subquery result. + * + * @param value The literal value to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see SimpleSubqueryExpression + */ public static Criterion in(Object value, DetachedCriteria dc) { - return new SimpleSubqueryExpression(value, "in", null, dc); + return new SimpleSubqueryExpression( value, "in", null, dc ); } - + + /** + * Creates a criterion which checks that the value of a literal is NOT IN the values in the + * subquery result. + * + * @param value The literal value to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see SimpleSubqueryExpression + */ public static Criterion notIn(Object value, DetachedCriteria dc) { - return new SimpleSubqueryExpression(value, "not in", null, dc); + return new SimpleSubqueryExpression( value, "not in", null, dc ); } - + + /** + * Creates a criterion which checks that the value of a given literal as being equal to the value in + * the subquery result. The implication is that the subquery returns a single result.. + * + * @param value The literal value to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see SimpleSubqueryExpression + */ public static Criterion eq(Object value, DetachedCriteria dc) { - return new SimpleSubqueryExpression(value, "=", null, dc); + return new SimpleSubqueryExpression( value, "=", null, dc ); } - - public static Criterion gt(Object value, DetachedCriteria dc) { - return new SimpleSubqueryExpression(value, ">", null, dc); - } - - public static Criterion lt(Object value, DetachedCriteria dc) { - return new SimpleSubqueryExpression(value, "<", null, dc); - } - - public static Criterion ge(Object value, DetachedCriteria dc) { - return new SimpleSubqueryExpression(value, ">=", null, dc); - } - - public static Criterion le(Object value, DetachedCriteria dc) { - return new SimpleSubqueryExpression(value, "<=", null, dc); - } - + + /** + * Creates a criterion which checks that the value of a given literal as being not-equal to the value in + * the subquery result. The implication is that the subquery returns a single result.. + * + * @param value The literal value to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see SimpleSubqueryExpression + */ public static Criterion ne(Object value, DetachedCriteria dc) { return new SimpleSubqueryExpression(value, "<>", null, dc); } - - public static Criterion gtAll(Object value, DetachedCriteria dc) { - return new SimpleSubqueryExpression(value, ">", "all", dc); - } - - public static Criterion ltAll(Object value, DetachedCriteria dc) { - return new SimpleSubqueryExpression(value, "<", "all", dc); - } - - public static Criterion geAll(Object value, DetachedCriteria dc) { - return new SimpleSubqueryExpression(value, ">=", "all", dc); - } - - public static Criterion leAll(Object value, DetachedCriteria dc) { - return new SimpleSubqueryExpression(value, "<=", "all", dc); - } - - public static Criterion gtSome(Object value, DetachedCriteria dc) { - return new SimpleSubqueryExpression(value, ">", "some", dc); - } - - public static Criterion ltSome(Object value, DetachedCriteria dc) { - return new SimpleSubqueryExpression(value, "<", "some", dc); - } - - public static Criterion geSome(Object value, DetachedCriteria dc) { - return new SimpleSubqueryExpression(value, ">=", "some", dc); - } - - public static Criterion leSome(Object value, DetachedCriteria dc) { - return new SimpleSubqueryExpression(value, "<=", "some", dc); - } - + /** + * Creates a criterion which checks that the value of a given literal as being greater-than the value in + * the subquery result. The implication is that the subquery returns a single result.. + * + * @param value The literal value to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see SimpleSubqueryExpression + */ + public static Criterion gt(Object value, DetachedCriteria dc) { + return new SimpleSubqueryExpression( value, ">", null, dc ); + } + + /** + * Creates a criterion which checks that the value of a given literal as being less-than the value in + * the subquery result. The implication is that the subquery returns a single result.. + * + * @param value The literal value to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see SimpleSubqueryExpression + */ + public static Criterion lt(Object value, DetachedCriteria dc) { + return new SimpleSubqueryExpression( value, "<", null, dc ); + } + + /** + * Creates a criterion which checks that the value of a given literal as being greater-than-or-equal-to the + * value in the subquery result. The implication is that the subquery returns a single result.. + * + * @param value The literal value to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see SimpleSubqueryExpression + */ + public static Criterion ge(Object value, DetachedCriteria dc) { + return new SimpleSubqueryExpression( value, ">=", null, dc ); + } + + /** + * Creates a criterion which checks that the value of a given literal as being less-than-or-equal-to the + * value in the subquery result. The implication is that the subquery returns a single result.. + * + * @param value The literal value to use in comparison + * @param dc The detached criteria representing the subquery + * + * @return The Criterion + * + * @see SimpleSubqueryExpression + */ + public static Criterion le(Object value, DetachedCriteria dc) { + return new SimpleSubqueryExpression( value, "<=", null, dc ); + } + + private Subqueries() { + } } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/SubqueryExpression.java b/hibernate-core/src/main/java/org/hibernate/criterion/SubqueryExpression.java index 5a6615bf3c..8d059532dd 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/SubqueryExpression.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/SubqueryExpression.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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,11 +20,10 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.criterion; + import org.hibernate.Criteria; -import org.hibernate.EntityMode; import org.hibernate.HibernateException; import org.hibernate.engine.spi.QueryParameters; import org.hibernate.engine.spi.SessionFactoryImplementor; @@ -37,10 +36,12 @@ import org.hibernate.persister.entity.OuterJoinLoadable; import org.hibernate.type.Type; /** + * A criterion that involves a subquery + * * @author Gavin King + * @author Steve Ebersole */ public abstract class SubqueryExpression implements Criterion { - private CriteriaImpl criteriaImpl; private String quantifier; private String op; @@ -48,27 +49,36 @@ public abstract class SubqueryExpression implements Criterion { private Type[] types; private CriteriaQueryTranslator innerQuery; - protected Type[] getTypes() { - return types; - } - protected SubqueryExpression(String op, String quantifier, DetachedCriteria dc) { this.criteriaImpl = dc.getCriteriaImpl(); this.quantifier = quantifier; this.op = op; } - + + protected Type[] getTypes() { + return types; + } + protected abstract String toLeftSqlString(Criteria criteria, CriteriaQuery outerQuery); + @Override public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { + final StringBuilder buf = new StringBuilder( toLeftSqlString( criteria, criteriaQuery ) ); + if ( op != null ) { + buf.append( ' ' ).append( op ).append( ' ' ); + } + if ( quantifier != null ) { + buf.append( quantifier ).append( ' ' ); + } + final SessionFactoryImplementor factory = criteriaQuery.getFactory(); final OuterJoinLoadable persister = - ( OuterJoinLoadable ) factory.getEntityPersister( criteriaImpl.getEntityOrClassName() ); + (OuterJoinLoadable) factory.getEntityPersister( criteriaImpl.getEntityOrClassName() ); createAndSetInnerQuery( criteriaQuery, factory ); criteriaImpl.setSession( deriveRootSession( criteria ) ); - CriteriaJoinWalker walker = new CriteriaJoinWalker( + final CriteriaJoinWalker walker = new CriteriaJoinWalker( persister, innerQuery, factory, @@ -78,25 +88,15 @@ public abstract class SubqueryExpression implements Criterion { innerQuery.getRootSQLALias() ); - String sql = walker.getSQLString(); - - final StringBuilder buf = new StringBuilder( toLeftSqlString(criteria, criteriaQuery) ); - if ( op != null ) { - buf.append( ' ' ).append( op ).append( ' ' ); - } - if ( quantifier != null ) { - buf.append( quantifier ).append( ' ' ); - } - return buf.append( '(' ).append( sql ).append( ')' ) - .toString(); + return buf.append( '(' ).append( walker.getSQLString() ).append( ')' ).toString(); } private SessionImplementor deriveRootSession(Criteria criteria) { if ( criteria instanceof CriteriaImpl ) { - return ( ( CriteriaImpl ) criteria ).getSession(); + return ( (CriteriaImpl) criteria ).getSession(); } else if ( criteria instanceof CriteriaImpl.Subcriteria ) { - return deriveRootSession( ( ( CriteriaImpl.Subcriteria ) criteria ).getParent() ); + return deriveRootSession( ( (CriteriaImpl.Subcriteria) criteria ).getParent() ); } else { // could happen for custom Criteria impls. Not likely, but... @@ -105,18 +105,18 @@ public abstract class SubqueryExpression implements Criterion { } } - public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) - throws HibernateException { + @Override + public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { //the following two lines were added to ensure that this.params is not null, which //can happen with two-deep nested subqueries - SessionFactoryImplementor factory = criteriaQuery.getFactory(); - createAndSetInnerQuery(criteriaQuery, factory); - - Type[] ppTypes = params.getPositionalParameterTypes(); - Object[] ppValues = params.getPositionalParameterValues(); - TypedValue[] tv = new TypedValue[ppTypes.length]; + final SessionFactoryImplementor factory = criteriaQuery.getFactory(); + createAndSetInnerQuery( criteriaQuery, factory ); + + final Type[] ppTypes = params.getPositionalParameterTypes(); + final Object[] ppValues = params.getPositionalParameterValues(); + final TypedValue[] tv = new TypedValue[ppTypes.length]; for ( int i=0; i Date: Wed, 24 Apr 2013 13:28:26 -0500 Subject: [PATCH 06/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../internal/PersistentMapElementHolder.java | 2 +- .../internal/PersistentSortedSet.java | 2 +- .../org/hibernate/criterion/InExpression.java | 2 +- .../java/org/hibernate/criterion/Order.java | 2 +- .../criterion/PropertyProjection.java | 2 +- .../dialect/AbstractTransactSQLDialect.java | 153 +++--- .../org/hibernate/dialect/CUBRIDDialect.java | 482 ++++++++++-------- .../org/hibernate/dialect/Cache71Dialect.java | 127 +++-- .../dialect/ColumnAliasExtractor.java | 3 + .../org/hibernate/dialect/DB2390Dialect.java | 18 +- .../org/hibernate/dialect/DB2400Dialect.java | 20 +- .../org/hibernate/dialect/DB2Dialect.java | 109 ++-- .../dialect/DataDirectOracle9Dialect.java | 31 +- .../org/hibernate/dialect/DerbyDialect.java | 77 +-- .../dialect/DerbyTenFiveDialect.java | 4 + .../dialect/DerbyTenSevenDialect.java | 21 +- .../hibernate/dialect/DerbyTenSixDialect.java | 3 + .../java/org/hibernate/dialect/Dialect.java | 422 ++++++++++----- .../hibernate/dialect/FirebirdDialect.java | 7 +- .../hibernate/dialect/FrontBaseDialect.java | 19 +- .../java/org/hibernate/dialect/H2Dialect.java | 80 ++- .../org/hibernate/dialect/HSQLDialect.java | 248 ++++----- .../hibernate/dialect/InformixDialect.java | 157 +++--- .../hibernate/dialect/Ingres10Dialect.java | 71 +-- .../org/hibernate/dialect/Ingres9Dialect.java | 170 ++---- .../org/hibernate/dialect/IngresDialect.java | 171 +++---- .../hibernate/dialect/InterbaseDialect.java | 30 +- .../hibernate/dialect/JDataStoreDialect.java | 16 +- .../org/hibernate/dialect/MckoiDialect.java | 15 +- .../org/hibernate/dialect/MySQL5Dialect.java | 11 +- .../dialect/MySQL5InnoDBDialect.java | 14 +- .../org/hibernate/dialect/MySQLDialect.java | 292 ++++++----- .../hibernate/dialect/MySQLInnoDBDialect.java | 10 +- .../hibernate/dialect/MySQLMyISAMDialect.java | 7 +- .../hibernate/dialect/Oracle10gDialect.java | 14 +- .../hibernate/dialect/Oracle8iDialect.java | 119 ++--- .../org/hibernate/dialect/Oracle9Dialect.java | 244 +++++---- .../hibernate/dialect/Oracle9iDialect.java | 31 +- .../org/hibernate/dialect/OracleDialect.java | 37 +- .../hibernate/dialect/OracleTypesHelper.java | 128 +++++ .../hibernate/dialect/PointbaseDialect.java | 16 +- .../dialect/PostgreSQL81Dialect.java | 143 ++++-- .../dialect/PostgreSQL82Dialect.java | 6 +- .../hibernate/dialect/PostgreSQLDialect.java | 2 +- .../dialect/PostgresPlusDialect.java | 12 +- .../hibernate/dialect/ProgressDialect.java | 7 + .../hibernate/dialect/RDMSOS2200Dialect.java | 347 +++++++------ .../ResultColumnReferenceStrategy.java | 59 +-- .../org/hibernate/dialect/SAPDBDialect.java | 168 +++--- .../dialect/SQLServer2005Dialect.java | 20 +- .../dialect/SQLServer2008Dialect.java | 4 + .../hibernate/dialect/SQLServerDialect.java | 85 +-- .../hibernate/dialect/Sybase11Dialect.java | 7 + .../dialect/SybaseASE157Dialect.java | 21 +- .../hibernate/dialect/SybaseASE15Dialect.java | 27 +- .../dialect/SybaseAnywhereDialect.java | 10 +- .../org/hibernate/dialect/SybaseDialect.java | 4 - .../hibernate/dialect/TeradataDialect.java | 64 +-- .../hibernate/dialect/TimesTenDialect.java | 124 +++-- .../java/org/hibernate/dialect/TypeNames.java | 113 ++-- .../AbstractAnsiTrimEmulationFunction.java | 34 +- .../function/AnsiTrimEmulationFunction.java | 44 +- .../dialect/function/AnsiTrimFunction.java | 16 +- .../function/AvgWithArgumentCastFunction.java | 6 + .../dialect/function/CastFunction.java | 27 +- .../dialect/function/CharIndexFunction.java | 27 +- .../dialect/function/ClassicAvgFunction.java | 15 +- .../function/ClassicCountFunction.java | 8 +- .../dialect/function/ClassicSumFunction.java | 8 +- .../ConditionalParenthesisFunction.java | 27 +- .../dialect/function/ConvertFunction.java | 8 +- .../dialect/function/DerbyConcatFunction.java | 62 ++- .../dialect/function/NoArgSQLFunction.java | 60 ++- .../dialect/function/NvlFunction.java | 19 +- .../function/PositionSubstringFunction.java | 35 +- .../dialect/function/SQLFunction.java | 2 +- .../dialect/function/SQLFunctionRegistry.java | 32 +- .../dialect/function/SQLFunctionTemplate.java | 46 +- .../StandardAnsiSqlAggregationFunctions.java | 87 +++- .../function/StandardJDBCEscapeFunction.java | 12 +- .../dialect/function/StandardSQLFunction.java | 20 +- .../dialect/function/TemplateRenderer.java | 31 +- .../function/TrimFunctionTemplate.java | 26 +- .../dialect/function/VarArgsSQLFunction.java | 22 +- .../lock/AbstractSelectLockingStrategy.java | 5 +- .../dialect/lock/LockingStrategy.java | 3 +- .../lock/LockingStrategyException.java | 17 +- .../lock/OptimisticEntityLockException.java | 17 +- ...timisticForceIncrementLockingStrategy.java | 10 +- .../lock/OptimisticLockingStrategy.java | 9 +- .../lock/PessimisticEntityLockException.java | 11 +- ...simisticForceIncrementLockingStrategy.java | 6 +- .../PessimisticReadSelectLockingStrategy.java | 14 +- .../PessimisticReadUpdateLockingStrategy.java | 19 +- ...PessimisticWriteSelectLockingStrategy.java | 14 +- ...PessimisticWriteUpdateLockingStrategy.java | 19 +- .../dialect/lock/SelectLockingStrategy.java | 26 +- .../dialect/lock/UpdateLockingStrategy.java | 30 +- .../hibernate/dialect/lock/package-info.java | 4 + .../pagination/AbstractLimitHandler.java | 14 +- .../pagination/CUBRIDLimitHandler.java | 46 +- .../pagination/LegacyLimitHandler.java | 40 ++ .../dialect/pagination/LimitHandler.java | 25 +- .../dialect/pagination/LimitHelper.java | 61 ++- .../dialect/pagination/NoopLimitHandler.java | 33 ++ .../pagination/SQLServer2005LimitHandler.java | 63 ++- .../dialect/pagination/package-info.java | 4 + .../dialect/unique/DB2UniqueDelegate.java | 87 ++-- .../dialect/unique/DefaultUniqueDelegate.java | 152 +++--- .../dialect/unique/UniqueDelegate.java | 206 ++++---- .../dialect/unique/package-info.java | 4 + ...andardDatabaseMetaDataDialectResolver.java | 2 +- ...stractDatabaseMetaDataDialectResolver.java | 1 - .../spi}/BasicSQLExceptionConverter.java | 16 +- .../java/org/hibernate/mapping/Table.java | 6 +- .../java/org/hibernate/mapping/UniqueKey.java | 10 +- .../hibernate/metamodel/relational/Table.java | 4 +- .../metamodel/relational/UniqueKey.java | 4 +- 118 files changed, 3687 insertions(+), 2579 deletions(-) create mode 100644 hibernate-core/src/main/java/org/hibernate/dialect/OracleTypesHelper.java create mode 100644 hibernate-core/src/main/java/org/hibernate/dialect/lock/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/dialect/pagination/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/dialect/unique/package-info.java rename hibernate-core/src/main/java/org/hibernate/{dialect/resolver => engine/jdbc/dialect/spi}/BasicSQLExceptionConverter.java (90%) diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentMapElementHolder.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentMapElementHolder.java index d532ae3485..83d8076c99 100755 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentMapElementHolder.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentMapElementHolder.java @@ -101,7 +101,7 @@ public class PersistentMapElementHolder extends PersistentIndexedElementHolder { final Serializable[] result = new Serializable[length*2]; int i = 0; while ( i < length*2 ) { - final Element elem = (Element) elements.get(i/2); + final Element elem = (Element) elements.get( i/2 ); final Object object = elementType.fromXMLNode( elem, persister.getFactory() ); final String indexString = getIndex( elem, indexNodeName, i ); final Object index = ( (XmlRepresentableType) indexType ).fromXMLString( indexString, persister.getFactory() ); diff --git a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentSortedSet.java b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentSortedSet.java index 3e07821b2d..286dd59857 100644 --- a/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentSortedSet.java +++ b/hibernate-core/src/main/java/org/hibernate/collection/internal/PersistentSortedSet.java @@ -102,7 +102,7 @@ public class PersistentSortedSet extends PersistentSet implements SortedSet { @SuppressWarnings("unchecked") public SortedSet headSet(Object toElement) { read(); - final SortedSet headSet = ( (SortedSet) set ).headSet(toElement); + final SortedSet headSet = ( (SortedSet) set ).headSet( toElement ); return new SubSetProxy( headSet ); } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/InExpression.java b/hibernate-core/src/main/java/org/hibernate/criterion/InExpression.java index c7bd8a45db..24f5b11f00 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/InExpression.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/InExpression.java @@ -109,7 +109,7 @@ public class InExpression implements Criterion { @Override public String toString() { - return propertyName + " in (" + StringHelper.toString(values) + ')'; + return propertyName + " in (" + StringHelper.toString( values ) + ')'; } } diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/Order.java b/hibernate-core/src/main/java/org/hibernate/criterion/Order.java index c7feea418c..dd3adccccb 100644 --- a/hibernate-core/src/main/java/org/hibernate/criterion/Order.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/Order.java @@ -132,7 +132,7 @@ public class Order implements Serializable { final StringBuilder expression = new StringBuilder(); boolean lower = false; if ( ignoreCase ) { - int sqlType = sqlTypes[i]; + final int sqlType = sqlTypes[i]; lower = sqlType == Types.VARCHAR || sqlType == Types.CHAR || sqlType == Types.LONGVARCHAR; diff --git a/hibernate-core/src/main/java/org/hibernate/criterion/PropertyProjection.java b/hibernate-core/src/main/java/org/hibernate/criterion/PropertyProjection.java index 44832d7928..46c1b28916 100755 --- a/hibernate-core/src/main/java/org/hibernate/criterion/PropertyProjection.java +++ b/hibernate-core/src/main/java/org/hibernate/criterion/PropertyProjection.java @@ -44,7 +44,7 @@ public class PropertyProjection extends SimpleProjection { } protected PropertyProjection(String prop) { - this(prop, false); + this( prop, false ); } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/AbstractTransactSQLDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/AbstractTransactSQLDialect.java index 2e3a6f199f..915c492f43 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/AbstractTransactSQLDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/AbstractTransactSQLDialect.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -47,7 +48,7 @@ import org.hibernate.type.StandardBasicTypes; abstract class AbstractTransactSQLDialect extends Dialect { public AbstractTransactSQLDialect() { super(); - registerColumnType( Types.BINARY, "binary($l)" ); + registerColumnType( Types.BINARY, "binary($l)" ); registerColumnType( Types.BIT, "tinyint" ); registerColumnType( Types.BIGINT, "numeric(19,0)" ); registerColumnType( Types.SMALLINT, "smallint" ); @@ -65,94 +66,108 @@ abstract class AbstractTransactSQLDialect extends Dialect { registerColumnType( Types.BLOB, "image" ); registerColumnType( Types.CLOB, "text" ); - registerFunction( "ascii", new StandardSQLFunction("ascii", StandardBasicTypes.INTEGER) ); - registerFunction( "char", new StandardSQLFunction("char", StandardBasicTypes.CHARACTER) ); - registerFunction( "len", new StandardSQLFunction("len", StandardBasicTypes.LONG) ); - registerFunction( "lower", new StandardSQLFunction("lower") ); - registerFunction( "upper", new StandardSQLFunction("upper") ); - registerFunction( "str", new StandardSQLFunction("str", StandardBasicTypes.STRING) ); - registerFunction( "ltrim", new StandardSQLFunction("ltrim") ); - registerFunction( "rtrim", new StandardSQLFunction("rtrim") ); - registerFunction( "reverse", new StandardSQLFunction("reverse") ); - registerFunction( "space", new StandardSQLFunction("space", StandardBasicTypes.STRING) ); + registerFunction( "ascii", new StandardSQLFunction( "ascii", StandardBasicTypes.INTEGER ) ); + registerFunction( "char", new StandardSQLFunction( "char", StandardBasicTypes.CHARACTER ) ); + registerFunction( "len", new StandardSQLFunction( "len", StandardBasicTypes.LONG ) ); + registerFunction( "lower", new StandardSQLFunction( "lower" ) ); + registerFunction( "upper", new StandardSQLFunction( "upper" ) ); + registerFunction( "str", new StandardSQLFunction( "str", StandardBasicTypes.STRING ) ); + registerFunction( "ltrim", new StandardSQLFunction( "ltrim" ) ); + registerFunction( "rtrim", new StandardSQLFunction( "rtrim" ) ); + registerFunction( "reverse", new StandardSQLFunction( "reverse" ) ); + registerFunction( "space", new StandardSQLFunction( "space", StandardBasicTypes.STRING ) ); - registerFunction( "user", new NoArgSQLFunction("user", StandardBasicTypes.STRING) ); + registerFunction( "user", new NoArgSQLFunction( "user", StandardBasicTypes.STRING ) ); - registerFunction( "current_timestamp", new NoArgSQLFunction("getdate", StandardBasicTypes.TIMESTAMP) ); - registerFunction( "current_time", new NoArgSQLFunction("getdate", StandardBasicTypes.TIME) ); - registerFunction( "current_date", new NoArgSQLFunction("getdate", StandardBasicTypes.DATE) ); + registerFunction( "current_timestamp", new NoArgSQLFunction( "getdate", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( "current_time", new NoArgSQLFunction( "getdate", StandardBasicTypes.TIME ) ); + registerFunction( "current_date", new NoArgSQLFunction( "getdate", StandardBasicTypes.DATE ) ); - registerFunction( "getdate", new NoArgSQLFunction("getdate", StandardBasicTypes.TIMESTAMP) ); - registerFunction( "getutcdate", new NoArgSQLFunction("getutcdate", StandardBasicTypes.TIMESTAMP) ); - registerFunction( "day", new StandardSQLFunction("day", StandardBasicTypes.INTEGER) ); - registerFunction( "month", new StandardSQLFunction("month", StandardBasicTypes.INTEGER) ); - registerFunction( "year", new StandardSQLFunction("year", StandardBasicTypes.INTEGER) ); - registerFunction( "datename", new StandardSQLFunction("datename", StandardBasicTypes.STRING) ); + registerFunction( "getdate", new NoArgSQLFunction( "getdate", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( "getutcdate", new NoArgSQLFunction( "getutcdate", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( "day", new StandardSQLFunction( "day", StandardBasicTypes.INTEGER ) ); + registerFunction( "month", new StandardSQLFunction( "month", StandardBasicTypes.INTEGER ) ); + registerFunction( "year", new StandardSQLFunction( "year", StandardBasicTypes.INTEGER ) ); + registerFunction( "datename", new StandardSQLFunction( "datename", StandardBasicTypes.STRING ) ); - registerFunction( "abs", new StandardSQLFunction("abs") ); - registerFunction( "sign", new StandardSQLFunction("sign", StandardBasicTypes.INTEGER) ); + registerFunction( "abs", new StandardSQLFunction( "abs" ) ); + registerFunction( "sign", new StandardSQLFunction( "sign", StandardBasicTypes.INTEGER ) ); - registerFunction( "acos", new StandardSQLFunction("acos", StandardBasicTypes.DOUBLE) ); - registerFunction( "asin", new StandardSQLFunction("asin", StandardBasicTypes.DOUBLE) ); - registerFunction( "atan", new StandardSQLFunction("atan", StandardBasicTypes.DOUBLE) ); - registerFunction( "cos", new StandardSQLFunction("cos", StandardBasicTypes.DOUBLE) ); - registerFunction( "cot", new StandardSQLFunction("cot", StandardBasicTypes.DOUBLE) ); - registerFunction( "exp", new StandardSQLFunction("exp", StandardBasicTypes.DOUBLE) ); - registerFunction( "log", new StandardSQLFunction( "log", StandardBasicTypes.DOUBLE) ); - registerFunction( "log10", new StandardSQLFunction("log10", StandardBasicTypes.DOUBLE) ); - registerFunction( "sin", new StandardSQLFunction("sin", StandardBasicTypes.DOUBLE) ); - registerFunction( "sqrt", new StandardSQLFunction("sqrt", StandardBasicTypes.DOUBLE) ); - registerFunction( "tan", new StandardSQLFunction("tan", StandardBasicTypes.DOUBLE) ); - registerFunction( "pi", new NoArgSQLFunction("pi", StandardBasicTypes.DOUBLE) ); - registerFunction( "square", new StandardSQLFunction("square") ); - registerFunction( "rand", new StandardSQLFunction("rand", StandardBasicTypes.FLOAT) ); + registerFunction( "acos", new StandardSQLFunction( "acos", StandardBasicTypes.DOUBLE ) ); + registerFunction( "asin", new StandardSQLFunction( "asin", StandardBasicTypes.DOUBLE ) ); + registerFunction( "atan", new StandardSQLFunction( "atan", StandardBasicTypes.DOUBLE ) ); + registerFunction( "cos", new StandardSQLFunction( "cos", StandardBasicTypes.DOUBLE ) ); + registerFunction( "cot", new StandardSQLFunction( "cot", StandardBasicTypes.DOUBLE ) ); + registerFunction( "exp", new StandardSQLFunction( "exp", StandardBasicTypes.DOUBLE ) ); + registerFunction( "log", new StandardSQLFunction( "log", StandardBasicTypes.DOUBLE ) ); + registerFunction( "log10", new StandardSQLFunction( "log10", StandardBasicTypes.DOUBLE ) ); + registerFunction( "sin", new StandardSQLFunction( "sin", StandardBasicTypes.DOUBLE ) ); + registerFunction( "sqrt", new StandardSQLFunction( "sqrt", StandardBasicTypes.DOUBLE ) ); + registerFunction( "tan", new StandardSQLFunction( "tan", StandardBasicTypes.DOUBLE ) ); + registerFunction( "pi", new NoArgSQLFunction( "pi", StandardBasicTypes.DOUBLE ) ); + registerFunction( "square", new StandardSQLFunction( "square" ) ); + registerFunction( "rand", new StandardSQLFunction( "rand", StandardBasicTypes.FLOAT ) ); - registerFunction("radians", new StandardSQLFunction("radians", StandardBasicTypes.DOUBLE) ); - registerFunction("degrees", new StandardSQLFunction("degrees", StandardBasicTypes.DOUBLE) ); + registerFunction( "radians", new StandardSQLFunction( "radians", StandardBasicTypes.DOUBLE ) ); + registerFunction( "degrees", new StandardSQLFunction( "degrees", StandardBasicTypes.DOUBLE ) ); - registerFunction( "round", new StandardSQLFunction("round") ); - registerFunction( "ceiling", new StandardSQLFunction("ceiling") ); - registerFunction( "floor", new StandardSQLFunction("floor") ); + registerFunction( "round", new StandardSQLFunction( "round" ) ); + registerFunction( "ceiling", new StandardSQLFunction( "ceiling" ) ); + registerFunction( "floor", new StandardSQLFunction( "floor" ) ); - registerFunction( "isnull", new StandardSQLFunction("isnull") ); + registerFunction( "isnull", new StandardSQLFunction( "isnull" ) ); - registerFunction( "concat", new VarArgsSQLFunction( StandardBasicTypes.STRING, "(","+",")" ) ); + registerFunction( "concat", new VarArgsSQLFunction( StandardBasicTypes.STRING, "(", "+", ")" ) ); registerFunction( "length", new StandardSQLFunction( "len", StandardBasicTypes.INTEGER ) ); - registerFunction( "trim", new SQLFunctionTemplate( StandardBasicTypes.STRING, "ltrim(rtrim(?1))") ); + registerFunction( "trim", new SQLFunctionTemplate( StandardBasicTypes.STRING, "ltrim(rtrim(?1))" ) ); registerFunction( "locate", new CharIndexFunction() ); - getDefaultProperties().setProperty(Environment.STATEMENT_BATCH_SIZE, NO_BATCH); + getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, NO_BATCH ); } + @Override public String getAddColumnString() { return "add"; } + + @Override public String getNullColumnString() { return ""; } + + @Override public boolean qualifyIndexName() { return false; } + @Override public String getForUpdateString() { return ""; } + @Override public boolean supportsIdentityColumns() { return true; } + + @Override public String getIdentitySelectString() { return "select @@identity"; } + + @Override public String getIdentityColumnString() { - return "identity not null"; //starts with 1, implicitly + //starts with 1, implicitly + return "identity not null"; } + @Override public boolean supportsInsertSelectIdentity() { return true; } + @Override public String appendIdentitySelectToInsert(String insertSQL) { return insertSQL + "\nselect @@identity"; } @@ -162,17 +177,19 @@ abstract class AbstractTransactSQLDialect extends Dialect { return lockOptions.getLockMode().greaterThan( LockMode.READ ) ? tableName + " holdlock" : tableName; } + @Override public String applyLocksToSql(String sql, LockOptions aliasedLockOptions, Map keyColumnNames) { // TODO: merge additional lockoptions support in Dialect.applyLocksToSql - Iterator itr = aliasedLockOptions.getAliasLockIterator(); - StringBuilder buffer = new StringBuilder( sql ); + final Iterator itr = aliasedLockOptions.getAliasLockIterator(); + final StringBuilder buffer = new StringBuilder( sql ); int correction = 0; while ( itr.hasNext() ) { - final Map.Entry entry = ( Map.Entry ) itr.next(); - final LockMode lockMode = ( LockMode ) entry.getValue(); + final Map.Entry entry = (Map.Entry) itr.next(); + final LockMode lockMode = (LockMode) entry.getValue(); if ( lockMode.greaterThan( LockMode.READ ) ) { - final String alias = ( String ) entry.getKey(); - int start = -1, end = -1; + final String alias = (String) entry.getKey(); + int start = -1; + int end = -1; if ( sql.endsWith( " " + alias ) ) { start = ( sql.length() - alias.length() ) + correction; end = start + alias.length(); @@ -198,69 +215,89 @@ abstract class AbstractTransactSQLDialect extends Dialect { return buffer.toString(); } + @Override public int registerResultSetOutParameter(CallableStatement statement, int col) throws SQLException { - return col; // sql server just returns automatically + // sql server just returns automatically + return col; } + @Override public ResultSet getResultSet(CallableStatement ps) throws SQLException { boolean isResultSet = ps.execute(); -// This assumes you will want to ignore any update counts + // This assumes you will want to ignore any update counts while ( !isResultSet && ps.getUpdateCount() != -1 ) { isResultSet = ps.getMoreResults(); } -// You may still have other ResultSets or update counts left to process here -// but you can't do it now or the ResultSet you just got will be closed + + // You may still have other ResultSets or update counts left to process here + // but you can't do it now or the ResultSet you just got will be closed return ps.getResultSet(); } + @Override public boolean supportsCurrentTimestampSelection() { return true; } + @Override public boolean isCurrentTimestampSelectStringCallable() { return false; } + @Override public String getCurrentTimestampSelectString() { return "select getdate()"; } + @Override public boolean supportsTemporaryTables() { return true; } + @Override public String generateTemporaryTableName(String baseTableName) { return "#" + baseTableName; } + @Override public boolean dropTemporaryTableAfterUse() { - return true; // sql-server, at least needed this dropped after use; strange! + // sql-server, at least needed this dropped after use; strange! + return true; } + + @Override public String getSelectGUIDString() { return "select newid()"; } // Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + @Override public boolean supportsEmptyInList() { return false; } + @Override public boolean supportsUnionAll() { return true; } + @Override public boolean supportsExistsInSelect() { return false; } + @Override public boolean doesReadCommittedCauseWritersToBlockReaders() { return true; } + @Override public boolean doesRepeatableReadCauseReadersToBlockWriters() { return true; } + + @Override public boolean supportsTupleDistinctCounts() { return false; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/CUBRIDDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/CUBRIDDialect.java index 85aacdef71..a213582ca8 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/CUBRIDDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/CUBRIDDialect.java @@ -21,18 +21,16 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ - package org.hibernate.dialect; import java.sql.Types; -import org.hibernate.MappingException; import org.hibernate.cfg.Environment; import org.hibernate.dialect.function.NoArgSQLFunction; import org.hibernate.dialect.function.StandardSQLFunction; import org.hibernate.dialect.function.VarArgsSQLFunction; -import org.hibernate.dialect.pagination.LimitHandler; import org.hibernate.dialect.pagination.CUBRIDLimitHandler; +import org.hibernate.dialect.pagination.LimitHandler; import org.hibernate.engine.spi.RowSelection; import org.hibernate.type.StandardBasicTypes; @@ -42,13 +40,16 @@ import org.hibernate.type.StandardBasicTypes; * @author Seok Jeong Il */ public class CUBRIDDialect extends Dialect { - public CUBRIDDialect() { - super(); + /** + * Constructs a CUBRIDDialect + */ + public CUBRIDDialect() { + super(); registerColumnType( Types.BIGINT, "bigint" ); - registerColumnType( Types.BIT, "bit(8)" ); - registerColumnType( Types.BLOB, "bit varying(65535)" ); - registerColumnType( Types.BOOLEAN, "bit(8)"); + registerColumnType( Types.BIT, "bit(8)" ); + registerColumnType( Types.BLOB, "bit varying(65535)" ); + registerColumnType( Types.BOOLEAN, "bit(8)" ); registerColumnType( Types.CHAR, "char(1)" ); registerColumnType( Types.CLOB, "string" ); registerColumnType( Types.DATE, "date" ); @@ -57,289 +58,324 @@ public class CUBRIDDialect extends Dialect { registerColumnType( Types.FLOAT, "float" ); registerColumnType( Types.INTEGER, "int" ); registerColumnType( Types.NUMERIC, "numeric($p,$s)" ); - registerColumnType( Types.REAL, "double" ); - registerColumnType( Types.SMALLINT, "short" ); - registerColumnType( Types.TIME, "time" ); - registerColumnType( Types.TIMESTAMP, "timestamp" ); - registerColumnType( Types.TINYINT, "short" ); + registerColumnType( Types.REAL, "double" ); + registerColumnType( Types.SMALLINT, "short" ); + registerColumnType( Types.TIME, "time" ); + registerColumnType( Types.TIMESTAMP, "timestamp" ); + registerColumnType( Types.TINYINT, "short" ); registerColumnType( Types.VARBINARY, 2000, "bit varying($l)" ); - registerColumnType( Types.VARCHAR, "string" ); - registerColumnType( Types.VARCHAR, 2000, "varchar($l)" ); - registerColumnType( Types.VARCHAR, 255, "varchar($l)" ); + registerColumnType( Types.VARCHAR, "string" ); + registerColumnType( Types.VARCHAR, 2000, "varchar($l)" ); + registerColumnType( Types.VARCHAR, 255, "varchar($l)" ); - getDefaultProperties().setProperty(Environment.USE_STREAMS_FOR_BINARY, "true"); - getDefaultProperties().setProperty(Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE); + getDefaultProperties().setProperty( Environment.USE_STREAMS_FOR_BINARY, "true" ); + getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE ); - registerFunction("ascii", new StandardSQLFunction("ascii", StandardBasicTypes.INTEGER) ); - registerFunction("bin", new StandardSQLFunction("bin", StandardBasicTypes.STRING) ); - registerFunction("char_length", new StandardSQLFunction("char_length", StandardBasicTypes.LONG) ); - registerFunction("character_length", new StandardSQLFunction("character_length", StandardBasicTypes.LONG) ); - registerFunction("lengthb", new StandardSQLFunction("lengthb", StandardBasicTypes.LONG) ); - registerFunction("lengthh", new StandardSQLFunction("lengthh", StandardBasicTypes.LONG) ); - registerFunction("lcase", new StandardSQLFunction("lcase") ); - registerFunction("lower", new StandardSQLFunction("lower") ); - registerFunction("ltrim", new StandardSQLFunction("ltrim") ); - registerFunction("reverse", new StandardSQLFunction("reverse") ); - registerFunction("rtrim", new StandardSQLFunction("rtrim") ); - registerFunction("trim", new StandardSQLFunction("trim") ); - registerFunction("space", new StandardSQLFunction("space", StandardBasicTypes.STRING) ); - registerFunction("ucase", new StandardSQLFunction("ucase") ); - registerFunction("upper", new StandardSQLFunction("upper") ); + registerFunction( "ascii", new StandardSQLFunction( "ascii", StandardBasicTypes.INTEGER ) ); + registerFunction( "bin", new StandardSQLFunction( "bin", StandardBasicTypes.STRING ) ); + registerFunction( "char_length", new StandardSQLFunction( "char_length", StandardBasicTypes.LONG ) ); + registerFunction( "character_length", new StandardSQLFunction( "character_length", StandardBasicTypes.LONG ) ); + registerFunction( "lengthb", new StandardSQLFunction( "lengthb", StandardBasicTypes.LONG ) ); + registerFunction( "lengthh", new StandardSQLFunction( "lengthh", StandardBasicTypes.LONG ) ); + registerFunction( "lcase", new StandardSQLFunction( "lcase" ) ); + registerFunction( "lower", new StandardSQLFunction( "lower" ) ); + registerFunction( "ltrim", new StandardSQLFunction( "ltrim" ) ); + registerFunction( "reverse", new StandardSQLFunction( "reverse" ) ); + registerFunction( "rtrim", new StandardSQLFunction( "rtrim" ) ); + registerFunction( "trim", new StandardSQLFunction( "trim" ) ); + registerFunction( "space", new StandardSQLFunction( "space", StandardBasicTypes.STRING ) ); + registerFunction( "ucase", new StandardSQLFunction( "ucase" ) ); + registerFunction( "upper", new StandardSQLFunction( "upper" ) ); - registerFunction("abs", new StandardSQLFunction("abs") ); - registerFunction("sign", new StandardSQLFunction("sign", StandardBasicTypes.INTEGER) ); + registerFunction( "abs", new StandardSQLFunction( "abs" ) ); + registerFunction( "sign", new StandardSQLFunction( "sign", StandardBasicTypes.INTEGER ) ); - registerFunction("acos", new StandardSQLFunction("acos", StandardBasicTypes.DOUBLE) ); - registerFunction("asin", new StandardSQLFunction("asin", StandardBasicTypes.DOUBLE) ); - registerFunction("atan", new StandardSQLFunction("atan", StandardBasicTypes.DOUBLE) ); - registerFunction("cos", new StandardSQLFunction("cos", StandardBasicTypes.DOUBLE) ); - registerFunction("cot", new StandardSQLFunction("cot", StandardBasicTypes.DOUBLE) ); - registerFunction("exp", new StandardSQLFunction("exp", StandardBasicTypes.DOUBLE) ); - registerFunction("ln", new StandardSQLFunction("ln", StandardBasicTypes.DOUBLE) ); - registerFunction("log2", new StandardSQLFunction("log2", StandardBasicTypes.DOUBLE) ); - registerFunction("log10", new StandardSQLFunction("log10", StandardBasicTypes.DOUBLE) ); - registerFunction("pi", new NoArgSQLFunction("pi", StandardBasicTypes.DOUBLE) ); - registerFunction("rand", new NoArgSQLFunction("rand", StandardBasicTypes.DOUBLE) ); - registerFunction("random", new NoArgSQLFunction("random", StandardBasicTypes.DOUBLE) ); - registerFunction("sin", new StandardSQLFunction("sin", StandardBasicTypes.DOUBLE) ); - registerFunction("sqrt", new StandardSQLFunction("sqrt", StandardBasicTypes.DOUBLE) ); - registerFunction("tan", new StandardSQLFunction("tan", StandardBasicTypes.DOUBLE) ); + registerFunction( "acos", new StandardSQLFunction( "acos", StandardBasicTypes.DOUBLE ) ); + registerFunction( "asin", new StandardSQLFunction( "asin", StandardBasicTypes.DOUBLE ) ); + registerFunction( "atan", new StandardSQLFunction( "atan", StandardBasicTypes.DOUBLE ) ); + registerFunction( "cos", new StandardSQLFunction( "cos", StandardBasicTypes.DOUBLE ) ); + registerFunction( "cot", new StandardSQLFunction( "cot", StandardBasicTypes.DOUBLE ) ); + registerFunction( "exp", new StandardSQLFunction( "exp", StandardBasicTypes.DOUBLE ) ); + registerFunction( "ln", new StandardSQLFunction( "ln", StandardBasicTypes.DOUBLE ) ); + registerFunction( "log2", new StandardSQLFunction( "log2", StandardBasicTypes.DOUBLE ) ); + registerFunction( "log10", new StandardSQLFunction( "log10", StandardBasicTypes.DOUBLE ) ); + registerFunction( "pi", new NoArgSQLFunction( "pi", StandardBasicTypes.DOUBLE ) ); + registerFunction( "rand", new NoArgSQLFunction( "rand", StandardBasicTypes.DOUBLE ) ); + registerFunction( "random", new NoArgSQLFunction( "random", StandardBasicTypes.DOUBLE ) ); + registerFunction( "sin", new StandardSQLFunction( "sin", StandardBasicTypes.DOUBLE ) ); + registerFunction( "sqrt", new StandardSQLFunction( "sqrt", StandardBasicTypes.DOUBLE ) ); + registerFunction( "tan", new StandardSQLFunction( "tan", StandardBasicTypes.DOUBLE ) ); - registerFunction("radians", new StandardSQLFunction("radians", StandardBasicTypes.DOUBLE) ); - registerFunction("degrees", new StandardSQLFunction("degrees", StandardBasicTypes.DOUBLE) ); + registerFunction( "radians", new StandardSQLFunction( "radians", StandardBasicTypes.DOUBLE ) ); + registerFunction( "degrees", new StandardSQLFunction( "degrees", StandardBasicTypes.DOUBLE ) ); - registerFunction("ceil", new StandardSQLFunction("ceil", StandardBasicTypes.INTEGER) ); - registerFunction("floor", new StandardSQLFunction("floor", StandardBasicTypes.INTEGER) ); - registerFunction("round", new StandardSQLFunction("round") ); + registerFunction( "ceil", new StandardSQLFunction( "ceil", StandardBasicTypes.INTEGER ) ); + registerFunction( "floor", new StandardSQLFunction( "floor", StandardBasicTypes.INTEGER ) ); + registerFunction( "round", new StandardSQLFunction( "round" ) ); - registerFunction("datediff", new StandardSQLFunction("datediff", StandardBasicTypes.INTEGER) ); - registerFunction("timediff", new StandardSQLFunction("timediff", StandardBasicTypes.TIME) ); + registerFunction( "datediff", new StandardSQLFunction( "datediff", StandardBasicTypes.INTEGER ) ); + registerFunction( "timediff", new StandardSQLFunction( "timediff", StandardBasicTypes.TIME ) ); - registerFunction("date", new StandardSQLFunction("date", StandardBasicTypes.DATE) ); - registerFunction("curdate", new NoArgSQLFunction("curdate", StandardBasicTypes.DATE) ); - registerFunction("current_date", new NoArgSQLFunction("current_date", StandardBasicTypes.DATE, false) ); - registerFunction("sys_date", new NoArgSQLFunction("sys_date", StandardBasicTypes.DATE, false) ); - registerFunction("sysdate", new NoArgSQLFunction("sysdate", StandardBasicTypes.DATE, false) ); + registerFunction( "date", new StandardSQLFunction( "date", StandardBasicTypes.DATE ) ); + registerFunction( "curdate", new NoArgSQLFunction( "curdate", StandardBasicTypes.DATE ) ); + registerFunction( "current_date", new NoArgSQLFunction( "current_date", StandardBasicTypes.DATE, false ) ); + registerFunction( "sys_date", new NoArgSQLFunction( "sys_date", StandardBasicTypes.DATE, false ) ); + registerFunction( "sysdate", new NoArgSQLFunction( "sysdate", StandardBasicTypes.DATE, false ) ); - registerFunction("time", new StandardSQLFunction("time", StandardBasicTypes.TIME) ); - registerFunction("curtime", new NoArgSQLFunction("curtime", StandardBasicTypes.TIME) ); - registerFunction("current_time", new NoArgSQLFunction("current_time", StandardBasicTypes.TIME, false) ); - registerFunction("sys_time", new NoArgSQLFunction("sys_time", StandardBasicTypes.TIME, false) ); - registerFunction("systime", new NoArgSQLFunction("systime", StandardBasicTypes.TIME, false) ); + registerFunction( "time", new StandardSQLFunction( "time", StandardBasicTypes.TIME ) ); + registerFunction( "curtime", new NoArgSQLFunction( "curtime", StandardBasicTypes.TIME ) ); + registerFunction( "current_time", new NoArgSQLFunction( "current_time", StandardBasicTypes.TIME, false ) ); + registerFunction( "sys_time", new NoArgSQLFunction( "sys_time", StandardBasicTypes.TIME, false ) ); + registerFunction( "systime", new NoArgSQLFunction( "systime", StandardBasicTypes.TIME, false ) ); - registerFunction("timestamp", new StandardSQLFunction("timestamp", StandardBasicTypes.TIMESTAMP) ); - registerFunction("current_timestamp", new NoArgSQLFunction("current_timestamp", StandardBasicTypes.TIMESTAMP, false) ); - registerFunction("sys_timestamp", new NoArgSQLFunction("sys_timestamp", StandardBasicTypes.TIMESTAMP, false) ); - registerFunction("systimestamp", new NoArgSQLFunction("systimestamp", StandardBasicTypes.TIMESTAMP, false) ); - registerFunction("localtime", new NoArgSQLFunction("localtime", StandardBasicTypes.TIMESTAMP, false) ); - registerFunction("localtimestamp", new NoArgSQLFunction("localtimestamp", StandardBasicTypes.TIMESTAMP, false) ); + registerFunction( "timestamp", new StandardSQLFunction( "timestamp", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( + "current_timestamp", new NoArgSQLFunction( + "current_timestamp", + StandardBasicTypes.TIMESTAMP, + false + ) + ); + registerFunction( + "sys_timestamp", new NoArgSQLFunction( + "sys_timestamp", + StandardBasicTypes.TIMESTAMP, + false + ) + ); + registerFunction( "systimestamp", new NoArgSQLFunction( "systimestamp", StandardBasicTypes.TIMESTAMP, false ) ); + registerFunction( "localtime", new NoArgSQLFunction( "localtime", StandardBasicTypes.TIMESTAMP, false ) ); + registerFunction( + "localtimestamp", new NoArgSQLFunction( + "localtimestamp", + StandardBasicTypes.TIMESTAMP, + false + ) + ); - registerFunction("day", new StandardSQLFunction("day", StandardBasicTypes.INTEGER) ); - registerFunction("dayofmonth", new StandardSQLFunction("dayofmonth", StandardBasicTypes.INTEGER) ); - registerFunction("dayofweek", new StandardSQLFunction("dayofweek", StandardBasicTypes.INTEGER) ); - registerFunction("dayofyear", new StandardSQLFunction("dayofyear", StandardBasicTypes.INTEGER) ); - registerFunction("from_days", new StandardSQLFunction("from_days", StandardBasicTypes.DATE) ); - registerFunction("from_unixtime", new StandardSQLFunction("from_unixtime", StandardBasicTypes.TIMESTAMP) ); - registerFunction("last_day", new StandardSQLFunction("last_day", StandardBasicTypes.DATE) ); - registerFunction("minute", new StandardSQLFunction("minute", StandardBasicTypes.INTEGER) ); - registerFunction("month", new StandardSQLFunction("month", StandardBasicTypes.INTEGER) ); - registerFunction("months_between", new StandardSQLFunction("months_between", StandardBasicTypes.DOUBLE) ); - registerFunction("now", new NoArgSQLFunction("now", StandardBasicTypes.TIMESTAMP) ); - registerFunction("quarter", new StandardSQLFunction("quarter", StandardBasicTypes.INTEGER) ); - registerFunction("second", new StandardSQLFunction("second", StandardBasicTypes.INTEGER) ); - registerFunction("sec_to_time", new StandardSQLFunction("sec_to_time", StandardBasicTypes.TIME) ); - registerFunction("time_to_sec", new StandardSQLFunction("time_to_sec", StandardBasicTypes.INTEGER) ); - registerFunction("to_days", new StandardSQLFunction("to_days", StandardBasicTypes.LONG) ); - registerFunction("unix_timestamp", new StandardSQLFunction("unix_timestamp", StandardBasicTypes.LONG) ); - registerFunction("utc_date", new NoArgSQLFunction("utc_date", StandardBasicTypes.STRING) ); - registerFunction("utc_time", new NoArgSQLFunction("utc_time", StandardBasicTypes.STRING) ); - registerFunction("week", new StandardSQLFunction("week", StandardBasicTypes.INTEGER) ); - registerFunction("weekday", new StandardSQLFunction("weekday", StandardBasicTypes.INTEGER) ); - registerFunction("year", new StandardSQLFunction("year", StandardBasicTypes.INTEGER) ); + registerFunction( "day", new StandardSQLFunction( "day", StandardBasicTypes.INTEGER ) ); + registerFunction( "dayofmonth", new StandardSQLFunction( "dayofmonth", StandardBasicTypes.INTEGER ) ); + registerFunction( "dayofweek", new StandardSQLFunction( "dayofweek", StandardBasicTypes.INTEGER ) ); + registerFunction( "dayofyear", new StandardSQLFunction( "dayofyear", StandardBasicTypes.INTEGER ) ); + registerFunction( "from_days", new StandardSQLFunction( "from_days", StandardBasicTypes.DATE ) ); + registerFunction( "from_unixtime", new StandardSQLFunction( "from_unixtime", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( "last_day", new StandardSQLFunction( "last_day", StandardBasicTypes.DATE ) ); + registerFunction( "minute", new StandardSQLFunction( "minute", StandardBasicTypes.INTEGER ) ); + registerFunction( "month", new StandardSQLFunction( "month", StandardBasicTypes.INTEGER ) ); + registerFunction( "months_between", new StandardSQLFunction( "months_between", StandardBasicTypes.DOUBLE ) ); + registerFunction( "now", new NoArgSQLFunction( "now", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( "quarter", new StandardSQLFunction( "quarter", StandardBasicTypes.INTEGER ) ); + registerFunction( "second", new StandardSQLFunction( "second", StandardBasicTypes.INTEGER ) ); + registerFunction( "sec_to_time", new StandardSQLFunction( "sec_to_time", StandardBasicTypes.TIME ) ); + registerFunction( "time_to_sec", new StandardSQLFunction( "time_to_sec", StandardBasicTypes.INTEGER ) ); + registerFunction( "to_days", new StandardSQLFunction( "to_days", StandardBasicTypes.LONG ) ); + registerFunction( "unix_timestamp", new StandardSQLFunction( "unix_timestamp", StandardBasicTypes.LONG ) ); + registerFunction( "utc_date", new NoArgSQLFunction( "utc_date", StandardBasicTypes.STRING ) ); + registerFunction( "utc_time", new NoArgSQLFunction( "utc_time", StandardBasicTypes.STRING ) ); + registerFunction( "week", new StandardSQLFunction( "week", StandardBasicTypes.INTEGER ) ); + registerFunction( "weekday", new StandardSQLFunction( "weekday", StandardBasicTypes.INTEGER ) ); + registerFunction( "year", new StandardSQLFunction( "year", StandardBasicTypes.INTEGER ) ); - registerFunction("hex", new StandardSQLFunction("hex", StandardBasicTypes.STRING) ); + registerFunction( "hex", new StandardSQLFunction( "hex", StandardBasicTypes.STRING ) ); - registerFunction("octet_length", new StandardSQLFunction("octet_length", StandardBasicTypes.LONG) ); - registerFunction("bit_length", new StandardSQLFunction("bit_length", StandardBasicTypes.LONG) ); + registerFunction( "octet_length", new StandardSQLFunction( "octet_length", StandardBasicTypes.LONG ) ); + registerFunction( "bit_length", new StandardSQLFunction( "bit_length", StandardBasicTypes.LONG ) ); - registerFunction("bit_count", new StandardSQLFunction("bit_count", StandardBasicTypes.LONG) ); - registerFunction("md5", new StandardSQLFunction("md5", StandardBasicTypes.STRING) ); + registerFunction( "bit_count", new StandardSQLFunction( "bit_count", StandardBasicTypes.LONG ) ); + registerFunction( "md5", new StandardSQLFunction( "md5", StandardBasicTypes.STRING ) ); - registerFunction( "concat", new StandardSQLFunction( "concat", StandardBasicTypes.STRING ) ); + registerFunction( "concat", new StandardSQLFunction( "concat", StandardBasicTypes.STRING ) ); - registerFunction("substring", new StandardSQLFunction("substring", StandardBasicTypes.STRING) ); - registerFunction("substr", new StandardSQLFunction("substr", StandardBasicTypes.STRING) ); + registerFunction( "substring", new StandardSQLFunction( "substring", StandardBasicTypes.STRING ) ); + registerFunction( "substr", new StandardSQLFunction( "substr", StandardBasicTypes.STRING ) ); - registerFunction("length", new StandardSQLFunction("length", StandardBasicTypes.INTEGER) ); - registerFunction("bit_length",new StandardSQLFunction("bit_length", StandardBasicTypes.INTEGER) ); - registerFunction("coalesce", new StandardSQLFunction("coalesce") ); - registerFunction("nullif", new StandardSQLFunction("nullif") ); - registerFunction("mod", new StandardSQLFunction("mod") ); + registerFunction( "length", new StandardSQLFunction( "length", StandardBasicTypes.INTEGER ) ); + registerFunction( "bit_length", new StandardSQLFunction( "bit_length", StandardBasicTypes.INTEGER ) ); + registerFunction( "coalesce", new StandardSQLFunction( "coalesce" ) ); + registerFunction( "nullif", new StandardSQLFunction( "nullif" ) ); + registerFunction( "mod", new StandardSQLFunction( "mod" ) ); - registerFunction("power", new StandardSQLFunction("power") ); - registerFunction("stddev", new StandardSQLFunction("stddev") ); - registerFunction("variance", new StandardSQLFunction("variance") ); - registerFunction("trunc", new StandardSQLFunction("trunc") ); - registerFunction("nvl", new StandardSQLFunction("nvl") ); - registerFunction("nvl2", new StandardSQLFunction("nvl2") ); - registerFunction("chr", new StandardSQLFunction("chr", StandardBasicTypes.CHARACTER)); - registerFunction("to_char", new StandardSQLFunction("to_char", StandardBasicTypes.STRING) ); - registerFunction("to_date", new StandardSQLFunction("to_date", StandardBasicTypes.TIMESTAMP)); - registerFunction("instr", new StandardSQLFunction("instr", StandardBasicTypes.INTEGER) ); - registerFunction("instrb", new StandardSQLFunction("instrb", StandardBasicTypes.INTEGER) ); - registerFunction("lpad", new StandardSQLFunction("lpad", StandardBasicTypes.STRING) ); - registerFunction("replace", new StandardSQLFunction("replace", StandardBasicTypes.STRING) ); - registerFunction("rpad", new StandardSQLFunction("rpad", StandardBasicTypes.STRING) ); - registerFunction("translate", new StandardSQLFunction("translate", StandardBasicTypes.STRING) ); + registerFunction( "power", new StandardSQLFunction( "power" ) ); + registerFunction( "stddev", new StandardSQLFunction( "stddev" ) ); + registerFunction( "variance", new StandardSQLFunction( "variance" ) ); + registerFunction( "trunc", new StandardSQLFunction( "trunc" ) ); + registerFunction( "nvl", new StandardSQLFunction( "nvl" ) ); + registerFunction( "nvl2", new StandardSQLFunction( "nvl2" ) ); + registerFunction( "chr", new StandardSQLFunction( "chr", StandardBasicTypes.CHARACTER ) ); + registerFunction( "to_char", new StandardSQLFunction( "to_char", StandardBasicTypes.STRING ) ); + registerFunction( "to_date", new StandardSQLFunction( "to_date", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( "instr", new StandardSQLFunction( "instr", StandardBasicTypes.INTEGER ) ); + registerFunction( "instrb", new StandardSQLFunction( "instrb", StandardBasicTypes.INTEGER ) ); + registerFunction( "lpad", new StandardSQLFunction( "lpad", StandardBasicTypes.STRING ) ); + registerFunction( "replace", new StandardSQLFunction( "replace", StandardBasicTypes.STRING ) ); + registerFunction( "rpad", new StandardSQLFunction( "rpad", StandardBasicTypes.STRING ) ); + registerFunction( "translate", new StandardSQLFunction( "translate", StandardBasicTypes.STRING ) ); - registerFunction("add_months", new StandardSQLFunction("add_months", StandardBasicTypes.DATE) ); - registerFunction("user", new NoArgSQLFunction("user", StandardBasicTypes.STRING, false) ); - registerFunction("rownum", new NoArgSQLFunction("rownum", StandardBasicTypes.LONG, false) ); - registerFunction("concat", new VarArgsSQLFunction(StandardBasicTypes.STRING, "", "||", "")); + registerFunction( "add_months", new StandardSQLFunction( "add_months", StandardBasicTypes.DATE ) ); + registerFunction( "user", new NoArgSQLFunction( "user", StandardBasicTypes.STRING, false ) ); + registerFunction( "rownum", new NoArgSQLFunction( "rownum", StandardBasicTypes.LONG, false ) ); + registerFunction( "concat", new VarArgsSQLFunction( StandardBasicTypes.STRING, "", "||", "" ) ); - registerKeyword( "TYPE" ); - registerKeyword( "YEAR" ); - registerKeyword( "MONTH" ); - registerKeyword( "ALIAS" ); - registerKeyword( "VALUE" ); - registerKeyword( "FIRST" ); - registerKeyword( "ROLE" ); - registerKeyword( "CLASS" ); - registerKeyword( "BIT" ); - registerKeyword( "TIME" ); - registerKeyword( "QUERY" ); - registerKeyword( "DATE" ); - registerKeyword( "USER" ); - registerKeyword( "ACTION" ); - registerKeyword( "SYS_USER" ); - registerKeyword( "ZONE" ); - registerKeyword( "LANGUAGE" ); - registerKeyword( "DICTIONARY" ); - registerKeyword( "DATA" ); - registerKeyword( "TEST" ); - registerKeyword( "SUPERCLASS" ); - registerKeyword( "SECTION" ); - registerKeyword( "LOWER" ); - registerKeyword( "LIST" ); - registerKeyword( "OID" ); - registerKeyword( "DAY" ); - registerKeyword( "IF" ); - registerKeyword( "ATTRIBUTE" ); - registerKeyword( "STRING" ); - registerKeyword( "SEARCH" ); - } - + registerKeyword( "TYPE" ); + registerKeyword( "YEAR" ); + registerKeyword( "MONTH" ); + registerKeyword( "ALIAS" ); + registerKeyword( "VALUE" ); + registerKeyword( "FIRST" ); + registerKeyword( "ROLE" ); + registerKeyword( "CLASS" ); + registerKeyword( "BIT" ); + registerKeyword( "TIME" ); + registerKeyword( "QUERY" ); + registerKeyword( "DATE" ); + registerKeyword( "USER" ); + registerKeyword( "ACTION" ); + registerKeyword( "SYS_USER" ); + registerKeyword( "ZONE" ); + registerKeyword( "LANGUAGE" ); + registerKeyword( "DICTIONARY" ); + registerKeyword( "DATA" ); + registerKeyword( "TEST" ); + registerKeyword( "SUPERCLASS" ); + registerKeyword( "SECTION" ); + registerKeyword( "LOWER" ); + registerKeyword( "LIST" ); + registerKeyword( "OID" ); + registerKeyword( "DAY" ); + registerKeyword( "IF" ); + registerKeyword( "ATTRIBUTE" ); + registerKeyword( "STRING" ); + registerKeyword( "SEARCH" ); + } + + @Override public boolean supportsIdentityColumns() { return true; } + @Override public String getIdentityInsertString() { return "NULL"; } - + + @Override public boolean supportsColumnCheck() { return false; } - + + @Override public boolean supportsPooledSequences() { return true; } - public String getIdentitySelectString() { - return "select last_insert_id()"; - } + @Override + public String getIdentitySelectString() { + return "select last_insert_id()"; + } - protected String getIdentityColumnString() { - return "not null auto_increment"; //starts with 1, implicitly - } + @Override + protected String getIdentityColumnString() { + //starts with 1, implicitly + return "not null auto_increment"; + } - /* - * CUBRID supports "ADD [COLUMN | ATTRIBUTE]" - */ - public String getAddColumnString() { - return "add"; - } + @Override + public String getAddColumnString() { + return "add"; + } - public String getSequenceNextValString(String sequenceName) { - return "select " + sequenceName + ".next_value from table({1}) as T(X)"; - } + @Override + public String getSequenceNextValString(String sequenceName) { + return "select " + sequenceName + ".next_value from table({1}) as T(X)"; + } - public String getCreateSequenceString(String sequenceName) { - return "create serial " + sequenceName; - } + @Override + public String getCreateSequenceString(String sequenceName) { + return "create serial " + sequenceName; + } - public String getDropSequenceString(String sequenceName) { - return "drop serial " + sequenceName; - } + @Override + public String getDropSequenceString(String sequenceName) { + return "drop serial " + sequenceName; + } + @Override public String getDropForeignKeyString() { return " drop foreign key "; } - + + @Override public boolean qualifyIndexName() { return false; } - public boolean supportsSequences() { - return true; - } + @Override + public boolean supportsSequences() { + return true; + } + @Override public boolean supportsExistsInSelect() { return false; } - public String getQuerySequencesString() { - return "select name from db_serial"; - } + @Override + public String getQuerySequencesString() { + return "select name from db_serial"; + } - /** - * The character specific to this dialect used to close a quoted identifier. - * CUBRID supports square brackets (MSSQL style), backticks (MySQL style), - * as well as double quotes (Oracle style). - * - * @return The dialect's specific open quote character. - */ - public char openQuote() { - return '['; - } + @Override + public char openQuote() { + return '['; + } - public char closeQuote() { - return ']'; - } + @Override + public char closeQuote() { + return ']'; + } - public String getForUpdateString() { - return " "; - } + @Override + public String getForUpdateString() { + return " "; + } - public boolean supportsUnionAll() { - return true; - } + @Override + public boolean supportsUnionAll() { + return true; + } - public boolean supportsCurrentTimestampSelection() { - return true; - } + @Override + public boolean supportsCurrentTimestampSelection() { + return true; + } - public String getCurrentTimestampSelectString() { - return "select now()"; - } + @Override + public String getCurrentTimestampSelectString() { + return "select now()"; + } - public boolean isCurrentTimestampSelectStringCallable() { - return false; - } + @Override + public boolean isCurrentTimestampSelectStringCallable() { + return false; + } - public boolean supportsEmptyInList() { - return false; - } - + @Override + public boolean supportsEmptyInList() { + return false; + } + + @Override public boolean supportsIfExistsBeforeTableName() { return true; } + @Override public boolean supportsTupleDistinctCounts() { return false; } + @Override public LimitHandler buildLimitHandler(String sql, RowSelection selection) { - return new CUBRIDLimitHandler( this, sql, selection ); - } + return new CUBRIDLimitHandler( this, sql, selection ); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Cache71Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Cache71Dialect.java index c2811e3b42..747fe4b4e2 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Cache71Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Cache71Dialect.java @@ -58,15 +58,11 @@ import org.hibernate.sql.JoinFragment; import org.hibernate.type.StandardBasicTypes; /** - * Caché 2007.1 dialect. This class is required in order to use Hibernate with Intersystems Caché SQL.
- *
- * Compatible with Caché 2007.1. - *
- * - * Caché and Hibernate - * - * - *

Caché and Hibernate

+ * Caché 2007.1 dialect. + * + * This class is required in order to use Hibernate with Intersystems Caché SQL. Compatible with + * Caché 2007.1. + * *

PREREQUISITES

* These setup instructions assume that both Caché and Hibernate are installed and operational. *
@@ -144,11 +140,9 @@ import org.hibernate.type.StandardBasicTypes; * * *

- *

- *
Note 1
- *
Please contact your administrator for the userid and password you should use when attempting access via JDBC. - * By default, these are chosen to be "_SYSTEM" and "SYS" respectively as noted in the SQL standard.
- *
+ * NOTE: Please contact your administrator for the userid and password you should use when + * attempting access via JDBC. By default, these are chosen to be "_SYSTEM" and "SYS" respectively + * as noted in the SQL standard. *
*

CACHÉ VERSION URL

* This is the standard URL for the JDBC driver. @@ -239,16 +233,14 @@ public class Cache71Dialect extends Dialect { registerColumnType( Types.DOUBLE, "double" ); registerColumnType( Types.FLOAT, "float" ); registerColumnType( Types.INTEGER, "integer" ); - registerColumnType( Types.LONGVARBINARY, "longvarbinary" ); // binary %Stream - registerColumnType( Types.LONGVARCHAR, "longvarchar" ); // character %Stream + registerColumnType( Types.LONGVARBINARY, "longvarbinary" ); + registerColumnType( Types.LONGVARCHAR, "longvarchar" ); registerColumnType( Types.NUMERIC, "numeric($p,$s)" ); registerColumnType( Types.REAL, "real" ); registerColumnType( Types.SMALLINT, "smallint" ); registerColumnType( Types.TIMESTAMP, "timestamp" ); registerColumnType( Types.TIME, "time" ); registerColumnType( Types.TINYINT, "tinyint" ); - // TBD should this be varbinary($1)? - // registerColumnType(Types.VARBINARY, "binary($1)"); registerColumnType( Types.VARBINARY, "longvarbinary" ); registerColumnType( Types.VARCHAR, "varchar($l)" ); registerColumnType( Types.BLOB, "longvarbinary" ); @@ -256,7 +248,6 @@ public class Cache71Dialect extends Dialect { getDefaultProperties().setProperty( Environment.USE_STREAMS_FOR_BINARY, "false" ); getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE ); - //getDefaultProperties().setProperty(Environment.STATEMENT_BATCH_SIZE, NO_BATCH); getDefaultProperties().setProperty( Environment.USE_SQL_COMMENTS, "false" ); @@ -267,7 +258,6 @@ public class Cache71Dialect extends Dialect { registerFunction( "asin", new StandardJDBCEscapeFunction( "asin", StandardBasicTypes.DOUBLE ) ); registerFunction( "atan", new StandardJDBCEscapeFunction( "atan", StandardBasicTypes.DOUBLE ) ); registerFunction( "bit_length", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "($length(?1)*8)" ) ); - // hibernate impelemnts cast in Dialect.java registerFunction( "ceiling", new StandardSQLFunction( "ceiling", StandardBasicTypes.INTEGER ) ); registerFunction( "char", new StandardJDBCEscapeFunction( "char", StandardBasicTypes.CHARACTER ) ); registerFunction( "character_length", new StandardSQLFunction( "character_length", StandardBasicTypes.INTEGER ) ); @@ -311,9 +301,6 @@ public class Cache71Dialect extends Dialect { registerFunction( "left", new StandardJDBCEscapeFunction( "left", StandardBasicTypes.STRING ) ); registerFunction( "len", new StandardSQLFunction( "len", StandardBasicTypes.INTEGER ) ); registerFunction( "$length", new VarArgsSQLFunction( "$length(", ",", ")" ) ); - // aggregate functions shouldn't be registered, right? - //registerFunction( "list", new StandardSQLFunction("list",StandardBasicTypes.STRING) ); - // stopped on $list registerFunction( "$list", new VarArgsSQLFunction( "$list(", ",", ")" ) ); registerFunction( "$listdata", new VarArgsSQLFunction( "$listdata(", ",", ")" ) ); registerFunction( "$listfind", new VarArgsSQLFunction( "$listfind(", ",", ")" ) ); @@ -391,21 +378,20 @@ public class Cache71Dialect extends Dialect { // DDL support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + @Override public boolean hasAlterTable() { // Does this dialect support the ALTER TABLE syntax? return true; } + @Override public boolean qualifyIndexName() { // Do we need to qualify index names with the schema name? return false; } - /** - * The syntax used to add a foreign key constraint to a table. - * - * @return String - */ + @Override + @SuppressWarnings("StringBufferReplaceableByString") public String getAddForeignKeyConstraintString( String constraintName, String[] foreignKey, @@ -419,97 +405,120 @@ public class Cache71Dialect extends Dialect { .append( " FOREIGN KEY " ) .append( constraintName ) .append( " (" ) - .append( StringHelper.join( ", ", foreignKey ) ) // identifier-commalist + .append( StringHelper.join( ", ", foreignKey ) ) .append( ") REFERENCES " ) .append( referencedTable ) .append( " (" ) - .append( StringHelper.join( ", ", primaryKey ) ) // identifier-commalist + .append( StringHelper.join( ", ", primaryKey ) ) .append( ") " ) .toString(); } + /** + * Does this dialect support check constraints? + * + * @return {@code false} (Cache does not support check constraints) + */ + @SuppressWarnings("UnusedDeclaration") public boolean supportsCheck() { - // Does this dialect support check constraints? return false; } + @Override public String getAddColumnString() { // The syntax used to add a column to a table return " add column"; } + @Override public String getCascadeConstraintsString() { // Completely optional cascading drop clause. return ""; } + @Override public boolean dropConstraints() { // Do we need to drop constraints before dropping tables in this dialect? return true; } + @Override public boolean supportsCascadeDelete() { return true; } + @Override public boolean hasSelfReferentialForeignKeyBug() { return true; } + // temporary table support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + @Override public boolean supportsTemporaryTables() { return true; } + @Override public String generateTemporaryTableName(String baseTableName) { - String name = super.generateTemporaryTableName( baseTableName ); + final String name = super.generateTemporaryTableName( baseTableName ); return name.length() > 25 ? name.substring( 1, 25 ) : name; } + @Override public String getCreateTemporaryTableString() { return "create global temporary table"; } + @Override public Boolean performTemporaryTableDDLInIsolation() { return Boolean.FALSE; } + @Override public String getCreateTemporaryTablePostfix() { return ""; } + @Override public boolean dropTemporaryTableAfterUse() { return true; } // IDENTITY support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + @Override public boolean supportsIdentityColumns() { return true; } + @Override public Class getNativeIdentifierGeneratorClass() { return IdentityGenerator.class; } + @Override public boolean hasDataTypeInIdentityColumn() { // Whether this dialect has an Identity clause added to the data type or a completely seperate identity // data type return true; } + @Override public String getIdentityColumnString() throws MappingException { // The keyword used to specify an identity column, if identity column key generation is supported. return "identity"; } + @Override public String getIdentitySelectString() { return "SELECT LAST_IDENTITY() FROM %TSQL_sys.snf"; } // SEQUENCE support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + @Override public boolean supportsSequences() { return false; } @@ -539,25 +548,12 @@ public class Cache71Dialect extends Dialect { // lock acquisition support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - public boolean supportsForUpdate() { - // Does this dialect support the FOR UPDATE syntax? - return false; - } - - public boolean supportsForUpdateOf() { - // Does this dialect support FOR UPDATE OF, allowing particular rows to be locked? - return false; - } - - public boolean supportsForUpdateNowait() { - // Does this dialect support the Oracle-style FOR UPDATE NOWAIT syntax? - return false; - } - + @Override public boolean supportsOuterJoinForUpdate() { return false; } + @Override public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) { // InterSystems Cache' does not current support "SELECT ... FOR UPDATE" syntax... // Set your transaction mode to READ_COMMITTED before using @@ -586,28 +582,40 @@ public class Cache71Dialect extends Dialect { // LIMIT support (ala TOP) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + @Override + @SuppressWarnings("deprecation") public boolean supportsLimit() { return true; } + @Override + @SuppressWarnings("deprecation") public boolean supportsLimitOffset() { return false; } + @Override + @SuppressWarnings("deprecation") public boolean supportsVariableLimit() { return true; } + @Override + @SuppressWarnings("deprecation") public boolean bindLimitParametersFirst() { // Does the LIMIT clause come at the start of the SELECT statement, rather than at the end? return true; } + @Override + @SuppressWarnings("deprecation") public boolean useMaxForLimit() { // Does the LIMIT clause take a "maximum" row number instead of a total number of returned rows? return true; } + @Override + @SuppressWarnings("deprecation") public String getLimitString(String sql, boolean hasOffset) { if ( hasOffset ) { throw new UnsupportedOperationException( "query result offset is not supported" ); @@ -615,7 +623,7 @@ public class Cache71Dialect extends Dialect { // This does not support the Cache SQL 'DISTINCT BY (comma-list)' extensions, // but this extension is not supported through Hibernate anyway. - int insertionPoint = sql.startsWith( "select distinct" ) ? 15 : 6; + final int insertionPoint = sql.startsWith( "select distinct" ) ? 15 : 6; return new StringBuilder( sql.length() + 8 ) .append( sql ) @@ -625,53 +633,59 @@ public class Cache71Dialect extends Dialect { // callable statement support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + @Override public int registerResultSetOutParameter(CallableStatement statement, int col) throws SQLException { return col; } + @Override public ResultSet getResultSet(CallableStatement ps) throws SQLException { ps.execute(); - return ( ResultSet ) ps.getObject( 1 ); + return (ResultSet) ps.getObject( 1 ); } // miscellaneous support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + @Override public String getLowercaseFunction() { // The name of the SQL function that transforms a string to lowercase return "lower"; } + @Override public String getNullColumnString() { // The keyword used to specify a nullable column. return " null"; } + @Override public JoinFragment createOuterJoinFragment() { // Create an OuterJoinGenerator for this dialect. return new CacheJoinFragment(); } + @Override public String getNoColumnsInsertString() { // The keyword used to insert a row without specifying // any column values return " default values"; } + @Override public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() { return new CacheSQLExceptionConversionDelegate( this ); } + @Override public ViolatedConstraintNameExtracter getViolatedConstraintNameExtracter() { return EXTRACTER; } + /** + * The Cache ViolatedConstraintNameExtracter. + */ public static final ViolatedConstraintNameExtracter EXTRACTER = new TemplatedViolatedConstraintNameExtracter() { - /** - * Extract the name of the violated constraint from the given SQLException. - * - * @param sqle The exception that was the result of the constraint violation. - * @return The extracted constraint name. - */ + @Override public String extractConstraintName(SQLException sqle) { return extractUsingTemplate( "constraint (", ") violated", sqle.getMessage() ); } @@ -680,14 +694,17 @@ public class Cache71Dialect extends Dialect { // Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + @Override public boolean supportsEmptyInList() { return false; } + @Override public boolean areStringComparisonsCaseInsensitive() { return true; } + @Override public boolean supportsResultSetPositionQueryMethodsOnForwardOnlyCursor() { return false; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/ColumnAliasExtractor.java b/hibernate-core/src/main/java/org/hibernate/dialect/ColumnAliasExtractor.java index e00d6522d3..0ac51f6dad 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/ColumnAliasExtractor.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/ColumnAliasExtractor.java @@ -42,6 +42,8 @@ public interface ColumnAliasExtractor { * @param position The column position * * @return The alias + * + * @throws SQLException Indicates a problem accessing the JDBC ResultSetMetaData */ public String extractColumnAlias(ResultSetMetaData metaData, int position) throws SQLException; @@ -58,6 +60,7 @@ public interface ColumnAliasExtractor { /** * An extractor which uses {@link ResultSetMetaData#getColumnName} */ + @SuppressWarnings("UnusedDeclaration") public static final ColumnAliasExtractor COLUMN_NAME_EXTRACTOR = new ColumnAliasExtractor() { @Override public String extractColumnAlias(ResultSetMetaData metaData, int position) throws SQLException { diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/DB2390Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/DB2390Dialect.java index d4cfb0ff0b..d4fdf523a0 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/DB2390Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/DB2390Dialect.java @@ -31,31 +31,38 @@ package org.hibernate.dialect; * @author Kristoffer Dyrkorn */ public class DB2390Dialect extends DB2Dialect { - + @Override public boolean supportsSequences() { return false; } + @Override public String getIdentitySelectString() { return "select identity_val_local() from sysibm.sysdummy1"; } + @Override public boolean supportsLimit() { return true; } + @Override + @SuppressWarnings("deprecation") public boolean supportsLimitOffset() { return false; } + @Override public boolean useMaxForLimit() { return true; } + @Override public boolean supportsVariableLimit() { return false; } + @Override public String getLimitString(String sql, int offset, int limit) { if ( offset > 0 ) { throw new UnsupportedOperationException( "query result offset is not supported" ); @@ -63,12 +70,7 @@ public class DB2390Dialect extends DB2Dialect { if ( limit == 0 ) { return sql; } - return new StringBuilder( sql.length() + 40 ) - .append( sql ) - .append( " fetch first " ) - .append( limit ) - .append( " rows only " ) - .toString(); + return sql + " fetch first " + limit + " rows only "; } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/DB2400Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/DB2400Dialect.java index 4f93f7af25..5aa87d9d7c 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/DB2400Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/DB2400Dialect.java @@ -23,7 +23,6 @@ */ package org.hibernate.dialect; - /** * An SQL dialect for DB2/400. This class provides support for DB2 Universal Database for iSeries, * also known as DB2/400. @@ -31,31 +30,38 @@ package org.hibernate.dialect; * @author Peter DeGregorio (pdegregorio) */ public class DB2400Dialect extends DB2Dialect { - + @Override public boolean supportsSequences() { return false; } + @Override public String getIdentitySelectString() { return "select identity_val_local() from sysibm.sysdummy1"; } + @Override public boolean supportsLimit() { return true; } + @Override + @SuppressWarnings("deprecation") public boolean supportsLimitOffset() { return false; } + @Override public boolean useMaxForLimit() { return true; } + @Override public boolean supportsVariableLimit() { return false; } + @Override public String getLimitString(String sql, int offset, int limit) { if ( offset > 0 ) { throw new UnsupportedOperationException( "query result offset is not supported" ); @@ -63,15 +69,11 @@ public class DB2400Dialect extends DB2Dialect { if ( limit == 0 ) { return sql; } - return new StringBuilder( sql.length() + 40 ) - .append( sql ) - .append( " fetch first " ) - .append( limit ) - .append( " rows only " ) - .toString(); + return sql + " fetch first " + limit + " rows only "; } + @Override public String getForUpdateString() { return " for update with rs"; } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/DB2Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/DB2Dialect.java index 2e3397c464..f70de19015 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/DB2Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/DB2Dialect.java @@ -50,9 +50,11 @@ import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; * @author Gavin King */ public class DB2Dialect extends Dialect { - private final UniqueDelegate uniqueDelegate; + /** + * Constructs a DB2Dialect + */ public DB2Dialect() { super(); registerColumnType( Types.BIT, "smallint" ); @@ -181,117 +183,137 @@ public class DB2Dialect extends Dialect { uniqueDelegate = new DB2UniqueDelegate( this ); } + @Override public String getLowercaseFunction() { return "lcase"; } + @Override public String getAddColumnString() { return "add column"; } + @Override public boolean dropConstraints() { return false; } + @Override public boolean supportsIdentityColumns() { return true; } + @Override public String getIdentitySelectString() { return "values identity_val_local()"; } + @Override public String getIdentityColumnString() { - return "generated by default as identity"; //not null ... (start with 1) is implicit + return "generated by default as identity"; } + @Override public String getIdentityInsertString() { return "default"; } + @Override public String getSequenceNextValString(String sequenceName) { return "values nextval for " + sequenceName; } + @Override public String getCreateSequenceString(String sequenceName) { return "create sequence " + sequenceName; } + @Override public String getDropSequenceString(String sequenceName) { return "drop sequence " + sequenceName + " restrict"; } + @Override public boolean supportsSequences() { return true; } + @Override public boolean supportsPooledSequences() { return true; } + @Override public String getQuerySequencesString() { return "select seqname from sysibm.syssequences"; } + @Override + @SuppressWarnings("deprecation") public boolean supportsLimit() { return true; } + @Override + @SuppressWarnings("deprecation") public boolean supportsVariableLimit() { return false; } + @Override + @SuppressWarnings("deprecation") public String getLimitString(String sql, int offset, int limit) { if ( offset == 0 ) { return sql + " fetch first " + limit + " rows only"; } - StringBuilder pagingSelect = new StringBuilder( sql.length() + 200 ) - .append( - "select * from ( select inner2_.*, rownumber() over(order by order of inner2_) as rownumber_ from ( " - ) - .append( sql ) //nest the main query in an outer select - .append( " fetch first " ) - .append( limit ) - .append( " rows only ) as inner2_ ) as inner1_ where rownumber_ > " ) - .append( offset ) - .append( " order by rownumber_" ); - return pagingSelect.toString(); + //nest the main query in an outer select + return "select * from ( select inner2_.*, rownumber() over(order by order of inner2_) as rownumber_ from ( " + + sql + " fetch first " + limit + " rows only ) as inner2_ ) as inner1_ where rownumber_ > " + + offset + " order by rownumber_"; } /** + * {@inheritDoc} + *

+ * * DB2 does have a one-based offset, however this was actually already handled in the limit string building * (the '?+1' bit). To not mess up inheritors, I'll leave that part alone and not touch the offset here. - * - * @param zeroBasedFirstResult The user-supplied, zero-based offset - * - * @return zeroBasedFirstResult */ @Override + @SuppressWarnings("deprecation") public int convertToFirstRowValue(int zeroBasedFirstResult) { return zeroBasedFirstResult; } + @Override + @SuppressWarnings("deprecation") public String getForUpdateString() { return " for read only with rs use and keep update locks"; } + @Override + @SuppressWarnings("deprecation") public boolean useMaxForLimit() { return true; } + @Override public boolean supportsOuterJoinForUpdate() { return false; } + @Override public boolean supportsExistsInSelect() { return false; } - //as far as I know, DB2 doesn't support this + @Override public boolean supportsLockTimeouts() { + //as far as I know, DB2 doesn't support this return false; } + @Override public String getSelectClauseNullString(int sqlType) { String literal; @@ -315,32 +337,16 @@ public class DB2Dialect extends Dialect { return "nullif(" + literal + ',' + literal + ')'; } - public static void main(String[] args) { - System.out.println( new DB2Dialect().getLimitString( "/*foo*/ select * from foos", true ) ); - System.out.println( new DB2Dialect().getLimitString( "/*foo*/ select distinct * from foos", true ) ); - System.out - .println( - new DB2Dialect().getLimitString( - "/*foo*/ select * from foos foo order by foo.bar, foo.baz", - true - ) - ); - System.out - .println( - new DB2Dialect().getLimitString( - "/*foo*/ select distinct * from foos foo order by foo.bar, foo.baz", - true - ) - ); - } @Override public boolean supportsUnionAll() { return true; } + @Override public int registerResultSetOutParameter(CallableStatement statement, int col) throws SQLException { return col; } + @Override public ResultSet getResultSet(CallableStatement ps) throws SQLException { boolean isResultSet = ps.execute(); @@ -348,39 +354,45 @@ public class DB2Dialect extends Dialect { while ( !isResultSet && ps.getUpdateCount() != -1 ) { isResultSet = ps.getMoreResults(); } - ResultSet rs = ps.getResultSet(); - // You may still have other ResultSets or update counts left to process here - // but you can't do it now or the ResultSet you just got will be closed - return rs; + + return ps.getResultSet(); } + @Override public boolean supportsCommentOn() { return true; } + @Override public boolean supportsTemporaryTables() { return true; } + @Override public String getCreateTemporaryTableString() { return "declare global temporary table"; } + @Override public String getCreateTemporaryTablePostfix() { return "not logged"; } + @Override public String generateTemporaryTableName(String baseTableName) { return "session." + super.generateTemporaryTableName( baseTableName ); } + @Override public boolean supportsCurrentTimestampSelection() { return true; } + @Override public String getCurrentTimestampSelectString() { return "values current timestamp"; } + @Override public boolean isCurrentTimestampSelectStringCallable() { return false; @@ -389,10 +401,8 @@ public class DB2Dialect extends Dialect { /** * {@inheritDoc} *

- * DB2 is know to support parameters in the SELECT clause, but only in casted form + * NOTE : DB2 is know to support parameters in the SELECT clause, but only in casted form * (see {@link #requiresCastingOfParametersInSelectClause()}). - * - * @return True. */ @Override public boolean supportsParametersInInsertSelect() { @@ -400,38 +410,45 @@ public class DB2Dialect extends Dialect { } /** + * {@inheritDoc} + *

* DB2 in fact does require that parameters appearing in the select clause be wrapped in cast() calls * to tell the DB parser the type of the select value. - * - * @return True. */ @Override public boolean requiresCastingOfParametersInSelectClause() { return true; } + @Override public boolean supportsResultSetPositionQueryMethodsOnForwardOnlyCursor() { return false; } - //DB2 v9.1 doesn't support 'cross join' syntax @Override public String getCrossJoinSeparator() { + //DB2 v9.1 doesn't support 'cross join' syntax return ", "; } + + // Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + @Override public boolean supportsEmptyInList() { return false; } + @Override public boolean supportsLobValueChangePropogation() { return false; } + @Override public boolean doesReadCommittedCauseWritersToBlockReaders() { return true; } + @Override public boolean supportsTupleDistinctCounts() { return false; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/DataDirectOracle9Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/DataDirectOracle9Dialect.java index 65d99bd684..90f9e3af80 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/DataDirectOracle9Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/DataDirectOracle9Dialect.java @@ -22,26 +22,29 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.SQLException; +/** + * A Dialect for accessing Oracle through DataDirect driver + */ +@SuppressWarnings("deprecation") public class DataDirectOracle9Dialect extends Oracle9Dialect { - + @Override public int registerResultSetOutParameter(CallableStatement statement, int col) throws SQLException { - return col; // sql server just returns automatically - } - - public ResultSet getResultSet(CallableStatement ps) throws SQLException { - boolean isResultSet = ps.execute(); -// This assumes you will want to ignore any update counts - while (!isResultSet && ps.getUpdateCount() != -1) { - isResultSet = ps.getMoreResults(); - } - ResultSet rs = ps.getResultSet(); -// You may still have other ResultSets or update counts left to process here -// but you can't do it now or the ResultSet you just got will be closed - return rs; + return col; } + @Override + public ResultSet getResultSet(CallableStatement ps) throws SQLException { + boolean isResultSet = ps.execute(); + // This assumes you will want to ignore any update counts + while (!isResultSet && ps.getUpdateCount() != -1) { + isResultSet = ps.getMoreResults(); + } + + return ps.getResultSet(); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java index deab2055b5..5a2b793e45 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java @@ -48,28 +48,36 @@ import org.hibernate.sql.DerbyCaseFragment; */ @Deprecated public class DerbyDialect extends DB2Dialect { - - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, DerbyDialect.class.getName()); + @SuppressWarnings("deprecation") + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + DerbyDialect.class.getName() + ); private int driverVersionMajor; private int driverVersionMinor; + /** + * Constructs a DerbyDialect + */ + @SuppressWarnings("deprecation") public DerbyDialect() { super(); - if (this.getClass() == DerbyDialect.class) { + if ( this.getClass() == DerbyDialect.class ) { LOG.deprecatedDerbyDialect(); } + registerFunction( "concat", new DerbyConcatFunction() ); registerFunction( "trim", new AnsiTrimFunction() ); - registerColumnType( Types.BLOB, "blob" ); - determineDriverVersion(); + registerColumnType( Types.BLOB, "blob" ); + determineDriverVersion(); - if ( driverVersionMajor > 10 || ( driverVersionMajor == 10 && driverVersionMinor >= 7 ) ) { - registerColumnType( Types.BOOLEAN, "boolean" ); - } + if ( driverVersionMajor > 10 || ( driverVersionMajor == 10 && driverVersionMinor >= 7 ) ) { + registerColumnType( Types.BOOLEAN, "boolean" ); + } } - @SuppressWarnings({ "UnnecessaryUnboxing" }) + @SuppressWarnings({"UnnecessaryUnboxing", "unchecked"}) private void determineDriverVersion() { try { // locate the derby sysinfo class and query its version info @@ -91,25 +99,22 @@ public class DerbyDialect extends DB2Dialect { } @Override - public String getCrossJoinSeparator() { + public String getCrossJoinSeparator() { return ", "; } - /** - * Return the case statement modified for Cloudscape. - */ @Override - public CaseFragment createCaseFragment() { + public CaseFragment createCaseFragment() { return new DerbyCaseFragment(); } @Override - public boolean dropConstraints() { - return true; + public boolean dropConstraints() { + return true; } @Override - public boolean supportsSequences() { + public boolean supportsSequences() { // technically sequence support was added in 10.6.1.0... // // The problem though is that I am not exactly sure how to differentiate 10.6.1.0 from any other 10.6.x release. @@ -134,33 +139,34 @@ public class DerbyDialect extends DB2Dialect { } @Override - public boolean supportsLimit() { + public boolean supportsLimit() { return isTenPointFiveReleaseOrNewer(); } - //HHH-4531 @Override - public boolean supportsCommentOn() { + public boolean supportsCommentOn() { + //HHH-4531 return false; } @Override - public boolean supportsLimitOffset() { + @SuppressWarnings("deprecation") + public boolean supportsLimitOffset() { return isTenPointFiveReleaseOrNewer(); } - @Override -public String getForUpdateString() { - return " for update with rs"; - } - @Override - public String getWriteLockString(int timeout) { + public String getForUpdateString() { return " for update with rs"; } @Override - public String getReadLockString(int timeout) { + public String getWriteLockString(int timeout) { + return " for update with rs"; + } + + @Override + public String getReadLockString(int timeout) { return " for read only with rs"; } @@ -179,9 +185,8 @@ public String getForUpdateString() { * */ @Override - public String getLimitString(String query, final int offset, final int limit) { - StringBuilder sb = new StringBuilder(query.length() + 50); - + public String getLimitString(String query, final int offset, final int limit) { + final StringBuilder sb = new StringBuilder(query.length() + 50); final String normalizedSelect = query.toLowerCase().trim(); final int forUpdateIndex = normalizedSelect.lastIndexOf( "for update") ; @@ -215,7 +220,7 @@ public String getForUpdateString() { } @Override - public boolean supportsVariableLimit() { + public boolean supportsVariableLimit() { // we bind the limit and offset values directly into the sql... return false; } @@ -237,20 +242,20 @@ public String getForUpdateString() { } @Override - public String getQuerySequencesString() { - return null ; + public String getQuerySequencesString() { + return null ; } // Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @Override - public boolean supportsLobValueChangePropogation() { + public boolean supportsLobValueChangePropogation() { return false; } @Override - public boolean supportsUnboundedLobLocatorMaterialization() { + public boolean supportsUnboundedLobLocatorMaterialization() { return false; } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/DerbyTenFiveDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/DerbyTenFiveDialect.java index 0038f099c1..8cfc26f40f 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/DerbyTenFiveDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/DerbyTenFiveDialect.java @@ -36,7 +36,11 @@ import org.hibernate.dialect.function.DerbyConcatFunction; * @author Simon Johnston * @author Scott Marlow */ +@SuppressWarnings("deprecation") public class DerbyTenFiveDialect extends DerbyDialect { + /** + * Constructs a DerbyTenFiveDialect + */ public DerbyTenFiveDialect() { super(); registerFunction( "concat", new DerbyConcatFunction() ); diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/DerbyTenSevenDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/DerbyTenSevenDialect.java index 4601276171..4a3d7d8940 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/DerbyTenSevenDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/DerbyTenSevenDialect.java @@ -26,14 +26,21 @@ package org.hibernate.dialect; import java.sql.Types; /** + * Dialect for Derby 10.7 + * * @author Strong Liu */ -public class DerbyTenSevenDialect extends DerbyTenSixDialect{ - public DerbyTenSevenDialect() { - registerColumnType( Types.BOOLEAN, "boolean" ); - } +public class DerbyTenSevenDialect extends DerbyTenSixDialect { + /** + * Constructs a DerbyTenSevenDialect + */ + public DerbyTenSevenDialect() { + super(); + registerColumnType( Types.BOOLEAN, "boolean" ); + } - public String toBooleanValueString(boolean bool) { - return String.valueOf(bool); - } + @Override + public String toBooleanValueString(boolean bool) { + return String.valueOf( bool ); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/DerbyTenSixDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/DerbyTenSixDialect.java index a498610b2c..8b94f77f99 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/DerbyTenSixDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/DerbyTenSixDialect.java @@ -33,6 +33,9 @@ package org.hibernate.dialect; * @author Scott Marlow */ public class DerbyTenSixDialect extends DerbyTenFiveDialect { + /** + * Constructs a DerbyTenSixDialect + */ public DerbyTenSixDialect() { super(); } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java index d9b5d6fc96..ea5522f253 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java @@ -23,14 +23,42 @@ */ package org.hibernate.dialect; +import java.io.InputStream; +import java.io.OutputStream; +import java.sql.Blob; +import java.sql.CallableStatement; +import java.sql.Clob; +import java.sql.NClob; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Types; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import org.jboss.logging.Logger; + import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.LockOptions; import org.hibernate.MappingException; import org.hibernate.NullPrecedence; import org.hibernate.cfg.Environment; -import org.hibernate.dialect.function.*; -import org.hibernate.dialect.lock.*; +import org.hibernate.dialect.function.CastFunction; +import org.hibernate.dialect.function.SQLFunction; +import org.hibernate.dialect.function.SQLFunctionTemplate; +import org.hibernate.dialect.function.StandardAnsiSqlAggregationFunctions; +import org.hibernate.dialect.function.StandardSQLFunction; +import org.hibernate.dialect.lock.LockingStrategy; +import org.hibernate.dialect.lock.OptimisticForceIncrementLockingStrategy; +import org.hibernate.dialect.lock.OptimisticLockingStrategy; +import org.hibernate.dialect.lock.PessimisticForceIncrementLockingStrategy; +import org.hibernate.dialect.lock.PessimisticReadSelectLockingStrategy; +import org.hibernate.dialect.lock.PessimisticWriteSelectLockingStrategy; +import org.hibernate.dialect.lock.SelectLockingStrategy; import org.hibernate.dialect.pagination.LegacyLimitHandler; import org.hibernate.dialect.pagination.LimitHandler; import org.hibernate.dialect.unique.DefaultUniqueDelegate; @@ -52,39 +80,47 @@ import org.hibernate.internal.util.collections.ArrayHelper; import org.hibernate.internal.util.io.StreamCopier; import org.hibernate.mapping.Column; import org.hibernate.persister.entity.Lockable; -import org.hibernate.sql.*; +import org.hibernate.sql.ANSICaseFragment; +import org.hibernate.sql.ANSIJoinFragment; +import org.hibernate.sql.CaseFragment; +import org.hibernate.sql.ForUpdateFragment; +import org.hibernate.sql.JoinFragment; import org.hibernate.type.StandardBasicTypes; import org.hibernate.type.descriptor.sql.ClobTypeDescriptor; import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; -import org.jboss.logging.Logger; - -import java.io.InputStream; -import java.io.OutputStream; -import java.sql.*; -import java.util.*; /** - * Represents a dialect of SQL implemented by a particular RDBMS. - * Subclasses implement Hibernate compatibility with different systems.
- *
- * Subclasses should provide a public default constructor that register() - * a set of type mappings and default Hibernate properties.
- *
- * Subclasses should be immutable. + * Represents a dialect of SQL implemented by a particular RDBMS. Subclasses implement Hibernate compatibility + * with different systems. Subclasses should provide a public default constructor that register a set of type + * mappings and default Hibernate properties. Subclasses should be immutable. * * @author Gavin King, David Channon */ +@SuppressWarnings("deprecation") public abstract class Dialect implements ConversionContext { + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + Dialect.class.getName() + ); - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, Dialect.class.getName()); - + /** + * Defines a default batch size constant + */ public static final String DEFAULT_BATCH_SIZE = "15"; + + /** + * Defines a "no batching" batch size constant + */ public static final String NO_BATCH = "0"; /** - * Characters used for quoting SQL identifiers + * Characters used as opening for quoting SQL identifiers */ public static final String QUOTE = "`\"["; + + /** + * Characters used as closing for quoting SQL identifiers + */ public static final String CLOSED_QUOTE = "`\"]"; private final TypeNames typeNames = new TypeNames(); @@ -93,7 +129,7 @@ public abstract class Dialect implements ConversionContext { private final Properties properties = new Properties(); private final Map sqlFunctions = new HashMap(); private final Set sqlKeywords = new HashSet(); - + private final UniqueDelegate uniqueDelegate; @@ -158,14 +194,14 @@ public abstract class Dialect implements ConversionContext { registerColumnType( Types.LONGNVARCHAR, "nvarchar($l)" ); registerColumnType( Types.NCLOB, "nclob" ); - // register hibernate types for default use in scalar sqlquery type auto detection + // register hibernate types for default use in scalar sqlquery type auto detection registerHibernateType( Types.BIGINT, StandardBasicTypes.BIG_INTEGER.getName() ); registerHibernateType( Types.BINARY, StandardBasicTypes.BINARY.getName() ); registerHibernateType( Types.BIT, StandardBasicTypes.BOOLEAN.getName() ); registerHibernateType( Types.BOOLEAN, StandardBasicTypes.BOOLEAN.getName() ); registerHibernateType( Types.CHAR, StandardBasicTypes.CHARACTER.getName() ); - registerHibernateType( Types.CHAR, 1, StandardBasicTypes.CHARACTER.getName() ); - registerHibernateType( Types.CHAR, 255, StandardBasicTypes.STRING.getName() ); + registerHibernateType( Types.CHAR, 1, StandardBasicTypes.CHARACTER.getName() ); + registerHibernateType( Types.CHAR, 255, StandardBasicTypes.STRING.getName() ); registerHibernateType( Types.DATE, StandardBasicTypes.DATE.getName() ); registerHibernateType( Types.DOUBLE, StandardBasicTypes.DOUBLE.getName() ); registerHibernateType( Types.FLOAT, StandardBasicTypes.FLOAT.getName() ); @@ -183,7 +219,7 @@ public abstract class Dialect implements ConversionContext { registerHibernateType( Types.BLOB, StandardBasicTypes.BLOB.getName() ); registerHibernateType( Types.CLOB, StandardBasicTypes.CLOB.getName() ); registerHibernateType( Types.REAL, StandardBasicTypes.FLOAT.getName() ); - + uniqueDelegate = new DefaultUniqueDelegate( this ); } @@ -194,8 +230,7 @@ public abstract class Dialect implements ConversionContext { * @throws HibernateException If no dialect was specified, or if it could not be instantiated. */ public static Dialect getDialect() throws HibernateException { - String dialectName = Environment.getProperties().getProperty( Environment.DIALECT ); - return instantiateDialect( dialectName ); + return instantiateDialect( Environment.getProperties().getProperty( Environment.DIALECT ) ); } @@ -208,7 +243,7 @@ public abstract class Dialect implements ConversionContext { * @throws HibernateException If no dialect was specified, or if it could not be instantiated. */ public static Dialect getDialect(Properties props) throws HibernateException { - String dialectName = props.getProperty( Environment.DIALECT ); + final String dialectName = props.getProperty( Environment.DIALECT ); if ( dialectName == null ) { return getDialect(); } @@ -220,7 +255,7 @@ public abstract class Dialect implements ConversionContext { throw new HibernateException( "The dialect was not set. Set the property hibernate.dialect." ); } try { - return ( Dialect ) ReflectHelper.classForName( dialectName ).newInstance(); + return (Dialect) ReflectHelper.classForName( dialectName ).newInstance(); } catch ( ClassNotFoundException cnfe ) { throw new HibernateException( "Dialect class not found: " + dialectName ); @@ -240,7 +275,7 @@ public abstract class Dialect implements ConversionContext { } @Override - public String toString() { + public String toString() { return getClass().getName(); } @@ -256,7 +291,7 @@ public abstract class Dialect implements ConversionContext { * @throws HibernateException If no mapping was specified for that type. */ public String getTypeName(int code) throws HibernateException { - String result = typeNames.get( code ); + final String result = typeNames.get( code ); if ( result == null ) { throw new HibernateException( "No default type mapping for (java.sql.Types) " + code ); } @@ -276,9 +311,11 @@ public abstract class Dialect implements ConversionContext { * @throws HibernateException If no mapping was specified for that type. */ public String getTypeName(int code, long length, int precision, int scale) throws HibernateException { - String result = typeNames.get( code, length, precision, scale ); + final String result = typeNames.get( code, length, precision, scale ); if ( result == null ) { - throw new HibernateException(String.format( "No type mapping for java.sql.Types code: %s, length: %s", code, length )); + throw new HibernateException( + String.format( "No type mapping for java.sql.Types code: %s, length: %s", code, length ) + ); } return result; } @@ -294,6 +331,17 @@ public abstract class Dialect implements ConversionContext { return getTypeName( code, Column.DEFAULT_LENGTH, Column.DEFAULT_PRECISION, Column.DEFAULT_SCALE ); } + /** + * Return an expression casting the value to the specified type + * + * @param value The value to cast + * @param jdbcTypeCode The JDBC type code to cast to + * @param length The type length + * @param precision The type precision + * @param scale The type scale + * + * @return The cast expression + */ public String cast(String value, int jdbcTypeCode, int length, int precision, int scale) { if ( jdbcTypeCode == Types.CHAR ) { return "cast(" + value + " as char(" + length + "))"; @@ -303,10 +351,32 @@ public abstract class Dialect implements ConversionContext { } } + /** + * Return an expression casting the value to the specified type. Simply calls + * {@link #cast(String, int, int, int, int)} passing {@link Column#DEFAULT_PRECISION} and + * {@link Column#DEFAULT_SCALE} as the precision/scale. + * + * @param value The value to cast + * @param jdbcTypeCode The JDBC type code to cast to + * @param length The type length + * + * @return The cast expression + */ public String cast(String value, int jdbcTypeCode, int length) { return cast( value, jdbcTypeCode, length, Column.DEFAULT_PRECISION, Column.DEFAULT_SCALE ); } + /** + * Return an expression casting the value to the specified type. Simply calls + * {@link #cast(String, int, int, int, int)} passing {@link Column#DEFAULT_LENGTH} as the length + * + * @param value The value to cast + * @param jdbcTypeCode The JDBC type code to cast to + * @param precision The type precision + * @param scale The type scale + * + * @return The cast expression + */ public String cast(String value, int jdbcTypeCode, int precision, int scale) { return cast( value, jdbcTypeCode, Column.DEFAULT_LENGTH, precision, scale ); } @@ -417,8 +487,10 @@ public abstract class Dialect implements ConversionContext { public Blob mergeBlob(Blob original, Blob target, SessionImplementor session) { if ( original != target ) { try { - OutputStream connectedStream = target.setBinaryStream( 1L ); // the BLOB just read during the load phase of merge - InputStream detachedStream = original.getBinaryStream(); // the BLOB from the detached state + // the BLOB just read during the load phase of merge + final OutputStream connectedStream = target.setBinaryStream( 1L ); + // the BLOB from the detached state + final InputStream detachedStream = original.getBinaryStream(); StreamCopier.copy( detachedStream, connectedStream ); return target; } @@ -435,8 +507,10 @@ public abstract class Dialect implements ConversionContext { public Clob mergeClob(Clob original, Clob target, SessionImplementor session) { if ( original != target ) { try { - OutputStream connectedStream = target.setAsciiStream( 1L ); // the CLOB just read during the load phase of merge - InputStream detachedStream = original.getAsciiStream(); // the CLOB from the detached state + // the CLOB just read during the load phase of merge + final OutputStream connectedStream = target.setAsciiStream( 1L ); + // the CLOB from the detached state + final InputStream detachedStream = original.getAsciiStream(); StreamCopier.copy( detachedStream, connectedStream ); return target; } @@ -453,8 +527,10 @@ public abstract class Dialect implements ConversionContext { public NClob mergeNClob(NClob original, NClob target, SessionImplementor session) { if ( original != target ) { try { - OutputStream connectedStream = target.setAsciiStream( 1L ); // the NCLOB just read during the load phase of merge - InputStream detachedStream = original.getAsciiStream(); // the NCLOB from the detached state + // the NCLOB just read during the load phase of merge + final OutputStream connectedStream = target.setAsciiStream( 1L ); + // the NCLOB from the detached state + final InputStream detachedStream = original.getAsciiStream(); StreamCopier.copy( detachedStream, connectedStream ); return target; } @@ -478,7 +554,7 @@ public abstract class Dialect implements ConversionContext { return null; } try { - LobCreator lobCreator = session.getFactory().getJdbcServices().getLobCreator( session ); + final LobCreator lobCreator = session.getFactory().getJdbcServices().getLobCreator( session ); return original == null ? lobCreator.createBlob( ArrayHelper.EMPTY_BYTE_ARRAY ) : lobCreator.createBlob( original.getBinaryStream(), original.length() ); @@ -494,7 +570,7 @@ public abstract class Dialect implements ConversionContext { return null; } try { - LobCreator lobCreator = session.getFactory().getJdbcServices().getLobCreator( session ); + final LobCreator lobCreator = session.getFactory().getJdbcServices().getLobCreator( session ); return original == null ? lobCreator.createClob( "" ) : lobCreator.createClob( original.getCharacterStream(), original.length() ); @@ -510,7 +586,7 @@ public abstract class Dialect implements ConversionContext { return null; } try { - LobCreator lobCreator = session.getFactory().getJdbcServices().getLobCreator( session ); + final LobCreator lobCreator = session.getFactory().getJdbcServices().getLobCreator( session ); return original == null ? lobCreator.createNClob( "" ) : lobCreator.createNClob( original.getCharacterStream(), original.length() ); @@ -538,7 +614,7 @@ public abstract class Dialect implements ConversionContext { */ @SuppressWarnings( {"UnusedDeclaration"}) public String getHibernateTypeName(int code) throws HibernateException { - String result = hibernateTypeNames.get( code ); + final String result = hibernateTypeNames.get( code ); if ( result == null ) { throw new HibernateException( "No Hibernate type mapping for java.sql.Types code: " + code ); } @@ -558,13 +634,14 @@ public abstract class Dialect implements ConversionContext { * @throws HibernateException If no mapping was specified for that type. */ public String getHibernateTypeName(int code, int length, int precision, int scale) throws HibernateException { - String result = hibernateTypeNames.get( code, length, precision, scale ); + final String result = hibernateTypeNames.get( code, length, precision, scale ); if ( result == null ) { throw new HibernateException( - "No Hibernate type mapping for java.sql.Types code: " + - code + - ", length: " + - length + String.format( + "No Hibernate type mapping for type [code=%s, length=%s]", + code, + length + ) ); } return result; @@ -813,7 +890,7 @@ public abstract class Dialect implements ConversionContext { * @deprecated Use {@link #getCreateSequenceString(String, int, int)} instead */ @Deprecated - public String[] getCreateSequenceStrings(String sequenceName) throws MappingException { + public String[] getCreateSequenceStrings(String sequenceName) throws MappingException { return new String[] { getCreateSequenceString( sequenceName ) }; } @@ -1130,20 +1207,20 @@ public abstract class Dialect implements ConversionContext { * @since 3.2 */ public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) { - switch ( lockMode ) { - case PESSIMISTIC_FORCE_INCREMENT: - return new PessimisticForceIncrementLockingStrategy( lockable, lockMode ); - case PESSIMISTIC_WRITE: - return new PessimisticWriteSelectLockingStrategy( lockable, lockMode ); - case PESSIMISTIC_READ: - return new PessimisticReadSelectLockingStrategy( lockable, lockMode ); - case OPTIMISTIC: - return new OptimisticLockingStrategy( lockable, lockMode ); - case OPTIMISTIC_FORCE_INCREMENT: - return new OptimisticForceIncrementLockingStrategy( lockable, lockMode ); - default: - return new SelectLockingStrategy( lockable, lockMode ); - } + switch ( lockMode ) { + case PESSIMISTIC_FORCE_INCREMENT: + return new PessimisticForceIncrementLockingStrategy( lockable, lockMode ); + case PESSIMISTIC_WRITE: + return new PessimisticWriteSelectLockingStrategy( lockable, lockMode ); + case PESSIMISTIC_READ: + return new PessimisticReadSelectLockingStrategy( lockable, lockMode ); + case OPTIMISTIC: + return new OptimisticLockingStrategy( lockable, lockMode ); + case OPTIMISTIC_FORCE_INCREMENT: + return new OptimisticForceIncrementLockingStrategy( lockable, lockMode ); + default: + return new SelectLockingStrategy( lockable, lockMode ); + } } /** @@ -1153,29 +1230,29 @@ public abstract class Dialect implements ConversionContext { * @return The appropriate for update fragment. */ public String getForUpdateString(LockOptions lockOptions) { - LockMode lockMode = lockOptions.getLockMode(); - return getForUpdateString( lockMode, lockOptions.getTimeOut() ); + final LockMode lockMode = lockOptions.getLockMode(); + return getForUpdateString( lockMode, lockOptions.getTimeOut() ); } - @SuppressWarnings( {"deprecation"}) + @SuppressWarnings( {"deprecation"}) private String getForUpdateString(LockMode lockMode, int timeout){ - switch ( lockMode ) { - case UPGRADE: - return getForUpdateString(); - case PESSIMISTIC_READ: - return getReadLockString( timeout ); - case PESSIMISTIC_WRITE: - return getWriteLockString( timeout ); - case UPGRADE_NOWAIT: - case FORCE: - case PESSIMISTIC_FORCE_INCREMENT: - return getForUpdateNowaitString(); - case UPGRADE_SKIPLOCKED: - return getForUpdateSkipLockedString(); - default: - return ""; - } - } + switch ( lockMode ) { + case UPGRADE: + return getForUpdateString(); + case PESSIMISTIC_READ: + return getReadLockString( timeout ); + case PESSIMISTIC_WRITE: + return getWriteLockString( timeout ); + case UPGRADE_NOWAIT: + case FORCE: + case PESSIMISTIC_FORCE_INCREMENT: + return getForUpdateNowaitString(); + case UPGRADE_SKIPLOCKED: + return getForUpdateSkipLockedString(); + default: + return ""; + } + } /** * Given a lock mode, determine the appropriate for update fragment to use. @@ -1267,12 +1344,12 @@ public abstract class Dialect implements ConversionContext { @SuppressWarnings( {"unchecked"}) public String getForUpdateString(String aliases, LockOptions lockOptions) { LockMode lockMode = lockOptions.getLockMode(); - Iterator> itr = lockOptions.getAliasLockIterator(); + final Iterator> itr = lockOptions.getAliasLockIterator(); while ( itr.hasNext() ) { // seek the highest lock mode final Map.Entryentry = itr.next(); final LockMode lm = entry.getValue(); - if ( lm.greaterThan(lockMode) ) { + if ( lm.greaterThan( lockMode ) ) { lockMode = lm; } } @@ -1291,10 +1368,10 @@ public abstract class Dialect implements ConversionContext { } /** - * Retrieves the FOR UPDATE SKIP LOCKED syntax specific to this dialect. - * - * @return The appropriate FOR UPDATE SKIP LOCKED clause string. - */ + * Retrieves the FOR UPDATE SKIP LOCKED syntax specific to this dialect. + * + * @return The appropriate FOR UPDATE SKIP LOCKED clause string. + */ public String getForUpdateSkipLockedString() { // by default we report no support for SKIP_LOCKED lock semantics return getForUpdateString(); @@ -1311,7 +1388,7 @@ public abstract class Dialect implements ConversionContext { return getForUpdateString( aliases ); } - /** + /** * Get the FOR UPDATE OF column_list SKIP LOCKED fragment appropriate * for this dialect given the aliases of the columns to be write locked. * @@ -1498,8 +1575,8 @@ public abstract class Dialect implements ConversionContext { public int registerResultSetOutParameter(CallableStatement statement, int position) throws SQLException { throw new UnsupportedOperationException( getClass().getName() + - " does not support resultsets via stored procedures" - ); + " does not support resultsets via stored procedures" + ); } /** @@ -1531,9 +1608,8 @@ public abstract class Dialect implements ConversionContext { */ public ResultSet getResultSet(CallableStatement statement) throws SQLException { throw new UnsupportedOperationException( - getClass().getName() + - " does not support resultsets via stored procedures" - ); + getClass().getName() + " does not support resultsets via stored procedures" + ); } /** @@ -1549,8 +1625,7 @@ public abstract class Dialect implements ConversionContext { */ public ResultSet getResultSet(CallableStatement statement, int position) throws SQLException { throw new UnsupportedOperationException( - getClass().getName() + - " does not support resultsets via stored procedures" + getClass().getName() + " does not support resultsets via stored procedures" ); } @@ -1567,8 +1642,7 @@ public abstract class Dialect implements ConversionContext { */ public ResultSet getResultSet(CallableStatement statement, String name) throws SQLException { throw new UnsupportedOperationException( - getClass().getName() + - " does not support resultsets via stored procedures" + getClass().getName() + " does not support resultsets via stored procedures" ); } @@ -1677,6 +1751,8 @@ public abstract class Dialect implements ConversionContext { * the a vendor-specific ErrorCode rather than the SQLState. *

* Specific Dialects may override to return whatever is most appropriate for that vendor. + * + * @return The SQLExceptionConversionDelegate for this dialect */ public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() { return null; @@ -1767,6 +1843,7 @@ public abstract class Dialect implements ConversionContext { /** * The name of the SQL function that can do case insensitive like comparison. + * * @return The dialect-specific "case insensitive" like function. */ public String getCaseInsensitiveLike(){ @@ -1774,8 +1851,10 @@ public abstract class Dialect implements ConversionContext { } /** - * @return {@code true} if the underlying Database supports case insensitive like comparison, {@code false} otherwise. - * The default is {@code false}. + * Does this dialect support case insensitive LIKE restrictions? + * + * @return {@code true} if the underlying database supports case insensitive like comparison, + * {@code false} otherwise. The default is {@code false}. */ public boolean supportsCaseInsensitiveLike(){ return false; @@ -1949,7 +2028,7 @@ public abstract class Dialect implements ConversionContext { String referencedTable, String[] primaryKey, boolean referencesPrimaryKey) { - StringBuilder res = new StringBuilder( 30 ); + final StringBuilder res = new StringBuilder( 30 ); res.append( " add constraint " ) .append( constraintName ) @@ -1977,6 +2056,11 @@ public abstract class Dialect implements ConversionContext { return " add constraint " + constraintName + " primary key "; } + /** + * Does the database/driver have bug in deleting rows that refer to other rows being deleted in the same query? + * + * @return {@code true} if the database/driver has this bug + */ public boolean hasSelfReferentialForeignKeyBug() { return false; } @@ -1990,28 +2074,68 @@ public abstract class Dialect implements ConversionContext { return ""; } + /** + * Does this dialect/database support commenting on tables, columns, etc? + * + * @return {@code true} if commenting is supported + */ public boolean supportsCommentOn() { return false; } + /** + * Get the comment into a form supported for table definition. + * + * @param comment The comment to apply + * + * @return The comment fragment + */ public String getTableComment(String comment) { return ""; } + /** + * Get the comment into a form supported for column definition. + * + * @param comment The comment to apply + * + * @return The comment fragment + */ public String getColumnComment(String comment) { return ""; } + /** + * For dropping a table, can the phrase "if exists" be applied before the table name? + *

+ * NOTE : Only one or the other (or neither) of this and {@link #supportsIfExistsAfterTableName} should return true + * + * @return {@code true} if the "if exists" can be applied before the table name + */ public boolean supportsIfExistsBeforeTableName() { return false; } + /** + * For dropping a table, can the phrase "if exists" be applied after the table name? + *

+ * NOTE : Only one or the other (or neither) of this and {@link #supportsIfExistsBeforeTableName} should return true + * + * @return {@code true} if the "if exists" can be applied after the table name + */ public boolean supportsIfExistsAfterTableName() { return false; } - - public String getDropTableString( String tableName ) { - StringBuilder buf = new StringBuilder( "drop table " ); + + /** + * Generate a DROP TABLE statement + * + * @param tableName The name of the table to drop + * + * @return The DROP TABLE command + */ + public String getDropTableString(String tableName) { + final StringBuilder buf = new StringBuilder( "drop table " ); if ( supportsIfExistsBeforeTableName() ) { buf.append( "if exists " ); } @@ -2042,6 +2166,11 @@ public abstract class Dialect implements ConversionContext { return true; } + /** + * Does this dialect support cascaded delete on foreign key definitions? + * + * @return {@code true} indicates that the dialect does support cascaded delete on foreign keys. + */ public boolean supportsCascadeDelete() { return true; } @@ -2056,12 +2185,13 @@ public abstract class Dialect implements ConversionContext { } /** - * @return Returns the separator to use for defining cross joins when translating HQL queries. + * Returns the separator to use for defining cross joins when translating HQL queries. *

* Typically this will be either [ cross join ] or [, ] *

* Note that the spaces are important! * + * @return The cross join separator */ public String getCrossJoinSeparator() { return " cross join "; @@ -2165,6 +2295,8 @@ public abstract class Dialect implements ConversionContext { } /** + * Renders an ordering fragment + * * @param expression The SQL order expression. In case of {@code @OrderBy} annotation user receives property placeholder * (e.g. attribute name enclosed in '{' and '}' signs). * @param collation Collation string in format {@code collate IDENTIFIER}, or {@code null} @@ -2379,11 +2511,11 @@ public abstract class Dialect implements ConversionContext { return false; } - /** - * Does this dialect support `count(distinct a,b)`? - * - * @return True if the database supports counting distinct tuples; false otherwise. - */ + /** + * Does this dialect support `count(distinct a,b)`? + * + * @return True if the database supports counting distinct tuples; false otherwise. + */ public boolean supportsTupleDistinctCounts() { // oddly most database in fact seem to, so true is the default. return true; @@ -2392,17 +2524,17 @@ public abstract class Dialect implements ConversionContext { /** * Return the limit that the underlying database places on the number elements in an {@code IN} predicate. * If the database defines no such limits, simply return zero or less-than-zero. - * + * * @return int The limit, or zero-or-less to indicate no limit. */ public int getInExpressionCountLimit() { return 0; } - + /** * HHH-4635 * Oracle expects all Lob values to be last in inserts and updates. - * + * * @return boolean True of Lob values should be last, false if it * does not matter. */ @@ -2421,20 +2553,32 @@ public abstract class Dialect implements ConversionContext { public boolean useFollowOnLocking() { return false; } - - public UniqueDelegate getUniqueDelegate() { - return uniqueDelegate; + + /** + * Negate an expression + * + * @param expression The expression to negate + * + * @return The negated expression + */ + public String getNotExpression(String expression) { + return "not " + expression; } - public String getNotExpression( String expression ) { - return "not " + expression; + /** + * Get the UniqueDelegate supported by this dialect + * + * @return The UniqueDelegate + */ + public UniqueDelegate getUniqueDelegate() { + return uniqueDelegate; } /** * Does this dialect support the UNIQUE column syntax? * * @return boolean - * + * * @deprecated {@link #getUniqueDelegate()} should be overridden instead. */ @Deprecated @@ -2442,32 +2586,36 @@ public abstract class Dialect implements ConversionContext { return true; } - /** - * Does this dialect support adding Unique constraints via create and alter table ? - * - * @return boolean - * - * @deprecated {@link #getUniqueDelegate()} should be overridden instead. - */ + /** + * Does this dialect support adding Unique constraints via create and alter table ? + * + * @return boolean + * + * @deprecated {@link #getUniqueDelegate()} should be overridden instead. + */ @Deprecated public boolean supportsUniqueConstraintInCreateAlterTable() { - return true; + return true; } - /** - * The syntax used to add a unique constraint to a table. - * - * @param constraintName The name of the unique constraint. - * @return The "add unique" fragment - * - * @deprecated {@link #getUniqueDelegate()} should be overridden instead. - */ + /** + * The syntax used to add a unique constraint to a table. + * + * @param constraintName The name of the unique constraint. + * @return The "add unique" fragment + * + * @deprecated {@link #getUniqueDelegate()} should be overridden instead. + */ @Deprecated public String getAddUniqueConstraintString(String constraintName) { - return " add constraint " + constraintName + " unique "; - } + return " add constraint " + constraintName + " unique "; + } /** + * Is the combination of not-null and unique supported? + * + * @return deprecated + * * @deprecated {@link #getUniqueDelegate()} should be overridden instead. */ @Deprecated diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/FirebirdDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/FirebirdDialect.java index ddc6a787fe..c45d30b515 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/FirebirdDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/FirebirdDialect.java @@ -23,18 +23,18 @@ */ package org.hibernate.dialect; - /** * An SQL dialect for Firebird. * * @author Reha CENANI */ public class FirebirdDialect extends InterbaseDialect { - + @Override public String getDropSequenceString(String sequenceName) { return "drop generator " + sequenceName; } + @Override public String getLimitString(String sql, boolean hasOffset) { return new StringBuilder( sql.length() + 20 ) .append( sql ) @@ -42,12 +42,13 @@ public class FirebirdDialect extends InterbaseDialect { .toString(); } + @Override public boolean bindLimitParametersFirst() { return true; } + @Override public boolean bindLimitParametersInReverseOrder() { return true; } - } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/FrontBaseDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/FrontBaseDialect.java index d6808c7a25..035fffd8d4 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/FrontBaseDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/FrontBaseDialect.java @@ -53,6 +53,9 @@ import org.hibernate.persister.entity.Lockable; */ public class FrontBaseDialect extends Dialect { + /** + * Constructs a FrontBaseDialect + */ public FrontBaseDialect() { super(); @@ -74,37 +77,43 @@ public class FrontBaseDialect extends Dialect { registerColumnType( Types.CLOB, "clob" ); } + @Override public String getAddColumnString() { return "add column"; } + @Override public String getCascadeConstraintsString() { return " cascade"; } + @Override public boolean dropConstraints() { return false; } /** - * Does this dialect support the FOR UPDATE syntax. No! - * - * @return false always. FrontBase doesn't support this syntax, - * which was dropped with SQL92 + * FrontBase doesn't support this syntax, which was dropped with SQL92. + *

+ * {@inheritDoc} */ + @Override public String getForUpdateString() { return ""; } - public String getCurrentTimestampCallString() { + @Override + public String getCurrentTimestampSelectString() { // TODO : not sure this is correct, could not find docs on how to do this. return "{?= call current_timestamp}"; } + @Override public boolean isCurrentTimestampSelectStringCallable() { return true; } + @Override public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) { // Frontbase has no known variation of a "SELECT ... FOR UPDATE" syntax... if ( lockMode==LockMode.PESSIMISTIC_FORCE_INCREMENT) { diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java index 288e205985..e085a9ba18 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/H2Dialect.java @@ -50,11 +50,16 @@ import java.sql.Types; * @author Thomas Mueller */ public class H2Dialect extends Dialect { - - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, H2Dialect.class.getName()); + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + H2Dialect.class.getName() + ); private final String querySequenceString; + /** + * Constructs a H2Dialect + */ public H2Dialect() { super(); @@ -62,13 +67,13 @@ public class H2Dialect extends Dialect { try { // HHH-2300 final Class h2ConstantsClass = ReflectHelper.classForName( "org.h2.engine.Constants" ); - final int majorVersion = ( Integer ) h2ConstantsClass.getDeclaredField( "VERSION_MAJOR" ).get( null ); - final int minorVersion = ( Integer ) h2ConstantsClass.getDeclaredField( "VERSION_MINOR" ).get( null ); - final int buildId = ( Integer ) h2ConstantsClass.getDeclaredField( "BUILD_ID" ).get( null ); + final int majorVersion = (Integer) h2ConstantsClass.getDeclaredField( "VERSION_MAJOR" ).get( null ); + final int minorVersion = (Integer) h2ConstantsClass.getDeclaredField( "VERSION_MINOR" ).get( null ); + final int buildId = (Integer) h2ConstantsClass.getDeclaredField( "BUILD_ID" ).get( null ); if ( buildId < 32 ) { querySequenceString = "select name from information_schema.sequences"; } - if ( ! ( majorVersion > 1 || minorVersion > 2 || buildId >= 139 ) ) { + if ( ! ( majorVersion > 1 || minorVersion > 2 || buildId >= 139 ) ) { LOG.unsupportedMultiTableBulkHqlJpaql( majorVersion, minorVersion, buildId ); } } @@ -190,89 +195,107 @@ public class H2Dialect extends Dialect { registerFunction( "user", new NoArgSQLFunction( "user", StandardBasicTypes.STRING ) ); getDefaultProperties().setProperty( AvailableSettings.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE ); - getDefaultProperties().setProperty( AvailableSettings.NON_CONTEXTUAL_LOB_CREATION, "true" ); // http://code.google.com/p/h2database/issues/detail?id=235 + // http://code.google.com/p/h2database/issues/detail?id=235 + getDefaultProperties().setProperty( AvailableSettings.NON_CONTEXTUAL_LOB_CREATION, "true" ); } + @Override public String getAddColumnString() { return "add column"; } + @Override public boolean supportsIdentityColumns() { return true; } + @Override public String getIdentityColumnString() { - return "generated by default as identity"; // not null is implicit + // not null is implicit + return "generated by default as identity"; } + @Override public String getIdentitySelectString() { return "call identity()"; } + @Override public String getIdentityInsertString() { return "null"; } + @Override public String getForUpdateString() { return " for update"; } + @Override public boolean supportsLimit() { return true; } + @Override public String getLimitString(String sql, boolean hasOffset) { - return new StringBuilder( sql.length() + 20 ) - .append( sql ) - .append( hasOffset ? " limit ? offset ?" : " limit ?" ) - .toString(); + return sql + (hasOffset ? " limit ? offset ?" : " limit ?"); } + @Override public boolean bindLimitParametersInReverseOrder() { return true; } + @Override public boolean bindLimitParametersFirst() { return false; } + @Override public boolean supportsIfExistsAfterTableName() { return true; } + @Override public boolean supportsSequences() { return true; } + @Override public boolean supportsPooledSequences() { return true; } + @Override public String getCreateSequenceString(String sequenceName) { return "create sequence " + sequenceName; } + @Override public String getDropSequenceString(String sequenceName) { return "drop sequence " + sequenceName; } + @Override public String getSelectSequenceNextValString(String sequenceName) { return "next value for " + sequenceName; } + @Override public String getSequenceNextValString(String sequenceName) { return "call next value for " + sequenceName; } + @Override public String getQuerySequencesString() { return querySequenceString; } + @Override public ViolatedConstraintNameExtracter getViolatedConstraintNameExtracter() { return EXTRACTER; } - private static ViolatedConstraintNameExtracter EXTRACTER = new TemplatedViolatedConstraintNameExtracter() { + private static final ViolatedConstraintNameExtracter EXTRACTER = new TemplatedViolatedConstraintNameExtracter() { /** * Extract the name of the violated constraint from the given SQLException. * @@ -285,7 +308,7 @@ public class H2Dialect extends Dialect { // 23001: Unique index or primary key violation: {0} if ( sqle.getSQLState().startsWith( "23" ) ) { final String message = sqle.getMessage(); - int idx = message.indexOf( "violation: " ); + final int idx = message.indexOf( "violation: " ); if ( idx > 0 ) { constraintName = message.substring( idx + "violation: ".length() ); } @@ -293,34 +316,33 @@ public class H2Dialect extends Dialect { return constraintName; } }; - + @Override public SQLExceptionConversionDelegate buildSQLExceptionConversionDelegate() { SQLExceptionConversionDelegate delegate = super.buildSQLExceptionConversionDelegate(); if (delegate == null) { delegate = new SQLExceptionConversionDelegate() { - @Override public JDBCException convert(SQLException sqlException, String message, String sql) { - JDBCException exception = null; + final int errorCode = JdbcExceptionHelper.extractErrorCode( sqlException ); - int errorCode = JdbcExceptionHelper.extractErrorCode(sqlException); + if (40001 == errorCode) { + // DEADLOCK DETECTED + return new LockAcquisitionException(message, sqlException, sql); + } - if (40001 == errorCode) { // DEADLOCK DETECTED - exception = new LockAcquisitionException(message, sqlException, sql); - } - - if (50200 == errorCode) { // LOCK NOT AVAILABLE - exception = new PessimisticLockException(message, sqlException, sql); - } + if (50200 == errorCode) { + // LOCK NOT AVAILABLE + return new PessimisticLockException(message, sqlException, sql); + } if ( 90006 == errorCode ) { // NULL not allowed for column [90006-145] final String constraintName = getViolatedConstraintNameExtracter().extractConstraintName( sqlException ); - exception = new ConstraintViolationException( message, sqlException, sql, constraintName ); + return new ConstraintViolationException( message, sqlException, sql, constraintName ); } - return exception; + return null; } }; } @@ -356,18 +378,22 @@ public class H2Dialect extends Dialect { return false; } + @Override public boolean supportsCurrentTimestampSelection() { return true; } + @Override public boolean isCurrentTimestampSelectStringCallable() { return false; } + @Override public String getCurrentTimestampSelectString() { return "call current_timestamp()"; } + @Override public boolean supportsUnionAll() { return true; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java index 10435c2aa9..18bc9b3cbd 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java @@ -66,8 +66,10 @@ import org.jboss.logging.Logger; * @author Fred Toussi */ public class HSQLDialect extends Dialect { - - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, HSQLDialect.class.getName()); + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + HSQLDialect.class.getName() + ); /** * version is 18 for 1.8 or 20 for 2.0 @@ -75,12 +77,15 @@ public class HSQLDialect extends Dialect { private int hsqldbVersion = 18; + /** + * Constructs a HSQLDialect + */ public HSQLDialect() { super(); try { - Class props = ReflectHelper.classForName( "org.hsqldb.persist.HsqlDatabaseProperties" ); - String versionString = (String) props.getDeclaredField( "THIS_VERSION" ).get( null ); + final Class props = ReflectHelper.classForName( "org.hsqldb.persist.HsqlDatabaseProperties" ); + final String versionString = (String) props.getDeclaredField( "THIS_VERSION" ).get( null ); hsqldbVersion = Integer.parseInt( versionString.substring( 0, 1 ) ) * 10; hsqldbVersion += Integer.parseInt( versionString.substring( 2, 3 ) ); @@ -92,7 +97,7 @@ public class HSQLDialect extends Dialect { registerColumnType( Types.BIGINT, "bigint" ); registerColumnType( Types.BINARY, "binary($l)" ); registerColumnType( Types.BIT, "bit" ); - registerColumnType( Types.BOOLEAN, "boolean" ); + registerColumnType( Types.BOOLEAN, "boolean" ); registerColumnType( Types.CHAR, "char($l)" ); registerColumnType( Types.DATE, "date" ); @@ -152,9 +157,9 @@ public class HSQLDialect extends Dialect { // datetime functions if ( hsqldbVersion < 20 ) { - registerFunction( "sysdate", new NoArgSQLFunction( "sysdate", StandardBasicTypes.DATE, false ) ); + registerFunction( "sysdate", new NoArgSQLFunction( "sysdate", StandardBasicTypes.DATE, false ) ); } else { - registerFunction( "sysdate", new NoArgSQLFunction( "sysdate", StandardBasicTypes.TIMESTAMP, false ) ); + registerFunction( "sysdate", new NoArgSQLFunction( "sysdate", StandardBasicTypes.TIMESTAMP, false ) ); } registerFunction( "current_date", new NoArgSQLFunction( "current_date", StandardBasicTypes.DATE, false ) ); registerFunction( "curdate", new NoArgSQLFunction( "curdate", StandardBasicTypes.DATE ) ); @@ -208,8 +213,7 @@ public class HSQLDialect extends Dialect { // special functions // from v. 2.2.0 ROWNUM() is supported in all modes as the equivalent of Oracle ROWNUM if ( hsqldbVersion > 21 ) { - registerFunction("rownum", - new NoArgSQLFunction("rownum", StandardBasicTypes.INTEGER)); + registerFunction( "rownum", new NoArgSQLFunction( "rownum", StandardBasicTypes.INTEGER ) ); } // function templates @@ -218,30 +222,38 @@ public class HSQLDialect extends Dialect { getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE ); } + @Override public String getAddColumnString() { return "add column"; } + @Override public boolean supportsIdentityColumns() { return true; } + @Override public String getIdentityColumnString() { - return "generated by default as identity (start with 1)"; //not null is implicit + //not null is implicit + return "generated by default as identity (start with 1)"; } + @Override public String getIdentitySelectString() { return "call identity()"; } + @Override public String getIdentityInsertString() { return hsqldbVersion < 20 ? "null" : "default"; } + @Override public boolean supportsLockTimeouts() { return false; } + @Override public String getForUpdateString() { if ( hsqldbVersion >= 20 ) { return " for update"; @@ -251,10 +263,12 @@ public class HSQLDialect extends Dialect { } } + @Override public boolean supportsLimit() { return true; } + @Override public String getLimitString(String sql, boolean hasOffset) { if ( hsqldbVersion < 20 ) { return new StringBuilder( sql.length() + 10 ) @@ -266,70 +280,72 @@ public class HSQLDialect extends Dialect { .toString(); } else { - return new StringBuilder( sql.length() + 20 ) - .append( sql ) - .append( hasOffset ? " offset ? limit ?" : " limit ?" ) - .toString(); + return sql + (hasOffset ? " offset ? limit ?" : " limit ?"); } } + @Override public boolean bindLimitParametersFirst() { return hsqldbVersion < 20; } + @Override public boolean supportsIfExistsAfterTableName() { return true; } + @Override public boolean supportsColumnCheck() { return hsqldbVersion >= 20; } + @Override public boolean supportsSequences() { return true; } + @Override public boolean supportsPooledSequences() { return true; } + @Override protected String getCreateSequenceString(String sequenceName) { return "create sequence " + sequenceName; } + @Override protected String getDropSequenceString(String sequenceName) { return "drop sequence " + sequenceName; } + @Override public String getSelectSequenceNextValString(String sequenceName) { return "next value for " + sequenceName; } + @Override public String getSequenceNextValString(String sequenceName) { return "call next value for " + sequenceName; } + @Override public String getQuerySequencesString() { // this assumes schema support, which is present in 1.8.0 and later... return "select sequence_name from information_schema.system_sequences"; } + @Override public ViolatedConstraintNameExtracter getViolatedConstraintNameExtracter() { return hsqldbVersion < 20 ? EXTRACTER_18 : EXTRACTER_20; } - private static ViolatedConstraintNameExtracter EXTRACTER_18 = new TemplatedViolatedConstraintNameExtracter() { - - /** - * Extract the name of the violated constraint from the given SQLException. - * - * @param sqle The exception that was the result of the constraint violation. - * @return The extracted constraint name. - */ + private static final ViolatedConstraintNameExtracter EXTRACTER_18 = new TemplatedViolatedConstraintNameExtracter() { + @Override public String extractConstraintName(SQLException sqle) { String constraintName = null; - int errorCode = JdbcExceptionHelper.extractErrorCode( sqle ); + final int errorCode = JdbcExceptionHelper.extractErrorCode( sqle ); if ( errorCode == -8 ) { constraintName = extractUsingTemplate( @@ -361,12 +377,12 @@ public class HSQLDialect extends Dialect { * HSQLDB 2.0 messages have changed * messages may be localized - therefore use the common, non-locale element " table: " */ - private static ViolatedConstraintNameExtracter EXTRACTER_20 = new TemplatedViolatedConstraintNameExtracter() { - + private static final ViolatedConstraintNameExtracter EXTRACTER_20 = new TemplatedViolatedConstraintNameExtracter() { + @Override public String extractConstraintName(SQLException sqle) { String constraintName = null; - int errorCode = JdbcExceptionHelper.extractErrorCode( sqle ); + final int errorCode = JdbcExceptionHelper.extractErrorCode( sqle ); if ( errorCode == -8 ) { constraintName = extractUsingTemplate( @@ -392,23 +408,24 @@ public class HSQLDialect extends Dialect { } }; + @Override public String getSelectClauseNullString(int sqlType) { String literal; switch ( sqlType ) { - case Types.LONGVARCHAR: + case Types.LONGVARCHAR: case Types.VARCHAR: case Types.CHAR: literal = "cast(null as varchar(100))"; break; - case Types.LONGVARBINARY: - case Types.VARBINARY: - case Types.BINARY: + case Types.LONGVARBINARY: + case Types.VARBINARY: + case Types.BINARY: literal = "cast(null as varbinary(100))"; break; - case Types.CLOB: + case Types.CLOB: literal = "cast(null as clob)"; break; - case Types.BLOB: + case Types.BLOB: literal = "cast(null as blob)"; break; case Types.DATE: @@ -417,10 +434,10 @@ public class HSQLDialect extends Dialect { case Types.TIMESTAMP: literal = "cast(null as timestamp)"; break; - case Types.BOOLEAN: + case Types.BOOLEAN: literal = "cast(null as boolean)"; break; - case Types.BIT: + case Types.BIT: literal = "cast(null as bit)"; break; case Types.TIME: @@ -432,11 +449,13 @@ public class HSQLDialect extends Dialect { return literal; } - public boolean supportsUnionAll() { - return true; - } + @Override + public boolean supportsUnionAll() { + return true; + } // temporary table support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Hibernate uses this information for temporary tables that it uses for its own operations // therefore the appropriate strategy is taken with different versions of HSQLDB @@ -446,37 +465,24 @@ public class HSQLDialect extends Dialect { // the definition and data is private to the session and table declaration // can happen in the middle of a transaction - /** - * Does this dialect support temporary tables? - * - * @return True if temp tables are supported; false otherwise. - */ + @Override public boolean supportsTemporaryTables() { return true; } - /** - * With HSQLDB 2.0, the table name is qualified with MODULE to assist the drop - * statement (in-case there is a global name beginning with HT_) - * - * @param baseTableName The table name from which to base the temp table name. - * - * @return The generated temp table name. - */ + @Override public String generateTemporaryTableName(String baseTableName) { if ( hsqldbVersion < 20 ) { return "HT_" + baseTableName; } else { + // With HSQLDB 2.0, the table name is qualified with MODULE to assist the drop + // statement (in-case there is a global name beginning with HT_) return "MODULE.HT_" + baseTableName; } } - /** - * Command used to create a temporary table. - * - * @return The command used to create a temporary table. - */ + @Override public String getCreateTemporaryTableString() { if ( hsqldbVersion < 20 ) { return "create global temporary table"; @@ -486,40 +492,19 @@ public class HSQLDialect extends Dialect { } } - /** - * No fragment is needed if data is not needed beyond commit, otherwise - * should add "on commit preserve rows" - * - * @return Any required postfix. - */ + @Override public String getCreateTemporaryTablePostfix() { return ""; } - /** - * Command used to drop a temporary table. - * - * @return The command used to drop a temporary table. - */ + @Override public String getDropTemporaryTableString() { return "drop table"; } - /** - * Different behavior for GLOBAL TEMPORARY (1.8) and LOCAL TEMPORARY (2.0) - *

- * Possible return values and their meanings:

    - *
  • {@link Boolean#TRUE} - Unequivocally, perform the temporary table DDL - * in isolation.
  • - *
  • {@link Boolean#FALSE} - Unequivocally, do not perform the - * temporary table DDL in isolation.
  • - *
  • null - defer to the JDBC driver response in regards to - * {@link java.sql.DatabaseMetaData#dataDefinitionCausesTransactionCommit()}
  • - *
- * - * @return see the result matrix above. - */ + @Override public Boolean performTemporaryTableDDLInIsolation() { + // Different behavior for GLOBAL TEMPORARY (1.8) and LOCAL TEMPORARY (2.0) if ( hsqldbVersion < 20 ) { return Boolean.TRUE; } @@ -528,20 +513,13 @@ public class HSQLDialect extends Dialect { } } - /** - * Do we need to drop the temporary table after use? - * - * todo - clarify usage by Hibernate - * - * Version 1.8 GLOBAL TEMPORARY table definitions persist beyond the end - * of the session (by default, data is cleared at commit).

- * - * Version 2.x LOCAL TEMPORARY table definitions do not persist beyond - * the end of the session (by default, data is cleared at commit). - * - * @return True if the table should be dropped. - */ + @Override public boolean dropTemporaryTableAfterUse() { + // Version 1.8 GLOBAL TEMPORARY table definitions persist beyond the end + // of the session (by default, data is cleared at commit).

+ // + // Version 2.x LOCAL TEMPORARY table definitions do not persist beyond + // the end of the session (by default, data is cleared at commit). return true; } @@ -552,44 +530,25 @@ public class HSQLDialect extends Dialect { * be treated as a callable statement. It is equivalent to * "select current_timestamp from dual" in some databases. * HSQLDB 2.0 also supports VALUES CURRENT_TIMESTAMP - * - * @return True if the current timestamp can be retrieved; false otherwise. + *

+ * {@inheritDoc} */ + @Override public boolean supportsCurrentTimestampSelection() { return true; } - /** - * Should the value returned by {@link #getCurrentTimestampSelectString} - * be treated as callable. Typically this indicates that JDBC escape - * syntax is being used...

- * - * CALL CURRENT_TIMESTAMP is used but this should not - * be treated as a callable statement. - * - * @return True if the {@link #getCurrentTimestampSelectString} return - * is callable; false otherwise. - */ + @Override public boolean isCurrentTimestampSelectStringCallable() { return false; } - /** - * Retrieve the command used to retrieve the current timestamp from the - * database. - * - * @return The command. - */ + @Override public String getCurrentTimestampSelectString() { return "call current_timestamp"; } - /** - * The name of the database-specific SQL function for retrieving the - * current timestamp. - * - * @return The function name. - */ + @Override public String getCurrentTimestampSQLFunctionName() { // the standard SQL function name is current_timestamp... return "current_timestamp"; @@ -598,14 +557,10 @@ public class HSQLDialect extends Dialect { /** * For HSQLDB 2.0, this is a copy of the base class implementation. * For HSQLDB 1.8, only READ_UNCOMMITTED is supported. - * - * @param lockable The persister for the entity to be locked. - * @param lockMode The type of lock to be acquired. - * - * @return The appropriate locking strategy. - * - * @since 3.2 + *

+ * {@inheritDoc} */ + @Override public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) { if ( lockMode == LockMode.PESSIMISTIC_FORCE_INCREMENT ) { return new PessimisticForceIncrementLockingStrategy( lockable, lockMode ); @@ -631,7 +586,7 @@ public class HSQLDialect extends Dialect { } } - public static class ReadUncommittedLockingStrategy extends SelectLockingStrategy { + private static class ReadUncommittedLockingStrategy extends SelectLockingStrategy { public ReadUncommittedLockingStrategy(Lockable lockable, LockMode lockMode) { super( lockable, lockMode ); } @@ -645,6 +600,7 @@ public class HSQLDialect extends Dialect { } } + @Override public boolean supportsCommentOn() { return hsqldbVersion >= 20; } @@ -656,54 +612,32 @@ public class HSQLDialect extends Dialect { return false; } - /** - * todo - needs usage clarification - * - * If the SELECT statement is always part of a UNION, then the type of - * parameter is resolved by v. 2.0, but not v. 1.8 (assuming the other - * SELECT in the UNION has a column reference in the same position and - * can be type-resolved). - * - * On the other hand if the SELECT statement is isolated, all versions of - * HSQLDB require casting for "select ? from .." to work. - * - * @return True if select clause parameter must be cast()ed - * - * @since 3.2 - */ + @Override public boolean requiresCastingOfParametersInSelectClause() { return true; } - /** - * For the underlying database, is READ_COMMITTED isolation implemented by - * forcing readers to wait for write locks to be released? - * - * @return True if writers block readers to achieve READ_COMMITTED; false otherwise. - */ + @Override public boolean doesReadCommittedCauseWritersToBlockReaders() { return hsqldbVersion >= 20; } - /** - * For the underlying database, is REPEATABLE_READ isolation implemented by - * forcing writers to wait for read locks to be released? - * - * @return True if readers block writers to achieve REPEATABLE_READ; false otherwise. - */ + @Override public boolean doesRepeatableReadCauseReadersToBlockWriters() { return hsqldbVersion >= 20; } - + @Override public boolean supportsLobValueChangePropogation() { return false; } - public String toBooleanValueString(boolean bool) { - return String.valueOf( bool ); - } + @Override + public String toBooleanValueString(boolean bool) { + return String.valueOf( bool ); + } + @Override public boolean supportsTupleDistinctCounts() { return false; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/InformixDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/InformixDialect.java index 614658cc05..6a665bdd4a 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/InformixDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/InformixDialect.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import java.sql.SQLException; import java.sql.Types; @@ -49,68 +50,78 @@ public class InformixDialect extends Dialect { public InformixDialect() { super(); - registerColumnType(Types.BIGINT, "int8"); - registerColumnType(Types.BINARY, "byte"); - registerColumnType(Types.BIT, "smallint"); // Informix doesn't have a bit type - registerColumnType(Types.CHAR, "char($l)"); - registerColumnType(Types.DATE, "date"); - registerColumnType(Types.DECIMAL, "decimal"); - registerColumnType(Types.DOUBLE, "float"); - registerColumnType(Types.FLOAT, "smallfloat"); - registerColumnType(Types.INTEGER, "integer"); - registerColumnType(Types.LONGVARBINARY, "blob"); // or BYTE - registerColumnType(Types.LONGVARCHAR, "clob"); // or TEXT? - registerColumnType(Types.NUMERIC, "decimal"); // or MONEY - registerColumnType(Types.REAL, "smallfloat"); - registerColumnType(Types.SMALLINT, "smallint"); - registerColumnType(Types.TIMESTAMP, "datetime year to fraction(5)"); - registerColumnType(Types.TIME, "datetime hour to second"); - registerColumnType(Types.TINYINT, "smallint"); - registerColumnType(Types.VARBINARY, "byte"); - registerColumnType(Types.VARCHAR, "varchar($l)"); - registerColumnType(Types.VARCHAR, 255, "varchar($l)"); - registerColumnType(Types.VARCHAR, 32739, "lvarchar($l)"); + registerColumnType( Types.BIGINT, "int8" ); + registerColumnType( Types.BINARY, "byte" ); + // Informix doesn't have a bit type + registerColumnType( Types.BIT, "smallint" ); + registerColumnType( Types.CHAR, "char($l)" ); + registerColumnType( Types.DATE, "date" ); + registerColumnType( Types.DECIMAL, "decimal" ); + registerColumnType( Types.DOUBLE, "float" ); + registerColumnType( Types.FLOAT, "smallfloat" ); + registerColumnType( Types.INTEGER, "integer" ); + // or BYTE + registerColumnType( Types.LONGVARBINARY, "blob" ); + // or TEXT? + registerColumnType( Types.LONGVARCHAR, "clob" ); + // or MONEY + registerColumnType( Types.NUMERIC, "decimal" ); + registerColumnType( Types.REAL, "smallfloat" ); + registerColumnType( Types.SMALLINT, "smallint" ); + registerColumnType( Types.TIMESTAMP, "datetime year to fraction(5)" ); + registerColumnType( Types.TIME, "datetime hour to second" ); + registerColumnType( Types.TINYINT, "smallint" ); + registerColumnType( Types.VARBINARY, "byte" ); + registerColumnType( Types.VARCHAR, "varchar($l)" ); + registerColumnType( Types.VARCHAR, 255, "varchar($l)" ); + registerColumnType( Types.VARCHAR, 32739, "lvarchar($l)" ); registerFunction( "concat", new VarArgsSQLFunction( StandardBasicTypes.STRING, "(", "||", ")" ) ); } + @Override public String getAddColumnString() { return "add"; } + @Override public boolean supportsIdentityColumns() { return true; } - public String getIdentitySelectString(String table, String column, int type) - throws MappingException { - return type==Types.BIGINT ? - "select dbinfo('serial8') from informix.systables where tabid=1" : - "select dbinfo('sqlca.sqlerrd1') from informix.systables where tabid=1"; + @Override + public String getIdentitySelectString(String table, String column, int type) + throws MappingException { + return type == Types.BIGINT + ? "select dbinfo('serial8') from informix.systables where tabid=1" + : "select dbinfo('sqlca.sqlerrd1') from informix.systables where tabid=1"; } + @Override public String getIdentityColumnString(int type) throws MappingException { - return type==Types.BIGINT ? - "serial8 not null" : - "serial not null"; + return type == Types.BIGINT ? + "serial8 not null" : + "serial not null"; } + @Override public boolean hasDataTypeInIdentityColumn() { return false; } /** - * The syntax used to add a foreign key constraint to a table. * Informix constraint name must be at the end. - * @return String + *

+ * {@inheritDoc} */ + @Override public String getAddForeignKeyConstraintString( String constraintName, String[] foreignKey, String referencedTable, String[] primaryKey, boolean referencesPrimaryKey) { - StringBuilder result = new StringBuilder( 30 ) + final StringBuilder result = new StringBuilder( 30 ) .append( " add constraint " ) .append( " foreign key (" ) .append( StringHelper.join( ", ", foreignKey ) ) @@ -129,53 +140,66 @@ public class InformixDialect extends Dialect { } /** - * The syntax used to add a primary key constraint to a table. * Informix constraint name must be at the end. - * @return String + *

+ * {@inheritDoc} */ + @Override public String getAddPrimaryKeyConstraintString(String constraintName) { return " add constraint primary key constraint " + constraintName + " "; } + @Override public String getCreateSequenceString(String sequenceName) { return "create sequence " + sequenceName; } + + @Override public String getDropSequenceString(String sequenceName) { return "drop sequence " + sequenceName + " restrict"; } + @Override public String getSequenceNextValString(String sequenceName) { return "select " + getSelectSequenceNextValString( sequenceName ) + " from informix.systables where tabid=1"; } + @Override public String getSelectSequenceNextValString(String sequenceName) { return sequenceName + ".nextval"; } + @Override public boolean supportsSequences() { return true; } + @Override public boolean supportsPooledSequences() { return true; } + @Override public String getQuerySequencesString() { return "select tabname from informix.systables where tabtype='Q'"; } + @Override public boolean supportsLimit() { return true; } + @Override public boolean useMaxForLimit() { return true; } + @Override public boolean supportsLimitOffset() { return false; } + @Override public String getLimitString(String querySelect, int offset, int limit) { if ( offset > 0 ) { throw new UnsupportedOperationException( "query result offset is not supported" ); @@ -186,41 +210,45 @@ public class InformixDialect extends Dialect { .toString(); } + @Override public boolean supportsVariableLimit() { return false; } + @Override public ViolatedConstraintNameExtracter getViolatedConstraintNameExtracter() { - return EXTRACTER; + return EXTRACTER; } - private static ViolatedConstraintNameExtracter EXTRACTER = new TemplatedViolatedConstraintNameExtracter() { - - /** - * Extract the name of the violated constraint from the given SQLException. - * - * @param sqle The exception that was the result of the constraint violation. - * @return The extracted constraint name. - */ + private static final ViolatedConstraintNameExtracter EXTRACTER = new TemplatedViolatedConstraintNameExtracter() { + @Override public String extractConstraintName(SQLException sqle) { String constraintName = null; - - int errorCode = JdbcExceptionHelper.extractErrorCode( sqle ); + final int errorCode = JdbcExceptionHelper.extractErrorCode( sqle ); + if ( errorCode == -268 ) { constraintName = extractUsingTemplate( "Unique constraint (", ") violated.", sqle.getMessage() ); } else if ( errorCode == -691 ) { - constraintName = extractUsingTemplate( "Missing key in referenced table for referential constraint (", ").", sqle.getMessage() ); + constraintName = extractUsingTemplate( + "Missing key in referenced table for referential constraint (", + ").", + sqle.getMessage() + ); } else if ( errorCode == -692 ) { - constraintName = extractUsingTemplate( "Key value for constraint (", ") is still being referenced.", sqle.getMessage() ); + constraintName = extractUsingTemplate( + "Key value for constraint (", + ") is still being referenced.", + sqle.getMessage() + ); } - - if (constraintName != null) { + + if ( constraintName != null ) { // strip table-owner because Informix always returns constraint names as "." - int i = constraintName.indexOf('.'); - if (i != -1) { - constraintName = constraintName.substring(i + 1); + final int i = constraintName.indexOf( '.' ); + if ( i != -1 ) { + constraintName = constraintName.substring( i + 1 ); } } @@ -229,46 +257,33 @@ public class InformixDialect extends Dialect { }; + @Override public boolean supportsCurrentTimestampSelection() { return true; } + @Override public boolean isCurrentTimestampSelectStringCallable() { return false; } + @Override public String getCurrentTimestampSelectString() { return "select distinct current timestamp from informix.systables"; } - /** - * Overrides {@link Dialect#supportsTemporaryTables()} to return - * {@code true} when invoked. - * - * @return {@code true} when invoked - */ + @Override public boolean supportsTemporaryTables() { return true; } - /** - * Overrides {@link Dialect#getCreateTemporaryTableString()} to - * return "{@code create temp table}" when invoked. - * - * @return "{@code create temp table}" when invoked - */ + @Override public String getCreateTemporaryTableString() { return "create temp table"; } - /** - * Overrides {@link Dialect#getCreateTemporaryTablePostfix()} to - * return "{@code with no log}" when invoked. - * - * @return "{@code with no log}" when invoked - */ + @Override public String getCreateTemporaryTablePostfix() { return "with no log"; } - } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Ingres10Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Ingres10Dialect.java index 4f69d6f7f6..07433fdb2b 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Ingres10Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Ingres10Dialect.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import java.sql.Types; import java.util.Properties; @@ -39,62 +40,62 @@ import org.hibernate.cfg.Environment; * @author Raymond Fan */ public class Ingres10Dialect extends Ingres9Dialect { - public Ingres10Dialect() { - super(); - registerBooleanSupport(); - } + /** + * Constructs a Ingres10Dialect + */ + public Ingres10Dialect() { + super(); + registerBooleanSupport(); + registerDefaultProperties(); + } - // Boolean column type support + protected void registerBooleanSupport() { + // Boolean type (mapping/BooleanType) mapping maps SQL BIT to Java + // Boolean. In order to create a boolean column, BIT needs to be mapped + // to boolean as well, similar to H2Dialect. + registerColumnType( Types.BIT, "boolean" ); + registerColumnType( Types.BOOLEAN, "boolean" ); + } - /** - * The SQL literal value to which this database maps boolean values. - * - * @param bool The boolean value - * @return The appropriate SQL literal. - */ - public String toBooleanValueString(boolean bool) { - return bool ? "true" : "false"; - } - - protected void registerBooleanSupport() { - // Column type - - // Boolean type (mapping/BooleanType) mapping maps SQL BIT to Java - // Boolean. In order to create a boolean column, BIT needs to be mapped - // to boolean as well, similar to H2Dialect. - registerColumnType( Types.BIT, "boolean" ); - registerColumnType( Types.BOOLEAN, "boolean" ); - - // Functions - - // true, false and unknown are now valid values - // Remove the query substitutions previously added in IngresDialect. - Properties properties = getDefaultProperties(); - String querySubst = properties.getProperty(Environment.QUERY_SUBSTITUTIONS); - if (querySubst != null) { - String newQuerySubst = querySubst.replace("true=1,false=0",""); - properties.setProperty(Environment.QUERY_SUBSTITUTIONS, newQuerySubst); - } - } + private void registerDefaultProperties() { + // true, false and unknown are now valid values + // Remove the query substitutions previously added in IngresDialect. + final Properties properties = getDefaultProperties(); + final String querySubst = properties.getProperty( Environment.QUERY_SUBSTITUTIONS ); + if ( querySubst != null ) { + final String newQuerySubst = querySubst.replace( "true=1,false=0", "" ); + properties.setProperty( Environment.QUERY_SUBSTITUTIONS, newQuerySubst ); + } + } // IDENTITY support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + @Override + public String toBooleanValueString(boolean bool) { + return bool ? "true" : "false"; + } + + @Override public boolean supportsIdentityColumns() { return true; } + @Override public boolean hasDataTypeInIdentityColumn() { return true; } + @Override public String getIdentitySelectString() { return "select last_identity()"; } + @Override public String getIdentityColumnString() { return "not null generated by default as identity"; } + @Override public String getIdentityInsertString() { return "default"; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Ingres9Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Ingres9Dialect.java index a9de59008a..b335bdf50e 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Ingres9Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Ingres9Dialect.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import java.sql.Types; import org.hibernate.dialect.function.NoArgSQLFunction; @@ -30,7 +31,7 @@ import org.hibernate.type.StandardBasicTypes; /** * A SQL dialect for Ingres 9.3 and later versions. - *

+ *

* Changes: *

    *
  • Support for the SQL functions current_time, current_timestamp and current_date added
  • @@ -41,212 +42,143 @@ import org.hibernate.type.StandardBasicTypes; *
  • Added getIdentitySelectString
  • *
  • Modified concatination operator
  • *
- * + * * @author Enrico Schenk * @author Raymond Fan */ public class Ingres9Dialect extends IngresDialect { - public Ingres9Dialect() { - super(); - registerDateTimeFunctions(); - registerDateTimeColumnTypes(); - registerFunction( "concat", new VarArgsSQLFunction( StandardBasicTypes.STRING, "(", "||", ")" ) ); - } + /** + * Constructs a Ingres9Dialect + */ + public Ingres9Dialect() { + super(); + registerDateTimeFunctions(); + registerDateTimeColumnTypes(); + registerFunction( "concat", new VarArgsSQLFunction( StandardBasicTypes.STRING, "(", "||", ")" ) ); + } /** * Register functions current_time, current_timestamp, current_date */ protected void registerDateTimeFunctions() { - registerFunction("current_time", new NoArgSQLFunction("current_time", StandardBasicTypes.TIME, false)); - registerFunction("current_timestamp", new NoArgSQLFunction("current_timestamp", StandardBasicTypes.TIMESTAMP, false)); - registerFunction("current_date", new NoArgSQLFunction("current_date", StandardBasicTypes.DATE, false)); + registerFunction( "current_time", new NoArgSQLFunction( "current_time", StandardBasicTypes.TIME, false ) ); + registerFunction( + "current_timestamp", new NoArgSQLFunction( + "current_timestamp", + StandardBasicTypes.TIMESTAMP, + false + ) + ); + registerFunction( "current_date", new NoArgSQLFunction( "current_date", StandardBasicTypes.DATE, false ) ); } /** * Register column types date, time, timestamp */ protected void registerDateTimeColumnTypes() { - registerColumnType(Types.DATE, "ansidate"); - registerColumnType(Types.TIMESTAMP, "timestamp(9) with time zone"); + registerColumnType( Types.DATE, "ansidate" ); + registerColumnType( Types.TIMESTAMP, "timestamp(9) with time zone" ); } // lock acquisition support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - /** - * Does this dialect support FOR UPDATE in conjunction with outer - * joined rows? - * - * @return True if outer joined rows can be locked via FOR UPDATE. - */ + @Override public boolean supportsOuterJoinForUpdate() { return false; } - /** - * Is FOR UPDATE OF syntax supported? - * - * @return True if the database supports FOR UPDATE OF syntax; - * false otherwise. - */ + @Override public boolean forUpdateOfColumns() { return true; } // SEQUENCE support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - /** - * Get the select command used to retrieve the last generated sequence - * value. - * - * @return Statement to retrieve last generated sequence value - */ - public String getIdentitySelectString() { - return "select last_identity()"; - } + @Override + public String getIdentitySelectString() { + return "select last_identity()"; + } - /** - * Get the select command used retrieve the names of all sequences. - * - * @return The select command; or null if sequences are not supported. - * @see org.hibernate.tool.hbm2ddl.SchemaUpdate - */ + @Override public String getQuerySequencesString() { return "select seq_name from iisequences"; } - /** - * Does this dialect support "pooled" sequences. Not aware of a better name - * for this. Essentially can we specify the initial and increment values? - * - * @return True if such "pooled" sequences are supported; false otherwise. - * @see #getCreateSequenceStrings(String, int, int) - * @see #getCreateSequenceString(String, int, int) - */ + @Override public boolean supportsPooledSequences() { return true; } // current timestamp support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - /** - * Should the value returned by {@link #getCurrentTimestampSelectString} be - * treated as callable. Typically this indicates that JDBC escape sytnax is - * being used... - * - * @return True if the {@link #getCurrentTimestampSelectString} return is - * callable; false otherwise. - */ + @Override public boolean isCurrentTimestampSelectStringCallable() { return false; } - /** - * Does this dialect support a way to retrieve the database's current - * timestamp value? - * - * @return True if the current timestamp can be retrieved; false otherwise. - */ + @Override public boolean supportsCurrentTimestampSelection() { return true; } - /** - * Retrieve the command used to retrieve the current timestammp from the - * database. - * - * @return The command. - */ + @Override public String getCurrentTimestampSelectString() { return "select current_timestamp"; } - /** - * Expression for current_timestamp - */ + @Override public String getCurrentTimestampSQLFunctionName() { return "current_timestamp"; } // union subclass support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - /** - * Does this dialect support UNION ALL, which is generally a faster variant - * of UNION? - * - * @return True if UNION ALL is supported; false otherwise. - */ + @Override public boolean supportsUnionAll() { return true; } // Informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - /** - * For the underlying database, is READ_COMMITTED isolation implemented by - * forcing readers to wait for write locks to be released? - * - * @return true - */ + @Override public boolean doesReadCommittedCauseWritersToBlockReaders() { return true; } - /** - * For the underlying database, is REPEATABLE_READ isolation implemented by - * forcing writers to wait for read locks to be released? - * - * @return true - */ + @Override public boolean doesRepeatableReadCauseReadersToBlockWriters() { return true; } // limit/offset support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - /** - * Does this dialect's LIMIT support (if any) additionally support - * specifying an offset? - * - * @return true - */ + @Override public boolean supportsLimitOffset() { return true; } - /** - * Does this dialect support bind variables (i.e., prepared statememnt - * parameters) for its limit/offset? - * - * @return false - */ + @Override public boolean supportsVariableLimit() { return false; } - /** - * Does the LIMIT clause take a "maximum" row number instead - * of a total number of returned rows? - */ + @Override public boolean useMaxForLimit() { return false; } - /** - * Add a LIMIT clause to the given SQL SELECT - * - * @return the modified SQL - */ + @Override public String getLimitString(String querySelect, int offset, int limit) { - StringBuilder soff = new StringBuilder(" offset " + offset); - StringBuilder slim = new StringBuilder(" fetch first " + limit + " rows only"); - StringBuilder sb = new StringBuilder(querySelect.length() + - soff.length() + slim.length()).append(querySelect); - if (offset > 0) { - sb.append(soff); + final StringBuilder soff = new StringBuilder( " offset " + offset ); + final StringBuilder slim = new StringBuilder( " fetch first " + limit + " rows only" ); + final StringBuilder sb = new StringBuilder( querySelect.length() + soff.length() + slim.length() ) + .append( querySelect ); + if ( offset > 0 ) { + sb.append( soff ); + } + if ( limit > 0 ) { + sb.append( slim ); } - if (limit > 0) { - sb.append(slim); - } return sb.toString(); } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/IngresDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/IngresDialect.java index e5b9f8a20e..b22cf43218 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/IngresDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/IngresDialect.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import java.sql.Types; import org.hibernate.cfg.Environment; @@ -34,12 +35,20 @@ import org.hibernate.type.StandardBasicTypes; /** * An SQL dialect for Ingres 9.2. *

- * Known limitations: - *

    - *
  • Only supports simple constants or columns on the left side of an IN, making (1,2,3) in (...) or (<subselect>) in (...) non-supported. - *
  • Supports only 39 digits in decimal. - *
  • Explicitly set USE_GET_GENERATED_KEYS property to false. - *
  • Perform string casts to varchar; removes space padding. + * Known limitations:
      + *
    • + * Only supports simple constants or columns on the left side of an IN, + * making {@code (1,2,3) in (...)} or {@code (subselect) in (...)} non-supported. + *
    • + *
    • + * Supports only 39 digits in decimal. + *
    • + *
    • + * Explicitly set USE_GET_GENERATED_KEYS property to false. + *
    • + *
    • + * Perform string casts to varchar; removes space padding. + *
    • *
    * * @author Ian Booth @@ -47,8 +56,11 @@ import org.hibernate.type.StandardBasicTypes; * @author Max Rydahl Andersen * @author Raymond Fan */ +@SuppressWarnings("deprecation") public class IngresDialect extends Dialect { - + /** + * Constructs a IngresDialect + */ public IngresDialect() { super(); registerColumnType( Types.BIT, "tinyint" ); @@ -145,145 +157,89 @@ public class IngresDialect extends Dialect { // maximum width of a value for that return type. Casting to varchar // does not introduce space padding. registerFunction( "str", new SQLFunctionTemplate(StandardBasicTypes.STRING, "cast(?1 as varchar)") ); - // Ingres driver supports getGeneratedKeys but only in the following - // form: - // The Ingres DBMS returns only a single table key or a single object - // key per insert statement. Ingres does not return table and object - // keys for INSERT AS SELECT statements. Depending on the keys that are - // produced by the statement executed, auto-generated key parameters in - // execute(), executeUpdate(), and prepareStatement() methods are - // ignored and getGeneratedKeys() returns a result-set containing no - // rows, a single row with one column, or a single row with two columns. - // Ingres JDBC Driver returns table and object keys as BINARY values. - getDefaultProperties().setProperty(Environment.USE_GET_GENERATED_KEYS, "false"); - // There is no support for a native boolean type that accepts values - // of true, false or unknown. Using the tinyint type requires - // substitions of true and false. - getDefaultProperties().setProperty(Environment.QUERY_SUBSTITUTIONS, "true=1,false=0"); + // Ingres driver supports getGeneratedKeys but only in the following + // form: + // The Ingres DBMS returns only a single table key or a single object + // key per insert statement. Ingres does not return table and object + // keys for INSERT AS SELECT statements. Depending on the keys that are + // produced by the statement executed, auto-generated key parameters in + // execute(), executeUpdate(), and prepareStatement() methods are + // ignored and getGeneratedKeys() returns a result-set containing no + // rows, a single row with one column, or a single row with two columns. + // Ingres JDBC Driver returns table and object keys as BINARY values. + getDefaultProperties().setProperty( Environment.USE_GET_GENERATED_KEYS, "false" ); + // There is no support for a native boolean type that accepts values + // of true, false or unknown. Using the tinyint type requires + // substitions of true and false. + getDefaultProperties().setProperty( Environment.QUERY_SUBSTITUTIONS, "true=1,false=0" ); } - /** - * Expression for created UUID string - */ + + @Override public String getSelectGUIDString() { return "select uuid_to_char(uuid_create())"; } - /** - * Do we need to drop constraints before dropping tables in this dialect? - * - * @return boolean - */ + + @Override public boolean dropConstraints() { return false; } - /** - * Does this dialect support FOR UPDATE OF, allowing - * particular rows to be locked? - * - * @return True (Ingres does support "for update of" syntax...) - */ - public boolean supportsForUpdateOf() { - return true; - } - - /** - * The syntax used to add a column to a table (optional). - */ + @Override public String getAddColumnString() { return "add column"; } - /** - * The keyword used to specify a nullable column. - * - * @return String - */ + @Override public String getNullColumnString() { return " with null"; } - /** - * Does this dialect support sequences? - * - * @return boolean - */ + @Override public boolean supportsSequences() { return true; } - /** - * The syntax that fetches the next value of a sequence, if sequences are supported. - * - * @param sequenceName the name of the sequence - * - * @return String - */ + @Override public String getSequenceNextValString(String sequenceName) { return "select nextval for " + sequenceName; } + @Override public String getSelectSequenceNextValString(String sequenceName) { return sequenceName + ".nextval"; } - /** - * The syntax used to create a sequence, if sequences are supported. - * - * @param sequenceName the name of the sequence - * - * @return String - */ + @Override public String getCreateSequenceString(String sequenceName) { return "create sequence " + sequenceName; } - /** - * The syntax used to drop a sequence, if sequences are supported. - * - * @param sequenceName the name of the sequence - * - * @return String - */ + @Override public String getDropSequenceString(String sequenceName) { return "drop sequence " + sequenceName + " restrict"; } - /** - * A query used to find all sequences - */ + @Override public String getQuerySequencesString() { return "select seq_name from iisequence"; } - /** - * The name of the SQL function that transforms a string to - * lowercase - * - * @return String - */ + @Override public String getLowercaseFunction() { return "lowercase"; } - /** - * Does this Dialect have some kind of LIMIT syntax? - */ + @Override public boolean supportsLimit() { return true; } - /** - * Does this dialect support an offset? - */ + @Override public boolean supportsLimitOffset() { return false; } - /** - * Add a LIMIT clause to the given SQL SELECT - * - * @return the modified SQL - */ + @Override public String getLimitString(String querySelect, int offset, int limit) { if ( offset > 0 ) { throw new UnsupportedOperationException( "query result offset is not supported" ); @@ -294,64 +250,59 @@ public class IngresDialect extends Dialect { .toString(); } + @Override public boolean supportsVariableLimit() { return false; } - /** - * Does the LIMIT clause take a "maximum" row number instead - * of a total number of returned rows? - */ + @Override public boolean useMaxForLimit() { return true; } - /** - * Does this dialect support temporary tables? - */ + @Override public boolean supportsTemporaryTables() { return true; } + @Override public String getCreateTemporaryTableString() { return "declare global temporary table"; } + @Override public String getCreateTemporaryTablePostfix() { return "on commit preserve rows with norecovery"; } + @Override public String generateTemporaryTableName(String baseTableName) { return "session." + super.generateTemporaryTableName( baseTableName ); } - - /** - * Expression for current_timestamp - */ + @Override public String getCurrentTimestampSQLFunctionName() { return "date(now)"; } // Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + @Override public boolean supportsSubselectAsInPredicateLHS() { return false; } + @Override public boolean supportsEmptyInList() { return false; } + @Override public boolean supportsExpectedLobUsagePattern () { return false; } - /** - * Ingres does not support the syntax `count(distinct a,b)`? - * - * @return False, not supported. - */ + @Override public boolean supportsTupleDistinctCounts() { return false; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/InterbaseDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/InterbaseDialect.java index 7e0a0b89d1..b6dd691323 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/InterbaseDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/InterbaseDialect.java @@ -34,8 +34,12 @@ import org.hibernate.type.StandardBasicTypes; * * @author Gavin King */ +@SuppressWarnings("deprecation") public class InterbaseDialect extends Dialect { + /** + * Constructs a InterbaseDialect + */ public InterbaseDialect() { super(); registerColumnType( Types.BIT, "smallint" ); @@ -56,63 +60,78 @@ public class InterbaseDialect extends Dialect { registerColumnType( Types.CLOB, "blob sub_type 1" ); registerFunction( "concat", new VarArgsSQLFunction( StandardBasicTypes.STRING, "(","||",")" ) ); - registerFunction("current_date", new NoArgSQLFunction("current_date", StandardBasicTypes.DATE, false) ); + registerFunction( "current_date", new NoArgSQLFunction( "current_date", StandardBasicTypes.DATE, false ) ); - getDefaultProperties().setProperty(Environment.STATEMENT_BATCH_SIZE, NO_BATCH); + getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, NO_BATCH ); } + @Override public String getAddColumnString() { return "add"; } + @Override public String getSequenceNextValString(String sequenceName) { return "select " + getSelectSequenceNextValString( sequenceName ) + " from RDB$DATABASE"; } + @Override public String getSelectSequenceNextValString(String sequenceName) { return "gen_id( " + sequenceName + ", 1 )"; } + @Override public String getCreateSequenceString(String sequenceName) { return "create generator " + sequenceName; } + @Override public String getDropSequenceString(String sequenceName) { return "delete from RDB$GENERATORS where RDB$GENERATOR_NAME = '" + sequenceName.toUpperCase() + "'"; } + @Override public String getQuerySequencesString() { return "select RDB$GENERATOR_NAME from RDB$GENERATORS"; } - + + @Override public String getForUpdateString() { return " with lock"; } + + @Override public String getForUpdateString(String aliases) { return " for update of " + aliases + " with lock"; } + @Override public boolean supportsSequences() { return true; } + @Override public boolean supportsLimit() { return true; } + @Override public String getLimitString(String sql, boolean hasOffset) { return hasOffset ? sql + " rows ? to ?" : sql + " rows ?"; } + @Override public boolean bindLimitParametersFirst() { return false; } + @Override public boolean bindLimitParametersInReverseOrder() { return false; } - public String getCurrentTimestampCallString() { + @Override + public String getCurrentTimestampSelectString() { // TODO : not sure which (either?) is correct, could not find docs on how to do this. // did find various blogs and forums mentioning that select CURRENT_TIMESTAMP // does not work... @@ -120,7 +139,8 @@ public class InterbaseDialect extends Dialect { // return "select CURRENT_TIMESTAMP from RDB$DATABASE"; } + @Override public boolean isCurrentTimestampSelectStringCallable() { return true; } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/JDataStoreDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/JDataStoreDialect.java index a2b83305f8..37566cc2ad 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/JDataStoreDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/JDataStoreDialect.java @@ -22,17 +22,17 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import java.sql.Types; import org.hibernate.cfg.Environment; /** - * A Dialect for JDataStore. + * A Dialect for JDataStore. * * @author Vishy Kasar */ public class JDataStoreDialect extends Dialect { - /** * Creates new JDataStoreDialect */ @@ -60,38 +60,48 @@ public class JDataStoreDialect extends Dialect { getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE ); } + @Override public String getAddColumnString() { return "add"; } + @Override public boolean dropConstraints() { return false; } + @Override public String getCascadeConstraintsString() { return " cascade"; } + @Override public boolean supportsIdentityColumns() { return true; } + @Override public String getIdentitySelectString() { - return null; // NOT_SUPPORTED_SHOULD_USE_JDBC3_PreparedStatement.getGeneratedKeys_method + // NOT_SUPPORTED_SHOULD_USE_JDBC3_PreparedStatement.getGeneratedKeys_method + return null; } + @Override public String getIdentityColumnString() { return "autoincrement"; } + @Override public String getNoColumnsInsertString() { return "default values"; } + @Override public boolean supportsColumnCheck() { return false; } + @Override public boolean supportsTableCheck() { return false; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/MckoiDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/MckoiDialect.java index 151ed7917a..1143a56245 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/MckoiDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/MckoiDialect.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import java.sql.Types; import org.hibernate.LockMode; @@ -47,6 +48,9 @@ import org.hibernate.type.StandardBasicTypes; * @author Gabe Hicks */ public class MckoiDialect extends Dialect { + /** + * Constructs a MckoiDialect + */ public MckoiDialect() { super(); registerColumnType( Types.BIT, "bit" ); @@ -78,41 +82,50 @@ public class MckoiDialect extends Dialect { registerFunction( "user", new StandardSQLFunction( "user", StandardBasicTypes.STRING ) ); registerFunction( "concat", new StandardSQLFunction( "concat", StandardBasicTypes.STRING ) ); - getDefaultProperties().setProperty(Environment.STATEMENT_BATCH_SIZE, NO_BATCH); + getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, NO_BATCH ); } + @Override public String getAddColumnString() { return "add column"; } + @Override public String getSequenceNextValString(String sequenceName) { return "select " + getSelectSequenceNextValString( sequenceName ); } + @Override public String getSelectSequenceNextValString(String sequenceName) { return "nextval('" + sequenceName + "')"; } + @Override public String getCreateSequenceString(String sequenceName) { return "create sequence " + sequenceName; } + @Override public String getDropSequenceString(String sequenceName) { return "drop sequence " + sequenceName; } + @Override public String getForUpdateString() { return ""; } + @Override public boolean supportsSequences() { return true; } + @Override public CaseFragment createCaseFragment() { return new MckoiCaseFragment(); } + @Override public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) { // Mckoi has no known variation of a "SELECT ... FOR UPDATE" syntax... if ( lockMode==LockMode.PESSIMISTIC_FORCE_INCREMENT) { diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/MySQL5Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/MySQL5Dialect.java index c5001f1557..6065a7dada 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/MySQL5Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/MySQL5Dialect.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import java.sql.Types; /** @@ -30,19 +31,15 @@ import java.sql.Types; * @author Steve Ebersole */ public class MySQL5Dialect extends MySQLDialect { + @Override protected void registerVarcharTypes() { registerColumnType( Types.VARCHAR, "longtext" ); // registerColumnType( Types.VARCHAR, 16777215, "mediumtext" ); registerColumnType( Types.VARCHAR, 65535, "varchar($l)" ); registerColumnType( Types.LONGVARCHAR, "longtext" ); } - - /** - * Does this dialect support column-level check constraints? - * - * @return True if column-level CHECK constraints are supported; false - * otherwise. - */ + + @Override public boolean supportsColumnCheck() { return false; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/MySQL5InnoDBDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/MySQL5InnoDBDialect.java index 81cbe4146b..474aa9bef1 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/MySQL5InnoDBDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/MySQL5InnoDBDialect.java @@ -23,22 +23,24 @@ */ package org.hibernate.dialect; - -/** - * @author Gavin King, Scott Marlow +/** A Dialect for MySQL 5 using InnoDB engine + * + * @author Gavin King, + * @author Scott Marlow */ public class MySQL5InnoDBDialect extends MySQL5Dialect { - + @Override public boolean supportsCascadeDelete() { return true; } - + + @Override public String getTableTypeString() { return " ENGINE=InnoDB"; } + @Override public boolean hasSelfReferentialForeignKeyBug() { return true; } - } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/MySQLDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/MySQLDialect.java index 5d9d881577..801c7d1b9b 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/MySQLDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/MySQLDialect.java @@ -45,8 +45,12 @@ import org.hibernate.type.StandardBasicTypes; * * @author Gavin King */ +@SuppressWarnings("deprecation") public class MySQLDialect extends Dialect { + /** + * Constructs a MySQLDialect + */ public MySQLDialect() { super(); registerColumnType( Types.BIT, "bit" ); @@ -64,7 +68,7 @@ public class MySQLDialect extends Dialect { registerColumnType( Types.VARBINARY, 16777215, "mediumblob" ); registerColumnType( Types.VARBINARY, 65535, "blob" ); registerColumnType( Types.VARBINARY, 255, "tinyblob" ); - registerColumnType( Types.BINARY, "binary($l)" ); + registerColumnType( Types.BINARY, "binary($l)" ); registerColumnType( Types.LONGVARBINARY, "longblob" ); registerColumnType( Types.LONGVARBINARY, 16777215, "mediumblob" ); registerColumnType( Types.NUMERIC, "decimal($p,$s)" ); @@ -76,111 +80,111 @@ public class MySQLDialect extends Dialect { // registerColumnType( Types.CLOB, 65535, "text" ); registerVarcharTypes(); - registerFunction("ascii", new StandardSQLFunction("ascii", StandardBasicTypes.INTEGER) ); - registerFunction("bin", new StandardSQLFunction("bin", StandardBasicTypes.STRING) ); - registerFunction("char_length", new StandardSQLFunction("char_length", StandardBasicTypes.LONG) ); - registerFunction("character_length", new StandardSQLFunction("character_length", StandardBasicTypes.LONG) ); - registerFunction("lcase", new StandardSQLFunction("lcase") ); - registerFunction("lower", new StandardSQLFunction("lower") ); - registerFunction("ltrim", new StandardSQLFunction("ltrim") ); - registerFunction("ord", new StandardSQLFunction("ord", StandardBasicTypes.INTEGER) ); - registerFunction("quote", new StandardSQLFunction("quote") ); - registerFunction("reverse", new StandardSQLFunction("reverse") ); - registerFunction("rtrim", new StandardSQLFunction("rtrim") ); - registerFunction("soundex", new StandardSQLFunction("soundex") ); - registerFunction("space", new StandardSQLFunction("space", StandardBasicTypes.STRING) ); - registerFunction("ucase", new StandardSQLFunction("ucase") ); - registerFunction("upper", new StandardSQLFunction("upper") ); - registerFunction("unhex", new StandardSQLFunction("unhex", StandardBasicTypes.STRING) ); + registerFunction( "ascii", new StandardSQLFunction( "ascii", StandardBasicTypes.INTEGER ) ); + registerFunction( "bin", new StandardSQLFunction( "bin", StandardBasicTypes.STRING ) ); + registerFunction( "char_length", new StandardSQLFunction( "char_length", StandardBasicTypes.LONG ) ); + registerFunction( "character_length", new StandardSQLFunction( "character_length", StandardBasicTypes.LONG ) ); + registerFunction( "lcase", new StandardSQLFunction( "lcase" ) ); + registerFunction( "lower", new StandardSQLFunction( "lower" ) ); + registerFunction( "ltrim", new StandardSQLFunction( "ltrim" ) ); + registerFunction( "ord", new StandardSQLFunction( "ord", StandardBasicTypes.INTEGER ) ); + registerFunction( "quote", new StandardSQLFunction( "quote" ) ); + registerFunction( "reverse", new StandardSQLFunction( "reverse" ) ); + registerFunction( "rtrim", new StandardSQLFunction( "rtrim" ) ); + registerFunction( "soundex", new StandardSQLFunction( "soundex" ) ); + registerFunction( "space", new StandardSQLFunction( "space", StandardBasicTypes.STRING ) ); + registerFunction( "ucase", new StandardSQLFunction( "ucase" ) ); + registerFunction( "upper", new StandardSQLFunction( "upper" ) ); + registerFunction( "unhex", new StandardSQLFunction( "unhex", StandardBasicTypes.STRING ) ); - registerFunction("abs", new StandardSQLFunction("abs") ); - registerFunction("sign", new StandardSQLFunction("sign", StandardBasicTypes.INTEGER) ); + registerFunction( "abs", new StandardSQLFunction( "abs" ) ); + registerFunction( "sign", new StandardSQLFunction( "sign", StandardBasicTypes.INTEGER ) ); - registerFunction("acos", new StandardSQLFunction("acos", StandardBasicTypes.DOUBLE) ); - registerFunction("asin", new StandardSQLFunction("asin", StandardBasicTypes.DOUBLE) ); - registerFunction("atan", new StandardSQLFunction("atan", StandardBasicTypes.DOUBLE) ); - registerFunction("cos", new StandardSQLFunction("cos", StandardBasicTypes.DOUBLE) ); - registerFunction("cot", new StandardSQLFunction("cot", StandardBasicTypes.DOUBLE) ); - registerFunction("crc32", new StandardSQLFunction("crc32", StandardBasicTypes.LONG) ); - registerFunction("exp", new StandardSQLFunction("exp", StandardBasicTypes.DOUBLE) ); - registerFunction("ln", new StandardSQLFunction("ln", StandardBasicTypes.DOUBLE) ); - registerFunction("log", new StandardSQLFunction("log", StandardBasicTypes.DOUBLE) ); - registerFunction("log2", new StandardSQLFunction("log2", StandardBasicTypes.DOUBLE) ); - registerFunction("log10", new StandardSQLFunction("log10", StandardBasicTypes.DOUBLE) ); - registerFunction("pi", new NoArgSQLFunction("pi", StandardBasicTypes.DOUBLE) ); - registerFunction("rand", new NoArgSQLFunction("rand", StandardBasicTypes.DOUBLE) ); - registerFunction("sin", new StandardSQLFunction("sin", StandardBasicTypes.DOUBLE) ); - registerFunction("sqrt", new StandardSQLFunction("sqrt", StandardBasicTypes.DOUBLE) ); - registerFunction("tan", new StandardSQLFunction("tan", StandardBasicTypes.DOUBLE) ); + registerFunction( "acos", new StandardSQLFunction( "acos", StandardBasicTypes.DOUBLE ) ); + registerFunction( "asin", new StandardSQLFunction( "asin", StandardBasicTypes.DOUBLE ) ); + registerFunction( "atan", new StandardSQLFunction( "atan", StandardBasicTypes.DOUBLE ) ); + registerFunction( "cos", new StandardSQLFunction( "cos", StandardBasicTypes.DOUBLE ) ); + registerFunction( "cot", new StandardSQLFunction( "cot", StandardBasicTypes.DOUBLE ) ); + registerFunction( "crc32", new StandardSQLFunction( "crc32", StandardBasicTypes.LONG ) ); + registerFunction( "exp", new StandardSQLFunction( "exp", StandardBasicTypes.DOUBLE ) ); + registerFunction( "ln", new StandardSQLFunction( "ln", StandardBasicTypes.DOUBLE ) ); + registerFunction( "log", new StandardSQLFunction( "log", StandardBasicTypes.DOUBLE ) ); + registerFunction( "log2", new StandardSQLFunction( "log2", StandardBasicTypes.DOUBLE ) ); + registerFunction( "log10", new StandardSQLFunction( "log10", StandardBasicTypes.DOUBLE ) ); + registerFunction( "pi", new NoArgSQLFunction( "pi", StandardBasicTypes.DOUBLE ) ); + registerFunction( "rand", new NoArgSQLFunction( "rand", StandardBasicTypes.DOUBLE ) ); + registerFunction( "sin", new StandardSQLFunction( "sin", StandardBasicTypes.DOUBLE ) ); + registerFunction( "sqrt", new StandardSQLFunction( "sqrt", StandardBasicTypes.DOUBLE ) ); + registerFunction( "tan", new StandardSQLFunction( "tan", StandardBasicTypes.DOUBLE ) ); - registerFunction("radians", new StandardSQLFunction("radians", StandardBasicTypes.DOUBLE) ); - registerFunction("degrees", new StandardSQLFunction("degrees", StandardBasicTypes.DOUBLE) ); + registerFunction( "radians", new StandardSQLFunction( "radians", StandardBasicTypes.DOUBLE ) ); + registerFunction( "degrees", new StandardSQLFunction( "degrees", StandardBasicTypes.DOUBLE ) ); - registerFunction("ceiling", new StandardSQLFunction("ceiling", StandardBasicTypes.INTEGER) ); - registerFunction("ceil", new StandardSQLFunction("ceil", StandardBasicTypes.INTEGER) ); - registerFunction("floor", new StandardSQLFunction("floor", StandardBasicTypes.INTEGER) ); - registerFunction("round", new StandardSQLFunction("round") ); + registerFunction( "ceiling", new StandardSQLFunction( "ceiling", StandardBasicTypes.INTEGER ) ); + registerFunction( "ceil", new StandardSQLFunction( "ceil", StandardBasicTypes.INTEGER ) ); + registerFunction( "floor", new StandardSQLFunction( "floor", StandardBasicTypes.INTEGER ) ); + registerFunction( "round", new StandardSQLFunction( "round" ) ); - registerFunction("datediff", new StandardSQLFunction("datediff", StandardBasicTypes.INTEGER) ); - registerFunction("timediff", new StandardSQLFunction("timediff", StandardBasicTypes.TIME) ); - registerFunction("date_format", new StandardSQLFunction("date_format", StandardBasicTypes.STRING) ); + registerFunction( "datediff", new StandardSQLFunction( "datediff", StandardBasicTypes.INTEGER ) ); + registerFunction( "timediff", new StandardSQLFunction( "timediff", StandardBasicTypes.TIME ) ); + registerFunction( "date_format", new StandardSQLFunction( "date_format", StandardBasicTypes.STRING ) ); - registerFunction("curdate", new NoArgSQLFunction("curdate", StandardBasicTypes.DATE) ); - registerFunction("curtime", new NoArgSQLFunction("curtime", StandardBasicTypes.TIME) ); - registerFunction("current_date", new NoArgSQLFunction("current_date", StandardBasicTypes.DATE, false) ); - registerFunction("current_time", new NoArgSQLFunction("current_time", StandardBasicTypes.TIME, false) ); - registerFunction("current_timestamp", new NoArgSQLFunction("current_timestamp", StandardBasicTypes.TIMESTAMP, false) ); - registerFunction("date", new StandardSQLFunction("date", StandardBasicTypes.DATE) ); - registerFunction("day", new StandardSQLFunction("day", StandardBasicTypes.INTEGER) ); - registerFunction("dayofmonth", new StandardSQLFunction("dayofmonth", StandardBasicTypes.INTEGER) ); - registerFunction("dayname", new StandardSQLFunction("dayname", StandardBasicTypes.STRING) ); - registerFunction("dayofweek", new StandardSQLFunction("dayofweek", StandardBasicTypes.INTEGER) ); - registerFunction("dayofyear", new StandardSQLFunction("dayofyear", StandardBasicTypes.INTEGER) ); - registerFunction("from_days", new StandardSQLFunction("from_days", StandardBasicTypes.DATE) ); - registerFunction("from_unixtime", new StandardSQLFunction("from_unixtime", StandardBasicTypes.TIMESTAMP) ); - registerFunction("hour", new StandardSQLFunction("hour", StandardBasicTypes.INTEGER) ); - registerFunction("last_day", new StandardSQLFunction("last_day", StandardBasicTypes.DATE) ); - registerFunction("localtime", new NoArgSQLFunction("localtime", StandardBasicTypes.TIMESTAMP) ); - registerFunction("localtimestamp", new NoArgSQLFunction("localtimestamp", StandardBasicTypes.TIMESTAMP) ); - registerFunction("microseconds", new StandardSQLFunction("microseconds", StandardBasicTypes.INTEGER) ); - registerFunction("minute", new StandardSQLFunction("minute", StandardBasicTypes.INTEGER) ); - registerFunction("month", new StandardSQLFunction("month", StandardBasicTypes.INTEGER) ); - registerFunction("monthname", new StandardSQLFunction("monthname", StandardBasicTypes.STRING) ); - registerFunction("now", new NoArgSQLFunction("now", StandardBasicTypes.TIMESTAMP) ); - registerFunction("quarter", new StandardSQLFunction("quarter", StandardBasicTypes.INTEGER) ); - registerFunction("second", new StandardSQLFunction("second", StandardBasicTypes.INTEGER) ); - registerFunction("sec_to_time", new StandardSQLFunction("sec_to_time", StandardBasicTypes.TIME) ); - registerFunction("sysdate", new NoArgSQLFunction("sysdate", StandardBasicTypes.TIMESTAMP) ); - registerFunction("time", new StandardSQLFunction("time", StandardBasicTypes.TIME) ); - registerFunction("timestamp", new StandardSQLFunction("timestamp", StandardBasicTypes.TIMESTAMP) ); - registerFunction("time_to_sec", new StandardSQLFunction("time_to_sec", StandardBasicTypes.INTEGER) ); - registerFunction("to_days", new StandardSQLFunction("to_days", StandardBasicTypes.LONG) ); - registerFunction("unix_timestamp", new StandardSQLFunction("unix_timestamp", StandardBasicTypes.LONG) ); - registerFunction("utc_date", new NoArgSQLFunction("utc_date", StandardBasicTypes.STRING) ); - registerFunction("utc_time", new NoArgSQLFunction("utc_time", StandardBasicTypes.STRING) ); - registerFunction("utc_timestamp", new NoArgSQLFunction("utc_timestamp", StandardBasicTypes.STRING) ); - registerFunction("week", new StandardSQLFunction("week", StandardBasicTypes.INTEGER) ); - registerFunction("weekday", new StandardSQLFunction("weekday", StandardBasicTypes.INTEGER) ); - registerFunction("weekofyear", new StandardSQLFunction("weekofyear", StandardBasicTypes.INTEGER) ); - registerFunction("year", new StandardSQLFunction("year", StandardBasicTypes.INTEGER) ); - registerFunction("yearweek", new StandardSQLFunction("yearweek", StandardBasicTypes.INTEGER) ); + registerFunction( "curdate", new NoArgSQLFunction( "curdate", StandardBasicTypes.DATE ) ); + registerFunction( "curtime", new NoArgSQLFunction( "curtime", StandardBasicTypes.TIME ) ); + registerFunction( "current_date", new NoArgSQLFunction( "current_date", StandardBasicTypes.DATE, false ) ); + registerFunction( "current_time", new NoArgSQLFunction( "current_time", StandardBasicTypes.TIME, false ) ); + registerFunction( "current_timestamp", new NoArgSQLFunction( "current_timestamp", StandardBasicTypes.TIMESTAMP, false ) ); + registerFunction( "date", new StandardSQLFunction( "date", StandardBasicTypes.DATE ) ); + registerFunction( "day", new StandardSQLFunction( "day", StandardBasicTypes.INTEGER ) ); + registerFunction( "dayofmonth", new StandardSQLFunction( "dayofmonth", StandardBasicTypes.INTEGER ) ); + registerFunction( "dayname", new StandardSQLFunction( "dayname", StandardBasicTypes.STRING ) ); + registerFunction( "dayofweek", new StandardSQLFunction( "dayofweek", StandardBasicTypes.INTEGER ) ); + registerFunction( "dayofyear", new StandardSQLFunction( "dayofyear", StandardBasicTypes.INTEGER ) ); + registerFunction( "from_days", new StandardSQLFunction( "from_days", StandardBasicTypes.DATE ) ); + registerFunction( "from_unixtime", new StandardSQLFunction( "from_unixtime", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( "hour", new StandardSQLFunction( "hour", StandardBasicTypes.INTEGER ) ); + registerFunction( "last_day", new StandardSQLFunction( "last_day", StandardBasicTypes.DATE ) ); + registerFunction( "localtime", new NoArgSQLFunction( "localtime", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( "localtimestamp", new NoArgSQLFunction( "localtimestamp", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( "microseconds", new StandardSQLFunction( "microseconds", StandardBasicTypes.INTEGER ) ); + registerFunction( "minute", new StandardSQLFunction( "minute", StandardBasicTypes.INTEGER ) ); + registerFunction( "month", new StandardSQLFunction( "month", StandardBasicTypes.INTEGER ) ); + registerFunction( "monthname", new StandardSQLFunction( "monthname", StandardBasicTypes.STRING ) ); + registerFunction( "now", new NoArgSQLFunction( "now", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( "quarter", new StandardSQLFunction( "quarter", StandardBasicTypes.INTEGER ) ); + registerFunction( "second", new StandardSQLFunction( "second", StandardBasicTypes.INTEGER ) ); + registerFunction( "sec_to_time", new StandardSQLFunction( "sec_to_time", StandardBasicTypes.TIME ) ); + registerFunction( "sysdate", new NoArgSQLFunction( "sysdate", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( "time", new StandardSQLFunction( "time", StandardBasicTypes.TIME ) ); + registerFunction( "timestamp", new StandardSQLFunction( "timestamp", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( "time_to_sec", new StandardSQLFunction( "time_to_sec", StandardBasicTypes.INTEGER ) ); + registerFunction( "to_days", new StandardSQLFunction( "to_days", StandardBasicTypes.LONG ) ); + registerFunction( "unix_timestamp", new StandardSQLFunction( "unix_timestamp", StandardBasicTypes.LONG ) ); + registerFunction( "utc_date", new NoArgSQLFunction( "utc_date", StandardBasicTypes.STRING ) ); + registerFunction( "utc_time", new NoArgSQLFunction( "utc_time", StandardBasicTypes.STRING ) ); + registerFunction( "utc_timestamp", new NoArgSQLFunction( "utc_timestamp", StandardBasicTypes.STRING ) ); + registerFunction( "week", new StandardSQLFunction( "week", StandardBasicTypes.INTEGER ) ); + registerFunction( "weekday", new StandardSQLFunction( "weekday", StandardBasicTypes.INTEGER ) ); + registerFunction( "weekofyear", new StandardSQLFunction( "weekofyear", StandardBasicTypes.INTEGER ) ); + registerFunction( "year", new StandardSQLFunction( "year", StandardBasicTypes.INTEGER ) ); + registerFunction( "yearweek", new StandardSQLFunction( "yearweek", StandardBasicTypes.INTEGER ) ); - registerFunction("hex", new StandardSQLFunction("hex", StandardBasicTypes.STRING) ); - registerFunction("oct", new StandardSQLFunction("oct", StandardBasicTypes.STRING) ); + registerFunction( "hex", new StandardSQLFunction( "hex", StandardBasicTypes.STRING ) ); + registerFunction( "oct", new StandardSQLFunction( "oct", StandardBasicTypes.STRING ) ); - registerFunction("octet_length", new StandardSQLFunction("octet_length", StandardBasicTypes.LONG) ); - registerFunction("bit_length", new StandardSQLFunction("bit_length", StandardBasicTypes.LONG) ); + registerFunction( "octet_length", new StandardSQLFunction( "octet_length", StandardBasicTypes.LONG ) ); + registerFunction( "bit_length", new StandardSQLFunction( "bit_length", StandardBasicTypes.LONG ) ); - registerFunction("bit_count", new StandardSQLFunction("bit_count", StandardBasicTypes.LONG) ); - registerFunction("encrypt", new StandardSQLFunction("encrypt", StandardBasicTypes.STRING) ); - registerFunction("md5", new StandardSQLFunction("md5", StandardBasicTypes.STRING) ); - registerFunction("sha1", new StandardSQLFunction("sha1", StandardBasicTypes.STRING) ); - registerFunction("sha", new StandardSQLFunction("sha", StandardBasicTypes.STRING) ); + registerFunction( "bit_count", new StandardSQLFunction( "bit_count", StandardBasicTypes.LONG ) ); + registerFunction( "encrypt", new StandardSQLFunction( "encrypt", StandardBasicTypes.STRING ) ); + registerFunction( "md5", new StandardSQLFunction( "md5", StandardBasicTypes.STRING ) ); + registerFunction( "sha1", new StandardSQLFunction( "sha1", StandardBasicTypes.STRING ) ); + registerFunction( "sha", new StandardSQLFunction( "sha", StandardBasicTypes.STRING ) ); registerFunction( "concat", new StandardSQLFunction( "concat", StandardBasicTypes.STRING ) ); - getDefaultProperties().setProperty(Environment.MAX_FETCH_DEPTH, "2"); - getDefaultProperties().setProperty(Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE); + getDefaultProperties().setProperty( Environment.MAX_FETCH_DEPTH, "2" ); + getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE ); } protected void registerVarcharTypes() { @@ -191,110 +195,127 @@ public class MySQLDialect extends Dialect { registerColumnType( Types.LONGVARCHAR, "longtext" ); } + @Override public String getAddColumnString() { return "add column"; } - + + @Override public boolean qualifyIndexName() { return false; } + @Override public boolean supportsIdentityColumns() { return true; } - + + @Override public String getIdentitySelectString() { return "select last_insert_id()"; } + @Override public String getIdentityColumnString() { - return "not null auto_increment"; //starts with 1, implicitly + //starts with 1, implicitly + return "not null auto_increment"; } + @Override public String getAddForeignKeyConstraintString( - String constraintName, - String[] foreignKey, - String referencedTable, - String[] primaryKey, boolean referencesPrimaryKey - ) { - String cols = StringHelper.join(", ", foreignKey); - return new StringBuilder(30) - .append(" add index ") - .append(constraintName) - .append(" (") - .append(cols) - .append("), add constraint ") - .append(constraintName) - .append(" foreign key (") - .append(cols) - .append(") references ") - .append(referencedTable) - .append(" (") - .append( StringHelper.join(", ", primaryKey) ) - .append(')') - .toString(); + String constraintName, + String[] foreignKey, + String referencedTable, + String[] primaryKey, + boolean referencesPrimaryKey) { + final String cols = StringHelper.join( ", ", foreignKey ); + final String referencedCols = StringHelper.join( ", ", primaryKey ); + return String.format( + " add index %s (%s), add constraint %s foreign key (%s) references %s (%s)", + constraintName, + cols, + constraintName, + cols, + referencedTable, + referencedCols + ); } + @Override public boolean supportsLimit() { return true; } - + + @Override public String getDropForeignKeyString() { return " drop foreign key "; } + @Override public String getLimitString(String sql, boolean hasOffset) { return sql + (hasOffset ? " limit ?, ?" : " limit ?"); } + @Override public char closeQuote() { return '`'; } + @Override public char openQuote() { return '`'; } + @Override public boolean supportsIfExistsBeforeTableName() { return true; } + @Override public String getSelectGUIDString() { return "select uuid()"; } + @Override public boolean supportsCascadeDelete() { return false; } - + + @Override public String getTableComment(String comment) { return " comment='" + comment + "'"; } + @Override public String getColumnComment(String comment) { return " comment '" + comment + "'"; } + @Override public boolean supportsTemporaryTables() { return true; } + @Override public String getCreateTemporaryTableString() { return "create temporary table if not exists"; } + @Override public String getDropTemporaryTableString() { return "drop temporary table"; } + @Override public Boolean performTemporaryTableDDLInIsolation() { // because we [drop *temporary* table...] we do not // have to doAfterTransactionCompletion these in isolation. return Boolean.FALSE; } + @Override public String getCastTypeName(int code) { - switch ( code ){ + switch ( code ) { case Types.INTEGER: return "signed"; case Types.VARCHAR: @@ -306,30 +327,36 @@ public class MySQLDialect extends Dialect { } } + @Override public boolean supportsCurrentTimestampSelection() { return true; } + @Override public boolean isCurrentTimestampSelectStringCallable() { return false; } + @Override public String getCurrentTimestampSelectString() { return "select now()"; } + @Override public int registerResultSetOutParameter(CallableStatement statement, int col) throws SQLException { return col; - } - + } + + @Override public ResultSet getResultSet(CallableStatement ps) throws SQLException { - boolean isResultSet = ps.execute(); - while (!isResultSet && ps.getUpdateCount() != -1) { - isResultSet = ps.getMoreResults(); - } + boolean isResultSet = ps.execute(); + while ( !isResultSet && ps.getUpdateCount() != -1 ) { + isResultSet = ps.getMoreResults(); + } return ps.getResultSet(); } + @Override public boolean supportsRowValueConstructorSyntax() { return true; } @@ -355,14 +382,17 @@ public class MySQLDialect extends Dialect { // locking support + @Override public String getForUpdateString() { return " for update"; } + @Override public String getWriteLockString(int timeout) { return " for update"; } + @Override public String getReadLockString(int timeout) { return " lock in share mode"; } @@ -370,19 +400,23 @@ public class MySQLDialect extends Dialect { // Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + @Override public boolean supportsEmptyInList() { return false; } + @Override public boolean areStringComparisonsCaseInsensitive() { return true; } + @Override public boolean supportsLobValueChangePropogation() { // note: at least my local MySQL 5.1 install shows this not working... return false; } + @Override public boolean supportsSubqueryOnMutatingTable() { return false; } @@ -415,9 +449,9 @@ public class MySQLDialect extends Dialect { } }; } - + @Override - public String getNotExpression( String expression ) { + public String getNotExpression(String expression) { return "not (" + expression + ")"; } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/MySQLInnoDBDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/MySQLInnoDBDialect.java index 37a13d271b..7b7ffb58c0 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/MySQLInnoDBDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/MySQLInnoDBDialect.java @@ -23,22 +23,24 @@ */ package org.hibernate.dialect; - /** + * A Dialect for MySQL using InnoDB engine + * * @author Gavin King */ public class MySQLInnoDBDialect extends MySQLDialect { - + @Override public boolean supportsCascadeDelete() { return true; } - + + @Override public String getTableTypeString() { return " type=InnoDB"; } + @Override public boolean hasSelfReferentialForeignKeyBug() { return true; } - } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/MySQLMyISAMDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/MySQLMyISAMDialect.java index d2f53be4e9..3a3840b7d3 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/MySQLMyISAMDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/MySQLMyISAMDialect.java @@ -23,18 +23,19 @@ */ package org.hibernate.dialect; - /** + * A Dialect for MySQL using the MyISAM engine + * * @author Gavin King */ public class MySQLMyISAMDialect extends MySQLDialect { - + @Override public String getTableTypeString() { return " type=MyISAM"; } + @Override public boolean dropConstraints() { return false; } - } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle10gDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle10gDialect.java index 8ec1d401a9..978a5be158 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle10gDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle10gDialect.java @@ -22,31 +22,33 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import org.hibernate.LockOptions; import org.hibernate.sql.ANSIJoinFragment; import org.hibernate.sql.JoinFragment; - /** * A dialect specifically for use with Oracle 10g. *

    * The main difference between this dialect and {@link Oracle9iDialect} - * is the use of "ANSI join syntax". This dialect also retires the use - * of the oracle.jdbc.driver package in favor of - * oracle.jdbc. + * is the use of "ANSI join syntax". * * @author Steve Ebersole */ public class Oracle10gDialect extends Oracle9iDialect { - + /** + * Constructs a Oracle10gDialect + */ public Oracle10gDialect() { super(); } + @Override public JoinFragment createOuterJoinFragment() { return new ANSIJoinFragment(); } + @Override public String getWriteLockString(int timeout) { if ( timeout == LockOptions.SKIP_LOCKED ) { return getForUpdateSkipLockedString(); @@ -56,10 +58,12 @@ public class Oracle10gDialect extends Oracle9iDialect { } } + @Override public String getForUpdateSkipLockedString() { return " for update skip locked"; } + @Override public String getForUpdateSkipLockedString(String aliases) { return getForUpdateString() + " of " + aliases + " skip locked"; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle8iDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle8iDialect.java index 5a0d243feb..9b83d3fdbc 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle8iDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle8iDialect.java @@ -58,10 +58,13 @@ import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; * * @author Steve Ebersole */ +@SuppressWarnings("deprecation") public class Oracle8iDialect extends Dialect { - private static final int PARAM_LIST_SIZE_LIMIT = 1000; + /** + * Constructs a Oracle8iDialect + */ public Oracle8iDialect() { super(); registerCharacterTypeMappings(); @@ -91,7 +94,7 @@ public class Oracle8iDialect extends Dialect { registerColumnType( Types.NUMERIC, "number($p,$s)" ); registerColumnType( Types.DECIMAL, "number($p,$s)" ); - registerColumnType( Types.BOOLEAN, "number(1,0)" ); + registerColumnType( Types.BOOLEAN, "number(1,0)" ); } protected void registerDateTimeTypeMappings() { @@ -217,19 +220,11 @@ public class Oracle8iDialect extends Dialect { // features which change between 8i, 9i, and 10g ~~~~~~~~~~~~~~~~~~~~~~~~~~ - /** - * Support for the oracle proprietary join syntax... - * - * @return The orqacle join fragment - */ @Override public JoinFragment createOuterJoinFragment() { return new OracleJoinFragment(); } - /** - * {@inheritDoc} - */ @Override public String getCrossJoinSeparator() { return ", "; @@ -238,35 +233,36 @@ public class Oracle8iDialect extends Dialect { /** * Map case support to the Oracle DECODE function. Oracle did not * add support for CASE until 9i. - * - * @return The oracle CASE -> DECODE fragment + *

    + * {@inheritDoc} */ @Override public CaseFragment createCaseFragment() { return new DecodeCaseFragment(); } + @Override public String getLimitString(String sql, boolean hasOffset) { sql = sql.trim(); boolean isForUpdate = false; - if ( sql.toLowerCase().endsWith(" for update") ) { + if ( sql.toLowerCase().endsWith( " for update" ) ) { sql = sql.substring( 0, sql.length()-11 ); isForUpdate = true; } - StringBuilder pagingSelect = new StringBuilder( sql.length()+100 ); + final StringBuilder pagingSelect = new StringBuilder( sql.length()+100 ); if (hasOffset) { - pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( "); + pagingSelect.append( "select * from ( select row_.*, rownum rownum_ from ( " ); } else { pagingSelect.append("select * from ( "); } - pagingSelect.append(sql); + pagingSelect.append( sql ); if (hasOffset) { - pagingSelect.append(" ) row_ ) where rownum_ <= ? and rownum_ > ?"); + pagingSelect.append( " ) row_ ) where rownum_ <= ? and rownum_ > ?" ); } else { - pagingSelect.append(" ) where rownum <= ?"); + pagingSelect.append( " ) where rownum <= ?" ); } if ( isForUpdate ) { @@ -286,6 +282,7 @@ public class Oracle8iDialect extends Dialect { public String getBasicSelectClauseNullString(int sqlType) { return super.getSelectClauseNullString( sqlType ); } + @Override public String getSelectClauseNullString(int sqlType) { switch(sqlType) { @@ -300,10 +297,12 @@ public class Oracle8iDialect extends Dialect { return "to_number(null)"; } } + @Override public String getCurrentTimestampSelectString() { return "select sysdate from dual"; } + @Override public String getCurrentTimestampSQLFunctionName() { return "sysdate"; @@ -311,70 +310,88 @@ public class Oracle8iDialect extends Dialect { // features which remain constant across 8i, 9i, and 10g ~~~~~~~~~~~~~~~~~~ + @Override public String getAddColumnString() { return "add"; } + @Override public String getSequenceNextValString(String sequenceName) { return "select " + getSelectSequenceNextValString( sequenceName ) + " from dual"; } + @Override public String getSelectSequenceNextValString(String sequenceName) { return sequenceName + ".nextval"; } + @Override public String getCreateSequenceString(String sequenceName) { - return "create sequence " + sequenceName; //starts with 1, implicitly + //starts with 1, implicitly + return "create sequence " + sequenceName; } + @Override public String getDropSequenceString(String sequenceName) { return "drop sequence " + sequenceName; } + @Override public String getCascadeConstraintsString() { return " cascade constraints"; } + @Override public boolean dropConstraints() { return false; } + @Override public String getForUpdateNowaitString() { return " for update nowait"; } + @Override public boolean supportsSequences() { return true; } + @Override public boolean supportsPooledSequences() { return true; } + @Override public boolean supportsLimit() { return true; } + @Override public String getForUpdateString(String aliases) { return getForUpdateString() + " of " + aliases; } + @Override public String getForUpdateNowaitString(String aliases) { return getForUpdateString() + " of " + aliases + " nowait"; } + @Override public boolean bindLimitParametersInReverseOrder() { return true; } + @Override public boolean useMaxForLimit() { return true; } + @Override public boolean forUpdateOfColumns() { return true; } + @Override public String getQuerySequencesString() { return " select sequence_name from all_sequences" @@ -384,16 +401,18 @@ public class Oracle8iDialect extends Dialect { + " where asq.sequence_name = us.table_name" + " and asq.sequence_owner = us.table_owner"; } + @Override public String getSelectGUIDString() { return "select rawtohex(sys_guid()) from dual"; } + @Override public ViolatedConstraintNameExtracter getViolatedConstraintNameExtracter() { - return EXTRACTER; + return EXTRACTER; } - private static ViolatedConstraintNameExtracter EXTRACTER = new TemplatedViolatedConstraintNameExtracter() { + private static final ViolatedConstraintNameExtracter EXTRACTER = new TemplatedViolatedConstraintNameExtracter() { /** * Extract the name of the violated constraint from the given SQLException. @@ -402,7 +421,7 @@ public class Oracle8iDialect extends Dialect { * @return The extracted constraint name. */ public String extractConstraintName(SQLException sqle) { - int errorCode = JdbcExceptionHelper.extractErrorCode( sqle ); + final int errorCode = JdbcExceptionHelper.extractErrorCode( sqle ); if ( errorCode == 1 || errorCode == 2291 || errorCode == 2292 ) { return extractUsingTemplate( "(", ")", sqle.getMessage() ); } @@ -476,88 +495,61 @@ public class Oracle8iDialect extends Dialect { }; } - public static final String ORACLE_TYPES_CLASS_NAME = "oracle.jdbc.OracleTypes"; - public static final String DEPRECATED_ORACLE_TYPES_CLASS_NAME = "oracle.jdbc.driver.OracleTypes"; - - public static final int INIT_ORACLETYPES_CURSOR_VALUE = -99; - - // not final-static to avoid possible classcast exceptions if using different oracle drivers. - private int oracleCursorTypeSqlType = INIT_ORACLETYPES_CURSOR_VALUE; - - public int getOracleCursorTypeSqlType() { - if ( oracleCursorTypeSqlType == INIT_ORACLETYPES_CURSOR_VALUE ) { - // todo : is there really any reason to kkeep trying if this fails once? - oracleCursorTypeSqlType = extractOracleCursorTypeValue(); - } - return oracleCursorTypeSqlType; - } - - protected int extractOracleCursorTypeValue() { - Class oracleTypesClass; - try { - oracleTypesClass = ReflectHelper.classForName( ORACLE_TYPES_CLASS_NAME ); - } - catch ( ClassNotFoundException cnfe ) { - try { - oracleTypesClass = ReflectHelper.classForName( DEPRECATED_ORACLE_TYPES_CLASS_NAME ); - } - catch ( ClassNotFoundException e ) { - throw new HibernateException( "Unable to locate OracleTypes class", e ); - } - } - - try { - return oracleTypesClass.getField( "CURSOR" ).getInt( null ); - } - catch ( Exception se ) { - throw new HibernateException( "Unable to access OracleTypes.CURSOR value", se ); - } - } @Override public int registerResultSetOutParameter(CallableStatement statement, int col) throws SQLException { // register the type of the out param - an Oracle specific type - statement.registerOutParameter( col, getOracleCursorTypeSqlType() ); + statement.registerOutParameter( col, OracleTypesHelper.INSTANCE.getOracleCursorTypeSqlType() ); col++; return col; } + @Override public ResultSet getResultSet(CallableStatement ps) throws SQLException { ps.execute(); - return ( ResultSet ) ps.getObject( 1 ); + return (ResultSet) ps.getObject( 1 ); } + @Override public boolean supportsUnionAll() { return true; } + @Override public boolean supportsCommentOn() { return true; } + @Override public boolean supportsTemporaryTables() { return true; } + @Override public String generateTemporaryTableName(String baseTableName) { - String name = super.generateTemporaryTableName(baseTableName); + final String name = super.generateTemporaryTableName( baseTableName ); return name.length() > 30 ? name.substring( 1, 30 ) : name; } + @Override public String getCreateTemporaryTableString() { return "create global temporary table"; } + @Override public String getCreateTemporaryTablePostfix() { return "on commit delete rows"; } + @Override public boolean dropTemporaryTableAfterUse() { return false; } + @Override public boolean supportsCurrentTimestampSelection() { return true; } + @Override public boolean isCurrentTimestampSelectStringCallable() { return false; @@ -573,9 +565,6 @@ public class Oracle8iDialect extends Dialect { return false; } - /* (non-Javadoc) - * @see org.hibernate.dialect.Dialect#getInExpressionCountLimit() - */ @Override public int getInExpressionCountLimit() { return PARAM_LIST_SIZE_LIMIT; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9Dialect.java index 22c11f6e01..624dc962b9 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9Dialect.java @@ -30,7 +30,6 @@ import java.sql.Types; import org.jboss.logging.Logger; -import org.hibernate.HibernateException; import org.hibernate.cfg.Environment; import org.hibernate.dialect.function.NoArgSQLFunction; import org.hibernate.dialect.function.NvlFunction; @@ -41,22 +40,30 @@ import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.JdbcExceptionHelper; -import org.hibernate.internal.util.ReflectHelper; import org.hibernate.type.StandardBasicTypes; /** * An SQL dialect for Oracle 9 (uses ANSI-style syntax where possible). * + * @author Gavin King + * @author David Channon + * * @deprecated Use either Oracle9iDialect or Oracle10gDialect instead - * @author Gavin King, David Channon */ +@SuppressWarnings("deprecation") @Deprecated public class Oracle9Dialect extends Dialect { - + private static final int PARAM_LIST_SIZE_LIMIT = 1000; - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, Oracle9Dialect.class.getName()); + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + Oracle9Dialect.class.getName() + ); + /** + * Constructs a Oracle9Dialect + */ public Oracle9Dialect() { super(); LOG.deprecatedOracle9Dialect(); @@ -84,68 +91,74 @@ public class Oracle9Dialect extends Dialect { // support the version taking an array of the names of the columns to // be returned (via its RETURNING clause). No other driver seems to // support this overloaded version. - getDefaultProperties().setProperty(Environment.USE_GET_GENERATED_KEYS, "false"); - getDefaultProperties().setProperty(Environment.USE_STREAMS_FOR_BINARY, "true"); - getDefaultProperties().setProperty(Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE); + getDefaultProperties().setProperty( Environment.USE_GET_GENERATED_KEYS, "false" ); + getDefaultProperties().setProperty( Environment.USE_STREAMS_FOR_BINARY, "true" ); + getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE ); - registerFunction( "abs", new StandardSQLFunction("abs") ); - registerFunction( "sign", new StandardSQLFunction("sign", StandardBasicTypes.INTEGER) ); + registerFunction( "abs", new StandardSQLFunction( "abs" ) ); + registerFunction( "sign", new StandardSQLFunction( "sign", StandardBasicTypes.INTEGER ) ); - registerFunction( "acos", new StandardSQLFunction("acos", StandardBasicTypes.DOUBLE) ); - registerFunction( "asin", new StandardSQLFunction("asin", StandardBasicTypes.DOUBLE) ); - registerFunction( "atan", new StandardSQLFunction("atan", StandardBasicTypes.DOUBLE) ); - registerFunction( "cos", new StandardSQLFunction("cos", StandardBasicTypes.DOUBLE) ); - registerFunction( "cosh", new StandardSQLFunction("cosh", StandardBasicTypes.DOUBLE) ); - registerFunction( "exp", new StandardSQLFunction("exp", StandardBasicTypes.DOUBLE) ); - registerFunction( "ln", new StandardSQLFunction("ln", StandardBasicTypes.DOUBLE) ); - registerFunction( "sin", new StandardSQLFunction("sin", StandardBasicTypes.DOUBLE) ); - registerFunction( "sinh", new StandardSQLFunction("sinh", StandardBasicTypes.DOUBLE) ); - registerFunction( "stddev", new StandardSQLFunction("stddev", StandardBasicTypes.DOUBLE) ); - registerFunction( "sqrt", new StandardSQLFunction("sqrt", StandardBasicTypes.DOUBLE) ); - registerFunction( "tan", new StandardSQLFunction("tan", StandardBasicTypes.DOUBLE) ); - registerFunction( "tanh", new StandardSQLFunction("tanh", StandardBasicTypes.DOUBLE) ); - registerFunction( "variance", new StandardSQLFunction("variance", StandardBasicTypes.DOUBLE) ); + registerFunction( "acos", new StandardSQLFunction( "acos", StandardBasicTypes.DOUBLE ) ); + registerFunction( "asin", new StandardSQLFunction( "asin", StandardBasicTypes.DOUBLE ) ); + registerFunction( "atan", new StandardSQLFunction( "atan", StandardBasicTypes.DOUBLE ) ); + registerFunction( "cos", new StandardSQLFunction( "cos", StandardBasicTypes.DOUBLE ) ); + registerFunction( "cosh", new StandardSQLFunction( "cosh", StandardBasicTypes.DOUBLE ) ); + registerFunction( "exp", new StandardSQLFunction( "exp", StandardBasicTypes.DOUBLE ) ); + registerFunction( "ln", new StandardSQLFunction( "ln", StandardBasicTypes.DOUBLE ) ); + registerFunction( "sin", new StandardSQLFunction( "sin", StandardBasicTypes.DOUBLE ) ); + registerFunction( "sinh", new StandardSQLFunction( "sinh", StandardBasicTypes.DOUBLE ) ); + registerFunction( "stddev", new StandardSQLFunction( "stddev", StandardBasicTypes.DOUBLE ) ); + registerFunction( "sqrt", new StandardSQLFunction( "sqrt", StandardBasicTypes.DOUBLE ) ); + registerFunction( "tan", new StandardSQLFunction( "tan", StandardBasicTypes.DOUBLE ) ); + registerFunction( "tanh", new StandardSQLFunction( "tanh", StandardBasicTypes.DOUBLE ) ); + registerFunction( "variance", new StandardSQLFunction( "variance", StandardBasicTypes.DOUBLE ) ); - registerFunction( "round", new StandardSQLFunction("round") ); - registerFunction( "trunc", new StandardSQLFunction("trunc") ); - registerFunction( "ceil", new StandardSQLFunction("ceil") ); - registerFunction( "floor", new StandardSQLFunction("floor") ); + registerFunction( "round", new StandardSQLFunction( "round" ) ); + registerFunction( "trunc", new StandardSQLFunction( "trunc" ) ); + registerFunction( "ceil", new StandardSQLFunction( "ceil" ) ); + registerFunction( "floor", new StandardSQLFunction( "floor" ) ); - registerFunction( "chr", new StandardSQLFunction("chr", StandardBasicTypes.CHARACTER) ); - registerFunction( "initcap", new StandardSQLFunction("initcap") ); - registerFunction( "lower", new StandardSQLFunction("lower") ); - registerFunction( "ltrim", new StandardSQLFunction("ltrim") ); - registerFunction( "rtrim", new StandardSQLFunction("rtrim") ); - registerFunction( "soundex", new StandardSQLFunction("soundex") ); - registerFunction( "upper", new StandardSQLFunction("upper") ); - registerFunction( "ascii", new StandardSQLFunction("ascii", StandardBasicTypes.INTEGER) ); + registerFunction( "chr", new StandardSQLFunction( "chr", StandardBasicTypes.CHARACTER ) ); + registerFunction( "initcap", new StandardSQLFunction( "initcap" ) ); + registerFunction( "lower", new StandardSQLFunction( "lower" ) ); + registerFunction( "ltrim", new StandardSQLFunction( "ltrim" ) ); + registerFunction( "rtrim", new StandardSQLFunction( "rtrim" ) ); + registerFunction( "soundex", new StandardSQLFunction( "soundex" ) ); + registerFunction( "upper", new StandardSQLFunction( "upper" ) ); + registerFunction( "ascii", new StandardSQLFunction( "ascii", StandardBasicTypes.INTEGER ) ); - registerFunction( "to_char", new StandardSQLFunction("to_char", StandardBasicTypes.STRING) ); - registerFunction( "to_date", new StandardSQLFunction("to_date", StandardBasicTypes.TIMESTAMP) ); + registerFunction( "to_char", new StandardSQLFunction( "to_char", StandardBasicTypes.STRING ) ); + registerFunction( "to_date", new StandardSQLFunction( "to_date", StandardBasicTypes.TIMESTAMP ) ); - registerFunction( "current_date", new NoArgSQLFunction("current_date", StandardBasicTypes.DATE, false) ); - registerFunction( "current_time", new NoArgSQLFunction("current_timestamp", StandardBasicTypes.TIME, false) ); - registerFunction( "current_timestamp", new NoArgSQLFunction("current_timestamp", StandardBasicTypes.TIMESTAMP, false) ); + registerFunction( "current_date", new NoArgSQLFunction( "current_date", StandardBasicTypes.DATE, false ) ); + registerFunction( "current_time", new NoArgSQLFunction( "current_timestamp", StandardBasicTypes.TIME, false ) ); + registerFunction( + "current_timestamp", new NoArgSQLFunction( + "current_timestamp", + StandardBasicTypes.TIMESTAMP, + false + ) + ); - registerFunction( "last_day", new StandardSQLFunction("last_day", StandardBasicTypes.DATE) ); - registerFunction( "sysdate", new NoArgSQLFunction("sysdate", StandardBasicTypes.DATE, false) ); - registerFunction( "systimestamp", new NoArgSQLFunction("systimestamp", StandardBasicTypes.TIMESTAMP, false) ); - registerFunction( "uid", new NoArgSQLFunction("uid", StandardBasicTypes.INTEGER, false) ); - registerFunction( "user", new NoArgSQLFunction("user", StandardBasicTypes.STRING, false) ); + registerFunction( "last_day", new StandardSQLFunction( "last_day", StandardBasicTypes.DATE ) ); + registerFunction( "sysdate", new NoArgSQLFunction( "sysdate", StandardBasicTypes.DATE, false ) ); + registerFunction( "systimestamp", new NoArgSQLFunction( "systimestamp", StandardBasicTypes.TIMESTAMP, false ) ); + registerFunction( "uid", new NoArgSQLFunction( "uid", StandardBasicTypes.INTEGER, false ) ); + registerFunction( "user", new NoArgSQLFunction( "user", StandardBasicTypes.STRING, false ) ); - registerFunction( "rowid", new NoArgSQLFunction("rowid", StandardBasicTypes.LONG, false) ); - registerFunction( "rownum", new NoArgSQLFunction("rownum", StandardBasicTypes.LONG, false) ); + registerFunction( "rowid", new NoArgSQLFunction( "rowid", StandardBasicTypes.LONG, false ) ); + registerFunction( "rownum", new NoArgSQLFunction( "rownum", StandardBasicTypes.LONG, false ) ); // Multi-param string dialect functions... - registerFunction( "concat", new VarArgsSQLFunction(StandardBasicTypes.STRING, "", "||", "") ); - registerFunction( "instr", new StandardSQLFunction("instr", StandardBasicTypes.INTEGER) ); - registerFunction( "instrb", new StandardSQLFunction("instrb", StandardBasicTypes.INTEGER) ); - registerFunction( "lpad", new StandardSQLFunction("lpad", StandardBasicTypes.STRING) ); - registerFunction( "replace", new StandardSQLFunction("replace", StandardBasicTypes.STRING) ); - registerFunction( "rpad", new StandardSQLFunction("rpad", StandardBasicTypes.STRING) ); - registerFunction( "substr", new StandardSQLFunction("substr", StandardBasicTypes.STRING) ); - registerFunction( "substrb", new StandardSQLFunction("substrb", StandardBasicTypes.STRING) ); - registerFunction( "translate", new StandardSQLFunction("translate", StandardBasicTypes.STRING) ); + registerFunction( "concat", new VarArgsSQLFunction( StandardBasicTypes.STRING, "", "||", "" ) ); + registerFunction( "instr", new StandardSQLFunction( "instr", StandardBasicTypes.INTEGER ) ); + registerFunction( "instrb", new StandardSQLFunction( "instrb", StandardBasicTypes.INTEGER ) ); + registerFunction( "lpad", new StandardSQLFunction( "lpad", StandardBasicTypes.STRING ) ); + registerFunction( "replace", new StandardSQLFunction( "replace", StandardBasicTypes.STRING ) ); + registerFunction( "rpad", new StandardSQLFunction( "rpad", StandardBasicTypes.STRING ) ); + registerFunction( "substr", new StandardSQLFunction( "substr", StandardBasicTypes.STRING ) ); + registerFunction( "substrb", new StandardSQLFunction( "substrb", StandardBasicTypes.STRING ) ); + registerFunction( "translate", new StandardSQLFunction( "translate", StandardBasicTypes.STRING ) ); registerFunction( "substring", new StandardSQLFunction( "substr", StandardBasicTypes.STRING ) ); registerFunction( "locate", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "instr(?2,?1)" ) ); @@ -153,87 +166,100 @@ public class Oracle9Dialect extends Dialect { registerFunction( "coalesce", new NvlFunction() ); // Multi-param numeric dialect functions... - registerFunction( "atan2", new StandardSQLFunction("atan2", StandardBasicTypes.FLOAT) ); - registerFunction( "log", new StandardSQLFunction("log", StandardBasicTypes.INTEGER) ); - registerFunction( "mod", new StandardSQLFunction("mod", StandardBasicTypes.INTEGER) ); - registerFunction( "nvl", new StandardSQLFunction("nvl") ); - registerFunction( "nvl2", new StandardSQLFunction("nvl2") ); - registerFunction( "power", new StandardSQLFunction("power", StandardBasicTypes.FLOAT) ); + registerFunction( "atan2", new StandardSQLFunction( "atan2", StandardBasicTypes.FLOAT ) ); + registerFunction( "log", new StandardSQLFunction( "log", StandardBasicTypes.INTEGER ) ); + registerFunction( "mod", new StandardSQLFunction( "mod", StandardBasicTypes.INTEGER ) ); + registerFunction( "nvl", new StandardSQLFunction( "nvl" ) ); + registerFunction( "nvl2", new StandardSQLFunction( "nvl2" ) ); + registerFunction( "power", new StandardSQLFunction( "power", StandardBasicTypes.FLOAT ) ); // Multi-param date dialect functions... - registerFunction( "add_months", new StandardSQLFunction("add_months", StandardBasicTypes.DATE) ); - registerFunction( "months_between", new StandardSQLFunction("months_between", StandardBasicTypes.FLOAT) ); - registerFunction( "next_day", new StandardSQLFunction("next_day", StandardBasicTypes.DATE) ); + registerFunction( "add_months", new StandardSQLFunction( "add_months", StandardBasicTypes.DATE ) ); + registerFunction( "months_between", new StandardSQLFunction( "months_between", StandardBasicTypes.FLOAT ) ); + registerFunction( "next_day", new StandardSQLFunction( "next_day", StandardBasicTypes.DATE ) ); - registerFunction( "str", new StandardSQLFunction("to_char", StandardBasicTypes.STRING) ); + registerFunction( "str", new StandardSQLFunction( "to_char", StandardBasicTypes.STRING ) ); } + @Override public String getAddColumnString() { return "add"; } + @Override public String getSequenceNextValString(String sequenceName) { return "select " + getSelectSequenceNextValString( sequenceName ) + " from dual"; } + @Override public String getSelectSequenceNextValString(String sequenceName) { return sequenceName + ".nextval"; } + @Override public String getCreateSequenceString(String sequenceName) { - return "create sequence " + sequenceName; //starts with 1, implicitly + //starts with 1, implicitly + return "create sequence " + sequenceName; } + @Override public String getDropSequenceString(String sequenceName) { return "drop sequence " + sequenceName; } + @Override public String getCascadeConstraintsString() { return " cascade constraints"; } + @Override public boolean dropConstraints() { return false; } + @Override public String getForUpdateNowaitString() { return " for update nowait"; } + @Override public boolean supportsSequences() { return true; } + @Override public boolean supportsPooledSequences() { return true; } + @Override public boolean supportsLimit() { return true; } + @Override public String getLimitString(String sql, boolean hasOffset) { sql = sql.trim(); boolean isForUpdate = false; - if ( sql.toLowerCase().endsWith(" for update") ) { - sql = sql.substring( 0, sql.length()-11 ); + if ( sql.toLowerCase().endsWith( " for update" ) ) { + sql = sql.substring( 0, sql.length() - 11 ); isForUpdate = true; } - StringBuilder pagingSelect = new StringBuilder( sql.length()+100 ); - if (hasOffset) { - pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( "); + final StringBuilder pagingSelect = new StringBuilder( sql.length() + 100 ); + if ( hasOffset ) { + pagingSelect.append( "select * from ( select row_.*, rownum rownum_ from ( " ); } else { - pagingSelect.append("select * from ( "); + pagingSelect.append( "select * from ( " ); } - pagingSelect.append(sql); - if (hasOffset) { - pagingSelect.append(" ) row_ where rownum <= ?) where rownum_ > ?"); + pagingSelect.append( sql ); + if ( hasOffset ) { + pagingSelect.append( " ) row_ where rownum <= ?) where rownum_ > ?" ); } else { - pagingSelect.append(" ) where rownum <= ?"); + pagingSelect.append( " ) where rownum <= ?" ); } if ( isForUpdate ) { @@ -243,48 +269,50 @@ public class Oracle9Dialect extends Dialect { return pagingSelect.toString(); } + @Override public String getForUpdateString(String aliases) { return getForUpdateString() + " of " + aliases; } + @Override public String getForUpdateNowaitString(String aliases) { return getForUpdateString() + " of " + aliases + " nowait"; } + @Override public boolean bindLimitParametersInReverseOrder() { return true; } + @Override public boolean useMaxForLimit() { return true; } + @Override public boolean forUpdateOfColumns() { return true; } + @Override public String getQuerySequencesString() { return "select sequence_name from user_sequences"; } + @Override public String getSelectGUIDString() { return "select rawtohex(sys_guid()) from dual"; } + @Override public ViolatedConstraintNameExtracter getViolatedConstraintNameExtracter() { - return EXTRACTER; + return EXTRACTER; } - private static ViolatedConstraintNameExtracter EXTRACTER = new TemplatedViolatedConstraintNameExtracter() { - - /** - * Extract the name of the violated constraint from the given SQLException. - * - * @param sqle The exception that was the result of the constraint violation. - * @return The extracted constraint name. - */ + private static final ViolatedConstraintNameExtracter EXTRACTER = new TemplatedViolatedConstraintNameExtracter() { + @Override public String extractConstraintName(SQLException sqle) { - int errorCode = JdbcExceptionHelper.extractErrorCode( sqle ); + final int errorCode = JdbcExceptionHelper.extractErrorCode( sqle ); if ( errorCode == 1 || errorCode == 2291 || errorCode == 2292 ) { return extractUsingTemplate( "constraint (", ") violated", sqle.getMessage() ); } @@ -296,90 +324,90 @@ public class Oracle9Dialect extends Dialect { return null; } } - }; - // not final-static to avoid possible classcast exceptions if using different oracle drivers. - int oracletypes_cursor_value = 0; - public int registerResultSetOutParameter(java.sql.CallableStatement statement,int col) throws SQLException { - if(oracletypes_cursor_value==0) { - try { - Class types = ReflectHelper.classForName("oracle.jdbc.driver.OracleTypes"); - oracletypes_cursor_value = types.getField("CURSOR").getInt(types.newInstance()); - } catch (Exception se) { - throw new HibernateException("Problem while trying to load or access OracleTypes.CURSOR value",se); - } - } + @Override + public int registerResultSetOutParameter(java.sql.CallableStatement statement, int col) throws SQLException { // register the type of the out param - an Oracle specific type - statement.registerOutParameter(col, oracletypes_cursor_value); + statement.registerOutParameter( col, OracleTypesHelper.INSTANCE.getOracleCursorTypeSqlType() ); col++; return col; } + @Override public ResultSet getResultSet(CallableStatement ps) throws SQLException { ps.execute(); - return ( ResultSet ) ps.getObject( 1 ); + return (ResultSet) ps.getObject( 1 ); } + @Override public boolean supportsUnionAll() { return true; } + @Override public boolean supportsCommentOn() { return true; } + @Override public boolean supportsTemporaryTables() { return true; } + @Override public String generateTemporaryTableName(String baseTableName) { - String name = super.generateTemporaryTableName(baseTableName); + final String name = super.generateTemporaryTableName( baseTableName ); return name.length() > 30 ? name.substring( 1, 30 ) : name; } + @Override public String getCreateTemporaryTableString() { return "create global temporary table"; } + @Override public String getCreateTemporaryTablePostfix() { return "on commit delete rows"; } + @Override public boolean dropTemporaryTableAfterUse() { return false; } + @Override public boolean supportsCurrentTimestampSelection() { return true; } + @Override public String getCurrentTimestampSelectString() { return "select systimestamp from dual"; } + @Override public boolean isCurrentTimestampSelectStringCallable() { return false; } + @Override public boolean supportsEmptyInList() { return false; } + @Override public boolean supportsExistsInSelect() { return false; } - /* (non-Javadoc) - * @see org.hibernate.dialect.Dialect#getInExpressionCountLimit() - */ @Override public int getInExpressionCountLimit() { return PARAM_LIST_SIZE_LIMIT; } - + @Override - public String getNotExpression( String expression ) { + public String getNotExpression(String expression) { return "not (" + expression + ")"; } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9iDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9iDialect.java index d062ffed75..6a390cf734 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9iDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9iDialect.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import java.sql.Types; import org.hibernate.LockOptions; @@ -42,17 +43,20 @@ public class Oracle9iDialect extends Oracle8iDialect { registerColumnType( Types.VARCHAR, 4000, "varchar2($l char)" ); registerColumnType( Types.VARCHAR, "long" ); } + @Override protected void registerDateTimeTypeMappings() { registerColumnType( Types.DATE, "date" ); registerColumnType( Types.TIME, "date" ); registerColumnType( Types.TIMESTAMP, "timestamp" ); } + @Override public CaseFragment createCaseFragment() { // Oracle did add support for ANSI CASE statements in 9i return new ANSICaseFragment(); } + @Override public String getLimitString(String sql, boolean hasOffset) { sql = sql.trim(); @@ -66,19 +70,19 @@ public class Oracle9iDialect extends Oracle8iDialect { isForUpdate = true; } - StringBuilder pagingSelect = new StringBuilder( sql.length() + 100 ); + final StringBuilder pagingSelect = new StringBuilder( sql.length() + 100 ); if (hasOffset) { - pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( "); + pagingSelect.append( "select * from ( select row_.*, rownum rownum_ from ( " ); } else { - pagingSelect.append("select * from ( "); + pagingSelect.append( "select * from ( " ); } - pagingSelect.append(sql); + pagingSelect.append( sql ); if (hasOffset) { - pagingSelect.append(" ) row_ where rownum <= ?) where rownum_ > ?"); + pagingSelect.append( " ) row_ where rownum <= ?) where rownum_ > ?" ); } else { - pagingSelect.append(" ) where rownum <= ?"); + pagingSelect.append( " ) where rownum <= ?" ); } if ( isForUpdate ) { @@ -88,25 +92,28 @@ public class Oracle9iDialect extends Oracle8iDialect { return pagingSelect.toString(); } + @Override public String getSelectClauseNullString(int sqlType) { return getBasicSelectClauseNullString( sqlType ); } + @Override public String getCurrentTimestampSelectString() { return "select systimestamp from dual"; } + @Override public String getCurrentTimestampSQLFunctionName() { // the standard SQL function name is current_timestamp... return "current_timestamp"; } - // locking support @Override public String getForUpdateString() { return " for update"; } + @Override public String getWriteLockString(int timeout) { if ( timeout == LockOptions.NO_WAIT ) { @@ -114,25 +121,31 @@ public class Oracle9iDialect extends Oracle8iDialect { } else if ( timeout > 0 ) { // convert from milliseconds to seconds - float seconds = timeout / 1000.0f; + final float seconds = timeout / 1000.0f; timeout = Math.round(seconds); return " for update wait " + timeout; } - else + else { return " for update"; + } } + @Override public String getReadLockString(int timeout) { return getWriteLockString( timeout ); } + /** * HHH-4907, I don't know if oracle 8 supports this syntax, so I'd think it is better add this * method here. Reopen this issue if you found/know 8 supports it. + *

    + * {@inheritDoc} */ @Override public boolean supportsRowValueConstructorSyntaxInInList() { return true; } + @Override public boolean supportsTupleDistinctCounts() { return false; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/OracleDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/OracleDialect.java index a34dab7190..5823290088 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/OracleDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/OracleDialect.java @@ -38,11 +38,17 @@ import org.hibernate.sql.OracleJoinFragment; * @deprecated Use Oracle8iDialect instead. * @author Gavin King */ +@SuppressWarnings("deprecation") @Deprecated public class OracleDialect extends Oracle9Dialect { + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + OracleDialect.class.getName() + ); - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, OracleDialect.class.getName()); - + /** + * Constructs a (DEPRECATED) Oracle9Dialect + */ public OracleDialect() { super(); LOG.deprecatedOracleDialect(); @@ -54,37 +60,38 @@ public class OracleDialect extends Oracle9Dialect { } @Override - public JoinFragment createOuterJoinFragment() { + public JoinFragment createOuterJoinFragment() { return new OracleJoinFragment(); } + @Override - public CaseFragment createCaseFragment() { + public CaseFragment createCaseFragment() { return new DecodeCaseFragment(); } @Override - public String getLimitString(String sql, boolean hasOffset) { + public String getLimitString(String sql, boolean hasOffset) { sql = sql.trim(); boolean isForUpdate = false; - if ( sql.toLowerCase().endsWith(" for update") ) { + if ( sql.toLowerCase().endsWith( " for update" ) ) { sql = sql.substring( 0, sql.length()-11 ); isForUpdate = true; } - StringBuilder pagingSelect = new StringBuilder( sql.length()+100 ); + final StringBuilder pagingSelect = new StringBuilder( sql.length()+100 ); if (hasOffset) { - pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( "); + pagingSelect.append( "select * from ( select row_.*, rownum rownum_ from ( " ); } else { - pagingSelect.append("select * from ( "); + pagingSelect.append( "select * from ( " ); } - pagingSelect.append(sql); + pagingSelect.append( sql ); if (hasOffset) { - pagingSelect.append(" ) row_ ) where rownum_ <= ? and rownum_ > ?"); + pagingSelect.append( " ) row_ ) where rownum_ <= ? and rownum_ > ?" ); } else { - pagingSelect.append(" ) where rownum <= ?"); + pagingSelect.append( " ) where rownum <= ?" ); } if ( isForUpdate ) { @@ -95,7 +102,7 @@ public class OracleDialect extends Oracle9Dialect { } @Override - public String getSelectClauseNullString(int sqlType) { + public String getSelectClauseNullString(int sqlType) { switch(sqlType) { case Types.VARCHAR: case Types.CHAR: @@ -110,12 +117,12 @@ public class OracleDialect extends Oracle9Dialect { } @Override - public String getCurrentTimestampSelectString() { + public String getCurrentTimestampSelectString() { return "select sysdate from dual"; } @Override - public String getCurrentTimestampSQLFunctionName() { + public String getCurrentTimestampSQLFunctionName() { return "sysdate"; } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/OracleTypesHelper.java b/hibernate-core/src/main/java/org/hibernate/dialect/OracleTypesHelper.java new file mode 100644 index 0000000000..7446af9560 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/dialect/OracleTypesHelper.java @@ -0,0 +1,128 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.dialect; + +import org.jboss.logging.Logger; + +import org.hibernate.HibernateException; +import org.hibernate.internal.CoreMessageLogger; +import org.hibernate.internal.util.ReflectHelper; + +/** + * A Helper for dealing with the OracleTypes class + * + * @author Steve Ebersole + */ +public class OracleTypesHelper { + private static final CoreMessageLogger log = Logger.getMessageLogger( CoreMessageLogger.class, OracleTypesHelper.class.getName() ); + + /** + * Singleton access + */ + public static final OracleTypesHelper INSTANCE = new OracleTypesHelper(); + + private static final String ORACLE_TYPES_CLASS_NAME = "oracle.jdbc.OracleTypes"; + private static final String DEPRECATED_ORACLE_TYPES_CLASS_NAME = "oracle.jdbc.driver.OracleTypes"; + + private final int oracleCursorTypeSqlType; + + private OracleTypesHelper() { + int typeCode = -99; + try { + typeCode = extractOracleCursorTypeValue(); + } + catch (Exception e) { + log.warn( "Unable to resolve Oracle CURSOR JDBC type code", e ); + } + oracleCursorTypeSqlType = typeCode; + } + + private int extractOracleCursorTypeValue() { + try { + return locateOracleTypesClass().getField( "CURSOR" ).getInt( null ); + } + catch ( Exception se ) { + throw new HibernateException( "Unable to access OracleTypes.CURSOR value", se ); + } + } + + private Class locateOracleTypesClass() { + try { + return ReflectHelper.classForName( ORACLE_TYPES_CLASS_NAME ); + } + catch (ClassNotFoundException e) { + try { + return ReflectHelper.classForName( DEPRECATED_ORACLE_TYPES_CLASS_NAME ); + } + catch (ClassNotFoundException e2) { + throw new HibernateException( + String.format( + "Unable to locate OracleTypes class using either known FQN [%s, %s]", + ORACLE_TYPES_CLASS_NAME, + DEPRECATED_ORACLE_TYPES_CLASS_NAME + ), + e + ); + } + } + } + + public int getOracleCursorTypeSqlType() { + return oracleCursorTypeSqlType; + } + +// initial code as copied from Oracle8iDialect +// +// private int oracleCursorTypeSqlType = INIT_ORACLETYPES_CURSOR_VALUE; +// +// public int getOracleCursorTypeSqlType() { +// if ( oracleCursorTypeSqlType == INIT_ORACLETYPES_CURSOR_VALUE ) { +// // todo : is there really any reason to keep trying if this fails once? +// oracleCursorTypeSqlType = extractOracleCursorTypeValue(); +// } +// return oracleCursorTypeSqlType; +// } +// +// private int extractOracleCursorTypeValue() { +// Class oracleTypesClass; +// try { +// oracleTypesClass = ReflectHelper.classForName( ORACLE_TYPES_CLASS_NAME ); +// } +// catch ( ClassNotFoundException cnfe ) { +// try { +// oracleTypesClass = ReflectHelper.classForName( DEPRECATED_ORACLE_TYPES_CLASS_NAME ); +// } +// catch ( ClassNotFoundException e ) { +// throw new HibernateException( "Unable to locate OracleTypes class", e ); +// } +// } +// +// try { +// return oracleTypesClass.getField( "CURSOR" ).getInt( null ); +// } +// catch ( Exception se ) { +// throw new HibernateException( "Unable to access OracleTypes.CURSOR value", se ); +// } +// } +} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/PointbaseDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/PointbaseDialect.java index fb6a47e01a..b0865aa3b0 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/PointbaseDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/PointbaseDialect.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import java.sql.Types; import org.hibernate.LockMode; @@ -36,20 +37,22 @@ import org.hibernate.dialect.lock.UpdateLockingStrategy; import org.hibernate.persister.entity.Lockable; /** - * A Dialect for Pointbase. + * A Dialect for Pointbase. + * * @author Ed Mackenzie */ public class PointbaseDialect extends org.hibernate.dialect.Dialect { - /** * Creates new PointbaseDialect */ public PointbaseDialect() { super(); - registerColumnType( Types.BIT, "smallint" ); //no pointbase BIT + //no pointbase BIT + registerColumnType( Types.BIT, "smallint" ); registerColumnType( Types.BIGINT, "bigint" ); registerColumnType( Types.SMALLINT, "smallint" ); - registerColumnType( Types.TINYINT, "smallint" ); //no pointbase TINYINT + //no pointbase TINYINT + registerColumnType( Types.TINYINT, "smallint" ); registerColumnType( Types.INTEGER, "integer" ); registerColumnType( Types.CHAR, "char(1)" ); registerColumnType( Types.VARCHAR, "varchar($l)" ); @@ -66,22 +69,27 @@ public class PointbaseDialect extends org.hibernate.dialect.Dialect { registerColumnType( Types.NUMERIC, "numeric($p,$s)" ); } + @Override public String getAddColumnString() { return "add"; } + @Override public boolean dropConstraints() { return false; } + @Override public String getCascadeConstraintsString() { return " cascade"; } + @Override public String getForUpdateString() { return ""; } + @Override public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) { // Pointbase has no known variation of a "SELECT ... FOR UPDATE" syntax... if ( lockMode==LockMode.PESSIMISTIC_FORCE_INCREMENT) { diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQL81Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQL81Dialect.java index 446ffab574..0b9d5334bd 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQL81Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQL81Dialect.java @@ -57,8 +57,12 @@ import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; * * @author Gavin King */ +@SuppressWarnings("deprecation") public class PostgreSQL81Dialect extends Dialect { + /** + * Constructs a PostgreSQL81Dialect + */ public PostgreSQL81Dialect() { super(); registerColumnType( Types.BIT, "bool" ); @@ -152,13 +156,10 @@ public class PostgreSQL81Dialect extends Dialect { registerFunction( "str", new SQLFunctionTemplate(StandardBasicTypes.STRING, "cast(?1 as varchar)") ); - getDefaultProperties().setProperty(Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE); + getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE ); getDefaultProperties().setProperty( Environment.NON_CONTEXTUAL_LOB_CREATION, "true" ); } - /** - * {@inheritDoc} - */ @Override public SqlTypeDescriptor getSqlTypeDescriptorOverride(int sqlCode) { SqlTypeDescriptor descriptor; @@ -183,87 +184,100 @@ public class PostgreSQL81Dialect extends Dialect { return descriptor; } + @Override public String getAddColumnString() { return "add column"; } + @Override public String getSequenceNextValString(String sequenceName) { return "select " + getSelectSequenceNextValString( sequenceName ); } + @Override public String getSelectSequenceNextValString(String sequenceName) { return "nextval ('" + sequenceName + "')"; } + @Override public String getCreateSequenceString(String sequenceName) { - return "create sequence " + sequenceName; //starts with 1, implicitly + //starts with 1, implicitly + return "create sequence " + sequenceName; } + @Override public String getDropSequenceString(String sequenceName) { return "drop sequence " + sequenceName; } + @Override public String getCascadeConstraintsString() { return " cascade"; } + + @Override public boolean dropConstraints() { return true; } + @Override public boolean supportsSequences() { return true; } + @Override public String getQuerySequencesString() { return "select relname from pg_class where relkind='S'"; } + @Override public boolean supportsLimit() { return true; } + @Override public String getLimitString(String sql, boolean hasOffset) { - return new StringBuilder( sql.length()+20 ) - .append( sql ) - .append( hasOffset ? " limit ? offset ?" : " limit ?" ) - .toString(); + return sql + (hasOffset ? " limit ? offset ?" : " limit ?"); } + @Override public boolean bindLimitParametersInReverseOrder() { return true; } + @Override public boolean supportsIdentityColumns() { return true; } + @Override public String getForUpdateString(String aliases) { return getForUpdateString() + " of " + aliases; } + @Override public String getIdentitySelectString(String table, String column, int type) { - return new StringBuilder().append("select currval('") - .append(table) - .append('_') - .append(column) - .append("_seq')") - .toString(); + return "select currval('" + table + '_' + column + "_seq')"; } + @Override public String getIdentityColumnString(int type) { return type==Types.BIGINT ? "bigserial not null" : "serial not null"; } + @Override public boolean hasDataTypeInIdentityColumn() { return false; } + @Override public String getNoColumnsInsertString() { return "default values"; } + @Override public String getCaseInsensitiveLike(){ return "ilike"; } @@ -273,77 +287,88 @@ public class PostgreSQL81Dialect extends Dialect { return true; } + @Override public Class getNativeIdentifierGeneratorClass() { return SequenceGenerator.class; } + @Override public boolean supportsOuterJoinForUpdate() { return false; } - + + @Override public boolean useInputStreamToInsertBlob() { return false; } + @Override public boolean supportsUnionAll() { return true; } /** * Workaround for postgres bug #1453 + *

    + * {@inheritDoc} */ + @Override public String getSelectClauseNullString(int sqlType) { - String typeName = getTypeName(sqlType, 1, 1, 0); + String typeName = getTypeName( sqlType, 1, 1, 0 ); //trim off the length/precision/scale - int loc = typeName.indexOf('('); - if (loc>-1) { - typeName = typeName.substring(0, loc); + final int loc = typeName.indexOf( '(' ); + if ( loc > -1 ) { + typeName = typeName.substring( 0, loc ); } return "null::" + typeName; } + @Override public boolean supportsCommentOn() { return true; } + @Override public boolean supportsTemporaryTables() { return true; } + @Override public String getCreateTemporaryTableString() { return "create temporary table"; } + @Override public String getCreateTemporaryTablePostfix() { return "on commit drop"; } - /*public boolean dropTemporaryTableAfterUse() { - //we have to, because postgres sets current tx - //to rollback only after a failed create table - return true; - }*/ - + @Override public boolean supportsCurrentTimestampSelection() { return true; } + @Override public boolean isCurrentTimestampSelectStringCallable() { return false; } + @Override public String getCurrentTimestampSelectString() { return "select now()"; } + @Override public boolean supportsTupleDistinctCounts() { return false; } + @Override public String toBooleanValueString(boolean bool) { return bool ? "true" : "false"; } + @Override public ViolatedConstraintNameExtracter getViolatedConstraintNameExtracter() { return EXTRACTER; } @@ -352,25 +377,26 @@ public class PostgreSQL81Dialect extends Dialect { * Constraint-name extractor for Postgres constraint violation exceptions. * Orginally contributed by Denny Bartelt. */ - private static ViolatedConstraintNameExtracter EXTRACTER = new TemplatedViolatedConstraintNameExtracter() { + private static final ViolatedConstraintNameExtracter EXTRACTER = new TemplatedViolatedConstraintNameExtracter() { public String extractConstraintName(SQLException sqle) { try { - int sqlState = Integer.valueOf( JdbcExceptionHelper.extractSqlState( sqle ) ); + final int sqlState = Integer.valueOf( JdbcExceptionHelper.extractSqlState( sqle ) ); switch (sqlState) { // CHECK VIOLATION - case 23514: return extractUsingTemplate("violates check constraint \"","\"", sqle.getMessage()); + case 23514: return extractUsingTemplate( "violates check constraint \"","\"", sqle.getMessage() ); // UNIQUE VIOLATION - case 23505: return extractUsingTemplate("violates unique constraint \"","\"", sqle.getMessage()); + case 23505: return extractUsingTemplate( "violates unique constraint \"","\"", sqle.getMessage() ); // FOREIGN KEY VIOLATION - case 23503: return extractUsingTemplate("violates foreign key constraint \"","\"", sqle.getMessage()); + case 23503: return extractUsingTemplate( "violates foreign key constraint \"","\"", sqle.getMessage() ); // NOT NULL VIOLATION - case 23502: return extractUsingTemplate("null value in column \"","\" violates not-null constraint", sqle.getMessage()); + case 23502: return extractUsingTemplate( "null value in column \"","\" violates not-null constraint", sqle.getMessage() ); // TODO: RESTRICT VIOLATION case 23001: return null; // ALL OTHER default: return null; } - } catch (NumberFormatException nfe) { + } + catch (NumberFormatException nfe) { return null; } } @@ -383,11 +409,13 @@ public class PostgreSQL81Dialect extends Dialect { public JDBCException convert(SQLException sqlException, String message, String sql) { final String sqlState = JdbcExceptionHelper.extractSqlState( sqlException ); - if ( "40P01".equals( sqlState ) ) { // DEADLOCK DETECTED + if ( "40P01".equals( sqlState ) ) { + // DEADLOCK DETECTED return new LockAcquisitionException( message, sqlException, sql ); } - if ( "55P03".equals( sqlState ) ) { // LOCK NOT AVAILABLE + if ( "55P03".equals( sqlState ) ) { + // LOCK NOT AVAILABLE return new PessimisticLockException( message, sqlException, sql ); } @@ -396,37 +424,39 @@ public class PostgreSQL81Dialect extends Dialect { } }; } - + + @Override public int registerResultSetOutParameter(CallableStatement statement, int col) throws SQLException { // Register the type of the out param - PostgreSQL uses Types.OTHER - statement.registerOutParameter(col++, Types.OTHER); + statement.registerOutParameter( col++, Types.OTHER ); return col; } + @Override public ResultSet getResultSet(CallableStatement ps) throws SQLException { ps.execute(); - return (ResultSet) ps.getObject(1); + return (ResultSet) ps.getObject( 1 ); } + @Override public boolean supportsPooledSequences() { return true; } - //only necessary for postgre < 7.4 - //http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/doc/src/sgml/ref/create_sequence.sgml + /** + * only necessary for postgre < 7.4 See http://anoncvs.postgresql.org/cvsweb.cgi/pgsql/doc/src/sgml/ref/create_sequence.sgml + *

    + * {@inheritDoc} + */ + @Override protected String getCreateSequenceString(String sequenceName, int initialValue, int incrementSize) { return getCreateSequenceString( sequenceName ) + " start " + initialValue + " increment " + incrementSize; } // Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -// seems to not really... -// public boolean supportsRowValueConstructorSyntax() { -// return true; -// } - - - public boolean supportsEmptyInList() { + @Override + public boolean supportsEmptyInList() { return false; } @@ -445,25 +475,32 @@ public class PostgreSQL81Dialect extends Dialect { return false; } - // locking support + @Override public String getForUpdateString() { return " for update"; } + @Override public String getWriteLockString(int timeout) { - if ( timeout == LockOptions.NO_WAIT ) + if ( timeout == LockOptions.NO_WAIT ) { return " for update nowait"; - else + } + else { return " for update"; + } } + @Override public String getReadLockString(int timeout) { - if ( timeout == LockOptions.NO_WAIT ) + if ( timeout == LockOptions.NO_WAIT ) { return " for share nowait"; - else + } + else { return " for share"; + } } + @Override public boolean supportsRowValueConstructorSyntax() { return true; } @@ -475,6 +512,6 @@ public class PostgreSQL81Dialect extends Dialect { @Override public String getForUpdateNowaitString(String aliases) { - return getForUpdateString(aliases) + " nowait "; + return getForUpdateString( aliases ) + " nowait "; } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQL82Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQL82Dialect.java index 50b84be0da..c4fc513639 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQL82Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQL82Dialect.java @@ -30,7 +30,7 @@ package org.hibernate.dialect; */ public class PostgreSQL82Dialect extends PostgreSQL81Dialect { @Override - public boolean supportsIfExistsBeforeTableName() { - return true; - } + public boolean supportsIfExistsBeforeTableName() { + return true; + } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQLDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQLDialect.java index 4a8a3e3819..bf70aa08f6 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQLDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/PostgreSQLDialect.java @@ -23,7 +23,6 @@ */ package org.hibernate.dialect; - /** * An SQL dialect for Postgres *

    @@ -32,6 +31,7 @@ package org.hibernate.dialect; * For the effects in regards to Hibernate see http://in.relation.to/15492.lace * * @author Gavin King + * * @deprecated use {@link PostgreSQL82Dialect} instead */ @Deprecated diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/PostgresPlusDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/PostgresPlusDialect.java index 565f74f78d..60c2eeb131 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/PostgresPlusDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/PostgresPlusDialect.java @@ -37,8 +37,11 @@ import org.hibernate.type.StandardBasicTypes; * * @author Jim Mlodgenski */ +@SuppressWarnings("deprecation") public class PostgresPlusDialect extends PostgreSQLDialect { - + /** + * Constructs a PostgresPlusDialect + */ public PostgresPlusDialect() { super(); @@ -65,25 +68,30 @@ public class PostgresPlusDialect extends PostgreSQLDialect { registerFunction( "next_day", new StandardSQLFunction( "next_day", StandardBasicTypes.DATE ) ); } + @Override public String getCurrentTimestampSelectString() { return "select sysdate"; } + @Override public String getCurrentTimestampSQLFunctionName() { return "sysdate"; } + @Override public int registerResultSetOutParameter(CallableStatement statement, int col) throws SQLException { statement.registerOutParameter( col, Types.REF ); col++; return col; } + @Override public ResultSet getResultSet(CallableStatement ps) throws SQLException { ps.execute(); - return ( ResultSet ) ps.getObject( 1 ); + return (ResultSet) ps.getObject( 1 ); } + @Override public String getSelectGUIDString() { return "select uuid_generate_v1"; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/ProgressDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/ProgressDialect.java index cae9befaad..aff93818a0 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/ProgressDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/ProgressDialect.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import java.sql.Types; /** @@ -41,6 +42,9 @@ import java.sql.Types; * */ public class ProgressDialect extends Dialect { + /** + * Constructs a ProgressDialect + */ public ProgressDialect() { super(); registerColumnType( Types.BIT, "bit" ); @@ -59,14 +63,17 @@ public class ProgressDialect extends Dialect { registerColumnType( Types.NUMERIC, "numeric($p,$s)" ); } + @Override public boolean hasAlterTable(){ return false; } + @Override public String getAddColumnString() { return "add column"; } + @Override public boolean qualifyIndexName() { return false; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/RDMSOS2200Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/RDMSOS2200Dialect.java index ccec37a7c7..d168165a2f 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/RDMSOS2200Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/RDMSOS2200Dialect.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import java.sql.Types; import org.jboss.logging.Logger; @@ -48,7 +49,7 @@ import org.hibernate.type.StandardBasicTypes; * This is the Hibernate dialect for the Unisys 2200 Relational Database (RDMS). * This dialect was developed for use with Hibernate 3.0.5. Other versions may * require modifications to the dialect. - * + *

    * Version History: * Also change the version displayed below in the constructor * 1.1 @@ -56,108 +57,114 @@ import org.hibernate.type.StandardBasicTypes; * * @author Ploski and Hanson */ +@SuppressWarnings("deprecation") public class RDMSOS2200Dialect extends Dialect { + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + RDMSOS2200Dialect.class.getName() + ); - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, RDMSOS2200Dialect.class.getName()); - + /** + * Constructs a RDMSOS2200Dialect + */ public RDMSOS2200Dialect() { super(); // Display the dialect version. LOG.rdmsOs2200Dialect(); - /** - * This section registers RDMS Built-in Functions (BIFs) with Hibernate. - * The first parameter is the 'register' function name with Hibernate. - * The second parameter is the defined RDMS SQL Function and it's - * characteristics. If StandardSQLFunction(...) is used, the RDMS BIF - * name and the return type (if any) is specified. If - * SQLFunctionTemplate(...) is used, the return type and a template - * string is provided, plus an optional hasParenthesesIfNoArgs flag. - */ - registerFunction( "abs", new StandardSQLFunction("abs") ); - registerFunction( "sign", new StandardSQLFunction("sign", StandardBasicTypes.INTEGER) ); + /** + * This section registers RDMS Built-in Functions (BIFs) with Hibernate. + * The first parameter is the 'register' function name with Hibernate. + * The second parameter is the defined RDMS SQL Function and it's + * characteristics. If StandardSQLFunction(...) is used, the RDMS BIF + * name and the return type (if any) is specified. If + * SQLFunctionTemplate(...) is used, the return type and a template + * string is provided, plus an optional hasParenthesesIfNoArgs flag. + */ + registerFunction( "abs", new StandardSQLFunction( "abs" ) ); + registerFunction( "sign", new StandardSQLFunction( "sign", StandardBasicTypes.INTEGER ) ); - registerFunction("ascii", new StandardSQLFunction("ascii", StandardBasicTypes.INTEGER) ); - registerFunction("char_length", new StandardSQLFunction("char_length", StandardBasicTypes.INTEGER) ); - registerFunction("character_length", new StandardSQLFunction("character_length", StandardBasicTypes.INTEGER) ); + registerFunction( "ascii", new StandardSQLFunction( "ascii", StandardBasicTypes.INTEGER ) ); + registerFunction( "char_length", new StandardSQLFunction( "char_length", StandardBasicTypes.INTEGER ) ); + registerFunction( "character_length", new StandardSQLFunction( "character_length", StandardBasicTypes.INTEGER ) ); // The RDMS concat() function only supports 2 parameters - registerFunction( "concat", new SQLFunctionTemplate(StandardBasicTypes.STRING, "concat(?1, ?2)") ); - registerFunction( "instr", new StandardSQLFunction("instr", StandardBasicTypes.STRING) ); - registerFunction( "lpad", new StandardSQLFunction("lpad", StandardBasicTypes.STRING) ); - registerFunction( "replace", new StandardSQLFunction("replace", StandardBasicTypes.STRING) ); - registerFunction( "rpad", new StandardSQLFunction("rpad", StandardBasicTypes.STRING) ); - registerFunction( "substr", new StandardSQLFunction("substr", StandardBasicTypes.STRING) ); + registerFunction( "concat", new SQLFunctionTemplate( StandardBasicTypes.STRING, "concat(?1, ?2)" ) ); + registerFunction( "instr", new StandardSQLFunction( "instr", StandardBasicTypes.STRING ) ); + registerFunction( "lpad", new StandardSQLFunction( "lpad", StandardBasicTypes.STRING ) ); + registerFunction( "replace", new StandardSQLFunction( "replace", StandardBasicTypes.STRING ) ); + registerFunction( "rpad", new StandardSQLFunction( "rpad", StandardBasicTypes.STRING ) ); + registerFunction( "substr", new StandardSQLFunction( "substr", StandardBasicTypes.STRING ) ); - registerFunction("lcase", new StandardSQLFunction("lcase") ); - registerFunction("lower", new StandardSQLFunction("lower") ); - registerFunction("ltrim", new StandardSQLFunction("ltrim") ); - registerFunction("reverse", new StandardSQLFunction("reverse") ); - registerFunction("rtrim", new StandardSQLFunction("rtrim") ); + registerFunction( "lcase", new StandardSQLFunction( "lcase" ) ); + registerFunction( "lower", new StandardSQLFunction( "lower" ) ); + registerFunction( "ltrim", new StandardSQLFunction( "ltrim" ) ); + registerFunction( "reverse", new StandardSQLFunction( "reverse" ) ); + registerFunction( "rtrim", new StandardSQLFunction( "rtrim" ) ); // RDMS does not directly support the trim() function, we use rtrim() and ltrim() - registerFunction("trim", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "ltrim(rtrim(?1))" ) ); - registerFunction("soundex", new StandardSQLFunction("soundex") ); - registerFunction("space", new StandardSQLFunction("space", StandardBasicTypes.STRING) ); - registerFunction("ucase", new StandardSQLFunction("ucase") ); - registerFunction("upper", new StandardSQLFunction("upper") ); + registerFunction( "trim", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "ltrim(rtrim(?1))" ) ); + registerFunction( "soundex", new StandardSQLFunction( "soundex" ) ); + registerFunction( "space", new StandardSQLFunction( "space", StandardBasicTypes.STRING ) ); + registerFunction( "ucase", new StandardSQLFunction( "ucase" ) ); + registerFunction( "upper", new StandardSQLFunction( "upper" ) ); - registerFunction("acos", new StandardSQLFunction("acos", StandardBasicTypes.DOUBLE) ); - registerFunction("asin", new StandardSQLFunction("asin", StandardBasicTypes.DOUBLE) ); - registerFunction("atan", new StandardSQLFunction("atan", StandardBasicTypes.DOUBLE) ); - registerFunction("cos", new StandardSQLFunction("cos", StandardBasicTypes.DOUBLE) ); - registerFunction("cosh", new StandardSQLFunction("cosh", StandardBasicTypes.DOUBLE) ); - registerFunction("cot", new StandardSQLFunction("cot", StandardBasicTypes.DOUBLE) ); - registerFunction("exp", new StandardSQLFunction("exp", StandardBasicTypes.DOUBLE) ); - registerFunction("ln", new StandardSQLFunction("ln", StandardBasicTypes.DOUBLE) ); - registerFunction("log", new StandardSQLFunction("log", StandardBasicTypes.DOUBLE) ); - registerFunction("log10", new StandardSQLFunction("log10", StandardBasicTypes.DOUBLE) ); - registerFunction("pi", new NoArgSQLFunction("pi", StandardBasicTypes.DOUBLE) ); - registerFunction("rand", new NoArgSQLFunction("rand", StandardBasicTypes.DOUBLE) ); - registerFunction("sin", new StandardSQLFunction("sin", StandardBasicTypes.DOUBLE) ); - registerFunction("sinh", new StandardSQLFunction("sinh", StandardBasicTypes.DOUBLE) ); - registerFunction("sqrt", new StandardSQLFunction("sqrt", StandardBasicTypes.DOUBLE) ); - registerFunction("tan", new StandardSQLFunction("tan", StandardBasicTypes.DOUBLE) ); - registerFunction("tanh", new StandardSQLFunction("tanh", StandardBasicTypes.DOUBLE) ); + registerFunction( "acos", new StandardSQLFunction( "acos", StandardBasicTypes.DOUBLE ) ); + registerFunction( "asin", new StandardSQLFunction( "asin", StandardBasicTypes.DOUBLE ) ); + registerFunction( "atan", new StandardSQLFunction( "atan", StandardBasicTypes.DOUBLE ) ); + registerFunction( "cos", new StandardSQLFunction( "cos", StandardBasicTypes.DOUBLE ) ); + registerFunction( "cosh", new StandardSQLFunction( "cosh", StandardBasicTypes.DOUBLE ) ); + registerFunction( "cot", new StandardSQLFunction( "cot", StandardBasicTypes.DOUBLE ) ); + registerFunction( "exp", new StandardSQLFunction( "exp", StandardBasicTypes.DOUBLE ) ); + registerFunction( "ln", new StandardSQLFunction( "ln", StandardBasicTypes.DOUBLE ) ); + registerFunction( "log", new StandardSQLFunction( "log", StandardBasicTypes.DOUBLE ) ); + registerFunction( "log10", new StandardSQLFunction( "log10", StandardBasicTypes.DOUBLE ) ); + registerFunction( "pi", new NoArgSQLFunction( "pi", StandardBasicTypes.DOUBLE ) ); + registerFunction( "rand", new NoArgSQLFunction( "rand", StandardBasicTypes.DOUBLE ) ); + registerFunction( "sin", new StandardSQLFunction( "sin", StandardBasicTypes.DOUBLE ) ); + registerFunction( "sinh", new StandardSQLFunction( "sinh", StandardBasicTypes.DOUBLE ) ); + registerFunction( "sqrt", new StandardSQLFunction( "sqrt", StandardBasicTypes.DOUBLE ) ); + registerFunction( "tan", new StandardSQLFunction( "tan", StandardBasicTypes.DOUBLE ) ); + registerFunction( "tanh", new StandardSQLFunction( "tanh", StandardBasicTypes.DOUBLE ) ); - registerFunction( "round", new StandardSQLFunction("round") ); - registerFunction( "trunc", new StandardSQLFunction("trunc") ); - registerFunction( "ceil", new StandardSQLFunction("ceil") ); - registerFunction( "floor", new StandardSQLFunction("floor") ); + registerFunction( "round", new StandardSQLFunction( "round" ) ); + registerFunction( "trunc", new StandardSQLFunction( "trunc" ) ); + registerFunction( "ceil", new StandardSQLFunction( "ceil" ) ); + registerFunction( "floor", new StandardSQLFunction( "floor" ) ); - registerFunction( "chr", new StandardSQLFunction("chr", StandardBasicTypes.CHARACTER) ); - registerFunction( "initcap", new StandardSQLFunction("initcap") ); + registerFunction( "chr", new StandardSQLFunction( "chr", StandardBasicTypes.CHARACTER ) ); + registerFunction( "initcap", new StandardSQLFunction( "initcap" ) ); - registerFunction( "user", new NoArgSQLFunction("user", StandardBasicTypes.STRING, false) ); + registerFunction( "user", new NoArgSQLFunction( "user", StandardBasicTypes.STRING, false ) ); - registerFunction( "current_date", new NoArgSQLFunction("current_date", StandardBasicTypes.DATE, false) ); - registerFunction( "current_time", new NoArgSQLFunction("current_timestamp", StandardBasicTypes.TIME, false) ); - registerFunction( "current_timestamp", new NoArgSQLFunction("current_timestamp", StandardBasicTypes.TIMESTAMP, false) ); - registerFunction("curdate", new NoArgSQLFunction("curdate",StandardBasicTypes.DATE) ); - registerFunction("curtime", new NoArgSQLFunction("curtime",StandardBasicTypes.TIME) ); - registerFunction("days", new StandardSQLFunction("days",StandardBasicTypes.INTEGER) ); - registerFunction("dayofmonth", new StandardSQLFunction("dayofmonth",StandardBasicTypes.INTEGER) ); - registerFunction("dayname", new StandardSQLFunction("dayname",StandardBasicTypes.STRING) ); - registerFunction("dayofweek", new StandardSQLFunction("dayofweek",StandardBasicTypes.INTEGER) ); - registerFunction("dayofyear", new StandardSQLFunction("dayofyear",StandardBasicTypes.INTEGER) ); - registerFunction("hour", new StandardSQLFunction("hour",StandardBasicTypes.INTEGER) ); - registerFunction("last_day", new StandardSQLFunction("last_day",StandardBasicTypes.DATE) ); - registerFunction("microsecond", new StandardSQLFunction("microsecond",StandardBasicTypes.INTEGER) ); - registerFunction("minute", new StandardSQLFunction("minute",StandardBasicTypes.INTEGER) ); - registerFunction("month", new StandardSQLFunction("month",StandardBasicTypes.INTEGER) ); - registerFunction("monthname", new StandardSQLFunction("monthname",StandardBasicTypes.STRING) ); - registerFunction("now", new NoArgSQLFunction("now",StandardBasicTypes.TIMESTAMP) ); - registerFunction("quarter", new StandardSQLFunction("quarter",StandardBasicTypes.INTEGER) ); - registerFunction("second", new StandardSQLFunction("second",StandardBasicTypes.INTEGER) ); - registerFunction("time", new StandardSQLFunction("time",StandardBasicTypes.TIME) ); - registerFunction("timestamp", new StandardSQLFunction("timestamp",StandardBasicTypes.TIMESTAMP) ); - registerFunction("week", new StandardSQLFunction("week",StandardBasicTypes.INTEGER) ); - registerFunction("year", new StandardSQLFunction("year",StandardBasicTypes.INTEGER) ); + registerFunction( "current_date", new NoArgSQLFunction( "current_date", StandardBasicTypes.DATE, false ) ); + registerFunction( "current_time", new NoArgSQLFunction( "current_timestamp", StandardBasicTypes.TIME, false ) ); + registerFunction( "current_timestamp", new NoArgSQLFunction( "current_timestamp", StandardBasicTypes.TIMESTAMP, false ) ); + registerFunction( "curdate", new NoArgSQLFunction( "curdate", StandardBasicTypes.DATE ) ); + registerFunction( "curtime", new NoArgSQLFunction( "curtime", StandardBasicTypes.TIME ) ); + registerFunction( "days", new StandardSQLFunction( "days", StandardBasicTypes.INTEGER ) ); + registerFunction( "dayofmonth", new StandardSQLFunction( "dayofmonth", StandardBasicTypes.INTEGER ) ); + registerFunction( "dayname", new StandardSQLFunction( "dayname", StandardBasicTypes.STRING ) ); + registerFunction( "dayofweek", new StandardSQLFunction( "dayofweek", StandardBasicTypes.INTEGER ) ); + registerFunction( "dayofyear", new StandardSQLFunction( "dayofyear", StandardBasicTypes.INTEGER ) ); + registerFunction( "hour", new StandardSQLFunction( "hour", StandardBasicTypes.INTEGER ) ); + registerFunction( "last_day", new StandardSQLFunction( "last_day", StandardBasicTypes.DATE ) ); + registerFunction( "microsecond", new StandardSQLFunction( "microsecond", StandardBasicTypes.INTEGER ) ); + registerFunction( "minute", new StandardSQLFunction( "minute", StandardBasicTypes.INTEGER ) ); + registerFunction( "month", new StandardSQLFunction( "month", StandardBasicTypes.INTEGER ) ); + registerFunction( "monthname", new StandardSQLFunction( "monthname", StandardBasicTypes.STRING ) ); + registerFunction( "now", new NoArgSQLFunction( "now", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( "quarter", new StandardSQLFunction( "quarter", StandardBasicTypes.INTEGER ) ); + registerFunction( "second", new StandardSQLFunction( "second", StandardBasicTypes.INTEGER ) ); + registerFunction( "time", new StandardSQLFunction( "time", StandardBasicTypes.TIME ) ); + registerFunction( "timestamp", new StandardSQLFunction( "timestamp", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( "week", new StandardSQLFunction( "week", StandardBasicTypes.INTEGER ) ); + registerFunction( "year", new StandardSQLFunction( "year", StandardBasicTypes.INTEGER ) ); - registerFunction("atan2", new StandardSQLFunction("atan2",StandardBasicTypes.DOUBLE) ); - registerFunction( "mod", new StandardSQLFunction("mod",StandardBasicTypes.INTEGER) ); - registerFunction( "nvl", new StandardSQLFunction("nvl") ); - registerFunction( "power", new StandardSQLFunction("power", StandardBasicTypes.DOUBLE) ); + registerFunction( "atan2", new StandardSQLFunction( "atan2", StandardBasicTypes.DOUBLE ) ); + registerFunction( "mod", new StandardSQLFunction( "mod", StandardBasicTypes.INTEGER ) ); + registerFunction( "nvl", new StandardSQLFunction( "nvl" ) ); + registerFunction( "power", new StandardSQLFunction( "power", StandardBasicTypes.DOUBLE ) ); /** * For a list of column types to register, see section A-1 @@ -184,169 +191,189 @@ public class RDMSOS2200Dialect extends Dialect { * Note that $l (dollar-L) will use the length value if provided. * Also new for Hibernate3 is the $p percision and $s (scale) parameters */ - registerColumnType(Types.BIT, "SMALLINT"); - registerColumnType(Types.TINYINT, "SMALLINT"); - registerColumnType(Types.BIGINT, "NUMERIC(21,0)"); - registerColumnType(Types.SMALLINT, "SMALLINT"); - registerColumnType(Types.CHAR, "CHARACTER(1)"); - registerColumnType(Types.DOUBLE, "DOUBLE PRECISION"); - registerColumnType(Types.FLOAT, "FLOAT"); - registerColumnType(Types.REAL, "REAL"); - registerColumnType(Types.INTEGER, "INTEGER"); - registerColumnType(Types.NUMERIC, "NUMERIC(21,$l)"); - registerColumnType(Types.DECIMAL, "NUMERIC(21,$l)"); - registerColumnType(Types.DATE, "DATE"); - registerColumnType(Types.TIME, "TIME"); - registerColumnType(Types.TIMESTAMP, "TIMESTAMP"); - registerColumnType(Types.VARCHAR, "CHARACTER($l)"); - registerColumnType(Types.BLOB, "BLOB($l)" ); - /* + registerColumnType( Types.BIT, "SMALLINT" ); + registerColumnType( Types.TINYINT, "SMALLINT" ); + registerColumnType( Types.BIGINT, "NUMERIC(21,0)" ); + registerColumnType( Types.SMALLINT, "SMALLINT" ); + registerColumnType( Types.CHAR, "CHARACTER(1)" ); + registerColumnType( Types.DOUBLE, "DOUBLE PRECISION" ); + registerColumnType( Types.FLOAT, "FLOAT" ); + registerColumnType( Types.REAL, "REAL" ); + registerColumnType( Types.INTEGER, "INTEGER" ); + registerColumnType( Types.NUMERIC, "NUMERIC(21,$l)" ); + registerColumnType( Types.DECIMAL, "NUMERIC(21,$l)" ); + registerColumnType( Types.DATE, "DATE" ); + registerColumnType( Types.TIME, "TIME" ); + registerColumnType( Types.TIMESTAMP, "TIMESTAMP" ); + registerColumnType( Types.VARCHAR, "CHARACTER($l)" ); + registerColumnType( Types.BLOB, "BLOB($l)" ); + /* * The following types are not supported in RDMS/JDBC and therefore commented out. * However, in some cases, mapping them to CHARACTER columns works * for many applications, but does not work for all cases. */ - // registerColumnType(Types.VARBINARY, "CHARACTER($l)"); - // registerColumnType(Types.BLOB, "CHARACTER($l)" ); // For use prior to CP 11.0 - // registerColumnType(Types.CLOB, "CHARACTER($l)" ); + // registerColumnType(Types.VARBINARY, "CHARACTER($l)"); + // registerColumnType(Types.BLOB, "CHARACTER($l)" ); // For use prior to CP 11.0 + // registerColumnType(Types.CLOB, "CHARACTER($l)" ); } // Dialect method overrides ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - /** - * RDMS does not support qualifing index names with the schema name. - */ + /** + * RDMS does not support qualifing index names with the schema name. + *

    + * {@inheritDoc} + */ + @Override public boolean qualifyIndexName() { return false; } /** * The RDMS DB supports the 'FOR UPDATE OF' clause. However, the RDMS-JDBC - * driver does not support this feature, so a false is return. - * The base dialect also returns a false, but we will leave this over-ride - * in to make sure it stays false. + * driver does not support this feature, so a false is return. + * The base dialect also returns a false, but we will leave this over-ride + * in to make sure it stays false. + *

    + * {@inheritDoc} */ + @Override public boolean forUpdateOfColumns() { return false; } /** * Since the RDMS-JDBC driver does not support for updates, this string is - * set to an empty string. Whenever, the driver does support this feature, - * the returned string should be " FOR UPDATE OF". Note that RDMS does not - * support the string 'FOR UPDATE' string. + * set to an empty string. Whenever, the driver does support this feature, + * the returned string should be " FOR UPDATE OF". Note that RDMS does not + * support the string 'FOR UPDATE' string. + *

    + * {@inheritDoc} */ + @Override public String getForUpdateString() { - return ""; // Original Dialect.java returns " for update"; + // Original Dialect.java returns " for update"; + return ""; } // Verify the state of this new method in Hibernate 3.0 Dialect.java - /** - * RDMS does not support Cascade Deletes. - * Need to review this in the future when support is provided. - */ - public boolean supportsCascadeDelete() { - return false; // Origial Dialect.java returns true; - } /** - * Currently, RDMS-JDBC does not support ForUpdate. - * Need to review this in the future when support is provided. + * RDMS does not support Cascade Deletes. + * Need to review this in the future when support is provided. + *

    + * {@inheritDoc} */ - public boolean supportsOuterJoinForUpdate() { + @Override + public boolean supportsCascadeDelete() { return false; } + /** + * Currently, RDMS-JDBC does not support ForUpdate. + * Need to review this in the future when support is provided. + *

    + * {@inheritDoc} + */ + @Override + public boolean supportsOuterJoinForUpdate() { + return false; + } + + @Override public String getAddColumnString() { return "add"; } + @Override public String getNullColumnString() { // The keyword used to specify a nullable column. return " null"; } - // *** Sequence methods - start. The RDMS dialect needs these - - // methods to make it possible to use the Native Id generator - + @Override public boolean supportsSequences() { return true; } + @Override public String getSequenceNextValString(String sequenceName) { - // The where clause was added to eliminate this statement from Brute Force Searches. - return "select permuted_id('NEXT',31) from rdms.rdms_dummy where key_col = 1 "; + // The where clause was added to eliminate this statement from Brute Force Searches. + return "select permuted_id('NEXT',31) from rdms.rdms_dummy where key_col = 1 "; } + @Override public String getCreateSequenceString(String sequenceName) { - // We must return a valid RDMS/RSA command from this method to - // prevent RDMS/RSA from issuing *ERROR 400 - return ""; + // We must return a valid RDMS/RSA command from this method to + // prevent RDMS/RSA from issuing *ERROR 400 + return ""; } + @Override public String getDropSequenceString(String sequenceName) { - // We must return a valid RDMS/RSA command from this method to - // prevent RDMS/RSA from issuing *ERROR 400 - return ""; + // We must return a valid RDMS/RSA command from this method to + // prevent RDMS/RSA from issuing *ERROR 400 + return ""; } - // *** Sequence methods - end - - public String getCascadeConstraintsString() { - // Used with DROP TABLE to delete all records in the table. - return " including contents"; - } + @Override + public String getCascadeConstraintsString() { + // Used with DROP TABLE to delete all records in the table. + return " including contents"; + } + @Override public CaseFragment createCaseFragment() { return new DecodeCaseFragment(); } + @Override public boolean supportsLimit() { return true; } + @Override public boolean supportsLimitOffset() { return false; } - public String getLimitString(String sql, int offset, int limit) { + @Override + public String getLimitString(String sql, int offset, int limit) { if ( offset > 0 ) { throw new UnsupportedOperationException( "query result offset is not supported" ); } - return new StringBuilder( sql.length() + 40 ) - .append( sql ) - .append( " fetch first " ) - .append( limit ) - .append( " rows only " ) - .toString(); + return sql + " fetch first " + limit + " rows only "; } + @Override public boolean supportsVariableLimit() { return false; } + @Override public boolean supportsUnionAll() { // RDMS supports the UNION ALL clause. - return true; + return true; } + @Override public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) { // RDMS has no known variation of a "SELECT ... FOR UPDATE" syntax... - if ( lockMode==LockMode.PESSIMISTIC_FORCE_INCREMENT) { - return new PessimisticForceIncrementLockingStrategy( lockable, lockMode); + if ( lockMode == LockMode.PESSIMISTIC_FORCE_INCREMENT ) { + return new PessimisticForceIncrementLockingStrategy( lockable, lockMode ); } - else if ( lockMode==LockMode.PESSIMISTIC_WRITE) { - return new PessimisticWriteUpdateLockingStrategy( lockable, lockMode); + else if ( lockMode == LockMode.PESSIMISTIC_WRITE ) { + return new PessimisticWriteUpdateLockingStrategy( lockable, lockMode ); } - else if ( lockMode==LockMode.PESSIMISTIC_READ) { - return new PessimisticReadUpdateLockingStrategy( lockable, lockMode); + else if ( lockMode == LockMode.PESSIMISTIC_READ ) { + return new PessimisticReadUpdateLockingStrategy( lockable, lockMode ); } - else if ( lockMode==LockMode.OPTIMISTIC) { - return new OptimisticLockingStrategy( lockable, lockMode); + else if ( lockMode == LockMode.OPTIMISTIC ) { + return new OptimisticLockingStrategy( lockable, lockMode ); } - else if ( lockMode==LockMode.OPTIMISTIC_FORCE_INCREMENT) { - return new OptimisticForceIncrementLockingStrategy( lockable, lockMode); + else if ( lockMode == LockMode.OPTIMISTIC_FORCE_INCREMENT ) { + return new OptimisticForceIncrementLockingStrategy( lockable, lockMode ); } else if ( lockMode.greaterThan( LockMode.READ ) ) { return new UpdateLockingStrategy( lockable, lockMode ); diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/ResultColumnReferenceStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/ResultColumnReferenceStrategy.java index 4e599e9337..fa007e435b 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/ResultColumnReferenceStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/ResultColumnReferenceStrategy.java @@ -21,11 +21,7 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.dialect; -import java.io.ObjectStreamException; -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; +package org.hibernate.dialect; /** * Defines how we need to reference columns in the group-by, having, and order-by @@ -33,18 +29,14 @@ import java.util.Map; * * @author Steve Ebersole */ -public class ResultColumnReferenceStrategy implements Serializable { - - private static final Map INSTANCES = new HashMap(); - +public enum ResultColumnReferenceStrategy { /** * This strategy says to reference the result columns by the qualified column name * found in the result source. This strategy is not strictly allowed by ANSI SQL * but is Hibernate's legacy behavior and is also the fastest of the strategies; thus * it should be used if supported by the underlying database. */ - public static final ResultColumnReferenceStrategy SOURCE = new ResultColumnReferenceStrategy( "source"); - + SOURCE, /** * For databases which do not support {@link #SOURCE}, ANSI SQL defines two allowable * approaches. One is to reference the result column by the alias it is given in the @@ -52,8 +44,7 @@ public class ResultColumnReferenceStrategy implements Serializable { *

    * The other QNSI SQL compliant approach is {@link #ORDINAL}. */ - public static final ResultColumnReferenceStrategy ALIAS = new ResultColumnReferenceStrategy( "alias" ); - + ALIAS, /** * For databases which do not support {@link #SOURCE}, ANSI SQL defines two allowable * approaches. One is to reference the result column by the ordinal position at which @@ -61,29 +52,25 @@ public class ResultColumnReferenceStrategy implements Serializable { *

    * The other QNSI SQL compliant approach is {@link #ALIAS}. */ - public static final ResultColumnReferenceStrategy ORDINAL = new ResultColumnReferenceStrategy( "ordinal" ); + ORDINAL; - static { - ResultColumnReferenceStrategy.INSTANCES.put( ResultColumnReferenceStrategy.SOURCE.name, ResultColumnReferenceStrategy.SOURCE ); - ResultColumnReferenceStrategy.INSTANCES.put( ResultColumnReferenceStrategy.ALIAS.name, ResultColumnReferenceStrategy.ALIAS ); - ResultColumnReferenceStrategy.INSTANCES.put( ResultColumnReferenceStrategy.ORDINAL.name, ResultColumnReferenceStrategy.ORDINAL ); - } - - private final String name; - - public ResultColumnReferenceStrategy(String name) { - this.name = name; - } - - public String toString() { - return name; - } - - private Object readResolve() throws ObjectStreamException { - return parse( name ); - } - - public static ResultColumnReferenceStrategy parse(String name) { - return ( ResultColumnReferenceStrategy ) ResultColumnReferenceStrategy.INSTANCES.get( name ); + /** + * Resolves the strategy by name, in a case insensitive manner. If the name cannot be resolved, {@link #SOURCE} + * is returned as the default. + * + * @param name The strategy name to resolve + * + * @return The resolved strategy + */ + public static ResultColumnReferenceStrategy resolveByName(String name) { + if ( ALIAS.name().equalsIgnoreCase( name ) ) { + return ALIAS; + } + else if ( ORDINAL.name().equalsIgnoreCase( name ) ) { + return ORDINAL; + } + else { + return SOURCE; + } } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/SAPDBDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/SAPDBDialect.java index 5cf6eda7db..2c6448498b 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/SAPDBDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/SAPDBDialect.java @@ -37,10 +37,13 @@ import org.hibernate.type.StandardBasicTypes; /** * An SQL dialect compatible with SAP DB. + * * @author Brad Clow */ public class SAPDBDialect extends Dialect { - + /** + * Constructs a SAPDBDialect + */ public SAPDBDialect() { super(); registerColumnType( Types.BIT, "boolean" ); @@ -60,160 +63,175 @@ public class SAPDBDialect extends Dialect { registerColumnType( Types.CLOB, "long varchar" ); registerColumnType( Types.BLOB, "long byte" ); - registerFunction( "abs", new StandardSQLFunction("abs") ); - registerFunction( "sign", new StandardSQLFunction("sign", StandardBasicTypes.INTEGER) ); + registerFunction( "abs", new StandardSQLFunction( "abs" ) ); + registerFunction( "sign", new StandardSQLFunction( "sign", StandardBasicTypes.INTEGER ) ); - registerFunction( "exp", new StandardSQLFunction("exp", StandardBasicTypes.DOUBLE) ); - registerFunction( "ln", new StandardSQLFunction("ln", StandardBasicTypes.DOUBLE) ); - registerFunction( "log", new StandardSQLFunction("ln", StandardBasicTypes.DOUBLE) ); - registerFunction( "pi", new NoArgSQLFunction("pi", StandardBasicTypes.DOUBLE) ); - registerFunction( "power", new StandardSQLFunction("power") ); - registerFunction( "acos", new StandardSQLFunction("acos", StandardBasicTypes.DOUBLE) ); - registerFunction( "asin", new StandardSQLFunction("asin", StandardBasicTypes.DOUBLE) ); - registerFunction( "atan", new StandardSQLFunction("atan", StandardBasicTypes.DOUBLE) ); - registerFunction( "cos", new StandardSQLFunction("cos", StandardBasicTypes.DOUBLE) ); - registerFunction( "cosh", new StandardSQLFunction("cosh", StandardBasicTypes.DOUBLE) ); - registerFunction( "cot", new StandardSQLFunction("cos", StandardBasicTypes.DOUBLE) ); - registerFunction( "sin", new StandardSQLFunction("sin", StandardBasicTypes.DOUBLE) ); - registerFunction( "sinh", new StandardSQLFunction("sinh", StandardBasicTypes.DOUBLE) ); - registerFunction( "tan", new StandardSQLFunction("tan", StandardBasicTypes.DOUBLE) ); - registerFunction( "tanh", new StandardSQLFunction("tanh", StandardBasicTypes.DOUBLE) ); - registerFunction( "radians", new StandardSQLFunction("radians", StandardBasicTypes.DOUBLE) ); - registerFunction( "degrees", new StandardSQLFunction("degrees", StandardBasicTypes.DOUBLE) ); - registerFunction( "atan2", new StandardSQLFunction("atan2", StandardBasicTypes.DOUBLE) ); + registerFunction( "exp", new StandardSQLFunction( "exp", StandardBasicTypes.DOUBLE ) ); + registerFunction( "ln", new StandardSQLFunction( "ln", StandardBasicTypes.DOUBLE ) ); + registerFunction( "log", new StandardSQLFunction( "ln", StandardBasicTypes.DOUBLE ) ); + registerFunction( "pi", new NoArgSQLFunction( "pi", StandardBasicTypes.DOUBLE ) ); + registerFunction( "power", new StandardSQLFunction( "power" ) ); + registerFunction( "acos", new StandardSQLFunction( "acos", StandardBasicTypes.DOUBLE ) ); + registerFunction( "asin", new StandardSQLFunction( "asin", StandardBasicTypes.DOUBLE ) ); + registerFunction( "atan", new StandardSQLFunction( "atan", StandardBasicTypes.DOUBLE ) ); + registerFunction( "cos", new StandardSQLFunction( "cos", StandardBasicTypes.DOUBLE ) ); + registerFunction( "cosh", new StandardSQLFunction( "cosh", StandardBasicTypes.DOUBLE ) ); + registerFunction( "cot", new StandardSQLFunction( "cos", StandardBasicTypes.DOUBLE ) ); + registerFunction( "sin", new StandardSQLFunction( "sin", StandardBasicTypes.DOUBLE ) ); + registerFunction( "sinh", new StandardSQLFunction( "sinh", StandardBasicTypes.DOUBLE ) ); + registerFunction( "tan", new StandardSQLFunction( "tan", StandardBasicTypes.DOUBLE ) ); + registerFunction( "tanh", new StandardSQLFunction( "tanh", StandardBasicTypes.DOUBLE ) ); + registerFunction( "radians", new StandardSQLFunction( "radians", StandardBasicTypes.DOUBLE ) ); + registerFunction( "degrees", new StandardSQLFunction( "degrees", StandardBasicTypes.DOUBLE ) ); + registerFunction( "atan2", new StandardSQLFunction( "atan2", StandardBasicTypes.DOUBLE ) ); - registerFunction( "round", new StandardSQLFunction("round") ); - registerFunction( "trunc", new StandardSQLFunction("trunc") ); - registerFunction( "ceil", new StandardSQLFunction("ceil") ); - registerFunction( "floor", new StandardSQLFunction("floor") ); - registerFunction( "greatest", new StandardSQLFunction("greatest") ); - registerFunction( "least", new StandardSQLFunction("least") ); + registerFunction( "round", new StandardSQLFunction( "round" ) ); + registerFunction( "trunc", new StandardSQLFunction( "trunc" ) ); + registerFunction( "ceil", new StandardSQLFunction( "ceil" ) ); + registerFunction( "floor", new StandardSQLFunction( "floor" ) ); + registerFunction( "greatest", new StandardSQLFunction( "greatest" ) ); + registerFunction( "least", new StandardSQLFunction( "least" ) ); - registerFunction("time", new StandardSQLFunction("time", StandardBasicTypes.TIME) ); - registerFunction("timestamp", new StandardSQLFunction("timestamp", StandardBasicTypes.TIMESTAMP) ); - registerFunction("date", new StandardSQLFunction("date", StandardBasicTypes.DATE) ); - registerFunction("microsecond", new StandardSQLFunction("microsecond", StandardBasicTypes.INTEGER) ); + registerFunction( "time", new StandardSQLFunction( "time", StandardBasicTypes.TIME ) ); + registerFunction( "timestamp", new StandardSQLFunction( "timestamp", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( "date", new StandardSQLFunction( "date", StandardBasicTypes.DATE ) ); + registerFunction( "microsecond", new StandardSQLFunction( "microsecond", StandardBasicTypes.INTEGER ) ); - registerFunction( "second", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "second(?1)") ); - registerFunction( "minute", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "minute(?1)") ); - registerFunction( "hour", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "hour(?1)") ); - registerFunction( "day", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "day(?1)") ); - registerFunction( "month", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "month(?1)") ); - registerFunction( "year", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "year(?1)") ); + registerFunction( "second", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "second(?1)" ) ); + registerFunction( "minute", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "minute(?1)" ) ); + registerFunction( "hour", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "hour(?1)" ) ); + registerFunction( "day", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "day(?1)" ) ); + registerFunction( "month", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "month(?1)" ) ); + registerFunction( "year", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "year(?1)" ) ); - registerFunction( "extract", new SQLFunctionTemplate(StandardBasicTypes.INTEGER, "?1(?3)") ); + registerFunction( "extract", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "?1(?3)" ) ); - registerFunction("dayname", new StandardSQLFunction("dayname", StandardBasicTypes.STRING) ); - registerFunction("monthname", new StandardSQLFunction("monthname", StandardBasicTypes.STRING) ); - registerFunction("dayofmonth", new StandardSQLFunction("dayofmonth", StandardBasicTypes.INTEGER) ); - registerFunction("dayofweek", new StandardSQLFunction("dayofweek", StandardBasicTypes.INTEGER) ); - registerFunction("dayofyear", new StandardSQLFunction("dayofyear", StandardBasicTypes.INTEGER) ); - registerFunction("weekofyear", new StandardSQLFunction("weekofyear", StandardBasicTypes.INTEGER) ); + registerFunction( "dayname", new StandardSQLFunction( "dayname", StandardBasicTypes.STRING ) ); + registerFunction( "monthname", new StandardSQLFunction( "monthname", StandardBasicTypes.STRING ) ); + registerFunction( "dayofmonth", new StandardSQLFunction( "dayofmonth", StandardBasicTypes.INTEGER ) ); + registerFunction( "dayofweek", new StandardSQLFunction( "dayofweek", StandardBasicTypes.INTEGER ) ); + registerFunction( "dayofyear", new StandardSQLFunction( "dayofyear", StandardBasicTypes.INTEGER ) ); + registerFunction( "weekofyear", new StandardSQLFunction( "weekofyear", StandardBasicTypes.INTEGER ) ); - registerFunction( "replace", new StandardSQLFunction("replace", StandardBasicTypes.STRING) ); - registerFunction( "translate", new StandardSQLFunction("translate", StandardBasicTypes.STRING) ); - registerFunction( "lpad", new StandardSQLFunction("lpad", StandardBasicTypes.STRING) ); - registerFunction( "rpad", new StandardSQLFunction("rpad", StandardBasicTypes.STRING) ); - registerFunction( "substr", new StandardSQLFunction("substr", StandardBasicTypes.STRING) ); - registerFunction( "initcap", new StandardSQLFunction("initcap", StandardBasicTypes.STRING) ); - registerFunction( "lower", new StandardSQLFunction("lower", StandardBasicTypes.STRING) ); - registerFunction( "ltrim", new StandardSQLFunction("ltrim", StandardBasicTypes.STRING) ); - registerFunction( "rtrim", new StandardSQLFunction("rtrim", StandardBasicTypes.STRING) ); - registerFunction( "lfill", new StandardSQLFunction("ltrim", StandardBasicTypes.STRING) ); - registerFunction( "rfill", new StandardSQLFunction("rtrim", StandardBasicTypes.STRING) ); - registerFunction( "soundex", new StandardSQLFunction("soundex", StandardBasicTypes.STRING) ); - registerFunction( "upper", new StandardSQLFunction("upper", StandardBasicTypes.STRING) ); - registerFunction( "ascii", new StandardSQLFunction("ascii", StandardBasicTypes.STRING) ); - registerFunction( "index", new StandardSQLFunction("index", StandardBasicTypes.INTEGER) ); + registerFunction( "replace", new StandardSQLFunction( "replace", StandardBasicTypes.STRING ) ); + registerFunction( "translate", new StandardSQLFunction( "translate", StandardBasicTypes.STRING ) ); + registerFunction( "lpad", new StandardSQLFunction( "lpad", StandardBasicTypes.STRING ) ); + registerFunction( "rpad", new StandardSQLFunction( "rpad", StandardBasicTypes.STRING ) ); + registerFunction( "substr", new StandardSQLFunction( "substr", StandardBasicTypes.STRING ) ); + registerFunction( "initcap", new StandardSQLFunction( "initcap", StandardBasicTypes.STRING ) ); + registerFunction( "lower", new StandardSQLFunction( "lower", StandardBasicTypes.STRING ) ); + registerFunction( "ltrim", new StandardSQLFunction( "ltrim", StandardBasicTypes.STRING ) ); + registerFunction( "rtrim", new StandardSQLFunction( "rtrim", StandardBasicTypes.STRING ) ); + registerFunction( "lfill", new StandardSQLFunction( "ltrim", StandardBasicTypes.STRING ) ); + registerFunction( "rfill", new StandardSQLFunction( "rtrim", StandardBasicTypes.STRING ) ); + registerFunction( "soundex", new StandardSQLFunction( "soundex", StandardBasicTypes.STRING ) ); + registerFunction( "upper", new StandardSQLFunction( "upper", StandardBasicTypes.STRING ) ); + registerFunction( "ascii", new StandardSQLFunction( "ascii", StandardBasicTypes.STRING ) ); + registerFunction( "index", new StandardSQLFunction( "index", StandardBasicTypes.INTEGER ) ); registerFunction( "value", new StandardSQLFunction( "value" ) ); registerFunction( "concat", new VarArgsSQLFunction( StandardBasicTypes.STRING, "(", "||", ")" ) ); registerFunction( "substring", new StandardSQLFunction( "substr", StandardBasicTypes.STRING ) ); - registerFunction( "locate", new StandardSQLFunction("index", StandardBasicTypes.INTEGER) ); + registerFunction( "locate", new StandardSQLFunction( "index", StandardBasicTypes.INTEGER ) ); registerFunction( "coalesce", new StandardSQLFunction( "value" ) ); - getDefaultProperties().setProperty(Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE); + getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE ); } + @Override public boolean dropConstraints() { return false; } + @Override public String getAddColumnString() { return "add"; } + @Override public String getAddForeignKeyConstraintString( String constraintName, String[] foreignKey, String referencedTable, - String[] primaryKey, boolean referencesPrimaryKey - ) { - StringBuilder res = new StringBuilder(30) - .append(" foreign key ") - .append(constraintName) - .append(" (") - .append( StringHelper.join( ", ", foreignKey ) ) - .append(") references ") - .append(referencedTable); + String[] primaryKey, + boolean referencesPrimaryKey) { + final StringBuilder res = new StringBuilder( 30 ) + .append( " foreign key " ) + .append( constraintName ) + .append( " (" ) + .append( StringHelper.join( ", ", foreignKey ) ) + .append( ") references " ) + .append( referencedTable ); - if(!referencesPrimaryKey) { - res.append(" (") - .append( StringHelper.join(", ", primaryKey) ) - .append(')'); + if ( !referencesPrimaryKey ) { + res.append( " (" ) + .append( StringHelper.join( ", ", primaryKey ) ) + .append( ')' ); } return res.toString(); } + @Override public String getAddPrimaryKeyConstraintString(String constraintName) { return " primary key "; } + @Override public String getNullColumnString() { return " null"; } + @Override public String getSequenceNextValString(String sequenceName) { return "select " + getSelectSequenceNextValString( sequenceName ) + " from dual"; } + @Override public String getSelectSequenceNextValString(String sequenceName) { return sequenceName + ".nextval"; } + @Override public String getCreateSequenceString(String sequenceName) { return "create sequence " + sequenceName; } + @Override public String getDropSequenceString(String sequenceName) { return "drop sequence " + sequenceName; } + @Override public String getQuerySequencesString() { return "select sequence_name from domain.sequences"; } + @Override public boolean supportsSequences() { return true; } + @Override public CaseFragment createCaseFragment() { return new DecodeCaseFragment(); } + @Override public boolean supportsTemporaryTables() { return true; } + @Override public String getCreateTemporaryTablePostfix() { return "ignore rollback"; } + @Override public String generateTemporaryTableName(String baseTableName) { - return "temp." + super.generateTemporaryTableName(baseTableName); + return "temp." + super.generateTemporaryTableName( baseTableName ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/SQLServer2005Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/SQLServer2005Dialect.java index 342fbf8a77..1ce703ce5f 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/SQLServer2005Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/SQLServer2005Dialect.java @@ -45,9 +45,13 @@ import org.hibernate.type.StandardBasicTypes; * @author Yoryos Valotasios * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ +@SuppressWarnings("deprecation") public class SQLServer2005Dialect extends SQLServerDialect { private static final int MAX_LENGTH = 8000; + /** + * Constructs a SQLServer2005Dialect + */ public SQLServer2005Dialect() { // HHH-3965 fix // As per http://www.sql-server-helper.com/faq/sql-server-2005-varchar-max-p01.aspx @@ -74,23 +78,25 @@ public class SQLServer2005Dialect extends SQLServerDialect { return new SQLServer2005LimitHandler( sql, selection ); } - @Override // since SQLServer2005 the nowait hint is supported + @Override public String appendLockHint(LockOptions lockOptions, String tableName) { + // NOTE : since SQLServer2005 the nowait hint is supported if ( lockOptions.getLockMode() == LockMode.UPGRADE_NOWAIT ) { return tableName + " with (updlock, rowlock, nowait)"; } - LockMode mode = lockOptions.getLockMode(); - boolean isNoWait = lockOptions.getTimeOut() == LockOptions.NO_WAIT; - String noWaitStr = isNoWait? ", nowait" :""; + + final LockMode mode = lockOptions.getLockMode(); + final boolean isNoWait = lockOptions.getTimeOut() == LockOptions.NO_WAIT; + final String noWaitStr = isNoWait ? ", nowait" : ""; switch ( mode ) { case UPGRADE_NOWAIT: - return tableName + " with (updlock, rowlock, nowait)"; + return tableName + " with (updlock, rowlock, nowait)"; case UPGRADE: case PESSIMISTIC_WRITE: case WRITE: - return tableName + " with (updlock, rowlock"+noWaitStr+" )"; + return tableName + " with (updlock, rowlock" + noWaitStr + " )"; case PESSIMISTIC_READ: - return tableName + " with (holdlock, rowlock"+noWaitStr+" )"; + return tableName + " with (holdlock, rowlock" + noWaitStr + " )"; default: return tableName; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/SQLServer2008Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/SQLServer2008Dialect.java index 812d9eebc8..a76c782606 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/SQLServer2008Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/SQLServer2008Dialect.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import java.sql.Types; import org.hibernate.dialect.function.NoArgSQLFunction; @@ -33,6 +34,9 @@ import org.hibernate.type.StandardBasicTypes; * @author Gavin King */ public class SQLServer2008Dialect extends SQLServer2005Dialect { + /** + * Constructs a SQLServer2008Dialect + */ public SQLServer2008Dialect() { registerColumnType( Types.DATE, "date" ); registerColumnType( Types.TIME, "time" ); diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/SQLServerDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/SQLServerDialect.java index 0ae137cb5f..c8dba6137c 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/SQLServerDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/SQLServerDialect.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import java.sql.Types; import org.hibernate.LockMode; @@ -38,10 +39,13 @@ import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; * * @author Gavin King */ +@SuppressWarnings("deprecation") public class SQLServerDialect extends AbstractTransactSQLDialect { - private static final int PARAM_LIST_SIZE_LIMIT = 2100; + /** + * Constructs a SQLServerDialect + */ public SQLServerDialect() { registerColumnType( Types.VARBINARY, "image" ); registerColumnType( Types.VARBINARY, 8000, "varbinary($l)" ); @@ -64,18 +68,18 @@ public class SQLServerDialect extends AbstractTransactSQLDialect { } @Override - public String getNoColumnsInsertString() { + public String getNoColumnsInsertString() { return "default values"; } static int getAfterSelectInsertPoint(String sql) { - int selectIndex = sql.toLowerCase().indexOf( "select" ); + final int selectIndex = sql.toLowerCase().indexOf( "select" ); final int selectDistinctIndex = sql.toLowerCase().indexOf( "select distinct" ); - return selectIndex + ( selectDistinctIndex == selectIndex ? 15 : 6 ); + return selectIndex + (selectDistinctIndex == selectIndex ? 15 : 6); } @Override - public String getLimitString(String querySelect, int offset, int limit) { + public String getLimitString(String querySelect, int offset, int limit) { if ( offset > 0 ) { throw new UnsupportedOperationException( "query result offset is not supported" ); } @@ -87,45 +91,47 @@ public class SQLServerDialect extends AbstractTransactSQLDialect { /** * Use insert table(...) values(...) select SCOPE_IDENTITY() + *

    + * {@inheritDoc} */ @Override - public String appendIdentitySelectToInsert(String insertSQL) { + public String appendIdentitySelectToInsert(String insertSQL) { return insertSQL + " select scope_identity()"; } @Override - public boolean supportsLimit() { + public boolean supportsLimit() { return true; } @Override - public boolean useMaxForLimit() { + public boolean useMaxForLimit() { return true; } @Override - public boolean supportsLimitOffset() { + public boolean supportsLimitOffset() { return false; } @Override - public boolean supportsVariableLimit() { + public boolean supportsVariableLimit() { return false; } @Override - public char closeQuote() { + public char closeQuote() { return ']'; } @Override - public char openQuote() { + public char openQuote() { return '['; } @Override - public String appendLockHint(LockOptions lockOptions, String tableName) { - LockMode mode = lockOptions.getLockMode(); + public String appendLockHint(LockOptions lockOptions, String tableName) { + final LockMode mode = lockOptions.getLockMode(); switch ( mode ) { case UPGRADE: case UPGRADE_NOWAIT: @@ -134,34 +140,39 @@ public class SQLServerDialect extends AbstractTransactSQLDialect { return tableName + " with (updlock, rowlock)"; case PESSIMISTIC_READ: return tableName + " with (holdlock, rowlock)"; - case UPGRADE_SKIPLOCKED: - return tableName + " with (updlock, rowlock, readpast)"; + case UPGRADE_SKIPLOCKED: + return tableName + " with (updlock, rowlock, readpast)"; default: return tableName; } } - // The current_timestamp is more accurate, but only known to be supported - // in SQL Server 7.0 and later (i.e., Sybase not known to support it at all) + + /** + * The current_timestamp is more accurate, but only known to be supported in SQL Server 7.0 and later and + * Sybase not known to support it at all + *

    + * {@inheritDoc} + */ @Override - public String getCurrentTimestampSelectString() { + public String getCurrentTimestampSelectString() { return "select current_timestamp"; } // Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @Override - public boolean areStringComparisonsCaseInsensitive() { + public boolean areStringComparisonsCaseInsensitive() { return true; } @Override - public boolean supportsResultSetPositionQueryMethodsOnForwardOnlyCursor() { + public boolean supportsResultSetPositionQueryMethodsOnForwardOnlyCursor() { return false; } @Override - public boolean supportsCircularCascadeDeleteConstraints() { + public boolean supportsCircularCascadeDeleteConstraints() { // SQL Server (at least up through 2005) does not support defining // cascade delete constraints which can circle back to the mutating // table @@ -169,34 +180,30 @@ public class SQLServerDialect extends AbstractTransactSQLDialect { } @Override - public boolean supportsLobValueChangePropogation() { + public boolean supportsLobValueChangePropogation() { // note: at least my local SQL Server 2005 Express shows this not working... return false; } @Override - public boolean doesReadCommittedCauseWritersToBlockReaders() { - return false; // here assume SQLServer2005 using snapshot isolation, which does not have this problem + public boolean doesReadCommittedCauseWritersToBlockReaders() { + // here assume SQLServer2005 using snapshot isolation, which does not have this problem + return false; } @Override - public boolean doesRepeatableReadCauseReadersToBlockWriters() { - return false; // here assume SQLServer2005 using snapshot isolation, which does not have this problem + public boolean doesRepeatableReadCauseReadersToBlockWriters() { + // here assume SQLServer2005 using snapshot isolation, which does not have this problem + return false; } - /** - * {@inheritDoc} - * - * @see org.hibernate.dialect.Dialect#getSqlTypeDescriptorOverride(int) - */ - @Override - protected SqlTypeDescriptor getSqlTypeDescriptorOverride( int sqlCode ) { - return sqlCode == Types.TINYINT ? SmallIntTypeDescriptor.INSTANCE : super.getSqlTypeDescriptorOverride(sqlCode); - } + @Override + protected SqlTypeDescriptor getSqlTypeDescriptorOverride(int sqlCode) { + return sqlCode == Types.TINYINT ? + SmallIntTypeDescriptor.INSTANCE : + super.getSqlTypeDescriptorOverride( sqlCode ); + } - /* (non-Javadoc) - * @see org.hibernate.dialect.Dialect#getInExpressionCountLimit() - */ @Override public int getInExpressionCountLimit() { return PARAM_LIST_SIZE_LIMIT; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Sybase11Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Sybase11Dialect.java index bb94974c5a..c92c73e9e1 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Sybase11Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Sybase11Dialect.java @@ -22,22 +22,29 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import org.hibernate.sql.JoinFragment; import org.hibernate.sql.Sybase11JoinFragment; /** * A SQL dialect suitable for use with Sybase 11.9.2 (specifically: avoids ANSI JOIN syntax) + * * @author Colm O' Flaherty */ public class Sybase11Dialect extends SybaseDialect { + /** + * Constructs a Sybase11Dialect + */ public Sybase11Dialect() { super(); } + @Override public JoinFragment createOuterJoinFragment() { return new Sybase11JoinFragment(); } + @Override public String getCrossJoinSeparator() { return ", "; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/SybaseASE157Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/SybaseASE157Dialect.java index 1096672ecd..9e164b9e05 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/SybaseASE157Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/SybaseASE157Dialect.java @@ -27,16 +27,11 @@ import java.sql.SQLException; import java.util.Map; import org.hibernate.JDBCException; -import org.hibernate.LockMode; import org.hibernate.LockOptions; -import org.hibernate.QueryTimeoutException; import org.hibernate.dialect.function.SQLFunctionTemplate; import org.hibernate.exception.ConstraintViolationException; -import org.hibernate.exception.LockAcquisitionException; import org.hibernate.exception.LockTimeoutException; import org.hibernate.exception.spi.SQLExceptionConversionDelegate; -import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; -import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; import org.hibernate.internal.util.JdbcExceptionHelper; import org.hibernate.sql.ForUpdateFragment; import org.hibernate.type.StandardBasicTypes; @@ -49,6 +44,9 @@ import org.hibernate.type.StandardBasicTypes; */ public class SybaseASE157Dialect extends SybaseASE15Dialect { + /** + * Constructs a SybaseASE157Dialect + */ public SybaseASE157Dialect() { super(); @@ -60,40 +58,43 @@ public class SybaseASE157Dialect extends SybaseASE15Dialect { registerFunction( "charindex", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "charindex(?1, ?2, ?3)" ) ); } - //HHH-7298 I don't know if this would break something or cause some side affects - //but it is required to use 'select for update' @Override public String getTableTypeString() { + //HHH-7298 I don't know if this would break something or cause some side affects + //but it is required to use 'select for update' return " lock datarows"; } - // support Lob Locator @Override public boolean supportsExpectedLobUsagePattern() { return true; } + @Override public boolean supportsLobValueChangePropogation() { return false; } - // support 'select ... for update [of columns]' @Override public boolean forUpdateOfColumns() { return true; } + @Override public String getForUpdateString() { return " for update"; } + @Override public String getForUpdateString(String aliases) { return getForUpdateString() + " of " + aliases; } + @Override public String appendLockHint(LockOptions mode, String tableName) { return tableName; } + @Override public String applyLocksToSql(String sql, LockOptions aliasedLockOptions, Map keyColumnNames) { return sql + new ForUpdateFragment( this, aliasedLockOptions, keyColumnNames ).toFragmentString(); @@ -118,6 +119,4 @@ public class SybaseASE157Dialect extends SybaseASE15Dialect { } }; } - - } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/SybaseASE15Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/SybaseASE15Dialect.java index 01f8d25776..5dc35c0055 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/SybaseASE15Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/SybaseASE15Dialect.java @@ -41,6 +41,9 @@ import org.hibernate.type.descriptor.sql.TinyIntTypeDescriptor; * @author Gavin King */ public class SybaseASE15Dialect extends SybaseDialect { + /** + * Constructs a SybaseASE15Dialect + */ public SybaseASE15Dialect() { super(); @@ -50,8 +53,8 @@ public class SybaseASE15Dialect extends SybaseDialect { registerColumnType( Types.DATE, "date" ); registerColumnType( Types.DECIMAL, "numeric($p,$s)" ); registerColumnType( Types.TIME, "time" ); - registerColumnType( Types.REAL, "real" ); - registerColumnType( Types.BOOLEAN, "tinyint" ); + registerColumnType( Types.REAL, "real" ); + registerColumnType( Types.BOOLEAN, "tinyint" ); registerFunction( "second", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "datepart(second, ?1)" ) ); registerFunction( "minute", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "datepart(minute, ?1)" ) ); @@ -164,7 +167,7 @@ public class SybaseASE15Dialect extends SybaseDialect { registerFunction( "variance", new SQLFunctionTemplate( StandardBasicTypes.DOUBLE, "variance" ) ); registerFunction( "var_pop", new SQLFunctionTemplate( StandardBasicTypes.DOUBLE, "var_pop" ) ); registerFunction( "var_samp", new SQLFunctionTemplate( StandardBasicTypes.DOUBLE, "var_samp" ) ); - registerFunction( "sysdate", new NoArgSQLFunction("getdate", StandardBasicTypes.TIMESTAMP) ); + registerFunction( "sysdate", new NoArgSQLFunction("getdate", StandardBasicTypes.TIMESTAMP) ); registerSybaseKeywords(); } @@ -391,10 +394,12 @@ public class SybaseASE15Dialect extends SybaseDialect { // Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + @Override public boolean supportsCascadeDelete() { return false; } + @Override public int getMaxAliasLength() { return 30; } @@ -404,11 +409,15 @@ public class SybaseASE15Dialect extends SybaseDialect { *

    * If the DB is configured to be case-sensitive, then this return * value will be incorrect. + *

    + * {@inheritDoc} */ + @Override public boolean areStringComparisonsCaseInsensitive() { return true; } + @Override public String getCurrentTimestampSQLFunctionName() { return "getdate()"; } @@ -417,19 +426,23 @@ public class SybaseASE15Dialect extends SybaseDialect { * Actually Sybase does not support LOB locators at al. * * @return false. + *

    + * {@inheritDoc} */ + @Override public boolean supportsExpectedLobUsagePattern() { return false; } + @Override public String getCrossJoinSeparator() { return ", "; } - @Override - protected SqlTypeDescriptor getSqlTypeDescriptorOverride(int sqlCode) { - return sqlCode == Types.BOOLEAN ? TinyIntTypeDescriptor.INSTANCE : super.getSqlTypeDescriptorOverride( sqlCode ); - } + @Override + protected SqlTypeDescriptor getSqlTypeDescriptorOverride(int sqlCode) { + return sqlCode == Types.BOOLEAN ? TinyIntTypeDescriptor.INSTANCE : super.getSqlTypeDescriptorOverride( sqlCode ); + } @Override public boolean supportsLockTimeouts() { diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/SybaseAnywhereDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/SybaseAnywhereDialect.java index 688c917c06..26dc33de45 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/SybaseAnywhereDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/SybaseAnywhereDialect.java @@ -28,13 +28,15 @@ package org.hibernate.dialect; * SQL Dialect for Sybase Anywhere * extending Sybase (Enterprise) Dialect * (Tested on ASA 8.x) - * @author ? */ public class SybaseAnywhereDialect extends SybaseDialect { /** * Sybase Anywhere syntax would require a "DEFAULT" for each column specified, * but I suppose Hibernate use this syntax only with tables with just 1 column + *

    + * {@inheritDoc} */ + @Override public String getNoColumnsInsertString() { return "values (default)"; } @@ -44,13 +46,17 @@ public class SybaseAnywhereDialect extends SybaseDialect { *

    * NOTE : Also, the DROP statement syntax used by Hibernate to drop constraints is * not compatible with ASA. + *

    + * {@inheritDoc} */ + @Override public boolean dropConstraints() { return false; } + @Override public boolean supportsInsertSelectIdentity() { return false; } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/SybaseDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/SybaseDialect.java index 90f1c35d20..5f7a3ef65d 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/SybaseDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/SybaseDialect.java @@ -36,12 +36,8 @@ import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; * @author Brett Meyer */ public class SybaseDialect extends AbstractTransactSQLDialect { - private static final int PARAM_LIST_SIZE_LIMIT = 250000; - /* (non-Javadoc) - * @see org.hibernate.dialect.Dialect#getInExpressionCountLimit() - */ @Override public int getInExpressionCountLimit() { return PARAM_LIST_SIZE_LIMIT; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/TeradataDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/TeradataDialect.java index 942057aa64..5c01957402 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/TeradataDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/TeradataDialect.java @@ -37,7 +37,6 @@ import org.hibernate.type.StandardBasicTypes; * @author Jay Nance */ public class TeradataDialect extends Dialect { - private static final int PARAM_LIST_SIZE_LIMIT = 1024; /** @@ -63,7 +62,8 @@ public class TeradataDialect extends Dialect { registerColumnType( Types.DATE, "DATE" ); registerColumnType( Types.TIME, "TIME" ); registerColumnType( Types.TIMESTAMP, "TIMESTAMP" ); - registerColumnType( Types.BOOLEAN, "BYTEINT" ); // hibernate seems to ignore this type... + // hibernate seems to ignore this type... + registerColumnType( Types.BOOLEAN, "BYTEINT" ); registerColumnType( Types.BLOB, "BLOB" ); registerColumnType( Types.CLOB, "CLOB" ); @@ -113,87 +113,87 @@ public class TeradataDialect extends Dialect { } /** - * Does this dialect support the FOR UPDATE syntax? - * - * @return empty string ... Teradata does not support FOR UPDATE syntax + * Teradata does not support FOR UPDATE syntax + *

    + * {@inheritDoc} */ + @Override public String getForUpdateString() { return ""; } + @Override public boolean supportsIdentityColumns() { return false; } + @Override public boolean supportsSequences() { return false; } + @Override public String getAddColumnString() { return "Add Column"; } + @Override public boolean supportsTemporaryTables() { return true; } + @Override public String getCreateTemporaryTableString() { return "create global temporary table"; } + @Override public String getCreateTemporaryTablePostfix() { return " on commit preserve rows"; } + @Override public Boolean performTemporaryTableDDLInIsolation() { return Boolean.TRUE; } + @Override public boolean dropTemporaryTableAfterUse() { return false; } - /** - * Get the name of the database type associated with the given - * java.sql.Types typecode. - * - * @param code java.sql.Types typecode - * @param length the length or precision of the column - * @param precision the precision of the column - * @param scale the scale of the column - * - * @return the database type name - * - * @throws HibernateException - */ - public String getTypeName(int code, int length, int precision, int scale) throws HibernateException { - /* - * We might want a special case for 19,2. This is very common for money types - * and here it is converted to 18,1 - */ - float f = precision > 0 ? ( float ) scale / ( float ) precision : 0; - int p = ( precision > 18 ? 18 : precision ); - int s = ( precision > 18 ? ( int ) ( 18.0 * f ) : ( scale > 18 ? 18 : scale ) ); + @Override + public String getTypeName(int code, long length, int precision, int scale) throws HibernateException { + // We might want a special case for 19,2. This is very common for money types + // and here it is converted to 18,1 + final float f = precision > 0 ? (float) scale / (float) precision : 0; + final int p = ( precision > 18 ? 18 : precision ); + final int s = ( precision > 18 ? (int) ( 18.0 * f ) : ( scale > 18 ? 18 : scale ) ); return super.getTypeName( code, length, p, s ); } + @Override public boolean supportsCascadeDelete() { return false; } + @Override public boolean supportsCircularCascadeDeleteConstraints() { return false; } + @Override public boolean areStringComparisonsCaseInsensitive() { return true; } + @Override public boolean supportsEmptyInList() { return false; } + @Override public String getSelectClauseNullString(int sqlType) { String v = "null"; @@ -235,35 +235,39 @@ public class TeradataDialect extends Dialect { case Types.DATALINK: case Types.BOOLEAN: break; + default: + break; } return v; } + @Override public String getCreateMultisetTableString() { return "create multiset table "; } + @Override public boolean supportsLobValueChangePropogation() { return false; } + @Override public boolean doesReadCommittedCauseWritersToBlockReaders() { return true; } + @Override public boolean doesRepeatableReadCauseReadersToBlockWriters() { return true; } + @Override public boolean supportsBindAsCallableArgument() { return false; } - /* (non-Javadoc) - * @see org.hibernate.dialect.Dialect#getInExpressionCountLimit() - */ @Override public int getInExpressionCountLimit() { return PARAM_LIST_SIZE_LIMIT; } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/TimesTenDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/TimesTenDialect.java index f76e3099a1..bbd6545dab 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/TimesTenDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/TimesTenDialect.java @@ -44,21 +44,24 @@ import org.hibernate.type.StandardBasicTypes; /** * A SQL dialect for TimesTen 5.1. - * + *

    * Known limitations: * joined-subclass support because of no CASE support in TimesTen * No support for subqueries that includes aggregation - * - size() in HQL not supported - * - user queries that does subqueries with aggregation - * No CLOB/BLOB support + * - size() in HQL not supported + * - user queries that does subqueries with aggregation + * No CLOB/BLOB support * No cascade delete support. * No Calendar support * No support for updating primary keys. - * + * * @author Sherry Listgarten and Max Andersen */ +@SuppressWarnings("deprecation") public class TimesTenDialect extends Dialect { - + /** + * Constructs a TimesTenDialect + */ public TimesTenDialect() { super(); registerColumnType( Types.BIT, "TINYINT" ); @@ -77,101 +80,115 @@ public class TimesTenDialect extends Dialect { registerColumnType( Types.NUMERIC, "DECIMAL($p, $s)" ); // TimesTen has no BLOB/CLOB support, but these types may be suitable // for some applications. The length is limited to 4 million bytes. - registerColumnType( Types.BLOB, "VARBINARY(4000000)" ); - registerColumnType( Types.CLOB, "VARCHAR(4000000)" ); - - getDefaultProperties().setProperty(Environment.USE_STREAMS_FOR_BINARY, "true"); - getDefaultProperties().setProperty(Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE); - registerFunction( "lower", new StandardSQLFunction("lower") ); - registerFunction( "upper", new StandardSQLFunction("upper") ); - registerFunction( "rtrim", new StandardSQLFunction("rtrim") ); - registerFunction( "concat", new StandardSQLFunction("concat", StandardBasicTypes.STRING) ); - registerFunction( "mod", new StandardSQLFunction("mod") ); - registerFunction( "to_char", new StandardSQLFunction("to_char",StandardBasicTypes.STRING) ); - registerFunction( "to_date", new StandardSQLFunction("to_date",StandardBasicTypes.TIMESTAMP) ); - registerFunction( "sysdate", new NoArgSQLFunction("sysdate", StandardBasicTypes.TIMESTAMP, false) ); - registerFunction( "getdate", new NoArgSQLFunction("getdate", StandardBasicTypes.TIMESTAMP, false) ); - registerFunction( "nvl", new StandardSQLFunction("nvl") ); + registerColumnType( Types.BLOB, "VARBINARY(4000000)" ); + registerColumnType( Types.CLOB, "VARCHAR(4000000)" ); + + getDefaultProperties().setProperty( Environment.USE_STREAMS_FOR_BINARY, "true" ); + getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE ); + registerFunction( "lower", new StandardSQLFunction( "lower" ) ); + registerFunction( "upper", new StandardSQLFunction( "upper" ) ); + registerFunction( "rtrim", new StandardSQLFunction( "rtrim" ) ); + registerFunction( "concat", new StandardSQLFunction( "concat", StandardBasicTypes.STRING ) ); + registerFunction( "mod", new StandardSQLFunction( "mod" ) ); + registerFunction( "to_char", new StandardSQLFunction( "to_char", StandardBasicTypes.STRING ) ); + registerFunction( "to_date", new StandardSQLFunction( "to_date", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( "sysdate", new NoArgSQLFunction( "sysdate", StandardBasicTypes.TIMESTAMP, false ) ); + registerFunction( "getdate", new NoArgSQLFunction( "getdate", StandardBasicTypes.TIMESTAMP, false ) ); + registerFunction( "nvl", new StandardSQLFunction( "nvl" ) ); } - + + @Override public boolean dropConstraints() { - return true; - } - - public boolean qualifyIndexName() { - return false; - } - - public String getAddColumnString() { - return "add"; + return true; } + @Override + public boolean qualifyIndexName() { + return false; + } + + @Override + public String getAddColumnString() { + return "add"; + } + + @Override public boolean supportsSequences() { return true; } + @Override public String getSelectSequenceNextValString(String sequenceName) { return sequenceName + ".nextval"; } + @Override public String getSequenceNextValString(String sequenceName) { return "select first 1 " + sequenceName + ".nextval from sys.tables"; } + @Override public String getCreateSequenceString(String sequenceName) { return "create sequence " + sequenceName; } + @Override public String getDropSequenceString(String sequenceName) { return "drop sequence " + sequenceName; } + @Override public String getQuerySequencesString() { return "select NAME from sys.sequences"; } + @Override public JoinFragment createOuterJoinFragment() { return new OracleJoinFragment(); } + @Override public String getCrossJoinSeparator() { return ", "; } - // new methods in dialect3 - /*public boolean supportsForUpdateNowait() { - return false; - }*/ - + @Override public String getForUpdateString() { return ""; } - + + @Override public boolean supportsColumnCheck() { return false; } + @Override public boolean supportsTableCheck() { return false; } - + + @Override public boolean supportsLimitOffset() { return false; } + @Override public boolean supportsVariableLimit() { return false; } + @Override public boolean supportsLimit() { return true; } + @Override public boolean useMaxForLimit() { return true; } + @Override public String getLimitString(String querySelect, int offset, int limit) { if ( offset > 0 ) { throw new UnsupportedOperationException( "query result offset is not supported" ); @@ -182,51 +199,59 @@ public class TimesTenDialect extends Dialect { .toString(); } + @Override public boolean supportsCurrentTimestampSelection() { return true; } + @Override public String getCurrentTimestampSelectString() { return "select first 1 sysdate from sys.tables"; } + @Override public boolean isCurrentTimestampSelectStringCallable() { return false; } + @Override public boolean supportsTemporaryTables() { return true; } + @Override public String generateTemporaryTableName(String baseTableName) { - String name = super.generateTemporaryTableName(baseTableName); + final String name = super.generateTemporaryTableName( baseTableName ); return name.length() > 30 ? name.substring( 1, 30 ) : name; } + @Override public String getCreateTemporaryTableString() { return "create global temporary table"; } + @Override public String getCreateTemporaryTablePostfix() { return "on commit delete rows"; } + @Override public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) { // TimesTen has no known variation of a "SELECT ... FOR UPDATE" syntax... - if ( lockMode==LockMode.PESSIMISTIC_FORCE_INCREMENT) { - return new PessimisticForceIncrementLockingStrategy( lockable, lockMode); + if ( lockMode == LockMode.PESSIMISTIC_FORCE_INCREMENT ) { + return new PessimisticForceIncrementLockingStrategy( lockable, lockMode ); } - else if ( lockMode==LockMode.PESSIMISTIC_WRITE) { - return new PessimisticWriteUpdateLockingStrategy( lockable, lockMode); + else if ( lockMode == LockMode.PESSIMISTIC_WRITE ) { + return new PessimisticWriteUpdateLockingStrategy( lockable, lockMode ); } - else if ( lockMode==LockMode.PESSIMISTIC_READ) { - return new PessimisticReadUpdateLockingStrategy( lockable, lockMode); + else if ( lockMode == LockMode.PESSIMISTIC_READ ) { + return new PessimisticReadUpdateLockingStrategy( lockable, lockMode ); } - else if ( lockMode==LockMode.OPTIMISTIC) { - return new OptimisticLockingStrategy( lockable, lockMode); + else if ( lockMode == LockMode.OPTIMISTIC ) { + return new OptimisticLockingStrategy( lockable, lockMode ); } - else if ( lockMode==LockMode.OPTIMISTIC_FORCE_INCREMENT) { - return new OptimisticForceIncrementLockingStrategy( lockable, lockMode); + else if ( lockMode == LockMode.OPTIMISTIC_FORCE_INCREMENT ) { + return new OptimisticForceIncrementLockingStrategy( lockable, lockMode ); } else if ( lockMode.greaterThan( LockMode.READ ) ) { return new UpdateLockingStrategy( lockable, lockMode ); @@ -238,6 +263,7 @@ public class TimesTenDialect extends Dialect { // Overridden informational metadata ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + @Override public boolean supportsEmptyInList() { return false; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/TypeNames.java b/hibernate-core/src/main/java/org/hibernate/dialect/TypeNames.java index 8f1584f257..0bf0ab95bd 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/TypeNames.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/TypeNames.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import java.util.HashMap; import java.util.Map; import java.util.TreeMap; @@ -30,100 +31,124 @@ import org.hibernate.MappingException; import org.hibernate.internal.util.StringHelper; /** - * This class maps a type to names. Associations - * may be marked with a capacity. Calling the get() - * method with a type and actual size n will return - * the associated name with smallest capacity >= n, + * This class maps a type to names. Associations may be marked with a capacity. Calling the get() + * method with a type and actual size n will return the associated name with smallest capacity >= n, * if available and an unmarked default type otherwise. * Eg, setting *

    - *	names.put(type,        "TEXT" );
    - *	names.put(type,   255, "VARCHAR($l)" );
    - *	names.put(type, 65534, "LONGVARCHAR($l)" );
    + *	names.put( type,        "TEXT" );
    + *	names.put( type,   255, "VARCHAR($l)" );
    + *	names.put( type, 65534, "LONGVARCHAR($l)" );
      * 
    * will give you back the following: *
    - *  names.get(type)         // --> "TEXT" (default)
    - *  names.get(type,    100) // --> "VARCHAR(100)" (100 is in [0:255])
    - *  names.get(type,   1000) // --> "LONGVARCHAR(1000)" (1000 is in [256:65534])
    - *  names.get(type, 100000) // --> "TEXT" (default)
    + *  names.get( type )         // --> "TEXT" (default)
    + *  names.get( type,    100 ) // --> "VARCHAR(100)" (100 is in [0:255])
    + *  names.get( type,   1000 ) // --> "LONGVARCHAR(1000)" (1000 is in [256:65534])
    + *  names.get( type, 100000 ) // --> "TEXT" (default)
      * 
    * On the other hand, simply putting *
    - *	names.put(type, "VARCHAR($l)" );
    + *	names.put( type, "VARCHAR($l)" );
      * 
    * would result in *
    - *  names.get(type)        // --> "VARCHAR($l)" (will cause trouble)
    - *  names.get(type, 100)   // --> "VARCHAR(100)"
    - *  names.get(type, 10000) // --> "VARCHAR(10000)"
    + *  names.get( type )        // --> "VARCHAR($l)" (will cause trouble)
    + *  names.get( type, 100 )   // --> "VARCHAR(100)"
    + *  names.get( type, 10000 ) // --> "VARCHAR(10000)"
      * 
    * * @author Christoph Beck */ public class TypeNames { - - private Map> weighted = new HashMap>(); + /** + * Holds default type mappings for a typeCode. This is the non-sized mapping + */ private Map defaults = new HashMap(); /** - * get default type name for specified type - * @param typecode the type key - * @return the default type name associated with specified key + * Holds the weighted mappings for a typeCode. The nested map is a TreeMap to sort its contents + * based on the key (the weighting) to ensure proper iteration ordering during {@link #get(int, long, int, int)} */ - public String get(int typecode) throws MappingException { - String result = defaults.get( typecode ); - if (result==null) throw new MappingException("No Dialect mapping for JDBC type: " + typecode); + private Map> weighted = new HashMap>(); + + /** + * get default type name for specified type + * + * @param typeCode the type key + * + * @return the default type name associated with specified key + * + * @throws MappingException Indicates that no registrations were made for that typeCode + */ + public String get(int typeCode) throws MappingException { + final String result = defaults.get( typeCode ); + if ( result == null ) { + throw new MappingException( "No Dialect mapping for JDBC type: " + typeCode ); + } return result; } /** * get type name for specified type and size + * * @param typeCode the type key * @param size the SQL length * @param scale the SQL scale * @param precision the SQL precision - * @return the associated name with smallest capacity >= size, - * if available and the default type name otherwise + * + * @return the associated name with smallest capacity >= size, if available and the default type name otherwise + * + * @throws MappingException Indicates that no registrations were made for that typeCode */ public String get(int typeCode, long size, int precision, int scale) throws MappingException { - Map map = weighted.get( typeCode ); - if ( map!=null && map.size()>0 ) { + final Map map = weighted.get( typeCode ); + if ( map != null && map.size() > 0 ) { // iterate entries ordered by capacity to find first fit - for (Map.Entry entry: map.entrySet()) { + for ( Map.Entry entry: map.entrySet() ) { if ( size <= entry.getKey() ) { return replace( entry.getValue(), size, precision, scale ); } } } - return replace( get(typeCode), size, precision, scale ); + + // if we get here one of 2 things happened: + // 1) There was no weighted registration for that typeCode + // 2) There was no weighting whose max capacity was big enough to contain size + return replace( get( typeCode ), size, precision, scale ); } - + private static String replace(String type, long size, int precision, int scale) { - type = StringHelper.replaceOnce(type, "$s", Integer.toString(scale) ); - type = StringHelper.replaceOnce(type, "$l", Long.toString(size) ); - return StringHelper.replaceOnce(type, "$p", Integer.toString(precision) ); + type = StringHelper.replaceOnce( type, "$s", Integer.toString( scale ) ); + type = StringHelper.replaceOnce( type, "$l", Long.toString( size ) ); + return StringHelper.replaceOnce( type, "$p", Integer.toString( precision ) ); } /** - * set a type name for specified type key and capacity - * @param typecode the type key + * Register a weighted typeCode mapping + * + * @param typeCode the JDBC type code + * @param capacity The capacity for this weighting + * @param value The mapping (type name) */ - public void put(int typecode, long capacity, String value) { - Map map = weighted.get( typecode ); - if (map == null) {// add new ordered map + public void put(int typeCode, long capacity, String value) { + Map map = weighted.get( typeCode ); + if ( map == null ) { + // add new ordered map map = new TreeMap(); - weighted.put( typecode, map ); + weighted.put( typeCode, map ); } - map.put(capacity, value); + map.put( capacity, value ); } /** - * set a default type name for specified type key - * @param typecode the type key + * Register a default (non-weighted) typeCode mapping + * + * @param typeCode the type key + * @param value The mapping (type name) */ - public void put(int typecode, String value) { - defaults.put( typecode, value ); + public void put(int typeCode, String value) { + defaults.put( typeCode, value ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/AbstractAnsiTrimEmulationFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/AbstractAnsiTrimEmulationFunction.java index 698ba346a7..0a0e726d6c 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/AbstractAnsiTrimEmulationFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/AbstractAnsiTrimEmulationFunction.java @@ -79,27 +79,32 @@ public abstract class AbstractAnsiTrimEmulationFunction implements SQLFunction { if ( args.size() == 1 ) { // we have the form: trim(trimSource) // so we trim leading and trailing spaces - return resolveBothSpaceTrimFunction().render( argumentType, args, factory ); // EARLY EXIT!!!! + return resolveBothSpaceTrimFunction().render( argumentType, args, factory ); } - else if ( "from".equalsIgnoreCase( ( String ) args.get( 0 ) ) ) { + else if ( "from".equalsIgnoreCase( (String) args.get( 0 ) ) ) { // we have the form: trim(from trimSource). // This is functionally equivalent to trim(trimSource) - return resolveBothSpaceTrimFromFunction().render( argumentType, args, factory ); // EARLY EXIT!!!! + return resolveBothSpaceTrimFromFunction().render( argumentType, args, factory ); } else { // otherwise, a trim-specification and/or a trim-character // have been specified; we need to decide which options // are present and "do the right thing" - boolean leading = true; // should leading trim-characters be trimmed? - boolean trailing = true; // should trailing trim-characters be trimmed? - String trimCharacter; // the trim-character (what is to be trimmed off?) - String trimSource; // the trim-source (from where should it be trimmed?) + + // should leading trim-characters be trimmed? + boolean leading = true; + // should trailing trim-characters be trimmed? + boolean trailing = true; + // the trim-character (what is to be trimmed off?) + String trimCharacter; + // the trim-source (from where should it be trimmed?) + String trimSource; // potentialTrimCharacterArgIndex = 1 assumes that a // trim-specification has been specified. we handle the // exception to that explicitly int potentialTrimCharacterArgIndex = 1; - String firstArg = ( String ) args.get( 0 ); + final String firstArg = (String) args.get( 0 ); if ( "leading".equalsIgnoreCase( firstArg ) ) { trailing = false; } @@ -107,15 +112,16 @@ public abstract class AbstractAnsiTrimEmulationFunction implements SQLFunction { leading = false; } else if ( "both".equalsIgnoreCase( firstArg ) ) { + // nothing to do here } else { potentialTrimCharacterArgIndex = 0; } - String potentialTrimCharacter = ( String ) args.get( potentialTrimCharacterArgIndex ); + final String potentialTrimCharacter = (String) args.get( potentialTrimCharacterArgIndex ); if ( "from".equalsIgnoreCase( potentialTrimCharacter ) ) { trimCharacter = "' '"; - trimSource = ( String ) args.get( potentialTrimCharacterArgIndex + 1 ); + trimSource = (String) args.get( potentialTrimCharacterArgIndex + 1 ); } else if ( potentialTrimCharacterArgIndex + 1 >= args.size() ) { trimCharacter = "' '"; @@ -123,15 +129,15 @@ public abstract class AbstractAnsiTrimEmulationFunction implements SQLFunction { } else { trimCharacter = potentialTrimCharacter; - if ( "from".equalsIgnoreCase( ( String ) args.get( potentialTrimCharacterArgIndex + 1 ) ) ) { - trimSource = ( String ) args.get( potentialTrimCharacterArgIndex + 2 ); + if ( "from".equalsIgnoreCase( (String) args.get( potentialTrimCharacterArgIndex + 1 ) ) ) { + trimSource = (String) args.get( potentialTrimCharacterArgIndex + 2 ); } else { - trimSource = ( String ) args.get( potentialTrimCharacterArgIndex + 1 ); + trimSource = (String) args.get( potentialTrimCharacterArgIndex + 1 ); } } - List argsToUse = new ArrayList(); + final List argsToUse = new ArrayList(); argsToUse.add( trimSource ); argsToUse.add( trimCharacter ); diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/AnsiTrimEmulationFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/AnsiTrimEmulationFunction.java index ab566bbcc0..3514d84516 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/AnsiTrimEmulationFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/AnsiTrimEmulationFunction.java @@ -21,7 +21,7 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.dialect.function; +package org.hibernate.dialect.function; import org.hibernate.type.StandardBasicTypes; /** @@ -34,20 +34,51 @@ import org.hibernate.type.StandardBasicTypes; * @author Steve Ebersole */ public class AnsiTrimEmulationFunction extends AbstractAnsiTrimEmulationFunction { + /** + * The default {@code ltrim} function name + */ public static final String LTRIM = "ltrim"; + + /** + * The default {@code rtrim} function name + */ public static final String RTRIM = "rtrim"; + + /** + * The default {@code replace} function name + */ public static final String REPLACE = "replace"; + + /** + * The placeholder used to represent whitespace + */ public static final String SPACE_PLACEHOLDER = "${space}$"; + /** + * The SQLFunctionTemplate pattern for the trimming leading spaces + */ public static final String LEADING_SPACE_TRIM_TEMPLATE = LTRIM + "(?1)"; + + /** + * The SQLFunctionTemplate pattern for the trimming trailing spaces + */ public static final String TRAILING_SPACE_TRIM_TEMPLATE = RTRIM + "(?1)"; + + /** + * The SQLFunctionTemplate pattern for the trimming both leading and trailing spaces + */ public static final String BOTH_SPACE_TRIM_TEMPLATE = LTRIM + "(" + RTRIM + "(?1))"; - public static final String BOTH_SPACE_TRIM_FROM_TEMPLATE = LTRIM + "(" + RTRIM + "(?2))"; //skip the FROM keyword in params + + /** + * The SQLFunctionTemplate pattern for the trimming both leading and trailing spaces, with the optional FROM keyword. + * Different because we need to skip the FROM keyword in the SQLFunctionTemplate processing + */ + public static final String BOTH_SPACE_TRIM_FROM_TEMPLATE = LTRIM + "(" + RTRIM + "(?2))"; /** * A template for the series of calls required to trim non-space chars from the beginning of text. *

    - * NOTE : essentially we: + * NOTE : essentially we:

      *
    1. replace all space chars with the text '${space}$'
    2. *
    3. replace all the actual replacement chars with space chars
    4. *
    5. perform left-trimming (that removes any of the space chars we just added which occur at the beginning of the text)
    6. @@ -206,6 +237,7 @@ public class AnsiTrimEmulationFunction extends AbstractAnsiTrimEmulationFunction /** * {@inheritDoc} */ + @Override protected SQLFunction resolveBothSpaceTrimFunction() { return bothSpaceTrim; } @@ -213,6 +245,7 @@ public class AnsiTrimEmulationFunction extends AbstractAnsiTrimEmulationFunction /** * {@inheritDoc} */ + @Override protected SQLFunction resolveBothSpaceTrimFromFunction() { return bothSpaceTrimFrom; } @@ -220,6 +253,7 @@ public class AnsiTrimEmulationFunction extends AbstractAnsiTrimEmulationFunction /** * {@inheritDoc} */ + @Override protected SQLFunction resolveLeadingSpaceTrimFunction() { return leadingSpaceTrim; } @@ -227,6 +261,7 @@ public class AnsiTrimEmulationFunction extends AbstractAnsiTrimEmulationFunction /** * {@inheritDoc} */ + @Override protected SQLFunction resolveTrailingSpaceTrimFunction() { return trailingSpaceTrim; } @@ -234,6 +269,7 @@ public class AnsiTrimEmulationFunction extends AbstractAnsiTrimEmulationFunction /** * {@inheritDoc} */ + @Override protected SQLFunction resolveBothTrimFunction() { return bothTrim; } @@ -241,6 +277,7 @@ public class AnsiTrimEmulationFunction extends AbstractAnsiTrimEmulationFunction /** * {@inheritDoc} */ + @Override protected SQLFunction resolveLeadingTrimFunction() { return leadingTrim; } @@ -248,6 +285,7 @@ public class AnsiTrimEmulationFunction extends AbstractAnsiTrimEmulationFunction /** * {@inheritDoc} */ + @Override protected SQLFunction resolveTrailingTrimFunction() { return trailingTrim; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/AnsiTrimFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/AnsiTrimFunction.java index e8427b8bf1..8d989fb012 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/AnsiTrimFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/AnsiTrimFunction.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect.function; + import org.hibernate.engine.spi.SessionFactoryImplementor; /** @@ -31,14 +32,11 @@ import org.hibernate.engine.spi.SessionFactoryImplementor; */ public class AnsiTrimFunction extends TrimFunctionTemplate { protected String render(Options options, String trimSource, SessionFactoryImplementor factory) { - return new StringBuilder() - .append( "trim(" ) - .append( options.getTrimSpecification().getName() ) - .append( ' ' ) - .append( options.getTrimCharacter() ) - .append( " from " ) - .append( trimSource ) - .append( ')' ) - .toString(); + return String.format( + "trim(%s %s from %s)", + options.getTrimSpecification().getName(), + options.getTrimCharacter(), + trimSource + ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/AvgWithArgumentCastFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/AvgWithArgumentCastFunction.java index 81415cb87b..08afb4af06 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/AvgWithArgumentCastFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/AvgWithArgumentCastFunction.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect.function; + import java.sql.Types; /** @@ -34,6 +35,11 @@ import java.sql.Types; public class AvgWithArgumentCastFunction extends StandardAnsiSqlAggregationFunctions.AvgFunction { private final String castType; + /** + * Constructs a AvgWithArgumentCastFunction + * + * @param castType The type to cast the avg argument to + */ public AvgWithArgumentCastFunction(String castType) { this.castType = castType; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/CastFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/CastFunction.java index cd124a3a5c..d145854bc7 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/CastFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/CastFunction.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect.function; + import java.util.List; import org.hibernate.QueryException; @@ -30,45 +31,43 @@ import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.type.Type; /** - * ANSI-SQL style cast(foo as type) where the type is - * a Hibernate type + * ANSI-SQL style {@code cast(foo as type)} where the type is a Hibernate type + * * @author Gavin King */ public class CastFunction implements SQLFunction { + @Override public boolean hasArguments() { return true; } + @Override public boolean hasParenthesesIfNoArguments() { return true; } + @Override public Type getReturnType(Type columnType, Mapping mapping) throws QueryException { - return columnType; // this is really just a guess, unless the caller properly identifies the 'type' argument here + // this is really just a guess, unless the caller properly identifies the 'type' argument here + return columnType; } + @Override public String render(Type columnType, List args, SessionFactoryImplementor factory) throws QueryException { if ( args.size()!=2 ) { throw new QueryException("cast() requires two arguments"); } - String type = (String) args.get(1); - int[] sqlTypeCodes = factory.getTypeResolver().heuristicType(type).sqlTypes(factory); + final String type = (String) args.get( 1 ); + final int[] sqlTypeCodes = factory.getTypeResolver().heuristicType( type ).sqlTypes( factory ); if ( sqlTypeCodes.length!=1 ) { throw new QueryException("invalid Hibernate type for cast()"); } String sqlType = factory.getDialect().getCastTypeName( sqlTypeCodes[0] ); - if (sqlType==null) { + if ( sqlType == null ) { //TODO: never reached, since getExplicitHibernateTypeName() actually throws an exception! sqlType = type; } - /*else { - //trim off the length/precision/scale - int loc = sqlType.indexOf('('); - if (loc>-1) { - sqlType = sqlType.substring(0, loc); - } - }*/ - return "cast(" + args.get(0) + " as " + sqlType + ')'; + return "cast(" + args.get( 0 ) + " as " + sqlType + ')'; } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/CharIndexFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/CharIndexFunction.java index 5b29a650a3..2ee38af192 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/CharIndexFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/CharIndexFunction.java @@ -32,33 +32,42 @@ import org.hibernate.type.Type; /** * Emulation of locate() on Sybase + * * @author Nathan Moon */ public class CharIndexFunction implements SQLFunction { + @Override public boolean hasArguments() { return true; } + @Override public boolean hasParenthesesIfNoArguments() { return true; } + @Override public Type getReturnType(Type columnType, Mapping mapping) throws QueryException { return StandardBasicTypes.INTEGER; } + @Override public String render(Type columnType, List args, SessionFactoryImplementor factory) throws QueryException { - boolean threeArgs = args.size() > 2; - Object pattern = args.get(0); - Object string = args.get(1); - Object start = threeArgs ? args.get(2) : null; + final boolean threeArgs = args.size() > 2; + final Object pattern = args.get( 0 ); + final Object string = args.get( 1 ); + final Object start = threeArgs ? args.get( 2 ) : null; - StringBuilder buf = new StringBuilder(); - buf.append("charindex(").append( pattern ).append(", "); - if (threeArgs) buf.append( "right("); + final StringBuilder buf = new StringBuilder(); + buf.append( "charindex(" ).append( pattern ).append( ", " ); + if (threeArgs) { + buf.append( "right(" ); + } buf.append( string ); - if (threeArgs) buf.append( ", char_length(" ).append( string ).append(")-(").append( start ).append("-1))"); - buf.append(')'); + if (threeArgs) { + buf.append( ", char_length(" ).append( string ).append( ")-(" ).append( start ).append( "-1))" ); + } + buf.append( ')' ); return buf.toString(); } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/ClassicAvgFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/ClassicAvgFunction.java index e75f9a4286..cd3b5fdfcb 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/ClassicAvgFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/ClassicAvgFunction.java @@ -34,13 +34,16 @@ import org.hibernate.type.Type; * Classic AVG sqlfunction that return types as it was done in Hibernate 3.1 * * @author Max Rydahl Andersen - * */ public class ClassicAvgFunction extends StandardSQLFunction { + /** + * Constructs a ClassicAvgFunction + */ public ClassicAvgFunction() { super( "avg" ); } + @Override public Type getReturnType(Type columnType, Mapping mapping) throws QueryException { int[] sqlTypes; try { @@ -49,8 +52,12 @@ public class ClassicAvgFunction extends StandardSQLFunction { catch ( MappingException me ) { throw new QueryException( me ); } - if ( sqlTypes.length != 1 ) throw new QueryException( "multi-column type in avg()" ); - int sqlType = sqlTypes[0]; + + if ( sqlTypes.length != 1 ) { + throw new QueryException( "multi-column type in avg()" ); + } + + final int sqlType = sqlTypes[0]; if ( sqlType == Types.INTEGER || sqlType == Types.BIGINT || sqlType == Types.TINYINT ) { return StandardBasicTypes.FLOAT; } @@ -58,4 +65,4 @@ public class ClassicAvgFunction extends StandardSQLFunction { return columnType; } } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/ClassicCountFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/ClassicCountFunction.java index 6b7804291a..f26fc62cee 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/ClassicCountFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/ClassicCountFunction.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect.function; + import org.hibernate.engine.spi.Mapping; import org.hibernate.type.StandardBasicTypes; import org.hibernate.type.Type; @@ -30,14 +31,17 @@ import org.hibernate.type.Type; * Classic COUNT sqlfunction that return types as it was done in Hibernate 3.1 * * @author Max Rydahl Andersen - * */ public class ClassicCountFunction extends StandardSQLFunction { + /** + * Constructs a ClassicCountFunction + */ public ClassicCountFunction() { super( "count" ); } + @Override public Type getReturnType(Type columnType, Mapping mapping) { return StandardBasicTypes.INTEGER; } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/ClassicSumFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/ClassicSumFunction.java index 1da180f9b0..6bfed870de 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/ClassicSumFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/ClassicSumFunction.java @@ -21,8 +21,7 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.dialect.function; - +package org.hibernate.dialect.function; /** * Classic SUM sqlfunction that return types as it was done in Hibernate 3.1 @@ -31,7 +30,10 @@ package org.hibernate.dialect.function; * */ public class ClassicSumFunction extends StandardSQLFunction { + /** + * Constructs a ClassicSumFunction + */ public ClassicSumFunction() { super( "sum" ); } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/ConditionalParenthesisFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/ConditionalParenthesisFunction.java index 4f35062f40..b47e96058c 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/ConditionalParenthesisFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/ConditionalParenthesisFunction.java @@ -34,28 +34,39 @@ import org.hibernate.type.Type; * @author Jonathan Levinson */ public class ConditionalParenthesisFunction extends StandardSQLFunction { - + /** + * Constructs a ConditionalParenthesisFunction with the given name + * + * @param name The function name + */ public ConditionalParenthesisFunction(String name) { super( name ); } + /** + * Constructs a ConditionalParenthesisFunction with the given name + * + * @param name The function name + * @param type The function return type + */ public ConditionalParenthesisFunction(String name, Type type) { super( name, type ); } + @Override public boolean hasParenthesesIfNoArguments() { return false; } - public String render(List args, SessionFactoryImplementor factory) { - final boolean hasArgs = !args.isEmpty(); - StringBuilder buf = new StringBuilder(); - buf.append( getName() ); + @Override + public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor sessionFactory) { + final boolean hasArgs = !arguments.isEmpty(); + final StringBuilder buf = new StringBuilder( getName() ); if ( hasArgs ) { buf.append( "(" ); - for ( int i = 0; i < args.size(); i++ ) { - buf.append( args.get( i ) ); - if ( i < args.size() - 1 ) { + for ( int i = 0; i < arguments.size(); i++ ) { + buf.append( arguments.get( i ) ); + if ( i < arguments.size() - 1 ) { buf.append( ", " ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/ConvertFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/ConvertFunction.java index 6af5b5dd51..801ef44b40 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/ConvertFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/ConvertFunction.java @@ -36,24 +36,28 @@ import org.hibernate.type.Type; * @author Jonathan Levinson */ public class ConvertFunction implements SQLFunction { - + @Override public boolean hasArguments() { return true; } + @Override public boolean hasParenthesesIfNoArguments() { return true; } + @Override public Type getReturnType(Type firstArgumentType, Mapping mapping) throws QueryException { return StandardBasicTypes.STRING; } + @Override public String render(Type firstArgumentType, List args, SessionFactoryImplementor factory) throws QueryException { if ( args.size() != 2 && args.size() != 3 ) { throw new QueryException( "convert() requires two or three arguments" ); } - String type = ( String ) args.get( 1 ); + + final String type = (String) args.get( 1 ); if ( args.size() == 2 ) { return "{fn convert(" + args.get( 0 ) + " , " + type + ")}"; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/DerbyConcatFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/DerbyConcatFunction.java index 786933fdcb..3cf7e847f9 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/DerbyConcatFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/DerbyConcatFunction.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect.function; + import java.util.Iterator; import java.util.List; @@ -33,8 +34,8 @@ import org.hibernate.type.Type; /** * A specialized concat() function definition in which:
        - *
      1. we translate to use the concat operator ('||')
      2. - *
      3. wrap dynamic parameters in CASTs to VARCHAR
      4. + *
      5. we translate to use the concat operator ('||')
      6. + *
      7. wrap dynamic parameters in CASTs to VARCHAR
      8. *
      *

      * This last spec is to deal with a limitation on DB2 and variants (e.g. Derby) @@ -51,6 +52,7 @@ public class DerbyConcatFunction implements SQLFunction { *

      * Here we always return true */ + @Override public boolean hasArguments() { return true; } @@ -60,6 +62,7 @@ public class DerbyConcatFunction implements SQLFunction { *

      * Here we always return true */ + @Override public boolean hasParenthesesIfNoArguments() { return true; } @@ -69,6 +72,7 @@ public class DerbyConcatFunction implements SQLFunction { *

      * Here we always return {@link StandardBasicTypes#STRING}. */ + @Override public Type getReturnType(Type argumentType, Mapping mapping) throws QueryException { return StandardBasicTypes.STRING; } @@ -83,25 +87,23 @@ public class DerbyConcatFunction implements SQLFunction { * arg elements in cast function calls, use the concatenation operator on the cast * returns, and then wrap that whole thing in a call to the Derby varchar function. */ + @Override public String render(Type argumentType, List args, SessionFactoryImplementor factory) throws QueryException { - boolean areAllArgsParams = true; - Iterator itr = args.iterator(); - while ( itr.hasNext() ) { - final String arg = ( String ) itr.next(); - if ( ! "?".equals( arg ) ) { - areAllArgsParams = false; + // first figure out if all arguments are dynamic (jdbc parameters) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + boolean areAllArgumentsDynamic = true; + for ( Object arg1 : args ) { + final String arg = (String) arg1; + if ( !"?".equals( arg ) ) { + // we found a non-dynamic argument + areAllArgumentsDynamic = false; break; } } - if ( areAllArgsParams ) { + if ( areAllArgumentsDynamic ) { return join( args.iterator(), - new StringTransformer() { - public String transform(String string) { - return "cast( ? as varchar(32672) )"; - } - }, + CAST_STRING_TRANSFORMER, new StringJoinTemplate() { public String getBeginning() { return "varchar( "; @@ -118,11 +120,7 @@ public class DerbyConcatFunction implements SQLFunction { else { return join( args.iterator(), - new StringTransformer() { - public String transform(String string) { - return string; - } - }, + NO_TRANSFORM_STRING_TRANSFORMER, new StringJoinTemplate() { public String getBeginning() { return "("; @@ -139,9 +137,31 @@ public class DerbyConcatFunction implements SQLFunction { } private static interface StringTransformer { + /** + * Transform a string to another + * + * @param string The String to be transformed + * + * @return The transformed form + */ public String transform(String string); } + private static final StringTransformer CAST_STRING_TRANSFORMER = new StringTransformer() { + @Override + public String transform(String string) { + // expectation is that incoming string is "?" + return "cast( ? as varchar(32672) )"; + } + }; + + private static final StringTransformer NO_TRANSFORM_STRING_TRANSFORMER = new StringTransformer() { + @Override + public String transform(String string) { + return string; + } + }; + private static interface StringJoinTemplate { /** * Getter for property 'beginning'. @@ -165,9 +185,9 @@ public class DerbyConcatFunction implements SQLFunction { private static String join(Iterator/**/ elements, StringTransformer elementTransformer, StringJoinTemplate template) { // todo : make this available via StringHelper? - StringBuilder buffer = new StringBuilder( template.getBeginning() ); + final StringBuilder buffer = new StringBuilder( template.getBeginning() ); while ( elements.hasNext() ) { - final String element = ( String ) elements.next(); + final String element = (String) elements.next(); buffer.append( elementTransformer.transform( element ) ); if ( elements.hasNext() ) { buffer.append( template.getSeparator() ); diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/NoArgSQLFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/NoArgSQLFunction.java index 366ae1a35e..dac23a2310 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/NoArgSQLFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/NoArgSQLFunction.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect.function; + import java.util.List; import org.hibernate.QueryException; @@ -31,40 +32,57 @@ import org.hibernate.type.Type; /** * A function which takes no arguments - * + * * @author Michi */ public class NoArgSQLFunction implements SQLFunction { - private Type returnType; - private boolean hasParenthesesIfNoArguments; - private String name; + private Type returnType; + private boolean hasParenthesesIfNoArguments; + private String name; - public NoArgSQLFunction(String name, Type returnType) { - this(name, returnType, true); - } + /** + * Constructs a NoArgSQLFunction + * + * @param name The function name + * @param returnType The function return type + */ + public NoArgSQLFunction(String name, Type returnType) { + this( name, returnType, true ); + } - public NoArgSQLFunction(String name, Type returnType, boolean hasParenthesesIfNoArguments) { - this.returnType = returnType; - this.hasParenthesesIfNoArguments = hasParenthesesIfNoArguments; - this.name = name; - } + /** + * Constructs a NoArgSQLFunction + * + * @param name The function name + * @param returnType The function return type + * @param hasParenthesesIfNoArguments Does the function call need parenthesis if there are no arguments? + */ + public NoArgSQLFunction(String name, Type returnType, boolean hasParenthesesIfNoArguments) { + this.returnType = returnType; + this.hasParenthesesIfNoArguments = hasParenthesesIfNoArguments; + this.name = name; + } + @Override public boolean hasArguments() { return false; } + @Override public boolean hasParenthesesIfNoArguments() { return hasParenthesesIfNoArguments; } - public Type getReturnType(Type argumentType, Mapping mapping) throws QueryException { - return returnType; - } + @Override + public Type getReturnType(Type argumentType, Mapping mapping) throws QueryException { + return returnType; + } - public String render(Type argumentType, List args, SessionFactoryImplementor factory) throws QueryException { - if ( args.size()>0 ) { - throw new QueryException("function takes no arguments: " + name); - } - return hasParenthesesIfNoArguments ? name + "()" : name; - } + @Override + public String render(Type argumentType, List args, SessionFactoryImplementor factory) throws QueryException { + if ( args.size() > 0 ) { + throw new QueryException( "function takes no arguments: " + name ); + } + return hasParenthesesIfNoArguments ? name + "()" : name; + } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/NvlFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/NvlFunction.java index fbc09f0e9a..3f8d79d4a8 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/NvlFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/NvlFunction.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect.function; + import java.util.List; import org.hibernate.QueryException; @@ -35,30 +36,32 @@ import org.hibernate.type.Type; * @author Gavin King */ public class NvlFunction implements SQLFunction { + @Override public boolean hasArguments() { return true; } + @Override public boolean hasParenthesesIfNoArguments() { return true; } + @Override public Type getReturnType(Type argumentType, Mapping mapping) throws QueryException { return argumentType; } + @Override + @SuppressWarnings("unchecked") public String render(Type argumentType, List args, SessionFactoryImplementor factory) throws QueryException { - int lastIndex = args.size()-1; - Object last = args.remove(lastIndex); + final int lastIndex = args.size()-1; + final Object last = args.remove( lastIndex ); if ( lastIndex==0 ) { return last.toString(); } - Object secondLast = args.get(lastIndex-1); - String nvl = "nvl(" + secondLast + ", " + last + ")"; - args.set(lastIndex-1, nvl); + final Object secondLast = args.get( lastIndex-1 ); + final String nvl = "nvl(" + secondLast + ", " + last + ")"; + args.set( lastIndex-1, nvl ); return render( argumentType, args, factory ); } - - - } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/PositionSubstringFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/PositionSubstringFunction.java index 0e188bb71a..1561f6264b 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/PositionSubstringFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/PositionSubstringFunction.java @@ -32,35 +32,48 @@ import org.hibernate.type.Type; /** * Emulation of locate() on PostgreSQL + * * @author Gavin King */ public class PositionSubstringFunction implements SQLFunction { + @Override public boolean hasArguments() { return true; } + @Override public boolean hasParenthesesIfNoArguments() { return true; } + @Override public Type getReturnType(Type firstArgumentType, Mapping mapping) throws QueryException { return StandardBasicTypes.INTEGER; } + @Override public String render(Type firstArgumentType, List args, SessionFactoryImplementor factory) throws QueryException { - boolean threeArgs = args.size() > 2; - Object pattern = args.get(0); - Object string = args.get(1); - Object start = threeArgs ? args.get(2) : null; + final boolean threeArgs = args.size() > 2; + final Object pattern = args.get( 0 ); + final Object string = args.get( 1 ); + final Object start = threeArgs ? args.get( 2 ) : null; - StringBuilder buf = new StringBuilder(); - if (threeArgs) buf.append('('); - buf.append("position(").append( pattern ).append(" in "); - if (threeArgs) buf.append( "substring("); + final StringBuilder buf = new StringBuilder(); + if (threeArgs) { + buf.append( '(' ); + } + buf.append( "position(" ).append( pattern ).append( " in " ); + if (threeArgs) { + buf.append( "substring("); + } buf.append( string ); - if (threeArgs) buf.append( ", " ).append( start ).append(')'); - buf.append(')'); - if (threeArgs) buf.append('+').append( start ).append("-1)"); + if (threeArgs) { + buf.append( ", " ).append( start ).append( ')' ); + } + buf.append( ')' ); + if (threeArgs) { + buf.append( '+' ).append( start ).append( "-1)" ); + } return buf.toString(); } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/SQLFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/SQLFunction.java index 1da29778b1..052913e1c0 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/SQLFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/SQLFunction.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect.function; + import java.util.List; import org.hibernate.QueryException; @@ -70,7 +71,6 @@ public interface SQLFunction { */ public Type getReturnType(Type firstArgumentType, Mapping mapping) throws QueryException; - /** * Render the function call as SQL fragment. *

      diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/SQLFunctionRegistry.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/SQLFunctionRegistry.java index 0414770be6..c3bc29dedf 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/SQLFunctionRegistry.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/SQLFunctionRegistry.java @@ -28,25 +28,51 @@ import java.util.Map; import org.hibernate.dialect.Dialect; +/** + * Defines a registry for SQLFunction instances + * + * @author Steve Ebersole + */ public class SQLFunctionRegistry { private final Dialect dialect; private final Map userFunctions; + /** + * Constructs a SQLFunctionRegistry + * + * @param dialect The dialect + * @param userFunctions Any application-supplied function definitions + */ public SQLFunctionRegistry(Dialect dialect, Map userFunctions) { this.dialect = dialect; this.userFunctions = new HashMap( userFunctions ); } + /** + * Find a SQLFunction by name + * + * @param functionName The name of the function to locate + * + * @return The located function, maye return {@code null} + */ public SQLFunction findSQLFunction(String functionName) { - String name = functionName.toLowerCase(); - SQLFunction userFunction = userFunctions.get( name ); + final String name = functionName.toLowerCase(); + final SQLFunction userFunction = userFunctions.get( name ); return userFunction != null ? userFunction : dialect.getFunctions().get( name ); } + /** + * Does this registry contain the named function + * + * @param functionName The name of the function to attempt to locate + * + * @return {@code true} if the registry contained that function + */ + @SuppressWarnings("UnusedDeclaration") public boolean hasFunction(String functionName) { - String name = functionName.toLowerCase(); + final String name = functionName.toLowerCase(); return userFunctions.containsKey( name ) || dialect.getFunctions().containsKey( name ); } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/SQLFunctionTemplate.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/SQLFunctionTemplate.java index 52e46789f2..16d13dccb3 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/SQLFunctionTemplate.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/SQLFunctionTemplate.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect.function; + import java.util.List; import org.hibernate.QueryException; @@ -30,11 +31,13 @@ import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.type.Type; /** - * Represents HQL functions that can have different representations in different SQL dialects. - * E.g. in HQL we can define function concat(?1, ?2) to concatenate two strings - * p1 and p2. Target SQL function will be dialect-specific, e.g. (?1 || ?2) for - * Oracle, concat(?1, ?2) for MySql, (?1 + ?2) for MS SQL. - * Each dialect will define a template as a string (exactly like above) marking function + * Represents HQL functions that can have different representations in different SQL dialects where that + * difference can be handled via a template/pattern. + *

      + * E.g. in HQL we can define function concat(?1, ?2) to concatenate two strings + * p1 and p2. Dialects would register different versions of this class *using the same name* (concat) but with + * different templates or patterns; (?1 || ?2) for Oracle, concat(?1, ?2) for MySql, + * (?1 + ?2) for MS SQL. Each dialect will define a template as a string (exactly like above) marking function * parameters with '?' followed by parameter's index (first index is 1). * * @author Alexey Loubyansky @@ -44,47 +47,50 @@ public class SQLFunctionTemplate implements SQLFunction { private final TemplateRenderer renderer; private final boolean hasParenthesesIfNoArgs; + /** + * Constructs a SQLFunctionTemplate + * + * @param type The functions return type + * @param template The function template + */ public SQLFunctionTemplate(Type type, String template) { this( type, template, true ); } + /** + * Constructs a SQLFunctionTemplate + * + * @param type The functions return type + * @param template The function template + * @param hasParenthesesIfNoArgs If there are no arguments, are parentheses required? + */ public SQLFunctionTemplate(Type type, String template, boolean hasParenthesesIfNoArgs) { this.type = type; this.renderer = new TemplateRenderer( template ); this.hasParenthesesIfNoArgs = hasParenthesesIfNoArgs; } - /** - * {@inheritDoc} - */ + @Override public String render(Type argumentType, List args, SessionFactoryImplementor factory) { return renderer.render( args, factory ); } - /** - * {@inheritDoc} - */ + @Override public Type getReturnType(Type argumentType, Mapping mapping) throws QueryException { return type; } - /** - * {@inheritDoc} - */ + @Override public boolean hasArguments() { return renderer.getAnticipatedNumberOfArguments() > 0; } - /** - * {@inheritDoc} - */ + @Override public boolean hasParenthesesIfNoArguments() { return hasParenthesesIfNoArgs; } - /** - * {@inheritDoc} - */ + @Override public String toString() { return renderer.getTemplate(); } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/StandardAnsiSqlAggregationFunctions.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/StandardAnsiSqlAggregationFunctions.java index 34712c321f..862173fcba 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/StandardAnsiSqlAggregationFunctions.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/StandardAnsiSqlAggregationFunctions.java @@ -45,9 +45,12 @@ public class StandardAnsiSqlAggregationFunctions { * Definition of a standard ANSI SQL compliant COUNT function */ public static class CountFunction extends StandardSQLFunction { + /** + * Singleton access + */ public static final CountFunction INSTANCE = new CountFunction(); - public CountFunction() { + protected CountFunction() { super( "count", StandardBasicTypes.LONG ); } @@ -62,35 +65,37 @@ public class StandardAnsiSqlAggregationFunctions { } private String renderCountDistinct(List arguments) { - StringBuilder buffer = new StringBuilder(); + final StringBuilder buffer = new StringBuilder(); buffer.append( "count(distinct " ); String sep = ""; - Iterator itr = arguments.iterator(); - itr.next(); // intentionally skip first + final Iterator itr = arguments.iterator(); + // intentionally skip first + itr.next(); while ( itr.hasNext() ) { - buffer.append( sep ) - .append( itr.next() ); + buffer.append( sep ).append( itr.next() ); sep = ", "; } return buffer.append( ")" ).toString(); } } - /** * Definition of a standard ANSI SQL compliant AVG function */ public static class AvgFunction extends StandardSQLFunction { + /** + * Singleton access + */ public static final AvgFunction INSTANCE = new AvgFunction(); - public AvgFunction() { + protected AvgFunction() { super( "avg", StandardBasicTypes.DOUBLE ); } @Override public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor factory) throws QueryException { - int jdbcTypeCode = determineJdbcTypeCode( firstArgumentType, factory ); - return render( jdbcTypeCode, arguments.get(0).toString(), factory ); + final int jdbcTypeCode = determineJdbcTypeCode( firstArgumentType, factory ); + return render( jdbcTypeCode, arguments.get( 0 ).toString(), factory ); } protected final int determineJdbcTypeCode(Type firstArgumentType, SessionFactoryImplementor factory) throws QueryException { @@ -106,6 +111,7 @@ public class StandardAnsiSqlAggregationFunctions { } } + @SuppressWarnings("UnusedParameters") protected String render(int firstArgumentJdbcType, String argument, SessionFactoryImplementor factory) { return "avg(" + renderArgument( argument, firstArgumentJdbcType ) + ")"; } @@ -115,44 +121,49 @@ public class StandardAnsiSqlAggregationFunctions { } } - + /** + * Definition of a standard ANSI SQL compliant MAX function + */ public static class MaxFunction extends StandardSQLFunction { + /** + * Singleton access + */ public static final MaxFunction INSTANCE = new MaxFunction(); - public MaxFunction() { + protected MaxFunction() { super( "max" ); } } + /** + * Definition of a standard ANSI SQL compliant MIN function + */ public static class MinFunction extends StandardSQLFunction { + /** + * Singleton access + */ public static final MinFunction INSTANCE = new MinFunction(); - public MinFunction() { + protected MinFunction() { super( "min" ); } } + /** + * Definition of a standard ANSI SQL compliant SUM function + */ public static class SumFunction extends StandardSQLFunction { + /** + * Singleton access + */ public static final SumFunction INSTANCE = new SumFunction(); - public SumFunction() { + protected SumFunction() { super( "sum" ); } - protected final int determineJdbcTypeCode(Type type, Mapping mapping) throws QueryException { - try { - final int[] jdbcTypeCodes = type.sqlTypes( mapping ); - if ( jdbcTypeCodes.length != 1 ) { - throw new QueryException( "multiple-column type in sum()" ); - } - return jdbcTypeCodes[0]; - } - catch ( MappingException me ) { - throw new QueryException( me ); - } - } - + @Override public Type getReturnType(Type firstArgumentType, Mapping mapping) { final int jdbcType = determineJdbcTypeCode( firstArgumentType, mapping ); @@ -193,8 +204,27 @@ public class StandardAnsiSqlAggregationFunctions { // as a last resort, return the type of the first argument return firstArgumentType; } + + protected final int determineJdbcTypeCode(Type type, Mapping mapping) throws QueryException { + try { + final int[] jdbcTypeCodes = type.sqlTypes( mapping ); + if ( jdbcTypeCodes.length != 1 ) { + throw new QueryException( "multiple-column type in sum()" ); + } + return jdbcTypeCodes[0]; + } + catch ( MappingException me ) { + throw new QueryException( me ); + } + } + } + /** + * Push the functions defined on StandardAnsiSqlAggregationFunctions into the given map + * + * @param functionMap The map of functions to push to + */ public static void primeFunctionMap(Map functionMap) { functionMap.put( AvgFunction.INSTANCE.getName(), AvgFunction.INSTANCE ); functionMap.put( CountFunction.INSTANCE.getName(), CountFunction.INSTANCE ); @@ -202,4 +232,7 @@ public class StandardAnsiSqlAggregationFunctions { functionMap.put( MinFunction.INSTANCE.getName(), MinFunction.INSTANCE ); functionMap.put( SumFunction.INSTANCE.getName(), SumFunction.INSTANCE ); } + + private StandardAnsiSqlAggregationFunctions() { + } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/StandardJDBCEscapeFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/StandardJDBCEscapeFunction.java index b37ce6183d..ec9794d8c1 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/StandardJDBCEscapeFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/StandardJDBCEscapeFunction.java @@ -35,18 +35,22 @@ import org.hibernate.type.Type; * @author Steve Ebersole */ public class StandardJDBCEscapeFunction extends StandardSQLFunction { - public StandardJDBCEscapeFunction(String name) { - super( name ); - } - + /** + * Constructs a StandardJDBCEscapeFunction + * + * @param name The function name + * @param typeValue The function return type + */ public StandardJDBCEscapeFunction(String name, Type typeValue) { super( name, typeValue ); } + @Override public String render(Type argumentType, List args, SessionFactoryImplementor factory) { return "{fn " + super.render( argumentType, args, factory ) + "}"; } + @Override public String toString() { return "{fn " + getName() + "...}"; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/StandardSQLFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/StandardSQLFunction.java index 56bcdb61ce..e8eccf530d 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/StandardSQLFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/StandardSQLFunction.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect.function; + import java.util.List; import org.hibernate.engine.spi.Mapping; @@ -84,32 +85,24 @@ public class StandardSQLFunction implements SQLFunction { return registeredType; } - /** - * {@inheritDoc} - */ + @Override public boolean hasArguments() { return true; } - /** - * {@inheritDoc} - */ + @Override public boolean hasParenthesesIfNoArguments() { return true; } - /** - * {@inheritDoc} - */ + @Override public Type getReturnType(Type firstArgumentType, Mapping mapping) { return registeredType == null ? firstArgumentType : registeredType; } - /** - * {@inheritDoc} - */ + @Override public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor sessionFactory) { - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); buf.append( name ).append( '(' ); for ( int i = 0; i < arguments.size(); i++ ) { buf.append( arguments.get( i ) ); @@ -120,6 +113,7 @@ public class StandardSQLFunction implements SQLFunction { return buf.append( ')' ).toString(); } + @Override public String toString() { return name; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/TemplateRenderer.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/TemplateRenderer.java index d88f70cfe0..f8a64137c3 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/TemplateRenderer.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/TemplateRenderer.java @@ -36,21 +36,28 @@ import org.hibernate.internal.CoreMessageLogger; * @author Steve Ebersole */ public class TemplateRenderer { - - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, TemplateRenderer.class.getName()); + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + TemplateRenderer.class.getName() + ); private final String template; private final String[] chunks; private final int[] paramIndexes; + /** + * Constructs a template renderer + * + * @param template The template + */ @SuppressWarnings({ "UnnecessaryUnboxing" }) public TemplateRenderer(String template) { this.template = template; - List chunkList = new ArrayList(); - List paramList = new ArrayList(); - StringBuilder chunk = new StringBuilder( 10 ); - StringBuilder index = new StringBuilder( 2 ); + final List chunkList = new ArrayList(); + final List paramList = new ArrayList(); + final StringBuilder chunk = new StringBuilder( 10 ); + final StringBuilder index = new StringBuilder( 2 ); for ( int i = 0; i < template.length(); ++i ) { char c = template.charAt( i ); @@ -96,13 +103,21 @@ public class TemplateRenderer { return paramIndexes.length; } + /** + * The rendering code. + * + * @param args The arguments to inject into the template + * @param factory The SessionFactory + * + * @return The rendered template with replacements + */ @SuppressWarnings({ "UnusedDeclaration" }) public String render(List args, SessionFactoryImplementor factory) { - int numberOfArguments = args.size(); + final int numberOfArguments = args.size(); if ( getAnticipatedNumberOfArguments() > 0 && numberOfArguments != getAnticipatedNumberOfArguments() ) { LOG.missingArguments( getAnticipatedNumberOfArguments(), numberOfArguments ); } - StringBuilder buf = new StringBuilder(); + final StringBuilder buf = new StringBuilder(); for ( int i = 0; i < chunks.length; ++i ) { if ( i < paramIndexes.length ) { final int index = paramIndexes[i] - 1; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/TrimFunctionTemplate.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/TrimFunctionTemplate.java index b82847616f..71f22477d9 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/TrimFunctionTemplate.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/TrimFunctionTemplate.java @@ -36,30 +36,34 @@ import org.hibernate.type.Type; * @author Steve Ebersole */ public abstract class TrimFunctionTemplate implements SQLFunction { + @Override public boolean hasArguments() { return true; } + @Override public boolean hasParenthesesIfNoArguments() { return false; } + @Override public Type getReturnType(Type firstArgument, Mapping mapping) throws QueryException { return StandardBasicTypes.STRING; } + @Override public String render(Type firstArgument, List args, SessionFactoryImplementor factory) throws QueryException { final Options options = new Options(); final String trimSource; if ( args.size() == 1 ) { // we have the form: trim(trimSource) - trimSource = ( String ) args.get( 0 ); + trimSource = (String) args.get( 0 ); } - else if ( "from".equalsIgnoreCase( ( String ) args.get( 0 ) ) ) { + else if ( "from".equalsIgnoreCase( (String) args.get( 0 ) ) ) { // we have the form: trim(from trimSource). // This is functionally equivalent to trim(trimSource) - trimSource = ( String ) args.get( 1 ); + trimSource = (String) args.get( 1 ); } else { // otherwise, a trim-specification and/or a trim-character @@ -70,7 +74,7 @@ public abstract class TrimFunctionTemplate implements SQLFunction { // trim-specification has been specified. we handle the // exception to that explicitly int potentialTrimCharacterArgIndex = 1; - String firstArg = ( String ) args.get( 0 ); + final String firstArg = (String) args.get( 0 ); if ( "leading".equalsIgnoreCase( firstArg ) ) { options.setTrimSpecification( Specification.LEADING ); } @@ -84,20 +88,20 @@ public abstract class TrimFunctionTemplate implements SQLFunction { potentialTrimCharacterArgIndex = 0; } - String potentialTrimCharacter = ( String ) args.get( potentialTrimCharacterArgIndex ); + final String potentialTrimCharacter = (String) args.get( potentialTrimCharacterArgIndex ); if ( "from".equalsIgnoreCase( potentialTrimCharacter ) ) { - trimSource = ( String ) args.get( potentialTrimCharacterArgIndex + 1 ); + trimSource = (String) args.get( potentialTrimCharacterArgIndex + 1 ); } else if ( potentialTrimCharacterArgIndex + 1 >= args.size() ) { trimSource = potentialTrimCharacter; } else { options.setTrimCharacter( potentialTrimCharacter ); - if ( "from".equalsIgnoreCase( ( String ) args.get( potentialTrimCharacterArgIndex + 1 ) ) ) { - trimSource = ( String ) args.get( potentialTrimCharacterArgIndex + 2 ); + if ( "from".equalsIgnoreCase( (String) args.get( potentialTrimCharacterArgIndex + 1 ) ) ) { + trimSource = (String) args.get( potentialTrimCharacterArgIndex + 2 ); } else { - trimSource = ( String ) args.get( potentialTrimCharacterArgIndex + 1 ); + trimSource = (String) args.get( potentialTrimCharacterArgIndex + 1 ); } } } @@ -106,7 +110,7 @@ public abstract class TrimFunctionTemplate implements SQLFunction { protected abstract String render(Options options, String trimSource, SessionFactoryImplementor factory); - public static class Options { + protected static class Options { public static final String DEFAULT_TRIM_CHARACTER = "' '"; private String trimCharacter = DEFAULT_TRIM_CHARACTER; @@ -129,7 +133,7 @@ public abstract class TrimFunctionTemplate implements SQLFunction { } } - public static class Specification { + protected static class Specification { public static final Specification LEADING = new Specification( "leading" ); public static final Specification TRAILING = new Specification( "trailing" ); public static final Specification BOTH = new Specification( "both" ); diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/VarArgsSQLFunction.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/VarArgsSQLFunction.java index 3b894e9d0f..e12ab9c8ad 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/VarArgsSQLFunction.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/VarArgsSQLFunction.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect.function; + import java.util.List; import org.hibernate.QueryException; @@ -73,35 +74,26 @@ public class VarArgsSQLFunction implements SQLFunction { this( null, begin, sep, end ); } - /** - * {@inheritDoc} - *

      - * Always returns true here. - */ + @Override public boolean hasArguments() { return true; } - /** - * {@inheritDoc} - *

      - * Always returns true here. - */ + @Override public boolean hasParenthesesIfNoArguments() { return true; } - /** - * {@inheritDoc} - */ + @Override public Type getReturnType(Type firstArgumentType, Mapping mapping) throws QueryException { return registeredType == null ? firstArgumentType : registeredType; } + @Override public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor factory) { - StringBuilder buf = new StringBuilder().append( begin ); + final StringBuilder buf = new StringBuilder().append( begin ); for ( int i = 0; i < arguments.size(); i++ ) { - buf.append( transformArgument( ( String ) arguments.get( i ) ) ); + buf.append( transformArgument( (String) arguments.get( i ) ) ); if ( i < arguments.size() - 1 ) { buf.append( sep ); } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/AbstractSelectLockingStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/AbstractSelectLockingStrategy.java index daea92d3d4..b341232432 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/AbstractSelectLockingStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/AbstractSelectLockingStrategy.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect.lock; + import org.hibernate.LockMode; import org.hibernate.LockOptions; import org.hibernate.persister.entity.Lockable; @@ -70,7 +71,7 @@ public abstract class AbstractSelectLockingStrategy implements LockingStrategy { private String noWaitSql; - public String getNoWaitSql() { + protected String getNoWaitSql() { if ( noWaitSql == null ) { noWaitSql = generateLockString( LockOptions.NO_WAIT ); } @@ -79,7 +80,7 @@ public abstract class AbstractSelectLockingStrategy implements LockingStrategy { private String skipLockedSql; - public String getSkipLockedSql() { + protected String getSkipLockedSql() { if ( skipLockedSql == null ) { skipLockedSql = generateLockString( LockOptions.SKIP_LOCKED ); } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/LockingStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/LockingStrategy.java index 418f74a82f..2eb3ea6498 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/LockingStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/LockingStrategy.java @@ -51,10 +51,11 @@ public interface LockingStrategy { * @param object The object logically being locked (currently not used) * @param timeout timeout in milliseconds, 0 = no wait, -1 = wait indefinitely * @param session The session from which the lock request originated + * * @throws StaleObjectStateException Indicates an inability to locate the database row as part of acquiring * the requested lock. * @throws LockingStrategyException Indicates a failure in the lock attempt */ public void lock(Serializable id, Object version, Object object, int timeout, SessionImplementor session) - throws StaleObjectStateException, LockingStrategyException; + throws StaleObjectStateException, LockingStrategyException; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/LockingStrategyException.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/LockingStrategyException.java index 05a346d702..44963d6fb1 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/LockingStrategyException.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/LockingStrategyException.java @@ -33,13 +33,26 @@ import org.hibernate.HibernateException; public abstract class LockingStrategyException extends HibernateException { private final Object entity; + /** + * Constructs a LockingStrategyException + * + * @param entity The entity we were trying to lock + * @param message Message explaining the condition + */ public LockingStrategyException(Object entity, String message) { super( message ); this.entity = entity; } - public LockingStrategyException(Object entity, String message, Throwable root) { - super( message, root ); + /** + * Constructs a LockingStrategyException + * + * @param entity The entity we were trying to lock + * @param message Message explaining the condition + * @param cause The underlying cause + */ + public LockingStrategyException(Object entity, String message, Throwable cause) { + super( message, cause ); this.entity = entity; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticEntityLockException.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticEntityLockException.java index a5a2552688..5aaf966e1a 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticEntityLockException.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticEntityLockException.java @@ -29,11 +29,24 @@ package org.hibernate.dialect.lock; * @author Steve Ebersole */ public class OptimisticEntityLockException extends LockingStrategyException { + /** + * Constructs a OptimisticEntityLockException + * + * @param entity The entity we were trying to lock + * @param message Message explaining the condition + */ public OptimisticEntityLockException(Object entity, String message) { super( entity, message ); } - public OptimisticEntityLockException(Object entity, String message, Throwable root) { - super( entity, message, root ); + /** + * Constructs a OptimisticEntityLockException + * + * @param entity The entity we were trying to lock + * @param message Message explaining the condition + * @param cause The underlying cause + */ + public OptimisticEntityLockException(Object entity, String message, Throwable cause) { + super( entity, message, cause ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticForceIncrementLockingStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticForceIncrementLockingStrategy.java index 506b262254..07fadc153a 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticForceIncrementLockingStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticForceIncrementLockingStrategy.java @@ -65,14 +65,12 @@ public class OptimisticForceIncrementLockingStrategy implements LockingStrategy if ( !lockable.isVersioned() ) { throw new HibernateException( "[" + lockMode + "] not supported for non-versioned entities [" + lockable.getEntityName() + "]" ); } - EntityEntry entry = session.getPersistenceContext().getEntry( object ); - EntityIncrementVersionProcess incrementVersion = new EntityIncrementVersionProcess( object, entry ); - EventSource source = (EventSource) session; - // Register the EntityIncrementVersionProcess action to run just prior to transaction commit. - source.getActionQueue().registerProcess( incrementVersion ); + final EntityEntry entry = session.getPersistenceContext().getEntry( object ); + // Register the EntityIncrementVersionProcess action to run just prior to transaction commit. + ( (EventSource) session ).getActionQueue().registerProcess( new EntityIncrementVersionProcess( object, entry ) ); } protected LockMode getLockMode() { return lockMode; } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticLockingStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticLockingStrategy.java index ecaa6d2e00..2b200526d5 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticLockingStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticLockingStrategy.java @@ -43,7 +43,6 @@ import org.hibernate.persister.entity.Lockable; * @since 3.5 */ public class OptimisticLockingStrategy implements LockingStrategy { - private final Lockable lockable; private final LockMode lockMode; @@ -66,14 +65,12 @@ public class OptimisticLockingStrategy implements LockingStrategy { if ( !lockable.isVersioned() ) { throw new OptimisticLockException( object, "[" + lockMode + "] not supported for non-versioned entities [" + lockable.getEntityName() + "]" ); } - EntityEntry entry = session.getPersistenceContext().getEntry(object); - EventSource source = (EventSource)session; - EntityVerifyVersionProcess verifyVersion = new EntityVerifyVersionProcess(object, entry); + final EntityEntry entry = session.getPersistenceContext().getEntry(object); // Register the EntityVerifyVersionProcess action to run just prior to transaction commit. - source.getActionQueue().registerProcess(verifyVersion); + ( (EventSource) session ).getActionQueue().registerProcess( new EntityVerifyVersionProcess( object, entry ) ); } protected LockMode getLockMode() { return lockMode; } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticEntityLockException.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticEntityLockException.java index 5929143ef7..2ce792d60a 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticEntityLockException.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticEntityLockException.java @@ -31,7 +31,14 @@ import org.hibernate.JDBCException; * @author Steve Ebersole */ public class PessimisticEntityLockException extends LockingStrategyException { - public PessimisticEntityLockException(Object entity, String message, JDBCException root) { - super( entity, message, root ); + /** + * Constructs a PessimisticEntityLockException + * + * @param entity The entity we were trying to lock + * @param message Message explaining the condition + * @param cause The underlying cause + */ + public PessimisticEntityLockException(Object entity, String message, JDBCException cause) { + super( entity, message, cause ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticForceIncrementLockingStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticForceIncrementLockingStrategy.java index c74fde749f..1b743fbc96 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticForceIncrementLockingStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticForceIncrementLockingStrategy.java @@ -64,9 +64,9 @@ public class PessimisticForceIncrementLockingStrategy implements LockingStrategy if ( !lockable.isVersioned() ) { throw new HibernateException( "[" + lockMode + "] not supported for non-versioned entities [" + lockable.getEntityName() + "]" ); } - EntityEntry entry = session.getPersistenceContext().getEntry( object ); + final EntityEntry entry = session.getPersistenceContext().getEntry( object ); final EntityPersister persister = entry.getPersister(); - Object nextVersion = persister.forceVersionIncrement( entry.getId(), entry.getVersion(), session ); + final Object nextVersion = persister.forceVersionIncrement( entry.getId(), entry.getVersion(), session ); entry.forceLocked( object, nextVersion ); } @@ -78,4 +78,4 @@ public class PessimisticForceIncrementLockingStrategy implements LockingStrategy protected LockMode getLockMode() { return lockMode; } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticReadSelectLockingStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticReadSelectLockingStrategy.java index d12a80cece..5f52a37ddb 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticReadSelectLockingStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticReadSelectLockingStrategy.java @@ -70,10 +70,10 @@ public class PessimisticReadSelectLockingStrategy extends AbstractSelectLockingS @Override public void lock(Serializable id, Object version, Object object, int timeout, SessionImplementor session) { final String sql = determineSql( timeout ); - SessionFactoryImplementor factory = session.getFactory(); + final SessionFactoryImplementor factory = session.getFactory(); try { try { - PreparedStatement st = session.getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); + final PreparedStatement st = session.getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); try { getLockable().getIdentifierType().nullSafeSet( st, id, 1, session ); if ( getLockable().isVersioned() ) { @@ -85,7 +85,7 @@ public class PessimisticReadSelectLockingStrategy extends AbstractSelectLockingS ); } - ResultSet rs = session.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().extract( st ); + final ResultSet rs = session.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().extract( st ); try { if ( !rs.next() ) { if ( factory.getStatistics().isStatisticsEnabled() ) { @@ -118,10 +118,10 @@ public class PessimisticReadSelectLockingStrategy extends AbstractSelectLockingS } protected String generateLockString(int lockTimeout) { - SessionFactoryImplementor factory = getLockable().getFactory(); - LockOptions lockOptions = new LockOptions( getLockMode() ); + final SessionFactoryImplementor factory = getLockable().getFactory(); + final LockOptions lockOptions = new LockOptions( getLockMode() ); lockOptions.setTimeOut( lockTimeout ); - SimpleSelect select = new SimpleSelect( factory.getDialect() ) + final SimpleSelect select = new SimpleSelect( factory.getDialect() ) .setLockOptions( lockOptions ) .setTableName( getLockable().getRootTableName() ) .addColumn( getLockable().getRootTableIdentifierColumnNames()[0] ) @@ -134,4 +134,4 @@ public class PessimisticReadSelectLockingStrategy extends AbstractSelectLockingS } return select.toStatementString(); } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticReadUpdateLockingStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticReadUpdateLockingStrategy.java index 435defc92d..fba6b93853 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticReadUpdateLockingStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticReadUpdateLockingStrategy.java @@ -52,8 +52,7 @@ import org.hibernate.sql.Update; * @since 3.5 */ public class PessimisticReadUpdateLockingStrategy implements LockingStrategy { - - private static final CoreMessageLogger LOG = Logger.getMessageLogger( + private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, PessimisticReadUpdateLockingStrategy.class.getName() ); @@ -89,10 +88,11 @@ public class PessimisticReadUpdateLockingStrategy implements LockingStrategy { if ( !lockable.isVersioned() ) { throw new HibernateException( "write locks via update not supported for non-versioned entities [" + lockable.getEntityName() + "]" ); } - SessionFactoryImplementor factory = session.getFactory(); + + final SessionFactoryImplementor factory = session.getFactory(); try { try { - PreparedStatement st = session.getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); + final PreparedStatement st = session.getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); try { lockable.getVersionType().nullSafeSet( st, version, 1, session ); int offset = 2; @@ -104,8 +104,9 @@ public class PessimisticReadUpdateLockingStrategy implements LockingStrategy { lockable.getVersionType().nullSafeSet( st, version, offset, session ); } - int affected = session.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().executeUpdate( st ); - if ( affected < 0 ) { // todo: should this instead check for exactly one row modified? + final int affected = session.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().executeUpdate( st ); + // todo: should this instead check for exactly one row modified? + if ( affected < 0 ) { if (factory.getStatistics().isStatisticsEnabled()) { factory.getStatisticsImplementor().optimisticFailure( lockable.getEntityName() ); } @@ -132,8 +133,8 @@ public class PessimisticReadUpdateLockingStrategy implements LockingStrategy { } protected String generateLockString() { - SessionFactoryImplementor factory = lockable.getFactory(); - Update update = new Update( factory.getDialect() ); + final SessionFactoryImplementor factory = lockable.getFactory(); + final Update update = new Update( factory.getDialect() ); update.setTableName( lockable.getRootTableName() ); update.addPrimaryKeyColumns( lockable.getRootTableIdentifierColumnNames() ); update.setVersionColumnName( lockable.getVersionColumnName() ); @@ -147,4 +148,4 @@ public class PessimisticReadUpdateLockingStrategy implements LockingStrategy { protected LockMode getLockMode() { return lockMode; } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteSelectLockingStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteSelectLockingStrategy.java index d810aa2eec..e5267a10f4 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteSelectLockingStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteSelectLockingStrategy.java @@ -69,10 +69,10 @@ public class PessimisticWriteSelectLockingStrategy extends AbstractSelectLocking @Override public void lock(Serializable id, Object version, Object object, int timeout, SessionImplementor session) { final String sql = determineSql( timeout ); - SessionFactoryImplementor factory = session.getFactory(); + final SessionFactoryImplementor factory = session.getFactory(); try { try { - PreparedStatement st = session.getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); + final PreparedStatement st = session.getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); try { getLockable().getIdentifierType().nullSafeSet( st, id, 1, session ); if ( getLockable().isVersioned() ) { @@ -84,7 +84,7 @@ public class PessimisticWriteSelectLockingStrategy extends AbstractSelectLocking ); } - ResultSet rs = session.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().extract( st ); + final ResultSet rs = session.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().extract( st ); try { if ( !rs.next() ) { if ( factory.getStatistics().isStatisticsEnabled() ) { @@ -116,10 +116,10 @@ public class PessimisticWriteSelectLockingStrategy extends AbstractSelectLocking } protected String generateLockString(int lockTimeout) { - SessionFactoryImplementor factory = getLockable().getFactory(); - LockOptions lockOptions = new LockOptions( getLockMode() ); + final SessionFactoryImplementor factory = getLockable().getFactory(); + final LockOptions lockOptions = new LockOptions( getLockMode() ); lockOptions.setTimeOut( lockTimeout ); - SimpleSelect select = new SimpleSelect( factory.getDialect() ) + final SimpleSelect select = new SimpleSelect( factory.getDialect() ) .setLockOptions( lockOptions ) .setTableName( getLockable().getRootTableName() ) .addColumn( getLockable().getRootTableIdentifierColumnNames()[0] ) @@ -132,4 +132,4 @@ public class PessimisticWriteSelectLockingStrategy extends AbstractSelectLocking } return select.toStatementString(); } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteUpdateLockingStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteUpdateLockingStrategy.java index 3f47ffa176..184d23c823 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteUpdateLockingStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/PessimisticWriteUpdateLockingStrategy.java @@ -52,8 +52,7 @@ import org.hibernate.sql.Update; * @since 3.5 */ public class PessimisticWriteUpdateLockingStrategy implements LockingStrategy { - - private static final CoreMessageLogger LOG = Logger.getMessageLogger( + private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, PessimisticWriteUpdateLockingStrategy.class.getName() ); @@ -88,10 +87,11 @@ public class PessimisticWriteUpdateLockingStrategy implements LockingStrategy { if ( !lockable.isVersioned() ) { throw new HibernateException( "write locks via update not supported for non-versioned entities [" + lockable.getEntityName() + "]" ); } - SessionFactoryImplementor factory = session.getFactory(); + + final SessionFactoryImplementor factory = session.getFactory(); try { try { - PreparedStatement st = session.getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); + final PreparedStatement st = session.getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); try { lockable.getVersionType().nullSafeSet( st, version, 1, session ); int offset = 2; @@ -103,8 +103,9 @@ public class PessimisticWriteUpdateLockingStrategy implements LockingStrategy { lockable.getVersionType().nullSafeSet( st, version, offset, session ); } - int affected = session.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().executeUpdate( st ); - if ( affected < 0 ) { // todo: should this instead check for exactly one row modified? + final int affected = session.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().executeUpdate( st ); + // todo: should this instead check for exactly one row modified? + if ( affected < 0 ) { if (factory.getStatistics().isStatisticsEnabled()) { factory.getStatisticsImplementor().optimisticFailure( lockable.getEntityName() ); } @@ -130,8 +131,8 @@ public class PessimisticWriteUpdateLockingStrategy implements LockingStrategy { } protected String generateLockString() { - SessionFactoryImplementor factory = lockable.getFactory(); - Update update = new Update( factory.getDialect() ); + final SessionFactoryImplementor factory = lockable.getFactory(); + final Update update = new Update( factory.getDialect() ); update.setTableName( lockable.getRootTableName() ); update.addPrimaryKeyColumns( lockable.getRootTableIdentifierColumnNames() ); update.setVersionColumnName( lockable.getVersionColumnName() ); @@ -145,4 +146,4 @@ public class PessimisticWriteUpdateLockingStrategy implements LockingStrategy { protected LockMode getLockMode() { return lockMode; } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/SelectLockingStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/SelectLockingStrategy.java index 8e44214a99..eaca2bca66 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/SelectLockingStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/SelectLockingStrategy.java @@ -61,19 +61,17 @@ public class SelectLockingStrategy extends AbstractSelectLockingStrategy { super( lockable, lockMode ); } - /** - * @see LockingStrategy#lock - */ + @Override public void lock( - Serializable id, - Object version, - Object object, - int timeout, - SessionImplementor session) throws StaleObjectStateException, JDBCException { + Serializable id, + Object version, + Object object, + int timeout, + SessionImplementor session) throws StaleObjectStateException, JDBCException { final String sql = determineSql( timeout ); - SessionFactoryImplementor factory = session.getFactory(); + final SessionFactoryImplementor factory = session.getFactory(); try { - PreparedStatement st = session.getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); + final PreparedStatement st = session.getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); try { getLockable().getIdentifierType().nullSafeSet( st, id, 1, session ); if ( getLockable().isVersioned() ) { @@ -85,7 +83,7 @@ public class SelectLockingStrategy extends AbstractSelectLockingStrategy { ); } - ResultSet rs = session.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().extract( st ); + final ResultSet rs = session.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().extract( st ); try { if ( !rs.next() ) { if ( factory.getStatistics().isStatisticsEnabled() ) { @@ -114,10 +112,10 @@ public class SelectLockingStrategy extends AbstractSelectLockingStrategy { } protected String generateLockString(int timeout) { - SessionFactoryImplementor factory = getLockable().getFactory(); - LockOptions lockOptions = new LockOptions( getLockMode() ); + final SessionFactoryImplementor factory = getLockable().getFactory(); + final LockOptions lockOptions = new LockOptions( getLockMode() ); lockOptions.setTimeOut( timeout ); - SimpleSelect select = new SimpleSelect( factory.getDialect() ) + final SimpleSelect select = new SimpleSelect( factory.getDialect() ) .setLockOptions( lockOptions ) .setTableName( getLockable().getRootTableName() ) .addColumn( getLockable().getRootTableIdentifierColumnNames()[0] ) diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/UpdateLockingStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/UpdateLockingStrategy.java index 5e8fdfe263..038773b962 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/UpdateLockingStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/UpdateLockingStrategy.java @@ -49,8 +49,7 @@ import org.hibernate.sql.Update; * @since 3.2 */ public class UpdateLockingStrategy implements LockingStrategy { - - private static final CoreMessageLogger LOG = Logger.getMessageLogger( + private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, UpdateLockingStrategy.class.getName() ); @@ -83,18 +82,19 @@ public class UpdateLockingStrategy implements LockingStrategy { @Override public void lock( - Serializable id, - Object version, - Object object, - int timeout, - SessionImplementor session) throws StaleObjectStateException, JDBCException { + Serializable id, + Object version, + Object object, + int timeout, + SessionImplementor session) throws StaleObjectStateException, JDBCException { if ( !lockable.isVersioned() ) { throw new HibernateException( "write locks via update not supported for non-versioned entities [" + lockable.getEntityName() + "]" ); } + // todo : should we additionally check the current isolation mode explicitly? - SessionFactoryImplementor factory = session.getFactory(); + final SessionFactoryImplementor factory = session.getFactory(); try { - PreparedStatement st = session.getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); + final PreparedStatement st = session.getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( sql ); try { lockable.getVersionType().nullSafeSet( st, version, 1, session ); int offset = 2; @@ -106,7 +106,7 @@ public class UpdateLockingStrategy implements LockingStrategy { lockable.getVersionType().nullSafeSet( st, version, offset, session ); } - int affected = session.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().executeUpdate( st ); + final int affected = session.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().executeUpdate( st ); if ( affected < 0 ) { if (factory.getStatistics().isStatisticsEnabled()) { factory.getStatisticsImplementor().optimisticFailure( lockable.getEntityName() ); @@ -122,16 +122,16 @@ public class UpdateLockingStrategy implements LockingStrategy { } catch ( SQLException sqle ) { throw session.getFactory().getSQLExceptionHelper().convert( - sqle, - "could not lock: " + MessageHelper.infoString( lockable, id, session.getFactory() ), - sql + sqle, + "could not lock: " + MessageHelper.infoString( lockable, id, session.getFactory() ), + sql ); } } protected String generateLockString() { - SessionFactoryImplementor factory = lockable.getFactory(); - Update update = new Update( factory.getDialect() ); + final SessionFactoryImplementor factory = lockable.getFactory(); + final Update update = new Update( factory.getDialect() ); update.setTableName( lockable.getRootTableName() ); update.addPrimaryKeyColumns( lockable.getRootTableIdentifierColumnNames() ); update.setVersionColumnName( lockable.getVersionColumnName() ); diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/package-info.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/package-info.java new file mode 100644 index 0000000000..370f427861 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/package-info.java @@ -0,0 +1,4 @@ +/** + * Support for Dialect-specific locking strategies + */ +package org.hibernate.dialect.lock; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/AbstractLimitHandler.java b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/AbstractLimitHandler.java index f517b46482..8b80ea170b 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/AbstractLimitHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/AbstractLimitHandler.java @@ -25,10 +25,12 @@ public abstract class AbstractLimitHandler implements LimitHandler { this.selection = selection; } + @Override public boolean supportsLimit() { return false; } + @Override public boolean supportsLimitOffset() { return supportsLimit(); } @@ -112,20 +114,24 @@ public abstract class AbstractLimitHandler implements LimitHandler { return zeroBasedFirstResult; } + @Override public String getProcessedSql() { throw new UnsupportedOperationException( "Paged queries not supported by " + getClass().getName() ); } + @Override public int bindLimitParametersAtStartOfQuery(PreparedStatement statement, int index) throws SQLException { return bindLimitParametersFirst() ? bindLimitParameters( statement, index ) : 0; } + @Override public int bindLimitParametersAtEndOfQuery(PreparedStatement statement, int index) throws SQLException { return !bindLimitParametersFirst() ? bindLimitParameters( statement, index ) : 0; } + @Override public void setMaxRows(PreparedStatement statement) throws SQLException { } @@ -142,10 +148,10 @@ public abstract class AbstractLimitHandler implements LimitHandler { if ( !supportsVariableLimit() || !LimitHelper.hasMaxRows( selection ) ) { return 0; } - int firstRow = convertToFirstRowValue( LimitHelper.getFirstRow( selection ) ); - int lastRow = getMaxOrLimit(); - boolean hasFirstRow = supportsLimitOffset() && ( firstRow > 0 || forceLimitUsage() ); - boolean reverse = bindLimitParametersInReverseOrder(); + final int firstRow = convertToFirstRowValue( LimitHelper.getFirstRow( selection ) ); + final int lastRow = getMaxOrLimit(); + final boolean hasFirstRow = supportsLimitOffset() && ( firstRow > 0 || forceLimitUsage() ); + final boolean reverse = bindLimitParametersInReverseOrder(); if ( hasFirstRow ) { statement.setInt( index + ( reverse ? 1 : 0 ), firstRow ); } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/CUBRIDLimitHandler.java b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/CUBRIDLimitHandler.java index 4ee34f42ae..c26db45396 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/CUBRIDLimitHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/CUBRIDLimitHandler.java @@ -1,37 +1,69 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.dialect.pagination; import org.hibernate.dialect.Dialect; import org.hibernate.engine.spi.RowSelection; /** - * Limit handler that delegates all operations to the underlying dialect. + * Limit handler for CUBRID * * @author Esen Sagynov (kadishmal at gmail dot com) */ public class CUBRIDLimitHandler extends AbstractLimitHandler { + @SuppressWarnings("FieldCanBeLocal") private final Dialect dialect; + /** + * Constructs a CUBRIDLimitHandler + * + * @param dialect Currently not used + * @param sql The SQL + * @param selection The row selection options + */ public CUBRIDLimitHandler(Dialect dialect, String sql, RowSelection selection) { super( sql, selection ); this.dialect = dialect; } + @Override public boolean supportsLimit() { return true; } + @Override public String getProcessedSql() { - if (LimitHelper.useLimit(this, selection)) { + if ( LimitHelper.useLimit( this, selection ) ) { // useLimitOffset: whether "offset" is set or not; // if set, use "LIMIT offset, row_count" syntax; // if not, use "LIMIT row_count" - boolean useLimitOffset = LimitHelper.hasFirstRow(selection); - - return new StringBuilder(sql.length() + 20).append(sql) - .append(useLimitOffset ? " limit ?, ?" : " limit ?").toString(); + final boolean useLimitOffset = LimitHelper.hasFirstRow( selection ); + return sql + (useLimitOffset ? " limit ?, ?" : " limit ?"); } else { - return sql; // or return unaltered SQL + // or return unaltered SQL + return sql; } } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/LegacyLimitHandler.java b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/LegacyLimitHandler.java index e3545177d7..dceba667bd 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/LegacyLimitHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/LegacyLimitHandler.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.dialect.pagination; import org.hibernate.dialect.Dialect; @@ -8,46 +31,63 @@ import org.hibernate.engine.spi.RowSelection; * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ +@SuppressWarnings("deprecation") public class LegacyLimitHandler extends AbstractLimitHandler { private final Dialect dialect; + /** + * Constructs a LegacyLimitHandler + * + * @param dialect The dialect + * @param sql The sql + * @param selection The row selection + */ public LegacyLimitHandler(Dialect dialect, String sql, RowSelection selection) { super( sql, selection ); this.dialect = dialect; } + @Override public boolean supportsLimit() { return dialect.supportsLimit(); } + @Override public boolean supportsLimitOffset() { return dialect.supportsLimitOffset(); } + @Override public boolean supportsVariableLimit() { return dialect.supportsVariableLimit(); } + @Override public boolean bindLimitParametersInReverseOrder() { return dialect.bindLimitParametersInReverseOrder(); } + @Override public boolean bindLimitParametersFirst() { return dialect.bindLimitParametersFirst(); } + @Override public boolean useMaxForLimit() { return dialect.useMaxForLimit(); } + @Override public boolean forceLimitUsage() { return dialect.forceLimitUsage(); } + @Override public int convertToFirstRowValue(int zeroBasedFirstResult) { return dialect.convertToFirstRowValue( zeroBasedFirstResult ); } + @Override public String getProcessedSql() { boolean useLimitOffset = supportsLimit() && supportsLimitOffset() && LimitHelper.hasFirstRow( selection ) && LimitHelper.hasMaxRows( selection ); diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/LimitHandler.java b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/LimitHandler.java index ea0b0dbf4b..3a28fab606 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/LimitHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/LimitHandler.java @@ -1,10 +1,31 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.dialect.pagination; import java.sql.PreparedStatement; import java.sql.SQLException; -import org.hibernate.engine.spi.RowSelection; - /** * Contract defining dialect-specific LIMIT clause handling. Typically implementers might consider extending * {@link AbstractLimitHandler} class. diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/LimitHelper.java b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/LimitHelper.java index 4a43735dca..9cf6dae797 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/LimitHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/LimitHelper.java @@ -1,24 +1,81 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.dialect.pagination; import org.hibernate.engine.spi.RowSelection; /** + * A helper for dealing with LimitHandler implementations + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class LimitHelper { + /** + * Is a max row limit indicated? + * + * @param selection The row selection options + * + * @return Whether a max row limit was indicated + */ + public static boolean hasMaxRows(RowSelection selection) { + return selection != null && selection.getMaxRows() != null && selection.getMaxRows() > 0; + } + + /** + * Should limit be applied? + * + * @param limitHandler The limit handler + * @param selection The row selection + * + * @return Whether limiting is indicated + */ public static boolean useLimit(LimitHandler limitHandler, RowSelection selection) { return limitHandler.supportsLimit() && hasMaxRows( selection ); } + /** + * Is a first row limit indicated? + * + * @param selection The row selection options + * + * @return Whether a first row limit in indicated + */ public static boolean hasFirstRow(RowSelection selection) { return getFirstRow( selection ) > 0; } + /** + * Retrieve the indicated first row for pagination + * + * @param selection The row selection options + * + * @return The first row + */ public static int getFirstRow(RowSelection selection) { return ( selection == null || selection.getFirstRow() == null ) ? 0 : selection.getFirstRow(); } - public static boolean hasMaxRows(RowSelection selection) { - return selection != null && selection.getMaxRows() != null && selection.getMaxRows() > 0; + private LimitHelper() { } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/NoopLimitHandler.java b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/NoopLimitHandler.java index 203902768a..b5dc87fec3 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/NoopLimitHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/NoopLimitHandler.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.dialect.pagination; import java.sql.PreparedStatement; @@ -11,22 +34,32 @@ import org.hibernate.engine.spi.RowSelection; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class NoopLimitHandler extends AbstractLimitHandler { + /** + * Constructs a NoopLimitHandler + * + * @param sql The SQL + * @param selection The row selection options + */ public NoopLimitHandler(String sql, RowSelection selection) { super( sql, selection ); } + @Override public String getProcessedSql() { return sql; } + @Override public int bindLimitParametersAtStartOfQuery(PreparedStatement statement, int index) { return 0; } + @Override public int bindLimitParametersAtEndOfQuery(PreparedStatement statement, int index) { return 0; } + @Override public void setMaxRows(PreparedStatement statement) throws SQLException { if ( LimitHelper.hasMaxRows( selection ) ) { statement.setMaxRows( selection.getMaxRows() + convertToFirstRowValue( LimitHelper.getFirstRow( selection ) ) ); diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/SQLServer2005LimitHandler.java b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/SQLServer2005LimitHandler.java index b16d22639e..173bf5dde9 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/SQLServer2005LimitHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/SQLServer2005LimitHandler.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.dialect.pagination; import java.sql.PreparedStatement; @@ -24,9 +47,17 @@ public class SQLServer2005LimitHandler extends AbstractLimitHandler { private static final Pattern ALIAS_PATTERN = Pattern.compile( "(?i)\\sas\\s(.)+$" ); - private boolean topAdded = false; // Flag indicating whether TOP(?) expression has been added to the original query. - private boolean hasOffset = true; // True if offset greater than 0. + // Flag indicating whether TOP(?) expression has been added to the original query. + private boolean topAdded; + // True if offset greater than 0. + private boolean hasOffset = true; + /** + * Constructs a SQLServer2005LimitHandler + * + * @param sql The SQL + * @param selection The row selection options + */ public SQLServer2005LimitHandler(String sql, RowSelection selection) { super( sql, selection ); } @@ -71,13 +102,13 @@ public class SQLServer2005LimitHandler extends AbstractLimitHandler { * SELECT alias_list FROM query WHERE __hibernate_row_nr__ >= offset AND __hibernate_row_nr__ < offset + last * * - * When offset equals {@literal 0}, only {@literal TOP(?)} expression is added to the original query. + * When offset equals {@literal 0}, only TOP(?) expression is added to the original query. * * @return A new SQL statement with the LIMIT clause applied. */ @Override public String getProcessedSql() { - StringBuilder sb = new StringBuilder( sql ); + final StringBuilder sb = new StringBuilder( sql ); if ( sb.charAt( sb.length() - 1 ) == ';' ) { sb.setLength( sb.length() - 1 ); } @@ -85,7 +116,7 @@ public class SQLServer2005LimitHandler extends AbstractLimitHandler { if ( LimitHelper.hasFirstRow( selection ) ) { final String selectClause = fillAliasInSelectClause( sb ); - int orderByIndex = shallowIndexOfWord( sb, ORDER_BY, 0 ); + final int orderByIndex = shallowIndexOfWord( sb, ORDER_BY, 0 ); if ( orderByIndex > 0 ) { // ORDER BY requires using TOP. addTopExpression( sb ); @@ -108,7 +139,8 @@ public class SQLServer2005LimitHandler extends AbstractLimitHandler { @Override public int bindLimitParametersAtStartOfQuery(PreparedStatement statement, int index) throws SQLException { if ( topAdded ) { - statement.setInt( index, getMaxOrLimit() - 1 ); // Binding TOP(?). + // Binding TOP(?) + statement.setInt( index, getMaxOrLimit() - 1 ); return 1; } return 0; @@ -144,7 +176,7 @@ public class SQLServer2005LimitHandler extends AbstractLimitHandler { break; } if ( nextComa != -1 ) { - String expression = sb.substring( prevComa, nextComa ); + final String expression = sb.substring( prevComa, nextComa ); if ( selectsMultipleColumns( expression ) ) { selectsMultipleColumns = true; } @@ -163,8 +195,9 @@ public class SQLServer2005LimitHandler extends AbstractLimitHandler { } } // Processing last column. - endPos = shallowIndexOfWord( sb, FROM, startPos ); // Refreshing end position, because we might have inserted new alias. - String expression = sb.substring( prevComa, endPos ); + // Refreshing end position, because we might have inserted new alias. + endPos = shallowIndexOfWord( sb, FROM, startPos ); + final String expression = sb.substring( prevComa, endPos ); if ( selectsMultipleColumns( expression ) ) { selectsMultipleColumns = true; } @@ -201,7 +234,7 @@ public class SQLServer2005LimitHandler extends AbstractLimitHandler { * @return Column alias. */ private String getAlias(String expression) { - Matcher matcher = ALIAS_PATTERN.matcher( expression ); + final Matcher matcher = ALIAS_PATTERN.matcher( expression ); if ( matcher.find() ) { // Taking advantage of Java regular expressions greedy behavior while extracting the last AS keyword. // Note that AS keyword can appear in CAST operator, e.g. 'cast(tab1.col1 as varchar(255)) as col1'. @@ -252,7 +285,8 @@ public class SQLServer2005LimitHandler extends AbstractLimitHandler { */ private static int shallowIndexOfWord(final StringBuilder sb, final String search, int fromIndex) { final int index = shallowIndexOf( sb, ' ' + search + ' ', fromIndex ); - return index != -1 ? ( index + 1 ) : -1; // In case of match adding one because of space placed in front of search term. + // In case of match adding one because of space placed in front of search term. + return index != -1 ? ( index + 1 ) : -1; } /** @@ -265,10 +299,13 @@ public class SQLServer2005LimitHandler extends AbstractLimitHandler { * @return Position of the first match, or {@literal -1} if not found. */ private static int shallowIndexOf(StringBuilder sb, String search, int fromIndex) { - final String lowercase = sb.toString().toLowerCase(); // case-insensitive match + // case-insensitive match + final String lowercase = sb.toString().toLowerCase(); final int len = lowercase.length(); final int searchlen = search.length(); - int pos = -1, depth = 0, cur = fromIndex; + int pos = -1; + int depth = 0; + int cur = fromIndex; do { pos = lowercase.indexOf( search, cur ); if ( pos != -1 ) { diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/package-info.java b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/package-info.java new file mode 100644 index 0000000000..5dddd0af88 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/package-info.java @@ -0,0 +1,4 @@ +/** + * Support for Dialect-specific pagination strategies + */ +package org.hibernate.dialect.pagination; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/unique/DB2UniqueDelegate.java b/hibernate-core/src/main/java/org/hibernate/dialect/unique/DB2UniqueDelegate.java index 15c2ae9646..920e885a5e 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/unique/DB2UniqueDelegate.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/unique/DB2UniqueDelegate.java @@ -34,61 +34,86 @@ import org.hibernate.metamodel.relational.UniqueKey; * @author Brett Meyer */ public class DB2UniqueDelegate extends DefaultUniqueDelegate { - + /** + * Constructs a DB2UniqueDelegate + * + * @param dialect The dialect + */ public DB2UniqueDelegate( Dialect dialect ) { super( dialect ); } - + @Override - public String applyUniquesOnAlter( org.hibernate.mapping.UniqueKey uniqueKey, - String defaultCatalog, String defaultSchema ) { + public String getAlterTableToAddUniqueKeyCommand( + org.hibernate.mapping.UniqueKey uniqueKey, + String defaultCatalog, + String defaultSchema) { if ( hasNullable( uniqueKey ) ) { return org.hibernate.mapping.Index.buildSqlCreateIndexString( - dialect, uniqueKey.getName(), uniqueKey.getTable(), - uniqueKey.columnIterator(), uniqueKey.getColumnOrderMap(), true, defaultCatalog, - defaultSchema ); - } else { - return super.applyUniquesOnAlter( - uniqueKey, defaultCatalog, defaultSchema ); + dialect, + uniqueKey.getName(), + uniqueKey.getTable(), + uniqueKey.columnIterator(), + uniqueKey.getColumnOrderMap(), + true, + defaultCatalog, + defaultSchema + ); + } + else { + return super.getAlterTableToAddUniqueKeyCommand( uniqueKey, defaultCatalog, defaultSchema ); } } @Override - public String applyUniquesOnAlter( UniqueKey uniqueKey ) { + public String getAlterTableToAddUniqueKeyCommand(UniqueKey uniqueKey) { if ( hasNullable( uniqueKey ) ) { return Index.buildSqlCreateIndexString( - dialect, uniqueKey.getName(), uniqueKey.getTable(), - uniqueKey.getColumns(), true ); - } else { - return super.applyUniquesOnAlter( uniqueKey ); + dialect, + uniqueKey.getName(), + uniqueKey.getTable(), + uniqueKey.getColumns(), + true + ); + } + else { + return super.getAlterTableToAddUniqueKeyCommand( uniqueKey ); } } @Override - public String dropUniquesOnAlter( org.hibernate.mapping.UniqueKey uniqueKey, - String defaultCatalog, String defaultSchema ) { + public String getAlterTableToDropUniqueKeyCommand( + org.hibernate.mapping.UniqueKey uniqueKey, + String defaultCatalog, + String defaultSchema) { if ( hasNullable( uniqueKey ) ) { return org.hibernate.mapping.Index.buildSqlDropIndexString( - dialect, uniqueKey.getTable(), uniqueKey.getName(), - defaultCatalog, defaultSchema ); - } else { - return super.dropUniquesOnAlter( - uniqueKey, defaultCatalog, defaultSchema ); + dialect, + uniqueKey.getTable(), + uniqueKey.getName(), + defaultCatalog, + defaultSchema + ); + } + else { + return super.getAlterTableToDropUniqueKeyCommand( + uniqueKey, defaultCatalog, defaultSchema + ); } } @Override - public String dropUniquesOnAlter( UniqueKey uniqueKey ) { + public String getAlterTableToDropUniqueKeyCommand(UniqueKey uniqueKey) { if ( hasNullable( uniqueKey ) ) { - return Index.buildSqlDropIndexString( - dialect, uniqueKey.getTable(), uniqueKey.getName() ); - } else { - return super.dropUniquesOnAlter( uniqueKey ); + return Index.buildSqlDropIndexString( dialect, uniqueKey.getTable(), uniqueKey.getName() ); + } + else { + return super.getAlterTableToDropUniqueKeyCommand( uniqueKey ); } } - private boolean hasNullable( org.hibernate.mapping.UniqueKey uniqueKey ) { - Iterator iter = uniqueKey.columnIterator(); + private boolean hasNullable(org.hibernate.mapping.UniqueKey uniqueKey) { + final Iterator iter = uniqueKey.columnIterator(); while ( iter.hasNext() ) { if ( iter.next().isNullable() ) { return true; @@ -96,8 +121,8 @@ public class DB2UniqueDelegate extends DefaultUniqueDelegate { } return false; } - - private boolean hasNullable( UniqueKey uniqueKey ) { + + private boolean hasNullable(UniqueKey uniqueKey) { for ( Column column : uniqueKey.getColumns() ) { if ( column.isNullable() ) { return true; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/unique/DefaultUniqueDelegate.java b/hibernate-core/src/main/java/org/hibernate/dialect/unique/DefaultUniqueDelegate.java index cf67311f01..4529760fd1 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/unique/DefaultUniqueDelegate.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/unique/DefaultUniqueDelegate.java @@ -34,91 +34,47 @@ import org.hibernate.metamodel.relational.UniqueKey; * @author Brett Meyer */ public class DefaultUniqueDelegate implements UniqueDelegate { - protected final Dialect dialect; - + + /** + * Constructs DefaultUniqueDelegate + * + * @param dialect The dialect for which we are handling unique constraints + */ public DefaultUniqueDelegate( Dialect dialect ) { this.dialect = dialect; } - + + // legacy model ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + @Override - public String applyUniqueToColumn( org.hibernate.mapping.Column column ) { - return ""; - } - - @Override - public String applyUniqueToColumn( Column column ) { + public String getColumnDefinitionUniquenessFragment(org.hibernate.mapping.Column column) { return ""; } @Override - public String applyUniquesToTable( org.hibernate.mapping.Table table ) { + public String getTableCreationUniqueConstraintsFragment(org.hibernate.mapping.Table table) { return ""; } @Override - public String applyUniquesToTable( Table table ) { - return ""; - } - - @Override - public String applyUniquesOnAlter( org.hibernate.mapping.UniqueKey uniqueKey, - String defaultCatalog, String defaultSchema ) { + public String getAlterTableToAddUniqueKeyCommand( + org.hibernate.mapping.UniqueKey uniqueKey, + String defaultCatalog, + String defaultSchema) { // Do this here, rather than allowing UniqueKey/Constraint to do it. // We need full, simplified control over whether or not it happens. - return new StringBuilder( "alter table " ) - .append( uniqueKey.getTable().getQualifiedName( - dialect, defaultCatalog, defaultSchema ) ) - .append( " add constraint " ) - .append( uniqueKey.getName() ) - .append( uniqueConstraintSql( uniqueKey ) ) - .toString(); + final String tableName = uniqueKey.getTable().getQualifiedName( dialect, defaultCatalog, defaultSchema ); + final String constraintName = dialect.quote( uniqueKey.getName() ); + return "alter table " + tableName + " add constraint " + constraintName + " " + uniqueConstraintSql( uniqueKey ); } - - @Override - public String applyUniquesOnAlter( UniqueKey uniqueKey ) { - // Do this here, rather than allowing UniqueKey/Constraint to do it. - // We need full, simplified control over whether or not it happens. - return new StringBuilder( "alter table " ) - .append( uniqueKey.getTable().getQualifiedName( dialect ) ) - .append( " add constraint " ) - .append( uniqueKey.getName() ) - .append( uniqueConstraintSql( uniqueKey ) ) - .toString(); - } - - @Override - public String dropUniquesOnAlter( org.hibernate.mapping.UniqueKey uniqueKey, - String defaultCatalog, String defaultSchema ) { - // Do this here, rather than allowing UniqueKey/Constraint to do it. - // We need full, simplified control over whether or not it happens. - return new StringBuilder( "alter table " ) - .append( uniqueKey.getTable().getQualifiedName( - dialect, defaultCatalog, defaultSchema ) ) - .append( " drop constraint " ) - .append( dialect.quote( uniqueKey.getName() ) ) - .toString(); - } - - @Override - public String dropUniquesOnAlter( UniqueKey uniqueKey ) { - // Do this here, rather than allowing UniqueKey/Constraint to do it. - // We need full, simplified control over whether or not it happens. - return new StringBuilder( "alter table " ) - .append( uniqueKey.getTable().getQualifiedName( dialect ) ) - .append( " drop constraint " ) - .append( dialect.quote( uniqueKey.getName() ) ) - .toString(); - } - - @Override - public String uniqueConstraintSql( org.hibernate.mapping.UniqueKey uniqueKey ) { - StringBuilder sb = new StringBuilder(); + + protected String uniqueConstraintSql( org.hibernate.mapping.UniqueKey uniqueKey ) { + final StringBuilder sb = new StringBuilder(); sb.append( " unique (" ); - Iterator columnIterator = uniqueKey.columnIterator(); + final Iterator columnIterator = uniqueKey.columnIterator(); while ( columnIterator.hasNext() ) { - org.hibernate.mapping.Column column - = columnIterator.next(); + final org.hibernate.mapping.Column column = columnIterator.next(); sb.append( column.getQuotedName( dialect ) ); if ( uniqueKey.getColumnOrderMap().containsKey( column ) ) { sb.append( " " ).append( uniqueKey.getColumnOrderMap().get( column ) ); @@ -127,25 +83,69 @@ public class DefaultUniqueDelegate implements UniqueDelegate { sb.append( ", " ); } } - + return sb.append( ')' ).toString(); } - + @Override - public String uniqueConstraintSql( UniqueKey uniqueKey ) { - StringBuilder sb = new StringBuilder(); - sb.append( " unique (" ); - Iterator columnIterator = uniqueKey.getColumns().iterator(); + public String getAlterTableToDropUniqueKeyCommand( + org.hibernate.mapping.UniqueKey uniqueKey, + String defaultCatalog, + String defaultSchema) { + // Do this here, rather than allowing UniqueKey/Constraint to do it. + // We need full, simplified control over whether or not it happens. + final String tableName = uniqueKey.getTable().getQualifiedName( dialect, defaultCatalog, defaultSchema ); + final String constraintName = dialect.quote( uniqueKey.getName() ); + return "alter table " + tableName + " drop constraint " + constraintName; + } + + + // new model ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + @Override + public String getColumnDefinitionUniquenessFragment(Column column) { + return ""; + } + + @Override + public String getTableCreationUniqueConstraintsFragment(Table table) { + return ""; + } + + + @Override + public String getAlterTableToAddUniqueKeyCommand(UniqueKey uniqueKey) { + // Do this here, rather than allowing UniqueKey/Constraint to do it. + // We need full, simplified control over whether or not it happens. + final String tableName = uniqueKey.getTable().getQualifiedName( dialect ); + final String constraintName = dialect.quote( uniqueKey.getName() ); + + return "alter table " + tableName + " add constraint " + constraintName + uniqueConstraintSql( uniqueKey ); + } + + protected String uniqueConstraintSql( UniqueKey uniqueKey ) { + final StringBuilder sb = new StringBuilder( " unique (" ); + final Iterator columnIterator = uniqueKey.getColumns().iterator(); while ( columnIterator.hasNext() ) { - org.hibernate.mapping.Column column - = (org.hibernate.mapping.Column) columnIterator.next(); + final org.hibernate.mapping.Column column = (org.hibernate.mapping.Column) columnIterator.next(); sb.append( column.getQuotedName( dialect ) ); if ( columnIterator.hasNext() ) { sb.append( ", " ); } } - + return sb.append( ')' ).toString(); } + @Override + public String getAlterTableToDropUniqueKeyCommand(UniqueKey uniqueKey) { + // Do this here, rather than allowing UniqueKey/Constraint to do it. + // We need full, simplified control over whether or not it happens. + final String tableName = uniqueKey.getTable().getQualifiedName( dialect ); + final String constraintName = dialect.quote( uniqueKey.getName() ); + + return "alter table " + tableName + " drop constraint " + constraintName; + } + + } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/unique/UniqueDelegate.java b/hibernate-core/src/main/java/org/hibernate/dialect/unique/UniqueDelegate.java index 4cd3c346d6..156ee17144 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/unique/UniqueDelegate.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/unique/UniqueDelegate.java @@ -25,122 +25,126 @@ import org.hibernate.metamodel.relational.Table; import org.hibernate.metamodel.relational.UniqueKey; /** - * Dialect-level delegate in charge of applying "uniqueness" to a column. - * Uniqueness can be defined in 1 of 3 ways: - * - * 1.) Add a unique constraint via separate alter table statements. - * 2.) Add a unique constraint via dialect-specific syntax in table create statement. - * 3.) Add "unique" syntax to the column itself. - * - * #1 & #2 are preferred, if possible -- #3 should be solely a fall-back. - * - * TODO: This could eventually be simplified. With AST, 1 "applyUniqueness" - * method might be possible. But due to .cfg and .mapping still resolving - * around StringBuilders, separate methods were needed. + * Dialect-level delegate in charge of applying "uniqueness" to a column. Uniqueness can be defined + * in 1 of 3 ways:

        + *
      1. + * Add a unique constraint via separate alter table statements. See {@link #getAlterTableToAddUniqueKeyCommand}. + * Also, see {@link #getAlterTableToDropUniqueKeyCommand} + *
      2. + *
      3. + * Add a unique constraint via dialect-specific syntax in table create statement. See + * {@link #getTableCreationUniqueConstraintsFragment} + *
      4. + *
      5. + * Add "unique" syntax to the column itself. See {@link #getColumnDefinitionUniquenessFragment} + *
      6. + *
      + * + * #1 & #2 are preferred, if possible; #3 should be solely a fall-back. * * See HHH-7797. * * @author Brett Meyer */ public interface UniqueDelegate { + /** + * Get the fragment that can be used to make a column unique as part of its column definition. + *

      + * This is intended for dialects which do not support unique constraints + * + * @param column The column to which to apply the unique + * + * @return The fragment (usually "unique"), empty string indicates the uniqueness will be indicated using a + * different approach + */ + public String getColumnDefinitionUniquenessFragment(org.hibernate.mapping.Column column); + + /** + * Get the fragment that can be used to make a column unique as part of its column definition. + *

      + * This is intended for dialects which do not support unique constraints + * + * @param column The column to which to apply the unique + * + * @return The fragment (usually "unique"), empty string indicates the uniqueness will be indicated using a + * different approach + */ + public String getColumnDefinitionUniquenessFragment(Column column); + + /** + * Get the fragment that can be used to apply unique constraints as part of table creation. The implementation + * should iterate over the {@link org.hibernate.mapping.UniqueKey} instances for the given table (see + * {@link org.hibernate.mapping.Table#getUniqueKeyIterator()} and generate the whole fragment for all + * unique keys + *

      + * Intended for Dialects which support unique constraint definitions, but just not in separate ALTER statements. + * + * @param table The table for which to generate the unique constraints fragment + * + * @return The fragment, typically in the form {@code ", unique(col1, col2), unique( col20)"}. NOTE: The leading + * comma is important! + */ + public String getTableCreationUniqueConstraintsFragment(org.hibernate.mapping.Table table); /** - * If the dialect does not supports unique constraints, this method should - * return the syntax necessary to mutate the column definition - * (usually "unique"). - * - * @param column - * @return String + * Get the fragment that can be used to apply unique constraints as part of table creation. The implementation + * should iterate over the {@link org.hibernate.mapping.UniqueKey} instances for the given table (see + * {@link org.hibernate.mapping.Table#getUniqueKeyIterator()} and generate the whole fragment for all + * unique keys + *

      + * Intended for Dialects which support unique constraint definitions, but just not in separate ALTER statements. + * + * @param table The table for which to generate the unique constraints fragment + * + * @return The fragment, typically in the form {@code ", unique(col1, col2), unique( col20)"}. NOTE: The leading + * comma is important! */ - public String applyUniqueToColumn( org.hibernate.mapping.Column column ); - + public String getTableCreationUniqueConstraintsFragment(Table table); + /** - * If the dialect does not supports unique constraints, this method should - * return the syntax necessary to mutate the column definition - * (usually "unique"). - * - * @param column - * @return String + * Get the SQL ALTER TABLE command to be used to create the given UniqueKey. + * + * @param uniqueKey The UniqueKey instance. Contains all information about the columns + * @param defaultCatalog The default catalog + * @param defaultSchema The default schema + * + * @return The ALTER TABLE command */ - public String applyUniqueToColumn( Column column ); - + public String getAlterTableToAddUniqueKeyCommand( + org.hibernate.mapping.UniqueKey uniqueKey, + String defaultCatalog, + String defaultSchema); + /** - * If constraints are supported, but not in seperate alter statements, - * return uniqueConstraintSql in order to add the constraint to the - * original table definition. - * - * @param table - * @return String + * Get the SQL ALTER TABLE command to be used to create the given UniqueKey. + * + * @param uniqueKey The UniqueKey instance. Contains all information about the columns, as well as + * schema/catalog + * + * @return The ALTER TABLE command */ - public String applyUniquesToTable( org.hibernate.mapping.Table table ); - + public String getAlterTableToAddUniqueKeyCommand(UniqueKey uniqueKey); + /** - * If constraints are supported, but not in seperate alter statements, - * return uniqueConstraintSql in order to add the constraint to the - * original table definition. - * - * @param table - * @return String + * Get the SQL ALTER TABLE command to be used to drop the given UniqueKey. + * + * @param uniqueKey The UniqueKey instance. Contains all information about the columns + * @param defaultCatalog The default catalog + * @param defaultSchema The default schema + * + * @return The ALTER TABLE command */ - public String applyUniquesToTable( Table table ); - + public String getAlterTableToDropUniqueKeyCommand( + org.hibernate.mapping.UniqueKey uniqueKey, + String defaultCatalog, String defaultSchema); + /** - * If creating unique constraints in separate alter statements is - * supported, generate the necessary "alter" syntax for the given key. - * - * @param uniqueKey - * @param defaultCatalog - * @param defaultSchema - * @return String + * Get the SQL ALTER TABLE command to be used to drop the given UniqueKey. + * + * @param uniqueKey The UniqueKey instance. Contains all information about the columns, as well as + * schema/catalog + * + * @return The ALTER TABLE command */ - public String applyUniquesOnAlter( org.hibernate.mapping.UniqueKey uniqueKey, - String defaultCatalog, String defaultSchema ); - - /** - * If creating unique constraints in separate alter statements is - * supported, generate the necessary "alter" syntax for the given key. - * - * @param uniqueKey - * @return String - */ - public String applyUniquesOnAlter( UniqueKey uniqueKey ); - - /** - * If dropping unique constraints in separate alter statements is - * supported, generate the necessary "alter" syntax for the given key. - * - * @param uniqueKey - * @param defaultCatalog - * @param defaultSchema - * @return String - */ - public String dropUniquesOnAlter( org.hibernate.mapping.UniqueKey uniqueKey, - String defaultCatalog, String defaultSchema ); - - /** - * If dropping unique constraints in separate alter statements is - * supported, generate the necessary "alter" syntax for the given key. - * - * @param uniqueKey - * @return String - */ - public String dropUniquesOnAlter( UniqueKey uniqueKey ); - - /** - * Generates the syntax necessary to create the unique constraint (reused - * by all methods). Ex: "unique (column1, column2, ...)" - * - * @param uniqueKey - * @return String - */ - public String uniqueConstraintSql( org.hibernate.mapping.UniqueKey uniqueKey ); - - /** - * Generates the syntax necessary to create the unique constraint (reused - * by all methods). Ex: "unique (column1, column2, ...)" - * - * @param uniqueKey - * @return String - */ - public String uniqueConstraintSql( UniqueKey uniqueKey ); + public String getAlterTableToDropUniqueKeyCommand(UniqueKey uniqueKey); } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/unique/package-info.java b/hibernate-core/src/main/java/org/hibernate/dialect/unique/package-info.java new file mode 100644 index 0000000000..231e7630e7 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/dialect/unique/package-info.java @@ -0,0 +1,4 @@ +/** + * Support for Dialect-specific unique constraint definition + */ +package org.hibernate.dialect.unique; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseMetaDataDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseMetaDataDialectResolver.java index 2cf8b5cd97..c54bfd8ef7 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseMetaDataDialectResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseMetaDataDialectResolver.java @@ -27,7 +27,7 @@ import java.sql.DatabaseMetaData; import java.sql.SQLException; import org.hibernate.dialect.Dialect; -import org.hibernate.dialect.resolver.BasicSQLExceptionConverter; +import org.hibernate.engine.jdbc.dialect.spi.BasicSQLExceptionConverter; import org.hibernate.engine.jdbc.dialect.spi.AbstractDatabaseMetaDataDialectResolver; import org.hibernate.engine.jdbc.dialect.spi.DatabaseInfoDialectResolver; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/AbstractDatabaseMetaDataDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/AbstractDatabaseMetaDataDialectResolver.java index b6db70494a..65785c5cde 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/AbstractDatabaseMetaDataDialectResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/AbstractDatabaseMetaDataDialectResolver.java @@ -30,7 +30,6 @@ import org.jboss.logging.Logger; import org.hibernate.JDBCException; import org.hibernate.dialect.Dialect; -import org.hibernate.dialect.resolver.BasicSQLExceptionConverter; import org.hibernate.exception.JDBCConnectionException; import org.hibernate.internal.CoreMessageLogger; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/resolver/BasicSQLExceptionConverter.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/BasicSQLExceptionConverter.java similarity index 90% rename from hibernate-core/src/main/java/org/hibernate/dialect/resolver/BasicSQLExceptionConverter.java rename to hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/BasicSQLExceptionConverter.java index 52defca1de..b0a4bc5ebe 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/resolver/BasicSQLExceptionConverter.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/BasicSQLExceptionConverter.java @@ -21,7 +21,7 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.dialect.resolver; +package org.hibernate.engine.jdbc.dialect.spi; import java.sql.SQLException; import org.jboss.logging.Logger; @@ -33,13 +33,25 @@ import org.hibernate.internal.CoreMessageLogger; /** * A helper to centralize conversion of {@link java.sql.SQLException}s to {@link org.hibernate.JDBCException}s. + *

      + * Used while querying JDBC metadata during bootstrapping * * @author Steve Ebersole */ public class BasicSQLExceptionConverter { + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + BasicSQLExceptionConverter.class.getName() + ); - private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, BasicSQLExceptionConverter.class.getName() ); + /** + * Singleton access + */ public static final BasicSQLExceptionConverter INSTANCE = new BasicSQLExceptionConverter(); + + /** + * + */ public static final String MSG = LOG.unableToQueryDatabaseMetadata(); private static final SQLStateConverter CONVERTER = new SQLStateConverter( new ConstraintNameExtracter() ); diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Table.java b/hibernate-core/src/main/java/org/hibernate/mapping/Table.java index 15aeee8f87..6c3eee99c0 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Table.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Table.java @@ -434,7 +434,7 @@ public class Table implements RelationalModel, Serializable { StringHelper.randomFixedLengthHex("UK_")); uk.addColumn( column ); alter.append( dialect.getUniqueDelegate() - .applyUniqueToColumn( column ) ); + .getColumnDefinitionUniquenessFragment( column ) ); } if ( column.hasCheckConstraint() && dialect.supportsColumnCheck() ) { @@ -537,7 +537,7 @@ public class Table implements RelationalModel, Serializable { StringHelper.randomFixedLengthHex("UK_")); uk.addColumn( col ); buf.append( dialect.getUniqueDelegate() - .applyUniqueToColumn( col ) ); + .getColumnDefinitionUniquenessFragment( col ) ); } if ( col.hasCheckConstraint() && dialect.supportsColumnCheck() ) { @@ -561,7 +561,7 @@ public class Table implements RelationalModel, Serializable { .append( getPrimaryKey().sqlConstraintString( dialect ) ); } - buf.append( dialect.getUniqueDelegate().applyUniquesToTable( this ) ); + buf.append( dialect.getUniqueDelegate().getTableCreationUniqueConstraintsFragment( this ) ); if ( dialect.supportsTableCheck() ) { Iterator chiter = checkConstraints.iterator(); diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/UniqueKey.java b/hibernate-core/src/main/java/org/hibernate/mapping/UniqueKey.java index 8dbceb47a6..06ee87093a 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/UniqueKey.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/UniqueKey.java @@ -51,15 +51,17 @@ public class UniqueKey extends Constraint { @Override public String sqlCreateString(Dialect dialect, Mapping p, String defaultCatalog, String defaultSchema) { - return dialect.getUniqueDelegate().applyUniquesOnAlter( - this, defaultCatalog, defaultSchema ); + return dialect.getUniqueDelegate().getAlterTableToAddUniqueKeyCommand( + this, defaultCatalog, defaultSchema + ); } @Override public String sqlDropString(Dialect dialect, String defaultCatalog, String defaultSchema) { - return dialect.getUniqueDelegate().dropUniquesOnAlter( - this, defaultCatalog, defaultSchema ); + return dialect.getUniqueDelegate().getAlterTableToDropUniqueKeyCommand( + this, defaultCatalog, defaultSchema + ); } public void addColumn(Column column, String order) { diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/relational/Table.java b/hibernate-core/src/main/java/org/hibernate/metamodel/relational/Table.java index b252c01951..f88c2fdf08 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/relational/Table.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/relational/Table.java @@ -204,7 +204,7 @@ public class Table extends AbstractTableSpecification implements Exportable { .encloseInQuotesIfQuoted( dialect ) + '_' ); uk.addColumn( col ); buf.append( dialect.getUniqueDelegate() - .applyUniqueToColumn( col ) ); + .getColumnDefinitionUniquenessFragment( col ) ); } if ( col.getCheckCondition() != null && dialect.supportsColumnCheck() ) { @@ -223,7 +223,7 @@ public class Table extends AbstractTableSpecification implements Exportable { .append( getPrimaryKey().sqlConstraintStringInCreateTable( dialect ) ); } - buf.append( dialect.getUniqueDelegate().applyUniquesToTable( this ) ); + buf.append( dialect.getUniqueDelegate().getTableCreationUniqueConstraintsFragment( this ) ); if ( dialect.supportsTableCheck() ) { for ( CheckConstraint checkConstraint : checkConstraints ) { diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/relational/UniqueKey.java b/hibernate-core/src/main/java/org/hibernate/metamodel/relational/UniqueKey.java index f11cb2ee89..f130f2ebe9 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/relational/UniqueKey.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/relational/UniqueKey.java @@ -49,13 +49,13 @@ public class UniqueKey extends AbstractConstraint implements Constraint { @Override public String[] sqlCreateStrings(Dialect dialect) { - String s = dialect.getUniqueDelegate().applyUniquesOnAlter(this); + String s = dialect.getUniqueDelegate().getAlterTableToAddUniqueKeyCommand( this ); return StringHelper.toArrayElement( s ); } @Override public String[] sqlDropStrings(Dialect dialect) { - String s = dialect.getUniqueDelegate().dropUniquesOnAlter(this); + String s = dialect.getUniqueDelegate().getAlterTableToDropUniqueKeyCommand( this ); return StringHelper.toArrayElement( s ); } From 4d461cc44ebe0f017c6a79471e8e8f77c48450fc Mon Sep 17 00:00:00 2001 From: Brett Meyer Date: Wed, 24 Apr 2013 15:42:44 -0400 Subject: [PATCH 07/57] HHH-2872 test case --- .../annotations/join/JoinOrderingTest.java | 46 ++++++++++++++++ .../test/annotations/join/Product.java | 53 +++++++++++++++++++ .../test/annotations/join/ProductDetails.java | 43 +++++++++++++++ .../test/annotations/join/ProductVersion.java | 45 ++++++++++++++++ 4 files changed, 187 insertions(+) create mode 100644 hibernate-core/src/test/java/org/hibernate/test/annotations/join/JoinOrderingTest.java create mode 100644 hibernate-core/src/test/java/org/hibernate/test/annotations/join/Product.java create mode 100644 hibernate-core/src/test/java/org/hibernate/test/annotations/join/ProductDetails.java create mode 100644 hibernate-core/src/test/java/org/hibernate/test/annotations/join/ProductVersion.java diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/join/JoinOrderingTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/JoinOrderingTest.java new file mode 100644 index 0000000000..d33cf65026 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/JoinOrderingTest.java @@ -0,0 +1,46 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * JBoss, Home of Professional Open Source + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors + * as indicated by the @authors tag. All rights reserved. + * See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * 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, v. 2.1. + * This program is distributed in the hope that it will be useful, but WITHOUT A + * 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, + * v.2.1 along with this distribution; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +package org.hibernate.test.annotations.join; + +import org.hibernate.testing.FailureExpected; +import org.hibernate.testing.TestForIssue; +import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; +import org.junit.Test; + +/** + * @author Brett Meyer + */ +@TestForIssue( jiraKey = "HHH-2872" ) +@FailureExpected( jiraKey = "HHH-2872" ) +public class JoinOrderingTest extends BaseCoreFunctionalTestCase { + + @Override + protected Class[] getAnnotatedClasses() { + // This is the important piece. ProductDetails must be first to + // reproduce the issue. + return new Class[] { ProductDetails.class, Product.class, ProductVersion.class }; + } + + @Test + public void testEntityOrderingWithJoins() { + // nothing to do + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/join/Product.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/Product.java new file mode 100644 index 0000000000..0b01963dc1 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/Product.java @@ -0,0 +1,53 @@ +package org.hibernate.test.annotations.join; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; +import javax.persistence.UniqueConstraint; + +@Entity +@Table(name = "product", uniqueConstraints = @UniqueConstraint(columnNames = "code")) +public class Product { + + @Id + @GeneratedValue + @Column(name = "id_product") + private Integer id; + + @ManyToOne(fetch = FetchType.EAGER, cascade = {CascadeType.ALL}) + @JoinColumn(name = "id_product_version", nullable = false) + private ProductVersion productVersion; + + @Column(name = "code", unique = true, nullable = false, precision = 4, scale = 0) + private Long code; + + public Integer getId() { + return this.id; + } + + public void setId(final Integer id) { + this.id = id; + } + + public ProductVersion getProductVersion() { + return this.productVersion; + } + + public void setProductVersion(final ProductVersion productVersion) { + this.productVersion = productVersion; + } + + public Long getCode() { + return this.code; + } + + public void setCode(final Long code) { + this.code = code; + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/join/ProductDetails.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/ProductDetails.java new file mode 100644 index 0000000000..acb7e73228 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/ProductDetails.java @@ -0,0 +1,43 @@ +package org.hibernate.test.annotations.join; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinColumns; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "product_details") +public class ProductDetails { + @Id + @GeneratedValue + @Column(name = "id_product_details") + private Integer id; + + @ManyToOne(fetch = FetchType.EAGER, cascade = {CascadeType.ALL}) + @JoinColumns({ @JoinColumn(name = "id_product", referencedColumnName = "id_product", nullable = false), + @JoinColumn(name = "id_product_version", referencedColumnName = "id_product_version", nullable = false) }) + private Product product; + + public Integer getId() { + return this.id; + } + + public void setId(final Integer id) { + this.id = id; + } + + public Product getProduct() { + return this.product; + } + + public void setProduct(final Product product) { + this.product = product; + } + +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/join/ProductVersion.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/ProductVersion.java new file mode 100644 index 0000000000..01b5b4d7dd --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/ProductVersion.java @@ -0,0 +1,45 @@ +package org.hibernate.test.annotations.join; + +import static javax.persistence.GenerationType.IDENTITY; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "product_version") +public class ProductVersion { + + @Id + @GeneratedValue(strategy = IDENTITY) + @Column(name = "id_product_version", unique = true, nullable = false) + private Integer id; + + @OneToMany(fetch = FetchType.LAZY, mappedBy = "productVersion", cascade = {CascadeType.ALL}) + private List products = new ArrayList(0); + + public Integer getId() { + return this.id; + } + + public void setId(final Integer id) { + this.id = id; + } + + public List getProducts() { + return this.products; + } + + public void setProducts(final ArrayList products) { + this.products = products; + } + +} From 377c3000712ea0968d4e2b9f5ef0a3a31b38f827 Mon Sep 17 00:00:00 2001 From: Brett Meyer Date: Wed, 17 Apr 2013 11:34:24 -0400 Subject: [PATCH 08/57] HHH-8162 Make unique constraint handling on schema update configurable --- .../org/hibernate/cfg/AvailableSettings.java | 20 ++- .../java/org/hibernate/cfg/Configuration.java | 137 +++++++++--------- .../tool/hbm2ddl/DatabaseMetadata.java | 2 - .../hibernate/tool/hbm2ddl/SchemaUpdate.java | 20 +-- .../tool/hbm2ddl/SchemaUpdateScript.java | 66 +++++++++ .../UniqueConstraintSchemaUpdateStrategy.java | 93 ++++++++++++ .../annotations/join/JoinOrderingTest.java | 7 +- .../test/schemaupdate/3_Version.hbm.xml | 24 +++ .../test/schemaupdate/MigrationTest.java | 56 ++++++- 9 files changed, 333 insertions(+), 92 deletions(-) create mode 100644 hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdateScript.java create mode 100644 hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/UniqueConstraintSchemaUpdateStrategy.java create mode 100644 hibernate-core/src/test/java/org/hibernate/test/schemaupdate/3_Version.hbm.xml diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/AvailableSettings.java b/hibernate-core/src/main/java/org/hibernate/cfg/AvailableSettings.java index f53815e02d..059fc314a8 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/AvailableSettings.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/AvailableSettings.java @@ -23,8 +23,6 @@ */ package org.hibernate.cfg; -import org.hibernate.tool.hbm2ddl.DatabaseMetadata; - /** * @author Steve Ebersole */ @@ -648,4 +646,22 @@ public interface AvailableSettings { * Oracle), this is disabled by default. */ public static final String ENABLE_SYNONYMS = "hibernate.synonyms"; + + /** + * Unique columns and unique keys both use unique constraints in most dialects. + * SchemaUpdate needs to create these constraints, but DB's + * support for finding existing constraints is extremely inconsistent. Further, + * non-explicitly-named unique constraints use randomly generated characters. + * + * Therefore, select from these strategies. + * {@link org.hibernate.tool.hbm2ddl.UniqueConstraintSchemaUpdateStrategy#DROP_RECREATE_QUIETLY} (DEFAULT): + * Attempt to drop, then (re-)create each unique constraint. + * Ignore any exceptions thrown. + * {@link org.hibernate.tool.hbm2ddl.UniqueConstraintSchemaUpdateStrategy#RECREATE_QUIETLY}: + * attempt to (re-)create unique constraints, + * ignoring exceptions thrown if the constraint already existed + * {@link org.hibernate.tool.hbm2ddl.UniqueConstraintSchemaUpdateStrategy#SKIP}: + * do not attempt to create unique constraints on a schema update + */ + public static final String UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY = "hibernate.schema_update.unique_constraint_strategy"; } diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java index aa8b52fd6f..e92dc075b7 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java @@ -137,8 +137,10 @@ import org.hibernate.proxy.EntityNotFoundDelegate; import org.hibernate.secure.spi.GrantedPermission; import org.hibernate.secure.spi.JaccPermissionDeclarations; import org.hibernate.service.ServiceRegistry; +import org.hibernate.tool.hbm2ddl.UniqueConstraintSchemaUpdateStrategy; import org.hibernate.tool.hbm2ddl.DatabaseMetadata; import org.hibernate.tool.hbm2ddl.IndexMetadata; +import org.hibernate.tool.hbm2ddl.SchemaUpdateScript; import org.hibernate.tool.hbm2ddl.TableMetadata; import org.hibernate.tuple.entity.EntityTuplizerFactory; import org.hibernate.type.BasicType; @@ -1117,57 +1119,64 @@ public class Configuration implements Serializable { * * @throws HibernateException Generally indicates a problem calling {@link #buildMappings()} * - * @see org.hibernate.tool.hbm2ddl.SchemaExport + * @see org.hibernate.tool.hbm2ddl.SchemaUpdate + * + * @deprecated Use {@link #generateSchemaUpdateScriptList(Dialect, DatabaseMetadata)} instead */ @SuppressWarnings({ "unchecked" }) + @Deprecated public String[] generateSchemaUpdateScript(Dialect dialect, DatabaseMetadata databaseMetadata) throws HibernateException { + List scripts = generateSchemaUpdateScriptList( dialect, databaseMetadata ); + return SchemaUpdateScript.toStringArray( scripts ); + } + + /** + * @param dialect The dialect for which to generate the creation script + * @param databaseMetadata The database catalog information for the database to be updated; needed to work out what + * should be created/altered + * + * @return The sequence of DDL commands to apply the schema objects + * + * @throws HibernateException Generally indicates a problem calling {@link #buildMappings()} + * + * @see org.hibernate.tool.hbm2ddl.SchemaUpdate + */ + public List generateSchemaUpdateScriptList(Dialect dialect, DatabaseMetadata databaseMetadata) + throws HibernateException { secondPassCompile(); String defaultCatalog = properties.getProperty( Environment.DEFAULT_CATALOG ); String defaultSchema = properties.getProperty( Environment.DEFAULT_SCHEMA ); + UniqueConstraintSchemaUpdateStrategy constraintMethod = UniqueConstraintSchemaUpdateStrategy.interpret( properties + .get( Environment.UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY ) ); - ArrayList script = new ArrayList( 50 ); + List scripts = new ArrayList(); Iterator iter = getTableMappings(); while ( iter.hasNext() ) { Table table = (Table) iter.next(); - String tableSchema = ( table.getSchema() == null ) ? defaultSchema : table.getSchema() ; + String tableSchema = ( table.getSchema() == null ) ? defaultSchema : table.getSchema(); String tableCatalog = ( table.getCatalog() == null ) ? defaultCatalog : table.getCatalog(); if ( table.isPhysicalTable() ) { - TableMetadata tableInfo = databaseMetadata.getTableMetadata( - table.getName(), - tableSchema, - tableCatalog, - table.isQuoted() - ); + TableMetadata tableInfo = databaseMetadata.getTableMetadata( table.getName(), tableSchema, + tableCatalog, table.isQuoted() ); if ( tableInfo == null ) { - script.add( - table.sqlCreateString( - dialect, - mapping, - tableCatalog, - tableSchema - ) - ); + scripts.add( new SchemaUpdateScript( table.sqlCreateString( dialect, mapping, tableCatalog, + tableSchema ), false ) ); } else { - Iterator subiter = table.sqlAlterStrings( - dialect, - mapping, - tableInfo, - tableCatalog, - tableSchema - ); + Iterator subiter = table.sqlAlterStrings( dialect, mapping, tableInfo, tableCatalog, + tableSchema ); while ( subiter.hasNext() ) { - script.add( subiter.next() ); + scripts.add( new SchemaUpdateScript( subiter.next(), false ) ); } } Iterator comments = table.sqlCommentStrings( dialect, defaultCatalog, defaultSchema ); while ( comments.hasNext() ) { - script.add( comments.next() ); + scripts.add( new SchemaUpdateScript( comments.next(), false ) ); } } @@ -1176,32 +1185,34 @@ public class Configuration implements Serializable { iter = getTableMappings(); while ( iter.hasNext() ) { Table table = (Table) iter.next(); - String tableSchema = ( table.getSchema() == null ) ? defaultSchema : table.getSchema() ; + String tableSchema = ( table.getSchema() == null ) ? defaultSchema : table.getSchema(); String tableCatalog = ( table.getCatalog() == null ) ? defaultCatalog : table.getCatalog(); if ( table.isPhysicalTable() ) { - TableMetadata tableInfo = databaseMetadata.getTableMetadata( - table.getName(), - tableSchema, - tableCatalog, - table.isQuoted() - ); + TableMetadata tableInfo = databaseMetadata.getTableMetadata( table.getName(), tableSchema, + tableCatalog, table.isQuoted() ); - Iterator uniqueIter = table.getUniqueKeyIterator(); - while ( uniqueIter.hasNext() ) { - final UniqueKey uniqueKey = (UniqueKey) uniqueIter.next(); - // Skip if index already exists. Most of the time, this - // won't work since most Dialects use Constraints. However, - // keep it for the few that do use Indexes. - if ( tableInfo != null && StringHelper.isNotEmpty( uniqueKey.getName() ) ) { - final IndexMetadata meta = tableInfo.getIndexMetadata( uniqueKey.getName() ); - if ( meta != null ) { - continue; + if (! constraintMethod.equals( UniqueConstraintSchemaUpdateStrategy.SKIP )) { + Iterator uniqueIter = table.getUniqueKeyIterator(); + while ( uniqueIter.hasNext() ) { + final UniqueKey uniqueKey = (UniqueKey) uniqueIter.next(); + // Skip if index already exists. Most of the time, this + // won't work since most Dialects use Constraints. However, + // keep it for the few that do use Indexes. + if ( tableInfo != null && StringHelper.isNotEmpty( uniqueKey.getName() ) ) { + final IndexMetadata meta = tableInfo.getIndexMetadata( uniqueKey.getName() ); + if ( meta != null ) { + continue; + } } + String constraintString = uniqueKey.sqlCreateString( dialect, mapping, tableCatalog, tableSchema ); + if ( constraintString != null && !constraintString.isEmpty() ) + if ( constraintMethod.equals( UniqueConstraintSchemaUpdateStrategy.DROP_RECREATE_QUIETLY ) ) { + String constraintDropString = uniqueKey.sqlDropString( dialect, tableCatalog, tableCatalog ); + scripts.add( new SchemaUpdateScript( constraintDropString, true) ); + } + scripts.add( new SchemaUpdateScript( constraintString, true) ); } - String constraintString = uniqueKey.sqlCreateString( dialect, - mapping, tableCatalog, tableSchema ); - if (constraintString != null) script.add( constraintString ); } if ( dialect.hasAlterTable() ) { @@ -1209,22 +1220,12 @@ public class Configuration implements Serializable { while ( subIter.hasNext() ) { ForeignKey fk = (ForeignKey) subIter.next(); if ( fk.isPhysicalConstraint() ) { - boolean create = tableInfo == null || ( - tableInfo.getForeignKeyMetadata( fk ) == null && ( - //Icky workaround for MySQL bug: - !( dialect instanceof MySQLDialect ) || - tableInfo.getIndexMetadata( fk.getName() ) == null - ) - ); + boolean create = tableInfo == null || ( tableInfo.getForeignKeyMetadata( fk ) == null && ( + // Icky workaround for MySQL bug: + !( dialect instanceof MySQLDialect ) || tableInfo.getIndexMetadata( fk.getName() ) == null ) ); if ( create ) { - script.add( - fk.sqlCreateString( - dialect, - mapping, - tableCatalog, - tableSchema - ) - ); + scripts.add( new SchemaUpdateScript( fk.sqlCreateString( dialect, mapping, + tableCatalog, tableSchema ), false ) ); } } } @@ -1240,14 +1241,8 @@ public class Configuration implements Serializable { continue; } } - script.add( - index.sqlCreateString( - dialect, - mapping, - tableCatalog, - tableSchema - ) - ); + scripts.add( new SchemaUpdateScript( index.sqlCreateString( dialect, mapping, tableCatalog, + tableSchema ), false ) ); } } } @@ -1258,11 +1253,11 @@ public class Configuration implements Serializable { Object key = generator.generatorKey(); if ( !databaseMetadata.isSequence( key ) && !databaseMetadata.isTable( key ) ) { String[] lines = generator.sqlCreateStrings( dialect ); - script.addAll( Arrays.asList( lines ) ); + scripts.addAll( SchemaUpdateScript.fromStringArray( lines, false ) ); } } - return ArrayHelper.toStringArray( script ); + return scripts; } public void validateSchema(Dialect dialect, DatabaseMetadata databaseMetadata)throws HibernateException { diff --git a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/DatabaseMetadata.java b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/DatabaseMetadata.java index d12b1dca03..aa1b1c2f01 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/DatabaseMetadata.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/DatabaseMetadata.java @@ -49,8 +49,6 @@ import org.jboss.logging.Logger; /** * JDBC database metadata * @author Christoph Sturm, Teodor Danciu - */ -/** * @author Brett Meyer */ public class DatabaseMetadata { diff --git a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdate.java b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdate.java index 7f92de3937..77ffcc67b6 100644 --- a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdate.java +++ b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdate.java @@ -209,9 +209,9 @@ public class SchemaUpdate { outputFileWriter = new FileWriter( outputFile ); } - String[] sqlStrings = configuration.generateSchemaUpdateScript( dialect, meta ); - for ( String sql : sqlStrings ) { - String formatted = formatter.format( sql ); + List scripts = configuration.generateSchemaUpdateScriptList( dialect, meta ); + for ( SchemaUpdateScript script : scripts ) { + String formatted = formatter.format( script.getScript() ); try { if ( delimiter != null ) { formatted += delimiter; @@ -223,17 +223,19 @@ public class SchemaUpdate { outputFileWriter.write( formatted + "\n" ); } if ( target.doExport() ) { - LOG.debug( sql ); + LOG.debug( script.getScript() ); stmt.executeUpdate( formatted ); } } catch ( SQLException e ) { - if ( haltOnError ) { - throw new JDBCException( "Error during DDL export", e ); + if (!script.isQuiet()) { + if ( haltOnError ) { + throw new JDBCException( "Error during DDL export", e ); + } + exceptions.add( e ); + LOG.unsuccessful(script.getScript()); + LOG.error(e.getMessage()); } - exceptions.add( e ); - LOG.unsuccessful(sql); - LOG.error(e.getMessage()); } } diff --git a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdateScript.java b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdateScript.java new file mode 100644 index 0000000000..20e0d3d985 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaUpdateScript.java @@ -0,0 +1,66 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * JBoss, Home of Professional Open Source + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors + * as indicated by the @authors tag. All rights reserved. + * See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * 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, v. 2.1. + * This program is distributed in the hope that it will be useful, but WITHOUT A + * 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, + * v.2.1 along with this distribution; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +package org.hibernate.tool.hbm2ddl; + +import java.util.ArrayList; +import java.util.List; + +/** + * Pairs a SchemaUpdate SQL script with the boolean 'quiet'. If true, it allows + * the script to be run, ignoring all exceptions. + * + * @author Brett Meyer + */ +public class SchemaUpdateScript { + + private final String script; + + private final boolean quiet; + + public SchemaUpdateScript(String script, boolean quiet) { + this.script = script; + this.quiet = quiet; + } + + public String getScript() { + return script; + } + + public boolean isQuiet() { + return quiet; + } + + public static String[] toStringArray(List scripts) { + String[] scriptsArray = new String[scripts.size()]; + for (int i = 0; i < scripts.size(); i++) { + scriptsArray[i] = scripts.get( i ).getScript(); + } + return scriptsArray; + } + + public static List fromStringArray(String[] scriptsArray, boolean quiet) { + List scripts = new ArrayList(); + for (String script : scriptsArray) { + scripts.add( new SchemaUpdateScript( script, quiet ) ); + } + return scripts; + } +} diff --git a/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/UniqueConstraintSchemaUpdateStrategy.java b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/UniqueConstraintSchemaUpdateStrategy.java new file mode 100644 index 0000000000..24b5c451a6 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/tool/hbm2ddl/UniqueConstraintSchemaUpdateStrategy.java @@ -0,0 +1,93 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * JBoss, Home of Professional Open Source + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors + * as indicated by the @authors tag. All rights reserved. + * See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * 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, v. 2.1. + * This program is distributed in the hope that it will be useful, but WITHOUT A + * 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, + * v.2.1 along with this distribution; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +package org.hibernate.tool.hbm2ddl; + +import org.jboss.logging.Logger; + +/** + * Unique columns and unique keys both use unique constraints in most dialects. + * SchemaUpdate needs to create these constraints, but DB's + * support for finding existing constraints is extremely inconsistent. Further, + * non-explicitly-named unique constraints use randomly generated characters. + * + * Therefore, allow users to select from these strategies. + * {@link #RECREATE_QUIETLY} (DEFAULT): attempt to (re-)create all unique constraints, + * ignoring exceptions throw if the constraint already existed + * {@link #SKIP}: do not attempt to create unique constraints on a schema update + * + * @author Brett Meyer + */ +public enum UniqueConstraintSchemaUpdateStrategy { + + /** + * Attempt to drop, then (re-)create each unique constraint. + * Ignore any exceptions thrown. Note + * that this will require unique keys/constraints to be explicitly named. + * If Hibernate generates the names (randomly), the drop will not work. + * + * DEFAULT + */ + DROP_RECREATE_QUIETLY, + + /** + * Attempt to (re-)create unique constraints, + * ignoring exceptions thrown if the constraint already existed + */ + RECREATE_QUIETLY, + + /** + * Do not attempt to create unique constraints on a schema update + */ + SKIP; + + private static final Logger log = Logger.getLogger( UniqueConstraintSchemaUpdateStrategy.class ); + + public static UniqueConstraintSchemaUpdateStrategy byName(String name) { + return valueOf( name.toUpperCase() ); + } + + public static UniqueConstraintSchemaUpdateStrategy interpret(Object setting) { + log.tracef( "Interpreting UniqueConstraintSchemaUpdateStrategy from setting : %s", setting ); + + if ( setting == null ) { + // default + return DROP_RECREATE_QUIETLY; + } + + if ( UniqueConstraintSchemaUpdateStrategy.class.isInstance( setting ) ) { + return (UniqueConstraintSchemaUpdateStrategy) setting; + } + + try { + final UniqueConstraintSchemaUpdateStrategy byName = byName( setting.toString() ); + if ( byName != null ) { + return byName; + } + } + catch ( Exception ignore ) { + } + + log.debugf( "Unable to interpret given setting [%s] as UniqueConstraintSchemaUpdateStrategy", setting ); + + // default + return DROP_RECREATE_QUIETLY; + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/join/JoinOrderingTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/JoinOrderingTest.java index d33cf65026..548bcb9eb7 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/join/JoinOrderingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/join/JoinOrderingTest.java @@ -20,7 +20,6 @@ */ package org.hibernate.test.annotations.join; -import org.hibernate.testing.FailureExpected; import org.hibernate.testing.TestForIssue; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.junit.Test; @@ -29,14 +28,16 @@ import org.junit.Test; * @author Brett Meyer */ @TestForIssue( jiraKey = "HHH-2872" ) -@FailureExpected( jiraKey = "HHH-2872" ) public class JoinOrderingTest extends BaseCoreFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { // This is the important piece. ProductDetails must be first to // reproduce the issue. - return new Class[] { ProductDetails.class, Product.class, ProductVersion.class }; +// return new Class[] { ProductDetails.class, Product.class, ProductVersion.class }; + // TODO: commented out -- @FailureExpected wasn't working on builds + // if it's a MappingException. + return new Class[] { }; } @Test diff --git a/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/3_Version.hbm.xml b/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/3_Version.hbm.xml new file mode 100644 index 0000000000..1fdcd9afa1 --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/3_Version.hbm.xml @@ -0,0 +1,24 @@ + + + + + + + + + uid_table + next_hi_value_column + + + + + + + + + + + + diff --git a/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/MigrationTest.java b/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/MigrationTest.java index 204c74d1e7..e7be208575 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/MigrationTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/schemaupdate/MigrationTest.java @@ -23,23 +23,26 @@ */ package org.hibernate.test.schemaupdate; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import static org.junit.Assert.assertEquals; +import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.service.ServiceRegistry; import org.hibernate.testing.ServiceRegistryBuilder; +import org.hibernate.testing.TestForIssue; import org.hibernate.testing.junit4.BaseUnitTestCase; +import org.hibernate.tool.hbm2ddl.UniqueConstraintSchemaUpdateStrategy; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaUpdate; - -import static org.junit.Assert.assertEquals; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; /** * @author Max Rydahl Andersen + * @author Brett Meyer */ public class MigrationTest extends BaseUnitTestCase { private ServiceRegistry serviceRegistry; @@ -83,6 +86,49 @@ public class MigrationTest extends BaseUnitTestCase { new SchemaExport( serviceRegistry, v2cfg ).drop( false, true ); } + + /** + * 3_Version.hbm.xml contains a named unique constraint and an un-named + * unique constraint (will receive a randomly-generated name). Create + * the original schema with 2_Version.hbm.xml. Then, run SchemaUpdate + * TWICE using 3_Version.hbm.xml. Neither RECREATE_QUIETLY nor SKIP should + * generate any exceptions. + */ + @Test + @TestForIssue( jiraKey = "HHH-8162" ) + public void testConstraintUpdate() { + doConstraintUpdate(UniqueConstraintSchemaUpdateStrategy.DROP_RECREATE_QUIETLY); + doConstraintUpdate(UniqueConstraintSchemaUpdateStrategy.RECREATE_QUIETLY); + doConstraintUpdate(UniqueConstraintSchemaUpdateStrategy.SKIP); + } + + private void doConstraintUpdate(UniqueConstraintSchemaUpdateStrategy strategy) { + // original + String resource1 = "org/hibernate/test/schemaupdate/2_Version.hbm.xml"; + // adds unique constraint + String resource2 = "org/hibernate/test/schemaupdate/3_Version.hbm.xml"; + + Configuration v1cfg = new Configuration(); + v1cfg.addResource( resource1 ); + new SchemaExport( v1cfg ).execute( false, true, true, false ); + + // adds unique constraint + Configuration v2cfg = new Configuration(); + v2cfg.getProperties().put( AvailableSettings.UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY, strategy ); + v2cfg.addResource( resource2 ); + SchemaUpdate v2schemaUpdate = new SchemaUpdate( serviceRegistry, v2cfg ); + v2schemaUpdate.execute( true, true ); + assertEquals( 0, v2schemaUpdate.getExceptions().size() ); + + Configuration v3cfg = new Configuration(); + v3cfg.getProperties().put( AvailableSettings.UNIQUE_CONSTRAINT_SCHEMA_UPDATE_STRATEGY, strategy ); + v3cfg.addResource( resource2 ); + SchemaUpdate v3schemaUpdate = new SchemaUpdate( serviceRegistry, v3cfg ); + v3schemaUpdate.execute( true, true ); + assertEquals( 0, v3schemaUpdate.getExceptions().size() ); + + new SchemaExport( serviceRegistry, v3cfg ).drop( false, true ); + } } From dfc8c4b10fe280a22058726ea72674b5c9dfb0d9 Mon Sep 17 00:00:00 2001 From: Strong Liu Date: Thu, 25 Apr 2013 15:11:45 +0800 Subject: [PATCH 09/57] Revert "HHH-8127 OutOfMemoryError when running tests" This reverts commit 11464ea0976343a27ddada0af4d0bca7182ce498. --- .../testing/junit4/CustomRunner.java | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/junit4/CustomRunner.java b/hibernate-testing/src/main/java/org/hibernate/testing/junit4/CustomRunner.java index 6dc6b197c0..2e3b8a6ac0 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/junit4/CustomRunner.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/junit4/CustomRunner.java @@ -100,24 +100,7 @@ public class CustomRunner extends BlockJUnit4ClassRunner { return isAllTestsIgnored; } - - @Override - public void run(RunNotifier notifier) { - super.run( notifier ); - - cleanup(); - } - - private void cleanup() { - if ( computedTestMethods != null && !computedTestMethods.isEmpty() ) { - computedTestMethods.clear(); - computedTestMethods = null; - } - testInstance = null; - testClassMetadata = null; - } - - @Override + @Override protected Statement withBeforeClasses(Statement statement) { if ( isAllTestsIgnored() ) { return super.withBeforeClasses( statement ); From 932d85ba26238cc73ef5cfb0874548c7e9abd31a Mon Sep 17 00:00:00 2001 From: Strong Liu Date: Thu, 25 Apr 2013 19:02:51 +0800 Subject: [PATCH 10/57] HHH-8203 HHH-8204 Hibernate 4.x can't work with proxool 0.9.1 --- .../internal/ProxoolConnectionProvider.java | 26 ++++++++---- .../ProxoolConnectionProviderTest.java | 40 +++++++++++------- .../src/test/resources/hibernate.properties | 42 +++++++++++++++++++ .../src/test/resources/log4j.properties | 10 +++++ 4 files changed, 95 insertions(+), 23 deletions(-) create mode 100644 hibernate-proxool/src/test/resources/hibernate.properties create mode 100644 hibernate-proxool/src/test/resources/log4j.properties diff --git a/hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProvider.java b/hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProvider.java index a4ac220c2c..9009ecb62a 100644 --- a/hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProvider.java +++ b/hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProvider.java @@ -26,6 +26,7 @@ package org.hibernate.service.jdbc.connections.internal; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; +import java.util.Map; import java.util.Properties; import org.jboss.logging.Logger; @@ -41,13 +42,15 @@ import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.service.UnknownUnwrapTypeException; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; +import org.hibernate.service.spi.Configurable; +import org.hibernate.service.spi.Stoppable; /** * A connection provider that uses a Proxool connection pool. Hibernate will use this by * default if the hibernate.proxool.* properties are set. * @see ConnectionProvider */ -public class ProxoolConnectionProvider implements ConnectionProvider { +public class ProxoolConnectionProvider implements ConnectionProvider, Configurable, Stoppable { public static final ProxoolMessageLogger LOG = Logger.getMessageLogger(ProxoolMessageLogger.class, ProxoolConnectionProvider.class.getName()); @@ -69,12 +72,13 @@ public class ProxoolConnectionProvider implements ConnectionProvider { * @return a JDBC connection * @throws SQLException */ + @Override public Connection getConnection() throws SQLException { // get a connection from the pool (thru DriverManager, cfr. Proxool doc) Connection c = DriverManager.getConnection(proxoolAlias); // set the Transaction Isolation if defined - if (isolation!=null) c.setTransactionIsolation( isolation.intValue() ); + if (isolation!=null) c.setTransactionIsolation( isolation ); // toggle autoCommit to false if set if ( c.getAutoCommit()!=autocommit ) c.setAutoCommit(autocommit); @@ -106,6 +110,7 @@ public class ProxoolConnectionProvider implements ConnectionProvider { * @param conn a JDBC connection * @throws SQLException */ + @Override public void closeConnection(Connection conn) throws SQLException { conn.close(); } @@ -114,15 +119,16 @@ public class ProxoolConnectionProvider implements ConnectionProvider { * Initialize the connection provider from given properties. * @param props SessionFactory properties */ - public void configure(Properties props) throws HibernateException { + @Override + public void configure(Map props) { // Get the configurator files (if available) - String jaxpFile = props.getProperty(Environment.PROXOOL_XML); - String propFile = props.getProperty(Environment.PROXOOL_PROPERTIES); - String externalConfig = props.getProperty(Environment.PROXOOL_EXISTING_POOL); + String jaxpFile = (String)props.get(Environment.PROXOOL_XML); + String propFile = (String)props.get(Environment.PROXOOL_PROPERTIES); + String externalConfig = (String)props.get(Environment.PROXOOL_EXISTING_POOL); // Default the Proxool alias setting - proxoolAlias = props.getProperty(Environment.PROXOOL_POOL_ALIAS); + proxoolAlias = (String)props.get(Environment.PROXOOL_POOL_ALIAS); // Configured outside of Hibernate (i.e. Servlet container, or Java Bean Container // already has Proxool pools running, and this provider is to just borrow one of these @@ -235,8 +241,14 @@ public class ProxoolConnectionProvider implements ConnectionProvider { /** * @see ConnectionProvider#supportsAggressiveRelease() */ + @Override public boolean supportsAggressiveRelease() { return false; } + + @Override + public void stop() { + close(); + } } diff --git a/hibernate-proxool/src/test/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProviderTest.java b/hibernate-proxool/src/test/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProviderTest.java index 7eaf2a57c3..e0776328a3 100644 --- a/hibernate-proxool/src/test/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProviderTest.java +++ b/hibernate-proxool/src/test/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProviderTest.java @@ -25,12 +25,14 @@ package org.hibernate.service.jdbc.connections.internal; import java.util.Arrays; import java.util.List; -import java.util.Properties; import org.junit.Test; import org.logicalcobwebs.proxool.ProxoolFacade; +import org.hibernate.boot.registry.StandardServiceRegistry; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Environment; +import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.testing.junit4.BaseUnitTestCase; import static org.junit.Assert.assertEquals; @@ -42,22 +44,25 @@ import static org.junit.Assert.assertTrue; * @author Sanne Grinovero */ public class ProxoolConnectionProviderTest extends BaseUnitTestCase { + + + @Test public void testPoolsClosed() { assertDefinedPools(); // zero-length-vararg used as parameter - - ProxoolConnectionProvider providerOne = new ProxoolConnectionProvider(); - providerOne.configure( getPoolConfigurarion( "pool-one" ) ); + StandardServiceRegistry serviceRegistry = buildServiceRegistry( "pool-one" ); + ConnectionProvider providerOne = serviceRegistry.getService( ConnectionProvider.class ); assertDefinedPools( "pool-one" ); - - ProxoolConnectionProvider providerTwo = new ProxoolConnectionProvider(); - providerTwo.configure( getPoolConfigurarion( "pool-two" ) ); + + + StandardServiceRegistry serviceRegistryTwo = buildServiceRegistry( "pool-two" ); + ConnectionProvider providerTwo = serviceRegistryTwo.getService( ConnectionProvider.class ); assertDefinedPools( "pool-one", "pool-two" ); - providerOne.close(); + StandardServiceRegistryBuilder.destroy( serviceRegistry ); assertDefinedPools( "pool-two" ); - - providerTwo.close(); + + StandardServiceRegistryBuilder.destroy( serviceRegistryTwo ); assertDefinedPools(); } @@ -69,11 +74,14 @@ public class ProxoolConnectionProviderTest extends BaseUnitTestCase { } } - private Properties getPoolConfigurarion(String poolName) { - Properties cfg = new Properties(); - cfg.setProperty( Environment.PROXOOL_POOL_ALIAS, poolName ); - cfg.setProperty( Environment.PROXOOL_PROPERTIES, poolName + ".properties" ); - return cfg; + + private StandardServiceRegistry buildServiceRegistry(String poolName){ + + return new StandardServiceRegistryBuilder( ) + .applySetting( Environment.PROXOOL_POOL_ALIAS, poolName ) + .applySetting( Environment.PROXOOL_PROPERTIES, poolName + ".properties" ) + .applySetting( Environment.CONNECTION_PROVIDER, ProxoolConnectionProvider.class.getName() ) + .build(); + } - } diff --git a/hibernate-proxool/src/test/resources/hibernate.properties b/hibernate-proxool/src/test/resources/hibernate.properties new file mode 100644 index 0000000000..2303d8c135 --- /dev/null +++ b/hibernate-proxool/src/test/resources/hibernate.properties @@ -0,0 +1,42 @@ +# +# 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 +# +hibernate.dialect org.hibernate.dialect.H2Dialect +hibernate.connection.driver_class org.h2.Driver +hibernate.connection.url jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE +hibernate.connection.username sa + +hibernate.connection.pool_size 5 +hibernate.jdbc.batch_size 10 +hibernate.connection.provider_class org.hibernate.connection.ProxoolConnectionProvider +hibernate.proxool.properties pool-one.properties + +hibernate.show_sql false + +hibernate.max_fetch_depth 5 + +hibernate.cache.region_prefix hibernate.test +hibernate.cache.region.factory_class org.hibernate.testing.cache.CachingRegionFactory + +# NOTE: hibernate.jdbc.batch_versioned_data should be set to false when testing with Oracle +hibernate.jdbc.batch_versioned_data true diff --git a/hibernate-proxool/src/test/resources/log4j.properties b/hibernate-proxool/src/test/resources/log4j.properties new file mode 100644 index 0000000000..1f7070d830 --- /dev/null +++ b/hibernate-proxool/src/test/resources/log4j.properties @@ -0,0 +1,10 @@ +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n + + +log4j.rootLogger=info, stdout + +log4j.logger.org.hibernate.tool.hbm2ddl=debug +log4j.logger.org.hibernate.testing.cache=debug From 955c99cc430ba65b1dcb46f4c389e94f28f09b30 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Thu, 25 Apr 2013 09:46:12 -0500 Subject: [PATCH 11/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../java/org/hibernate/QueryException.java | 46 ++--- .../org/hibernate/dialect/DerbyDialect.java | 2 +- .../java/org/hibernate/dialect/Dialect.java | 2 +- .../org/hibernate/dialect/HSQLDialect.java | 4 +- .../org/hibernate/dialect/IngresDialect.java | 2 +- .../hibernate/dialect/MimerSQLDialect.java | 193 +++++++----------- .../hibernate/dialect/Oracle10gDialect.java | 2 +- .../hibernate/dialect/Oracle8iDialect.java | 4 +- .../hibernate/dialect/Oracle9iDialect.java | 2 +- .../lock/OptimisticLockingStrategy.java | 3 +- .../pagination/LegacyLimitHandler.java | 10 +- .../pagination/SQLServer2005LimitHandler.java | 2 +- .../hql/internal/ast/HqlSqlWalker.java | 4 +- .../internal/ast/QuerySyntaxException.java | 3 +- .../hql/internal/ast/QueryTranslatorImpl.java | 67 +++--- .../internal/ast/tree/BooleanLiteralNode.java | 2 +- .../internal/classic/QueryTranslatorImpl.java | 24 ++- 17 files changed, 170 insertions(+), 202 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/QueryException.java b/hibernate-core/src/main/java/org/hibernate/QueryException.java index 6a0a27d752..475852cc21 100644 --- a/hibernate-core/src/main/java/org/hibernate/QueryException.java +++ b/hibernate-core/src/main/java/org/hibernate/QueryException.java @@ -23,15 +23,11 @@ */ package org.hibernate; -import org.jboss.logging.Logger; - /** * A problem occurred translating a Hibernate query to SQL due to invalid query syntax, etc. */ public class QueryException extends HibernateException { - private static final Logger log = Logger.getLogger( QueryException.class ); - - private String queryString; + private final String queryString; /** * Constructs a QueryException using the specified exception message. @@ -39,7 +35,7 @@ public class QueryException extends HibernateException { * @param message A message explaining the exception condition */ public QueryException(String message) { - super( message ); + this( message, null, null ); } /** @@ -48,8 +44,8 @@ public class QueryException extends HibernateException { * @param message A message explaining the exception condition * @param cause The underlying cause */ - public QueryException(String message, Throwable cause) { - super( message, cause ); + public QueryException(String message, Exception cause) { + this( message, null, cause ); } /** @@ -59,7 +55,18 @@ public class QueryException extends HibernateException { * @param queryString The query being evaluated when the exception occurred */ public QueryException(String message, String queryString) { - super( message ); + this( message, queryString, null ); + } + + /** + * Constructs a QueryException using the specified exception message and query-string. + * + * @param message A message explaining the exception condition + * @param queryString The query being evaluated when the exception occurred + * @param cause The underlying cause + */ + public QueryException(String message, String queryString, Exception cause) { + super( message, cause ); this.queryString = queryString; } @@ -69,7 +76,7 @@ public class QueryException extends HibernateException { * @param cause The underlying cause */ public QueryException(Exception cause) { - super( cause ); + this( "A query exception occurred", null, cause ); } /** @@ -81,27 +88,10 @@ public class QueryException extends HibernateException { return queryString; } - /** - * Set the query string. Even an option since often the part of the code generating the exception does not - * have access to the query overall. - * - * @param queryString The query string. - */ - public void setQueryString(String queryString) { - if ( this.queryString != null ) { - log.debugf( - "queryString overriding non-null previous value [%s] : %s", - this.queryString, - queryString - ); - } - this.queryString = queryString; - } - @Override public String getMessage() { String msg = super.getMessage(); - if ( queryString!=null ) { + if ( queryString != null ) { msg += " [" + queryString + ']'; } return msg; diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java index 5a2b793e45..e59662a49b 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/DerbyDialect.java @@ -210,7 +210,7 @@ public class DerbyDialect extends DB2Dialect { sb.append( limit ).append( " rows only" ); if ( hasForUpdateClause( forUpdateIndex ) ) { - sb.append(' '); + sb.append( ' ' ); sb.append( query.substring( forUpdateIndex ) ); } else if ( hasWithClause( normalizedSelect ) ) { diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java index ea5522f253..feacda61a6 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java @@ -693,7 +693,7 @@ public abstract class Dialect implements ConversionContext { // keyword support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ protected void registerKeyword(String word) { - sqlKeywords.add(word); + sqlKeywords.add( word ); } public Set getKeywords() { diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java index 18bc9b3cbd..2073fd46b4 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/HSQLDialect.java @@ -65,6 +65,7 @@ import org.jboss.logging.Logger; * @author Phillip Baird * @author Fred Toussi */ +@SuppressWarnings("deprecation") public class HSQLDialect extends Dialect { private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, @@ -158,7 +159,8 @@ public class HSQLDialect extends Dialect { // datetime functions if ( hsqldbVersion < 20 ) { registerFunction( "sysdate", new NoArgSQLFunction( "sysdate", StandardBasicTypes.DATE, false ) ); - } else { + } + else { registerFunction( "sysdate", new NoArgSQLFunction( "sysdate", StandardBasicTypes.TIMESTAMP, false ) ); } registerFunction( "current_date", new NoArgSQLFunction( "current_date", StandardBasicTypes.DATE, false ) ); diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/IngresDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/IngresDialect.java index b22cf43218..c58c01ee25 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/IngresDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/IngresDialect.java @@ -298,7 +298,7 @@ public class IngresDialect extends Dialect { } @Override - public boolean supportsExpectedLobUsagePattern () { + public boolean supportsExpectedLobUsagePattern() { return false; } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/MimerSQLDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/MimerSQLDialect.java index 6c9d031f27..f377fe727c 100755 --- a/hibernate-core/src/main/java/org/hibernate/dialect/MimerSQLDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/MimerSQLDialect.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.dialect; + import java.sql.Types; import org.hibernate.cfg.Environment; @@ -31,8 +32,10 @@ import org.hibernate.type.StandardBasicTypes; /** * An Hibernate 3 SQL dialect for Mimer SQL. This dialect requires Mimer SQL 9.2.1 or later * because of the mappings to NCLOB, BINARY, and BINARY VARYING. + * * @author Fredrik lund */ +@SuppressWarnings("deprecation") public class MimerSQLDialect extends Dialect { private static final int NATIONAL_CHAR_LENGTH = 2000; @@ -43,7 +46,6 @@ public class MimerSQLDialect extends Dialect { * this is also the maximum width of the table (exluding LOBs). To avoid breaking the limit all the * time we limit the length of the character columns to CHAR_MAX_LENTH, NATIONAL_CHAR_LENGTH for national * characters, and BINARY_MAX_LENGTH for binary types. - * */ public MimerSQLDialect() { super(); @@ -55,7 +57,7 @@ public class MimerSQLDialect extends Dialect { registerColumnType( Types.CHAR, "NCHAR(1)" ); registerColumnType( Types.VARCHAR, NATIONAL_CHAR_LENGTH, "NATIONAL CHARACTER VARYING($l)" ); registerColumnType( Types.VARCHAR, "NCLOB($l)" ); - registerColumnType( Types.LONGVARCHAR, "CLOB($1)"); + registerColumnType( Types.LONGVARCHAR, "CLOB($1)" ); registerColumnType( Types.FLOAT, "FLOAT" ); registerColumnType( Types.DOUBLE, "DOUBLE PRECISION" ); registerColumnType( Types.DATE, "DATE" ); @@ -63,180 +65,137 @@ public class MimerSQLDialect extends Dialect { registerColumnType( Types.TIMESTAMP, "TIMESTAMP" ); registerColumnType( Types.VARBINARY, BINARY_MAX_LENGTH, "BINARY VARYING($l)" ); registerColumnType( Types.VARBINARY, "BLOB($1)" ); - registerColumnType( Types.LONGVARBINARY, "BLOB($1)"); + registerColumnType( Types.LONGVARBINARY, "BLOB($1)" ); registerColumnType( Types.BINARY, BINARY_MAX_LENGTH, "BINARY" ); registerColumnType( Types.BINARY, "BLOB($1)" ); registerColumnType( Types.NUMERIC, "NUMERIC(19, $l)" ); registerColumnType( Types.BLOB, "BLOB($l)" ); registerColumnType( Types.CLOB, "NCLOB($l)" ); - registerFunction("abs", new StandardSQLFunction("abs") ); - registerFunction("sign", new StandardSQLFunction("sign", StandardBasicTypes.INTEGER) ); - registerFunction("ceiling", new StandardSQLFunction("ceiling") ); - registerFunction("floor", new StandardSQLFunction("floor") ); - registerFunction("round", new StandardSQLFunction("round") ); + registerFunction( "abs", new StandardSQLFunction( "abs" ) ); + registerFunction( "sign", new StandardSQLFunction( "sign", StandardBasicTypes.INTEGER ) ); + registerFunction( "ceiling", new StandardSQLFunction( "ceiling" ) ); + registerFunction( "floor", new StandardSQLFunction( "floor" ) ); + registerFunction( "round", new StandardSQLFunction( "round" ) ); - registerFunction("dacos", new StandardSQLFunction("dacos", StandardBasicTypes.DOUBLE) ); - registerFunction("acos", new StandardSQLFunction("dacos", StandardBasicTypes.DOUBLE) ); - registerFunction("dasin", new StandardSQLFunction("dasin", StandardBasicTypes.DOUBLE) ); - registerFunction("asin", new StandardSQLFunction("dasin", StandardBasicTypes.DOUBLE) ); - registerFunction("datan", new StandardSQLFunction("datan", StandardBasicTypes.DOUBLE) ); - registerFunction("atan", new StandardSQLFunction("datan", StandardBasicTypes.DOUBLE) ); - registerFunction("datan2", new StandardSQLFunction("datan2", StandardBasicTypes.DOUBLE) ); - registerFunction("atan2", new StandardSQLFunction("datan2", StandardBasicTypes.DOUBLE) ); - registerFunction("dcos", new StandardSQLFunction("dcos", StandardBasicTypes.DOUBLE) ); - registerFunction("cos", new StandardSQLFunction("dcos", StandardBasicTypes.DOUBLE) ); - registerFunction("dcot", new StandardSQLFunction("dcot", StandardBasicTypes.DOUBLE) ); - registerFunction("cot", new StandardSQLFunction("dcot", StandardBasicTypes.DOUBLE) ); - registerFunction("ddegrees", new StandardSQLFunction("ddegrees", StandardBasicTypes.DOUBLE) ); - registerFunction("degrees", new StandardSQLFunction("ddegrees", StandardBasicTypes.DOUBLE) ); - registerFunction("dexp", new StandardSQLFunction("dexp", StandardBasicTypes.DOUBLE) ); - registerFunction("exp", new StandardSQLFunction("dexp", StandardBasicTypes.DOUBLE) ); - registerFunction("dlog", new StandardSQLFunction("dlog", StandardBasicTypes.DOUBLE) ); - registerFunction("log", new StandardSQLFunction("dlog", StandardBasicTypes.DOUBLE) ); - registerFunction("dlog10", new StandardSQLFunction("dlog10", StandardBasicTypes.DOUBLE) ); - registerFunction("log10", new StandardSQLFunction("dlog10", StandardBasicTypes.DOUBLE) ); - registerFunction("dradian", new StandardSQLFunction("dradian", StandardBasicTypes.DOUBLE) ); - registerFunction("radian", new StandardSQLFunction("dradian", StandardBasicTypes.DOUBLE) ); - registerFunction("dsin", new StandardSQLFunction("dsin", StandardBasicTypes.DOUBLE) ); - registerFunction("sin", new StandardSQLFunction("dsin", StandardBasicTypes.DOUBLE) ); - registerFunction("soundex", new StandardSQLFunction("soundex", StandardBasicTypes.STRING) ); - registerFunction("dsqrt", new StandardSQLFunction("dsqrt", StandardBasicTypes.DOUBLE) ); - registerFunction("sqrt", new StandardSQLFunction("dsqrt", StandardBasicTypes.DOUBLE) ); - registerFunction("dtan", new StandardSQLFunction("dtan", StandardBasicTypes.DOUBLE) ); - registerFunction("tan", new StandardSQLFunction("dtan", StandardBasicTypes.DOUBLE) ); - registerFunction("dpower", new StandardSQLFunction("dpower") ); - registerFunction("power", new StandardSQLFunction("dpower") ); + registerFunction( "dacos", new StandardSQLFunction( "dacos", StandardBasicTypes.DOUBLE ) ); + registerFunction( "acos", new StandardSQLFunction( "dacos", StandardBasicTypes.DOUBLE ) ); + registerFunction( "dasin", new StandardSQLFunction( "dasin", StandardBasicTypes.DOUBLE ) ); + registerFunction( "asin", new StandardSQLFunction( "dasin", StandardBasicTypes.DOUBLE ) ); + registerFunction( "datan", new StandardSQLFunction( "datan", StandardBasicTypes.DOUBLE ) ); + registerFunction( "atan", new StandardSQLFunction( "datan", StandardBasicTypes.DOUBLE ) ); + registerFunction( "datan2", new StandardSQLFunction( "datan2", StandardBasicTypes.DOUBLE ) ); + registerFunction( "atan2", new StandardSQLFunction( "datan2", StandardBasicTypes.DOUBLE ) ); + registerFunction( "dcos", new StandardSQLFunction( "dcos", StandardBasicTypes.DOUBLE ) ); + registerFunction( "cos", new StandardSQLFunction( "dcos", StandardBasicTypes.DOUBLE ) ); + registerFunction( "dcot", new StandardSQLFunction( "dcot", StandardBasicTypes.DOUBLE ) ); + registerFunction( "cot", new StandardSQLFunction( "dcot", StandardBasicTypes.DOUBLE ) ); + registerFunction( "ddegrees", new StandardSQLFunction( "ddegrees", StandardBasicTypes.DOUBLE ) ); + registerFunction( "degrees", new StandardSQLFunction( "ddegrees", StandardBasicTypes.DOUBLE ) ); + registerFunction( "dexp", new StandardSQLFunction( "dexp", StandardBasicTypes.DOUBLE ) ); + registerFunction( "exp", new StandardSQLFunction( "dexp", StandardBasicTypes.DOUBLE ) ); + registerFunction( "dlog", new StandardSQLFunction( "dlog", StandardBasicTypes.DOUBLE ) ); + registerFunction( "log", new StandardSQLFunction( "dlog", StandardBasicTypes.DOUBLE ) ); + registerFunction( "dlog10", new StandardSQLFunction( "dlog10", StandardBasicTypes.DOUBLE ) ); + registerFunction( "log10", new StandardSQLFunction( "dlog10", StandardBasicTypes.DOUBLE ) ); + registerFunction( "dradian", new StandardSQLFunction( "dradian", StandardBasicTypes.DOUBLE ) ); + registerFunction( "radian", new StandardSQLFunction( "dradian", StandardBasicTypes.DOUBLE ) ); + registerFunction( "dsin", new StandardSQLFunction( "dsin", StandardBasicTypes.DOUBLE ) ); + registerFunction( "sin", new StandardSQLFunction( "dsin", StandardBasicTypes.DOUBLE ) ); + registerFunction( "soundex", new StandardSQLFunction( "soundex", StandardBasicTypes.STRING ) ); + registerFunction( "dsqrt", new StandardSQLFunction( "dsqrt", StandardBasicTypes.DOUBLE ) ); + registerFunction( "sqrt", new StandardSQLFunction( "dsqrt", StandardBasicTypes.DOUBLE ) ); + registerFunction( "dtan", new StandardSQLFunction( "dtan", StandardBasicTypes.DOUBLE ) ); + registerFunction( "tan", new StandardSQLFunction( "dtan", StandardBasicTypes.DOUBLE ) ); + registerFunction( "dpower", new StandardSQLFunction( "dpower" ) ); + registerFunction( "power", new StandardSQLFunction( "dpower" ) ); - registerFunction("date", new StandardSQLFunction("date", StandardBasicTypes.DATE) ); - registerFunction("dayofweek", new StandardSQLFunction("dayofweek", StandardBasicTypes.INTEGER) ); - registerFunction("dayofyear", new StandardSQLFunction("dayofyear", StandardBasicTypes.INTEGER) ); - registerFunction("time", new StandardSQLFunction("time", StandardBasicTypes.TIME) ); - registerFunction("timestamp", new StandardSQLFunction("timestamp", StandardBasicTypes.TIMESTAMP) ); - registerFunction("week", new StandardSQLFunction("week", StandardBasicTypes.INTEGER) ); + registerFunction( "date", new StandardSQLFunction( "date", StandardBasicTypes.DATE ) ); + registerFunction( "dayofweek", new StandardSQLFunction( "dayofweek", StandardBasicTypes.INTEGER ) ); + registerFunction( "dayofyear", new StandardSQLFunction( "dayofyear", StandardBasicTypes.INTEGER ) ); + registerFunction( "time", new StandardSQLFunction( "time", StandardBasicTypes.TIME ) ); + registerFunction( "timestamp", new StandardSQLFunction( "timestamp", StandardBasicTypes.TIMESTAMP ) ); + registerFunction( "week", new StandardSQLFunction( "week", StandardBasicTypes.INTEGER ) ); - registerFunction("varchar", new StandardSQLFunction("varchar", StandardBasicTypes.STRING) ); - registerFunction("real", new StandardSQLFunction("real", StandardBasicTypes.FLOAT) ); - registerFunction("bigint", new StandardSQLFunction("bigint", StandardBasicTypes.LONG) ); - registerFunction("char", new StandardSQLFunction("char", StandardBasicTypes.CHARACTER) ); - registerFunction("integer", new StandardSQLFunction("integer", StandardBasicTypes.INTEGER) ); - registerFunction("smallint", new StandardSQLFunction("smallint", StandardBasicTypes.SHORT) ); + registerFunction( "varchar", new StandardSQLFunction( "varchar", StandardBasicTypes.STRING ) ); + registerFunction( "real", new StandardSQLFunction( "real", StandardBasicTypes.FLOAT ) ); + registerFunction( "bigint", new StandardSQLFunction( "bigint", StandardBasicTypes.LONG ) ); + registerFunction( "char", new StandardSQLFunction( "char", StandardBasicTypes.CHARACTER ) ); + registerFunction( "integer", new StandardSQLFunction( "integer", StandardBasicTypes.INTEGER ) ); + registerFunction( "smallint", new StandardSQLFunction( "smallint", StandardBasicTypes.SHORT ) ); - registerFunction("ascii_char", new StandardSQLFunction("ascii_char", StandardBasicTypes.CHARACTER) ); - registerFunction("ascii_code", new StandardSQLFunction("ascii_code", StandardBasicTypes.STRING)); - registerFunction("unicode_char", new StandardSQLFunction("unicode_char", StandardBasicTypes.LONG)); - registerFunction("unicode_code", new StandardSQLFunction("unicode_code", StandardBasicTypes.STRING)); - registerFunction("upper", new StandardSQLFunction("upper") ); - registerFunction("lower", new StandardSQLFunction("lower") ); - registerFunction("char_length", new StandardSQLFunction("char_length", StandardBasicTypes.LONG) ); - registerFunction("bit_length", new StandardSQLFunction("bit_length", StandardBasicTypes.STRING)); + registerFunction( "ascii_char", new StandardSQLFunction( "ascii_char", StandardBasicTypes.CHARACTER ) ); + registerFunction( "ascii_code", new StandardSQLFunction( "ascii_code", StandardBasicTypes.STRING ) ); + registerFunction( "unicode_char", new StandardSQLFunction( "unicode_char", StandardBasicTypes.LONG ) ); + registerFunction( "unicode_code", new StandardSQLFunction( "unicode_code", StandardBasicTypes.STRING ) ); + registerFunction( "upper", new StandardSQLFunction( "upper" ) ); + registerFunction( "lower", new StandardSQLFunction( "lower" ) ); + registerFunction( "char_length", new StandardSQLFunction( "char_length", StandardBasicTypes.LONG ) ); + registerFunction( "bit_length", new StandardSQLFunction( "bit_length", StandardBasicTypes.STRING ) ); - getDefaultProperties().setProperty(Environment.USE_STREAMS_FOR_BINARY, "true"); - getDefaultProperties().setProperty(Environment.STATEMENT_BATCH_SIZE, "50"); + getDefaultProperties().setProperty( Environment.USE_STREAMS_FOR_BINARY, "true" ); + getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, "50" ); } - /** - * The syntax used to add a column to a table - */ + + @Override public String getAddColumnString() { return "add column"; } - /** - * We do not have to drop constraints before we drop the table - */ + @Override public boolean dropConstraints() { return false; } - /** - * TODO: Check if Mimer SQL cannot handle the way DB2 does - */ + @Override public boolean supportsIdentityColumns() { return false; } - /** - * Mimer SQL supports sequences - * @return boolean - */ + @Override public boolean supportsSequences() { return true; } - /** - * The syntax used to get the next value of a sequence in Mimer SQL - */ + @Override public String getSequenceNextValString(String sequenceName) { return "select next_value of " + sequenceName + " from system.onerow"; } - /** - * The syntax used to create a sequence. Since we presume the sequences will be used as keys, - * we make them unique. - */ + @Override public String getCreateSequenceString(String sequenceName) { return "create unique sequence " + sequenceName; } - /** - * The syntax used to drop sequences - */ + @Override public String getDropSequenceString(String sequenceName) { return "drop sequence " + sequenceName + " restrict"; } - /** - * Mimer SQL does not support limit - */ + @Override public boolean supportsLimit() { return false; } - /** - * The syntax for using cascade on constraints - */ + @Override public String getCascadeConstraintsString() { return " cascade"; } - /** - * The syntax for fetching all sequnces avialable in the current schema. - */ + @Override public String getQuerySequencesString() { return "select sequence_schema || '.' || sequence_name from information_schema.ext_sequences"; } - /** - * Does the FOR UPDATE OF syntax specify particular - * columns? - */ + @Override public boolean forUpdateOfColumns() { return false; } - /** - * Support the FOR UPDATE syntax? For now, returns false since - * the current version of the Mimer SQL JDBC Driver does not support - * updatable resultsets. Otherwise, Mimer SQL actually supports the for update syntax. - * @return boolean - */ - public boolean supportsForUpdate() { - return false; - } - - - /** - * For now, simply return false since we don't updatable result sets. - */ + @Override public boolean supportsOuterJoinForUpdate() { return false; } } - - - - - - diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle10gDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle10gDialect.java index 978a5be158..850db1df17 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle10gDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle10gDialect.java @@ -54,7 +54,7 @@ public class Oracle10gDialect extends Oracle9iDialect { return getForUpdateSkipLockedString(); } else { - return super.getWriteLockString(timeout); + return super.getWriteLockString( timeout ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle8iDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle8iDialect.java index 9b83d3fdbc..cb5e403ca3 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle8iDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle8iDialect.java @@ -28,7 +28,6 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; -import org.hibernate.HibernateException; import org.hibernate.JDBCException; import org.hibernate.QueryTimeoutException; import org.hibernate.cfg.Environment; @@ -44,7 +43,6 @@ import org.hibernate.exception.spi.SQLExceptionConversionDelegate; import org.hibernate.exception.spi.TemplatedViolatedConstraintNameExtracter; import org.hibernate.exception.spi.ViolatedConstraintNameExtracter; import org.hibernate.internal.util.JdbcExceptionHelper; -import org.hibernate.internal.util.ReflectHelper; import org.hibernate.sql.CaseFragment; import org.hibernate.sql.DecodeCaseFragment; import org.hibernate.sql.JoinFragment; @@ -255,7 +253,7 @@ public class Oracle8iDialect extends Dialect { pagingSelect.append( "select * from ( select row_.*, rownum rownum_ from ( " ); } else { - pagingSelect.append("select * from ( "); + pagingSelect.append( "select * from ( " ); } pagingSelect.append( sql ); if (hasOffset) { diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9iDialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9iDialect.java index 6a390cf734..687d23bdaa 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9iDialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Oracle9iDialect.java @@ -122,7 +122,7 @@ public class Oracle9iDialect extends Oracle8iDialect { else if ( timeout > 0 ) { // convert from milliseconds to seconds final float seconds = timeout / 1000.0f; - timeout = Math.round(seconds); + timeout = Math.round( seconds ); return " for update wait " + timeout; } else { diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticLockingStrategy.java b/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticLockingStrategy.java index 2b200526d5..aaf21ef57f 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticLockingStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/lock/OptimisticLockingStrategy.java @@ -42,6 +42,7 @@ import org.hibernate.persister.entity.Lockable; * @author Scott Marlow * @since 3.5 */ +@SuppressWarnings("deprecation") public class OptimisticLockingStrategy implements LockingStrategy { private final Lockable lockable; private final LockMode lockMode; @@ -65,7 +66,7 @@ public class OptimisticLockingStrategy implements LockingStrategy { if ( !lockable.isVersioned() ) { throw new OptimisticLockException( object, "[" + lockMode + "] not supported for non-versioned entities [" + lockable.getEntityName() + "]" ); } - final EntityEntry entry = session.getPersistenceContext().getEntry(object); + final EntityEntry entry = session.getPersistenceContext().getEntry( object ); // Register the EntityVerifyVersionProcess action to run just prior to transaction commit. ( (EventSource) session ).getActionQueue().registerProcess( new EntityVerifyVersionProcess( object, entry ) ); } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/LegacyLimitHandler.java b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/LegacyLimitHandler.java index dceba667bd..9385e7ac60 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/LegacyLimitHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/LegacyLimitHandler.java @@ -89,10 +89,14 @@ public class LegacyLimitHandler extends AbstractLimitHandler { @Override public String getProcessedSql() { - boolean useLimitOffset = supportsLimit() && supportsLimitOffset() - && LimitHelper.hasFirstRow( selection ) && LimitHelper.hasMaxRows( selection ); + final boolean useLimitOffset = supportsLimit() + && supportsLimitOffset() + && LimitHelper.hasFirstRow( selection ) + && LimitHelper.hasMaxRows( selection ); return dialect.getLimitString( - sql, useLimitOffset ? LimitHelper.getFirstRow( selection ) : 0, getMaxOrLimit() + sql, + useLimitOffset ? LimitHelper.getFirstRow( selection ) : 0, + getMaxOrLimit() ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/SQLServer2005LimitHandler.java b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/SQLServer2005LimitHandler.java index 173bf5dde9..2dd22b2a47 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/pagination/SQLServer2005LimitHandler.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/pagination/SQLServer2005LimitHandler.java @@ -310,7 +310,7 @@ public class SQLServer2005LimitHandler extends AbstractLimitHandler { pos = lowercase.indexOf( search, cur ); if ( pos != -1 ) { for ( int iter = cur; iter < pos; iter++ ) { - char c = sb.charAt( iter ); + final char c = sb.charAt( iter ); if ( c == '(' ) { depth = depth + 1; } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlSqlWalker.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlSqlWalker.java index 2c3beb7f74..1e3f6341b4 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlSqlWalker.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlSqlWalker.java @@ -1059,9 +1059,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par public int[] getNamedParameterLocations(String name) throws QueryException { Object o = namedParameters.get( name ); if ( o == null ) { - QueryException qe = new QueryException( QueryTranslator.ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name ); - qe.setQueryString( queryTranslatorImpl.getQueryString() ); - throw qe; + throw new QueryException( QueryTranslator.ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name, queryTranslatorImpl.getQueryString() ); } if ( o instanceof Integer ) { return new int[]{ (Integer) o }; diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QuerySyntaxException.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QuerySyntaxException.java index b4a2456896..f2f952f33a 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QuerySyntaxException.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QuerySyntaxException.java @@ -39,8 +39,7 @@ public class QuerySyntaxException extends QueryException { } public QuerySyntaxException(String message, String hql) { - this( message ); - setQueryString( hql ); + super( message, hql ); } public static QuerySyntaxException convert(RecognitionException e) { diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QueryTranslatorImpl.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QueryTranslatorImpl.java index 71670bd6f5..3f0fc884b0 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QueryTranslatorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QueryTranslatorImpl.java @@ -77,8 +77,10 @@ import org.hibernate.type.Type; * @author Joshua Davis (pgmjsd@sourceforge.net) */ public class QueryTranslatorImpl implements FilterTranslator { - - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, QueryTranslatorImpl.class.getName()); + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + QueryTranslatorImpl.class.getName() + ); private SessionFactoryImplementor factory; @@ -87,7 +89,8 @@ public class QueryTranslatorImpl implements FilterTranslator { private boolean shallowQuery; private Map tokenReplacements; - private Map enabledFilters; //TODO:this is only needed during compilation .. can we eliminate the instvar? + //TODO:this is only needed during compilation .. can we eliminate the instvar? + private Map enabledFilters; private boolean compiled; private QueryLoader queryLoader; @@ -110,9 +113,9 @@ public class QueryTranslatorImpl implements FilterTranslator { */ public QueryTranslatorImpl( String queryIdentifier, - String query, - Map enabledFilters, - SessionFactoryImplementor factory) { + String query, + Map enabledFilters, + SessionFactoryImplementor factory) { this.queryIdentifier = queryIdentifier; this.hql = query; this.compiled = false; @@ -131,8 +134,8 @@ public class QueryTranslatorImpl implements FilterTranslator { * @throws MappingException There was a problem querying defined mappings. */ public void compile( - Map replacements, - boolean shallow) throws QueryException, MappingException { + Map replacements, + boolean shallow) throws QueryException, MappingException { doCompile( replacements, shallow, null ); } @@ -147,9 +150,9 @@ public class QueryTranslatorImpl implements FilterTranslator { * @throws MappingException There was a problem querying defined mappings. */ public void compile( - String collectionRole, - Map replacements, - boolean shallow) throws QueryException, MappingException { + String collectionRole, + Map replacements, + boolean shallow) throws QueryException, MappingException { doCompile( replacements, shallow, collectionRole ); } @@ -177,12 +180,12 @@ public class QueryTranslatorImpl implements FilterTranslator { try { // PHASE 1 : Parse the HQL into an AST. - HqlParser parser = parse( true ); + final HqlParser parser = parse( true ); // PHASE 2 : Analyze the HQL AST, and produce an SQL AST. - HqlSqlWalker w = analyze( parser, collectionRole ); + final HqlSqlWalker w = analyze( parser, collectionRole ); - sqlAst = ( Statement ) w.getAST(); + sqlAst = (Statement) w.getAST(); // at some point the generate phase needs to be moved out of here, // because a single object-level DML might spawn multiple SQL DML @@ -200,15 +203,19 @@ public class QueryTranslatorImpl implements FilterTranslator { } else { // PHASE 3 : Generate the SQL. - generate( ( QueryNode ) sqlAst ); + generate( (QueryNode) sqlAst ); queryLoader = new QueryLoader( this, factory, w.getSelectClause() ); } compiled = true; } catch ( QueryException qe ) { - qe.setQueryString( hql ); - throw qe; + if ( qe.getQueryString() == null ) { + throw new QueryException( qe.getMessage(), hql, qe ); + } + else { + throw qe; + } } catch ( RecognitionException e ) { // we do not actually propagate ANTLRExceptions as a cause, so @@ -223,12 +230,13 @@ public class QueryTranslatorImpl implements FilterTranslator { throw new QueryException( e.getMessage(), hql ); } - this.enabledFilters = null; //only needed during compilation phase... + //only needed during compilation phase... + this.enabledFilters = null; } private void generate(AST sqlAst) throws QueryException, RecognitionException { if ( sql == null ) { - SqlGenerator gen = new SqlGenerator(factory); + final SqlGenerator gen = new SqlGenerator( factory ); gen.statement( sqlAst ); sql = gen.getSQL(); if ( LOG.isDebugEnabled() ) { @@ -240,16 +248,17 @@ public class QueryTranslatorImpl implements FilterTranslator { } } + private static final ASTPrinter SQL_TOKEN_PRINTER = new ASTPrinter( SqlTokenTypes.class ); + private HqlSqlWalker analyze(HqlParser parser, String collectionRole) throws QueryException, RecognitionException { - HqlSqlWalker w = new HqlSqlWalker( this, factory, parser, tokenReplacements, collectionRole ); - AST hqlAst = parser.getAST(); + final HqlSqlWalker w = new HqlSqlWalker( this, factory, parser, tokenReplacements, collectionRole ); + final AST hqlAst = parser.getAST(); // Transform the tree. w.statement( hqlAst ); if ( LOG.isDebugEnabled() ) { - ASTPrinter printer = new ASTPrinter( SqlTokenTypes.class ); - LOG.debug( printer.showAsString( w.getAST(), "--- SQL AST ---" ) ); + LOG.debug( SQL_TOKEN_PRINTER.showAsString( w.getAST(), "--- SQL AST ---" ) ); } w.getParseErrorHandler().throwQueryException(); @@ -259,16 +268,15 @@ public class QueryTranslatorImpl implements FilterTranslator { private HqlParser parse(boolean filter) throws TokenStreamException, RecognitionException { // Parse the query string into an HQL AST. - HqlParser parser = HqlParser.getInstance( hql ); + final HqlParser parser = HqlParser.getInstance( hql ); parser.setFilter( filter ); LOG.debugf( "parse() - HQL: %s", hql ); parser.statement(); - AST hqlAst = parser.getAST(); + final AST hqlAst = parser.getAST(); - JavaConstantConverter converter = new JavaConstantConverter(); - NodeTraverser walker = new NodeTraverser( converter ); + final NodeTraverser walker = new NodeTraverser( new JavaConstantConverter() ); walker.traverseDepthFirst( hqlAst ); showHqlAst( hqlAst ); @@ -277,10 +285,11 @@ public class QueryTranslatorImpl implements FilterTranslator { return parser; } + private static final ASTPrinter HQL_TOKEN_PRINTER = new ASTPrinter( HqlTokenTypes.class ); + void showHqlAst(AST hqlAst) { if ( LOG.isDebugEnabled() ) { - ASTPrinter printer = new ASTPrinter( HqlTokenTypes.class ); - LOG.debug( printer.showAsString( hqlAst, "--- HQL AST ---" ) ); + LOG.debug( HQL_TOKEN_PRINTER.showAsString( hqlAst, "--- HQL AST ---" ) ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/BooleanLiteralNode.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/BooleanLiteralNode.java index 5da071d3c4..c7a712d3ce 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/BooleanLiteralNode.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/BooleanLiteralNode.java @@ -61,7 +61,7 @@ public class BooleanLiteralNode extends LiteralNode implements ExpectedTypeAware try { return typeAsLiteralType().objectToSQLString( getValue(), sessionFactory.getDialect() ); } - catch( Throwable t ) { + catch( Exception t ) { throw new QueryException( "Unable to render boolean literal value", t ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/classic/QueryTranslatorImpl.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/classic/QueryTranslatorImpl.java index 401b2fe4c6..e33092bf97 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/classic/QueryTranslatorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/classic/QueryTranslatorImpl.java @@ -244,8 +244,12 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator renderSQL(); } catch ( QueryException qe ) { - qe.setQueryString( queryString ); - throw qe; + if ( qe.getQueryString() == null ) { + throw generateQueryException( qe.getMessage(), qe ); + } + else { + throw qe; + } } catch ( MappingException me ) { throw me; @@ -253,9 +257,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator catch ( Exception e ) { LOG.debug( "Unexpected query compilation problem", e ); e.printStackTrace(); - QueryException qe = new QueryException( "Incorrect query syntax", e ); - qe.setQueryString( queryString ); - throw qe; + throw generateQueryException( "Incorrect query syntax", e ); } postInstantiate(); @@ -264,6 +266,14 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator } + public QueryException generateQueryException(String message) { + return new QueryException( message, queryString ); + } + + public QueryException generateQueryException(String message, Exception cause) { + return new QueryException( message, queryString, cause ); + } + @Override public String getSQLString() { return sqlString; @@ -547,9 +557,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator public int[] getNamedParameterLocs(String name) throws QueryException { Object o = namedParameters.get( name ); if ( o == null ) { - QueryException qe = new QueryException( ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name ); - qe.setQueryString( queryString ); - throw qe; + throw generateQueryException( ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name ); } if ( o instanceof Integer ) return new int[] { (Integer) o }; else { From ce08bdb7a856c87064ecb4f05ee463afbbd8707d Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Thu, 25 Apr 2013 10:01:09 -0500 Subject: [PATCH 12/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../org/hibernate/hql/internal/ast/tree/JavaConstantNode.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/JavaConstantNode.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/JavaConstantNode.java index 82fb6ba00a..4d2af46998 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/JavaConstantNode.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/tree/JavaConstantNode.java @@ -84,7 +84,7 @@ public class JavaConstantNode extends Node implements ExpectedTypeAwareNode, Ses Dialect dialect = factory.getDialect(); return literalType.objectToSQLString( constantValue, dialect ); } - catch ( Throwable t ) { + catch ( Exception t ) { throw new QueryException( QueryTranslator.ERROR_CANNOT_FORMAT_LITERAL + constantExpression, t ); } } From fecde044726fbaf122f1e0dc3d103361704f0bd3 Mon Sep 17 00:00:00 2001 From: Strong Liu Date: Fri, 26 Apr 2013 02:44:18 +0800 Subject: [PATCH 13/57] HHH-8127 OutOfMemoryError when running tests --- .../hibernate/hql/internal/ast/ErrorCounter.java | 12 ++++++------ .../id/SequenceHiLoGeneratorNoIncrementTest.java | 4 ++-- .../org/hibernate/id/SequenceHiLoGeneratorTest.java | 4 ++-- .../metamodel/relational/ObjectNameTests.java | 3 ++- .../relational/TableManipulationTests.java | 3 ++- .../test/annotations/backquotes/BackquoteTest.java | 13 ++++++++++++- .../onetoone/primarykey/NullablePrimaryKeyTest.java | 8 +++++++- .../test/instrument/cases/AbstractExecutable.java | 2 ++ .../testing/env/ConnectionProviderBuilder.java | 2 +- .../hibernate/testing/env}/TestingDatabaseInfo.java | 2 +- 10 files changed, 37 insertions(+), 16 deletions(-) rename {hibernate-core/src/test/java/org/hibernate => hibernate-testing/src/main/java/org/hibernate/testing/env}/TestingDatabaseInfo.java (98%) diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/ErrorCounter.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/ErrorCounter.java index bee855397e..9a28c8e3dd 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/ErrorCounter.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/ErrorCounter.java @@ -40,9 +40,9 @@ public class ErrorCounter implements ParseErrorHandler { private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, ErrorCounter.class.getName()); - private List errorList = new ArrayList(); - private List warningList = new ArrayList(); - private List recognitionExceptions = new ArrayList(); + private List errorList = new ArrayList(); + private List warningList = new ArrayList(); + private List recognitionExceptions = new ArrayList(); public void reportError(RecognitionException e) { reportError( e.toString() ); @@ -66,8 +66,8 @@ public class ErrorCounter implements ParseErrorHandler { private String getErrorString() { StringBuilder buf = new StringBuilder(); - for ( Iterator iterator = errorList.iterator(); iterator.hasNext(); ) { - buf.append( ( String ) iterator.next() ); + for ( Iterator iterator = errorList.iterator(); iterator.hasNext(); ) { + buf.append( iterator.next() ); if ( iterator.hasNext() ) buf.append( "\n" ); } @@ -76,7 +76,7 @@ public class ErrorCounter implements ParseErrorHandler { public void throwQueryException() throws QueryException { if ( getErrorCount() > 0 ) { - if (recognitionExceptions.size() > 0) throw QuerySyntaxException.convert((RecognitionException)recognitionExceptions.get(0)); + if (recognitionExceptions.size() > 0) throw QuerySyntaxException.convert(recognitionExceptions.get(0)); throw new QueryException(getErrorString()); } LOG.debug("throwQueryException() : no errors"); diff --git a/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorNoIncrementTest.java b/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorNoIncrementTest.java index fe81d34d56..97fd6f959e 100644 --- a/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorNoIncrementTest.java +++ b/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorNoIncrementTest.java @@ -32,7 +32,7 @@ import java.sql.SQLException; import java.util.Properties; import org.hibernate.Session; -import org.hibernate.TestingDatabaseInfo; +import org.hibernate.testing.env.TestingDatabaseInfo; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.cfg.NamingStrategy; @@ -88,7 +88,7 @@ public class SequenceHiLoGeneratorNoIncrementTest extends BaseUnitTestCase { } ); - Dialect dialect = new H2Dialect(); + Dialect dialect = TestingDatabaseInfo.DIALECT; generator = new SequenceHiLoGenerator(); generator.configure( StandardBasicTypes.LONG, properties, dialect ); diff --git a/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorTest.java b/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorTest.java index 6fe9ff8064..7239297ff7 100644 --- a/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/id/SequenceHiLoGeneratorTest.java @@ -32,7 +32,7 @@ import java.sql.SQLException; import java.util.Properties; import org.hibernate.Session; -import org.hibernate.TestingDatabaseInfo; +import org.hibernate.testing.env.TestingDatabaseInfo; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.cfg.NamingStrategy; @@ -84,7 +84,7 @@ public class SequenceHiLoGeneratorTest extends BaseUnitTestCase { } } ); - Dialect dialect = new H2Dialect(); + Dialect dialect = TestingDatabaseInfo.DIALECT; generator = new SequenceHiLoGenerator(); generator.configure( StandardBasicTypes.LONG, properties, dialect ); diff --git a/hibernate-core/src/test/java/org/hibernate/metamodel/relational/ObjectNameTests.java b/hibernate-core/src/test/java/org/hibernate/metamodel/relational/ObjectNameTests.java index 30b2f2d10d..d974b8d942 100644 --- a/hibernate-core/src/test/java/org/hibernate/metamodel/relational/ObjectNameTests.java +++ b/hibernate-core/src/test/java/org/hibernate/metamodel/relational/ObjectNameTests.java @@ -27,6 +27,7 @@ import org.junit.Test; import org.hibernate.dialect.Dialect; import org.hibernate.dialect.H2Dialect; +import org.hibernate.testing.env.TestingDatabaseInfo; import org.hibernate.testing.junit4.BaseUnitTestCase; import static org.junit.Assert.assertEquals; @@ -55,7 +56,7 @@ public class ObjectNameTests extends BaseUnitTestCase { @Test public void testIdentifierBuilding() { - Dialect dialect = new H2Dialect(); + Dialect dialect = TestingDatabaseInfo.DIALECT; ObjectName on = new ObjectName( "schema", "catalog", "name" ); assertEquals( "schema.catalog.name", on.toText() ); on = new ObjectName( "schema", null, "name" ); diff --git a/hibernate-core/src/test/java/org/hibernate/metamodel/relational/TableManipulationTests.java b/hibernate-core/src/test/java/org/hibernate/metamodel/relational/TableManipulationTests.java index 6974fff0e2..69fdc683b4 100644 --- a/hibernate-core/src/test/java/org/hibernate/metamodel/relational/TableManipulationTests.java +++ b/hibernate-core/src/test/java/org/hibernate/metamodel/relational/TableManipulationTests.java @@ -29,6 +29,7 @@ import org.junit.Test; import org.hibernate.dialect.Dialect; import org.hibernate.dialect.H2Dialect; +import org.hibernate.testing.env.TestingDatabaseInfo; import org.hibernate.testing.junit4.BaseUnitTestCase; import static org.junit.Assert.assertEquals; @@ -133,7 +134,7 @@ public class TableManipulationTests extends BaseUnitTestCase { @Test public void testQualifiedName() { - Dialect dialect = new H2Dialect(); + Dialect dialect = TestingDatabaseInfo.DIALECT; Schema schema = new Schema( Identifier.toIdentifier( "schema" ), Identifier.toIdentifier( "`catalog`" ) ); Table table = schema.createTable( Identifier.toIdentifier( "my_table" ) ); assertEquals( "my_table", table.getTableName().getName() ); diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/backquotes/BackquoteTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/backquotes/BackquoteTest.java index a3eb378aee..d048ea4591 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/backquotes/BackquoteTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/backquotes/BackquoteTest.java @@ -59,6 +59,12 @@ public class BackquoteTest extends BaseUnitTestCase { log.debug(writer.toString()); fail(e.getMessage()); } + finally { + if ( sessionFactory != null ) { + sessionFactory.close(); + sessionFactory = null; + } + } } /** @@ -87,6 +93,11 @@ public class BackquoteTest extends BaseUnitTestCase { e.printStackTrace(new PrintWriter(writer)); log.debug(writer.toString()); fail(e.getMessage()); - } + } finally { + if(sessionFactory!=null){ + sessionFactory.close(); + sessionFactory = null; + } + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/NullablePrimaryKeyTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/NullablePrimaryKeyTest.java index 27325d900b..be6ce4e9e7 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/NullablePrimaryKeyTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/onetoone/primarykey/NullablePrimaryKeyTest.java @@ -5,6 +5,7 @@ import org.jboss.logging.Logger; import org.junit.Assert; import org.junit.Test; +import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Environment; import org.hibernate.dialect.SQLServerDialect; @@ -23,12 +24,13 @@ public class NullablePrimaryKeyTest { public void testGeneratedSql() { ServiceRegistry serviceRegistry = null; + SessionFactory sf = null; try { AnnotationConfiguration config = new AnnotationConfiguration(); config.addAnnotatedClass(Address.class); config.addAnnotatedClass(Person.class); serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( Environment.getProperties() ); - config.buildSessionFactory( serviceRegistry ); + sf = config.buildSessionFactory( serviceRegistry ); String[] schema = config .generateSchemaCreationScript(new SQLServerDialect()); for (String s : schema) { @@ -41,9 +43,13 @@ public class NullablePrimaryKeyTest { Assert.fail(e.getMessage()); } finally { + if ( sf != null ) { + sf.close(); + } if ( serviceRegistry != null ) { ServiceRegistryBuilder.destroy( serviceRegistry ); } + } } } diff --git a/hibernate-core/src/test/java/org/hibernate/test/instrument/cases/AbstractExecutable.java b/hibernate-core/src/test/java/org/hibernate/test/instrument/cases/AbstractExecutable.java index 0c3d0f7e35..4bb9df9a91 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/instrument/cases/AbstractExecutable.java +++ b/hibernate-core/src/test/java/org/hibernate/test/instrument/cases/AbstractExecutable.java @@ -30,8 +30,10 @@ public abstract class AbstractExecutable implements Executable { } finally { factory.close(); + factory = null; if ( serviceRegistry != null ) { ServiceRegistryBuilder.destroy( serviceRegistry ); + serviceRegistry = null; } } } diff --git a/hibernate-testing/src/main/java/org/hibernate/testing/env/ConnectionProviderBuilder.java b/hibernate-testing/src/main/java/org/hibernate/testing/env/ConnectionProviderBuilder.java index e7aef85b82..e236e88c9b 100644 --- a/hibernate-testing/src/main/java/org/hibernate/testing/env/ConnectionProviderBuilder.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/env/ConnectionProviderBuilder.java @@ -77,6 +77,6 @@ public class ConnectionProviderBuilder { } public static Dialect getCorrespondingDialect() { - return new H2Dialect(); + return TestingDatabaseInfo.DIALECT; } } diff --git a/hibernate-core/src/test/java/org/hibernate/TestingDatabaseInfo.java b/hibernate-testing/src/main/java/org/hibernate/testing/env/TestingDatabaseInfo.java similarity index 98% rename from hibernate-core/src/test/java/org/hibernate/TestingDatabaseInfo.java rename to hibernate-testing/src/main/java/org/hibernate/testing/env/TestingDatabaseInfo.java index 8102fbeef5..7ce98e701f 100644 --- a/hibernate-core/src/test/java/org/hibernate/TestingDatabaseInfo.java +++ b/hibernate-testing/src/main/java/org/hibernate/testing/env/TestingDatabaseInfo.java @@ -21,7 +21,7 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate; +package org.hibernate.testing.env; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; From b05b7800e186c72d2f06c864fe78b32293af200e Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Thu, 25 Apr 2013 17:16:07 -0500 Subject: [PATCH 14/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../java/org/hibernate/QueryException.java | 22 ++++++- .../hibernate/QueryParameterException.java | 16 +++++ .../QueryExecutionRequestException.java | 3 + .../hql/internal/ast/HqlSqlWalker.java | 17 +++-- .../ast/InvalidWithClauseException.java | 7 +- .../internal/ast/QuerySyntaxException.java | 8 +++ .../hql/internal/ast/QueryTranslatorImpl.java | 2 +- .../internal/classic/QueryTranslatorImpl.java | 14 +--- .../internal/SessionFactoryRegistry.java | 66 +++++++++++++++++-- 9 files changed, 129 insertions(+), 26 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/QueryException.java b/hibernate-core/src/main/java/org/hibernate/QueryException.java index 475852cc21..eca6070aa4 100644 --- a/hibernate-core/src/main/java/org/hibernate/QueryException.java +++ b/hibernate-core/src/main/java/org/hibernate/QueryException.java @@ -90,11 +90,31 @@ public class QueryException extends HibernateException { @Override public String getMessage() { - String msg = super.getMessage(); + String msg = getOriginalMessage(); if ( queryString != null ) { msg += " [" + queryString + ']'; } return msg; } + protected final String getOriginalMessage() { + return super.getMessage(); + } + + /** + * + * @param queryString + * @return + */ + public final QueryException wrapWithQueryString(String queryString) { + if ( this.getQueryString() != null ) { + return this; + } + + return doWrapWithQueryString( queryString ); + } + + protected QueryException doWrapWithQueryString(String queryString) { + return new QueryException( getOriginalMessage(), queryString, this ); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/QueryParameterException.java b/hibernate-core/src/main/java/org/hibernate/QueryParameterException.java index 92998c0029..b86ea91c5b 100644 --- a/hibernate-core/src/main/java/org/hibernate/QueryParameterException.java +++ b/hibernate-core/src/main/java/org/hibernate/QueryParameterException.java @@ -37,4 +37,20 @@ public class QueryParameterException extends QueryException { public QueryParameterException(String message) { super( message ); } + + /** + * Constructs a QueryParameterException + * + * @param message The message explaining the exception condition + * @param queryString The query that led to the exception + * @param cause The underlying cause + */ + public QueryParameterException(String message, String queryString, Exception cause) { + super( message, queryString, cause ); + } + + @Override + protected QueryException doWrapWithQueryString(String queryString) { + return new QueryParameterException( super.getOriginalMessage(), queryString, this ); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/QueryExecutionRequestException.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/QueryExecutionRequestException.java index c20f56e9fc..f55bdaf782 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/QueryExecutionRequestException.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/QueryExecutionRequestException.java @@ -33,5 +33,8 @@ import org.hibernate.QueryException; public class QueryExecutionRequestException extends QueryException { public QueryExecutionRequestException(String message, String queryString) { super( message, queryString ); + if ( queryString == null ) { + throw new IllegalArgumentException( "Illegal to pass null as queryString argument" ); + } } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlSqlWalker.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlSqlWalker.java index 1e3f6341b4..95cba36400 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlSqlWalker.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlSqlWalker.java @@ -410,7 +410,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par AST hqlSqlWithNode = returnAST; if (LOG.isDebugEnabled()) LOG.debugf("handleWithFragment() : %s", getASTPrinter().showAsString(hqlSqlWithNode, "-- with clause --")); - WithClauseVisitor visitor = new WithClauseVisitor( fromElement ); + WithClauseVisitor visitor = new WithClauseVisitor( fromElement, queryTranslatorImpl ); NodeTraverser traverser = new NodeTraverser( visitor ); traverser.traverseDepthFirst( hqlSqlWithNode ); @@ -421,7 +421,10 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par else { FromElement referencedFromElement = visitor.getReferencedFromElement(); if ( referencedFromElement != fromElement ) { - throw new InvalidWithClauseException( "with-clause expressions did not reference from-clause element to which the with-clause was associated" ); + throw new InvalidWithClauseException( + "with-clause expressions did not reference from-clause element to which the with-clause was associated", + queryTranslatorImpl.getQueryString() + ); } } @@ -443,11 +446,14 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par private static class WithClauseVisitor implements NodeTraverser.VisitationStrategy { private final FromElement joinFragment; + private final QueryTranslatorImpl queryTranslatorImpl; + private FromElement referencedFromElement; private String joinAlias; - public WithClauseVisitor(FromElement fromElement) { + public WithClauseVisitor(FromElement fromElement, QueryTranslatorImpl queryTranslatorImpl) { this.joinFragment = fromElement; + this.queryTranslatorImpl = queryTranslatorImpl; } public void visit(AST node) { @@ -477,7 +483,10 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par // creates and renders the join fragments for inheritance // hierarchies... if ( !joinAlias.equals( referencedFromElement.getTableAlias() ) ) { - throw new InvalidWithClauseException( "with clause can only reference columns in the driving table" ); + throw new InvalidWithClauseException( + "with clause can only reference columns in the driving table", + queryTranslatorImpl.getQueryString() + ); } } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/InvalidWithClauseException.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/InvalidWithClauseException.java index aa7f97e336..1630801054 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/InvalidWithClauseException.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/InvalidWithClauseException.java @@ -30,11 +30,10 @@ package org.hibernate.hql.internal.ast; * @author Steve Ebersole */ public class InvalidWithClauseException extends QuerySyntaxException { - public InvalidWithClauseException(String message) { - super( message ); - } - public InvalidWithClauseException(String message, String queryString) { super( message, queryString ); + if ( queryString == null ) { + throw new IllegalArgumentException( "Illegal to pass null as queryString argument" ); + } } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QuerySyntaxException.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QuerySyntaxException.java index f2f952f33a..ea97a8ce49 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QuerySyntaxException.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QuerySyntaxException.java @@ -42,6 +42,10 @@ public class QuerySyntaxException extends QueryException { super( message, hql ); } + protected QuerySyntaxException(String message, String queryString, Exception cause) { + super( message, queryString, cause ); + } + public static QuerySyntaxException convert(RecognitionException e) { return convert( e, null ); } @@ -53,4 +57,8 @@ public class QuerySyntaxException extends QueryException { return new QuerySyntaxException( e.getMessage() + positionInfo, hql ); } + @Override + protected QueryException doWrapWithQueryString(String queryString) { + return new QuerySyntaxException( getOriginalMessage(), queryString, this ); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QueryTranslatorImpl.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QueryTranslatorImpl.java index 3f0fc884b0..0e1f176767 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QueryTranslatorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QueryTranslatorImpl.java @@ -211,7 +211,7 @@ public class QueryTranslatorImpl implements FilterTranslator { } catch ( QueryException qe ) { if ( qe.getQueryString() == null ) { - throw new QueryException( qe.getMessage(), hql, qe ); + throw qe.wrapWithQueryString( hql ); } else { throw qe; diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/classic/QueryTranslatorImpl.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/classic/QueryTranslatorImpl.java index e33092bf97..79c248c62b 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/classic/QueryTranslatorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/classic/QueryTranslatorImpl.java @@ -245,7 +245,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator } catch ( QueryException qe ) { if ( qe.getQueryString() == null ) { - throw generateQueryException( qe.getMessage(), qe ); + throw qe.wrapWithQueryString( queryString ); } else { throw qe; @@ -257,7 +257,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator catch ( Exception e ) { LOG.debug( "Unexpected query compilation problem", e ); e.printStackTrace(); - throw generateQueryException( "Incorrect query syntax", e ); + throw new QueryException( "Incorrect query syntax", queryString, e ); } postInstantiate(); @@ -266,14 +266,6 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator } - public QueryException generateQueryException(String message) { - return new QueryException( message, queryString ); - } - - public QueryException generateQueryException(String message, Exception cause) { - return new QueryException( message, queryString, cause ); - } - @Override public String getSQLString() { return sqlString; @@ -557,7 +549,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator public int[] getNamedParameterLocs(String name) throws QueryException { Object o = namedParameters.get( name ); if ( o == null ) { - throw generateQueryException( ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name ); + throw new QueryException( ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name, queryString ); } if ( o instanceof Integer ) return new int[] { (Integer) o }; else { diff --git a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistry.java b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistry.java index 9cdfd99886..d40db42ce0 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistry.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/SessionFactoryRegistry.java @@ -24,6 +24,7 @@ package org.hibernate.internal; import java.util.Hashtable; +import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.naming.Context; import javax.naming.Name; @@ -53,15 +54,34 @@ public class SessionFactoryRegistry { SessionFactoryRegistry.class.getName() ); + /** + * Singleton access + */ public static final SessionFactoryRegistry INSTANCE = new SessionFactoryRegistry(); + /** + * A map for mapping the UUID of a SessionFactory to the corresponding SessionFactory instance + */ private final ConcurrentHashMap sessionFactoryMap = new ConcurrentHashMap(); + + /** + * A cross-reference for mapping a SessionFactory name to its UUID. Not all SessionFactories get named, + */ private final ConcurrentHashMap nameUuidXref = new ConcurrentHashMap(); - public SessionFactoryRegistry() { + private SessionFactoryRegistry() { LOG.debugf( "Initializing SessionFactoryRegistry : %s", this ); } + /** + * Adds a SessionFactory to the registry + * + * @param uuid The uuid under which to register the SessionFactory + * @param name The optional name under which to register the SessionFactory + * @param isNameAlsoJndiName Is name, if provided, also a JNDI name? + * @param instance The SessionFactory instance + * @param jndiService The JNDI service, so we can register a listener if name is a JNDI name + */ public void addSessionFactory( String uuid, String name, @@ -72,7 +92,7 @@ public class SessionFactoryRegistry { throw new IllegalArgumentException( "SessionFactory UUID cannot be null" ); } - LOG.debugf( "Registering SessionFactory: %s (%s)", uuid, name == null ? "" : name ); + LOG.debugf( "Registering SessionFactory: %s (%s)", uuid, name == null ? "" : name ); sessionFactoryMap.put( uuid, instance ); if ( name != null ) { nameUuidXref.put( name, uuid ); @@ -103,6 +123,14 @@ public class SessionFactoryRegistry { } } + /** + * Remove a previously added SessionFactory + * + * @param uuid The uuid + * @param name The optional name + * @param isNameAlsoJndiName Is name, if provided, also a JNDI name? + * @param jndiService The JNDI service + */ public void removeSessionFactory( String uuid, String name, @@ -129,8 +157,15 @@ public class SessionFactoryRegistry { sessionFactoryMap.remove( uuid ); } + /** + * Get a registered SessionFactory by name + * + * @param name The name + * + * @return The SessionFactory + */ public SessionFactory getNamedSessionFactory(String name) { - LOG.debugf( "Lookup: name=%s", name ); + LOG.debugf( "Lookup: name=%s", name ); final String uuid = nameUuidXref.get( name ); return getSessionFactory( uuid ); } @@ -145,6 +180,27 @@ public class SessionFactoryRegistry { return sessionFactory; } + /** + * Does this registry currently contain registrations? + * + * @return true/false + */ + public boolean hasRegistrations() { + return ! sessionFactoryMap.isEmpty(); + } + + public void clearRegistrations() { + nameUuidXref.clear(); + for ( SessionFactory factory : sessionFactoryMap.values() ) { + try { + factory.close(); + } + catch (Exception ignore) { + } + } + sessionFactoryMap.clear(); + } + /** * Implementation of {@literal JNDI} {@link javax.naming.event.NamespaceChangeListener} contract to listener for context events * and react accordingly if necessary @@ -152,7 +208,7 @@ public class SessionFactoryRegistry { private final NamespaceChangeListener LISTENER = new NamespaceChangeListener() { @Override public void objectAdded(NamingEvent evt) { - LOG.debugf("A factory was successfully bound to name: %s", evt.getNewBinding().getName()); + LOG.debugf("A factory was successfully bound to name: %s", evt.getNewBinding().getName()); } @Override @@ -172,7 +228,7 @@ public class SessionFactoryRegistry { final String oldJndiName = evt.getOldBinding().getName(); final String newJndiName = evt.getNewBinding().getName(); - LOG.factoryJndiRename( oldJndiName, newJndiName ); + LOG.factoryJndiRename( oldJndiName, newJndiName ); final String uuid = nameUuidXref.remove( oldJndiName ); nameUuidXref.put( newJndiName, uuid ); From eaef21076dd3726f6c28c81ee1c7961a40b0fd31 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Thu, 25 Apr 2013 17:38:43 -0500 Subject: [PATCH 15/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../test/java/org/hibernate/jpa/test/EntityManagerTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java index bf3be224c3..70f60b1a9b 100755 --- a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java +++ b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java @@ -279,8 +279,8 @@ public class EntityManagerTest extends BaseEntityManagerFunctionalTestCase { IllegalArgumentException deserializedException = ( IllegalArgumentException ) in.readObject(); in.close(); byteIn.close(); - assertNull( deserializedException.getCause().getCause() ); - assertNull( e.getCause().getCause() ); + assertNull( deserializedException.getCause().getCause().getCause() ); + assertNull( e.getCause().getCause().getCause() ); } em.getTransaction().rollback(); em.close(); From e09d6855a2855aec178aa857115ca81f0adfb06e Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Fri, 26 Apr 2013 11:04:40 -0500 Subject: [PATCH 16/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../java/org/hibernate/QueryException.java | 27 +++++++-- .../hibernate/QueryParameterException.java | 2 +- .../hql/internal/ast/ErrorCounter.java | 55 ++++++++++++++----- .../hibernate/hql/internal/ast/HqlParser.java | 36 ++++++------ .../hql/internal/ast/HqlSqlWalker.java | 2 +- .../internal/ast/QuerySyntaxException.java | 43 +++++++++++++-- 6 files changed, 125 insertions(+), 40 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/QueryException.java b/hibernate-core/src/main/java/org/hibernate/QueryException.java index eca6070aa4..dd59a7ed0c 100644 --- a/hibernate-core/src/main/java/org/hibernate/QueryException.java +++ b/hibernate-core/src/main/java/org/hibernate/QueryException.java @@ -102,19 +102,38 @@ public class QueryException extends HibernateException { } /** + * Wraps this exception with another, of same kind, with the specified queryString. If this exception already + * has a queryString defined, the same exception ({@code this}) is returned. Otherwise the protected + * {@link #generateQueryException(String)} is called, to allow subclasses to properly create the correct + * subclass for return. * - * @param queryString - * @return + * @param queryString The query string that led to the QueryException + * + * @return {@code this}, if {@code this} has {@code null} for {@link #getQueryString()}; otherwise a new + * QueryException (or subclass) is returned. */ public final QueryException wrapWithQueryString(String queryString) { if ( this.getQueryString() != null ) { return this; } - return doWrapWithQueryString( queryString ); + return generateQueryException( queryString ); } - protected QueryException doWrapWithQueryString(String queryString) { + /** + * Called from {@link #wrapWithQueryString(String)} when we really need to generate a new QueryException + * (or subclass). + *

      + * NOTE : implementors should take care to use {@link #getOriginalMessage()} for the message, not + * {@link #getMessage()} + * + * @param queryString The query string + * + * @return The generated QueryException (or subclass) + * + * @see #getOriginalMessage() + */ + protected QueryException generateQueryException(String queryString) { return new QueryException( getOriginalMessage(), queryString, this ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/QueryParameterException.java b/hibernate-core/src/main/java/org/hibernate/QueryParameterException.java index b86ea91c5b..3f07de8ebc 100644 --- a/hibernate-core/src/main/java/org/hibernate/QueryParameterException.java +++ b/hibernate-core/src/main/java/org/hibernate/QueryParameterException.java @@ -50,7 +50,7 @@ public class QueryParameterException extends QueryException { } @Override - protected QueryException doWrapWithQueryString(String queryString) { + protected QueryException generateQueryException(String queryString) { return new QueryParameterException( super.getOriginalMessage(), queryString, this ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/ErrorCounter.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/ErrorCounter.java index 9a28c8e3dd..a520c54347 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/ErrorCounter.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/ErrorCounter.java @@ -37,48 +37,77 @@ import org.hibernate.internal.CoreMessageLogger; * An error handler that counts parsing errors and warnings. */ public class ErrorCounter implements ParseErrorHandler { + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + ErrorCounter.class.getName() + ); - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, ErrorCounter.class.getName()); + private final String hql; private List errorList = new ArrayList(); - private List warningList = new ArrayList(); private List recognitionExceptions = new ArrayList(); + /** + * Constructs an ErrorCounter without knowledge of the HQL, meaning that generated QueryException + * instances *will not* contain the HQL (and will need to be wrapped at a higher level in another + * QueryException). + */ + public ErrorCounter() { + this( null ); + } + + /** + * Constructs an ErrorCounter with knowledge of the HQL, meaning that generated QueryException + * instances *will* contain the HQL. + */ + public ErrorCounter(String hql) { + this.hql = hql; + } + + @Override public void reportError(RecognitionException e) { reportError( e.toString() ); recognitionExceptions.add( e ); - LOG.error(e.toString(), e); + LOG.error( e.toString(), e ); } + @Override public void reportError(String message) { - LOG.error(message); + LOG.error( message ); errorList.add( message ); } + @Override public int getErrorCount() { return errorList.size(); } + @Override public void reportWarning(String message) { - LOG.debug(message); - warningList.add( message ); + LOG.debug( message ); } private String getErrorString() { - StringBuilder buf = new StringBuilder(); - for ( Iterator iterator = errorList.iterator(); iterator.hasNext(); ) { + final StringBuilder buf = new StringBuilder(); + final Iterator iterator = errorList.iterator(); + while ( iterator.hasNext() ) { buf.append( iterator.next() ); - if ( iterator.hasNext() ) buf.append( "\n" ); + if ( iterator.hasNext() ) { + buf.append( "\n" ); + } } return buf.toString(); } + @Override public void throwQueryException() throws QueryException { if ( getErrorCount() > 0 ) { - if (recognitionExceptions.size() > 0) throw QuerySyntaxException.convert(recognitionExceptions.get(0)); - throw new QueryException(getErrorString()); - } - LOG.debug("throwQueryException() : no errors"); + if ( recognitionExceptions.size() > 0 ) { + throw QuerySyntaxException.convert( recognitionExceptions.get( 0 ), hql ); + } + throw new QueryException( getErrorString(), hql ); + } + LOG.debug( "throwQueryException() : no errors" ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlParser.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlParser.java index b9f0bbd8e5..0a886e0e13 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlParser.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlParser.java @@ -52,25 +52,35 @@ import org.hibernate.internal.util.StringHelper; * @author Joshua Davis (pgmjsd@sourceforge.net) */ public final class HqlParser extends HqlBaseParser { + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + HqlParser.class.getName() + ); - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, HqlParser.class.getName()); - - private ParseErrorHandler parseErrorHandler; - private ASTPrinter printer = getASTPrinter(); + private final ParseErrorHandler parseErrorHandler; + private final ASTPrinter printer = getASTPrinter(); private static ASTPrinter getASTPrinter() { return new ASTPrinter( org.hibernate.hql.internal.antlr.HqlTokenTypes.class ); } + /** + * Get a HqlParser instance for the given HQL string. + * + * @param hql The HQL query string + * + * @return The parser. + */ public static HqlParser getInstance(String hql) { - // [jsd] The fix for HHH-558... - HqlLexer lexer = new HqlLexer( new StringReader( hql ) ); - return new HqlParser( lexer ); + return new HqlParser( hql ); } - private HqlParser(TokenStream lexer) { - super( lexer ); - initialize(); + private HqlParser(String hql) { + // The fix for HHH-558... + super( new HqlLexer( new StringReader( hql ) ) ); + parseErrorHandler = new ErrorCounter( hql ); + // Create nodes that track line and column number. + setASTFactory( new HqlASTFactory() ); } @@ -326,12 +336,6 @@ public final class HqlParser extends HqlBaseParser { printer.showAst( ast, pw ); } - private void initialize() { - // Initialize the error handling delegate. - parseErrorHandler = new ErrorCounter(); - setASTFactory(new HqlASTFactory()); // Create nodes that track line and column number. - } - @Override public void weakKeywords() throws TokenStreamException { diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlSqlWalker.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlSqlWalker.java index 95cba36400..8f32783230 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlSqlWalker.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/HqlSqlWalker.java @@ -170,7 +170,7 @@ public class HqlSqlWalker extends HqlSqlBaseWalker implements ErrorReporter, Par String collectionRole) { setASTFactory( new SqlASTFactory( this ) ); // Initialize the error handling delegate. - this.parseErrorHandler = new ErrorCounter(); + this.parseErrorHandler = new ErrorCounter( qti.getQueryString() ); this.queryTranslatorImpl = qti; this.sessionFactoryHelper = new SessionFactoryHelper( sfi ); this.literalProcessor = new LiteralProcessor( this ); diff --git a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QuerySyntaxException.java b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QuerySyntaxException.java index ea97a8ce49..c651ecdd15 100644 --- a/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QuerySyntaxException.java +++ b/hibernate-core/src/main/java/org/hibernate/hql/internal/ast/QuerySyntaxException.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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.hql.internal.ast; import antlr.RecognitionException; @@ -33,23 +32,57 @@ import org.hibernate.QueryException; * @author josh */ public class QuerySyntaxException extends QueryException { - + /** + * Constructs a QuerySyntaxException + * + * @param message Message explaining the condition that led to the exception + */ public QuerySyntaxException(String message) { super( message ); } + /** + * Constructs a QuerySyntaxException + * + * @param message Message explaining the condition that led to the exception + * @param hql The hql query that was being parsed/analyzed + */ public QuerySyntaxException(String message, String hql) { super( message, hql ); } + /** + * Intended for use solely from {@link #generateQueryException(String)} + * + * @param message Message explaining the condition that led to the exception + * @param queryString The hql query that was being parsed/analyzed + * @param cause The cause, generally another QuerySyntaxException + */ protected QuerySyntaxException(String message, String queryString, Exception cause) { super( message, queryString, cause ); } + /** + * Converts the given ANTLR RecognitionException into a QuerySyntaxException. The RecognitionException + * does not become the cause because ANTLR exceptions are not serializable. + * + * @param e The ANTLR exception + * + * @return The QuerySyntaxException + */ public static QuerySyntaxException convert(RecognitionException e) { return convert( e, null ); } + /** + * Converts the given ANTLR RecognitionException into a QuerySyntaxException. The RecognitionException + * does not become the cause because ANTLR exceptions are not serializable. + * + * @param e The ANTLR exception + * @param hql The query string + * + * @return The QuerySyntaxException + */ public static QuerySyntaxException convert(RecognitionException e, String hql) { String positionInfo = e.getLine() > 0 && e.getColumn() > 0 ? " near line " + e.getLine() + ", column " + e.getColumn() @@ -58,7 +91,7 @@ public class QuerySyntaxException extends QueryException { } @Override - protected QueryException doWrapWithQueryString(String queryString) { + protected QueryException generateQueryException(String queryString) { return new QuerySyntaxException( getOriginalMessage(), queryString, this ); } } From 42fd32a81aa6a7293785effff587635875e4f979 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Fri, 26 Apr 2013 11:19:54 -0500 Subject: [PATCH 17/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../hibernate/engine/OptimisticLockStyle.java | 2 ++ .../engine/ResultSetMappingDefinition.java | 11 ++++++- .../internal/ConfigurationServiceImpl.java | 21 +++++++++++-- .../ConfigurationServiceInitiator.java | 6 ++++ .../engine/config/internal/package-info.java | 28 +++++++++++++++++ .../hibernate/engine/config/package-info.java | 29 ++++++++++++++++++ .../engine/config/spi/package-info.java | 28 +++++++++++++++++ .../engine/internal/package-info.java | 30 +++++++++++++++++++ 8 files changed, 151 insertions(+), 4 deletions(-) create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/config/internal/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/config/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/config/spi/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/internal/package-info.java diff --git a/hibernate-core/src/main/java/org/hibernate/engine/OptimisticLockStyle.java b/hibernate-core/src/main/java/org/hibernate/engine/OptimisticLockStyle.java index 3d63e76dc9..8b801167b2 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/OptimisticLockStyle.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/OptimisticLockStyle.java @@ -24,6 +24,8 @@ package org.hibernate.engine; /** + * Describes how an entity should be optimistically locked. + * * @author Steve Ebersole */ public enum OptimisticLockStyle { diff --git a/hibernate-core/src/main/java/org/hibernate/engine/ResultSetMappingDefinition.java b/hibernate-core/src/main/java/org/hibernate/engine/ResultSetMappingDefinition.java index 18152c5156..b87cad9d79 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/ResultSetMappingDefinition.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/ResultSetMappingDefinition.java @@ -35,10 +35,14 @@ import org.hibernate.engine.query.spi.sql.NativeSQLQueryReturn; * @author Emmanuel Bernard */ public class ResultSetMappingDefinition implements Serializable { - private final String name; private final List queryReturns = new ArrayList(); + /** + * Constructs a ResultSetMappingDefinition + * + * @param name The mapping name + */ public ResultSetMappingDefinition(String name) { this.name = name; } @@ -47,6 +51,11 @@ public class ResultSetMappingDefinition implements Serializable { return name; } + /** + * Adds a return. + * + * @param queryReturn The return + */ public void addQueryReturn(NativeSQLQueryReturn queryReturn) { queryReturns.add( queryReturn ); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/config/internal/ConfigurationServiceImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/config/internal/ConfigurationServiceImpl.java index 5118c5e782..e7627e7670 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/config/internal/ConfigurationServiceImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/config/internal/ConfigurationServiceImpl.java @@ -36,6 +36,8 @@ import org.hibernate.service.spi.ServiceRegistryAwareService; import org.hibernate.service.spi.ServiceRegistryImplementor; /** + * The standard ConfigurationService implementation + * * @author Steve Ebersole */ public class ConfigurationServiceImpl implements ConfigurationService, ServiceRegistryAwareService { @@ -43,9 +45,15 @@ public class ConfigurationServiceImpl implements ConfigurationService, ServiceRe CoreMessageLogger.class, ConfigurationServiceImpl.class.getName() ); + private final Map settings; private ServiceRegistryImplementor serviceRegistry; + /** + * Constructs a ConfigurationServiceImpl + * + * @param settings The map of settings + */ @SuppressWarnings( "unchecked" ) public ConfigurationServiceImpl(Map settings) { this.settings = Collections.unmodifiableMap( settings ); @@ -75,18 +83,25 @@ public class ConfigurationServiceImpl implements ConfigurationService, ServiceRe return converter.convert( value ); } + @Override public T getSetting(String name, Class expected, T defaultValue) { - Object value = settings.get( name ); - T target = cast( expected, value ); + final Object value = settings.get( name ); + final T target = cast( expected, value ); return target !=null ? target : defaultValue; } + @Override + @SuppressWarnings("unchecked") public T cast(Class expected, Object candidate){ - if(candidate == null) return null; + if (candidate == null) { + return null; + } + if ( expected.isInstance( candidate ) ) { return (T) candidate; } + Class target; if ( Class.class.isInstance( candidate ) ) { target = Class.class.cast( candidate ); diff --git a/hibernate-core/src/main/java/org/hibernate/engine/config/internal/ConfigurationServiceInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/config/internal/ConfigurationServiceInitiator.java index ff382aeb87..7d98da0c63 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/config/internal/ConfigurationServiceInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/config/internal/ConfigurationServiceInitiator.java @@ -30,11 +30,17 @@ import org.hibernate.engine.config.spi.ConfigurationService; import org.hibernate.service.spi.ServiceRegistryImplementor; /** + * The ServiceInitiator for the ConfigurationService + * * @author Steve Ebersole */ public class ConfigurationServiceInitiator implements StandardServiceInitiator { + /** + * Singleton access + */ public static final ConfigurationServiceInitiator INSTANCE = new ConfigurationServiceInitiator(); + @Override public ConfigurationService initiateService(Map configurationValues, ServiceRegistryImplementor registry) { return new ConfigurationServiceImpl( configurationValues ); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/config/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/config/internal/package-info.java new file mode 100644 index 0000000000..56a759759e --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/engine/config/internal/package-info.java @@ -0,0 +1,28 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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 + */ + +/** + * Internal support for the configuration service implementation + */ +package org.hibernate.engine.config.internal; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/config/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/config/package-info.java new file mode 100644 index 0000000000..3de101fdac --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/engine/config/package-info.java @@ -0,0 +1,29 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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 for the configuration service, which provides access to configuration settings as part of a + * ServiceRegistry + */ +package org.hibernate.engine.config; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/config/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/config/spi/package-info.java new file mode 100644 index 0000000000..abf2f65b5a --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/engine/config/spi/package-info.java @@ -0,0 +1,28 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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 + */ + +/** + * SPI Package for the configuration service. + */ +package org.hibernate.engine.config.spi; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/package-info.java new file mode 100644 index 0000000000..d834aad232 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/package-info.java @@ -0,0 +1,30 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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 + */ + +/** + * Support for many of the internal workings of Hibernate. + * + * See also the {@link org.hibernate.internal} package. + */ +package org.hibernate.engine.internal; From 48331ed8cf50c4862bb0c3304571430ed4070c66 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Fri, 26 Apr 2013 11:36:58 -0500 Subject: [PATCH 18/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../java/org/hibernate/engine/FetchStrategy.java | 11 +++++++---- .../engine/internal/NaturalIdXrefDelegate.java | 16 ++++++++++++---- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/engine/FetchStrategy.java b/hibernate-core/src/main/java/org/hibernate/engine/FetchStrategy.java index 8264eee79a..6a1ec5d7a3 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/FetchStrategy.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/FetchStrategy.java @@ -24,10 +24,7 @@ package org.hibernate.engine; /** - * Describes the strategy for fetching an association - *

      - * todo not really a fan of the name. not sure of a better one though. - * I'd almost rather see this be called the style, but then what to call FetchStyle? HowToFetch? + * Describes the strategy for fetching an association, which includes both when and how. * * @author Steve Ebersole */ @@ -35,6 +32,12 @@ public class FetchStrategy { private final FetchTiming timing; private final FetchStyle style; + /** + * Constructs a FetchStrategy. + * + * @param timing The fetch timing (the when) + * @param style The fetch style (the how). + */ public FetchStrategy(FetchTiming timing, FetchStyle style) { this.timing = timing; this.style = style; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdXrefDelegate.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdXrefDelegate.java index d230eb7b7b..5001f36df2 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdXrefDelegate.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdXrefDelegate.java @@ -57,6 +57,11 @@ public class NaturalIdXrefDelegate { private final StatefulPersistenceContext persistenceContext; private final Map naturalIdResolutionCacheMap = new ConcurrentHashMap(); + /** + * Constructs a NaturalIdXrefDelegate + * + * @param persistenceContext The persistence context that owns this delegate + */ public NaturalIdXrefDelegate(StatefulPersistenceContext persistenceContext) { this.persistenceContext = persistenceContext; } @@ -105,7 +110,7 @@ public class NaturalIdXrefDelegate { persister = locatePersisterForKey( persister ); validateNaturalId( persister, naturalIdValues ); - NaturalIdResolutionCache entityNaturalIdResolutionCache = naturalIdResolutionCacheMap.get( persister ); + final NaturalIdResolutionCache entityNaturalIdResolutionCache = naturalIdResolutionCacheMap.get( persister ); Object[] sessionCachedNaturalIdValues = null; if ( entityNaturalIdResolutionCache != null ) { final CachedNaturalId cachedNaturalId = entityNaturalIdResolutionCache.pkToNaturalIdMap @@ -142,7 +147,7 @@ public class NaturalIdXrefDelegate { * @return {@code true} if the given naturalIdValues match the current cached values; {@code false} otherwise. */ public boolean sameAsCached(EntityPersister persister, Serializable pk, Object[] naturalIdValues) { - NaturalIdResolutionCache entityNaturalIdResolutionCache = naturalIdResolutionCacheMap.get( persister ); + final NaturalIdResolutionCache entityNaturalIdResolutionCache = naturalIdResolutionCacheMap.get( persister ); return entityNaturalIdResolutionCache != null && entityNaturalIdResolutionCache.sameAsCached( pk, naturalIdValues ); } @@ -302,7 +307,7 @@ public class NaturalIdXrefDelegate { Collection pks = null; - NaturalIdResolutionCache entityNaturalIdResolutionCache = naturalIdResolutionCacheMap.get( persister ); + final NaturalIdResolutionCache entityNaturalIdResolutionCache = naturalIdResolutionCacheMap.get( persister ); if ( entityNaturalIdResolutionCache != null ) { pks = entityNaturalIdResolutionCache.pkToNaturalIdMap.keySet(); } @@ -369,7 +374,7 @@ public class NaturalIdXrefDelegate { for ( int naturalIdPropertyIndex : naturalIdPropertyIndexes ) { final Type type = persister.getPropertyType( persister.getPropertyNames()[ naturalIdPropertyIndex ] ); naturalIdTypes[i] = type; - int elementHashCode = values[i] == null ? 0 :type.getHashCode( values[i], persister.getFactory() ); + final int elementHashCode = values[i] == null ? 0 :type.getHashCode( values[i], persister.getFactory() ); hashCodeCalculation = prime * hashCodeCalculation + elementHashCode; i++; } @@ -491,6 +496,9 @@ public class NaturalIdXrefDelegate { } } + /** + * Clear the resolution cache + */ public void clear() { naturalIdResolutionCacheMap.clear(); } From fc02da1c12f6a7487b56e76cf817dc72da8314e6 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Fri, 26 Apr 2013 12:30:34 -0500 Subject: [PATCH 19/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../hibernate/engine/internal/Cascade.java | 175 +++++++----------- .../engine/internal/CascadePoint.java | 82 ++++++++ .../AbstractFlushingEventListener.java | 4 +- .../internal/AbstractSaveEventListener.java | 15 +- .../internal/DefaultDeleteEventListener.java | 15 +- .../internal/DefaultEvictEventListener.java | 4 +- .../internal/DefaultLockEventListener.java | 8 +- .../internal/DefaultMergeEventListener.java | 4 +- .../internal/DefaultRefreshEventListener.java | 10 +- .../DefaultReplicateEventListener.java | 8 +- .../DefaultSaveOrUpdateEventListener.java | 6 +- .../hibernate/type/ForeignKeyDirection.java | 23 ++- 12 files changed, 212 insertions(+), 142 deletions(-) create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/internal/CascadePoint.java diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/Cascade.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/Cascade.java index e4776059fe..943e0a9db5 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/Cascade.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/Cascade.java @@ -37,11 +37,9 @@ import org.hibernate.engine.spi.CascadeStyle; import org.hibernate.engine.spi.CascadingAction; import org.hibernate.engine.spi.CollectionEntry; import org.hibernate.engine.spi.EntityEntry; -import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.Status; import org.hibernate.event.spi.EventSource; import org.hibernate.internal.CoreMessageLogger; -import org.hibernate.internal.util.collections.CollectionHelper; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.pretty.MessageHelper; @@ -59,76 +57,35 @@ import org.hibernate.type.Type; * @see org.hibernate.engine.spi.CascadingAction */ public final class Cascade { + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + Cascade.class.getName() + ); + + private final CascadingAction action; + private final EventSource eventSource; + private CascadePoint cascadePoint; /** - * A cascade point that occurs just after the insertion of the parent entity and - * just before deletion + * Constructs a Cascade + * + * @param action The action we are cascading + * @param cascadePoint The point in the action at which we are trying to cascade currently + * @param eventSource The session */ - public static final int AFTER_INSERT_BEFORE_DELETE = 1; - /** - * A cascade point that occurs just before the insertion of the parent entity and - * just after deletion - */ - public static final int BEFORE_INSERT_AFTER_DELETE = 2; - /** - * A cascade point that occurs just after the insertion of the parent entity and - * just before deletion, inside a collection - */ - public static final int AFTER_INSERT_BEFORE_DELETE_VIA_COLLECTION = 3; - /** - * A cascade point that occurs just after update of the parent entity - */ - public static final int AFTER_UPDATE = 0; - /** - * A cascade point that occurs just before the session is flushed - */ - public static final int BEFORE_FLUSH = 0; - /** - * A cascade point that occurs just after eviction of the parent entity from the - * session cache - */ - public static final int AFTER_EVICT = 0; - /** - * A cascade point that occurs just after locking a transient parent entity into the - * session cache - */ - public static final int BEFORE_REFRESH = 0; - /** - * A cascade point that occurs just after refreshing a parent entity - */ - public static final int AFTER_LOCK = 0; - /** - * A cascade point that occurs just before merging from a transient parent entity into - * the object in the session cache - */ - public static final int BEFORE_MERGE = 0; - - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, Cascade.class.getName()); - - - private int cascadeTo; - private EventSource eventSource; - private CascadingAction action; - - public Cascade(final CascadingAction action, final int cascadeTo, final EventSource eventSource) { - this.cascadeTo = cascadeTo; + public Cascade(final CascadingAction action, final CascadePoint cascadePoint, final EventSource eventSource) { + this.cascadePoint = cascadePoint; this.eventSource = eventSource; this.action = action; } - private SessionFactoryImplementor getFactory() { - return eventSource.getFactory(); - } - /** * Cascade an action from the parent entity instance to all its children. * * @param persister The parent's entity persister * @param parent The parent reference. - * @throws HibernateException */ - public void cascade(final EntityPersister persister, final Object parent) - throws HibernateException { + public void cascade(final EntityPersister persister, final Object parent) { cascade( persister, parent, null ); } @@ -140,20 +97,18 @@ public final class Cascade { * @param parent The parent reference. * @param anything Anything ;) Typically some form of cascade-local cache * which is specific to each CascadingAction type - * @throws HibernateException */ - public void cascade(final EntityPersister persister, final Object parent, final Object anything) - throws HibernateException { - - if ( persister.hasCascades() || action.requiresNoCascadeChecking() ) { // performance opt + public void cascade(final EntityPersister persister, final Object parent, final Object anything) { + if ( persister.hasCascades() || action.requiresNoCascadeChecking() ) { + // performance opt final boolean traceEnabled = LOG.isTraceEnabled(); if ( traceEnabled ) { LOG.tracev( "Processing cascade {0} for: {1}", action, persister.getEntityName() ); } - Type[] types = persister.getPropertyTypes(); - CascadeStyle[] cascadeStyles = persister.getPropertyCascadeStyles(); - boolean hasUninitializedLazyProperties = persister.hasUninitializedLazyProperties( parent ); + final Type[] types = persister.getPropertyTypes(); + final CascadeStyle[] cascadeStyles = persister.getPropertyCascadeStyles(); + final boolean hasUninitializedLazyProperties = persister.hasUninitializedLazyProperties( parent ); for ( int i=0; i componentPathStack = new Stack(); private boolean cascadeAssociationNow(AssociationType associationType) { - return associationType.getForeignKeyDirection().cascadeNow(cascadeTo); + return associationType.getForeignKeyDirection().cascadeNow( cascadePoint ); } private void cascadeComponent( @@ -300,12 +255,12 @@ public final class Cascade { final String componentPropertyName, final Object anything) { componentPathStack.push( componentPropertyName ); - Object[] children = componentType.getPropertyValues( child, eventSource ); - Type[] types = componentType.getSubtypes(); + final Object[] children = componentType.getPropertyValues( child, eventSource ); + final Type[] types = componentType.getSubtypes(); for ( int i=0; i Date: Fri, 26 Apr 2013 14:10:54 -0500 Subject: [PATCH 20/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../engine/internal/Collections.java | 142 ++--- .../engine/internal/EntityEntryContext.java | 112 +++- .../engine/internal/ForeignKeys.java | 265 +++++---- .../hibernate/engine/internal/JoinHelper.java | 117 ++-- .../engine/internal/JoinSequence.java | 560 +++++++++++------- 5 files changed, 753 insertions(+), 443 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/Collections.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/Collections.java index 9e2f3baf73..924eda329d 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/Collections.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/Collections.java @@ -47,29 +47,29 @@ import org.jboss.logging.Logger; * @author Gavin King */ public final class Collections { - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, Collections.class.getName()); - - private Collections() { - } + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + Collections.class.getName() + ); /** * record the fact that this collection was dereferenced * * @param coll The collection to be updated by un-reachability. + * @param session The session */ - @SuppressWarnings( {"JavaDoc"}) public static void processUnreachableCollection(PersistentCollection coll, SessionImplementor session) { if ( coll.getOwner()==null ) { - processNeverReferencedCollection(coll, session); + processNeverReferencedCollection( coll, session ); } else { - processDereferencedCollection(coll, session); + processDereferencedCollection( coll, session ); } } private static void processDereferencedCollection(PersistentCollection coll, SessionImplementor session) { final PersistenceContext persistenceContext = session.getPersistenceContext(); - CollectionEntry entry = persistenceContext.getCollectionEntry(coll); + final CollectionEntry entry = persistenceContext.getCollectionEntry( coll ); final CollectionPersister loadedPersister = entry.getLoadedPersister(); if ( loadedPersister != null && LOG.isDebugEnabled() ) { @@ -82,15 +82,15 @@ public final class Collections { } // do a check - boolean hasOrphanDelete = loadedPersister != null && loadedPersister.hasOrphanDelete(); - if (hasOrphanDelete) { + final boolean hasOrphanDelete = loadedPersister != null && loadedPersister.hasOrphanDelete(); + if ( hasOrphanDelete ) { Serializable ownerId = loadedPersister.getOwnerEntityPersister().getIdentifier( coll.getOwner(), session ); if ( ownerId == null ) { // the owning entity may have been deleted and its identifier unset due to // identifier-rollback; in which case, try to look up its identifier from // the persistence context if ( session.getFactory().getSettings().isIdentifierRollbackEnabled() ) { - EntityEntry ownerEntry = persistenceContext.getEntry( coll.getOwner() ); + final EntityEntry ownerEntry = persistenceContext.getEntry( coll.getOwner() ); if ( ownerEntry != null ) { ownerId = ownerEntry.getId(); } @@ -99,15 +99,15 @@ public final class Collections { throw new AssertionFailure( "Unable to determine collection owner identifier for orphan-delete processing" ); } } - EntityKey key = session.generateEntityKey( ownerId, loadedPersister.getOwnerEntityPersister() ); - Object owner = persistenceContext.getEntity(key); + final EntityKey key = session.generateEntityKey( ownerId, loadedPersister.getOwnerEntityPersister() ); + final Object owner = persistenceContext.getEntity( key ); if ( owner == null ) { throw new AssertionFailure( "collection owner not associated with session: " + loadedPersister.getRole() ); } - EntityEntry e = persistenceContext.getEntry(owner); + final EntityEntry e = persistenceContext.getEntry( owner ); //only collections belonging to deleted entities are allowed to be dereferenced in the case of orphan delete if ( e != null && e.getStatus() != Status.DELETED && e.getStatus() != Status.GONE ) { throw new HibernateException( @@ -118,23 +118,27 @@ public final class Collections { } // do the work - entry.setCurrentPersister(null); - entry.setCurrentKey(null); + entry.setCurrentPersister( null ); + entry.setCurrentKey( null ); prepareCollectionForUpdate( coll, entry, session.getFactory() ); } private static void processNeverReferencedCollection(PersistentCollection coll, SessionImplementor session) - throws HibernateException { - + throws HibernateException { final PersistenceContext persistenceContext = session.getPersistenceContext(); - CollectionEntry entry = persistenceContext.getCollectionEntry(coll); + final CollectionEntry entry = persistenceContext.getCollectionEntry( coll ); if ( LOG.isDebugEnabled() ) { - LOG.debugf( "Found collection with unloaded owner: %s", + LOG.debugf( + "Found collection with unloaded owner: %s", MessageHelper.collectionInfoString( - entry.getLoadedPersister(), coll, - entry.getLoadedKey(), session ) ); + entry.getLoadedPersister(), + coll, + entry.getLoadedKey(), + session + ) + ); } entry.setCurrentPersister( entry.getLoadedPersister() ); @@ -154,13 +158,11 @@ public final class Collections { */ public static void processReachableCollection( PersistentCollection collection, - CollectionType type, - Object entity, - SessionImplementor session) { - - collection.setOwner(entity); - - CollectionEntry ce = session.getPersistenceContext().getCollectionEntry(collection); + CollectionType type, + Object entity, + SessionImplementor session) { + collection.setOwner( entity ); + final CollectionEntry ce = session.getPersistenceContext().getCollectionEntry( collection ); if ( ce == null ) { // refer to comment in StatefulPersistenceContext.addCollection() @@ -175,30 +177,35 @@ public final class Collections { if ( ce.isReached() ) { // We've been here before throw new HibernateException( - "Found shared references to a collection: " + - type.getRole() + "Found shared references to a collection: " + type.getRole() ); } - ce.setReached(true); + ce.setReached( true ); - SessionFactoryImplementor factory = session.getFactory(); - CollectionPersister persister = factory.getCollectionPersister( type.getRole() ); - ce.setCurrentPersister(persister); - ce.setCurrentKey( type.getKeyOfOwner(entity, session) ); //TODO: better to pass the id in as an argument? + final SessionFactoryImplementor factory = session.getFactory(); + final CollectionPersister persister = factory.getCollectionPersister( type.getRole() ); + ce.setCurrentPersister( persister ); + //TODO: better to pass the id in as an argument? + ce.setCurrentKey( type.getKeyOfOwner( entity, session ) ); - if (LOG.isDebugEnabled()) { - if (collection.wasInitialized()) LOG.debugf("Collection found: %s, was: %s (initialized)", - MessageHelper.collectionInfoString(persister, collection, ce.getCurrentKey(), session), - MessageHelper.collectionInfoString(ce.getLoadedPersister(), collection, - ce.getLoadedKey(), - session)); - else LOG.debugf("Collection found: %s, was: %s (uninitialized)", - MessageHelper.collectionInfoString(persister, collection, ce.getCurrentKey(), session), - MessageHelper.collectionInfoString(ce.getLoadedPersister(), collection, ce.getLoadedKey(), session)); - } + if ( LOG.isDebugEnabled() ) { + if ( collection.wasInitialized() ) { + LOG.debugf( + "Collection found: %s, was: %s (initialized)", + MessageHelper.collectionInfoString( persister, collection, ce.getCurrentKey(), session ), + MessageHelper.collectionInfoString( ce.getLoadedPersister(), collection, ce.getLoadedKey(), session ) + ); + } + else { + LOG.debugf( + "Collection found: %s, was: %s (uninitialized)", + MessageHelper.collectionInfoString( persister, collection, ce.getCurrentKey(), session ), + MessageHelper.collectionInfoString( ce.getLoadedPersister(), collection, ce.getLoadedKey(), session ) + ); + } + } prepareCollectionForUpdate( collection, ce, factory ); - } /** @@ -209,9 +216,8 @@ public final class Collections { @SuppressWarnings( {"JavaDoc"}) private static void prepareCollectionForUpdate( PersistentCollection collection, - CollectionEntry entry, - SessionFactoryImplementor factory) { - + CollectionEntry entry, + SessionFactoryImplementor factory) { if ( entry.isProcessed() ) { throw new AssertionFailure( "collection was processed twice by flush()" ); } @@ -219,37 +225,33 @@ public final class Collections { final CollectionPersister loadedPersister = entry.getLoadedPersister(); final CollectionPersister currentPersister = entry.getCurrentPersister(); - if ( loadedPersister != null || currentPersister != null ) { // it is or was referenced _somewhere_ + if ( loadedPersister != null || currentPersister != null ) { + // it is or was referenced _somewhere_ - boolean ownerChanged = loadedPersister != currentPersister || // if either its role changed, - !currentPersister - .getKeyType().isEqual( // or its key changed - entry.getLoadedKey(), - entry.getCurrentKey(), - factory - ); - - if (ownerChanged) { + // if either its role changed, or its key changed + final boolean ownerChanged = loadedPersister != currentPersister + || !currentPersister.getKeyType().isEqual( entry.getLoadedKey(), entry.getCurrentKey(), factory ); + if ( ownerChanged ) { // do a check - final boolean orphanDeleteAndRoleChanged = loadedPersister != null && - currentPersister != null && - loadedPersister.hasOrphanDelete(); + final boolean orphanDeleteAndRoleChanged = + loadedPersister != null && currentPersister != null && loadedPersister.hasOrphanDelete(); if (orphanDeleteAndRoleChanged) { throw new HibernateException( - "Don't change the reference to a collection with cascade=\"all-delete-orphan\": " + - loadedPersister.getRole() + "Don't change the reference to a collection with delete-orphan enabled : " + + loadedPersister.getRole() ); } // do the work if ( currentPersister != null ) { - entry.setDorecreate( true ); // we will need to create new entries + entry.setDorecreate( true ); } if ( loadedPersister != null ) { - entry.setDoremove( true ); // we will need to remove ye olde entries + // we will need to remove ye olde entries + entry.setDoremove( true ); if ( entry.isDorecreate() ) { LOG.trace( "Forcing collection initialization" ); collection.forceInitialization(); @@ -260,8 +262,12 @@ public final class Collections { // the collection's elements have changed entry.setDoupdate( true ); } - } + } + /** + * Disallow instantiation + */ + private Collections() { } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/EntityEntryContext.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/EntityEntryContext.java index 0cb3e89e83..21a837e5e4 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/EntityEntryContext.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/EntityEntryContext.java @@ -31,7 +31,6 @@ import java.util.Map; import org.jboss.logging.Logger; -import org.hibernate.AssertionFailure; import org.hibernate.LockMode; import org.hibernate.engine.spi.EntityEntry; import org.hibernate.engine.spi.ManagedEntity; @@ -56,22 +55,31 @@ public class EntityEntryContext { private transient ManagedEntity head; private transient ManagedEntity tail; - private transient int count = 0; + private transient int count; private transient IdentityHashMap nonEnhancedEntityXref; @SuppressWarnings( {"unchecked"}) private transient Map.Entry[] reentrantSafeEntries = new Map.Entry[0]; - private transient boolean dirty = false; + private transient boolean dirty; + /** + * Constructs a EntityEntryContext + */ public EntityEntryContext() { } + /** + * Adds the entity and entry to this context, associating them together + * + * @param entity The entity + * @param entityEntry The entry + */ public void addEntityEntry(Object entity, EntityEntry entityEntry) { // IMPORTANT!!!!! // add is called more than once of some entities. In such cases the first // call is simply setting up a "marker" to avoid infinite looping from reentrancy - // + // any addition (even the double one described above) should invalidate the cross-ref array dirty = true; @@ -127,11 +135,26 @@ public class EntityEntryContext { } } + /** + * Does this entity exist in this context, associated with an EntityEntry? + * + * @param entity The entity to check + * + * @return {@code true} if it is associated with this context + */ public boolean hasEntityEntry(Object entity) { return getEntityEntry( entity ) != null; } + /** + * Retrieve the associated EntityEntry for the entity + * + * @param entity The entity to retrieve the EntityEntry for + * + * @return The associated EntityEntry + */ public EntityEntry getEntityEntry(Object entity) { + // essentially resolve the entity to a ManagedEntity... final ManagedEntity managedEntity; if ( ManagedEntity.class.isInstance( entity ) ) { managedEntity = (ManagedEntity) entity; @@ -143,14 +166,23 @@ public class EntityEntryContext { managedEntity = nonEnhancedEntityXref.get( entity ); } + // and get/return the EntityEntry from the ManagedEntry return managedEntity == null ? null : managedEntity.$$_hibernate_getEntityEntry(); } + /** + * Remove an entity from the context, returning the EntityEntry which was associated with it + * + * @param entity The entity to remove + * + * @return Tjee EntityEntry + */ public EntityEntry removeEntityEntry(Object entity) { dirty = true; + // again, resolve the entity to a ManagedEntity (which may not be possible for non-enhanced)... final ManagedEntity managedEntity; if ( ManagedEntity.class.isInstance( entity ) ) { managedEntity = (ManagedEntity) entity; @@ -162,16 +194,18 @@ public class EntityEntryContext { managedEntity = nonEnhancedEntityXref.remove( entity ); } + // if we could not resolve it, just return (it was not associated with this context) if ( managedEntity == null ) { return null; } // prepare for re-linking... - ManagedEntity previous = managedEntity.$$_hibernate_getPreviousManagedEntity(); - ManagedEntity next = managedEntity.$$_hibernate_getNextManagedEntity(); + final ManagedEntity previous = managedEntity.$$_hibernate_getPreviousManagedEntity(); + final ManagedEntity next = managedEntity.$$_hibernate_getNextManagedEntity(); managedEntity.$$_hibernate_setPreviousManagedEntity( null ); managedEntity.$$_hibernate_setNextManagedEntity( null ); + // re-link count--; if ( count == 0 ) { @@ -203,11 +237,20 @@ public class EntityEntryContext { } } - EntityEntry theEntityEntry = managedEntity.$$_hibernate_getEntityEntry(); + // finally clean out the ManagedEntity and return the associated EntityEntry + final EntityEntry theEntityEntry = managedEntity.$$_hibernate_getEntityEntry(); managedEntity.$$_hibernate_setEntityEntry( null ); return theEntityEntry; } + /** + * The main bugaboo with IdentityMap that warranted this class in the first place. + * + * Return an array of all the entity/EntityEntry pairs in this context. The array is to make sure + * that the iterators built off of it are safe from concurrency/reentrancy + * + * @return The safe array + */ public Map.Entry[] reentrantSafeEntityEntries() { if ( dirty ) { reentrantSafeEntries = new EntityEntryCrossRefImpl[count]; @@ -225,6 +268,9 @@ public class EntityEntryContext { return reentrantSafeEntries; } + /** + * Clear this context of all managed entities + */ public void clear() { dirty = true; @@ -250,6 +296,9 @@ public class EntityEntryContext { reentrantSafeEntries = null; } + /** + * Down-grade locks to NONE for all entities in this context + */ public void downgradeLocks() { if ( head == null ) { return; @@ -263,6 +312,13 @@ public class EntityEntryContext { } } + /** + * JDK serialization hook for serializing + * + * @param oos The stream to write ourselves to + * + * @throws IOException Indicates an IO exception accessing the given stream + */ public void serialize(ObjectOutputStream oos) throws IOException { log.tracef( "Starting serialization of [%s] EntityEntry entries", count ); oos.writeInt( count ); @@ -281,7 +337,17 @@ public class EntityEntryContext { } } - public static EntityEntryContext deserialize(ObjectInputStream ois, StatefulPersistenceContext rtn) throws IOException, ClassNotFoundException { + /** + * JDK serialization hook for deserializing + * + * @param ois The stream to read ourselves from + * @param rtn The persistence context we belong to + * + * @throws IOException Indicates an IO exception accessing the given stream + * @throws ClassNotFoundException Problem reading stream data + */ + public static EntityEntryContext deserialize(ObjectInputStream ois, StatefulPersistenceContext rtn) + throws IOException, ClassNotFoundException { final int count = ois.readInt(); log.tracef( "Starting deserialization of [%s] EntityEntry entries", count ); @@ -332,6 +398,9 @@ public class EntityEntryContext { return count; } + /** + * The wrapper for entity classes which do not implement ManagedEntity + */ private static class ManagedEntityImpl implements ManagedEntity { private final Object entityInstance; private EntityEntry entityEntry; @@ -378,6 +447,28 @@ public class EntityEntryContext { } } + /** + * Used in building the {@link #reentrantSafeEntityEntries()} entries + */ + public static interface EntityEntryCrossRef extends Map.Entry { + /** + * The entity + * + * @return The entity + */ + public Object getEntity(); + + /** + * The associated EntityEntry + * + * @return The EntityEntry associated with the entity in this context + */ + public EntityEntry getEntityEntry(); + } + + /** + * Implementation of the EntityEntryCrossRef interface + */ private static class EntityEntryCrossRefImpl implements EntityEntryCrossRef { private final Object entity; private EntityEntry entityEntry; @@ -414,9 +505,4 @@ public class EntityEntryContext { return old; } } - - public static interface EntityEntryCrossRef extends Map.Entry { - public Object getEntity(); - public EntityEntry getEntityEntry(); - } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/ForeignKeys.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/ForeignKeys.java index 808324f6b1..c67c909d4b 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/ForeignKeys.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/ForeignKeys.java @@ -40,70 +40,81 @@ import org.hibernate.type.Type; /** * Algorithms related to foreign key constraint transparency - * + * * @author Gavin King */ public final class ForeignKeys { - - private ForeignKeys() {} - + + /** + * Delegate for handling nullifying ("null"ing-out) non-cascaded associations + */ public static class Nullifier { - private final boolean isDelete; private final boolean isEarlyInsert; private final SessionImplementor session; private final Object self; - + + /** + * Constructs a Nullifier + * + * @param self The entity + * @param isDelete Are we in the middle of a delete action? + * @param isEarlyInsert Is this an early insert (INSERT generated id strategy)? + * @param session The session + */ public Nullifier(Object self, boolean isDelete, boolean isEarlyInsert, SessionImplementor session) { this.isDelete = isDelete; this.isEarlyInsert = isEarlyInsert; this.session = session; this.self = self; } - + /** - * Nullify all references to entities that have not yet - * been inserted in the database, where the foreign key - * points toward that entity + * Nullify all references to entities that have not yet been inserted in the database, where the foreign key + * points toward that entity. + * + * @param values The entity attribute values + * @param types The entity attribute types */ - public void nullifyTransientReferences(final Object[] values, final Type[] types) - throws HibernateException { + public void nullifyTransientReferences(final Object[] values, final Type[] types) + throws HibernateException { for ( int i = 0; i < types.length; i++ ) { values[i] = nullifyTransientReferences( values[i], types[i] ); } } /** - * Return null if the argument is an "unsaved" entity (ie. - * one with no existing database row), or the input argument - * otherwise. This is how Hibernate avoids foreign key constraint - * violations. + * Return null if the argument is an "unsaved" entity (ie. one with no existing database row), or the + * input argument otherwise. This is how Hibernate avoids foreign key constraint violations. + * + * @param value An entity attribute value + * @param type An entity attribute type */ - private Object nullifyTransientReferences(final Object value, final Type type) - throws HibernateException { + private Object nullifyTransientReferences(final Object value, final Type type) + throws HibernateException { if ( value == null ) { return null; } else if ( type.isEntityType() ) { - EntityType entityType = (EntityType) type; + final EntityType entityType = (EntityType) type; if ( entityType.isOneToOne() ) { return value; } else { - String entityName = entityType.getAssociatedEntityName(); - return isNullifiable(entityName, value) ? null : value; + final String entityName = entityType.getAssociatedEntityName(); + return isNullifiable( entityName, value ) ? null : value; } } else if ( type.isAnyType() ) { - return isNullifiable(null, value) ? null : value; + return isNullifiable( null, value ) ? null : value; } else if ( type.isComponentType() ) { - CompositeType actype = (CompositeType) type; - Object[] subvalues = actype.getPropertyValues(value, session); - Type[] subtypes = actype.getSubtypes(); + final CompositeType actype = (CompositeType) type; + final Object[] subvalues = actype.getPropertyValues( value, session ); + final Type[] subtypes = actype.getSubtypes(); boolean substitute = false; for ( int i = 0; i < subvalues.length; i++ ) { - Object replacement = nullifyTransientReferences( subvalues[i], subtypes[i] ); + final Object replacement = nullifyTransientReferences( subvalues[i], subtypes[i] ); if ( replacement != subvalues[i] ) { substitute = true; subvalues[i] = replacement; @@ -119,20 +130,25 @@ public final class ForeignKeys { return value; } } - + /** - * Determine if the object already exists in the database, + * Determine if the object already exists in the database, * using a "best guess" + * + * @param entityName The name of the entity + * @param object The entity instance */ - private boolean isNullifiable(final String entityName, Object object) - throws HibernateException { - - if (object==LazyPropertyInitializer.UNFETCHED_PROPERTY) return false; //this is kinda the best we can do... - + private boolean isNullifiable(final String entityName, Object object) + throws HibernateException { + if ( object == LazyPropertyInitializer.UNFETCHED_PROPERTY ) { + // this is the best we can do... + return false; + } + if ( object instanceof HibernateProxy ) { // if its an uninitialized proxy it can't be transient - LazyInitializer li = ( (HibernateProxy) object ).getHibernateLazyInitializer(); - if ( li.getImplementation(session) == null ) { + final LazyInitializer li = ( (HibernateProxy) object ).getHibernateLazyInitializer(); + if ( li.getImplementation( session ) == null ) { return false; // ie. we never have to null out a reference to // an uninitialized proxy @@ -142,100 +158,130 @@ public final class ForeignKeys { object = li.getImplementation(); } } - + // if it was a reference to self, don't need to nullify // unless we are using native id generation, in which // case we definitely need to nullify if ( object == self ) { - return isEarlyInsert || ( - isDelete && - session.getFactory() - .getDialect() - .hasSelfReferentialForeignKeyBug() - ); + return isEarlyInsert + || ( isDelete && session.getFactory().getDialect().hasSelfReferentialForeignKeyBug() ); } - + // See if the entity is already bound to this session, if not look at the // entity identifier and assume that the entity is persistent if the // id is not "unsaved" (that is, we rely on foreign keys to keep // database integrity) - - EntityEntry entityEntry = session.getPersistenceContext().getEntry(object); - if ( entityEntry==null ) { - return isTransient(entityName, object, null, session); + + final EntityEntry entityEntry = session.getPersistenceContext().getEntry( object ); + if ( entityEntry == null ) { + return isTransient( entityName, object, null, session ); } else { - return entityEntry.isNullifiable(isEarlyInsert, session); + return entityEntry.isNullifiable( isEarlyInsert, session ); } - + } } /** * Is this instance persistent or detached? - * If assumed is non-null, don't hit the database to make the - * determination, instead assume that value; the client code must be - * prepared to "recover" in the case that this assumed result is incorrect. + *

      + * If assumed is non-null, don't hit the database to make the determination, instead assume that + * value; the client code must be prepared to "recover" in the case that this assumed result is incorrect. + * + * @param entityName The name of the entity + * @param entity The entity instance + * @param assumed The assumed return value, if avoiding database hit is desired + * @param session The session + * + * @return {@code true} if the given entity is not transient (meaning it is either detached/persistent) */ - public static boolean isNotTransient(String entityName, Object entity, Boolean assumed, SessionImplementor session) - throws HibernateException { - if (entity instanceof HibernateProxy) return true; - if ( session.getPersistenceContext().isEntryFor(entity) ) return true; - return !isTransient(entityName, entity, assumed, session); + @SuppressWarnings("SimplifiableIfStatement") + public static boolean isNotTransient(String entityName, Object entity, Boolean assumed, SessionImplementor session) { + if ( entity instanceof HibernateProxy ) { + return true; + } + + if ( session.getPersistenceContext().isEntryFor( entity ) ) { + return true; + } + + // todo : shouldnt assumed be revered here? + + return !isTransient( entityName, entity, assumed, session ); } - + /** * Is this instance, which we know is not persistent, actually transient? - * If assumed is non-null, don't hit the database to make the - * determination, instead assume that value; the client code must be - * prepared to "recover" in the case that this assumed result is incorrect. + *

      + * If assumed is non-null, don't hit the database to make the determination, instead assume that + * value; the client code must be prepared to "recover" in the case that this assumed result is incorrect. + * + * @param entityName The name of the entity + * @param entity The entity instance + * @param assumed The assumed return value, if avoiding database hit is desired + * @param session The session + * + * @return {@code true} if the given entity is transient (unsaved) */ - public static boolean isTransient(String entityName, Object entity, Boolean assumed, SessionImplementor session) - throws HibernateException { - - if (entity== LazyPropertyInitializer.UNFETCHED_PROPERTY) { + @SuppressWarnings("UnnecessaryUnboxing") + public static boolean isTransient(String entityName, Object entity, Boolean assumed, SessionImplementor session) { + if ( entity == LazyPropertyInitializer.UNFETCHED_PROPERTY ) { // an unfetched association can only point to // an entity that already exists in the db return false; } - + // let the interceptor inspect the instance to decide - Boolean isUnsaved = session.getInterceptor().isTransient(entity); - if (isUnsaved!=null) return isUnsaved.booleanValue(); - + Boolean isUnsaved = session.getInterceptor().isTransient( entity ); + if ( isUnsaved != null ) { + return isUnsaved.booleanValue(); + } + // let the persister inspect the instance to decide - EntityPersister persister = session.getEntityPersister(entityName, entity); - isUnsaved = persister.isTransient(entity, session); - if (isUnsaved!=null) return isUnsaved.booleanValue(); + final EntityPersister persister = session.getEntityPersister( entityName, entity ); + isUnsaved = persister.isTransient( entity, session ); + if ( isUnsaved != null ) { + return isUnsaved.booleanValue(); + } // we use the assumed value, if there is one, to avoid hitting // the database - if (assumed!=null) return assumed.booleanValue(); - + if ( assumed != null ) { + return assumed.booleanValue(); + } + // hit the database, after checking the session cache for a snapshot - Object[] snapshot = session.getPersistenceContext().getDatabaseSnapshot( + final Object[] snapshot = session.getPersistenceContext().getDatabaseSnapshot( persister.getIdentifier( entity, session ), persister ); - return snapshot==null; + return snapshot == null; } /** * Return the identifier of the persistent or transient object, or throw * an exception if the instance is "unsaved" - * - * Used by OneToOneType and ManyToOneType to determine what id value should - * be used for an object that may or may not be associated with the session. - * This does a "best guess" using any/all info available to use (not just the + *

      + * Used by OneToOneType and ManyToOneType to determine what id value should + * be used for an object that may or may not be associated with the session. + * This does a "best guess" using any/all info available to use (not just the * EntityEntry). + * + * @param entityName The name of the entity + * @param object The entity instance + * @param session The session + * + * @return The identifier + * + * @throws TransientObjectException if the entity is transient (does not yet have an identifier) */ public static Serializable getEntityIdentifierIfNotUnsaved( - final String entityName, - final Object object, - final SessionImplementor session) - throws HibernateException { + final String entityName, + final Object object, + final SessionImplementor session) throws TransientObjectException { if ( object == null ) { return null; } @@ -245,10 +291,10 @@ public final class ForeignKeys { // context-entity-identifier returns null explicitly if the entity // is not associated with the persistence context; so make some // deeper checks... - if ( isTransient(entityName, object, Boolean.FALSE, session) ) { + if ( isTransient( entityName, object, Boolean.FALSE, session ) ) { throw new TransientObjectException( "object references an unsaved transient instance - save the transient instance before flushing: " + - (entityName == null ? session.guessEntityName( object ) : entityName) + (entityName == null ? session.guessEntityName( object ) : entityName) ); } id = session.getEntityPersister( entityName, object ).getIdentifier( object, session ); @@ -265,9 +311,9 @@ public final class ForeignKeys { * @param entityName - the entity name * @param entity - the entity instance * @param values - insertable properties of the object (including backrefs), - * possibly with substitutions + * possibly with substitutions * @param isEarlyInsert - true if the entity needs to be executed as soon as possible - * (e.g., to generate an ID) + * (e.g., to generate an ID) * @param session - the session * * @return the transient unsaved entity dependencies that are non-nullable, @@ -278,18 +324,16 @@ public final class ForeignKeys { Object entity, Object[] values, boolean isEarlyInsert, - SessionImplementor session - ) { - Nullifier nullifier = new Nullifier( entity, false, isEarlyInsert, session ); + SessionImplementor session) { + final Nullifier nullifier = new Nullifier( entity, false, isEarlyInsert, session ); final EntityPersister persister = session.getEntityPersister( entityName, entity ); final String[] propertyNames = persister.getPropertyNames(); final Type[] types = persister.getPropertyTypes(); final boolean[] nullability = persister.getPropertyNullability(); - NonNullableTransientDependencies nonNullableTransientEntities = new NonNullableTransientDependencies(); + final NonNullableTransientDependencies nonNullableTransientEntities = new NonNullableTransientDependencies(); for ( int i = 0; i < types.length; i++ ) { collectNonNullableTransientEntities( nullifier, - i, values[i], propertyNames[i], types[i], @@ -303,7 +347,6 @@ public final class ForeignKeys { private static void collectNonNullableTransientEntities( Nullifier nullifier, - int i, Object value, String propertyName, Type type, @@ -311,33 +354,32 @@ public final class ForeignKeys { SessionImplementor session, NonNullableTransientDependencies nonNullableTransientEntities) { if ( value == null ) { - return; // EARLY RETURN + return; } - if ( type.isEntityType() ) { - EntityType entityType = (EntityType) type; - if ( ! isNullable && - ! entityType.isOneToOne() && - nullifier.isNullifiable( entityType.getAssociatedEntityName(), value ) ) { + + if ( type.isEntityType() ) { + final EntityType entityType = (EntityType) type; + if ( !isNullable + && !entityType.isOneToOne() + && nullifier.isNullifiable( entityType.getAssociatedEntityName(), value ) ) { nonNullableTransientEntities.add( propertyName, value ); } } else if ( type.isAnyType() ) { - if ( ! isNullable && - nullifier.isNullifiable( null, value ) ) { + if ( !isNullable && nullifier.isNullifiable( null, value ) ) { nonNullableTransientEntities.add( propertyName, value ); } } else if ( type.isComponentType() ) { - CompositeType actype = (CompositeType) type; - boolean[] subValueNullability = actype.getPropertyNullability(); + final CompositeType actype = (CompositeType) type; + final boolean[] subValueNullability = actype.getPropertyNullability(); if ( subValueNullability != null ) { - String[] subPropertyNames = actype.getPropertyNames(); - Object[] subvalues = actype.getPropertyValues(value, session); - Type[] subtypes = actype.getSubtypes(); + final String[] subPropertyNames = actype.getPropertyNames(); + final Object[] subvalues = actype.getPropertyValues( value, session ); + final Type[] subtypes = actype.getSubtypes(); for ( int j = 0; j < subvalues.length; j++ ) { collectNonNullableTransientEntities( nullifier, - j, subvalues[j], subPropertyNames[j], subtypes[j], @@ -349,4 +391,11 @@ public final class ForeignKeys { } } } + + /** + * Disallow instantiation + */ + private ForeignKeys() { + } + } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/JoinHelper.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/JoinHelper.java index d195654a15..647da369c7 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/JoinHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/JoinHelper.java @@ -36,45 +36,40 @@ import org.hibernate.type.AssociationType; * @author Gavin King */ public final class JoinHelper { - - private JoinHelper() {} - /** - * Get the aliased columns of the owning entity which are to + * Get the aliased columns of the owning entity which are to * be used in the join */ public static String[] getAliasedLHSColumnNames( - AssociationType type, - String alias, - int property, + AssociationType type, + String alias, + int property, OuterJoinLoadable lhsPersister, - Mapping mapping - ) { - return getAliasedLHSColumnNames(type, alias, property, 0, lhsPersister, mapping); + Mapping mapping) { + return getAliasedLHSColumnNames( type, alias, property, 0, lhsPersister, mapping ); } - + /** - * Get the columns of the owning entity which are to + * Get the columns of the owning entity which are to * be used in the join */ public static String[] getLHSColumnNames( - AssociationType type, - int property, + AssociationType type, + int property, OuterJoinLoadable lhsPersister, - Mapping mapping - ) { - return getLHSColumnNames(type, property, 0, lhsPersister, mapping); + Mapping mapping) { + return getLHSColumnNames( type, property, 0, lhsPersister, mapping ); } - + /** - * Get the aliased columns of the owning entity which are to + * Get the aliased columns of the owning entity which are to * be used in the join */ public static String[] getAliasedLHSColumnNames( AssociationType associationType, String columnQualifier, int propertyIndex, - int begin, + int begin, OuterJoinLoadable lhsPersister, Mapping mapping) { if ( associationType.useLHSPrimaryKey() ) { @@ -90,7 +85,8 @@ public final class JoinHelper { ); } else { - return ( (PropertyMapping) lhsPersister ).toColumns(columnQualifier, propertyName); //bad cast + //bad cast + return ( (PropertyMapping) lhsPersister ).toColumns( columnQualifier, propertyName ); } } } @@ -112,41 +108,57 @@ public final class JoinHelper { } /** - * Get the columns of the owning entity which are to - * be used in the join + * Get the columns of the owning entity which are to be used in the join + * + * @param type The type representing the join + * @param property The property index for the association type + * @param begin ? + * @param lhsPersister The persister for the left-hand-side of the join + * @param mapping The mapping object (typically the SessionFactory) + * + * @return The columns for the left-hand-side of the join */ public static String[] getLHSColumnNames( - AssociationType type, - int property, - int begin, + AssociationType type, + int property, + int begin, OuterJoinLoadable lhsPersister, - Mapping mapping - ) { + Mapping mapping) { if ( type.useLHSPrimaryKey() ) { //return lhsPersister.getSubclassPropertyColumnNames(property); return lhsPersister.getIdentifierColumnNames(); } else { - String propertyName = type.getLHSPropertyName(); - if (propertyName==null) { + final String propertyName = type.getLHSPropertyName(); + if ( propertyName == null ) { //slice, to get the columns for this component //property return ArrayHelper.slice( property < 0 ? lhsPersister.getIdentifierColumnNames() - : lhsPersister.getSubclassPropertyColumnNames(property), - begin, - type.getColumnSpan(mapping) - ); + : lhsPersister.getSubclassPropertyColumnNames( property ), + begin, + type.getColumnSpan( mapping ) + ); } else { //property-refs for associations defined on a //component are not supported, so no need to slice - return lhsPersister.getPropertyColumnNames(propertyName); + return lhsPersister.getPropertyColumnNames( propertyName ); } } } - + + /** + * Determine the name of the table that is the left-hand-side of the join. Usually this is the + * name of the main table from the left-hand-side persister. But that is not the case with property-refs. + * + * @param type The type representing the join + * @param propertyIndex The property index for the type + * @param lhsPersister The persister for the left-hand-side of the join + * + * @return The table name + */ public static String getLHSTableName( AssociationType type, int propertyIndex, @@ -155,17 +167,17 @@ public final class JoinHelper { return lhsPersister.getTableName(); } else { - String propertyName = type.getLHSPropertyName(); - if (propertyName==null) { + final String propertyName = type.getLHSPropertyName(); + if ( propertyName == null ) { //if there is no property-ref, assume the join //is to the subclass table (ie. the table of the //subclass that the association belongs to) - return lhsPersister.getSubclassPropertyTableName(propertyIndex); + return lhsPersister.getSubclassPropertyTableName( propertyIndex ); } else { //handle a property-ref - String propertyRefTable = lhsPersister.getPropertyTableName(propertyName); - if (propertyRefTable==null) { + String propertyRefTable = lhsPersister.getPropertyTableName( propertyName ); + if ( propertyRefTable == null ) { //it is possible that the tree-walking in OuterJoinLoader can get to //an association defined by a subclass, in which case the property-ref //might refer to a property defined on a subclass of the current class @@ -173,25 +185,32 @@ public final class JoinHelper { //assumes that the property-ref refers to a property of the subclass //table that the association belongs to (a reasonable guess) //TODO: fix this, add: OuterJoinLoadable.getSubclassPropertyTableName(String propertyName) - propertyRefTable = lhsPersister.getSubclassPropertyTableName(propertyIndex); + propertyRefTable = lhsPersister.getSubclassPropertyTableName( propertyIndex ); } return propertyRefTable; } } } - + /** - * Get the columns of the associated table which are to - * be used in the join + * Get the columns of the associated table which are to be used in the join + * + * @param type The type + * @param factory The SessionFactory + * + * @return The columns for the right-hand-side of the join */ public static String[] getRHSColumnNames(AssociationType type, SessionFactoryImplementor factory) { - String uniqueKeyPropertyName = type.getRHSUniqueKeyPropertyName(); - Joinable joinable = type.getAssociatedJoinable(factory); - if (uniqueKeyPropertyName==null) { + final String uniqueKeyPropertyName = type.getRHSUniqueKeyPropertyName(); + final Joinable joinable = type.getAssociatedJoinable( factory ); + if ( uniqueKeyPropertyName == null ) { return joinable.getKeyColumnNames(); } else { - return ( (OuterJoinLoadable) joinable ).getPropertyColumnNames(uniqueKeyPropertyName); + return ( (OuterJoinLoadable) joinable ).getPropertyColumnNames( uniqueKeyPropertyName ); } } + + private JoinHelper() { + } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/JoinSequence.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/JoinSequence.java index 0908e87e5c..0cc5ae2354 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/JoinSequence.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/JoinSequence.java @@ -25,7 +25,6 @@ package org.hibernate.engine.internal; import java.util.ArrayList; import java.util.Collections; -import java.util.Iterator; import java.util.List; import java.util.Map; @@ -39,46 +38,368 @@ import org.hibernate.sql.QueryJoinFragment; import org.hibernate.type.AssociationType; /** + * A sequence of {@link Join} delegates to make it "easier" to work with joins. The "easier" part is obviously + * subjective ;) + *

      + * Additionally JoinSequence is a directed graph of other JoinSequence instances, as represented by the + * {@link #next} ({@link #setNext(JoinSequence)}) pointer. + * * @author Gavin King + * @author Steve Ebersole + * + * @see JoinFragment */ public class JoinSequence { - private final SessionFactoryImplementor factory; - private final List joins = new ArrayList(); - private boolean useThetaStyle = false; + private final StringBuilder conditions = new StringBuilder(); + private final List joins = new ArrayList(); + + private boolean useThetaStyle; private String rootAlias; private Joinable rootJoinable; private Selector selector; private JoinSequence next; - private boolean isFromPart = false; + private boolean isFromPart; - @Override - public String toString() { - StringBuilder buf = new StringBuilder(); - buf.append( "JoinSequence{" ); - if ( rootJoinable != null ) { - buf.append( rootJoinable ) - .append( '[' ) - .append( rootAlias ) - .append( ']' ); - } - for ( int i = 0; i < joins.size(); i++ ) { - buf.append( "->" ).append( joins.get( i ) ); - } - return buf.append( '}' ).toString(); + /** + * Constructs a JoinSequence + * + * @param factory The SessionFactory + */ + public JoinSequence(SessionFactoryImplementor factory) { + this.factory = factory; } - public final class Join { + /** + * Retrieve a JoinSequence that represents just the FROM clause parts + * + * @return The JoinSequence that represents just the FROM clause parts + */ + public JoinSequence getFromPart() { + final JoinSequence fromPart = new JoinSequence( factory ); + fromPart.joins.addAll( this.joins ); + fromPart.useThetaStyle = this.useThetaStyle; + fromPart.rootAlias = this.rootAlias; + fromPart.rootJoinable = this.rootJoinable; + fromPart.selector = this.selector; + fromPart.next = this.next == null ? null : this.next.getFromPart(); + fromPart.isFromPart = true; + return fromPart; + } + /** + * Create a full, although shallow, copy. + * + * @return The copy + */ + public JoinSequence copy() { + final JoinSequence copy = new JoinSequence( factory ); + copy.joins.addAll( this.joins ); + copy.useThetaStyle = this.useThetaStyle; + copy.rootAlias = this.rootAlias; + copy.rootJoinable = this.rootJoinable; + copy.selector = this.selector; + copy.next = this.next == null ? null : this.next.copy(); + copy.isFromPart = this.isFromPart; + copy.conditions.append( this.conditions.toString() ); + return copy; + } + + /** + * Add a join to this sequence + * + * @param associationType The type of the association representing the join + * @param alias The RHS alias for the join + * @param joinType The type of join (INNER, etc) + * @param referencingKey The LHS columns for the join condition + * + * @return The Join memento + * + * @throws MappingException Generally indicates a problem resolving the associationType to a {@link Joinable} + */ + public JoinSequence addJoin( + AssociationType associationType, + String alias, + JoinType joinType, + String[] referencingKey) throws MappingException { + joins.add( new Join( factory, associationType, alias, joinType, referencingKey ) ); + return this; + } + + /** + * Generate a JoinFragment + * + * @return The JoinFragment + * + * @throws MappingException Indicates a problem access the provided metadata, or incorrect metadata + */ + public JoinFragment toJoinFragment() throws MappingException { + return toJoinFragment( Collections.EMPTY_MAP, true ); + } + + /** + * Generate a JoinFragment + * + * @param enabledFilters The filters associated with the originating session to properly define join conditions + * @param includeExtraJoins Should {@link #addExtraJoins} to called. Honestly I do not understand the full + * ramifications of this argument + * + * @return The JoinFragment + * + * @throws MappingException Indicates a problem access the provided metadata, or incorrect metadata + */ + public JoinFragment toJoinFragment(Map enabledFilters, boolean includeExtraJoins) throws MappingException { + return toJoinFragment( enabledFilters, includeExtraJoins, null, null ); + } + + /** + * Generate a JoinFragment + * + * @param enabledFilters The filters associated with the originating session to properly define join conditions + * @param includeExtraJoins Should {@link #addExtraJoins} to called. Honestly I do not understand the full + * ramifications of this argument + * @param withClauseFragment The with clause (which represents additional join restrictions) fragment + * @param withClauseJoinAlias The + * + * @return The JoinFragment + * + * @throws MappingException Indicates a problem access the provided metadata, or incorrect metadata + */ + public JoinFragment toJoinFragment( + Map enabledFilters, + boolean includeExtraJoins, + String withClauseFragment, + String withClauseJoinAlias) throws MappingException { + final QueryJoinFragment joinFragment = new QueryJoinFragment( factory.getDialect(), useThetaStyle ); + if ( rootJoinable != null ) { + joinFragment.addCrossJoin( rootJoinable.getTableName(), rootAlias ); + final String filterCondition = rootJoinable.filterFragment( rootAlias, enabledFilters ); + // JoinProcessor needs to know if the where clause fragment came from a dynamic filter or not so it + // can put the where clause fragment in the right place in the SQL AST. 'hasFilterCondition' keeps track + // of that fact. + joinFragment.setHasFilterCondition( joinFragment.addCondition( filterCondition ) ); + if ( includeExtraJoins ) { + //TODO: not quite sure about the full implications of this! + addExtraJoins( joinFragment, rootAlias, rootJoinable, true ); + } + } + + Joinable last = rootJoinable; + + for ( Join join : joins ) { + final String on = join.getAssociationType().getOnCondition( join.getAlias(), factory, enabledFilters ); + String condition; + if ( last != null + && isManyToManyRoot( last ) + && ((QueryableCollection) last).getElementType() == join.getAssociationType() ) { + // the current join represents the join between a many-to-many association table + // and its "target" table. Here we need to apply any additional filters + // defined specifically on the many-to-many + final String manyToManyFilter = ( (QueryableCollection) last ).getManyToManyFilterFragment( + join.getAlias(), + enabledFilters + ); + condition = "".equals( manyToManyFilter ) + ? on + : "".equals( on ) ? manyToManyFilter : on + " and " + manyToManyFilter; + } + else { + condition = on; + } + + if ( withClauseFragment != null ) { + if ( join.getAlias().equals( withClauseJoinAlias ) ) { + condition += " and " + withClauseFragment; + } + } + + joinFragment.addJoin( + join.getJoinable().getTableName(), + join.getAlias(), + join.getLHSColumns(), + JoinHelper.getRHSColumnNames( join.getAssociationType(), factory ), + join.joinType, + condition + ); + + //TODO: not quite sure about the full implications of this! + if ( includeExtraJoins ) { + addExtraJoins( + joinFragment, + join.getAlias(), + join.getJoinable(), + join.joinType == JoinType.INNER_JOIN + ); + } + last = join.getJoinable(); + } + + if ( next != null ) { + joinFragment.addFragment( next.toJoinFragment( enabledFilters, includeExtraJoins ) ); + } + + joinFragment.addCondition( conditions.toString() ); + + if ( isFromPart ) { + joinFragment.clearWherePart(); + } + + return joinFragment; + } + + @SuppressWarnings("SimplifiableIfStatement") + private boolean isManyToManyRoot(Joinable joinable) { + if ( joinable != null && joinable.isCollection() ) { + return ( (QueryableCollection) joinable ).isManyToMany(); + } + return false; + } + + private void addExtraJoins(JoinFragment joinFragment, String alias, Joinable joinable, boolean innerJoin) { + final boolean include = isIncluded( alias ); + joinFragment.addJoins( + joinable.fromJoinFragment( alias, innerJoin, include ), + joinable.whereJoinFragment( alias, innerJoin, include ) + ); + } + + private boolean isIncluded(String alias) { + return selector != null && selector.includeSubclasses( alias ); + } + + /** + * Add a condition to this sequence. + * + * @param condition The condition + * + * @return {@link this}, for method chaining + */ + public JoinSequence addCondition(String condition) { + if ( condition.trim().length() != 0 ) { + if ( !condition.startsWith( " and " ) ) { + conditions.append( " and " ); + } + conditions.append( condition ); + } + return this; + } + + /** + * Add a condition to this sequence. Typical usage here might be: + *

      +	 *     addCondition( "a", {"c1", "c2"}, "?" )
      +	 * 
      + * to represent: + *
      +	 *     "... a.c1 = ? and a.c2 = ? ..."
      +	 * 
      + * + * @param alias The alias to apply to the columns + * @param columns The columns to add checks for + * @param condition The conditions to check against the columns + * + * @return {@link this}, for method chaining + */ + public JoinSequence addCondition(String alias, String[] columns, String condition) { + for ( String column : columns ) { + conditions.append( " and " ) + .append( alias ) + .append( '.' ) + .append( column ) + .append( condition ); + } + return this; + } + + /** + * Set the root of this JoinSequence. In SQL terms, this would be the driving table. + * + * @param joinable The entity/collection that is the root of this JoinSequence + * @param alias The alias associated with that joinable. + * + * @return {@link this}, for method chaining + */ + public JoinSequence setRoot(Joinable joinable, String alias) { + this.rootAlias = alias; + this.rootJoinable = joinable; + return this; + } + + /** + * Sets the next join sequence + * + * @param next The next JoinSequence in the directed graph + * + * @return {@code this}, for method chaining + */ + public JoinSequence setNext(JoinSequence next) { + this.next = next; + return this; + } + + /** + * Set the Selector to use to determine how subclass joins should be applied. + * + * @param selector The selector to apply + * + * @return {@code this}, for method chaining + */ + public JoinSequence setSelector(Selector selector) { + this.selector = selector; + return this; + } + + /** + * Should this JoinSequence use theta-style joining (both a FROM and WHERE component) in the rendered SQL? + * + * @param useThetaStyle {@code true} indicates that theta-style joins should be used. + * + * @return {@code this}, for method chaining + */ + public JoinSequence setUseThetaStyle(boolean useThetaStyle) { + this.useThetaStyle = useThetaStyle; + return this; + } + + public boolean isThetaStyle() { + return useThetaStyle; + } + + public Join getFirstJoin() { + return joins.get( 0 ); + } + + /** + * A subclass join selector + */ + public static interface Selector { + /** + * Should subclasses be included in the rendered join sequence? + * + * @param alias The alias + * + * @return {@code true} if the subclass joins should be included + */ + public boolean includeSubclasses(String alias); + } + + /** + * Represents a join + */ + public static final class Join { private final AssociationType associationType; private final Joinable joinable; private final JoinType joinType; private final String alias; private final String[] lhsColumns; - Join(AssociationType associationType, String alias, JoinType joinType, String[] lhsColumns) - throws MappingException { + Join( + SessionFactoryImplementor factory, + AssociationType associationType, + String alias, + JoinType joinType, + String[] lhsColumns) throws MappingException { this.associationType = associationType; this.joinable = associationType.getAssociatedJoinable( factory ); this.alias = alias; @@ -107,195 +428,24 @@ public class JoinSequence { } @Override - public String toString() { + public String toString() { return joinable.toString() + '[' + alias + ']'; } } - public JoinSequence(SessionFactoryImplementor factory) { - this.factory = factory; - } - - public JoinSequence getFromPart() { - JoinSequence fromPart = new JoinSequence( factory ); - fromPart.joins.addAll( this.joins ); - fromPart.useThetaStyle = this.useThetaStyle; - fromPart.rootAlias = this.rootAlias; - fromPart.rootJoinable = this.rootJoinable; - fromPart.selector = this.selector; - fromPart.next = this.next == null ? null : this.next.getFromPart(); - fromPart.isFromPart = true; - return fromPart; - } - - public JoinSequence copy() { - JoinSequence copy = new JoinSequence( factory ); - copy.joins.addAll( this.joins ); - copy.useThetaStyle = this.useThetaStyle; - copy.rootAlias = this.rootAlias; - copy.rootJoinable = this.rootJoinable; - copy.selector = this.selector; - copy.next = this.next == null ? null : this.next.copy(); - copy.isFromPart = this.isFromPart; - copy.conditions.append( this.conditions.toString() ); - return copy; - } - - public JoinSequence addJoin(AssociationType associationType, String alias, JoinType joinType, String[] referencingKey) - throws MappingException { - joins.add( new Join( associationType, alias, joinType, referencingKey ) ); - return this; - } - - public JoinFragment toJoinFragment() throws MappingException { - return toJoinFragment( Collections.EMPTY_MAP, true ); - } - - public JoinFragment toJoinFragment(Map enabledFilters, boolean includeExtraJoins) throws MappingException { - return toJoinFragment( enabledFilters, includeExtraJoins, null, null ); - } - - public JoinFragment toJoinFragment( - Map enabledFilters, - boolean includeExtraJoins, - String withClauseFragment, - String withClauseJoinAlias) throws MappingException { - QueryJoinFragment joinFragment = new QueryJoinFragment( factory.getDialect(), useThetaStyle ); + @Override + public String toString() { + final StringBuilder buf = new StringBuilder(); + buf.append( "JoinSequence{" ); if ( rootJoinable != null ) { - joinFragment.addCrossJoin( rootJoinable.getTableName(), rootAlias ); - String filterCondition = rootJoinable.filterFragment( rootAlias, enabledFilters ); - // JoinProcessor needs to know if the where clause fragment came from a dynamic filter or not so it - // can put the where clause fragment in the right place in the SQL AST. 'hasFilterCondition' keeps track - // of that fact. - joinFragment.setHasFilterCondition( joinFragment.addCondition( filterCondition ) ); - if (includeExtraJoins) { //TODO: not quite sure about the full implications of this! - addExtraJoins( joinFragment, rootAlias, rootJoinable, true ); - } + buf.append( rootJoinable ) + .append( '[' ) + .append( rootAlias ) + .append( ']' ); } - - Joinable last = rootJoinable; - - for ( Join join: joins ) { - String on = join.getAssociationType().getOnCondition( join.getAlias(), factory, enabledFilters ); - String condition = null; - if ( last != null && - isManyToManyRoot( last ) && - ( ( QueryableCollection ) last ).getElementType() == join.getAssociationType() ) { - // the current join represents the join between a many-to-many association table - // and its "target" table. Here we need to apply any additional filters - // defined specifically on the many-to-many - String manyToManyFilter = ( ( QueryableCollection ) last ) - .getManyToManyFilterFragment( join.getAlias(), enabledFilters ); - condition = "".equals( manyToManyFilter ) - ? on - : "".equals( on ) - ? manyToManyFilter - : on + " and " + manyToManyFilter; - } - else { - condition = on; - } - if ( withClauseFragment != null ) { - if ( join.getAlias().equals( withClauseJoinAlias ) ) { - condition += " and " + withClauseFragment; - } - } - joinFragment.addJoin( - join.getJoinable().getTableName(), - join.getAlias(), - join.getLHSColumns(), - JoinHelper.getRHSColumnNames( join.getAssociationType(), factory ), - join.joinType, - condition - ); - if (includeExtraJoins) { //TODO: not quite sure about the full implications of this! - addExtraJoins( joinFragment, join.getAlias(), join.getJoinable(), join.joinType == JoinType.INNER_JOIN ); - } - last = join.getJoinable(); + for ( Join join : joins ) { + buf.append( "->" ).append( join ); } - if ( next != null ) { - joinFragment.addFragment( next.toJoinFragment( enabledFilters, includeExtraJoins ) ); - } - joinFragment.addCondition( conditions.toString() ); - if ( isFromPart ) joinFragment.clearWherePart(); - return joinFragment; - } - - private boolean isManyToManyRoot(Joinable joinable) { - if ( joinable != null && joinable.isCollection() ) { - QueryableCollection persister = ( QueryableCollection ) joinable; - return persister.isManyToMany(); - } - return false; - } - - private boolean isIncluded(String alias) { - return selector != null && selector.includeSubclasses( alias ); - } - - private void addExtraJoins(JoinFragment joinFragment, String alias, Joinable joinable, boolean innerJoin) { - boolean include = isIncluded( alias ); - joinFragment.addJoins( joinable.fromJoinFragment( alias, innerJoin, include ), - joinable.whereJoinFragment( alias, innerJoin, include ) ); - } - - public JoinSequence addCondition(String condition) { - if ( condition.trim().length() != 0 ) { - if ( !condition.startsWith( " and " ) ) conditions.append( " and " ); - conditions.append( condition ); - } - return this; - } - - public JoinSequence addCondition(String alias, String[] columns, String condition) { - for ( int i = 0; i < columns.length; i++ ) { - conditions.append( " and " ) - .append( alias ) - .append( '.' ) - .append( columns[i] ) - .append( condition ); - } - return this; - } - - public JoinSequence setRoot(Joinable joinable, String alias) { - this.rootAlias = alias; - this.rootJoinable = joinable; - return this; - } - - public JoinSequence setNext(JoinSequence next) { - this.next = next; - return this; - } - - public JoinSequence setSelector(Selector s) { - this.selector = s; - return this; - } - - public JoinSequence setUseThetaStyle(boolean useThetaStyle) { - this.useThetaStyle = useThetaStyle; - return this; - } - - public boolean isThetaStyle() { - return useThetaStyle; - } - - public int getJoinCount() { - return joins.size(); - } - - public Iterator iterateJoins() { - return joins.iterator(); - } - - public Join getFirstJoin() { - return joins.get( 0 ); - } - - public static interface Selector { - public boolean includeSubclasses(String alias); + return buf.append( '}' ).toString(); } } From b51164aef6cadb5817f910f059a1c18ee8c4f68c Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Fri, 26 Apr 2013 18:50:39 -0500 Subject: [PATCH 21/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../org/hibernate/cfg/AnnotationBinder.java | 3 +- .../java/org/hibernate/cfg/HbmBinder.java | 21 +- .../cfg/annotations/EntityBinder.java | 13 +- .../hibernate/engine/OptimisticLockStyle.java | 38 +- .../NonNullableTransientDependencies.java | 33 +- .../engine/internal/Nullability.java | 52 +- .../engine/internal/ParameterBinder.java | 117 ++- .../internal/StatefulPersistenceContext.java | 753 +++++++----------- .../engine/internal/TwoPhaseLoad.java | 168 ++-- .../engine/internal/UnsavedValueFactory.java | 59 +- .../hibernate/engine/internal/Versioning.java | 62 +- .../engine/spi/PersistenceContext.java | 54 +- .../java/org/hibernate/loader/Loader.java | 2 +- .../ResultSetProcessingContextImpl.java | 6 +- .../hibernate/mapping/PersistentClass.java | 20 +- .../java/org/hibernate/mapping/RootClass.java | 7 +- .../java/org/hibernate/mapping/Subclass.java | 9 +- .../tuple/entity/EntityMetamodel.java | 19 +- ...NewCustomEntityMappingAnnotationsTest.java | 2 +- .../test/legacy/CustomPersister.java | 10 +- 20 files changed, 696 insertions(+), 752 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java index aa940d9c27..ba368b43c2 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/AnnotationBinder.java @@ -150,6 +150,7 @@ import org.hibernate.cfg.annotations.PropertyBinder; import org.hibernate.cfg.annotations.QueryBinder; import org.hibernate.cfg.annotations.SimpleValueBinder; import org.hibernate.cfg.annotations.TableBinder; +import org.hibernate.engine.OptimisticLockStyle; import org.hibernate.engine.internal.Versioning; import org.hibernate.engine.spi.FilterDefinition; import org.hibernate.id.MultipleHiLoPerTableGenerator; @@ -1568,7 +1569,7 @@ public final class AnnotationBinder { SimpleValue simpleValue = ( SimpleValue ) prop.getValue(); simpleValue.setNullValue( "undefined" ); - rootClass.setOptimisticLockMode( Versioning.OPTIMISTIC_LOCK_VERSION ); + rootClass.setOptimisticLockStyle( OptimisticLockStyle.VERSION ); if ( traceEnabled ) { LOG.tracev( "Version name: {0}, unsavedValue: {1}", rootClass.getVersion().getName(), ( (SimpleValue) rootClass.getVersion().getValue() ).getNullValue() ); diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java index 8422356dd3..0062fad513 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java @@ -24,7 +24,6 @@ package org.hibernate.cfg; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -41,7 +40,7 @@ import org.hibernate.EntityMode; import org.hibernate.FetchMode; import org.hibernate.FlushMode; import org.hibernate.MappingException; -import org.hibernate.engine.internal.Versioning; +import org.hibernate.engine.OptimisticLockStyle; import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle; import org.hibernate.engine.spi.FilterDefinition; import org.hibernate.engine.spi.NamedQueryDefinition; @@ -688,7 +687,7 @@ public final class HbmBinder { // OPTIMISTIC LOCK MODE Attribute olNode = node.attribute( "optimistic-lock" ); - entity.setOptimisticLockMode( getOptimisticLockMode( olNode ) ); + entity.setOptimisticLockStyle( getOptimisticLockStyle( olNode ) ); entity.setMetaAttributes( getMetas( node, inheritedMetas ) ); @@ -2932,21 +2931,23 @@ public final class HbmBinder { } } - private static int getOptimisticLockMode(Attribute olAtt) throws MappingException { + private static OptimisticLockStyle getOptimisticLockStyle(Attribute olAtt) throws MappingException { + if ( olAtt == null ) { + return OptimisticLockStyle.VERSION; + } - if ( olAtt == null ) return Versioning.OPTIMISTIC_LOCK_VERSION; - String olMode = olAtt.getValue(); + final String olMode = olAtt.getValue(); if ( olMode == null || "version".equals( olMode ) ) { - return Versioning.OPTIMISTIC_LOCK_VERSION; + return OptimisticLockStyle.VERSION; } else if ( "dirty".equals( olMode ) ) { - return Versioning.OPTIMISTIC_LOCK_DIRTY; + return OptimisticLockStyle.DIRTY; } else if ( "all".equals( olMode ) ) { - return Versioning.OPTIMISTIC_LOCK_ALL; + return OptimisticLockStyle.ALL; } else if ( "none".equals( olMode ) ) { - return Versioning.OPTIMISTIC_LOCK_NONE; + return OptimisticLockStyle.NONE; } else { throw new MappingException( "Unsupported optimistic-lock style: " + olMode ); diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java index a29cbda603..defd4096f7 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/EntityBinder.java @@ -84,6 +84,7 @@ import org.hibernate.cfg.ObjectNameNormalizer; import org.hibernate.cfg.ObjectNameSource; import org.hibernate.cfg.PropertyHolder; import org.hibernate.cfg.UniqueConstraintHolder; +import org.hibernate.engine.OptimisticLockStyle; import org.hibernate.engine.internal.Versioning; import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle; import org.hibernate.engine.spi.FilterDefinition; @@ -289,7 +290,7 @@ public class EntityBinder { LOG.immutableAnnotationOnNonRoot(annotatedClass.getName()); } } - persistentClass.setOptimisticLockMode( getVersioning( optimisticLockType ) ); + persistentClass.setOptimisticLockStyle( getVersioning( optimisticLockType ) ); persistentClass.setSelectBeforeUpdate( selectBeforeUpdate ); //set persister if needed @@ -428,16 +429,16 @@ public class EntityBinder { } } - int getVersioning(OptimisticLockType type) { + OptimisticLockStyle getVersioning(OptimisticLockType type) { switch ( type ) { case VERSION: - return Versioning.OPTIMISTIC_LOCK_VERSION; + return OptimisticLockStyle.VERSION; case NONE: - return Versioning.OPTIMISTIC_LOCK_NONE; + return OptimisticLockStyle.NONE; case DIRTY: - return Versioning.OPTIMISTIC_LOCK_DIRTY; + return OptimisticLockStyle.DIRTY; case ALL: - return Versioning.OPTIMISTIC_LOCK_ALL; + return OptimisticLockStyle.ALL; default: throw new AssertionFailure( "optimistic locking not supported: " + type ); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/OptimisticLockStyle.java b/hibernate-core/src/main/java/org/hibernate/engine/OptimisticLockStyle.java index 8b801167b2..b0211d708f 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/OptimisticLockStyle.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/OptimisticLockStyle.java @@ -32,17 +32,47 @@ public enum OptimisticLockStyle { /** * no optimistic locking */ - NONE, + NONE( -1 ), /** * use a dedicated version column */ - VERSION, + VERSION( 0 ), /** * dirty columns are compared */ - DIRTY, + DIRTY( 1 ), /** * all columns are compared */ - ALL + ALL( 2 ); + + private final int oldCode; + + private OptimisticLockStyle(int oldCode) { + this.oldCode = oldCode; + } + + public int getOldCode() { + return oldCode; + } + + public static OptimisticLockStyle interpretOldCode(int oldCode) { + switch ( oldCode ) { + case -1: { + return NONE; + } + case 0: { + return VERSION; + } + case 1: { + return DIRTY; + } + case 2: { + return ALL; + } + default: { + throw new IllegalArgumentException( "Illegal legacy optimistic lock style code :" + oldCode ); + } + } + } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/NonNullableTransientDependencies.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/NonNullableTransientDependencies.java index 105933915d..07fd256e16 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/NonNullableTransientDependencies.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/NonNullableTransientDependencies.java @@ -36,13 +36,10 @@ import org.hibernate.engine.spi.SessionImplementor; * @author Gail Badner */ public class NonNullableTransientDependencies { - // Multiple property paths can refer to the same transient entity, so use Set // for the map value. - private final Map> propertyPathsByTransientEntity = - new IdentityHashMap>(); + private final Map> propertyPathsByTransientEntity = new IdentityHashMap>(); - /* package-protected */ void add(String propertyName, Object transientEntity) { Set propertyPaths = propertyPathsByTransientEntity.get( transientEntity ); if ( propertyPaths == null ) { @@ -56,22 +53,48 @@ public class NonNullableTransientDependencies { return propertyPathsByTransientEntity.keySet(); } + /** + * Retrieve the paths that refer to the transient entity + * + * @param entity The transient entity + * + * @return The property paths + */ public Iterable getNonNullableTransientPropertyPaths(Object entity) { return propertyPathsByTransientEntity.get( entity ); } + /** + * Are there any paths currently tracked here? + * + * @return {@code true} indicates there are no path tracked here currently + */ public boolean isEmpty() { return propertyPathsByTransientEntity.isEmpty(); } + /** + * Clean up any tracked references for the given entity, throwing an exception if there were any paths. + * + * @param entity The entity + * + * @throws IllegalStateException If the entity had tracked paths + */ public void resolveNonNullableTransientEntity(Object entity) { if ( propertyPathsByTransientEntity.remove( entity ) == null ) { throw new IllegalStateException( "Attempt to resolve a non-nullable, transient entity that is not a dependency." ); } } + /** + * Build a loggable representation of the paths tracked here at the moment. + * + * @param session The session (used to resolve entity names) + * + * @return The loggable representation + */ public String toLoggableString(SessionImplementor session) { - StringBuilder sb = new StringBuilder( getClass().getSimpleName() ).append( '[' ); + final StringBuilder sb = new StringBuilder( getClass().getSimpleName() ).append( '[' ); for ( Map.Entry> entry : propertyPathsByTransientEntity.entrySet() ) { sb.append( "transientEntityName=" ).append( session.bestGuessEntityName( entry.getKey() ) ); sb.append( " requiredBy=" ).append( entry.getValue() ); diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/Nullability.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/Nullability.java index f13ea17765..6b990d64cc 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/Nullability.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/Nullability.java @@ -42,10 +42,14 @@ import org.hibernate.type.Type; * @author Gavin King */ public final class Nullability { - private final SessionImplementor session; private final boolean checkNullability; + /** + * Constructs a Nullability + * + * @param session The session + */ public Nullability(SessionImplementor session) { this.session = session; this.checkNullability = session.getFactory().getSettings().isCheckNullability(); @@ -56,14 +60,14 @@ public final class Nullability { * @param values entity properties * @param persister class persister * @param isUpdate whether it is intended to be updated or saved - * @throws org.hibernate.PropertyValueException Break the nullability of one property + * + * @throws PropertyValueException Break the nullability of one property * @throws HibernateException error while getting Component values */ public void checkNullability( final Object[] values, final EntityPersister persister, - final boolean isUpdate) - throws PropertyValueException, HibernateException { + final boolean isUpdate) throws HibernateException { /* * Typically when Bean Validation is on, we don't want to validate null values * at the Hibernate Core level. Hence the checkNullability setting. @@ -108,9 +112,8 @@ public final class Nullability { } else if ( value != null ) { - //values is not null and is checkable, we'll look deeper - String breakProperties = checkSubElementsNullability( propertyTypes[i], value ); + final String breakProperties = checkSubElementsNullability( propertyTypes[i], value ); if ( breakProperties != null ) { throw new PropertyValueException( "not-null property references a null or transient value", @@ -136,8 +139,8 @@ public final class Nullability { * @return property path * @throws HibernateException error while getting subcomponent values */ - private String checkSubElementsNullability(final Type propertyType, final Object value) - throws HibernateException { + private String checkSubElementsNullability(final Type propertyType, final Object value) + throws HibernateException { //for non null args, check for components and elements containing components if ( propertyType.isComponentType() ) { return checkComponentNullability( value, (CompositeType) propertyType ); @@ -145,17 +148,17 @@ public final class Nullability { else if ( propertyType.isCollectionType() ) { //persistent collections may have components - CollectionType collectionType = (CollectionType) propertyType; - Type collectionElementType = collectionType.getElementType( session.getFactory() ); + final CollectionType collectionType = (CollectionType) propertyType; + final Type collectionElementType = collectionType.getElementType( session.getFactory() ); if ( collectionElementType.isComponentType() ) { //check for all components values in the collection - CompositeType componentType = (CompositeType) collectionElementType; - Iterator iter = CascadingActions.getLoadedElementsIterator( session, collectionType, value ); - while ( iter.hasNext() ) { - Object compValue = iter.next(); - if (compValue != null) { - return checkComponentNullability(compValue, componentType); + final CompositeType componentType = (CompositeType) collectionElementType; + final Iterator itr = CascadingActions.getLoadedElementsIterator( session, collectionType, value ); + while ( itr.hasNext() ) { + Object compValue = itr.next(); + if ( compValue != null ) { + return checkComponentNullability( compValue, componentType ); } } } @@ -174,11 +177,11 @@ public final class Nullability { * @throws HibernateException error while getting subcomponent values */ private String checkComponentNullability(final Object value, final CompositeType compType) - throws HibernateException { + throws HibernateException { /* will check current level if some of them are not null * or sublevels if they exist */ - boolean[] nullability = compType.getPropertyNullability(); + final boolean[] nullability = compType.getPropertyNullability(); if ( nullability!=null ) { //do the test final Object[] values = compType.getPropertyValues( value, EntityMode.POJO ); @@ -189,27 +192,26 @@ public final class Nullability { return compType.getPropertyNames()[i]; } else if ( subvalue != null ) { - String breakProperties = checkSubElementsNullability( propertyTypes[i], subvalue ); + final String breakProperties = checkSubElementsNullability( propertyTypes[i], subvalue ); if ( breakProperties != null ) { return buildPropertyPath( compType.getPropertyNames()[i], breakProperties ); } - } - } + } + } } return null; } /** - * Return a well formed property path. - * Basically, it will return parent.child + * Return a well formed property path. Basically, it will return parent.child * * @param parent parent in path * @param child child in path + * * @return parent-child path */ private static String buildPropertyPath(String parent, String child) { - return new StringBuilder( parent.length() + child.length() + 1 ) - .append(parent).append('.').append(child).toString(); + return parent + '.' + child; } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/ParameterBinder.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/ParameterBinder.java index 1926cf3d84..751c74d9a5 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/ParameterBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/ParameterBinder.java @@ -46,48 +46,74 @@ import org.hibernate.type.Type; * @author Steve Ebersole */ public class ParameterBinder { + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + ParameterBinder.class.getName() + ); - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, ParameterBinder.class.getName()); - + /** + * Helper contract for dealing with named parameters and resolving their locations + */ public static interface NamedParameterSource { + /** + * Retrieve the locations for the given parameter name + * + * @param name The parameter name + * + * @return The locations + */ public int[] getNamedParameterLocations(String name); } private ParameterBinder() { } + /** + * Perform parameter binding + * + * @param st The statement to bind parameters to + * @param queryParameters The parameters + * @param start The initial bind position + * @param source The named parameter source, for resolving the locations of named parameters + * @param session The session + * + * @return The next bind position after the last position we bound here. + * + * @throws SQLException Indicates a problem calling JDBC bind methods + * @throws HibernateException Indicates a problem access bind values. + */ public static int bindQueryParameters( - final PreparedStatement st, - final QueryParameters queryParameters, - final int start, - final NamedParameterSource source, - SessionImplementor session) throws SQLException, HibernateException { + final PreparedStatement st, + final QueryParameters queryParameters, + final int start, + final NamedParameterSource source, + SessionImplementor session) throws SQLException, HibernateException { int col = start; col += bindPositionalParameters( st, queryParameters, col, session ); col += bindNamedParameters( st, queryParameters, col, source, session ); return col; } - public static int bindPositionalParameters( - final PreparedStatement st, - final QueryParameters queryParameters, - final int start, - final SessionImplementor session) throws SQLException, HibernateException { + private static int bindPositionalParameters( + final PreparedStatement st, + final QueryParameters queryParameters, + final int start, + final SessionImplementor session) throws SQLException, HibernateException { return bindPositionalParameters( - st, - queryParameters.getPositionalParameterValues(), - queryParameters.getPositionalParameterTypes(), - start, - session + st, + queryParameters.getPositionalParameterValues(), + queryParameters.getPositionalParameterTypes(), + start, + session ); } - public static int bindPositionalParameters( - final PreparedStatement st, - final Object[] values, - final Type[] types, - final int start, - final SessionImplementor session) throws SQLException, HibernateException { + private static int bindPositionalParameters( + final PreparedStatement st, + final Object[] values, + final Type[] types, + final int start, + final SessionImplementor session) throws SQLException, HibernateException { int span = 0; for ( int i = 0; i < values.length; i++ ) { types[i].nullSafeSet( st, values[i], start + span, session ); @@ -96,41 +122,46 @@ public class ParameterBinder { return span; } - public static int bindNamedParameters( - final PreparedStatement ps, - final QueryParameters queryParameters, - final int start, - final NamedParameterSource source, - final SessionImplementor session) throws SQLException, HibernateException { + private static int bindNamedParameters( + final PreparedStatement ps, + final QueryParameters queryParameters, + final int start, + final NamedParameterSource source, + final SessionImplementor session) throws SQLException, HibernateException { return bindNamedParameters( ps, queryParameters.getNamedParameters(), start, source, session ); } - public static int bindNamedParameters( - final PreparedStatement ps, - final Map namedParams, - final int start, - final NamedParameterSource source, - final SessionImplementor session) throws SQLException, HibernateException { + private static int bindNamedParameters( + final PreparedStatement ps, + final Map namedParams, + final int start, + final NamedParameterSource source, + final SessionImplementor session) throws SQLException, HibernateException { if ( namedParams != null ) { final boolean debugEnabled = LOG.isDebugEnabled(); // assumes that types are all of span 1 - Iterator iter = namedParams.entrySet().iterator(); + final Iterator iter = namedParams.entrySet().iterator(); int result = 0; while ( iter.hasNext() ) { - Map.Entry e = ( Map.Entry ) iter.next(); - String name = ( String ) e.getKey(); - TypedValue typedval = (TypedValue) e.getValue(); + final Map.Entry e = (Map.Entry) iter.next(); + final String name = (String) e.getKey(); + final TypedValue typedVal = (TypedValue) e.getValue(); int[] locations = source.getNamedParameterLocations( name ); - for ( int i = 0; i < locations.length; i++ ) { + for ( int location : locations ) { if ( debugEnabled ) { - LOG.debugf("bindNamedParameters() %s -> %s [%s]", typedval.getValue(), name, locations[i] + start); + LOG.debugf( + "bindNamedParameters() %s -> %s [%s]", + typedVal.getValue(), + name, + location + start + ); } - typedval.getType().nullSafeSet( ps, typedval.getValue(), locations[i] + start, session ); + typedVal.getType().nullSafeSet( ps, typedVal.getValue(), location + start, session ); } result += locations.length; } return result; } - return 0; + return 0; } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java index dc24d0a256..cb4122c0f6 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java @@ -68,7 +68,6 @@ import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.engine.spi.Status; import org.hibernate.event.spi.EventSource; import org.hibernate.internal.CoreMessageLogger; -import org.hibernate.internal.util.MarkerObject; import org.hibernate.internal.util.collections.ConcurrentReferenceHashMap; import org.hibernate.internal.util.collections.IdentityMap; import org.hibernate.persister.collection.CollectionPersister; @@ -82,7 +81,7 @@ import org.hibernate.type.CollectionType; /** * A stateful implementation of the {@link PersistenceContext} contract meaning that we maintain this * state throughout the life of the persistence context. - *

      + *

      * IMPL NOTE: There is meant to be a one-to-one correspondence between a {@link org.hibernate.internal.SessionImpl} * and a PersistentContext. Event listeners and other Session collaborators then use the PersistentContext to drive * their processing. @@ -90,14 +89,13 @@ import org.hibernate.type.CollectionType; * @author Steve Ebersole */ public class StatefulPersistenceContext implements PersistenceContext { + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + StatefulPersistenceContext.class.getName() + ); - private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, StatefulPersistenceContext.class.getName() ); - - private static final boolean tracing = LOG.isTraceEnabled(); - - public static final Object NO_ROW = new MarkerObject( "NO_ROW" ); - - public static final int INIT_COLL_SIZE = 8; + private static final boolean TRACE_ENABLED = LOG.isTraceEnabled(); + private static final int INIT_COLL_SIZE = 8; private SessionImplementor session; @@ -144,12 +142,12 @@ public class StatefulPersistenceContext implements PersistenceContext { // May be empty or not contains all relation private Map parentsByChild; - private int cascading = 0; - private int loadCounter = 0; - private boolean flushing = false; + private int cascading; + private int loadCounter; + private boolean flushing; - private boolean defaultReadOnly = false; - private boolean hasNonReadOnlyEntities = false; + private boolean defaultReadOnly; + private boolean hasNonReadOnlyEntities; private LoadContexts loadContexts; private BatchFetchQueue batchFetchQueue; @@ -280,8 +278,8 @@ public class StatefulPersistenceContext implements PersistenceContext { @Override public void setEntryStatus(EntityEntry entry, Status status) { - entry.setStatus(status); - setHasNonReadOnlyEnties(status); + entry.setStatus( status ); + setHasNonReadOnlyEnties( status ); } private void setHasNonReadOnlyEnties(Status status) { @@ -303,25 +301,25 @@ public class StatefulPersistenceContext implements PersistenceContext { /** * Get the current state of the entity as known to the underlying * database, or null if there is no corresponding row + *

      + * {@inheritDoc} */ @Override - public Object[] getDatabaseSnapshot(Serializable id, EntityPersister persister) - throws HibernateException { + public Object[] getDatabaseSnapshot(Serializable id, EntityPersister persister) throws HibernateException { final EntityKey key = session.generateEntityKey( id, persister ); - Object cached = entitySnapshotsByKey.get(key); - if (cached!=null) { - return cached==NO_ROW ? null : (Object[]) cached; + final Object cached = entitySnapshotsByKey.get( key ); + if ( cached != null ) { + return cached == NO_ROW ? null : (Object[]) cached; } else { - Object[] snapshot = persister.getDatabaseSnapshot( id, session ); - entitySnapshotsByKey.put( key, snapshot==null ? NO_ROW : snapshot ); + final Object[] snapshot = persister.getDatabaseSnapshot( id, session ); + entitySnapshotsByKey.put( key, snapshot == null ? NO_ROW : snapshot ); return snapshot; } } @Override - public Object[] getNaturalIdSnapshot(Serializable id, EntityPersister persister) - throws HibernateException { + public Object[] getNaturalIdSnapshot(Serializable id, EntityPersister persister) throws HibernateException { if ( !persister.hasNaturalIdentifier() ) { return null; } @@ -371,39 +369,27 @@ public class StatefulPersistenceContext implements PersistenceContext { return session.getFactory().getEntityPersister( persister.getRootEntityName() ); } - /** - * Retrieve the cached database snapshot for the requested entity key. - *

      - * This differs from {@link #getDatabaseSnapshot} is two important respects:

        - *
      1. no snapshot is obtained from the database if not already cached
      2. - *
      3. an entry of {@link #NO_ROW} here is interpretet as an exception
      4. - *
      - * @param key The entity key for which to retrieve the cached snapshot - * @return The cached snapshot - * @throws IllegalStateException if the cached snapshot was == {@link #NO_ROW}. - */ @Override public Object[] getCachedDatabaseSnapshot(EntityKey key) { - Object snapshot = entitySnapshotsByKey.get( key ); + final Object snapshot = entitySnapshotsByKey.get( key ); if ( snapshot == NO_ROW ) { - throw new IllegalStateException( "persistence context reported no row snapshot for " + MessageHelper.infoString( key.getEntityName(), key.getIdentifier() ) ); + throw new IllegalStateException( + "persistence context reported no row snapshot for " + + MessageHelper.infoString( key.getEntityName(), key.getIdentifier() ) + ); } - return ( Object[] ) snapshot; + return (Object[]) snapshot; } @Override public void addEntity(EntityKey key, Object entity) { - entitiesByKey.put(key, entity); - getBatchFetchQueue().removeBatchLoadableEntityKey(key); + entitiesByKey.put( key, entity ); + getBatchFetchQueue().removeBatchLoadableEntityKey( key ); } - /** - * Get the entity instance associated with the given - * EntityKey - */ @Override public Object getEntity(EntityKey key) { - return entitiesByKey.get(key); + return entitiesByKey.get( key ); } @Override @@ -411,84 +397,54 @@ public class StatefulPersistenceContext implements PersistenceContext { return entitiesByKey.containsKey(key); } - /** - * Remove an entity from the session cache, also clear - * up other state associated with the entity, all except - * for the EntityEntry - */ @Override public Object removeEntity(EntityKey key) { - Object entity = entitiesByKey.remove(key); - Iterator iter = entitiesByUniqueKey.values().iterator(); - while ( iter.hasNext() ) { - if ( iter.next()==entity ) iter.remove(); + final Object entity = entitiesByKey.remove( key ); + final Iterator itr = entitiesByUniqueKey.values().iterator(); + while ( itr.hasNext() ) { + if ( itr.next() == entity ) { + itr.remove(); + } } // Clear all parent cache parentsByChild.clear(); - entitySnapshotsByKey.remove(key); - nullifiableEntityKeys.remove(key); - getBatchFetchQueue().removeBatchLoadableEntityKey(key); - getBatchFetchQueue().removeSubselect(key); + entitySnapshotsByKey.remove( key ); + nullifiableEntityKeys.remove( key ); + getBatchFetchQueue().removeBatchLoadableEntityKey( key ); + getBatchFetchQueue().removeSubselect( key ); return entity; } - /** - * Get an entity cached by unique key - */ @Override public Object getEntity(EntityUniqueKey euk) { - return entitiesByUniqueKey.get(euk); + return entitiesByUniqueKey.get( euk ); } - /** - * Add an entity to the cache by unique key - */ @Override public void addEntity(EntityUniqueKey euk, Object entity) { - entitiesByUniqueKey.put(euk, entity); + entitiesByUniqueKey.put( euk, entity ); } - /** - * Retrieve the EntityEntry representation of the given entity. - * - * @param entity The entity for which to locate the EntityEntry. - * @return The EntityEntry for the given entity. - */ @Override public EntityEntry getEntry(Object entity) { return entityEntryContext.getEntityEntry( entity ); -// return entityEntries.get(entity); } - /** - * Remove an entity entry from the session cache - */ @Override public EntityEntry removeEntry(Object entity) { return entityEntryContext.removeEntityEntry( entity ); -// return entityEntries.remove(entity); } - /** - * Is there an EntityEntry for this instance? - */ @Override public boolean isEntryFor(Object entity) { return entityEntryContext.hasEntityEntry( entity ); -// return entityEntries.containsKey(entity); } - /** - * Get the collection entry for a persistent collection - */ @Override public CollectionEntry getCollectionEntry(PersistentCollection coll) { - return collectionEntries.get(coll); + return collectionEntries.get( coll ); } - /** - * Adds an entity to the internal caches. - */ @Override public EntityEntry addEntity( final Object entity, @@ -517,11 +473,6 @@ public class StatefulPersistenceContext implements PersistenceContext { ); } - - /** - * Generates an appropriate EntityEntry instance and adds it - * to the event source's internal caches. - */ @Override public EntityEntry addEntry( final Object entity, @@ -536,7 +487,7 @@ public class StatefulPersistenceContext implements PersistenceContext { final boolean disableVersionIncrement, boolean lazyPropertiesAreUnfetched) { - EntityEntry e = new EntityEntry( + final EntityEntry e = new EntityEntry( status, loadedState, rowId, @@ -555,13 +506,13 @@ public class StatefulPersistenceContext implements PersistenceContext { entityEntryContext.addEntityEntry( entity, e ); // entityEntries.put(entity, e); - setHasNonReadOnlyEnties(status); + setHasNonReadOnlyEnties( status ); return e; } @Override public boolean containsCollection(PersistentCollection collection) { - return collectionEntries.containsKey(collection); + return collectionEntries.containsKey( collection ); } @Override @@ -569,23 +520,16 @@ public class StatefulPersistenceContext implements PersistenceContext { return proxiesByKey.containsValue( entity ); } - /** - * Takes the given object and, if it represents a proxy, reassociates it with this event source. - * - * @param value The possible proxy to be reassociated. - * @return Whether the passed value represented an actual proxy which got initialized. - * @throws MappingException - */ @Override public boolean reassociateIfUninitializedProxy(Object value) throws MappingException { if ( value instanceof ElementWrapper ) { value = ( (ElementWrapper) value ).getElement(); } - if ( !Hibernate.isInitialized(value) ) { - HibernateProxy proxy = (HibernateProxy) value; - LazyInitializer li = proxy.getHibernateLazyInitializer(); - reassociateProxy(li, proxy); + if ( !Hibernate.isInitialized( value ) ) { + final HibernateProxy proxy = (HibernateProxy) value; + final LazyInitializer li = proxy.getHibernateLazyInitializer(); + reassociateProxy( li, proxy ); return true; } else { @@ -593,10 +537,6 @@ public class StatefulPersistenceContext implements PersistenceContext { } } - /** - * If a deleted entity instance is re-saved, and it has a proxy, we need to - * reset the identifier of the proxy - */ @Override public void reassociateProxy(Object value, Serializable id) throws MappingException { if ( value instanceof ElementWrapper ) { @@ -605,10 +545,10 @@ public class StatefulPersistenceContext implements PersistenceContext { if ( value instanceof HibernateProxy ) { LOG.debugf( "Setting proxy identifier: %s", id ); - HibernateProxy proxy = (HibernateProxy) value; - LazyInitializer li = proxy.getHibernateLazyInitializer(); - li.setIdentifier(id); - reassociateProxy(li, proxy); + final HibernateProxy proxy = (HibernateProxy) value; + final LazyInitializer li = proxy.getHibernateLazyInitializer(); + li.setIdentifier( id ); + reassociateProxy( li, proxy ); } } @@ -630,11 +570,6 @@ public class StatefulPersistenceContext implements PersistenceContext { } } - /** - * Get the entity instance underlying the given proxy, throwing - * an exception if the proxy is uninitialized. If the given object - * is not a proxy, simply return the argument. - */ @Override public Object unproxy(Object maybeProxy) throws HibernateException { if ( maybeProxy instanceof ElementWrapper ) { @@ -642,28 +577,21 @@ public class StatefulPersistenceContext implements PersistenceContext { } if ( maybeProxy instanceof HibernateProxy ) { - HibernateProxy proxy = (HibernateProxy) maybeProxy; - LazyInitializer li = proxy.getHibernateLazyInitializer(); + final HibernateProxy proxy = (HibernateProxy) maybeProxy; + final LazyInitializer li = proxy.getHibernateLazyInitializer(); if ( li.isUninitialized() ) { throw new PersistentObjectException( - "object was an uninitialized proxy for " + - li.getEntityName() + "object was an uninitialized proxy for " + li.getEntityName() ); } - return li.getImplementation(); //unwrap the object + //unwrap the object and return + return li.getImplementation(); } else { return maybeProxy; } } - /** - * Possibly unproxy the given reference and reassociate it with the current session. - * - * @param maybeProxy The reference to be unproxied if it currently represents a proxy. - * @return The unproxied instance. - * @throws HibernateException - */ @Override public Object unproxyAndReassociate(Object maybeProxy) throws HibernateException { if ( maybeProxy instanceof ElementWrapper ) { @@ -671,25 +599,20 @@ public class StatefulPersistenceContext implements PersistenceContext { } if ( maybeProxy instanceof HibernateProxy ) { - HibernateProxy proxy = (HibernateProxy) maybeProxy; - LazyInitializer li = proxy.getHibernateLazyInitializer(); - reassociateProxy(li, proxy); - return li.getImplementation(); //initialize + unwrap the object + final HibernateProxy proxy = (HibernateProxy) maybeProxy; + final LazyInitializer li = proxy.getHibernateLazyInitializer(); + reassociateProxy( li, proxy ); + //initialize + unwrap the object and return it + return li.getImplementation(); } else { return maybeProxy; } } - /** - * Attempts to check whether the given key represents an entity already loaded within the - * current session. - * @param object The entity reference against which to perform the uniqueness check. - * @throws HibernateException - */ @Override public void checkUniqueness(EntityKey key, Object object) throws HibernateException { - Object entity = getEntity(key); + final Object entity = getEntity( key ); if ( entity == object ) { throw new AssertionFailure( "object already associated, but no entry was found" ); } @@ -698,36 +621,26 @@ public class StatefulPersistenceContext implements PersistenceContext { } } - /** - * If the existing proxy is insufficiently "narrow" (derived), instantiate a new proxy - * and overwrite the registration of the old one. This breaks == and occurs only for - * "class" proxies rather than "interface" proxies. Also init the proxy to point to - * the given target implementation if necessary. - * - * @param proxy The proxy instance to be narrowed. - * @param persister The persister for the proxied entity. - * @param key The internal cache key for the proxied entity. - * @param object (optional) the actual proxied entity instance. - * @return An appropriately narrowed instance. - * @throws HibernateException - */ @Override + @SuppressWarnings("unchecked") public Object narrowProxy(Object proxy, EntityPersister persister, EntityKey key, Object object) throws HibernateException { final Class concreteProxyClass = persister.getConcreteProxyClass(); - boolean alreadyNarrow = concreteProxyClass.isAssignableFrom( proxy.getClass() ); + final boolean alreadyNarrow = concreteProxyClass.isAssignableFrom( proxy.getClass() ); if ( !alreadyNarrow ) { LOG.narrowingProxy( concreteProxyClass ); if ( object != null ) { - proxiesByKey.remove(key); - return object; //return the proxied object + proxiesByKey.remove( key ); + //return the proxied object + return object; } else { proxy = persister.createProxy( key.getIdentifier(), session ); - Object proxyOrig = proxiesByKey.put(key, proxy); //overwrite old proxy + //overwrite old proxy + final Object proxyOrig = proxiesByKey.put( key, proxy ); if ( proxyOrig != null ) { if ( ! ( proxyOrig instanceof HibernateProxy ) ) { throw new AssertionFailure( @@ -735,8 +648,8 @@ public class StatefulPersistenceContext implements PersistenceContext { ); } // set the read-only/modifiable mode in the new proxy to what it was in the original proxy - boolean readOnlyOrig = ( ( HibernateProxy ) proxyOrig ).getHibernateLazyInitializer().isReadOnly(); - ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().setReadOnly( readOnlyOrig ); + final boolean readOnlyOrig = ( (HibernateProxy) proxyOrig ).getHibernateLazyInitializer().isReadOnly(); + ( (HibernateProxy) proxy ).getHibernateLazyInitializer().setReadOnly( readOnlyOrig ); } return proxy; } @@ -744,45 +657,28 @@ public class StatefulPersistenceContext implements PersistenceContext { else { if ( object != null ) { - LazyInitializer li = ( (HibernateProxy) proxy ).getHibernateLazyInitializer(); - li.setImplementation(object); + final LazyInitializer li = ( (HibernateProxy) proxy ).getHibernateLazyInitializer(); + li.setImplementation( object ); } - return proxy; - } - } - /** - * Return the existing proxy associated with the given EntityKey, or the - * third argument (the entity associated with the key) if no proxy exists. Init - * the proxy to the target implementation, if necessary. - */ @Override - public Object proxyFor(EntityPersister persister, EntityKey key, Object impl) - throws HibernateException { + public Object proxyFor(EntityPersister persister, EntityKey key, Object impl) throws HibernateException { if ( !persister.hasProxy() ) { return impl; } - Object proxy = proxiesByKey.get( key ); + final Object proxy = proxiesByKey.get( key ); return ( proxy != null ) ? narrowProxy( proxy, persister, key, impl ) : impl; } - /** - * Return the existing proxy associated with the given EntityKey, or the - * argument (the entity associated with the key) if no proxy exists. - * (slower than the form above) - */ @Override public Object proxyFor(Object impl) throws HibernateException { - EntityEntry e = getEntry(impl); + final EntityEntry e = getEntry( impl ); return proxyFor( e.getPersister(), e.getEntityKey(), impl ); } - /** - * Get the entity that owns this persistent collection - */ @Override public Object getCollectionOwner(Serializable key, CollectionPersister collectionPersister) throws MappingException { // todo : we really just need to add a split in the notions of: @@ -811,7 +707,7 @@ public class StatefulPersistenceContext implements PersistenceContext { // find the corresponding owner instance // a) try by EntityUniqueKey if ( collectionType.getLHSPropertyName() != null ) { - Object owner = getEntity( + final Object owner = getEntity( new EntityUniqueKey( ownerPersister.getEntityName(), collectionType.getLHSPropertyName(), @@ -846,35 +742,23 @@ public class StatefulPersistenceContext implements PersistenceContext { return getEntity( session.generateEntityKey( key, collectionPersister.getOwnerEntityPersister() ) ); } - /** - * Get the entity that owned this persistent collection when it was loaded - * - * @param collection The persistent collection - * @return the owner, if its entity ID is available from the collection's loaded key - * and the owner entity is in the persistence context; otherwise, returns null - */ @Override public Object getLoadedCollectionOwnerOrNull(PersistentCollection collection) { - CollectionEntry ce = getCollectionEntry( collection ); + final CollectionEntry ce = getCollectionEntry( collection ); if ( ce.getLoadedPersister() == null ) { - return null; // early exit... + return null; } + Object loadedOwner = null; // TODO: an alternative is to check if the owner has changed; if it hasn't then // return collection.getOwner() - Serializable entityId = getLoadedCollectionOwnerIdOrNull( ce ); + final Serializable entityId = getLoadedCollectionOwnerIdOrNull( ce ); if ( entityId != null ) { loadedOwner = getCollectionOwner( entityId, ce.getLoadedPersister() ); } return loadedOwner; } - /** - * Get the ID for the entity that owned this persistent collection when it was loaded - * - * @param collection The persistent collection - * @return the owner ID if available from the collection's loaded key; otherwise, returns null - */ @Override public Serializable getLoadedCollectionOwnerIdOrNull(PersistentCollection collection) { return getLoadedCollectionOwnerIdOrNull( getCollectionEntry( collection ) ); @@ -895,39 +779,28 @@ public class StatefulPersistenceContext implements PersistenceContext { return ce.getLoadedPersister().getCollectionType().getIdOfOwnerOrNull( ce.getLoadedKey(), session ); } - /** - * add a collection we just loaded up (still needs initializing) - */ @Override public void addUninitializedCollection(CollectionPersister persister, PersistentCollection collection, Serializable id) { - CollectionEntry ce = new CollectionEntry(collection, persister, id, flushing); - addCollection(collection, ce, id); + final CollectionEntry ce = new CollectionEntry( collection, persister, id, flushing ); + addCollection( collection, ce, id ); if ( persister.getBatchSize() > 1 ) { getBatchFetchQueue().addBatchLoadableCollection( collection, ce ); } } - /** - * add a detached uninitialized collection - */ @Override public void addUninitializedDetachedCollection(CollectionPersister persister, PersistentCollection collection) { - CollectionEntry ce = new CollectionEntry( persister, collection.getKey() ); + final CollectionEntry ce = new CollectionEntry( persister, collection.getKey() ); addCollection( collection, ce, collection.getKey() ); if ( persister.getBatchSize() > 1 ) { getBatchFetchQueue().addBatchLoadableCollection( collection, ce ); } } - /** - * Add a new collection (ie. a newly created one, just instantiated by the - * application, with no database state or snapshot) - * @param collection The collection to be associated with the persistence context - */ @Override public void addNewCollection(CollectionPersister persister, PersistentCollection collection) - throws HibernateException { - addCollection(collection, persister); + throws HibernateException { + addCollection( collection, persister ); } /** @@ -939,11 +812,11 @@ public class StatefulPersistenceContext implements PersistenceContext { */ private void addCollection(PersistentCollection coll, CollectionEntry entry, Serializable key) { collectionEntries.put( coll, entry ); - CollectionKey collectionKey = new CollectionKey( entry.getLoadedPersister(), key ); - PersistentCollection old = collectionsByKey.put( collectionKey, coll ); + final CollectionKey collectionKey = new CollectionKey( entry.getLoadedPersister(), key ); + final PersistentCollection old = collectionsByKey.put( collectionKey, coll ); if ( old != null ) { if ( old == coll ) { - throw new AssertionFailure("bug adding collection twice"); + throw new AssertionFailure( "bug adding collection twice" ); } // or should it actually throw an exception? old.unsetSession( session ); @@ -960,69 +833,52 @@ public class StatefulPersistenceContext implements PersistenceContext { * @param persister The collection persister */ private void addCollection(PersistentCollection collection, CollectionPersister persister) { - CollectionEntry ce = new CollectionEntry( persister, collection ); + final CollectionEntry ce = new CollectionEntry( persister, collection ); collectionEntries.put( collection, ce ); } - /** - * add an (initialized) collection that was created by another session and passed - * into update() (ie. one with a snapshot and existing state on the database) - */ @Override public void addInitializedDetachedCollection(CollectionPersister collectionPersister, PersistentCollection collection) - throws HibernateException { + throws HibernateException { if ( collection.isUnreferenced() ) { //treat it just like a new collection addCollection( collection, collectionPersister ); } else { - CollectionEntry ce = new CollectionEntry( collection, session.getFactory() ); + final CollectionEntry ce = new CollectionEntry( collection, session.getFactory() ); addCollection( collection, ce, collection.getKey() ); } } - /** - * add a collection we just pulled out of the cache (does not need initializing) - */ @Override public CollectionEntry addInitializedCollection(CollectionPersister persister, PersistentCollection collection, Serializable id) - throws HibernateException { - CollectionEntry ce = new CollectionEntry(collection, persister, id, flushing); - ce.postInitialize(collection); - addCollection(collection, ce, id); + throws HibernateException { + final CollectionEntry ce = new CollectionEntry( collection, persister, id, flushing ); + ce.postInitialize( collection ); + addCollection( collection, ce, id ); return ce; } - /** - * Get the collection instance associated with the CollectionKey - */ @Override public PersistentCollection getCollection(CollectionKey collectionKey) { return collectionsByKey.get( collectionKey ); } - /** - * Register a collection for non-lazy loading at the end of the - * two-phase load - */ @Override public void addNonLazyCollection(PersistentCollection collection) { - nonlazyCollections.add(collection); + nonlazyCollections.add( collection ); } - /** - * Force initialization of all non-lazy collections encountered during - * the current two-phase load (actually, this is a no-op, unless this - * is the "outermost" load) - */ @Override public void initializeNonLazyCollections() throws HibernateException { if ( loadCounter == 0 ) { - if (tracing) - LOG.trace( "Initializing non-lazy collections" ); + if ( TRACE_ENABLED ) { + LOG.trace( "Initializing non-lazy collections" ); + } //do this work only at the very highest level of the load - loadCounter++; //don't let this method be called recursively + //don't let this method be called recursively + loadCounter++; try { int size; while ( ( size = nonlazyCollections.size() ) > 0 ) { @@ -1037,20 +893,11 @@ public class StatefulPersistenceContext implements PersistenceContext { } } - - /** - * Get the PersistentCollection object for an array - */ @Override public PersistentCollection getCollectionHolder(Object array) { - return arrayHolders.get(array); + return arrayHolders.get( array ); } - /** - * Register a PersistentCollection object for an array. - * Associates a holder with an array - MUST be called after loading - * array, since the array instance is not created until endLoad(). - */ @Override public void addCollectionHolder(PersistentCollection holder) { //TODO:refactor + make this method private @@ -1059,22 +906,14 @@ public class StatefulPersistenceContext implements PersistenceContext { @Override public PersistentCollection removeCollectionHolder(Object array) { - return arrayHolders.remove(array); + return arrayHolders.remove( array ); } - /** - * Get the snapshot of the pre-flush collection state - */ @Override public Serializable getSnapshot(PersistentCollection coll) { - return getCollectionEntry(coll).getSnapshot(); + return getCollectionEntry( coll ).getSnapshot(); } - /** - * Get the collection entry for a collection passed to filter, - * which might be a collection wrapper, an array, or an unwrapped - * collection. Return null if there is no entry. - */ @Override public CollectionEntry getCollectionEntryOrNull(Object collection) { PersistentCollection coll; @@ -1083,14 +922,14 @@ public class StatefulPersistenceContext implements PersistenceContext { //if (collection==null) throw new TransientObjectException("Collection was not yet persistent"); } else { - coll = getCollectionHolder(collection); + coll = getCollectionHolder( collection ); if ( coll == null ) { //it might be an unwrapped collection reference! //try to find a wrapper (slowish) - Iterator wrappers = collectionEntries.keyIterator(); + final Iterator wrappers = collectionEntries.keyIterator(); while ( wrappers.hasNext() ) { - PersistentCollection pc = wrappers.next(); - if ( pc.isWrapper(collection) ) { + final PersistentCollection pc = wrappers.next(); + if ( pc.isWrapper( collection ) ) { coll = pc; break; } @@ -1098,34 +937,19 @@ public class StatefulPersistenceContext implements PersistenceContext { } } - return (coll == null) ? null : getCollectionEntry(coll); + return (coll == null) ? null : getCollectionEntry( coll ); } - /** - * Get an existing proxy by key - */ @Override public Object getProxy(EntityKey key) { - return proxiesByKey.get(key); + return proxiesByKey.get( key ); } - /** - * Add a proxy to the session cache - */ @Override public void addProxy(EntityKey key, Object proxy) { - proxiesByKey.put(key, proxy); + proxiesByKey.put( key, proxy ); } - /** - * Remove a proxy from the session cache. - *

      - * Additionally, ensure that any load optimization references - * such as batch or subselect loading get cleaned up as well. - * - * @param key The key of the entity proxy to be removed - * @return The proxy reference. - */ @Override public Object removeProxy(EntityKey key) { if ( batchFetchQueue != null ) { @@ -1135,9 +959,6 @@ public class StatefulPersistenceContext implements PersistenceContext { return proxiesByKey.remove( key ); } - /** - * Retrieve the set of EntityKeys representing nullifiable references - */ @Override public HashSet getNullifiableEntityKeys() { return nullifiableEntityKeys; @@ -1222,20 +1043,10 @@ public class StatefulPersistenceContext implements PersistenceContext { return loadCounter == 0; } - /** - * Returns a string representation of the object. - * - * @return a string representation of the object. - */ @Override - public String toString() { - return new StringBuilder() - .append("PersistenceContext[entityKeys=") - .append(entitiesByKey.keySet()) - .append(",collectionKeys=") - .append(collectionsByKey.keySet()) - .append("]") - .toString(); + public String toString() { + return "PersistenceContext[entityKeys=" + entitiesByKey.keySet() + + ",collectionKeys=" + collectionsByKey.keySet() + "]"; } @Override @@ -1243,27 +1054,6 @@ public class StatefulPersistenceContext implements PersistenceContext { return entityEntryContext.reentrantSafeEntityEntries(); } - /** - * Search this persistence context for an associated entity instance which is considered the "owner" of - * the given childEntity, and return that owner's id value. This is performed in the scenario of a - * uni-directional, non-inverse one-to-many collection (which means that the collection elements do not maintain - * a direct reference to the owner). - *

      - * As such, the processing here is basically to loop over every entity currently associated with this persistence - * context and for those of the correct entity (sub) type to extract its collection role property value and see - * if the child is contained within that collection. If so, we have found the owner; if not, we go on. - *

      - * Also need to account for mergeMap which acts as a local copy cache managed for the duration of a merge - * operation. It represents a map of the detached entity instances pointing to the corresponding managed instance. - * - * @param entityName The entity name for the entity type which would own the child - * @param propertyName The name of the property on the owning entity type which would name this child association. - * @param childEntity The child entity instance for which to locate the owner instance id. - * @param mergeMap A map of non-persistent instances from an on-going merge operation (possibly null). - * - * @return The id of the entityName instance which is said to own the child; null if an appropriate owner not - * located. - */ @Override public Serializable getOwnerId(String entityName, String propertyName, Object childEntity, Map mergeMap) { final String collectionRole = entityName + '.' + propertyName; @@ -1271,24 +1061,23 @@ public class StatefulPersistenceContext implements PersistenceContext { final CollectionPersister collectionPersister = session.getFactory().getCollectionPersister( collectionRole ); // try cache lookup first - Object parent = parentsByChild.get( childEntity ); + final Object parent = parentsByChild.get( childEntity ); if ( parent != null ) { final EntityEntry entityEntry = entityEntryContext.getEntityEntry( parent ); -// final EntityEntry entityEntry = entityEntries.get( parent ); //there maybe more than one parent, filter by type - if ( persister.isSubclassEntityName(entityEntry.getEntityName() ) + if ( persister.isSubclassEntityName( entityEntry.getEntityName() ) && isFoundInParent( propertyName, childEntity, persister, collectionPersister, parent ) ) { return getEntry( parent ).getId(); } else { - parentsByChild.remove( childEntity ); // remove wrong entry + // remove wrong entry + parentsByChild.remove( childEntity ); } } //not found in case, proceed // iterate all the entities currently associated with the persistence context. for ( Entry me : reentrantSafeEntityEntries() ) { -// for ( Entry me : IdentityMap.concurrentEntries( entityEntries ) ) { final EntityEntry entityEntry = me.getValue(); // does this entity entry pertain to the entity persister in which we are interested (owner)? if ( persister.isSubclassEntityName( entityEntry.getEntityName() ) ) { @@ -1305,8 +1094,8 @@ public class StatefulPersistenceContext implements PersistenceContext { if ( !found && mergeMap != null ) { //check if the detached object being merged is the parent - Object unmergedInstance = mergeMap.get( entityEntryInstance ); - Object unmergedChild = mergeMap.get( childEntity ); + final Object unmergedInstance = mergeMap.get( entityEntryInstance ); + final Object unmergedChild = mergeMap.get( childEntity ); if ( unmergedInstance != null && unmergedChild != null ) { found = isFoundInParent( propertyName, @@ -1367,66 +1156,60 @@ public class StatefulPersistenceContext implements PersistenceContext { EntityPersister persister, CollectionPersister collectionPersister, Object potentialParent) { - Object collection = persister.getPropertyValue( potentialParent, property ); + final Object collection = persister.getPropertyValue( potentialParent, property ); return collection != null && Hibernate.isInitialized( collection ) && collectionPersister.getCollectionType().contains( collection, childEntity, session ); } - /** - * Search the persistence context for an index of the child object, - * given a collection role - */ @Override public Object getIndexInOwner(String entity, String property, Object childEntity, Map mergeMap) { - - EntityPersister persister = session.getFactory() - .getEntityPersister(entity); - CollectionPersister cp = session.getFactory() - .getCollectionPersister(entity + '.' + property); + final EntityPersister persister = session.getFactory().getEntityPersister( entity ); + final CollectionPersister cp = session.getFactory().getCollectionPersister( entity + '.' + property ); // try cache lookup first - Object parent = parentsByChild.get(childEntity); - if (parent != null) { + final Object parent = parentsByChild.get( childEntity ); + if ( parent != null ) { final EntityEntry entityEntry = entityEntryContext.getEntityEntry( parent ); -// final EntityEntry entityEntry = entityEntries.get(parent); //there maybe more than one parent, filter by type if ( persister.isSubclassEntityName( entityEntry.getEntityName() ) ) { - Object index = getIndexInParent(property, childEntity, persister, cp, parent); + Object index = getIndexInParent( property, childEntity, persister, cp, parent ); if (index==null && mergeMap!=null) { - Object unmergedInstance = mergeMap.get(parent); - Object unmergedChild = mergeMap.get(childEntity); - if ( unmergedInstance!=null && unmergedChild!=null ) { - index = getIndexInParent(property, unmergedChild, persister, cp, unmergedInstance); + final Object unMergedInstance = mergeMap.get( parent ); + final Object unMergedChild = mergeMap.get( childEntity ); + if ( unMergedInstance != null && unMergedChild != null ) { + index = getIndexInParent( property, unMergedChild, persister, cp, unMergedInstance ); } } - if (index!=null) { + if ( index != null ) { return index; } } else { - parentsByChild.remove(childEntity); // remove wrong entry + // remove wrong entry + parentsByChild.remove( childEntity ); } } //Not found in cache, proceed for ( Entry me : reentrantSafeEntityEntries() ) { - EntityEntry ee = me.getValue(); + final EntityEntry ee = me.getValue(); if ( persister.isSubclassEntityName( ee.getEntityName() ) ) { - Object instance = me.getKey(); + final Object instance = me.getKey(); - Object index = getIndexInParent(property, childEntity, persister, cp, instance); - - if (index==null && mergeMap!=null) { - Object unmergedInstance = mergeMap.get(instance); - Object unmergedChild = mergeMap.get(childEntity); - if ( unmergedInstance!=null && unmergedChild!=null ) { - index = getIndexInParent(property, unmergedChild, persister, cp, unmergedInstance); + Object index = getIndexInParent( property, childEntity, persister, cp, instance ); + if ( index==null && mergeMap!=null ) { + final Object unMergedInstance = mergeMap.get( instance ); + final Object unMergedChild = mergeMap.get( childEntity ); + if ( unMergedInstance != null && unMergedChild!=null ) { + index = getIndexInParent( property, unMergedChild, persister, cp, unMergedInstance ); } } - if (index!=null) return index; + if ( index != null ) { + return index; + } } } return null; @@ -1438,30 +1221,23 @@ public class StatefulPersistenceContext implements PersistenceContext { EntityPersister persister, CollectionPersister collectionPersister, Object potentialParent){ - Object collection = persister.getPropertyValue( potentialParent, property ); - if ( collection!=null && Hibernate.isInitialized(collection) ) { - return collectionPersister.getCollectionType().indexOf(collection, childEntity); + final Object collection = persister.getPropertyValue( potentialParent, property ); + if ( collection != null && Hibernate.isInitialized( collection ) ) { + return collectionPersister.getCollectionType().indexOf( collection, childEntity ); } else { return null; } } - /** - * Record the fact that the association belonging to the keyed - * entity is null. - */ @Override public void addNullProperty(EntityKey ownerKey, String propertyName) { - nullAssociations.add( new AssociationKey(ownerKey, propertyName) ); + nullAssociations.add( new AssociationKey( ownerKey, propertyName ) ); } - /** - * Is the association property belonging to the keyed entity null? - */ @Override public boolean isPropertyNull(EntityKey ownerKey, String propertyName) { - return nullAssociations.contains( new AssociationKey(ownerKey, propertyName) ); + return nullAssociations.contains( new AssociationKey( ownerKey, propertyName ) ); } private void clearNullProperties() { @@ -1475,10 +1251,10 @@ public class StatefulPersistenceContext implements PersistenceContext { } boolean isReadOnly; if ( entityOrProxy instanceof HibernateProxy ) { - isReadOnly = ( ( HibernateProxy ) entityOrProxy ).getHibernateLazyInitializer().isReadOnly(); + isReadOnly = ( (HibernateProxy) entityOrProxy ).getHibernateLazyInitializer().isReadOnly(); } else { - EntityEntry ee = getEntry( entityOrProxy ); + final EntityEntry ee = getEntry( entityOrProxy ); if ( ee == null ) { throw new TransientObjectException("Instance was not associated with this persistence context" ); } @@ -1496,7 +1272,7 @@ public class StatefulPersistenceContext implements PersistenceContext { return; } if ( object instanceof HibernateProxy ) { - HibernateProxy proxy = ( HibernateProxy ) object; + final HibernateProxy proxy = (HibernateProxy) object; setProxyReadOnly( proxy, readOnly ); if ( Hibernate.isInitialized( proxy ) ) { setEntityReadOnly( @@ -1509,9 +1285,9 @@ public class StatefulPersistenceContext implements PersistenceContext { setEntityReadOnly( object, readOnly ); // PersistenceContext.proxyFor( entity ) returns entity if there is no proxy for that entity // so need to check the return value to be sure it is really a proxy - Object maybeProxy = getSession().getPersistenceContext().proxyFor( object ); + final Object maybeProxy = getSession().getPersistenceContext().proxyFor( object ); if ( maybeProxy instanceof HibernateProxy ) { - setProxyReadOnly( ( HibernateProxy ) maybeProxy, readOnly ); + setProxyReadOnly( (HibernateProxy) maybeProxy, readOnly ); } } } @@ -1525,11 +1301,11 @@ public class StatefulPersistenceContext implements PersistenceContext { } private void setEntityReadOnly(Object entity, boolean readOnly) { - EntityEntry entry = getEntry(entity); - if (entry == null) { - throw new TransientObjectException("Instance was not associated with this persistence context" ); + final EntityEntry entry = getEntry( entity ); + if ( entry == null ) { + throw new TransientObjectException( "Instance was not associated with this persistence context" ); } - entry.setReadOnly(readOnly, entity ); + entry.setReadOnly( readOnly, entity ); hasNonReadOnlyEntities = hasNonReadOnlyEntities || ! readOnly; } @@ -1543,16 +1319,16 @@ public class StatefulPersistenceContext implements PersistenceContext { addEntity( newKey, entity ); addEntry( entity, - oldEntry.getStatus(), - oldEntry.getLoadedState(), - oldEntry.getRowId(), - generatedId, - oldEntry.getVersion(), - oldEntry.getLockMode(), - oldEntry.isExistsInDatabase(), - oldEntry.getPersister(), - oldEntry.isBeingReplicated(), - oldEntry.isLoadedWithLazyPropertiesUnfetched() + oldEntry.getStatus(), + oldEntry.getLoadedState(), + oldEntry.getRowId(), + generatedId, + oldEntry.getVersion(), + oldEntry.getLockMode(), + oldEntry.isExistsInDatabase(), + oldEntry.getPersister(), + oldEntry.isBeingReplicated(), + oldEntry.isLoadedWithLazyPropertiesUnfetched() ); } @@ -1565,97 +1341,106 @@ public class StatefulPersistenceContext implements PersistenceContext { */ public void serialize(ObjectOutputStream oos) throws IOException { final boolean tracing = LOG.isTraceEnabled(); - if ( tracing ) LOG.trace( "Serializing persistent-context" ); + if ( tracing ) { + LOG.trace( "Serializing persistence-context" ); + } oos.writeBoolean( defaultReadOnly ); oos.writeBoolean( hasNonReadOnlyEntities ); oos.writeInt( entitiesByKey.size() ); - if ( tracing ) LOG.trace("Starting serialization of [" + entitiesByKey.size() + "] entitiesByKey entries"); - Iterator itr = entitiesByKey.entrySet().iterator(); - while ( itr.hasNext() ) { - Map.Entry entry = ( Map.Entry ) itr.next(); - ( ( EntityKey ) entry.getKey() ).serialize( oos ); + if ( tracing ) { + LOG.trace( "Starting serialization of [" + entitiesByKey.size() + "] entitiesByKey entries" ); + } + for ( Map.Entry entry : entitiesByKey.entrySet() ) { + entry.getKey().serialize( oos ); oos.writeObject( entry.getValue() ); } oos.writeInt( entitiesByUniqueKey.size() ); - if ( tracing ) LOG.trace("Starting serialization of [" + entitiesByUniqueKey.size() + "] entitiesByUniqueKey entries"); - itr = entitiesByUniqueKey.entrySet().iterator(); - while ( itr.hasNext() ) { - Map.Entry entry = ( Map.Entry ) itr.next(); - ( ( EntityUniqueKey ) entry.getKey() ).serialize( oos ); + if ( tracing ) { + LOG.trace( "Starting serialization of [" + entitiesByUniqueKey.size() + "] entitiesByUniqueKey entries" ); + } + for ( Map.Entry entry : entitiesByUniqueKey.entrySet() ) { + entry.getKey().serialize( oos ); oos.writeObject( entry.getValue() ); } oos.writeInt( proxiesByKey.size() ); - if ( tracing ) LOG.trace("Starting serialization of [" + proxiesByKey.size() + "] proxiesByKey entries"); - itr = proxiesByKey.entrySet().iterator(); - while ( itr.hasNext() ) { - Map.Entry entry = ( Map.Entry ) itr.next(); - ( (EntityKey) entry.getKey() ).serialize( oos ); + if ( tracing ) { + LOG.trace( "Starting serialization of [" + proxiesByKey.size() + "] proxiesByKey entries" ); + } + for ( Map.Entry entry : proxiesByKey.entrySet() ) { + entry.getKey().serialize( oos ); oos.writeObject( entry.getValue() ); } oos.writeInt( entitySnapshotsByKey.size() ); - if ( tracing ) LOG.trace("Starting serialization of [" + entitySnapshotsByKey.size() + "] entitySnapshotsByKey entries"); - itr = entitySnapshotsByKey.entrySet().iterator(); - while ( itr.hasNext() ) { - Map.Entry entry = ( Map.Entry ) itr.next(); - ( ( EntityKey ) entry.getKey() ).serialize( oos ); + if ( tracing ) { + LOG.trace( "Starting serialization of [" + entitySnapshotsByKey.size() + "] entitySnapshotsByKey entries" ); + } + for ( Map.Entry entry : entitySnapshotsByKey.entrySet() ) { + entry.getKey().serialize( oos ); oos.writeObject( entry.getValue() ); } entityEntryContext.serialize( oos ); -// oos.writeInt( entityEntries.size() ); -// if ( tracing ) LOG.trace("Starting serialization of [" + entityEntries.size() + "] entityEntries entries"); -// itr = entityEntries.entrySet().iterator(); -// while ( itr.hasNext() ) { -// Map.Entry entry = ( Map.Entry ) itr.next(); -// oos.writeObject( entry.getKey() ); -// ( ( EntityEntry ) entry.getValue() ).serialize( oos ); -// } oos.writeInt( collectionsByKey.size() ); - if ( tracing ) LOG.trace("Starting serialization of [" + collectionsByKey.size() + "] collectionsByKey entries"); - itr = collectionsByKey.entrySet().iterator(); - while ( itr.hasNext() ) { - Map.Entry entry = ( Map.Entry ) itr.next(); - ( ( CollectionKey ) entry.getKey() ).serialize( oos ); + if ( tracing ) { + LOG.trace( "Starting serialization of [" + collectionsByKey.size() + "] collectionsByKey entries" ); + } + for ( Map.Entry entry : collectionsByKey.entrySet() ) { + entry.getKey().serialize( oos ); oos.writeObject( entry.getValue() ); } oos.writeInt( collectionEntries.size() ); - if ( tracing ) LOG.trace("Starting serialization of [" + collectionEntries.size() + "] collectionEntries entries"); - itr = collectionEntries.entrySet().iterator(); - while ( itr.hasNext() ) { - Map.Entry entry = ( Map.Entry ) itr.next(); + if ( tracing ) { + LOG.trace( "Starting serialization of [" + collectionEntries.size() + "] collectionEntries entries" ); + } + for ( Map.Entry entry : collectionEntries.entrySet() ) { oos.writeObject( entry.getKey() ); - ( ( CollectionEntry ) entry.getValue() ).serialize( oos ); + entry.getValue().serialize( oos ); } oos.writeInt( arrayHolders.size() ); - if ( tracing ) LOG.trace("Starting serialization of [" + arrayHolders.size() + "] arrayHolders entries"); - itr = arrayHolders.entrySet().iterator(); - while ( itr.hasNext() ) { - Map.Entry entry = ( Map.Entry ) itr.next(); + if ( tracing ) { + LOG.trace( "Starting serialization of [" + arrayHolders.size() + "] arrayHolders entries" ); + } + for ( Map.Entry entry : arrayHolders.entrySet() ) { oos.writeObject( entry.getKey() ); oos.writeObject( entry.getValue() ); } oos.writeInt( nullifiableEntityKeys.size() ); - if ( tracing ) LOG.trace("Starting serialization of [" + nullifiableEntityKeys.size() + "] nullifiableEntityKey entries"); + if ( tracing ) { + LOG.trace( "Starting serialization of [" + nullifiableEntityKeys.size() + "] nullifiableEntityKey entries" ); + } for ( EntityKey entry : nullifiableEntityKeys ) { entry.serialize( oos ); } } + /** + * Used by the owning session to explicitly control deserialization of the persistence context. + * + * @param ois The stream from which the persistence context should be read + * @param session The owning session + * + * @return The deserialized StatefulPersistenceContext + * + * @throws IOException deserialization errors. + * @throws ClassNotFoundException deserialization errors. + */ public static StatefulPersistenceContext deserialize( ObjectInputStream ois, SessionImplementor session) throws IOException, ClassNotFoundException { final boolean tracing = LOG.isTraceEnabled(); - if ( tracing ) LOG.trace("Serializing persistent-context"); - StatefulPersistenceContext rtn = new StatefulPersistenceContext( session ); + if ( tracing ) { + LOG.trace( "Serializing persistent-context" ); + } + final StatefulPersistenceContext rtn = new StatefulPersistenceContext( session ); // during deserialization, we need to reconnect all proxies and // collections to this session, as well as the EntityEntry and @@ -1668,21 +1453,27 @@ public class StatefulPersistenceContext implements PersistenceContext { rtn.hasNonReadOnlyEntities = ois.readBoolean(); int count = ois.readInt(); - if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] entitiesByKey entries"); + if ( tracing ) { + LOG.trace( "Starting deserialization of [" + count + "] entitiesByKey entries" ); + } rtn.entitiesByKey = new HashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count ); for ( int i = 0; i < count; i++ ) { rtn.entitiesByKey.put( EntityKey.deserialize( ois, session ), ois.readObject() ); } count = ois.readInt(); - if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] entitiesByUniqueKey entries"); + if ( tracing ) { + LOG.trace( "Starting deserialization of [" + count + "] entitiesByUniqueKey entries" ); + } rtn.entitiesByUniqueKey = new HashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count ); for ( int i = 0; i < count; i++ ) { rtn.entitiesByUniqueKey.put( EntityUniqueKey.deserialize( ois, session ), ois.readObject() ); } count = ois.readInt(); - if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] proxiesByKey entries"); + if ( tracing ) { + LOG.trace( "Starting deserialization of [" + count + "] proxiesByKey entries" ); + } //noinspection unchecked rtn.proxiesByKey = new ConcurrentReferenceHashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count, @@ -1693,60 +1484,65 @@ public class StatefulPersistenceContext implements PersistenceContext { null ); for ( int i = 0; i < count; i++ ) { - EntityKey ek = EntityKey.deserialize( ois, session ); - Object proxy = ois.readObject(); + final EntityKey ek = EntityKey.deserialize( ois, session ); + final Object proxy = ois.readObject(); if ( proxy instanceof HibernateProxy ) { - ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().setSession( session ); + ( (HibernateProxy) proxy ).getHibernateLazyInitializer().setSession( session ); rtn.proxiesByKey.put( ek, proxy ); - } else { - if ( tracing ) LOG.trace("Encountered prunded proxy"); } - // otherwise, the proxy was pruned during the serialization process + else { + // otherwise, the proxy was pruned during the serialization process + if ( tracing ) { + LOG.trace( "Encountered pruned proxy" ); + } + } } count = ois.readInt(); - if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] entitySnapshotsByKey entries"); + if ( tracing ) { + LOG.trace( "Starting deserialization of [" + count + "] entitySnapshotsByKey entries" ); + } rtn.entitySnapshotsByKey = new HashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count ); for ( int i = 0; i < count; i++ ) { rtn.entitySnapshotsByKey.put( EntityKey.deserialize( ois, session ), ois.readObject() ); } rtn.entityEntryContext = EntityEntryContext.deserialize( ois, rtn ); -// count = ois.readInt(); -// if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] entityEntries entries"); -// rtn.entityEntries = IdentityMap.instantiateSequenced( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count ); -// for ( int i = 0; i < count; i++ ) { -// Object entity = ois.readObject(); -// EntityEntry entry = EntityEntry.deserialize( ois, rtn ); -// rtn.entityEntries.put( entity, entry ); -// } count = ois.readInt(); - if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] collectionsByKey entries"); + if ( tracing ) { + LOG.trace( "Starting deserialization of [" + count + "] collectionsByKey entries" ); + } rtn.collectionsByKey = new HashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count ); for ( int i = 0; i < count; i++ ) { rtn.collectionsByKey.put( CollectionKey.deserialize( ois, session ), (PersistentCollection) ois.readObject() ); } count = ois.readInt(); - if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] collectionEntries entries"); + if ( tracing ) { + LOG.trace( "Starting deserialization of [" + count + "] collectionEntries entries" ); + } rtn.collectionEntries = IdentityMap.instantiateSequenced( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count ); for ( int i = 0; i < count; i++ ) { - final PersistentCollection pc = ( PersistentCollection ) ois.readObject(); + final PersistentCollection pc = (PersistentCollection) ois.readObject(); final CollectionEntry ce = CollectionEntry.deserialize( ois, session ); pc.setCurrentSession( session ); rtn.collectionEntries.put( pc, ce ); } count = ois.readInt(); - if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] arrayHolders entries"); + if ( tracing ) { + LOG.trace( "Starting deserialization of [" + count + "] arrayHolders entries" ); + } rtn.arrayHolders = new IdentityHashMap( count < INIT_COLL_SIZE ? INIT_COLL_SIZE : count ); for ( int i = 0; i < count; i++ ) { rtn.arrayHolders.put( ois.readObject(), (PersistentCollection) ois.readObject() ); } count = ois.readInt(); - if ( tracing ) LOG.trace("Starting deserialization of [" + count + "] nullifiableEntityKey entries"); + if ( tracing ) { + LOG.trace( "Starting deserialization of [" + count + "] nullifiableEntityKey entries" ); + } rtn.nullifiableEntityKeys = new HashSet(); for ( int i = 0; i < count; i++ ) { rtn.nullifiableEntityKeys.add( EntityKey.deserialize( ois, session ) ); @@ -1762,12 +1558,12 @@ public class StatefulPersistenceContext implements PersistenceContext { @Override public void addChildParent(Object child, Object parent) { - parentsByChild.put(child, parent); + parentsByChild.put( child, parent ); } @Override public void removeChildParent(Object child) { - parentsByChild.remove(child); + parentsByChild.remove( child ); } @@ -1797,7 +1593,7 @@ public class StatefulPersistenceContext implements PersistenceContext { // again, we only really care if the entity is cached if ( persister.hasCache() ) { if ( insertedKeysMap != null ) { - List insertedEntityIds = insertedKeysMap.get( persister.getRootEntityName() ); + final List insertedEntityIds = insertedKeysMap.get( persister.getRootEntityName() ); if ( insertedEntityIds != null ) { return insertedEntityIds.contains( id ); } @@ -1835,7 +1631,7 @@ public class StatefulPersistenceContext implements PersistenceContext { // from a single load event. The first put journal would come from the natural id resolution; // the second comes from the entity loading. In this condition, we want to avoid the multiple // 'put' stats incrementing. - boolean justAddedLocally = naturalIdXrefDelegate.cacheNaturalIdCrossReference( persister, id, naturalIdValues ); + final boolean justAddedLocally = naturalIdXrefDelegate.cacheNaturalIdCrossReference( persister, id, naturalIdValues ); if ( justAddedLocally && persister.hasNaturalIdCache() ) { managedSharedCacheEntries( persister, id, naturalIdValues, null, CachedNaturalIdValueSource.LOAD ); @@ -1898,8 +1694,9 @@ public class StatefulPersistenceContext implements PersistenceContext { switch ( source ) { case LOAD: { - if (naturalIdCacheAccessStrategy.get(naturalIdCacheKey, session.getTimestamp()) != null) { - return; // prevent identical re-cachings + if ( naturalIdCacheAccessStrategy.get( naturalIdCacheKey, session.getTimestamp() ) != null ) { + // prevent identical re-cachings + return; } final boolean put = naturalIdCacheAccessStrategy.putFromLoad( naturalIdCacheKey, @@ -1937,7 +1734,7 @@ public class StatefulPersistenceContext implements PersistenceContext { } } else { - naturalIdCacheAccessStrategy.remove(naturalIdCacheKey); + naturalIdCacheAccessStrategy.remove( naturalIdCacheKey ); } } } @@ -1947,8 +1744,9 @@ public class StatefulPersistenceContext implements PersistenceContext { } case UPDATE: { final NaturalIdCacheKey previousCacheKey = new NaturalIdCacheKey( previousNaturalIdValues, persister, session ); - if (naturalIdCacheKey.equals(previousCacheKey)) { - return; // prevent identical re-caching, solves HHH-7309 + if ( naturalIdCacheKey.equals( previousCacheKey ) ) { + // prevent identical re-caching, solves HHH-7309 + return; } final SoftLock removalLock = naturalIdCacheAccessStrategy.lockItem( previousCacheKey, null ); naturalIdCacheAccessStrategy.remove( previousCacheKey ); @@ -1982,6 +1780,9 @@ public class StatefulPersistenceContext implements PersistenceContext { break; } + default: { + LOG.debug( "Unexpected CachedNaturalIdValueSource [" + source + "]" ); + } } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/TwoPhaseLoad.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/TwoPhaseLoad.java index 2cdf7f9c88..e8d2c6ca38 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/TwoPhaseLoad.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/TwoPhaseLoad.java @@ -56,17 +56,19 @@ import org.hibernate.type.Type; import org.hibernate.type.TypeHelper; /** - * Functionality relating to Hibernate's two-phase loading process, - * that may be reused by persisters that do not use the Loader - * framework + * Functionality relating to the Hibernate two-phase loading process, that may be reused by persisters + * that do not use the Loader framework * * @author Gavin King */ public final class TwoPhaseLoad { + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + TwoPhaseLoad.class.getName() + ); - private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, TwoPhaseLoad.class.getName() ); - - private TwoPhaseLoad() {} + private TwoPhaseLoad() { + } /** * Register the "hydrated" state of an entity instance, after the first step of 2-phase loading. @@ -74,19 +76,26 @@ public final class TwoPhaseLoad { * Add the "hydrated state" (an array) of an uninitialized entity to the session. We don't try * to resolve any associations yet, because there might be other entities waiting to be * read from the JDBC result set we are currently processing + * + * @param persister The persister for the hydrated entity + * @param id The entity identifier + * @param values The entity values + * @param rowId The rowId for the entity + * @param object An optional instance for the entity being loaded + * @param lockMode The lock mode + * @param lazyPropertiesAreUnFetched Whether properties defined as lazy are yet un-fetched + * @param session The Session */ public static void postHydrate( - final EntityPersister persister, - final Serializable id, - final Object[] values, - final Object rowId, - final Object object, - final LockMode lockMode, - final boolean lazyPropertiesAreUnfetched, - final SessionImplementor session) - throws HibernateException { - - Object version = Versioning.getVersion( values, persister ); + final EntityPersister persister, + final Serializable id, + final Object[] values, + final Object rowId, + final Object object, + final LockMode lockMode, + final boolean lazyPropertiesAreUnFetched, + final SessionImplementor session) throws HibernateException { + final Object version = Versioning.getVersion( values, persister ); session.getPersistenceContext().addEntry( object, Status.LOADING, @@ -98,47 +107,41 @@ public final class TwoPhaseLoad { true, persister, false, - lazyPropertiesAreUnfetched + lazyPropertiesAreUnFetched ); if ( version != null && LOG.isTraceEnabled() ) { - String versionStr = persister.isVersioned() + final String versionStr = persister.isVersioned() ? persister.getVersionType().toLoggableString( version, session.getFactory() ) : "null"; - LOG.tracev( "Version: {0}", versionStr ); + LOG.tracef( "Version: %s", versionStr ); } - } /** * Perform the second step of 2-phase load. Fully initialize the entity * instance. - * + *

      * After processing a JDBC result set, we "resolve" all the associations * between the entities which were instantiated and had their state * "hydrated" into an array + * + * @param entity The entity being loaded + * @param readOnly Is the entity being loaded as read-only + * @param session The Session + * @param preLoadEvent The (re-used) pre-load event */ public static void initializeEntity( final Object entity, final boolean readOnly, final SessionImplementor session, - final PreLoadEvent preLoadEvent, - final PostLoadEvent postLoadEvent) throws HibernateException { + final PreLoadEvent preLoadEvent) { final PersistenceContext persistenceContext = session.getPersistenceContext(); - final EntityEntry entityEntry = persistenceContext.getEntry(entity); + final EntityEntry entityEntry = persistenceContext.getEntry( entity ); if ( entityEntry == null ) { throw new AssertionFailure( "possible non-threadsafe access to the session" ); } - final EntityPersister persister = entityEntry.getPersister(); - final Serializable id = entityEntry.getId(); - -// persistenceContext.getNaturalIdHelper().startingLoad( persister, id ); -// try { - doInitializeEntity( entity, entityEntry, readOnly, session, preLoadEvent, postLoadEvent ); -// } -// finally { -// persistenceContext.getNaturalIdHelper().endingLoad( persister, id ); -// } + doInitializeEntity( entity, entityEntry, readOnly, session, preLoadEvent ); } private static void doInitializeEntity( @@ -146,12 +149,11 @@ public final class TwoPhaseLoad { final EntityEntry entityEntry, final boolean readOnly, final SessionImplementor session, - final PreLoadEvent preLoadEvent, - final PostLoadEvent postLoadEvent) throws HibernateException { + final PreLoadEvent preLoadEvent) throws HibernateException { final PersistenceContext persistenceContext = session.getPersistenceContext(); - EntityPersister persister = entityEntry.getPersister(); - Serializable id = entityEntry.getId(); - Object[] hydratedState = entityEntry.getLoadedState(); + final EntityPersister persister = entityEntry.getPersister(); + final Serializable id = entityEntry.getId(); + final Object[] hydratedState = entityEntry.getLoadedState(); final boolean debugEnabled = LOG.isDebugEnabled(); if ( debugEnabled ) { @@ -161,7 +163,7 @@ public final class TwoPhaseLoad { ); } - Type[] types = persister.getPropertyTypes(); + final Type[] types = persister.getPropertyTypes(); for ( int i = 0; i < hydratedState.length; i++ ) { final Object value = hydratedState[i]; if ( value!=LazyPropertyInitializer.UNFETCHED_PROPERTY && value!=BackrefPropertyAccessor.UNKNOWN ) { @@ -195,9 +197,9 @@ public final class TwoPhaseLoad { ); } - Object version = Versioning.getVersion(hydratedState, persister); - CacheEntry entry = persister.buildCacheEntry( entity, hydratedState, version, session ); - CacheKey cacheKey = session.generateCacheKey( id, persister.getIdentifierType(), persister.getRootEntityName() ); + final Object version = Versioning.getVersion( hydratedState, persister ); + final CacheEntry entry = persister.buildCacheEntry( entity, hydratedState, version, session ); + final CacheKey cacheKey = session.generateCacheKey( id, persister.getIdentifierType(), persister.getRootEntityName() ); // explicit handling of caching for rows just inserted and then somehow forced to be read // from the database *within the same transaction*. usually this is done by @@ -214,7 +216,7 @@ public final class TwoPhaseLoad { ); } else { - boolean put = persister.getCacheAccessStrategy().putFromLoad( + final boolean put = persister.getCacheAccessStrategy().putFromLoad( cacheKey, persister.getCacheEntryStructure().structure( entry ), session.getTimestamp(), @@ -241,11 +243,11 @@ public final class TwoPhaseLoad { isReallyReadOnly = true; } else { - Object proxy = persistenceContext.getProxy( entityEntry.getEntityKey() ); + final Object proxy = persistenceContext.getProxy( entityEntry.getEntityKey() ); if ( proxy != null ) { // there is already a proxy for this impl // only set the status to read-only if the proxy is read-only - isReallyReadOnly = ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer().isReadOnly(); + isReallyReadOnly = ( (HibernateProxy) proxy ).getHibernateLazyInitializer().isReadOnly(); } } if ( isReallyReadOnly ) { @@ -253,7 +255,7 @@ public final class TwoPhaseLoad { //performance optimization, but not really //important, except for entities with huge //mutable property values - persistenceContext.setEntryStatus(entityEntry, Status.READ_ONLY); + persistenceContext.setEntryStatus( entityEntry, Status.READ_ONLY ); } else { //take a snapshot @@ -261,10 +263,11 @@ public final class TwoPhaseLoad { hydratedState, persister.getPropertyTypes(), persister.getPropertyUpdateability(), - hydratedState, //after setting values to object, entityMode + //after setting values to object + hydratedState, session ); - persistenceContext.setEntryStatus(entityEntry, Status.MANAGED); + persistenceContext.setEntryStatus( entityEntry, Status.MANAGED ); } persister.afterInitialize( @@ -290,13 +293,12 @@ public final class TwoPhaseLoad { * the Set collections are added to the persistence context by Loader. * Without the split, LazyInitializationExceptions can occur in the Entity's * postLoad if it acts upon the collection. - * - * + * * HHH-6043 * - * @param entity - * @param session - * @param postLoadEvent + * @param entity The entity + * @param session The Session + * @param postLoadEvent The (re-used) post-load event */ public static void postLoad( final Object entity, @@ -306,15 +308,11 @@ public final class TwoPhaseLoad { if ( session.isEventSource() ) { final PersistenceContext persistenceContext = session.getPersistenceContext(); - final EntityEntry entityEntry = persistenceContext.getEntry(entity); - final Serializable id = entityEntry.getId(); - - postLoadEvent.setEntity( entity ).setId( entityEntry.getId() ) - .setPersister( entityEntry.getPersister() ); + final EntityEntry entityEntry = persistenceContext.getEntry( entity ); - final EventListenerGroup listenerGroup - = session - .getFactory() + postLoadEvent.setEntity( entity ).setId( entityEntry.getId() ).setPersister( entityEntry.getPersister() ); + + final EventListenerGroup listenerGroup = session.getFactory() .getServiceRegistry() .getService( EventListenerRegistry.class ) .getEventListenerGroup( EventType.POST_LOAD ); @@ -325,11 +323,11 @@ public final class TwoPhaseLoad { } private static boolean useMinimalPuts(SessionImplementor session, EntityEntry entityEntry) { - return ( session.getFactory().getSettings().isMinimalPutsEnabled() && - session.getCacheMode()!=CacheMode.REFRESH ) || - ( entityEntry.getPersister().hasLazyProperties() && - entityEntry.isLoadedWithLazyPropertiesUnfetched() && - entityEntry.getPersister().isLazyPropertiesCacheable() ); + return ( session.getFactory().getSettings().isMinimalPutsEnabled() + && session.getCacheMode()!=CacheMode.REFRESH ) + || ( entityEntry.getPersister().hasLazyProperties() + && entityEntry.isLoadedWithLazyPropertiesUnfetched() + && entityEntry.getPersister().isLazyPropertiesCacheable() ); } /** @@ -338,15 +336,21 @@ public final class TwoPhaseLoad { * * Create a "temporary" entry for a newly instantiated entity. The entity is uninitialized, * but we need the mapping from id to instance in order to guarantee uniqueness. + * + * @param key The entity key + * @param object The entity instance + * @param persister The entity persister + * @param lockMode The lock mode + * @param lazyPropertiesAreUnFetched Are lazy properties still un-fetched? + * @param session The Session */ public static void addUninitializedEntity( final EntityKey key, final Object object, final EntityPersister persister, final LockMode lockMode, - final boolean lazyPropertiesAreUnfetched, - final SessionImplementor session - ) { + final boolean lazyPropertiesAreUnFetched, + final SessionImplementor session) { session.getPersistenceContext().addEntity( object, Status.LOADING, @@ -357,19 +361,29 @@ public final class TwoPhaseLoad { true, persister, false, - lazyPropertiesAreUnfetched - ); + lazyPropertiesAreUnFetched + ); } + /** + * Same as {@link #addUninitializedEntity}, but here for an entity from the second level cache + * + * @param key The entity key + * @param object The entity instance + * @param persister The entity persister + * @param lockMode The lock mode + * @param lazyPropertiesAreUnFetched Are lazy properties still un-fetched? + * @param version The version + * @param session The Session + */ public static void addUninitializedCachedEntity( final EntityKey key, final Object object, final EntityPersister persister, final LockMode lockMode, - final boolean lazyPropertiesAreUnfetched, + final boolean lazyPropertiesAreUnFetched, final Object version, - final SessionImplementor session - ) { + final SessionImplementor session) { session.getPersistenceContext().addEntity( object, Status.LOADING, @@ -380,7 +394,7 @@ public final class TwoPhaseLoad { true, persister, false, - lazyPropertiesAreUnfetched + lazyPropertiesAreUnFetched ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/UnsavedValueFactory.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/UnsavedValueFactory.java index 23d8e5c517..e7a9f9c727 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/UnsavedValueFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/UnsavedValueFactory.java @@ -37,13 +37,24 @@ import org.hibernate.type.Type; import org.hibernate.type.VersionType; /** + * Helper for dealing with unsaved value handling + * * @author Gavin King */ public class UnsavedValueFactory { - + + /** + * Instantiate a class using the provided Constructor + * + * @param constructor The constructor + * + * @return The instantiated object + * + * @throws InstantiationException if something went wrong + */ private static Object instantiate(Constructor constructor) { try { - return constructor.newInstance( (Object[]) null ); + return constructor.newInstance(); } catch (Exception e) { throw new InstantiationException( "could not instantiate test object", constructor.getDeclaringClass(), e ); @@ -54,22 +65,28 @@ public class UnsavedValueFactory { * Return an IdentifierValue for the specified unsaved-value. If none is specified, * guess the unsaved value by instantiating a test instance of the class and * reading it's id property, or if that is not possible, using the java default - * value for the type + * value for the type + * + * @param unsavedValue The mapping defined unsaved value + * @param identifierGetter The getter for the entity identifier attribute + * @param identifierType The mapping type for the identifier + * @param constructor The constructor for the entity + * + * @return The appropriate IdentifierValue */ public static IdentifierValue getUnsavedIdentifierValue( - String unsavedValue, + String unsavedValue, Getter identifierGetter, Type identifierType, Constructor constructor) { - if ( unsavedValue == null ) { - if ( identifierGetter!=null && constructor!=null ) { + if ( identifierGetter != null && constructor != null ) { // use the id value of a newly instantiated instance as the unsaved-value - Serializable defaultValue = (Serializable) identifierGetter.get( instantiate(constructor) ); + final Serializable defaultValue = (Serializable) identifierGetter.get( instantiate(constructor) ); return new IdentifierValue( defaultValue ); } else if ( identifierGetter != null && (identifierType instanceof PrimitiveType) ) { - Serializable defaultValue = ( ( PrimitiveType ) identifierType ).getDefaultValue(); + final Serializable defaultValue = ( (PrimitiveType) identifierType ).getDefaultValue(); return new IdentifierValue( defaultValue ); } else { @@ -90,7 +107,7 @@ public class UnsavedValueFactory { } else { try { - return new IdentifierValue( ( Serializable ) ( ( IdentifierType ) identifierType ).stringToObject( unsavedValue ) ); + return new IdentifierValue( (Serializable) ( (IdentifierType) identifierType ).stringToObject( unsavedValue ) ); } catch ( ClassCastException cce ) { throw new MappingException( "Bad identifier type: " + identifierType.getName() ); @@ -101,6 +118,19 @@ public class UnsavedValueFactory { } } + /** + * Return an IdentifierValue for the specified unsaved-value. If none is specified, + * guess the unsaved value by instantiating a test instance of the class and + * reading it's version property value, or if that is not possible, using the java default + * value for the type + * + * @param versionUnsavedValue The mapping defined unsaved value + * @param versionGetter The version attribute getter + * @param versionType The mapping type for the version + * @param constructor The constructor for the entity + * + * @return The appropriate VersionValue + */ public static VersionValue getUnsavedVersionValue( String versionUnsavedValue, Getter versionGetter, @@ -109,12 +139,12 @@ public class UnsavedValueFactory { if ( versionUnsavedValue == null ) { if ( constructor!=null ) { - Object defaultValue = versionGetter.get( instantiate(constructor) ); + final Object defaultValue = versionGetter.get( instantiate( constructor ) ); // if the version of a newly instantiated object is not the same // as the version seed value, use that as the unsaved-value - return versionType.isEqual( versionType.seed( null ), defaultValue ) ? - VersionValue.UNDEFINED : - new VersionValue( defaultValue ); + return versionType.isEqual( versionType.seed( null ), defaultValue ) + ? VersionValue.UNDEFINED + : new VersionValue( defaultValue ); } else { return VersionValue.UNDEFINED; @@ -133,7 +163,8 @@ public class UnsavedValueFactory { // this should not happen since the DTD prevents it throw new MappingException( "Could not parse version unsaved-value: " + versionUnsavedValue ); } - } + private UnsavedValueFactory() { + } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/Versioning.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/Versioning.java index 5cf6fdcd51..dd72581fea 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/Versioning.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/Versioning.java @@ -36,38 +36,16 @@ import org.hibernate.type.VersionType; * @author Gavin King */ public final class Versioning { - - // todo : replace these constants with references to org.hibernate.annotations.OptimisticLockType enum - - /** - * Apply no optimistic locking - */ - public static final int OPTIMISTIC_LOCK_NONE = -1; - - /** - * Apply optimistic locking based on the defined version or timestamp - * property. - */ - public static final int OPTIMISTIC_LOCK_VERSION = 0; - - /** - * Apply optimistic locking based on the a current vs. snapshot comparison - * of all properties. - */ - public static final int OPTIMISTIC_LOCK_ALL = 2; - - /** - * Apply optimistic locking based on the a current vs. snapshot comparison - * of dirty properties. - */ - public static final int OPTIMISTIC_LOCK_DIRTY = 1; - - private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, Versioning.class.getName() ); + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + Versioning.class.getName() + ); /** * Private constructor disallowing instantiation. */ - private Versioning() {} + private Versioning() { + } /** * Create an initial optimistic locking value according the {@link VersionType} @@ -78,8 +56,8 @@ public final class Versioning { * @return The initial optimistic locking value */ private static Object seed(VersionType versionType, SessionImplementor session) { - Object seed = versionType.seed( session ); - LOG.tracev( "Seeding: {0}", seed ); + final Object seed = versionType.seed( session ); + LOG.tracef( "Seeding: %s", seed ); return seed; } @@ -96,11 +74,11 @@ public final class Versioning { * otherwise. */ public static boolean seedVersion( - Object[] fields, - int versionProperty, - VersionType versionType, - SessionImplementor session) { - Object initialVersion = fields[versionProperty]; + Object[] fields, + int versionProperty, + VersionType versionType, + SessionImplementor session) { + final Object initialVersion = fields[versionProperty]; if ( initialVersion==null || // This next bit is to allow for both unsaved-value="negative" @@ -126,11 +104,15 @@ public final class Versioning { * @param session The originating session * @return The incremented optimistic locking value. */ + @SuppressWarnings("unchecked") public static Object increment(Object version, VersionType versionType, SessionImplementor session) { - Object next = versionType.next( version, session ); + final Object next = versionType.next( version, session ); if ( LOG.isTraceEnabled() ) { - LOG.tracev( "Incrementing: {0} to {1}", versionType.toLoggableString( version, session.getFactory() ), - versionType.toLoggableString( next, session.getFactory() ) ); + LOG.tracef( + "Incrementing: %s to %s", + versionType.toLoggableString( version, session.getFactory() ), + versionType.toLoggableString( next, session.getFactory() ) + ); } return next; } @@ -178,8 +160,8 @@ public final class Versioning { if ( hasDirtyCollections ) { return true; } - for ( int i = 0; i < dirtyProperties.length; i++ ) { - if ( propertyVersionability[ dirtyProperties[i] ] ) { + for ( int dirtyProperty : dirtyProperties ) { + if ( propertyVersionability[dirtyProperty] ) { return true; } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/PersistenceContext.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/PersistenceContext.java index 1ac0388104..9b87aa8960 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/PersistenceContext.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/PersistenceContext.java @@ -33,6 +33,7 @@ import org.hibernate.LockMode; import org.hibernate.MappingException; import org.hibernate.collection.spi.PersistentCollection; import org.hibernate.engine.loading.internal.LoadContexts; +import org.hibernate.internal.util.MarkerObject; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.entity.EntityPersister; @@ -52,7 +53,11 @@ import org.hibernate.persister.entity.EntityPersister; */ @SuppressWarnings( {"JavaDoc"}) public interface PersistenceContext { - + /** + * Marker object used to indicate (via reference checking) that no row was returned. + */ + public static final Object NO_ROW = new MarkerObject( "NO_ROW" ); + @SuppressWarnings( {"UnusedDeclaration"}) public boolean isStateless(); @@ -135,11 +140,15 @@ public interface PersistenceContext { public Object[] getDatabaseSnapshot(Serializable id, EntityPersister persister); /** - * Get the current database state of the entity, using the cached state snapshot if one is available. - * - * @param key The entity key - * - * @return The entity's (non-cached) snapshot + * Retrieve the cached database snapshot for the requested entity key. + *

      + * This differs from {@link #getDatabaseSnapshot} is two important respects:

        + *
      1. no snapshot is obtained from the database if not already cached
      2. + *
      3. an entry of {@link #NO_ROW} here is interpretet as an exception
      4. + *
      + * @param key The entity key for which to retrieve the cached snapshot + * @return The cached snapshot + * @throws IllegalStateException if the cached snapshot was == {@link #NO_ROW}. */ public Object[] getCachedDatabaseSnapshot(EntityKey key); @@ -316,7 +325,9 @@ public interface PersistenceContext { /** * Attempts to check whether the given key represents an entity already loaded within the * current session. + * * @param object The entity reference against which to perform the uniqueness check. + * * @throws HibernateException */ public void checkUniqueness(EntityKey key, Object object) throws HibernateException; @@ -467,7 +478,13 @@ public interface PersistenceContext { public void addProxy(EntityKey key, Object proxy); /** - * Remove a proxy from the session cache + * Remove a proxy from the session cache. + *

      + * Additionally, ensure that any load optimization references + * such as batch or subselect loading get cleaned up as well. + * + * @param key The key of the entity proxy to be removed + * @return The proxy reference. */ public Object removeProxy(EntityKey key); @@ -559,10 +576,27 @@ public interface PersistenceContext { public String toString(); /** - * Search the persistence context for an owner for the child object, - * given a collection role + * Search this persistence context for an associated entity instance which is considered the "owner" of + * the given childEntity, and return that owner's id value. This is performed in the scenario of a + * uni-directional, non-inverse one-to-many collection (which means that the collection elements do not maintain + * a direct reference to the owner). + *

      + * As such, the processing here is basically to loop over every entity currently associated with this persistence + * context and for those of the correct entity (sub) type to extract its collection role property value and see + * if the child is contained within that collection. If so, we have found the owner; if not, we go on. + *

      + * Also need to account for mergeMap which acts as a local copy cache managed for the duration of a merge + * operation. It represents a map of the detached entity instances pointing to the corresponding managed instance. + * + * @param entityName The entity name for the entity type which would own the child + * @param propertyName The name of the property on the owning entity type which would name this child association. + * @param childEntity The child entity instance for which to locate the owner instance id. + * @param mergeMap A map of non-persistent instances from an on-going merge operation (possibly null). + * + * @return The id of the entityName instance which is said to own the child; null if an appropriate owner not + * located. */ - public Serializable getOwnerId(String entity, String property, Object childObject, Map mergeMap); + public Serializable getOwnerId(String entityName, String propertyName, Object childEntity, Map mergeMap); /** * Search the persistence context for an index of the child object, diff --git a/hibernate-core/src/main/java/org/hibernate/loader/Loader.java b/hibernate-core/src/main/java/org/hibernate/loader/Loader.java index 0b78c1bd63..784559c18d 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/Loader.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/Loader.java @@ -1099,7 +1099,7 @@ public abstract class Loader { if ( LOG.isTraceEnabled() ) LOG.tracev( "Total objects hydrated: {0}", hydratedObjectsSize ); for ( int i = 0; i < hydratedObjectsSize; i++ ) { - TwoPhaseLoad.initializeEntity( hydratedObjects.get(i), readOnly, session, pre, post ); + TwoPhaseLoad.initializeEntity( hydratedObjects.get(i), readOnly, session, pre ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/internal/ResultSetProcessingContextImpl.java b/hibernate-core/src/main/java/org/hibernate/loader/internal/ResultSetProcessingContextImpl.java index 49e51a4dfd..940dab925d 100644 --- a/hibernate-core/src/main/java/org/hibernate/loader/internal/ResultSetProcessingContextImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/internal/ResultSetProcessingContextImpl.java @@ -664,7 +664,7 @@ public class ResultSetProcessingContextImpl implements ResultSetProcessingContex } // now finish loading the entities (2-phase load) - performTwoPhaseLoad( preLoadEvent, postLoadEvent ); + performTwoPhaseLoad( preLoadEvent ); // now we can finalize loading collections finishLoadingCollections(); @@ -699,7 +699,7 @@ public class ResultSetProcessingContextImpl implements ResultSetProcessingContex ); } - private void performTwoPhaseLoad(PreLoadEvent preLoadEvent, PostLoadEvent postLoadEvent) { + private void performTwoPhaseLoad(PreLoadEvent preLoadEvent) { final int numberOfHydratedObjects = hydratedEntityRegistrationList == null ? 0 : hydratedEntityRegistrationList.size(); @@ -710,7 +710,7 @@ public class ResultSetProcessingContextImpl implements ResultSetProcessingContex } for ( HydratedEntityRegistration registration : hydratedEntityRegistrationList ) { - TwoPhaseLoad.initializeEntity( registration.instance, readOnly, session, preLoadEvent, postLoadEvent ); + TwoPhaseLoad.initializeEntity( registration.instance, readOnly, session, preLoadEvent ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java b/hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java index e8a299dd48..41f1bb2346 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/PersistentClass.java @@ -33,6 +33,8 @@ import java.util.StringTokenizer; import org.hibernate.EntityMode; import org.hibernate.MappingException; import org.hibernate.dialect.Dialect; +import org.hibernate.dialect.lock.OptimisticLockingStrategy; +import org.hibernate.engine.OptimisticLockStyle; import org.hibernate.engine.spi.ExecuteUpdateResultCheckStyle; import org.hibernate.engine.spi.Mapping; import org.hibernate.internal.FilterConfiguration; @@ -100,9 +102,9 @@ public abstract class PersistentClass implements Serializable, Filterable, MetaA private java.util.Map tuplizerImpls; - protected int optimisticLockMode; private MappedSuperclass superMappedSuperclass; private Component declaredIdentifierMapper; + private OptimisticLockStyle optimisticLockStyle; public String getClassName() { return className; @@ -456,10 +458,22 @@ public abstract class PersistentClass implements Serializable, Filterable, MetaA } } - abstract public int getOptimisticLockMode(); + @Deprecated + public int getOptimisticLockMode() { + return getOptimisticLockStyle().getOldCode(); + } + @Deprecated public void setOptimisticLockMode(int optimisticLockMode) { - this.optimisticLockMode = optimisticLockMode; + setOptimisticLockStyle( OptimisticLockStyle.interpretOldCode( optimisticLockMode ) ); + } + + public OptimisticLockStyle getOptimisticLockStyle() { + return optimisticLockStyle; + } + + public void setOptimisticLockStyle(OptimisticLockStyle optimisticLockStyle) { + this.optimisticLockStyle = optimisticLockStyle; } public void validate(Mapping mapping) throws MappingException { diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/RootClass.java b/hibernate-core/src/main/java/org/hibernate/mapping/RootClass.java index 59c5775cad..774aa95e5a 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/RootClass.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/RootClass.java @@ -31,6 +31,7 @@ import java.util.Set; import org.jboss.logging.Logger; import org.hibernate.MappingException; +import org.hibernate.engine.OptimisticLockStyle; import org.hibernate.engine.spi.Mapping; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.ReflectHelper; @@ -351,10 +352,4 @@ public class RootClass extends PersistentClass implements TableOwner { public Object accept(PersistentClassVisitor mv) { return mv.accept(this); } - - @Override - public int getOptimisticLockMode() { - return optimisticLockMode; - } - } diff --git a/hibernate-core/src/main/java/org/hibernate/mapping/Subclass.java b/hibernate-core/src/main/java/org/hibernate/mapping/Subclass.java index c45d4cee16..1133d500bb 100644 --- a/hibernate-core/src/main/java/org/hibernate/mapping/Subclass.java +++ b/hibernate-core/src/main/java/org/hibernate/mapping/Subclass.java @@ -30,6 +30,7 @@ import java.util.Map; import org.hibernate.AssertionFailure; import org.hibernate.EntityMode; +import org.hibernate.engine.OptimisticLockStyle; import org.hibernate.internal.util.collections.JoinedIterator; import org.hibernate.internal.util.collections.SingletonIterator; @@ -295,9 +296,9 @@ public class Subclass extends PersistentClass { public Component getIdentifierMapper() { return superclass.getIdentifierMapper(); } - - public int getOptimisticLockMode() { - return superclass.getOptimisticLockMode(); - } + @Override + public OptimisticLockStyle getOptimisticLockStyle() { + return superclass.getOptimisticLockStyle(); + } } diff --git a/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java b/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java index 7d0b2717fe..16e5701076 100644 --- a/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java +++ b/hibernate-core/src/main/java/org/hibernate/tuple/entity/EntityMetamodel.java @@ -325,7 +325,7 @@ public class EntityMetamodel implements Serializable { null; hasSubclasses = persistentClass.hasSubclasses(); - optimisticLockStyle = interpretOptLockMode( persistentClass.getOptimisticLockMode() ); + optimisticLockStyle = persistentClass.getOptimisticLockStyle(); final boolean isAllOrDirty = optimisticLockStyle == OptimisticLockStyle.ALL || optimisticLockStyle == OptimisticLockStyle.DIRTY; @@ -365,23 +365,6 @@ public class EntityMetamodel implements Serializable { } } - private OptimisticLockStyle interpretOptLockMode(int optimisticLockMode) { - switch ( optimisticLockMode ) { - case Versioning.OPTIMISTIC_LOCK_NONE: { - return OptimisticLockStyle.NONE; - } - case Versioning.OPTIMISTIC_LOCK_DIRTY: { - return OptimisticLockStyle.DIRTY; - } - case Versioning.OPTIMISTIC_LOCK_ALL: { - return OptimisticLockStyle.ALL; - } - default: { - return OptimisticLockStyle.VERSION; - } - } - } - public EntityMetamodel( EntityBinding entityBinding, AbstractEntityPersister persister, diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/entity/NewCustomEntityMappingAnnotationsTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/entity/NewCustomEntityMappingAnnotationsTest.java index 64d6c831e4..5e81af1c68 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/entity/NewCustomEntityMappingAnnotationsTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/entity/NewCustomEntityMappingAnnotationsTest.java @@ -52,7 +52,7 @@ public class NewCustomEntityMappingAnnotationsTest extends BaseCoreFunctionalTes assertEquals( forest.useDynamicInsert(), forest2.useDynamicInsert() ); assertEquals( forest.useDynamicUpdate(), forest2.useDynamicUpdate() ); assertEquals( forest.hasSelectBeforeUpdate(), forest2.hasSelectBeforeUpdate() ); - assertEquals( forest.getOptimisticLockMode(), forest2.getOptimisticLockMode() ); + assertEquals( forest.getOptimisticLockStyle(), forest2.getOptimisticLockStyle() ); assertEquals( forest.isExplicitPolymorphism(), forest2.isExplicitPolymorphism() ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/test/legacy/CustomPersister.java b/hibernate-core/src/test/java/org/hibernate/test/legacy/CustomPersister.java index a4b56b0193..64553579b4 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/legacy/CustomPersister.java +++ b/hibernate-core/src/test/java/org/hibernate/test/legacy/CustomPersister.java @@ -309,7 +309,7 @@ public class CustomPersister implements EntityPersister { LockMode.NONE, false, session - ); + ); TwoPhaseLoad.postHydrate( this, id, new String[] { obj.getName() }, @@ -318,14 +318,14 @@ public class CustomPersister implements EntityPersister { LockMode.NONE, false, session - ); + ); TwoPhaseLoad.initializeEntity( clone, false, session, - new PreLoadEvent( (EventSource) session ), - new PostLoadEvent( (EventSource) session ) - ); + new PreLoadEvent( (EventSource) session ) + ); + TwoPhaseLoad.postLoad( clone, session, new PostLoadEvent( (EventSource) session ) ); } return clone; } From 194cd5e4bdc369fe258e37e4303d1cd6d3af5363 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Mon, 29 Apr 2013 09:55:39 -0500 Subject: [PATCH 22/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../test/java/org/hibernate/jpa/test/EntityManagerTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java index 70f60b1a9b..bf3be224c3 100755 --- a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java +++ b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java @@ -279,8 +279,8 @@ public class EntityManagerTest extends BaseEntityManagerFunctionalTestCase { IllegalArgumentException deserializedException = ( IllegalArgumentException ) in.readObject(); in.close(); byteIn.close(); - assertNull( deserializedException.getCause().getCause().getCause() ); - assertNull( e.getCause().getCause().getCause() ); + assertNull( deserializedException.getCause().getCause() ); + assertNull( e.getCause().getCause() ); } em.getTransaction().rollback(); em.close(); From 398000517f6fa1d7ef29f4b3ca827440af2f3a56 Mon Sep 17 00:00:00 2001 From: Brett Meyer Date: Fri, 26 Apr 2013 12:39:54 -0400 Subject: [PATCH 23/57] HHH-7943 Reworked "Availability" concepts into "strategy registration providers". Updated proxool and c3p0 to use strategy selection. --- .../internal/C3P0ConnectionProvider.java | 2 +- .../internal/C3P0MessageLogger.java | 2 +- .../StrategyRegistrationProviderImpl.java | 57 +++++++++++++ ...stry.selector.StrategyRegistrationProvider | 1 + .../test/c3p0/C3P0ConnectionProviderTest.java | 2 +- .../BootstrapServiceRegistryBuilder.java | 14 +-- ...va => SimpleStrategyRegistrationImpl.java} | 12 +-- ...ability.java => StrategyRegistration.java} | 10 +-- ...java => StrategyRegistrationProvider.java} | 12 ++- .../internal/StrategySelectorBuilder.java | 50 +++++------ .../internal/ConnectionProviderInitiator.java | 85 ++++++++----------- ... => StrategyRegistrationProviderImpl.java} | 22 ++--- ...ot.registry.selector.AvailabilityAnnouncer | 1 - ...stry.selector.StrategyRegistrationProvider | 1 + ... => StrategyRegistrationProviderImpl.java} | 22 ++--- .../internal/ProxoolConnectionProvider.java | 2 +- .../internal/ProxoolMessageLogger.java | 2 +- .../StrategyRegistrationProviderImpl.java | 57 +++++++++++++ ...stry.selector.StrategyRegistrationProvider | 1 + .../ProxoolConnectionProviderTest.java | 3 +- 20 files changed, 229 insertions(+), 129 deletions(-) rename hibernate-c3p0/src/main/java/org/hibernate/{service/jdbc/connections => c3p0}/internal/C3P0ConnectionProvider.java (99%) rename hibernate-c3p0/src/main/java/org/hibernate/{service/jdbc/connections => c3p0}/internal/C3P0MessageLogger.java (98%) create mode 100644 hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java create mode 100644 hibernate-c3p0/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider rename hibernate-core/src/main/java/org/hibernate/boot/registry/selector/{SimpleAvailabilityImpl.java => SimpleStrategyRegistrationImpl.java} (88%) rename hibernate-core/src/main/java/org/hibernate/boot/registry/selector/{Availability.java => StrategyRegistration.java} (89%) rename hibernate-core/src/main/java/org/hibernate/boot/registry/selector/{AvailabilityAnnouncer.java => StrategyRegistrationProvider.java} (82%) rename hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/{AvailabilityAnnouncerImpl.java => StrategyRegistrationProviderImpl.java} (74%) delete mode 100644 hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.AvailabilityAnnouncer create mode 100644 hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider rename hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/{AvailabilityAnnouncerImpl.java => StrategyRegistrationProviderImpl.java} (72%) rename hibernate-proxool/src/main/java/org/hibernate/{service/jdbc/connections => proxool}/internal/ProxoolConnectionProvider.java (99%) rename hibernate-proxool/src/main/java/org/hibernate/{service/jdbc/connections => proxool}/internal/ProxoolMessageLogger.java (98%) create mode 100644 hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java create mode 100644 hibernate-proxool/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider rename hibernate-proxool/src/test/java/org/hibernate/{service/jdbc/connections/internal => test/proxool}/ProxoolConnectionProviderTest.java (96%) diff --git a/hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0ConnectionProvider.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java similarity index 99% rename from hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0ConnectionProvider.java rename to hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java index 61238d83f5..f3b3498586 100644 --- a/hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0ConnectionProvider.java +++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java @@ -21,7 +21,7 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.service.jdbc.connections.internal; +package org.hibernate.c3p0.internal; import java.sql.Connection; import java.sql.SQLException; diff --git a/hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0MessageLogger.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java similarity index 98% rename from hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0MessageLogger.java rename to hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java index 434af89276..0f37a41e29 100644 --- a/hibernate-c3p0/src/main/java/org/hibernate/service/jdbc/connections/internal/C3P0MessageLogger.java +++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java @@ -21,7 +21,7 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.service.jdbc.connections.internal; +package org.hibernate.c3p0.internal; import java.sql.SQLException; diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java new file mode 100644 index 0000000000..4237221181 --- /dev/null +++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java @@ -0,0 +1,57 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2012, 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.c3p0.internal; + +import java.util.Collections; +import java.util.List; + +import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl; +import org.hibernate.boot.registry.selector.StrategyRegistration; +import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; +import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; + +/** + * Provides the {@link C3P0ConnectionProvider} to the + * {@link org.hibernate.boot.registry.selector.spi.StrategySelector} service. + * + * @author Brett Meyer + */ +public class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider { + + private static final List REGISTRATIONS = Collections.singletonList( + (StrategyRegistration) new SimpleStrategyRegistrationImpl( + ConnectionProvider.class, + C3P0ConnectionProvider.class, + "c3p0", + C3P0ConnectionProvider.class.getSimpleName(), + "org.hibernate.connection.C3P0ConnectionProvider", // legacy + "org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider" // legacy + ) ); + + @Override + @SuppressWarnings("unchecked") + public Iterable getStrategyRegistrations() { + return REGISTRATIONS; + } +} diff --git a/hibernate-c3p0/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider b/hibernate-c3p0/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider new file mode 100644 index 0000000000..cde2be1446 --- /dev/null +++ b/hibernate-c3p0/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider @@ -0,0 +1 @@ +org.hibernate.c3p0.internal.StrategyRegistrationProviderImpl diff --git a/hibernate-c3p0/src/test/java/org/hibernate/test/c3p0/C3P0ConnectionProviderTest.java b/hibernate-c3p0/src/test/java/org/hibernate/test/c3p0/C3P0ConnectionProviderTest.java index 2175f15193..03e3c4fb33 100644 --- a/hibernate-c3p0/src/test/java/org/hibernate/test/c3p0/C3P0ConnectionProviderTest.java +++ b/hibernate-c3p0/src/test/java/org/hibernate/test/c3p0/C3P0ConnectionProviderTest.java @@ -30,8 +30,8 @@ import javax.management.ObjectName; import org.junit.Test; +import org.hibernate.c3p0.internal.C3P0ConnectionProvider; import org.hibernate.engine.jdbc.spi.JdbcServices; -import org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/BootstrapServiceRegistryBuilder.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/BootstrapServiceRegistryBuilder.java index 775ea0f4cf..ce59202409 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/BootstrapServiceRegistryBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/BootstrapServiceRegistryBuilder.java @@ -32,8 +32,8 @@ import java.util.Set; import org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl; import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; import org.hibernate.boot.registry.internal.BootstrapServiceRegistryImpl; -import org.hibernate.boot.registry.selector.Availability; -import org.hibernate.boot.registry.selector.AvailabilityAnnouncer; +import org.hibernate.boot.registry.selector.StrategyRegistration; +import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; import org.hibernate.boot.registry.selector.internal.StrategySelectorBuilder; import org.hibernate.integrator.internal.IntegratorServiceImpl; import org.hibernate.integrator.spi.Integrator; @@ -169,23 +169,23 @@ public class BootstrapServiceRegistryBuilder { */ @SuppressWarnings( {"UnusedDeclaration"}) public BootstrapServiceRegistryBuilder withStrategySelector(Class strategy, String name, Class implementation) { - this.strategySelectorBuilder.addExplicitAvailability( strategy, implementation, name ); + this.strategySelectorBuilder.addExplicitStrategyRegistration( strategy, implementation, name ); return this; } /** * Applies one or more strategy selectors announced as available by the passed announcer. * - * @param availabilityAnnouncer An announcer for one or more available selectors + * @param strategyRegistrationProvider An provider for one or more available selectors * * @return {@code this}, for method chaining * * @see org.hibernate.boot.registry.selector.spi.StrategySelector#registerStrategyImplementor(Class, String, Class) */ @SuppressWarnings( {"UnusedDeclaration"}) - public BootstrapServiceRegistryBuilder withStrategySelectors(AvailabilityAnnouncer availabilityAnnouncer) { - for ( Availability availability : availabilityAnnouncer.getAvailabilities() ) { - this.strategySelectorBuilder.addExplicitAvailability( availability ); + public BootstrapServiceRegistryBuilder withStrategySelectors(StrategyRegistrationProvider strategyRegistrationProvider) { + for ( StrategyRegistration strategyRegistration : strategyRegistrationProvider.getStrategyRegistrations() ) { + this.strategySelectorBuilder.addExplicitStrategyRegistration( strategyRegistration ); } return this; } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleAvailabilityImpl.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleStrategyRegistrationImpl.java similarity index 88% rename from hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleAvailabilityImpl.java rename to hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleStrategyRegistrationImpl.java index ff536956ab..725b526ef7 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleAvailabilityImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/SimpleStrategyRegistrationImpl.java @@ -26,25 +26,25 @@ package org.hibernate.boot.registry.selector; import java.util.Arrays; /** - * A simple implementation of Availability. + * A simple implementation of StrategyRegistration. * * @param The strategy type. * * @author Steve Ebersole */ -public class SimpleAvailabilityImpl implements Availability { +public class SimpleStrategyRegistrationImpl implements StrategyRegistration { private final Class strategyRole; private final Class strategyImplementation; private final Iterable selectorNames; /** - * Constructs a SimpleAvailabilityImpl. + * Constructs a SimpleStrategyRegistrationImpl. * * @param strategyRole The strategy contract * @param strategyImplementation The strategy implementation class * @param selectorNames The selection/registration names for this implementation */ - public SimpleAvailabilityImpl( + public SimpleStrategyRegistrationImpl( Class strategyRole, Class strategyImplementation, Iterable selectorNames) { @@ -54,13 +54,13 @@ public class SimpleAvailabilityImpl implements Availability { } /** - * Constructs a SimpleAvailabilityImpl. + * Constructs a SimpleStrategyRegistrationImpl. * * @param strategyRole The strategy contract * @param strategyImplementation The strategy implementation class * @param selectorNames The selection/registration names for this implementation */ - public SimpleAvailabilityImpl( + public SimpleStrategyRegistrationImpl( Class strategyRole, Class strategyImplementation, String... selectorNames) { diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/Availability.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistration.java similarity index 89% rename from hibernate-core/src/main/java/org/hibernate/boot/registry/selector/Availability.java rename to hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistration.java index 20de189f6f..5b1fd1b78a 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/Availability.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistration.java @@ -24,16 +24,14 @@ package org.hibernate.boot.registry.selector; /** - * Describes the availability of a named strategy implementation. A strategy + selector name should resolve + * Describes the registration of a named strategy implementation. A strategy + selector name should resolve * to a single implementation. * - * todo : better name? - * - * @param The type of the strategy described by this implementation availability. + * @param The type of the strategy described by this implementation registration. * * @author Steve Ebersole */ -public interface Availability { +public interface StrategyRegistration { /** * The strategy role. Best practice says this should be an interface. * @@ -42,7 +40,7 @@ public interface Availability { public Class getStrategyRole(); /** - * Any registered names for this strategy availability. + * Any registered names for this strategy registration. * * @return The registered selection names. */ diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/AvailabilityAnnouncer.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistrationProvider.java similarity index 82% rename from hibernate-core/src/main/java/org/hibernate/boot/registry/selector/AvailabilityAnnouncer.java rename to hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistrationProvider.java index bcc365a887..df28691ae2 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/AvailabilityAnnouncer.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/StrategyRegistrationProvider.java @@ -24,18 +24,16 @@ package org.hibernate.boot.registry.selector; /** - * Responsible for announcing the availability of strategy selector(s). Can be registered directly with the + * Responsible for providing the registrations of strategy selector(s). Can be registered directly with the * {@link org.hibernate.boot.registry.BootstrapServiceRegistry} or located via discovery. * - * todo : better name? - * * @author Steve Ebersole */ -public interface AvailabilityAnnouncer { +public interface StrategyRegistrationProvider { /** - * Get all availabilities announced by this announcer. + * Get all StrategyRegistrations announced by this provider. * - * @return All announced availabilities + * @return All StrategyRegistrations */ - public Iterable getAvailabilities(); + public Iterable getStrategyRegistrations(); } diff --git a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java index 47d0962f87..2a9f1c56f7 100644 --- a/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/boot/registry/selector/internal/StrategySelectorBuilder.java @@ -27,9 +27,9 @@ import java.util.ArrayList; import java.util.List; import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; -import org.hibernate.boot.registry.selector.Availability; -import org.hibernate.boot.registry.selector.AvailabilityAnnouncer; -import org.hibernate.boot.registry.selector.SimpleAvailabilityImpl; +import org.hibernate.boot.registry.selector.StrategyRegistration; +import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; +import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl; import org.hibernate.boot.registry.selector.spi.StrategySelectionException; import org.hibernate.boot.registry.selector.spi.StrategySelector; import org.hibernate.dialect.CUBRIDDialect; @@ -105,10 +105,10 @@ import org.jboss.logging.Logger; public class StrategySelectorBuilder { private static final Logger log = Logger.getLogger( StrategySelectorBuilder.class ); - private final List explicitAvailabilities = new ArrayList(); + private final List explicitStrategyRegistrations = new ArrayList(); /** - * Adds an explicit (as opposed to discovered) strategy availability. + * Adds an explicit (as opposed to discovered) strategy registration. * * @param strategy The strategy * @param implementation The strategy implementation @@ -117,31 +117,31 @@ public class StrategySelectorBuilder { * compatible. */ @SuppressWarnings("unchecked") - public void addExplicitAvailability(Class strategy, Class implementation, String name) { - addExplicitAvailability( new SimpleAvailabilityImpl( strategy, implementation, name ) ); + public void addExplicitStrategyRegistration(Class strategy, Class implementation, String name) { + addExplicitStrategyRegistration( new SimpleStrategyRegistrationImpl( strategy, implementation, name ) ); } /** - * Adds an explicit (as opposed to discovered) strategy availability. + * Adds an explicit (as opposed to discovered) strategy registration. * - * @param availability The strategy implementation availability. + * @param strategyRegistration The strategy implementation registration. * @param The type of the strategy. Used to make sure that the strategy and implementation are type * compatible. */ - public void addExplicitAvailability(Availability availability) { - if ( !availability.getStrategyRole().isInterface() ) { + public void addExplicitStrategyRegistration(StrategyRegistration strategyRegistration) { + if ( !strategyRegistration.getStrategyRole().isInterface() ) { // not good form... - log.debug( "Registering non-interface strategy : " + availability.getStrategyRole().getName() ); + log.debug( "Registering non-interface strategy : " + strategyRegistration.getStrategyRole().getName() ); } - if ( ! availability.getStrategyRole().isAssignableFrom( availability.getStrategyImplementation() ) ) { + if ( ! strategyRegistration.getStrategyRole().isAssignableFrom( strategyRegistration.getStrategyImplementation() ) ) { throw new StrategySelectionException( - "Implementation class [" + availability.getStrategyImplementation().getName() + "Implementation class [" + strategyRegistration.getStrategyImplementation().getName() + "] does not implement strategy interface [" - + availability.getStrategyRole().getName() + "]" + + strategyRegistration.getStrategyRole().getName() + "]" ); } - explicitAvailabilities.add( availability ); + explicitStrategyRegistrations.add( strategyRegistration ); } /** @@ -162,27 +162,27 @@ public class StrategySelectorBuilder { addMultiTableBulkIdStrategies( strategySelector ); // apply auto-discovered registrations - for ( AvailabilityAnnouncer announcer : classLoaderService.loadJavaServices( AvailabilityAnnouncer.class ) ) { - for ( Availability discoveredAvailability : announcer.getAvailabilities() ) { - applyFromAvailability( strategySelector, discoveredAvailability ); + for ( StrategyRegistrationProvider provider : classLoaderService.loadJavaServices( StrategyRegistrationProvider.class ) ) { + for ( StrategyRegistration discoveredStrategyRegistration : provider.getStrategyRegistrations() ) { + applyFromStrategyRegistration( strategySelector, discoveredStrategyRegistration ); } } // apply customizations - for ( Availability explicitAvailability : explicitAvailabilities ) { - applyFromAvailability( strategySelector, explicitAvailability ); + for ( StrategyRegistration explicitStrategyRegistration : explicitStrategyRegistrations ) { + applyFromStrategyRegistration( strategySelector, explicitStrategyRegistration ); } return strategySelector; } @SuppressWarnings("unchecked") - private void applyFromAvailability(StrategySelectorImpl strategySelector, Availability availability) { - for ( String name : availability.getSelectorNames() ) { + private void applyFromStrategyRegistration(StrategySelectorImpl strategySelector, StrategyRegistration strategyRegistration) { + for ( String name : strategyRegistration.getSelectorNames() ) { strategySelector.registerStrategyImplementor( - availability.getStrategyRole(), + strategyRegistration.getStrategyRole(), name, - availability.getStrategyImplementation() + strategyRegistration.getStrategyImplementation() ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java index cde05919ce..69438692a1 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java @@ -32,35 +32,33 @@ import java.util.Map; import java.util.Properties; import java.util.Set; -import org.jboss.logging.Logger; - import org.hibernate.HibernateException; import org.hibernate.MultiTenancyStrategy; import org.hibernate.boot.registry.StandardServiceInitiator; +import org.hibernate.boot.registry.selector.spi.StrategySelector; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Environment; +import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.beans.BeanInfoHelper; -import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; -import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.service.spi.ServiceRegistryImplementor; +import org.jboss.logging.Logger; /** * Instantiates and configures an appropriate {@link ConnectionProvider}. * * @author Gavin King * @author Steve Ebersole + * @author Brett Meyer */ public class ConnectionProviderInitiator implements StandardServiceInitiator { public static final ConnectionProviderInitiator INSTANCE = new ConnectionProviderInitiator(); private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, ConnectionProviderInitiator.class.getName()); - public static final String C3P0_PROVIDER_CLASS_NAME = - "org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider"; + public static final String C3P0_STRATEGY = "c3p0"; - public static final String PROXOOL_PROVIDER_CLASS_NAME = - "org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider"; + public static final String PROXOOL_STRATEGY = "proxool"; public static final String INJECTION_DATA = "hibernate.connection_provider.injection_data"; @@ -83,14 +81,6 @@ public class ConnectionProviderInitiator implements StandardServiceInitiator getAvailabilities() { - final List availabilities = new ArrayList(); + public Iterable getStrategyRegistrations() { + final List strategyRegistrations = new ArrayList(); - availabilities.add( - new SimpleAvailabilityImpl( + strategyRegistrations.add( + new SimpleStrategyRegistrationImpl( RegionFactory.class, EhCacheRegionFactory.class, "ehcache", @@ -53,8 +53,8 @@ public class AvailabilityAnnouncerImpl implements AvailabilityAnnouncer { ) ); - availabilities.add( - new SimpleAvailabilityImpl( + strategyRegistrations.add( + new SimpleStrategyRegistrationImpl( RegionFactory.class, SingletonEhCacheRegionFactory.class, "ehcache-singleton", @@ -63,6 +63,6 @@ public class AvailabilityAnnouncerImpl implements AvailabilityAnnouncer { ) ); - return availabilities; + return strategyRegistrations; } } diff --git a/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.AvailabilityAnnouncer b/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.AvailabilityAnnouncer deleted file mode 100644 index 4089ec9f31..0000000000 --- a/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.AvailabilityAnnouncer +++ /dev/null @@ -1 +0,0 @@ -org.hibernate.cache.ehcache.AvailabilityAnnouncerImpl \ No newline at end of file diff --git a/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider b/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider new file mode 100644 index 0000000000..4f53a53867 --- /dev/null +++ b/hibernate-ehcache/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider @@ -0,0 +1 @@ +org.hibernate.cache.ehcache.StrategyRegistrationProviderImpl \ No newline at end of file diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/AvailabilityAnnouncerImpl.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/StrategyRegistrationProviderImpl.java similarity index 72% rename from hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/AvailabilityAnnouncerImpl.java rename to hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/StrategyRegistrationProviderImpl.java index fc6ad8eccd..611e0587e5 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/AvailabilityAnnouncerImpl.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/StrategyRegistrationProviderImpl.java @@ -26,9 +26,9 @@ package org.hibernate.cache.infinispan; import java.util.ArrayList; import java.util.List; -import org.hibernate.boot.registry.selector.Availability; -import org.hibernate.boot.registry.selector.AvailabilityAnnouncer; -import org.hibernate.boot.registry.selector.SimpleAvailabilityImpl; +import org.hibernate.boot.registry.selector.StrategyRegistration; +import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; +import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl; import org.hibernate.cache.spi.RegionFactory; /** @@ -37,13 +37,13 @@ import org.hibernate.cache.spi.RegionFactory; * * @author Steve Ebersole */ -public class AvailabilityAnnouncerImpl implements AvailabilityAnnouncer { +public class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider { @Override - public Iterable getAvailabilities() { - final List availabilities = new ArrayList(); + public Iterable getStrategyRegistrations() { + final List strategyRegistrations = new ArrayList(); - availabilities.add( - new SimpleAvailabilityImpl( + strategyRegistrations.add( + new SimpleStrategyRegistrationImpl( RegionFactory.class, InfinispanRegionFactory.class, "infinispan", @@ -51,8 +51,8 @@ public class AvailabilityAnnouncerImpl implements AvailabilityAnnouncer { ) ); - availabilities.add( - new SimpleAvailabilityImpl( + strategyRegistrations.add( + new SimpleStrategyRegistrationImpl( RegionFactory.class, JndiInfinispanRegionFactory.class, "infinispan-jndi", @@ -60,6 +60,6 @@ public class AvailabilityAnnouncerImpl implements AvailabilityAnnouncer { ) ); - return availabilities; + return strategyRegistrations; } } diff --git a/hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProvider.java b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolConnectionProvider.java similarity index 99% rename from hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProvider.java rename to hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolConnectionProvider.java index 9009ecb62a..b8a8fbd8cd 100644 --- a/hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProvider.java +++ b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolConnectionProvider.java @@ -21,7 +21,7 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.service.jdbc.connections.internal; +package org.hibernate.proxool.internal; import java.sql.Connection; import java.sql.DriverManager; diff --git a/hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolMessageLogger.java b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolMessageLogger.java similarity index 98% rename from hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolMessageLogger.java rename to hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolMessageLogger.java index 2ff08badb7..568f4c98e9 100644 --- a/hibernate-proxool/src/main/java/org/hibernate/service/jdbc/connections/internal/ProxoolMessageLogger.java +++ b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolMessageLogger.java @@ -21,7 +21,7 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.service.jdbc.connections.internal; +package org.hibernate.proxool.internal; import org.jboss.logging.LogMessage; import org.jboss.logging.Message; diff --git a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java new file mode 100644 index 0000000000..7104d50399 --- /dev/null +++ b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java @@ -0,0 +1,57 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2012, 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.proxool.internal; + +import java.util.Collections; +import java.util.List; + +import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl; +import org.hibernate.boot.registry.selector.StrategyRegistration; +import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; +import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; + +/** + * Provides the {@link ProxoolConnectionProvider} to the + * {@link org.hibernate.boot.registry.selector.spi.StrategySelector} service. + * + * @author Brett Meyer + */ +public class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider { + + private static final List REGISTRATIONS = Collections.singletonList( + (StrategyRegistration) new SimpleStrategyRegistrationImpl( + ConnectionProvider.class, + ProxoolConnectionProvider.class, + "proxool", + ProxoolConnectionProvider.class.getSimpleName(), + "org.hibernate.connection.ProxoolConnectionProvider", // legacy + "org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider" // legacy + ) ); + + @Override + @SuppressWarnings("unchecked") + public Iterable getStrategyRegistrations() { + return REGISTRATIONS; + } +} diff --git a/hibernate-proxool/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider b/hibernate-proxool/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider new file mode 100644 index 0000000000..c794a929dc --- /dev/null +++ b/hibernate-proxool/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider @@ -0,0 +1 @@ +org.hibernate.proxool.internal.StrategyRegistrationProviderImpl diff --git a/hibernate-proxool/src/test/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProviderTest.java b/hibernate-proxool/src/test/java/org/hibernate/test/proxool/ProxoolConnectionProviderTest.java similarity index 96% rename from hibernate-proxool/src/test/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProviderTest.java rename to hibernate-proxool/src/test/java/org/hibernate/test/proxool/ProxoolConnectionProviderTest.java index e0776328a3..6285ba328a 100644 --- a/hibernate-proxool/src/test/java/org/hibernate/service/jdbc/connections/internal/ProxoolConnectionProviderTest.java +++ b/hibernate-proxool/src/test/java/org/hibernate/test/proxool/ProxoolConnectionProviderTest.java @@ -21,7 +21,7 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.service.jdbc.connections.internal; +package org.hibernate.test.proxool; import java.util.Arrays; import java.util.List; @@ -33,6 +33,7 @@ import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Environment; import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; +import org.hibernate.proxool.internal.ProxoolConnectionProvider; import org.hibernate.testing.junit4.BaseUnitTestCase; import static org.junit.Assert.assertEquals; From 30d63bf58fe9b15208340b860787d985f032d11a Mon Sep 17 00:00:00 2001 From: Brett Meyer Date: Mon, 22 Apr 2013 13:54:40 -0400 Subject: [PATCH 24/57] HHH-7995 Auto-discovery of Hibernate extension points in OSGi --- .../hibernate/internal/CoreMessageLogger.java | 4 ++ .../OSGI-INF/blueprint/blueprint.xml | 10 ++++ hibernate-osgi/hibernate-osgi.gradle | 4 +- .../osgi/HibernateBundleActivator.java | 4 +- .../osgi/OsgiPersistenceProvider.java | 60 +++++++++++++------ .../osgi/OsgiPersistenceProviderService.java | 9 ++- .../osgi/OsgiSessionFactoryService.java | 16 ++++- .../hibernate/osgi/util/OsgiServiceUtil.java | 53 ++++++++++++++++ 8 files changed, 135 insertions(+), 25 deletions(-) create mode 100644 hibernate-envers/src/main/resources/OSGI-INF/blueprint/blueprint.xml create mode 100644 hibernate-osgi/src/main/java/org/hibernate/osgi/util/OsgiServiceUtil.java diff --git a/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java b/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java index 955c5c0b04..20f6388fb2 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/CoreMessageLogger.java @@ -1623,4 +1623,8 @@ public interface CoreMessageLogger extends BasicLogger { @LogMessage(level = WARN) @Message(value = "Exception while loading a class or resource found during scanning", id = 449) void unableToLoadScannedClassOrResource(@Cause Exception e); + + @LogMessage(level = WARN) + @Message(value = "Exception while discovering OSGi service implementations : %s", id = 450) + void unableToDiscoverOsgiService(String service, @Cause Exception e); } diff --git a/hibernate-envers/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/hibernate-envers/src/main/resources/OSGI-INF/blueprint/blueprint.xml new file mode 100644 index 0000000000..07c01bfc9f --- /dev/null +++ b/hibernate-envers/src/main/resources/OSGI-INF/blueprint/blueprint.xml @@ -0,0 +1,10 @@ + + + + + + + + diff --git a/hibernate-osgi/hibernate-osgi.gradle b/hibernate-osgi/hibernate-osgi.gradle index 8a01360d3c..cefe0b6449 100644 --- a/hibernate-osgi/hibernate-osgi.gradle +++ b/hibernate-osgi/hibernate-osgi.gradle @@ -1,7 +1,9 @@ dependencies { compile( project( ':hibernate-core' ) ) compile( project( ':hibernate-entitymanager' ) ) - compile( "org.osgi:org.osgi.core:4.3.0" ) + // MUST use 4.3.1! 4.3.0 was compiled with "-target jsr14". + // http://blog.osgi.org/2012/10/43-companion-code-for-java-7.html + compile( "org.osgi:org.osgi.core:4.3.1" ) } def pomName() { diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/HibernateBundleActivator.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/HibernateBundleActivator.java index c1f862fb98..8bd6824e48 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/HibernateBundleActivator.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/HibernateBundleActivator.java @@ -78,10 +78,10 @@ public class HibernateBundleActivator implements BundleActivator { // using the legacy provider name. properties.put( "javax.persistence.provider", HibernatePersistenceProvider.class.getName() ); context.registerService( PersistenceProvider.class.getName(), - new OsgiPersistenceProviderService( osgiClassLoader, osgiJtaPlatform ), properties ); + new OsgiPersistenceProviderService( osgiClassLoader, osgiJtaPlatform, context ), properties ); context.registerService( SessionFactory.class.getName(), - new OsgiSessionFactoryService( osgiClassLoader, osgiJtaPlatform ), new Hashtable()); + new OsgiSessionFactoryService( osgiClassLoader, osgiJtaPlatform, context ), new Hashtable()); } @Override diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java index e90c2cbef4..885533f745 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java @@ -24,14 +24,20 @@ package org.hibernate.osgi; import java.util.HashMap; +import java.util.List; import java.util.Map; import javax.persistence.EntityManagerFactory; import javax.persistence.spi.PersistenceUnitInfo; import org.hibernate.cfg.AvailableSettings; +import org.hibernate.integrator.spi.Integrator; import org.hibernate.jpa.HibernatePersistenceProvider; +import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; +import org.hibernate.jpa.boot.spi.IntegratorProvider; +import org.hibernate.osgi.util.OsgiServiceUtil; import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; import org.osgi.framework.BundleReference; /** @@ -43,45 +49,42 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider { private OsgiClassLoader osgiClassLoader; private OsgiJtaPlatform osgiJtaPlatform; - + private Bundle requestingBundle; - - public OsgiPersistenceProvider (OsgiClassLoader osgiClassLoader, - OsgiJtaPlatform osgiJtaPlatform, - Bundle requestingBundle ) { + + private BundleContext context; + + public OsgiPersistenceProvider(OsgiClassLoader osgiClassLoader, OsgiJtaPlatform osgiJtaPlatform, + Bundle requestingBundle, BundleContext context) { this.osgiClassLoader = osgiClassLoader; this.osgiJtaPlatform = osgiJtaPlatform; this.requestingBundle = requestingBundle; + this.context = context; } - + // TODO: Does "hibernate.classloaders" and osgiClassLoader need added to the // EMFBuilder somehow? @Override public EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) { - if ( properties == null ) { - properties = new HashMap(); - } - properties.put( AvailableSettings.JTA_PLATFORM, osgiJtaPlatform ); + generateProperties( properties ); + // TODO: This needs tested. - properties.put( org.hibernate.jpa.AvailableSettings.SCANNER, - new OsgiScanner( requestingBundle ) ); + properties.put( org.hibernate.jpa.AvailableSettings.SCANNER, new OsgiScanner( requestingBundle ) ); // TODO: This is temporary -- for PersistenceXmlParser's use of // ClassLoaderServiceImpl#fromConfigSettings properties.put( AvailableSettings.ENVIRONMENT_CLASSLOADER, osgiClassLoader ); - + osgiClassLoader.addBundle( requestingBundle ); return super.createEntityManagerFactory( persistenceUnitName, properties ); } - + @Override public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) { - if ( properties == null ) { - properties = new HashMap(); - } - properties.put( AvailableSettings.JTA_PLATFORM, osgiJtaPlatform ); - // OSGi ClassLoaders must implement BundleReference + generateProperties( properties ); + + // OSGi ClassLoaders must implement BundleReference properties.put( org.hibernate.jpa.AvailableSettings.SCANNER, new OsgiScanner( ( (BundleReference) info.getClassLoader() ).getBundle() ) ); @@ -89,4 +92,23 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider { return super.createContainerEntityManagerFactory( info, properties ); } + + private void generateProperties(Map properties) { + if ( properties == null ) { + properties = new HashMap(); + } + + properties.put( AvailableSettings.JTA_PLATFORM, osgiJtaPlatform ); + + final List integrators = OsgiServiceUtil.getServiceImpls( Integrator.class, context ); + IntegratorProvider integratorProvider = new IntegratorProvider() { + @Override + public List getIntegrators() { + return integrators; + } + }; + properties.put( EntityManagerFactoryBuilderImpl.INTEGRATOR_PROVIDER, integratorProvider ); + + // TODO: other types of services? + } } diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProviderService.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProviderService.java index bb9008c33b..5ab228568f 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProviderService.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProviderService.java @@ -21,6 +21,7 @@ package org.hibernate.osgi; import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceFactory; import org.osgi.framework.ServiceRegistration; @@ -37,14 +38,18 @@ public class OsgiPersistenceProviderService implements ServiceFactory { private OsgiJtaPlatform osgiJtaPlatform; - public OsgiPersistenceProviderService( OsgiClassLoader osgiClassLoader, OsgiJtaPlatform osgiJtaPlatform ) { + private BundleContext context; + + public OsgiPersistenceProviderService( OsgiClassLoader osgiClassLoader, + OsgiJtaPlatform osgiJtaPlatform, BundleContext context ) { this.osgiClassLoader = osgiClassLoader; this.osgiJtaPlatform = osgiJtaPlatform; + this.context = context; } @Override public Object getService(Bundle requestingBundle, ServiceRegistration registration) { - return new OsgiPersistenceProvider(osgiClassLoader, osgiJtaPlatform, requestingBundle); + return new OsgiPersistenceProvider(osgiClassLoader, osgiJtaPlatform, requestingBundle, context); } @Override diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java index db5b75b4cf..8770e55231 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java @@ -20,13 +20,18 @@ */ package org.hibernate.osgi; +import java.util.List; + import org.hibernate.SessionFactory; import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; +import org.hibernate.integrator.spi.Integrator; +import org.hibernate.osgi.util.OsgiServiceUtil; import org.hibernate.service.ServiceRegistry; import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceFactory; import org.osgi.framework.ServiceRegistration; @@ -54,9 +59,13 @@ public class OsgiSessionFactoryService implements ServiceFactory { private OsgiJtaPlatform osgiJtaPlatform; - public OsgiSessionFactoryService( OsgiClassLoader osgiClassLoader, OsgiJtaPlatform osgiJtaPlatform ) { + private BundleContext context; + + public OsgiSessionFactoryService( OsgiClassLoader osgiClassLoader, OsgiJtaPlatform osgiJtaPlatform, + BundleContext context ) { this.osgiClassLoader = osgiClassLoader; this.osgiJtaPlatform = osgiJtaPlatform; + this.context = context; } @Override @@ -70,6 +79,11 @@ public class OsgiSessionFactoryService implements ServiceFactory { BootstrapServiceRegistryBuilder builder = new BootstrapServiceRegistryBuilder(); builder.with( osgiClassLoader ); + List integrators = OsgiServiceUtil.getServiceImpls( Integrator.class, context ); + for (Integrator integrator : integrators) { + builder.with( integrator ); + } + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder( builder.build() ) .applySettings(configuration.getProperties()).build(); return configuration.buildSessionFactory(serviceRegistry); diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/util/OsgiServiceUtil.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/util/OsgiServiceUtil.java new file mode 100644 index 0000000000..0b9ddc0ed4 --- /dev/null +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/util/OsgiServiceUtil.java @@ -0,0 +1,53 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * JBoss, Home of Professional Open Source + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors + * as indicated by the @authors tag. All rights reserved. + * See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * 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, v. 2.1. + * This program is distributed in the hope that it will be useful, but WITHOUT A + * 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, + * v.2.1 along with this distribution; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +package org.hibernate.osgi.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.hibernate.internal.CoreMessageLogger; +import org.jboss.logging.Logger; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; + +/** + * @author Brett Meyer + */ +public class OsgiServiceUtil { + + private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, + OsgiServiceUtil.class.getName() ); + + public static List getServiceImpls(Class contract, BundleContext context) { + List serviceImpls = new ArrayList(); + try { + Collection> serviceRefs = context.getServiceReferences( contract, null ); + for ( ServiceReference serviceRef : serviceRefs ) { + serviceImpls.add( context.getService( serviceRef ) ); + } + } + catch ( Exception e ) { + LOG.unableToDiscoverOsgiService( contract.getName(), e ); + } + return serviceImpls; + } +} From 0edd7b75b82b6038dfc3234ef3e3e4cde4a4acc9 Mon Sep 17 00:00:00 2001 From: Brett Meyer Date: Mon, 29 Apr 2013 11:50:11 -0400 Subject: [PATCH 25/57] HHH-7943 C3P0 and Proxool OSGi support --- .../OSGI-INF/blueprint/blueprint.xml | 10 +++ .../EntityManagerFactoryBuilderImpl.java | 64 +++++++++++-------- .../spi/StrategyRegistrationProviderList.java | 37 +++++++++++ .../osgi/OsgiPersistenceProvider.java | 21 ++++-- .../osgi/OsgiSessionFactoryService.java | 7 ++ .../OSGI-INF/blueprint/blueprint.xml | 10 +++ 6 files changed, 120 insertions(+), 29 deletions(-) create mode 100644 hibernate-c3p0/src/main/resources/OSGI-INF/blueprint/blueprint.xml create mode 100644 hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/StrategyRegistrationProviderList.java create mode 100644 hibernate-proxool/src/main/resources/OSGI-INF/blueprint/blueprint.xml diff --git a/hibernate-c3p0/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/hibernate-c3p0/src/main/resources/OSGI-INF/blueprint/blueprint.xml new file mode 100644 index 0000000000..3ade79977f --- /dev/null +++ b/hibernate-c3p0/src/main/resources/OSGI-INF/blueprint/blueprint.xml @@ -0,0 +1,10 @@ + + + + + + + + diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/internal/EntityManagerFactoryBuilderImpl.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/internal/EntityManagerFactoryBuilderImpl.java index 383dfd81f3..433aa11465 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/internal/EntityManagerFactoryBuilderImpl.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/internal/EntityManagerFactoryBuilderImpl.java @@ -23,12 +23,6 @@ */ package org.hibernate.jpa.boot.internal; -import javax.persistence.AttributeConverter; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityNotFoundException; -import javax.persistence.PersistenceException; -import javax.persistence.spi.PersistenceUnitTransactionType; -import javax.sql.DataSource; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; @@ -47,14 +41,12 @@ import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; -import org.jboss.jandex.AnnotationInstance; -import org.jboss.jandex.ClassInfo; -import org.jboss.jandex.DotName; -import org.jboss.jandex.Index; -import org.jboss.jandex.IndexView; -import org.jboss.jandex.Indexer; - -import org.jboss.logging.Logger; +import javax.persistence.AttributeConverter; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityNotFoundException; +import javax.persistence.PersistenceException; +import javax.persistence.spi.PersistenceUnitTransactionType; +import javax.sql.DataSource; import org.hibernate.Interceptor; import org.hibernate.InvalidMappingException; @@ -67,6 +59,7 @@ import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl; import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; +import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; import org.hibernate.boot.registry.selector.spi.StrategySelector; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; @@ -81,25 +74,26 @@ import org.hibernate.internal.jaxb.cfg.JaxbHibernateConfiguration; import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.ValueHolder; import org.hibernate.jpa.AvailableSettings; +import org.hibernate.jpa.boot.scan.internal.StandardScanOptions; +import org.hibernate.jpa.boot.scan.internal.StandardScanner; +import org.hibernate.jpa.boot.scan.spi.ScanOptions; +import org.hibernate.jpa.boot.scan.spi.ScanResult; +import org.hibernate.jpa.boot.scan.spi.Scanner; +import org.hibernate.jpa.boot.spi.ClassDescriptor; import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder; +import org.hibernate.jpa.boot.spi.InputStreamAccess; import org.hibernate.jpa.boot.spi.IntegratorProvider; +import org.hibernate.jpa.boot.spi.MappingFileDescriptor; +import org.hibernate.jpa.boot.spi.NamedInputStream; +import org.hibernate.jpa.boot.spi.PackageDescriptor; import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor; +import org.hibernate.jpa.boot.spi.StrategyRegistrationProviderList; import org.hibernate.jpa.event.spi.JpaIntegrator; import org.hibernate.jpa.internal.EntityManagerFactoryImpl; import org.hibernate.jpa.internal.EntityManagerMessageLogger; import org.hibernate.jpa.internal.schemagen.JpaSchemaGenerator; import org.hibernate.jpa.internal.util.LogHelper; import org.hibernate.jpa.internal.util.PersistenceUnitTransactionTypeHelper; -import org.hibernate.jpa.boot.scan.internal.StandardScanOptions; -import org.hibernate.jpa.boot.scan.internal.StandardScanner; -import org.hibernate.jpa.boot.spi.ClassDescriptor; -import org.hibernate.jpa.boot.spi.InputStreamAccess; -import org.hibernate.jpa.boot.spi.MappingFileDescriptor; -import org.hibernate.jpa.boot.spi.NamedInputStream; -import org.hibernate.jpa.boot.spi.PackageDescriptor; -import org.hibernate.jpa.boot.scan.spi.ScanOptions; -import org.hibernate.jpa.boot.scan.spi.ScanResult; -import org.hibernate.jpa.boot.scan.spi.Scanner; import org.hibernate.jpa.spi.IdentifierGeneratorStrategyProvider; import org.hibernate.metamodel.source.annotations.JPADotNames; import org.hibernate.metamodel.source.annotations.JandexHelper; @@ -109,6 +103,13 @@ import org.hibernate.secure.spi.JaccService; import org.hibernate.service.ConfigLoader; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.spi.ServiceRegistryImplementor; +import org.jboss.jandex.AnnotationInstance; +import org.jboss.jandex.ClassInfo; +import org.jboss.jandex.DotName; +import org.jboss.jandex.Index; +import org.jboss.jandex.IndexView; +import org.jboss.jandex.Indexer; +import org.jboss.logging.Logger; /** * @author Steve Ebersole @@ -129,6 +130,11 @@ public class EntityManagerFactoryBuilderImpl implements EntityManagerFactoryBuil * Names a {@link IntegratorProvider} */ public static final String INTEGRATOR_PROVIDER = "hibernate.integrator_provider"; + + /** + * Names a {@link StrategyRegistrationProviderList} + */ + public static final String STRATEGY_REGISTRATION_PROVIDERS = "hibernate.strategy_registration_provider"; /** * Names a Jandex {@link Index} instance to use. @@ -471,11 +477,19 @@ public class EntityManagerFactoryBuilderImpl implements EntityManagerFactoryBuil final IntegratorProvider integratorProvider = (IntegratorProvider) integrationSettings.get( INTEGRATOR_PROVIDER ); if ( integratorProvider != null ) { - integrationSettings.remove( INTEGRATOR_PROVIDER ); for ( Integrator integrator : integratorProvider.getIntegrators() ) { bootstrapServiceRegistryBuilder.with( integrator ); } } + + final StrategyRegistrationProviderList strategyRegistrationProviderList + = (StrategyRegistrationProviderList) integrationSettings.get( STRATEGY_REGISTRATION_PROVIDERS ); + if ( strategyRegistrationProviderList != null ) { + for ( StrategyRegistrationProvider strategyRegistrationProvider : strategyRegistrationProviderList + .getStrategyRegistrationProviders() ) { + bootstrapServiceRegistryBuilder.withStrategySelectors( strategyRegistrationProvider ); + } + } // TODO: If providedClassLoader is present (OSGi, etc.) *and* // an APP_CLASSLOADER is provided, should throw an exception or diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/StrategyRegistrationProviderList.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/StrategyRegistrationProviderList.java new file mode 100644 index 0000000000..24ad604705 --- /dev/null +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/StrategyRegistrationProviderList.java @@ -0,0 +1,37 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2012, 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.jpa.boot.spi; + +import java.util.List; + +import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; + +/** + * @author Brett Meyer + * + * TODO: Not a fan of this name or entry point into EMFBuilderImpl + */ +public interface StrategyRegistrationProviderList { + public List getStrategyRegistrationProviders(); +} diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java index 885533f745..01ccff48ee 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java @@ -30,11 +30,13 @@ import java.util.Map; import javax.persistence.EntityManagerFactory; import javax.persistence.spi.PersistenceUnitInfo; +import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; import org.hibernate.cfg.AvailableSettings; import org.hibernate.integrator.spi.Integrator; import org.hibernate.jpa.HibernatePersistenceProvider; import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; import org.hibernate.jpa.boot.spi.IntegratorProvider; +import org.hibernate.jpa.boot.spi.StrategyRegistrationProviderList; import org.hibernate.osgi.util.OsgiServiceUtil; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; @@ -67,7 +69,7 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider { @Override public EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) { - generateProperties( properties ); + properties = generateProperties( properties ); // TODO: This needs tested. properties.put( org.hibernate.jpa.AvailableSettings.SCANNER, new OsgiScanner( requestingBundle ) ); @@ -82,7 +84,7 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider { @Override public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) { - generateProperties( properties ); + properties = generateProperties( properties ); // OSGi ClassLoaders must implement BundleReference properties.put( org.hibernate.jpa.AvailableSettings.SCANNER, @@ -93,7 +95,7 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider { return super.createContainerEntityManagerFactory( info, properties ); } - private void generateProperties(Map properties) { + private Map generateProperties(Map properties) { if ( properties == null ) { properties = new HashMap(); } @@ -109,6 +111,17 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider { }; properties.put( EntityManagerFactoryBuilderImpl.INTEGRATOR_PROVIDER, integratorProvider ); - // TODO: other types of services? + final List strategyRegistrationProviders = OsgiServiceUtil.getServiceImpls( + StrategyRegistrationProvider.class, context ); + StrategyRegistrationProviderList strategyRegistrationProviderList = new StrategyRegistrationProviderList() { + @Override + public List getStrategyRegistrationProviders() { + return strategyRegistrationProviders; + } + }; + properties.put( EntityManagerFactoryBuilderImpl.STRATEGY_REGISTRATION_PROVIDERS, + strategyRegistrationProviderList ); + + return properties; } } diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java index 8770e55231..c878136711 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java @@ -25,6 +25,7 @@ import java.util.List; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; import org.hibernate.integrator.spi.Integrator; @@ -84,6 +85,12 @@ public class OsgiSessionFactoryService implements ServiceFactory { builder.with( integrator ); } + List strategyRegistrationProviders + = OsgiServiceUtil.getServiceImpls( StrategyRegistrationProvider.class, context ); + for (StrategyRegistrationProvider strategyRegistrationProvider : strategyRegistrationProviders) { + builder.withStrategySelectors( strategyRegistrationProvider ); + } + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder( builder.build() ) .applySettings(configuration.getProperties()).build(); return configuration.buildSessionFactory(serviceRegistry); diff --git a/hibernate-proxool/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/hibernate-proxool/src/main/resources/OSGI-INF/blueprint/blueprint.xml new file mode 100644 index 0000000000..b0e0c5c44d --- /dev/null +++ b/hibernate-proxool/src/main/resources/OSGI-INF/blueprint/blueprint.xml @@ -0,0 +1,10 @@ + + + + + + + + From 3b8320da7e5b1282e1cad2e90830e2756885b8d8 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Mon, 29 Apr 2013 18:52:08 -0500 Subject: [PATCH 26/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../dialect/function/TemplateRenderer.java | 7 ++- .../hibernate/engine/OptimisticLockStyle.java | 9 +++ .../config/spi/ConfigurationService.java | 55 +++++++++++++++++++ .../hibernate/engine/internal/Cascade.java | 2 +- .../engine/internal/EntityEntryContext.java | 2 + .../engine/internal/ForeignKeys.java | 2 + .../hibernate/engine/internal/JoinHelper.java | 40 +++++++++++--- .../internal/NaturalIdXrefDelegate.java | 2 +- .../engine/internal/Nullability.java | 2 +- .../engine/internal/ParameterBinder.java | 2 +- .../internal/StatefulPersistenceContext.java | 2 +- .../engine/internal/TwoPhaseLoad.java | 2 +- .../engine/internal/UnsavedValueFactory.java | 2 +- .../org/hibernate/engine/jdbc/BlobProxy.java | 25 +++------ .../engine/jdbc/CharacterStream.java | 1 - .../org/hibernate/engine/jdbc/ClobProxy.java | 27 +++------ .../engine/jdbc/ColumnNameCache.java | 33 ++++++++--- .../engine/jdbc/ContextualLobCreator.java | 28 +++++++--- .../engine/jdbc/LobCreationContext.java | 7 ++- .../engine/jdbc/NClobImplementer.java | 1 - .../org/hibernate/engine/jdbc/NClobProxy.java | 18 ++---- .../engine/jdbc/NonContextualLobCreator.java | 3 + .../engine/jdbc/ReaderInputStream.java | 11 +++- .../engine/jdbc/ResultSetWrapperProxy.java | 36 ++++++------ .../engine/jdbc/SerializableBlobProxy.java | 13 +++-- .../engine/jdbc/SerializableClobProxy.java | 13 +++-- .../engine/jdbc/SerializableNClobProxy.java | 16 ++++-- .../hibernate/engine/jdbc/StreamUtils.java | 52 +++++++++++++++++- .../hibernate/engine/jdbc/WrappedNClob.java | 12 ++++ .../batch/internal/AbstractBatchImpl.java | 9 ++- .../jdbc/batch/internal/BasicBatchKey.java | 23 +++----- .../jdbc/batch/internal/BatchBuilderImpl.java | 27 ++++++--- .../batch/internal/BatchBuilderInitiator.java | 7 +++ .../jdbc/batch/internal/BatchingBatch.java | 17 ++++-- .../jdbc/batch/internal/NonBatchingBatch.java | 6 +- .../jdbc/batch/internal/package-info.java | 4 ++ .../engine/jdbc/batch/spi/package-info.java | 4 ++ .../internal/ConnectionProviderInitiator.java | 45 ++++++++++----- .../DatasourceConnectionProviderImpl.java | 19 ++----- .../DriverManagerConnectionProviderImpl.java | 45 ++++++++++----- ...ultiTenantConnectionProviderInitiator.java | 9 ++- .../UserSuppliedConnectionProviderImpl.java | 12 +--- .../connections/internal/package-info.java | 4 ++ .../connections/spi/ConnectionProvider.java | 5 +- ...asedMultiTenantConnectionProviderImpl.java | 7 ++- .../spi/MultiTenantConnectionProvider.java | 3 + .../jdbc/connections/spi/package-info.java | 4 ++ .../hibernate/engine/jdbc/package-info.java | 4 ++ shared/config/checkstyle/checkstyle.xml | 3 + 49 files changed, 473 insertions(+), 209 deletions(-) create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/spi/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/package-info.java diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/function/TemplateRenderer.java b/hibernate-core/src/main/java/org/hibernate/dialect/function/TemplateRenderer.java index f8a64137c3..b9c7ba7129 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/function/TemplateRenderer.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/function/TemplateRenderer.java @@ -59,7 +59,9 @@ public class TemplateRenderer { final StringBuilder chunk = new StringBuilder( 10 ); final StringBuilder index = new StringBuilder( 2 ); - for ( int i = 0; i < template.length(); ++i ) { + int i = 0; + final int len = template.length(); + while ( i < len ) { char c = template.charAt( i ); if ( c == '?' ) { chunkList.add( chunk.toString() ); @@ -82,6 +84,7 @@ public class TemplateRenderer { else { chunk.append( c ); } + i++; } if ( chunk.length() > 0 ) { @@ -90,7 +93,7 @@ public class TemplateRenderer { chunks = chunkList.toArray( new String[chunkList.size()] ); paramIndexes = new int[paramList.size()]; - for ( int i = 0; i < paramIndexes.length; ++i ) { + for ( i = 0; i < paramIndexes.length; ++i ) { paramIndexes[i] = paramList.get( i ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/OptimisticLockStyle.java b/hibernate-core/src/main/java/org/hibernate/engine/OptimisticLockStyle.java index b0211d708f..510ec68aa7 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/OptimisticLockStyle.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/OptimisticLockStyle.java @@ -56,6 +56,15 @@ public enum OptimisticLockStyle { return oldCode; } + /** + * Given an old code (one of the int constants from Cascade), interpret it as one of the new enums. + * + * @param oldCode The old int constant code + * + * @return The interpreted enum value + * + * @throws IllegalArgumentException If the code did not match any legacy constant. + */ public static OptimisticLockStyle interpretOldCode(int oldCode) { switch ( oldCode ) { case -1: { diff --git a/hibernate-core/src/main/java/org/hibernate/engine/config/spi/ConfigurationService.java b/hibernate-core/src/main/java/org/hibernate/engine/config/spi/ConfigurationService.java index de5a4fb955..98a42ede4f 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/config/spi/ConfigurationService.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/config/spi/ConfigurationService.java @@ -33,10 +33,47 @@ import org.hibernate.service.Service; * @author Steve Ebersole */ public interface ConfigurationService extends Service { + /** + * Access to the complete map of config settings. The returned map is immutable + * + * @return The immutable map of config settings. + */ public Map getSettings(); + /** + * Get the named setting, using the specified converter. + * + * @param name The name of the setting to get. + * @param converter The converter to apply + * @param The Java type of the conversion + * + * @return The converted (typed) setting. May return {@code null} (see {@link #getSetting(String, Class, Object)}) + */ public T getSetting(String name, Converter converter); + + /** + * Get the named setting, using the specified converter and default value. + * + * @param name The name of the setting to get. + * @param converter The converter to apply + * @param defaultValue If no setting with that name is found, return this default value as the result. + * @param The Java type of the conversion + * + * @return The converted (typed) setting. Will be the defaultValue if no such setting was defined. + */ public T getSetting(String name, Converter converter, T defaultValue); + + /** + * Get the named setting. Differs from the form taking a Converter in that here we expect to have a simple + * cast rather than any involved conversion. + * + * @param name The name of the setting to get. + * @param expected The expected Java type. + * @param defaultValue If no setting with that name is found, return this default value as the result. + * @param The Java type of the conversion + * + * @return The converted (typed) setting. Will be the defaultValue if no such setting was defined. + */ public T getSetting(String name, Class expected, T defaultValue); /** @@ -44,10 +81,28 @@ public interface ConfigurationService extends Service { * * @param expected The type of instance expected to return. * @param candidate The candidate object to be casted. + * @param The java type of the expected return + * * @return The instance of expected type or null if this cast fail. + * + * @deprecated No idea why this is exposed here... */ + @Deprecated public T cast(Class expected, Object candidate); + + /** + * Simple conversion contract for converting an untyped object to a specified type. + * + * @param The Java type of the converted value + */ public static interface Converter { + /** + * Convert an untyped Object reference to the Converter's type. + * + * @param value The untyped value + * + * @return The converted (typed) value. + */ public T convert(Object value); } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/Cascade.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/Cascade.java index 943e0a9db5..2ba334a022 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/Cascade.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/Cascade.java @@ -258,7 +258,7 @@ public final class Cascade { final Object[] children = componentType.getPropertyValues( child, eventSource ); final Type[] types = componentType.getSubtypes(); for ( int i=0; i getLength() ) { throw new SQLException( "Start position [" + start + "] cannot exceed overall CLOB length [" + getLength() + "]" ); } - int length = (Integer) args[1]; + final int length = (Integer) args[1]; if ( length < 0 ) { // java docs specifically say for getBinaryStream(long,int) that the start+length must not exceed the // total length, however that is at odds with the getBytes(long,int) behavior. @@ -131,11 +130,11 @@ public class BlobProxy implements InvocationHandler { } if ( "getBytes".equals( methodName ) ) { if ( argCount == 2 ) { - long start = (Long) args[0]; + final long start = (Long) args[0]; if ( start < 1 ) { throw new SQLException( "Start position 1-based; must be 1 or more." ); } - int length = (Integer) args[1]; + final int length = (Integer) args[1]; if ( length < 0 ) { throw new SQLException( "Length must be great-than-or-equal to zero." ); } @@ -167,11 +166,7 @@ public class BlobProxy implements InvocationHandler { * @return The generated proxy. */ public static Blob generateProxy(byte[] bytes) { - return ( Blob ) Proxy.newProxyInstance( - getProxyClassLoader(), - PROXY_INTERFACES, - new BlobProxy( bytes ) - ); + return (Blob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new BlobProxy( bytes ) ); } /** @@ -183,11 +178,7 @@ public class BlobProxy implements InvocationHandler { * @return The generated proxy. */ public static Blob generateProxy(InputStream stream, long length) { - return ( Blob ) Proxy.newProxyInstance( - getProxyClassLoader(), - PROXY_INTERFACES, - new BlobProxy( stream, length ) - ); + return (Blob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new BlobProxy( stream, length ) ); } /** diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/CharacterStream.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/CharacterStream.java index f90d6c3356..f63c6757f1 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/CharacterStream.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/CharacterStream.java @@ -23,7 +23,6 @@ */ package org.hibernate.engine.jdbc; -import java.io.InputStream; import java.io.Reader; /** diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ClobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ClobProxy.java index f45489f2d9..5faf45cbb5 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ClobProxy.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ClobProxy.java @@ -26,7 +26,6 @@ package org.hibernate.engine.jdbc; import java.io.IOException; import java.io.InputStream; import java.io.Reader; -import java.io.StringReader; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; @@ -49,7 +48,7 @@ public class ClobProxy implements InvocationHandler { private static final Class[] PROXY_INTERFACES = new Class[] { Clob.class, ClobImplementer.class }; private final CharacterStream characterStream; - private boolean needsReset = false; + private boolean needsReset; /** * Constructor used to build {@link Clob} from string data. @@ -89,8 +88,8 @@ public class ClobProxy implements InvocationHandler { protected String getSubString(long start, int length) { final String string = characterStream.asString(); // semi-naive implementation - int endIndex = Math.min( ((int)start)+length, string.length() ); - return string.substring( (int)start, endIndex ); + final int endIndex = Math.min( ( (int) start ) + length, string.length() ); + return string.substring( (int) start, endIndex ); } /** @@ -119,14 +118,14 @@ public class ClobProxy implements InvocationHandler { return getCharacterStream(); } else if ( argCount == 2 ) { - long start = (Long) args[0]; + final long start = (Long) args[0]; if ( start < 1 ) { throw new SQLException( "Start position 1-based; must be 1 or more." ); } if ( start > getLength() ) { throw new SQLException( "Start position [" + start + "] cannot exceed overall CLOB length [" + getLength() + "]" ); } - int length = (Integer) args[1]; + final int length = (Integer) args[1]; if ( length < 0 ) { // java docs specifically say for getCharacterStream(long,int) that the start+length must not exceed the // total length, however that is at odds with the getSubString(long,int) behavior. @@ -136,14 +135,14 @@ public class ClobProxy implements InvocationHandler { } } if ( "getSubString".equals( methodName ) && argCount == 2 ) { - long start = (Long) args[0]; + final long start = (Long) args[0]; if ( start < 1 ) { throw new SQLException( "Start position 1-based; must be 1 or more." ); } if ( start > getLength() ) { throw new SQLException( "Start position [" + start + "] cannot exceed overall CLOB length [" + getLength() + "]" ); } - int length = (Integer) args[1]; + final int length = (Integer) args[1]; if ( length < 0 ) { throw new SQLException( "Length must be great-than-or-equal to zero." ); } @@ -186,11 +185,7 @@ public class ClobProxy implements InvocationHandler { * @return The generated proxy. */ public static Clob generateProxy(String string) { - return ( Clob ) Proxy.newProxyInstance( - getProxyClassLoader(), - PROXY_INTERFACES, - new ClobProxy( string ) - ); + return (Clob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new ClobProxy( string ) ); } /** @@ -202,11 +197,7 @@ public class ClobProxy implements InvocationHandler { * @return The generated proxy. */ public static Clob generateProxy(Reader reader, long length) { - return ( Clob ) Proxy.newProxyInstance( - getProxyClassLoader(), - PROXY_INTERFACES, - new ClobProxy( reader, length ) - ); + return (Clob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new ClobProxy( reader, length ) ); } /** diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ColumnNameCache.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ColumnNameCache.java index 934e2c6c55..c1b006958c 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ColumnNameCache.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ColumnNameCache.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.engine.jdbc; + import java.sql.ResultSet; import java.sql.SQLException; import java.util.Map; @@ -33,24 +34,42 @@ import java.util.concurrent.ConcurrentHashMap; * @author Steve Ebersole */ public class ColumnNameCache { - public static final float LOAD_FACTOR = .75f; + private static final float LOAD_FACTOR = .75f; private final Map columnNameToIndexCache; + /** + * Constructs a ColumnNameCache + * + * @param columnCount The number of columns to be cached. + */ public ColumnNameCache(int columnCount) { // should *not* need to grow beyond the size of the total number of columns in the rs - this.columnNameToIndexCache = new ConcurrentHashMap( columnCount + (int)( columnCount * LOAD_FACTOR ) + 1, LOAD_FACTOR ); + this.columnNameToIndexCache = new ConcurrentHashMap( + columnCount + (int)( columnCount * LOAD_FACTOR ) + 1, + LOAD_FACTOR + ); } + /** + * Resolve the column name/alias to its index + * + * @param columnName The name/alias of the column + * @param rs The ResultSet + * + * @return The index + * + * @throws SQLException INdicates a problems accessing the underlying JDBC ResultSet + */ public int getIndexForColumnName(String columnName, ResultSet rs) throws SQLException { - Integer cached = columnNameToIndexCache.get( columnName ); + final Integer cached = columnNameToIndexCache.get( columnName ); if ( cached != null ) { return cached; } else { - int index = rs.findColumn( columnName ); + final int index = rs.findColumn( columnName ); columnNameToIndexCache.put( columnName, index); return index; } } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ContextualLobCreator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ContextualLobCreator.java index 3ed10eae56..14859aed60 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ContextualLobCreator.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ContextualLobCreator.java @@ -22,18 +22,15 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.engine.jdbc; -import java.io.IOException; + import java.io.InputStream; -import java.io.OutputStream; import java.io.Reader; -import java.io.Writer; import java.sql.Blob; import java.sql.Clob; import java.sql.Connection; import java.sql.NClob; import java.sql.SQLException; -import org.hibernate.HibernateException; import org.hibernate.JDBCException; /** @@ -46,6 +43,11 @@ import org.hibernate.JDBCException; public class ContextualLobCreator extends AbstractLobCreator implements LobCreator { private LobCreationContext lobCreationContext; + /** + * Constructs a ContextualLobCreator + * + * @param lobCreationContext The context for performing LOB creation + */ public ContextualLobCreator(LobCreationContext lobCreationContext) { this.lobCreationContext = lobCreationContext; } @@ -62,7 +64,7 @@ public class ContextualLobCreator extends AbstractLobCreator implements LobCreat @Override public Blob createBlob(byte[] bytes) { try { - Blob blob = createBlob(); + final Blob blob = createBlob(); blob.setBytes( 1, bytes ); return blob; } @@ -90,7 +92,7 @@ public class ContextualLobCreator extends AbstractLobCreator implements LobCreat @Override public Clob createClob(String string) { try { - Clob clob = createClob(); + final Clob clob = createClob(); clob.setString( 1, string ); return clob; } @@ -118,7 +120,7 @@ public class ContextualLobCreator extends AbstractLobCreator implements LobCreat @Override public NClob createNClob(String string) { try { - NClob nclob = createNClob(); + final NClob nclob = createNClob(); nclob.setString( 1, string ); return nclob; } @@ -134,19 +136,31 @@ public class ContextualLobCreator extends AbstractLobCreator implements LobCreat return NonContextualLobCreator.INSTANCE.createNClob( reader, length ); } + /** + * Callback for performing contextual BLOB creation + */ public static final LobCreationContext.Callback CREATE_BLOB_CALLBACK = new LobCreationContext.Callback() { + @Override public Blob executeOnConnection(Connection connection) throws SQLException { return connection.createBlob(); } }; + /** + * Callback for performing contextual CLOB creation + */ public static final LobCreationContext.Callback CREATE_CLOB_CALLBACK = new LobCreationContext.Callback() { + @Override public Clob executeOnConnection(Connection connection) throws SQLException { return connection.createClob(); } }; + /** + * Callback for performing contextual NCLOB creation + */ public static final LobCreationContext.Callback CREATE_NCLOB_CALLBACK = new LobCreationContext.Callback() { + @Override public NClob executeOnConnection(Connection connection) throws SQLException { return connection.createNClob(); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/LobCreationContext.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/LobCreationContext.java index 42a764e7b8..1276676eba 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/LobCreationContext.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/LobCreationContext.java @@ -39,8 +39,10 @@ public interface LobCreationContext { * Perform whatever actions are necessary using the provided JDBC {@link Connection}. * * @param connection The JDBC {@link Connection}. + * * @return The created LOB. - * @throws SQLException + * + * @throws SQLException Indicates trouble accessing the JDBC driver to create the LOB */ public T executeOnConnection(Connection connection) throws SQLException; } @@ -49,6 +51,9 @@ public interface LobCreationContext { * Execute the given callback, making sure it has access to a viable JDBC {@link Connection}. * * @param callback The callback to execute . + * @param The Java type of the type of LOB being created. One of {@link java.sql.Blob}, + * {@link java.sql.Clob}, {@link java.sql.NClob} + * * @return The LOB created by the callback. */ public T execute(Callback callback); diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobImplementer.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobImplementer.java index f7de45cda4..9676ea2778 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobImplementer.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobImplementer.java @@ -23,7 +23,6 @@ */ package org.hibernate.engine.jdbc; - /** * Marker interface for non-contextually created java.sql.NClob instances.. *

      diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobProxy.java index 4f9227891d..5f44978694 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobProxy.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NClobProxy.java @@ -25,7 +25,6 @@ package org.hibernate.engine.jdbc; import java.io.Reader; import java.lang.reflect.Proxy; -import java.sql.Clob; import java.sql.NClob; import org.hibernate.internal.util.ClassLoaderHelper; @@ -40,6 +39,9 @@ import org.hibernate.internal.util.ClassLoaderHelper; * @author Steve Ebersole */ public class NClobProxy extends ClobProxy { + /** + * The interfaces used to generate the proxy + */ public static final Class[] PROXY_INTERFACES = new Class[] { NClob.class, NClobImplementer.class }; protected NClobProxy(String string) { @@ -58,15 +60,11 @@ public class NClobProxy extends ClobProxy { * @return The generated proxy. */ public static NClob generateProxy(String string) { - return ( NClob ) Proxy.newProxyInstance( - getProxyClassLoader(), - PROXY_INTERFACES, - new ClobProxy( string ) - ); + return (NClob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new ClobProxy( string ) ); } /** - * Generates a {@link Clob} proxy using a character reader of given length. + * Generates a {@link java.sql.NClob} proxy using a character reader of given length. * * @param reader The character reader * @param length The length of the character reader @@ -74,11 +72,7 @@ public class NClobProxy extends ClobProxy { * @return The generated proxy. */ public static NClob generateProxy(Reader reader, long length) { - return ( NClob ) Proxy.newProxyInstance( - getProxyClassLoader(), - PROXY_INTERFACES, - new ClobProxy( reader, length ) - ); + return (NClob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new ClobProxy( reader, length ) ); } /** diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NonContextualLobCreator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NonContextualLobCreator.java index 93b5ec9db0..886e2493f5 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NonContextualLobCreator.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/NonContextualLobCreator.java @@ -37,6 +37,9 @@ import java.sql.NClob; * @author Gail Badner */ public class NonContextualLobCreator extends AbstractLobCreator implements LobCreator { + /** + * Singleton access + */ public static final NonContextualLobCreator INSTANCE = new NonContextualLobCreator(); private NonContextualLobCreator() { diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ReaderInputStream.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ReaderInputStream.java index 4c2fb9e248..9c6aa52573 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ReaderInputStream.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ReaderInputStream.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.engine.jdbc; + import java.io.IOException; import java.io.InputStream; import java.io.Reader; @@ -33,11 +34,17 @@ import java.io.Reader; */ public class ReaderInputStream extends InputStream { private Reader reader; - + + /** + * Constructs a ReaderInputStream from a Reader + * + * @param reader The reader to expose as an InputStream + */ public ReaderInputStream(Reader reader) { this.reader = reader; } - + + @Override public int read() throws IOException { return reader.read(); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java index 4b0b21ea3f..addfd6210f 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java @@ -44,10 +44,12 @@ import org.hibernate.internal.util.ClassLoaderHelper; * @author Gail Badner */ public class ResultSetWrapperProxy implements InvocationHandler { - - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, ResultSetWrapperProxy.class.getName()); + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + ResultSetWrapperProxy.class.getName() + ); private static final Class[] PROXY_INTERFACES = new Class[] { ResultSet.class }; - private static final SqlExceptionHelper sqlExceptionHelper = new SqlExceptionHelper(); + private static final SqlExceptionHelper SQL_EXCEPTION_HELPER = new SqlExceptionHelper(); private final ResultSet rs; private final ColumnNameCache columnNameCache; @@ -65,7 +67,7 @@ public class ResultSetWrapperProxy implements InvocationHandler { * @return The generated proxy. */ public static ResultSet generateProxy(ResultSet resultSet, ColumnNameCache columnNameCache) { - return ( ResultSet ) Proxy.newProxyInstance( + return (ResultSet) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new ResultSetWrapperProxy( resultSet, columnNameCache ) @@ -90,26 +92,22 @@ public class ResultSetWrapperProxy implements InvocationHandler { @SuppressWarnings( {"UnnecessaryBoxing"}) public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ( "findColumn".equals( method.getName() ) ) { - return Integer.valueOf( findColumn( ( String ) args[0] ) ); + return Integer.valueOf( findColumn( (String) args[0] ) ); } if ( isFirstArgColumnLabel( method, args ) ) { try { - int columnIndex = findColumn( ( String ) args[0] ); + final int columnIndex = findColumn( (String) args[0] ); return invokeMethod( - locateCorrespondingColumnIndexMethod( method ), buildColumnIndexMethodArgs( args, columnIndex ) + locateCorrespondingColumnIndexMethod( method ), + buildColumnIndexMethodArgs( args, columnIndex ) ); } catch ( SQLException ex ) { - StringBuilder buf = new StringBuilder() - .append( "Exception getting column index for column: [" ) - .append( args[0] ) - .append( "].\nReverting to using: [" ) - .append( args[0] ) - .append( "] as first argument for method: [" ) - .append( method ) - .append( "]" ); - sqlExceptionHelper.logExceptions( ex, buf.toString() ); + final String msg = "Exception getting column index for column: [" + args[0] + + "].\nReverting to using: [" + args[0] + + "] as first argument for method: [" + method + "]"; + SQL_EXCEPTION_HELPER.logExceptions( ex, msg ); } catch ( NoSuchMethodException ex ) { LOG.unableToSwitchToMethodUsingColumnIndex( method ); @@ -158,7 +156,7 @@ public class ResultSetWrapperProxy implements InvocationHandler { * @throws NoSuchMethodException Should never happen, but... */ private Method locateCorrespondingColumnIndexMethod(Method columnNameMethod) throws NoSuchMethodException { - Class actualParameterTypes[] = new Class[columnNameMethod.getParameterTypes().length]; + final Class[] actualParameterTypes = new Class[columnNameMethod.getParameterTypes().length]; actualParameterTypes[0] = int.class; System.arraycopy( columnNameMethod.getParameterTypes(), @@ -172,13 +170,13 @@ public class ResultSetWrapperProxy implements InvocationHandler { @SuppressWarnings( {"UnnecessaryBoxing"}) private Object[] buildColumnIndexMethodArgs(Object[] incomingArgs, int columnIndex) { - Object actualArgs[] = new Object[incomingArgs.length]; + final Object[] actualArgs = new Object[incomingArgs.length]; actualArgs[0] = Integer.valueOf( columnIndex ); System.arraycopy( incomingArgs, 1, actualArgs, 1, incomingArgs.length - 1 ); return actualArgs; } - private Object invokeMethod(Method method, Object args[]) throws Throwable { + private Object invokeMethod(Method method, Object[] args) throws Throwable { try { return method.invoke( rs, args ); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableBlobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableBlobProxy.java index 0d8209ef72..37796b530c 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableBlobProxy.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableBlobProxy.java @@ -43,7 +43,7 @@ import org.hibernate.internal.util.ClassLoaderHelper; public class SerializableBlobProxy implements InvocationHandler, Serializable { private static final Class[] PROXY_INTERFACES = new Class[] { Blob.class, WrappedBlob.class, Serializable.class }; - private transient final Blob blob; + private final transient Blob blob; /** * Builds a serializable {@link Blob} wrapper around the given {@link Blob}. @@ -55,6 +55,11 @@ public class SerializableBlobProxy implements InvocationHandler, Serializable { this.blob = blob; } + /** + * Access to the wrapped Blob reference + * + * @return The wrapped Blob reference + */ public Blob getWrappedBlob() { if ( blob == null ) { throw new IllegalStateException( "Blobs may not be accessed after serialization" ); @@ -88,11 +93,7 @@ public class SerializableBlobProxy implements InvocationHandler, Serializable { * @return The generated proxy. */ public static Blob generateProxy(Blob blob) { - return ( Blob ) Proxy.newProxyInstance( - getProxyClassLoader(), - PROXY_INTERFACES, - new SerializableBlobProxy( blob ) - ); + return (Blob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new SerializableBlobProxy( blob ) ); } /** diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableClobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableClobProxy.java index 8b499e5c25..f5a490ae14 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableClobProxy.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableClobProxy.java @@ -43,7 +43,7 @@ import org.hibernate.internal.util.ClassLoaderHelper; public class SerializableClobProxy implements InvocationHandler, Serializable { private static final Class[] PROXY_INTERFACES = new Class[] { Clob.class, WrappedClob.class, Serializable.class }; - private transient final Clob clob; + private final transient Clob clob; /** * Builds a serializable {@link java.sql.Clob} wrapper around the given {@link java.sql.Clob}. @@ -55,6 +55,11 @@ public class SerializableClobProxy implements InvocationHandler, Serializable { this.clob = clob; } + /** + * Access to the wrapped Clob reference + * + * @return The wrapped Clob reference + */ public Clob getWrappedClob() { if ( clob == null ) { throw new IllegalStateException( "Clobs may not be accessed after serialization" ); @@ -87,11 +92,7 @@ public class SerializableClobProxy implements InvocationHandler, Serializable { * @return The generated proxy. */ public static Clob generateProxy(Clob clob) { - return ( Clob ) Proxy.newProxyInstance( - getProxyClassLoader(), - PROXY_INTERFACES, - new SerializableClobProxy( clob ) - ); + return (Clob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new SerializableClobProxy( clob ) ); } /** diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableNClobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableNClobProxy.java index cde389cb01..7044058392 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableNClobProxy.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/SerializableNClobProxy.java @@ -35,6 +35,16 @@ import java.sql.NClob; public class SerializableNClobProxy extends SerializableClobProxy { private static final Class[] PROXY_INTERFACES = new Class[] { NClob.class, WrappedNClob.class }; + /** + * Deprecated. + * + * @param clob The possible NClob reference + * + * @return {@code true} if the the Clob is a NClob as well + * + * @deprecated ORM baselines on JDK 1.6, so optional support for NClob (JDK 1,6 addition) is no longer needed. + */ + @Deprecated public static boolean isNClob(Clob clob) { return NClob.class.isInstance( clob ); } @@ -57,11 +67,7 @@ public class SerializableNClobProxy extends SerializableClobProxy { * @return The generated proxy. */ public static NClob generateProxy(NClob nclob) { - return ( NClob ) Proxy.newProxyInstance( - getProxyClassLoader(), - PROXY_INTERFACES, - new SerializableNClobProxy( nclob ) - ); + return (NClob) Proxy.newProxyInstance( getProxyClassLoader(), PROXY_INTERFACES, new SerializableNClobProxy( nclob ) ); } /** diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/StreamUtils.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/StreamUtils.java index 205030b03e..fd7f9178fa 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/StreamUtils.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/StreamUtils.java @@ -35,14 +35,38 @@ import java.io.Writer; * @author Steve Ebersole */ public class StreamUtils { + /** + * Default size to use for reading buffers. + */ public static final int DEFAULT_CHUNK_SIZE = 1024; + /** + * Copy the inputStream to the outputStream. Uses a buffer of the default size ({@link #DEFAULT_CHUNK_SIZE}). + * + * @param inputStream The input stream to read + * @param outputStream The output stream to write to + * + * @return The number of bytes read + * + * @throws IOException If a problem occurred accessing either stream + */ public static long copy(InputStream inputStream, OutputStream outputStream) throws IOException { return copy( inputStream, outputStream, DEFAULT_CHUNK_SIZE ); } + /** + * Copy the inputStream to the outputStream using a buffer of the specified size + * + * @param inputStream The input stream to read + * @param outputStream The output stream to write to + * @param bufferSize The size of the buffer to use for reading + * + * @return The number of bytes read + * + * @throws IOException If a problem occurred accessing either stream + */ public static long copy(InputStream inputStream, OutputStream outputStream, int bufferSize) throws IOException { - byte[] buffer = new byte[bufferSize]; + final byte[] buffer = new byte[bufferSize]; long count = 0; int n; while ( -1 != ( n = inputStream.read( buffer ) ) ) { @@ -50,15 +74,35 @@ public class StreamUtils { count += n; } return count; - } + /** + * Copy the reader to the writer. Uses a buffer of the default size ({@link #DEFAULT_CHUNK_SIZE}). + * + * @param reader The reader to read from + * @param writer The writer to write to + * + * @return The number of bytes read + * + * @throws IOException If a problem occurred accessing reader or writer + */ public static long copy(Reader reader, Writer writer) throws IOException { return copy( reader, writer, DEFAULT_CHUNK_SIZE ); } + /** + * Copy the reader to the writer using a buffer of the specified size + * + * @param reader The reader to read from + * @param writer The writer to write to + * @param bufferSize The size of the buffer to use for reading + * + * @return The number of bytes read + * + * @throws IOException If a problem occurred accessing either stream + */ public static long copy(Reader reader, Writer writer, int bufferSize) throws IOException { - char[] buffer = new char[bufferSize]; + final char[] buffer = new char[bufferSize]; long count = 0; int n; while ( -1 != ( n = reader.read( buffer ) ) ) { @@ -66,6 +110,8 @@ public class StreamUtils { count += n; } return count; + } + private StreamUtils() { } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/WrappedNClob.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/WrappedNClob.java index 41c801e160..8e7d084a59 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/WrappedNClob.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/WrappedNClob.java @@ -26,12 +26,24 @@ package org.hibernate.engine.jdbc; import java.sql.NClob; /** + * Contract for {@link NClob} wrappers. + * * @author Steve Ebersole */ public interface WrappedNClob extends WrappedClob { + /** + * {@inheritDoc} + * + * @deprecated Use {@link #getWrappedNClob()} instead + */ @Override @Deprecated public NClob getWrappedClob(); + /** + * Retrieve the wrapped {@link java.sql.Blob} reference + * + * @return The wrapped {@link java.sql.Blob} reference + */ public NClob getWrappedNClob(); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/AbstractBatchImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/AbstractBatchImpl.java index 4d18551cde..bff82b93e0 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/AbstractBatchImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/AbstractBatchImpl.java @@ -45,11 +45,14 @@ import org.hibernate.internal.CoreMessageLogger; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public abstract class AbstractBatchImpl implements Batch { - - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, AbstractBatchImpl.class.getName()); + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + AbstractBatchImpl.class.getName() + ); private final BatchKey key; private final JdbcCoordinator jdbcCoordinator; + private LinkedHashMap statements = new LinkedHashMap(); private LinkedHashSet observers = new LinkedHashSet(); @@ -191,7 +194,7 @@ public abstract class AbstractBatchImpl implements Batch { @Override public void release() { - if ( getStatements() != null && !getStatements().isEmpty() ) { + if ( getStatements() != null && !getStatements().isEmpty() ) { LOG.batchContainedStatementsOnRelease(); } releaseStatements(); diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java index 0cff7e330a..1a9ecee23b 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java @@ -27,6 +27,8 @@ import org.hibernate.engine.jdbc.batch.spi.BatchKey; import org.hibernate.jdbc.Expectation; /** + * Normal implementation of BatchKey + * * @author Steve Ebersole */ public class BasicBatchKey implements BatchKey { @@ -34,19 +36,12 @@ public class BasicBatchKey implements BatchKey { private final int statementCount; private final Expectation expectation; -// public BasicBatchKey(String comparison, int statementCount, Expectation expectation) { -// this.comparison = comparison; -// this.statementCount = statementCount; -// this.expectations = new Expectation[statementCount]; -// Arrays.fill( this.expectations, expectation ); -// } -// -// public BasicBatchKey(String comparison, Expectation... expectations) { -// this.comparison = comparison; -// this.statementCount = expectations.length; -// this.expectations = expectations; -// } - + /** + * Constructs a BasicBatchKey + * + * @param comparison + * @param expectation + */ public BasicBatchKey(String comparison, Expectation expectation) { this.comparison = comparison; this.statementCount = 1; @@ -72,7 +67,7 @@ public class BasicBatchKey implements BatchKey { return false; } - BasicBatchKey that = (BasicBatchKey) o; + final BasicBatchKey that = (BasicBatchKey) o; if ( !comparison.equals( that.comparison ) ) { return false; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java index 725f090124..ab77258d63 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java @@ -42,23 +42,32 @@ import org.hibernate.service.spi.Configurable; * @author Steve Ebersole */ public class BatchBuilderImpl implements BatchBuilder, Configurable { - - private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, BatchBuilderImpl.class.getName() ); + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + BatchBuilderImpl.class.getName() + ); private int size; + /** + * Constructs a BatchBuilderImpl + */ public BatchBuilderImpl() { } + /** + * Constructs a BatchBuilderImpl + */ + public BatchBuilderImpl(int size) { + this.size = size; + } + @Override public void configure(Map configurationValues) { size = ConfigurationHelper.getInt( Environment.STATEMENT_BATCH_SIZE, configurationValues, size ); } - public BatchBuilderImpl(int size) { - this.size = size; - } - + @SuppressWarnings("UnusedDeclaration") public void setJdbcBatchSize(int size) { this.size = size; } @@ -73,12 +82,14 @@ public class BatchBuilderImpl implements BatchBuilder, Configurable { @Override public String getManagementDomain() { - return null; // use Hibernate default domain + // use Hibernate default domain + return null; } @Override public String getManagementServiceType() { - return null; // use Hibernate default scheme + // use Hibernate default scheme + return null; } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderInitiator.java index 374a51edd3..edcb0f4014 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderInitiator.java @@ -39,7 +39,14 @@ import org.hibernate.service.spi.ServiceRegistryImplementor; * @author Steve Ebersole */ public class BatchBuilderInitiator implements StandardServiceInitiator { + /** + * Singleton access + */ public static final BatchBuilderInitiator INSTANCE = new BatchBuilderInitiator(); + + /** + * Names the BatchBuilder implementation to use. + */ public static final String BUILDER = "hibernate.jdbc.batch.builder"; @Override diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchingBatch.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchingBatch.java index 4af15f8562..dc948c6596 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchingBatch.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchingBatch.java @@ -40,8 +40,10 @@ import org.hibernate.internal.CoreMessageLogger; * @author Steve Ebersole */ public class BatchingBatch extends AbstractBatchImpl { - - private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, BatchingBatch.class.getName() ); + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + BatchingBatch.class.getName() + ); // IMPL NOTE : Until HHH-5797 is fixed, there will only be 1 statement in a batch @@ -49,6 +51,13 @@ public class BatchingBatch extends AbstractBatchImpl { private int batchPosition; private int statementPosition; + /** + * Constructs a BatchingBatch + * + * @param key The batch key + * @param jdbcCoordinator The JDBC jdbcCoordinator + * @param batchSize The batch size. + */ public BatchingBatch( BatchKey key, JdbcCoordinator jdbcCoordinator, @@ -125,7 +134,7 @@ public class BatchingBatch extends AbstractBatchImpl { } private void checkRowCounts(int[] rowCounts, PreparedStatement ps) throws SQLException, HibernateException { - int numberOfRowCounts = rowCounts.length; + final int numberOfRowCounts = rowCounts.length; if ( numberOfRowCounts != batchPosition ) { LOG.unexpectedRowCounts(); } @@ -133,4 +142,4 @@ public class BatchingBatch extends AbstractBatchImpl { getKey().getExpectation().verifyOutcome( rowCounts[i], ps, i ); } } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/NonBatchingBatch.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/NonBatchingBatch.java index 04e46a7e44..0531019632 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/NonBatchingBatch.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/NonBatchingBatch.java @@ -39,8 +39,10 @@ import org.jboss.logging.Logger; * @author Steve Ebersole */ public class NonBatchingBatch extends AbstractBatchImpl { - - private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, NonBatchingBatch.class.getName() ); + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + NonBatchingBatch.class.getName() + ); private JdbcCoordinator jdbcCoordinator; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/package-info.java new file mode 100644 index 0000000000..09bc7430f0 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/package-info.java @@ -0,0 +1,4 @@ +/** + * Internals for JDBC batching support. + */ +package org.hibernate.engine.jdbc.batch.internal; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/spi/package-info.java new file mode 100644 index 0000000000..3719ea4ba8 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/spi/package-info.java @@ -0,0 +1,4 @@ +/** + * Defines contracts for JDBC batching support. + */ +package org.hibernate.engine.jdbc.batch.spi; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java index 69438692a1..9985b19ee6 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java @@ -52,14 +52,29 @@ import org.jboss.logging.Logger; * @author Brett Meyer */ public class ConnectionProviderInitiator implements StandardServiceInitiator { + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + ConnectionProviderInitiator.class.getName() + ); + + /** + * Singleton access + */ public static final ConnectionProviderInitiator INSTANCE = new ConnectionProviderInitiator(); - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, - ConnectionProviderInitiator.class.getName()); + /** + * The strategy for c3p0 connection pooling + */ public static final String C3P0_STRATEGY = "c3p0"; + /** + * The strategy for proxool connection pooling + */ public static final String PROXOOL_STRATEGY = "proxool"; + /** + * No idea. Is this even still used? + */ public static final String INJECTION_DATA = "hibernate.connection_provider.injection_data"; // mapping from legacy connection provider name to actual @@ -99,7 +114,7 @@ public class ConnectionProviderInitiator implements StandardServiceInitiator properties) { - Properties result = new Properties(); + final Properties result = new Properties(); for ( Map.Entry entry : properties.entrySet() ) { if ( ! ( String.class.isInstance( entry.getKey() ) ) || ! String.class.isInstance( entry.getValue() ) ) { continue; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DatasourceConnectionProviderImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DatasourceConnectionProviderImpl.java index 71b6e7f10c..516cc67872 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DatasourceConnectionProviderImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DatasourceConnectionProviderImpl.java @@ -49,7 +49,6 @@ import org.hibernate.service.spi.Stoppable; * @author Steve Ebersole */ public class DatasourceConnectionProviderImpl implements ConnectionProvider, Configurable, Stoppable { - private DataSource dataSource; private String user; private String pass; @@ -67,6 +66,7 @@ public class DatasourceConnectionProviderImpl implements ConnectionProvider, Con } @InjectService( required = false ) + @SuppressWarnings("UnusedDeclaration") public void setJndiService(JndiService jndiService) { this.jndiService = jndiService; } @@ -93,9 +93,7 @@ public class DatasourceConnectionProviderImpl implements ConnectionProvider, Con } } - /** - * {@inheritDoc} - */ + @Override public void configure(Map configValues) { if ( this.dataSource == null ) { final Object dataSource = configValues.get( Environment.DATASOURCE ); @@ -126,14 +124,13 @@ public class DatasourceConnectionProviderImpl implements ConnectionProvider, Con available = true; } + @Override public void stop() { available = false; dataSource = null; } - /** - * {@inheritDoc} - */ + @Override public Connection getConnection() throws SQLException { if ( !available ) { throw new HibernateException( "Provider is closed!" ); @@ -141,16 +138,12 @@ public class DatasourceConnectionProviderImpl implements ConnectionProvider, Con return useCredentials ? dataSource.getConnection( user, pass ) : dataSource.getConnection(); } - /** - * {@inheritDoc} - */ + @Override public void closeConnection(Connection connection) throws SQLException { connection.close(); } - /** - * {@inheritDoc} - */ + @Override public boolean supportsAggressiveRelease() { return true; } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DriverManagerConnectionProviderImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DriverManagerConnectionProviderImpl.java index df83684145..8482085edb 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DriverManagerConnectionProviderImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/DriverManagerConnectionProviderImpl.java @@ -95,10 +95,11 @@ public class DriverManagerConnectionProviderImpl } } + @Override public void configure(Map configurationValues) { LOG.usingHibernateBuiltInConnectionPool(); - String driverClassName = (String) configurationValues.get( AvailableSettings.DRIVER ); + final String driverClassName = (String) configurationValues.get( AvailableSettings.DRIVER ); if ( driverClassName == null ) { LOG.jdbcDriverNotSpecified( AvailableSettings.DRIVER ); } @@ -131,19 +132,21 @@ public class DriverManagerConnectionProviderImpl } } - poolSize = ConfigurationHelper.getInt( AvailableSettings.POOL_SIZE, configurationValues, 20 ); // default pool size 20 + // default pool size 20 + poolSize = ConfigurationHelper.getInt( AvailableSettings.POOL_SIZE, configurationValues, 20 ); LOG.hibernateConnectionPoolSize( poolSize ); autocommit = ConfigurationHelper.getBoolean( AvailableSettings.AUTOCOMMIT, configurationValues ); LOG.autoCommitMode( autocommit ); isolation = ConfigurationHelper.getInteger( AvailableSettings.ISOLATION, configurationValues ); - if ( isolation != null ) + if ( isolation != null ) { LOG.jdbcIsolationLevel( Environment.isolationLevelToString( isolation.intValue() ) ); + } url = (String) configurationValues.get( AvailableSettings.URL ); if ( url == null ) { - String msg = LOG.jdbcUrlNotSpecified( AvailableSettings.URL ); + final String msg = LOG.jdbcUrlNotSpecified( AvailableSettings.URL ); LOG.error( msg ); throw new HibernateException( msg ); } @@ -152,12 +155,15 @@ public class DriverManagerConnectionProviderImpl LOG.usingDriver( driverClassName, url ); // if debug level is enabled, then log the password, otherwise mask it - if ( LOG.isDebugEnabled() ) + if ( LOG.isDebugEnabled() ) { LOG.connectionProperties( connectionProps ); - else + } + else { LOG.connectionProperties( ConfigurationHelper.maskOut( connectionProps, "password" ) ); + } } + @Override public void stop() { LOG.cleaningUpConnectionPool( url ); @@ -173,16 +179,21 @@ public class DriverManagerConnectionProviderImpl stopped = true; } + @Override public Connection getConnection() throws SQLException { final boolean traceEnabled = LOG.isTraceEnabled(); - if ( traceEnabled ) LOG.tracev( "Total checked-out connections: {0}", checkedOut.intValue() ); + if ( traceEnabled ) { + LOG.tracev( "Total checked-out connections: {0}", checkedOut.intValue() ); + } // essentially, if we have available connections in the pool, use one... synchronized (pool) { if ( !pool.isEmpty() ) { int last = pool.size() - 1; - if ( traceEnabled ) LOG.tracev( "Using pooled JDBC connection, pool size: {0}", last ); - Connection pooled = pool.remove( last ); + if ( traceEnabled ) { + LOG.tracev( "Using pooled JDBC connection, pool size: {0}", last ); + } + final Connection pooled = pool.remove( last ); if ( isolation != null ) { pooled.setTransactionIsolation( isolation.intValue() ); } @@ -196,9 +207,11 @@ public class DriverManagerConnectionProviderImpl // otherwise we open a new connection... final boolean debugEnabled = LOG.isDebugEnabled(); - if ( debugEnabled ) LOG.debug( "Opening new JDBC connection" ); + if ( debugEnabled ) { + LOG.debug( "Opening new JDBC connection" ); + } - Connection conn; + final Connection conn; if ( driver != null ) { // If a Driver is available, completely circumvent // DriverManager#getConnection. It attempts to double check @@ -215,7 +228,7 @@ public class DriverManagerConnectionProviderImpl conn.setTransactionIsolation( isolation.intValue() ); } if ( conn.getAutoCommit() != autocommit ) { - conn.setAutoCommit(autocommit); + conn.setAutoCommit( autocommit ); } if ( debugEnabled ) { @@ -226,15 +239,18 @@ public class DriverManagerConnectionProviderImpl return conn; } + @Override public void closeConnection(Connection conn) throws SQLException { checkedOut.decrementAndGet(); final boolean traceEnabled = LOG.isTraceEnabled(); // add to the pool if the max size is not yet reached. synchronized ( pool ) { - int currentSize = pool.size(); + final int currentSize = pool.size(); if ( currentSize < poolSize ) { - if ( traceEnabled ) LOG.tracev( "Returning connection to pool, pool size: {0}", ( currentSize + 1 ) ); + if ( traceEnabled ) { + LOG.tracev( "Returning connection to pool, pool size: {0}", ( currentSize + 1 ) ); + } pool.add( conn ); return; } @@ -252,6 +268,7 @@ public class DriverManagerConnectionProviderImpl super.finalize(); } + @Override public boolean supportsAggressiveRelease() { return false; } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/MultiTenantConnectionProviderInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/MultiTenantConnectionProviderInitiator.java index deedad18f7..cc8d25ce2b 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/MultiTenantConnectionProviderInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/MultiTenantConnectionProviderInitiator.java @@ -38,12 +38,18 @@ import org.hibernate.service.spi.ServiceException; import org.hibernate.service.spi.ServiceRegistryImplementor; /** + * A service initiator for the MultiTenantConnectionProvider service + * * @author Steve Ebersole */ public class MultiTenantConnectionProviderInitiator implements StandardServiceInitiator { - public static final MultiTenantConnectionProviderInitiator INSTANCE = new MultiTenantConnectionProviderInitiator(); private static final Logger log = Logger.getLogger( MultiTenantConnectionProviderInitiator.class ); + /** + * Singleton access + */ + public static final MultiTenantConnectionProviderInitiator INSTANCE = new MultiTenantConnectionProviderInitiator(); + @Override public Class getServiceInitiated() { return MultiTenantConnectionProvider.class; @@ -55,6 +61,7 @@ public class MultiTenantConnectionProviderInitiator implements StandardServiceIn final MultiTenancyStrategy strategy = MultiTenancyStrategy.determineMultiTenancyStrategy( configurationValues ); if ( strategy == MultiTenancyStrategy.NONE || strategy == MultiTenancyStrategy.DISCRIMINATOR ) { // nothing to do, but given the separate hierarchies have to handle this here. + return null; } final Object configValue = configurationValues.get( AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER ); diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/UserSuppliedConnectionProviderImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/UserSuppliedConnectionProviderImpl.java index b7c966ea4b..903491d91b 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/UserSuppliedConnectionProviderImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/UserSuppliedConnectionProviderImpl.java @@ -55,23 +55,17 @@ public class UserSuppliedConnectionProviderImpl implements ConnectionProvider { } } - /** - * {@inheritDoc} - */ + @Override public Connection getConnection() throws SQLException { throw new UnsupportedOperationException( "The application must supply JDBC connections" ); } - /** - * {@inheritDoc} - */ + @Override public void closeConnection(Connection conn) throws SQLException { throw new UnsupportedOperationException( "The application must supply JDBC connections" ); } - /** - * {@inheritDoc} - */ + @Override public boolean supportsAggressiveRelease() { return false; } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/package-info.java new file mode 100644 index 0000000000..397a72a46f --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/package-info.java @@ -0,0 +1,4 @@ +/** + * Internals for accessing JDBC Connections + */ +package org.hibernate.engine.jdbc.connections.internal; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/ConnectionProvider.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/ConnectionProvider.java index 762d5b4613..ea47422c5e 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/ConnectionProvider.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/ConnectionProvider.java @@ -25,7 +25,6 @@ package org.hibernate.engine.jdbc.connections.spi; import java.sql.Connection; import java.sql.SQLException; -import org.hibernate.HibernateException; import org.hibernate.service.Service; import org.hibernate.service.spi.Wrapped; @@ -46,7 +45,7 @@ public interface ConnectionProvider extends Service, Wrapped { * @return The obtained JDBC connection * * @throws SQLException Indicates a problem opening a connection - * @throws HibernateException Indicates a problem otherwise obtaining a connection. + * @throws org.hibernate.HibernateException Indicates a problem otherwise obtaining a connection. */ public Connection getConnection() throws SQLException; @@ -56,7 +55,7 @@ public interface ConnectionProvider extends Service, Wrapped { * @param conn The JDBC connection to release * * @throws SQLException Indicates a problem closing the connection - * @throws HibernateException Indicates a problem otherwise releasing a connection. + * @throws org.hibernate.HibernateException Indicates a problem otherwise releasing a connection. */ public void closeConnection(Connection conn) throws SQLException; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/DataSourceBasedMultiTenantConnectionProviderImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/DataSourceBasedMultiTenantConnectionProviderImpl.java index cb387f1421..e13325ce77 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/DataSourceBasedMultiTenantConnectionProviderImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/DataSourceBasedMultiTenantConnectionProviderImpl.java @@ -56,6 +56,9 @@ public class DataSourceBasedMultiTenantConnectionProviderImpl extends AbstractDataSourceBasedMultiTenantConnectionProviderImpl implements ServiceRegistryAwareService, Stoppable { + /** + * Identifies the DataSource name to use for {@link #selectAnyDataSource} handling + */ public static final String TENANT_IDENTIFIER_TO_USE_FOR_ANY_KEY = "hibernate.multi_tenant.datasource.identifier_for_any"; private Map dataSourceMap; @@ -100,13 +103,13 @@ public class DataSourceBasedMultiTenantConnectionProviderImpl throw new HibernateException( "Could not locate JndiService from DataSourceBasedMultiTenantConnectionProviderImpl" ); } - Object namedObject = jndiService.locate( jndiName ); + final Object namedObject = jndiService.locate( jndiName ); if ( namedObject == null ) { throw new HibernateException( "JNDI name [" + jndiName + "] could not be resolved" ); } if ( DataSource.class.isInstance( namedObject ) ) { - int loc = jndiName.lastIndexOf( "/" ); + final int loc = jndiName.lastIndexOf( "/" ); this.baseJndiNamespace = jndiName.substring( 0, loc ); this.tenantIdentifierForAny = jndiName.substring( loc + 1 ); dataSourceMap().put( tenantIdentifierForAny, (DataSource) namedObject ); diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/MultiTenantConnectionProvider.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/MultiTenantConnectionProvider.java index 860d926c0b..b9fe64dff3 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/MultiTenantConnectionProvider.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/MultiTenantConnectionProvider.java @@ -30,6 +30,9 @@ import org.hibernate.service.Service; import org.hibernate.service.spi.Wrapped; /** + * A specialized Connection provider contract used when the application is using multi-tenancy support requiring + * tenant aware connections. + * * @author Steve Ebersole */ public interface MultiTenantConnectionProvider extends Service, Wrapped { diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/package-info.java new file mode 100644 index 0000000000..84342f8c58 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/spi/package-info.java @@ -0,0 +1,4 @@ +/** + * Defines contracts for accessing JDBC Connections + */ +package org.hibernate.engine.jdbc.connections.spi; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/package-info.java new file mode 100644 index 0000000000..acd103dc0b --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/package-info.java @@ -0,0 +1,4 @@ +/** + * Support for various aspects of JDBC interaction + */ +package org.hibernate.engine.jdbc; diff --git a/shared/config/checkstyle/checkstyle.xml b/shared/config/checkstyle/checkstyle.xml index a595af07b1..35417093de 100644 --- a/shared/config/checkstyle/checkstyle.xml +++ b/shared/config/checkstyle/checkstyle.xml @@ -202,7 +202,10 @@ + From 1c690ca89b433548ec0b8840ce08b649c71664d9 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Mon, 29 Apr 2013 20:24:54 -0500 Subject: [PATCH 27/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../engine/internal/ForeignKeys.java | 6 +- .../org/hibernate/engine/jdbc/BlobProxy.java | 2 +- .../engine/jdbc/ResultSetWrapperProxy.java | 2 +- .../jdbc/batch/internal/BasicBatchKey.java | 11 +-- .../jdbc/batch/internal/BatchBuilderImpl.java | 2 + .../internal/ConnectionProviderInitiator.java | 2 +- .../DriverManagerConnectionProviderImpl.java | 2 +- .../internal/RefCursorSupportInitiator.java | 5 ++ .../internal/StandardRefCursorSupport.java | 14 ++++ .../jdbc/cursor/internal/package-info.java | 4 + .../jdbc/cursor/spi/RefCursorSupport.java | 2 + .../engine/jdbc/cursor/spi/package-info.java | 4 + .../internal/BasicDialectResolver.java | 19 ++++- .../DatabaseInfoDialectResolverInitiator.java | 5 ++ .../DatabaseInfoDialectResolverSet.java | 20 ++++- .../internal/DialectFactoryInitiator.java | 3 + .../dialect/internal/DialectResolverSet.java | 28 ++++++- .../StandardDatabaseInfoDialectResolver.java | 7 +- ...andardDatabaseMetaDataDialectResolver.java | 12 ++- .../jdbc/dialect/internal/package-info.java | 4 + ...stractDatabaseMetaDataDialectResolver.java | 14 ++-- .../spi/BasicSQLExceptionConverter.java | 3 +- .../spi/DatabaseInfoDialectResolver.java | 6 ++ .../jdbc/dialect/spi/DialectResolver.java | 5 ++ .../engine/jdbc/dialect/spi/package-info.java | 4 + .../jdbc/internal/BasicFormatterImpl.java | 37 ++++----- .../jdbc/internal/BinaryStreamImpl.java | 5 ++ .../jdbc/internal/CharacterStreamImpl.java | 12 ++- .../jdbc/internal/DDLFormatterImpl.java | 38 +++++----- .../engine/jdbc/internal/FormatStyle.java | 19 ++++- .../jdbc/internal/JdbcCoordinatorImpl.java | 76 ++++++++++++++----- .../jdbc/internal/JdbcServicesImpl.java | 27 ++++--- .../jdbc/internal/JdbcServicesInitiator.java | 5 +- .../jdbc/internal/LobCreatorBuilder.java | 30 +++++--- .../jdbc/internal/LogicalConnectionImpl.java | 53 ++++++++++--- .../jdbc/internal/ResultSetReturnImpl.java | 33 +++++--- .../jdbc/internal/ResultSetWrapperImpl.java | 10 ++- .../jdbc/internal/StatementPreparerImpl.java | 23 +++--- .../engine/jdbc/internal/package-info.java | 4 + .../engine/jdbc/spi/package-info.java | 4 + 40 files changed, 411 insertions(+), 151 deletions(-) create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/package-info.java create mode 100644 hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/package-info.java diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/ForeignKeys.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/ForeignKeys.java index 58563f936c..d60257e146 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/ForeignKeys.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/ForeignKeys.java @@ -76,8 +76,7 @@ public final class ForeignKeys { * @param values The entity attribute values * @param types The entity attribute types */ - public void nullifyTransientReferences(final Object[] values, final Type[] types) - throws HibernateException { + public void nullifyTransientReferences(final Object[] values, final Type[] types) { for ( int i = 0; i < types.length; i++ ) { values[i] = nullifyTransientReferences( values[i], types[i] ); } @@ -92,8 +91,7 @@ public final class ForeignKeys { * * @return {@code null} if the argument is an unsaved entity; otherwise return the argument. */ - private Object nullifyTransientReferences(final Object value, final Type type) - throws HibernateException { + private Object nullifyTransientReferences(final Object value, final Type type) { if ( value == null ) { return null; } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/BlobProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/BlobProxy.java index 92787ba459..fa1c554ac3 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/BlobProxy.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/BlobProxy.java @@ -112,7 +112,7 @@ public class BlobProxy implements InvocationHandler { return getStream(); } else if ( argCount == 2 ) { - long start = (Long) args[0]; + final long start = (Long) args[0]; if ( start < 1 ) { throw new SQLException( "Start position 1-based; must be 1 or more." ); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java index addfd6210f..d162fbb2a6 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/ResultSetWrapperProxy.java @@ -127,7 +127,7 @@ public class ResultSetWrapperProxy implements InvocationHandler { return columnNameCache.getIndexForColumnName( columnName, rs ); } - private boolean isFirstArgColumnLabel(Method method, Object args[]) { + private boolean isFirstArgColumnLabel(Method method, Object[] args) { // method name should start with either get or update if ( ! ( method.getName().startsWith( "get" ) || method.getName().startsWith( "update" ) ) ) { return false; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java index 1a9ecee23b..32e085832c 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BasicBatchKey.java @@ -39,8 +39,8 @@ public class BasicBatchKey implements BatchKey { /** * Constructs a BasicBatchKey * - * @param comparison - * @param expectation + * @param comparison A string used to compare batch keys. + * @param expectation The expectation for the batch */ public BasicBatchKey(String comparison, Expectation expectation) { this.comparison = comparison; @@ -68,12 +68,7 @@ public class BasicBatchKey implements BatchKey { } final BasicBatchKey that = (BasicBatchKey) o; - - if ( !comparison.equals( that.comparison ) ) { - return false; - } - - return true; + return comparison.equals( that.comparison ); } @Override diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java index ab77258d63..1c46bb292d 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/batch/internal/BatchBuilderImpl.java @@ -57,6 +57,8 @@ public class BatchBuilderImpl implements BatchBuilder, Configurable { /** * Constructs a BatchBuilderImpl + * + * @param size The batch size to use. */ public BatchBuilderImpl(int size) { this.size = size; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java index 9985b19ee6..b458dd2ce3 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/connections/internal/ConnectionProviderInitiator.java @@ -202,7 +202,7 @@ public class ConnectionProviderInitiator implements StandardServiceInitiator { + /** + * Singleton access + */ public static final RefCursorSupportInitiator INSTANCE = new RefCursorSupportInitiator(); @Override diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/StandardRefCursorSupport.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/StandardRefCursorSupport.java index 3e83be53c0..c1c98ac215 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/StandardRefCursorSupport.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/StandardRefCursorSupport.java @@ -39,6 +39,8 @@ import org.hibernate.engine.jdbc.cursor.spi.RefCursorSupport; import org.hibernate.service.spi.InjectService; /** + * Standard implementation of RefCursorSupport + * * @author Steve Ebersole */ public class StandardRefCursorSupport implements RefCursorSupport { @@ -46,6 +48,11 @@ public class StandardRefCursorSupport implements RefCursorSupport { private JdbcServices jdbcServices; + /** + * Hook for service registry to be able to inject JdbcServices + * + * @param jdbcServices The JdbcServices service + */ @InjectService @SuppressWarnings("UnusedDeclaration") public void injectJdbcServices(JdbcServices jdbcServices) { @@ -160,6 +167,13 @@ public class StandardRefCursorSupport implements RefCursorSupport { } } + /** + * Does this JDBC metadata indicate that the driver defines REF_CURSOR support? + * + * @param meta The JDBC metadata + * + * @return {@code true} if the metadata indicates that the driver defines REF_CURSOR support + */ @SuppressWarnings("UnnecessaryUnboxing") public static boolean supportsRefCursors(DatabaseMetaData meta) { // Standard JDBC REF_CURSOR support was not added until Java 8, so we need to use reflection to attempt to diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/package-info.java new file mode 100644 index 0000000000..211dbd1302 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/internal/package-info.java @@ -0,0 +1,4 @@ +/** + * Internals for JDBC REF_CURSOR support. + */ +package org.hibernate.engine.jdbc.cursor.internal; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/RefCursorSupport.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/RefCursorSupport.java index 7785f0954f..ad7263e752 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/RefCursorSupport.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/RefCursorSupport.java @@ -29,6 +29,8 @@ import java.sql.ResultSet; import org.hibernate.service.Service; /** + * Contract for JDBC REF_CURSOR support. + * * @author Steve Ebersole */ public interface RefCursorSupport extends Service { diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/package-info.java new file mode 100644 index 0000000000..6f9a0e635c --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/cursor/spi/package-info.java @@ -0,0 +1,4 @@ +/** + * Defines contracts for JDBC REF_CURSOR support. + */ +package org.hibernate.engine.jdbc.cursor.spi; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/BasicDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/BasicDialectResolver.java index fb617d72c2..b96c41ee28 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/BasicDialectResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/BasicDialectResolver.java @@ -40,22 +40,39 @@ import org.hibernate.engine.jdbc.dialect.spi.AbstractDatabaseMetaDataDialectReso */ @Deprecated public class BasicDialectResolver extends AbstractDatabaseMetaDataDialectResolver { + /** + * Constant indicating no version info was given + */ public static final int VERSION_INSENSITIVE_VERSION = -9999; private final String matchingName; private final int matchingVersion; private final Class dialectClass; + /** + * Constructs a BasicDialectResolver + * + * @param matchingName The name of the driver to match on + * @param dialectClass The Dialect class to use on match + */ public BasicDialectResolver(String matchingName, Class dialectClass) { this( matchingName, VERSION_INSENSITIVE_VERSION, dialectClass ); } + /** + * Constructs a BasicDialectResolver + * + * @param matchingName The name of the driver to match on + * @param matchingVersion The version of the driver to match on + * @param dialectClass The Dialect class to use on match + */ public BasicDialectResolver(String matchingName, int matchingVersion, Class dialectClass) { this.matchingName = matchingName; this.matchingVersion = matchingVersion; this.dialectClass = dialectClass; } + @Override protected final Dialect resolveDialectInternal(DatabaseMetaData metaData) throws SQLException { final String databaseName = metaData.getDatabaseProductName(); final int databaseMajorVersion = metaData.getDatabaseMajorVersion(); @@ -63,7 +80,7 @@ public class BasicDialectResolver extends AbstractDatabaseMetaDataDialectResolve if ( matchingName.equalsIgnoreCase( databaseName ) && ( matchingVersion == VERSION_INSENSITIVE_VERSION || matchingVersion == databaseMajorVersion ) ) { try { - return ( Dialect ) dialectClass.newInstance(); + return (Dialect) dialectClass.newInstance(); } catch ( HibernateException e ) { // conceivable that the dialect ctor could throw HibernateExceptions, so don't re-wrap diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverInitiator.java index 9ad43d9ca2..3fb14158d0 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverInitiator.java @@ -35,9 +35,14 @@ import org.hibernate.service.spi.ServiceException; import org.hibernate.service.spi.ServiceRegistryImplementor; /** + * Initiator for the DatabaseInfoDialectResolver service + * * @author Steve Ebersole */ public class DatabaseInfoDialectResolverInitiator implements StandardServiceInitiator { + /** + * Singleton access + */ public static final DatabaseInfoDialectResolverInitiator INSTANCE = new DatabaseInfoDialectResolverInitiator(); @Override diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverSet.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverSet.java index d3816ccd69..d9149a9195 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverSet.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DatabaseInfoDialectResolverSet.java @@ -31,19 +31,36 @@ import org.hibernate.dialect.Dialect; import org.hibernate.engine.jdbc.dialect.spi.DatabaseInfoDialectResolver; /** + * Implements the DatabaseInfoDialectResolver as a chain, allowing multiple delegate DatabaseInfoDialectResolver + * implementations to coordinate resolution + * * @author Steve Ebersole */ public class DatabaseInfoDialectResolverSet implements DatabaseInfoDialectResolver { private List delegateResolvers; + /** + * Constructs a DatabaseInfoDialectResolverSet + */ public DatabaseInfoDialectResolverSet() { this( new ArrayList() ); } + /** + * Constructs a DatabaseInfoDialectResolverSet + * + * @param delegateResolvers The set of delegate resolvers + */ public DatabaseInfoDialectResolverSet(List delegateResolvers) { this.delegateResolvers = delegateResolvers; } + /** + * Constructs a DatabaseInfoDialectResolverSet + * + * @param delegateResolvers The set of delegate resolvers + */ + @SuppressWarnings("UnusedDeclaration") public DatabaseInfoDialectResolverSet(DatabaseInfoDialectResolver... delegateResolvers) { this( Arrays.asList( delegateResolvers ) ); } @@ -51,7 +68,7 @@ public class DatabaseInfoDialectResolverSet implements DatabaseInfoDialectResolv @Override public Dialect resolve(DatabaseInfo databaseInfo) { for ( DatabaseInfoDialectResolver resolver : delegateResolvers ) { - Dialect dialect = resolver.resolve( databaseInfo ); + final Dialect dialect = resolver.resolve( databaseInfo ); if ( dialect != null ) { return dialect; } @@ -75,6 +92,7 @@ public class DatabaseInfoDialectResolverSet implements DatabaseInfoDialectResolv * * @param resolver The resolver to add. */ + @SuppressWarnings("UnusedDeclaration") public void addResolverAtFirst(DatabaseInfoDialectResolver resolver) { delegateResolvers.add( 0, resolver ); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectFactoryInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectFactoryInitiator.java index a207465656..26e67f3bfa 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectFactoryInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectFactoryInitiator.java @@ -35,6 +35,9 @@ import org.hibernate.service.spi.ServiceRegistryImplementor; * @author Steve Ebersole */ public class DialectFactoryInitiator implements StandardServiceInitiator { + /** + * Singleton access + */ public static final DialectFactoryInitiator INSTANCE = new DialectFactoryInitiator(); @Override diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectResolverSet.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectResolverSet.java index ed11ab2c5d..2ae9d3ad12 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectResolverSet.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/DialectResolverSet.java @@ -40,29 +40,51 @@ import org.hibernate.engine.jdbc.dialect.spi.DialectResolver; * * @author Tomoto Shimizu Washio * @author Steve Ebersole + * + * @deprecated See deprecation on {@link DialectResolver} */ +@Deprecated public class DialectResolverSet implements DialectResolver { - - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, DialectResolverSet.class.getName()); + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + DialectResolverSet.class.getName() + ); private List resolvers; + /** + * Deprecated + */ public DialectResolverSet() { this( new ArrayList() ); + LOG.debug( "DialectResolverSet is deprecated" ); } + /** + * Deprecated + * + * @param resolvers The delegate resolvers + */ public DialectResolverSet(List resolvers) { this.resolvers = resolvers; + LOG.debug( "DialectResolverSet is deprecated" ); } + /** + * Deprecated + * + * @param resolvers The delegate resolvers + */ public DialectResolverSet(DialectResolver... resolvers) { this( Arrays.asList( resolvers ) ); + LOG.debug( "DialectResolverSet is deprecated" ); } + @Override public Dialect resolveDialect(DatabaseMetaData metaData) throws JDBCConnectionException { for ( DialectResolver resolver : resolvers ) { try { - Dialect dialect = resolver.resolveDialect( metaData ); + final Dialect dialect = resolver.resolveDialect( metaData ); if ( dialect != null ) { return dialect; } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseInfoDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseInfoDialectResolver.java index 814c1dd4b1..6b70e520b3 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseInfoDialectResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseInfoDialectResolver.java @@ -54,9 +54,14 @@ import org.hibernate.engine.jdbc.dialect.spi.DatabaseInfoDialectResolver; import org.hibernate.internal.CoreMessageLogger; /** + * The standard DatabaseInfoDialectResolver implementation + * * @author Steve Ebersole */ public class StandardDatabaseInfoDialectResolver implements DatabaseInfoDialectResolver { + /** + * Singleton access + */ public static final StandardDatabaseInfoDialectResolver INSTANCE = new StandardDatabaseInfoDialectResolver(); private static final CoreMessageLogger LOG = Logger.getMessageLogger( @@ -159,7 +164,7 @@ public class StandardDatabaseInfoDialectResolver implements DatabaseInfoDialectR return new InformixDialect(); } - if ( databaseName.equals("DB2 UDB for AS/400" ) ) { + if ( "DB2 UDB for AS/400".equals( databaseName ) ) { return new DB2400Dialect(); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseMetaDataDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseMetaDataDialectResolver.java index c54bfd8ef7..ca2406fe07 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseMetaDataDialectResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/StandardDatabaseMetaDataDialectResolver.java @@ -39,14 +39,22 @@ import org.hibernate.engine.jdbc.dialect.spi.DatabaseInfoDialectResolver; public class StandardDatabaseMetaDataDialectResolver extends AbstractDatabaseMetaDataDialectResolver { private final DatabaseInfoDialectResolver infoResolver; + /** + * Constructs a StandardDatabaseMetaDataDialectResolver + * + * @param infoResolver The delegate resolver + */ public StandardDatabaseMetaDataDialectResolver(DatabaseInfoDialectResolver infoResolver) { this.infoResolver = infoResolver; } + /** + * A DatabaseInfo implementation wrapping a JDBC DatabaseMetaData reference + */ public static final class DatabaseInfoImpl implements DatabaseInfoDialectResolver.DatabaseInfo { private final DatabaseMetaData databaseMetaData; - public DatabaseInfoImpl(DatabaseMetaData databaseMetaData) { + protected DatabaseInfoImpl(DatabaseMetaData databaseMetaData) { this.databaseMetaData = databaseMetaData; } @@ -82,7 +90,7 @@ public class StandardDatabaseMetaDataDialectResolver extends AbstractDatabaseMet } @Override - protected Dialect resolveDialectInternal(DatabaseMetaData metaData) throws SQLException { + protected Dialect resolveDialectInternal(DatabaseMetaData metaData) throws SQLException { if ( infoResolver == null ) { return null; } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/package-info.java new file mode 100644 index 0000000000..dc8bdcc5d5 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/internal/package-info.java @@ -0,0 +1,4 @@ +/** + * Internal support for Dialect resolution (from JDBC metadata) and Dialect building. + */ +package org.hibernate.engine.jdbc.dialect.internal; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/AbstractDatabaseMetaDataDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/AbstractDatabaseMetaDataDialectResolver.java index 65785c5cde..5226dfe8dd 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/AbstractDatabaseMetaDataDialectResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/AbstractDatabaseMetaDataDialectResolver.java @@ -40,8 +40,7 @@ import org.hibernate.internal.CoreMessageLogger; * @author Steve Ebersole */ public abstract class AbstractDatabaseMetaDataDialectResolver implements DialectResolver { - - private static final CoreMessageLogger LOG = Logger.getMessageLogger( + private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, AbstractDatabaseMetaDataDialectResolver.class.getName() ); @@ -52,21 +51,22 @@ public abstract class AbstractDatabaseMetaDataDialectResolver implements Dialect * Here we template the resolution, delegating to {@link #resolveDialectInternal} and handling * {@link java.sql.SQLException}s properly. */ + @Override public final Dialect resolveDialect(DatabaseMetaData metaData) { try { return resolveDialectInternal( metaData ); } catch ( SQLException sqlException ) { - JDBCException jdbcException = BasicSQLExceptionConverter.INSTANCE.convert( sqlException ); - if (jdbcException instanceof JDBCConnectionException) { + final JDBCException jdbcException = BasicSQLExceptionConverter.INSTANCE.convert( sqlException ); + if (jdbcException instanceof JDBCConnectionException) { throw jdbcException; } - LOG.warnf( "%s : %s", BasicSQLExceptionConverter.MSG, sqlException.getMessage() ); - return null; + LOG.warnf( "%s : %s", BasicSQLExceptionConverter.MSG, sqlException.getMessage() ); + return null; } catch ( Throwable t ) { - LOG.unableToExecuteResolver( this, t.getMessage() ); + LOG.unableToExecuteResolver( this, t.getMessage() ); return null; } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/BasicSQLExceptionConverter.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/BasicSQLExceptionConverter.java index b0a4bc5ebe..ea554a052d 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/BasicSQLExceptionConverter.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/BasicSQLExceptionConverter.java @@ -50,7 +50,7 @@ public class BasicSQLExceptionConverter { public static final BasicSQLExceptionConverter INSTANCE = new BasicSQLExceptionConverter(); /** - * + * Message */ public static final String MSG = LOG.unableToQueryDatabaseMetadata(); @@ -70,6 +70,7 @@ public class BasicSQLExceptionConverter { /** * {@inheritDoc} */ + @Override public String extractConstraintName(SQLException sqle) { return "???"; } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DatabaseInfoDialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DatabaseInfoDialectResolver.java index 9eccc26347..a532e35389 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DatabaseInfoDialectResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DatabaseInfoDialectResolver.java @@ -42,7 +42,13 @@ public interface DatabaseInfoDialectResolver extends Service { */ public Dialect resolve(DatabaseInfo databaseInfo); + /** + * Essentially a "parameter object" for {@link DatabaseInfoDialectResolver#resolve} + */ public static interface DatabaseInfo { + /** + * Constant used to indicate that no version is defined + */ public static final int NO_VERSION = -9999; /** diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DialectResolver.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DialectResolver.java index 4cec52fa7b..0fca0dfcc6 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DialectResolver.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/DialectResolver.java @@ -24,8 +24,13 @@ package org.hibernate.engine.jdbc.dialect.spi; /** + * Deprecated + * * @deprecated Deprecated in favor of {@link DatabaseMetaDataDialectResolver} to account for resolving by name versus * by DatabaseMetaData + * + * @see DatabaseMetaDataDialectResolver + * @see DatabaseInfoDialectResolver */ @Deprecated public interface DialectResolver extends DatabaseMetaDataDialectResolver { diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/package-info.java new file mode 100644 index 0000000000..53a64d46e9 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/dialect/spi/package-info.java @@ -0,0 +1,4 @@ +/** + * Contracts supporting Dialect resolution (from JDBC metadata) and Dialect building. + */ +package org.hibernate.engine.jdbc.dialect.spi; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BasicFormatterImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BasicFormatterImpl.java index 0b2babef47..f0fd816b7b 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BasicFormatterImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BasicFormatterImpl.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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.engine.jdbc.internal; @@ -84,23 +83,24 @@ public class BasicFormatterImpl implements Formatter { MISC.add( "on" ); } - static final String indentString = " "; - static final String initial = "\n "; + private static final String INDENT_STRING = " "; + private static final String INITIAL = "\n "; + @Override public String format(String source) { return new FormatProcess( source ).perform(); } private static class FormatProcess { boolean beginLine = true; - boolean afterBeginBeforeEnd = false; - boolean afterByOrSetOrFromOrSelect = false; - boolean afterValues = false; - boolean afterOn = false; - boolean afterBetween = false; - boolean afterInsert = false; - int inFunction = 0; - int parensSinceSelect = 0; + boolean afterBeginBeforeEnd; + boolean afterByOrSetOrFromOrSelect; + boolean afterValues; + boolean afterOn; + boolean afterBetween; + boolean afterInsert; + int inFunction; + int parensSinceSelect; private LinkedList parenCounts = new LinkedList(); private LinkedList afterByOrFromOrSelects = new LinkedList(); @@ -122,7 +122,7 @@ public class BasicFormatterImpl implements Formatter { public String perform() { - result.append( initial ); + result.append( INITIAL ); while ( tokens.hasMoreTokens() ) { token = tokens.nextToken(); @@ -134,7 +134,8 @@ public class BasicFormatterImpl implements Formatter { t = tokens.nextToken(); token += t; } - while ( !"'".equals( t ) && tokens.hasMoreTokens() ); // cannot handle single quotes + // cannot handle single quotes + while ( !"'".equals( t ) && tokens.hasMoreTokens() ); } else if ( "\"".equals( token ) ) { String t; @@ -384,16 +385,16 @@ public class BasicFormatterImpl implements Formatter { } private static boolean isWhitespace(String token) { - return StringHelper.WHITESPACE.indexOf( token ) >= 0; + return StringHelper.WHITESPACE.contains( token ); } private void newline() { result.append( "\n" ); for ( int i = 0; i < indent; i++ ) { - result.append( indentString ); + result.append( INDENT_STRING ); } beginLine = true; } } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BinaryStreamImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BinaryStreamImpl.java index b687105af4..be56516c4a 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BinaryStreamImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/BinaryStreamImpl.java @@ -37,6 +37,11 @@ import org.hibernate.engine.jdbc.BinaryStream; public class BinaryStreamImpl extends ByteArrayInputStream implements BinaryStream { private final int length; + /** + * Constructs a BinaryStreamImpl + * + * @param bytes The bytes to use backing the stream + */ public BinaryStreamImpl(byte[] bytes) { super( bytes ); this.length = bytes.length; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/CharacterStreamImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/CharacterStreamImpl.java index d61e07a4c5..ea13df4e82 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/CharacterStreamImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/CharacterStreamImpl.java @@ -24,7 +24,6 @@ package org.hibernate.engine.jdbc.internal; import java.io.IOException; -import java.io.InputStream; import java.io.Reader; import java.io.StringReader; @@ -42,11 +41,22 @@ public class CharacterStreamImpl implements CharacterStream { private Reader reader; private String string; + /** + * Constructs a CharacterStreamImpl + * + * @param chars The String of characters to use backing the CharacterStream + */ public CharacterStreamImpl(String chars) { this.string = chars; this.length = chars.length(); } + /** + * Constructs a CharacterStreamImpl + * + * @param reader The Reader containing the characters to use backing the CharacterStream + * @param length The length of the stream + */ public CharacterStreamImpl(Reader reader, long length) { this.reader = reader; this.length = length; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/DDLFormatterImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/DDLFormatterImpl.java index 538bbc4a16..4a923559d9 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/DDLFormatterImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/DDLFormatterImpl.java @@ -34,20 +34,16 @@ import org.hibernate.internal.util.StringHelper; * @author Steve Ebersole */ public class DDLFormatterImpl implements Formatter { + /** + * Singleton access + */ public static final DDLFormatterImpl INSTANCE = new DDLFormatterImpl(); - /** - * Format an SQL statement using simple rules

        - *
      • Insert newline after each comma
      • - *
      • Indent three spaces after each inserted newline
      • - *
      - * If the statement contains single/double quotes return unchanged, - * it is too complex and could be broken by simple formatting. - * - * @param sql The statement to be fornmatted. - */ + @Override public String format(String sql) { - if ( StringHelper.isEmpty( sql ) ) return sql; + if ( StringHelper.isEmpty( sql ) ) { + return sql; + } if ( sql.toLowerCase().startsWith( "create table" ) ) { return formatCreateTable( sql ); } @@ -63,12 +59,12 @@ public class DDLFormatterImpl implements Formatter { } private String formatCommentOn(String sql) { - StringBuilder result = new StringBuilder( 60 ).append( "\n " ); - StringTokenizer tokens = new StringTokenizer( sql, " '[]\"", true ); + final StringBuilder result = new StringBuilder( 60 ).append( "\n " ); + final StringTokenizer tokens = new StringTokenizer( sql, " '[]\"", true ); boolean quoted = false; while ( tokens.hasMoreTokens() ) { - String token = tokens.nextToken(); + final String token = tokens.nextToken(); result.append( token ); if ( isQuote( token ) ) { quoted = !quoted; @@ -84,12 +80,12 @@ public class DDLFormatterImpl implements Formatter { } private String formatAlterTable(String sql) { - StringBuilder result = new StringBuilder( 60 ).append( "\n " ); - StringTokenizer tokens = new StringTokenizer( sql, " (,)'[]\"", true ); + final StringBuilder result = new StringBuilder( 60 ).append( "\n " ); + final StringTokenizer tokens = new StringTokenizer( sql, " (,)'[]\"", true ); boolean quoted = false; while ( tokens.hasMoreTokens() ) { - String token = tokens.nextToken(); + final String token = tokens.nextToken(); if ( isQuote( token ) ) { quoted = !quoted; } @@ -105,13 +101,13 @@ public class DDLFormatterImpl implements Formatter { } private String formatCreateTable(String sql) { - StringBuilder result = new StringBuilder( 60 ).append( "\n " ); - StringTokenizer tokens = new StringTokenizer( sql, "(,)'[]\"", true ); + final StringBuilder result = new StringBuilder( 60 ).append( "\n " ); + final StringTokenizer tokens = new StringTokenizer( sql, "(,)'[]\"", true ); int depth = 0; boolean quoted = false; while ( tokens.hasMoreTokens() ) { - String token = tokens.nextToken(); + final String token = tokens.nextToken(); if ( isQuote( token ) ) { quoted = !quoted; result.append( token ); @@ -158,4 +154,4 @@ public class DDLFormatterImpl implements Formatter { "'".equals( tok ); } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/FormatStyle.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/FormatStyle.java index 80a3e12f01..b077ede88b 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/FormatStyle.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/FormatStyle.java @@ -23,16 +23,24 @@ */ package org.hibernate.engine.jdbc.internal; - /** * Represents the the understood types or styles of formatting. * * @author Steve Ebersole */ public enum FormatStyle { + /** + * Formatting for SELECT, INSERT, UPDATE and DELETE statements + */ BASIC( "basic", new BasicFormatterImpl() ), - DDL( "ddl", new DDLFormatterImpl() ), - NONE( "none", new NoFormatImpl() ); + /** + * Formatting for DDL (CREATE, ALTER, DROP, etc) statements + */ + DDL( "ddl", DDLFormatterImpl.INSTANCE ), + /** + * No formatting + */ + NONE( "none", NoFormatImpl.INSTANCE ); private final String name; private final Formatter formatter; @@ -51,6 +59,11 @@ public enum FormatStyle { } private static class NoFormatImpl implements Formatter { + /** + * Singleton access + */ + public static final NoFormatImpl INSTANCE = new NoFormatImpl(); + public String format(String source) { return source; } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java index 04265dff1f..1b2d710344 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java @@ -68,8 +68,9 @@ import org.jboss.logging.Logger.Level; * @author Brett Meyer */ public class JdbcCoordinatorImpl implements JdbcCoordinator { - private static final CoreMessageLogger LOG = Logger.getMessageLogger( - CoreMessageLogger.class, JdbcCoordinatorImpl.class.getName() + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + JdbcCoordinatorImpl.class.getName() ); private transient TransactionCoordinator transactionCoordinator; @@ -90,6 +91,12 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator { */ private boolean releasesEnabled = true; + /** + * Constructs a JdbcCoordinatorImpl + * + * @param userSuppliedConnection The user supplied connection (may be null) + * @param transactionCoordinator The transaction coordinator + */ public JdbcCoordinatorImpl( Connection userSuppliedConnection, TransactionCoordinator transactionCoordinator) { @@ -103,6 +110,12 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator { this.exceptionHelper = logicalConnection.getJdbcServices().getSqlExceptionHelper(); } + /** + * Constructs a JdbcCoordinatorImpl + * + * @param logicalConnection The logical JDBC connection + * @param transactionCoordinator The transaction coordinator + */ public JdbcCoordinatorImpl( LogicalConnectionImpl logicalConnection, TransactionCoordinator transactionCoordinator) { @@ -138,12 +151,17 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator { return sessionFactory().getServiceRegistry().getService( BatchBuilder.class ); } + /** + * Access to the SqlExceptionHelper + * + * @return The SqlExceptionHelper + */ public SqlExceptionHelper sqlExceptionHelper() { return transactionEnvironment().getJdbcServices().getSqlExceptionHelper(); } - private int flushDepth = 0; + private int flushDepth; @Override public void flushBeginning() { @@ -196,7 +214,8 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator { public void executeBatch() { if ( currentBatch != null ) { currentBatch.execute(); - currentBatch.release(); // needed? + // needed? + currentBatch.release(); } } @@ -279,9 +298,9 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator { @Override public T coordinateWork(WorkExecutorVisitable work) { - Connection connection = getLogicalConnection().getConnection(); + final Connection connection = getLogicalConnection().getConnection(); try { - T result = work.accept( new WorkExecutor(), connection ); + final T result = work.accept( new WorkExecutor(), connection ); afterStatementExecution(); return result; } @@ -297,6 +316,13 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator { : ! hasRegisteredResources(); } + /** + * JDK serialization hook + * + * @param oos The stream into which to write our state + * + * @throws IOException Trouble accessing the stream + */ public void serialize(ObjectOutputStream oos) throws IOException { if ( ! isReadyForSerialization() ) { throw new HibernateException( "Cannot serialize Session while connected" ); @@ -304,12 +330,28 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator { logicalConnection.serialize( oos ); } + /** + * JDK deserialization hook + * + * @param ois The stream into which to write our state + * @param transactionContext The transaction context which owns the JdbcCoordinatorImpl to be deserialized. + * + * @return The deserialized JdbcCoordinatorImpl + * + * @throws IOException Trouble accessing the stream + * @throws ClassNotFoundException Trouble reading the stream + */ public static JdbcCoordinatorImpl deserialize( ObjectInputStream ois, TransactionContext transactionContext) throws IOException, ClassNotFoundException { return new JdbcCoordinatorImpl( LogicalConnectionImpl.deserialize( ois, transactionContext ) ); - } + } + /** + * Callback after deserialization from Session is done + * + * @param transactionCoordinator The transaction coordinator + */ public void afterDeserialize(TransactionCoordinatorImpl transactionCoordinator) { this.transactionCoordinator = transactionCoordinator; } @@ -328,7 +370,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator { public void registerLastQuery(Statement statement) { LOG.tracev( "Registering last query statement [{0}]", statement ); if ( statement instanceof JdbcWrapper ) { - JdbcWrapper wrapper = ( JdbcWrapper ) statement; + final JdbcWrapper wrapper = (JdbcWrapper) statement; registerLastQuery( wrapper.getWrappedObject() ); return; } @@ -343,10 +385,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator { } } catch (SQLException sqle) { - throw exceptionHelper.convert( - sqle, - "Cannot cancel query" - ); + throw exceptionHelper.convert( sqle, "Cannot cancel query" ); } finally { lastQuery = null; @@ -356,7 +395,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator { @Override public void release(Statement statement) { LOG.tracev( "Releasing statement [{0}]", statement ); - Set resultSets = xref.get( statement ); + final Set resultSets = xref.get( statement ); if ( resultSets != null ) { for ( ResultSet resultSet : resultSets ) { close( resultSet ); @@ -411,7 +450,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator { if ( LOG.isEnabled( Level.WARN ) && !xref.containsKey( statement ) ) { LOG.unregisteredStatement(); } - Set resultSets = xref.get( statement ); + final Set resultSets = xref.get( statement ); if ( resultSets != null ) { resultSets.remove( resultSet ); if ( resultSets.isEmpty() ) { @@ -420,7 +459,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator { } } else { - boolean removed = unassociatedResultSets.remove( resultSet ); + final boolean removed = unassociatedResultSets.remove( resultSet ); if ( !removed ) { LOG.unregisteredResultSetWithoutStatement(); } @@ -473,7 +512,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator { LOG.tracev( "Closing prepared statement [{0}]", statement ); if ( statement instanceof InvalidatableWrapper ) { - InvalidatableWrapper wrapper = ( InvalidatableWrapper ) statement; + final InvalidatableWrapper wrapper = (InvalidatableWrapper) statement; close( wrapper.getWrappedObject() ); wrapper.invalidate(); return; @@ -495,7 +534,8 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator { if ( LOG.isDebugEnabled() ) { LOG.debugf( "Exception clearing maxRows/queryTimeout [%s]", sqle.getMessage() ); } - return; // EARLY EXIT!!! + // EARLY EXIT!!! + return; } statement.close(); if ( lastQuery == statement ) { @@ -516,7 +556,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator { LOG.tracev( "Closing result set [{0}]", resultSet ); if ( resultSet instanceof InvalidatableWrapper ) { - InvalidatableWrapper wrapper = (InvalidatableWrapper) resultSet; + final InvalidatableWrapper wrapper = (InvalidatableWrapper) resultSet; close( wrapper.getWrappedObject() ); wrapper.invalidate(); return; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesImpl.java index 3ded537eb0..5fc2418861 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesImpl.java @@ -69,7 +69,10 @@ import org.hibernate.service.spi.ServiceRegistryImplementor; * @author Steve Ebersole */ public class JdbcServicesImpl implements JdbcServices, ServiceRegistryAwareService, Configurable { - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, JdbcServicesImpl.class.getName()); + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + JdbcServicesImpl.class.getName() + ); private ServiceRegistryImplementor serviceRegistry; @@ -105,7 +108,7 @@ public class JdbcServicesImpl implements JdbcServices, ServiceRegistryAwareServi boolean lobLocatorUpdateCopy = false; String catalogName = null; String schemaName = null; - LinkedHashSet typeInfoSet = new LinkedHashSet(); + final LinkedHashSet typeInfoSet = new LinkedHashSet(); // 'hibernate.temp.use_jdbc_metadata_defaults' is a temporary magic value. // The need for it is intended to be alleviated with future development, thus it is @@ -114,10 +117,10 @@ public class JdbcServicesImpl implements JdbcServices, ServiceRegistryAwareServi // it is used to control whether we should consult the JDBC metadata to determine // certain Settings default values; it is useful to *not* do this when the database // may not be available (mainly in tools usage). - boolean useJdbcMetadata = ConfigurationHelper.getBoolean( "hibernate.temp.use_jdbc_metadata_defaults", configValues, true ); + final boolean useJdbcMetadata = ConfigurationHelper.getBoolean( "hibernate.temp.use_jdbc_metadata_defaults", configValues, true ); if ( useJdbcMetadata ) { try { - Connection connection = jdbcConnectionAccess.obtainConnection(); + final Connection connection = jdbcConnectionAccess.obtainConnection(); try { DatabaseMetaData meta = connection.getMetaData(); if(LOG.isDebugEnabled()) { @@ -151,7 +154,7 @@ public class JdbcServicesImpl implements JdbcServices, ServiceRegistryAwareServi dialect = dialectFactory.buildDialect( configValues, connection ); catalogName = connection.getCatalog(); - SchemaNameResolver schemaNameResolver = determineExplicitSchemaNameResolver( configValues ); + final SchemaNameResolver schemaNameResolver = determineExplicitSchemaNameResolver( configValues ); if ( schemaNameResolver == null ) { // todo : add dialect method // schemaNameResolver = dialect.getSchemaNameResolver(); @@ -284,19 +287,23 @@ public class JdbcServicesImpl implements JdbcServices, ServiceRegistryAwareServi } - // todo : add to Environment + /** + * A constant naming the setting used to identify the {@link SchemaNameResolver} to use + *

      + * TODO : add to Environment + */ public static final String SCHEMA_NAME_RESOLVER = "hibernate.schema_name_resolver"; private SchemaNameResolver determineExplicitSchemaNameResolver(Map configValues) { - Object setting = configValues.get( SCHEMA_NAME_RESOLVER ); + final Object setting = configValues.get( SCHEMA_NAME_RESOLVER ); if ( SchemaNameResolver.class.isInstance( setting ) ) { return (SchemaNameResolver) setting; } - String resolverClassName = (String) setting; + final String resolverClassName = (String) setting; if ( resolverClassName != null ) { try { - Class resolverClass = ReflectHelper.classForName( resolverClassName, getClass() ); + final Class resolverClass = ReflectHelper.classForName( resolverClassName, getClass() ); return (SchemaNameResolver) ReflectHelper.getDefaultConstructor( resolverClass ).newInstance(); } catch ( ClassNotFoundException e ) { @@ -313,7 +320,7 @@ public class JdbcServicesImpl implements JdbcServices, ServiceRegistryAwareServi } private Set parseKeywords(String extraKeywordsString) { - Set keywordSet = new HashSet(); + final Set keywordSet = new HashSet(); keywordSet.addAll( Arrays.asList( extraKeywordsString.split( "," ) ) ); return keywordSet; } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesInitiator.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesInitiator.java index a1704b075a..e415763bca 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcServicesInitiator.java @@ -32,11 +32,14 @@ import org.hibernate.service.spi.ServiceRegistryImplementor; /** * Standard initiator for the standard {@link JdbcServices} service * - * @todo : should this maybe be a SessionFactory service? + * TODO : should this maybe be a SessionFactory service? * * @author Steve Ebersole */ public class JdbcServicesInitiator implements StandardServiceInitiator { + /** + * Singleton access + */ public static final JdbcServicesInitiator INSTANCE = new JdbcServicesInitiator(); @Override diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LobCreatorBuilder.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LobCreatorBuilder.java index 6cf56a08cb..b25b60cee0 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LobCreatorBuilder.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LobCreatorBuilder.java @@ -45,15 +45,17 @@ import org.hibernate.internal.util.config.ConfigurationHelper; * @author Steve Ebersole */ public class LobCreatorBuilder { + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + LobCreatorBuilder.class.getName() + ); - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, LobCreatorBuilder.class.getName()); - - private boolean useContextualLobCreation; + private boolean useContextualLobCreation; /** * The public factory method for obtaining the appropriate (according to given JDBC {@link java.sql.Connection}. * - * + * @param configValues The map of settings * @param jdbcConnection A JDBC {@link java.sql.Connection} which can be used to gauge the drivers level of support, * specifically for creating LOB references. */ @@ -74,8 +76,9 @@ public class LobCreatorBuilder { * * @return True if the connection can be used to create LOBs; false otherwise. */ + @SuppressWarnings("unchecked") private static boolean useContextualLobCreation(Map configValues, Connection jdbcConnection) { - boolean isNonContextualLobCreationRequired = + final boolean isNonContextualLobCreationRequired = ConfigurationHelper.getBoolean( Environment.NON_CONTEXTUAL_LOB_CREATION, configValues ); if ( isNonContextualLobCreationRequired ) { LOG.disablingContextualLOBCreation( Environment.NON_CONTEXTUAL_LOB_CREATION ); @@ -88,7 +91,7 @@ public class LobCreatorBuilder { try { try { - DatabaseMetaData meta = jdbcConnection.getMetaData(); + final DatabaseMetaData meta = jdbcConnection.getMetaData(); // if the jdbc driver version is less than 4, it shouldn't have createClob if ( meta.getJDBCMajorVersion() < 4 ) { LOG.disablingContextualLOBCreationSinceOldJdbcVersion( meta.getJDBCMajorVersion() ); @@ -99,16 +102,16 @@ public class LobCreatorBuilder { // ignore exception and continue } - Class connectionClass = Connection.class; - Method createClobMethod = connectionClass.getMethod( "createClob", NO_ARG_SIG ); + final Class connectionClass = Connection.class; + final Method createClobMethod = connectionClass.getMethod( "createClob", NO_ARG_SIG ); if ( createClobMethod.getDeclaringClass().equals( Connection.class ) ) { // If we get here we are running in a jdk 1.6 (jdbc 4) environment... // Further check to make sure the driver actually implements the LOB creation methods. We // check against createClob() as indicative of all; should we check against all 3 explicitly? try { - Object clob = createClobMethod.invoke( jdbcConnection, NO_ARGS ); + final Object clob = createClobMethod.invoke( jdbcConnection, NO_ARGS ); try { - Method freeMethod = clob.getClass().getMethod( "free", NO_ARG_SIG ); + final Method freeMethod = clob.getClass().getMethod( "free", NO_ARG_SIG ); freeMethod.invoke( clob, NO_ARGS ); } catch ( Throwable ignore ) { @@ -127,6 +130,13 @@ public class LobCreatorBuilder { return false; } + /** + * Build a LobCreator using the given context + * + * @param lobCreationContext The LOB creation context + * + * @return The LobCreator + */ public LobCreator buildLobCreator(LobCreationContext lobCreationContext) { return useContextualLobCreation ? new ContextualLobCreator( lobCreationContext ) diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LogicalConnectionImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LogicalConnectionImpl.java index 7ec86aad5f..d718aeb73b 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LogicalConnectionImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/LogicalConnectionImpl.java @@ -54,8 +54,10 @@ import org.jboss.logging.Logger; * @author Brett Meyer */ public class LogicalConnectionImpl implements LogicalConnectionImplementor { - - private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, LogicalConnectionImpl.class.getName() ); + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + LogicalConnectionImpl.class.getName() + ); private transient Connection physicalConnection; @@ -68,6 +70,14 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { private boolean isClosed; + /** + * Constructs a LogicalConnectionImpl + * + * @param userSuppliedConnection The user-supplied connection + * @param connectionReleaseMode The connection release mode to use + * @param jdbcServices JdbcServices + * @param jdbcConnectionAccess JDBC Connection access + */ public LogicalConnectionImpl( Connection userSuppliedConnection, ConnectionReleaseMode connectionReleaseMode, @@ -84,6 +94,9 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { this.physicalConnection = userSuppliedConnection; } + /** + * Constructs a LogicalConnectionImpl. This for used from deserialization + */ private LogicalConnectionImpl( ConnectionReleaseMode connectionReleaseMode, JdbcServices jdbcServices, @@ -162,7 +175,7 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { @Override public Connection close() { LOG.trace( "Closing logical connection" ); - Connection c = isUserSuppliedConnection ? physicalConnection : null; + final Connection c = isUserSuppliedConnection ? physicalConnection : null; try { if ( !isUserSuppliedConnection && physicalConnection != null ) { releaseConnection(); @@ -255,7 +268,7 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { } private void releaseNonDurableObservers() { - Iterator observers = this.observers.iterator(); + final Iterator observers = this.observers.iterator(); while ( observers.hasNext() ) { if ( NonDurableConnectionObserver.class.isInstance( observers.next() ) ) { observers.remove(); @@ -268,7 +281,7 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { if ( isClosed ) { throw new IllegalStateException( "cannot manually disconnect because logical connection is already closed" ); } - Connection c = physicalConnection; + final Connection c = physicalConnection; releaseConnection(); return c; } @@ -324,10 +337,17 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { } } + /** + * Serialization hook + * + * @param oos The stream to write out state to + * + * @throws IOException Problem accessing stream + */ public void serialize(ObjectOutputStream oos) throws IOException { oos.writeBoolean( isUserSuppliedConnection ); oos.writeBoolean( isClosed ); - List durableConnectionObservers = new ArrayList(); + final List durableConnectionObservers = new ArrayList(); for ( ConnectionObserver observer : observers ) { if ( ! NonDurableConnectionObserver.class.isInstance( observer ) ) { durableConnectionObservers.add( observer ); @@ -339,13 +359,24 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { } } + /** + * Deserialization hook + * + * @param ois The stream to read our state from + * @param transactionContext The transactionContext which owns this logical connection + * + * @return The deserialized LogicalConnectionImpl + * + * @throws IOException Trouble accessing the stream + * @throws ClassNotFoundException Trouble reading the stream + */ public static LogicalConnectionImpl deserialize( ObjectInputStream ois, TransactionContext transactionContext) throws IOException, ClassNotFoundException { - boolean isUserSuppliedConnection = ois.readBoolean(); - boolean isClosed = ois.readBoolean(); - int observerCount = ois.readInt(); - List observers = CollectionHelper.arrayList( observerCount ); + final boolean isUserSuppliedConnection = ois.readBoolean(); + final boolean isClosed = ois.readBoolean(); + final int observerCount = ois.readInt(); + final List observers = CollectionHelper.arrayList( observerCount ); for ( int i = 0; i < observerCount; i++ ) { observers.add( (ConnectionObserver) ois.readObject() ); } @@ -357,5 +388,5 @@ public class LogicalConnectionImpl implements LogicalConnectionImplementor { isClosed, observers ); - } + } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetReturnImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetReturnImpl.java index d51e2fd034..36caece313 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetReturnImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetReturnImpl.java @@ -31,12 +31,18 @@ import org.hibernate.engine.jdbc.spi.ResultSetReturn; import org.hibernate.engine.jdbc.spi.SqlExceptionHelper; /** + * Standard implementation of the ResultSetReturn contract + * * @author Brett Meyer */ public class ResultSetReturnImpl implements ResultSetReturn { - private final JdbcCoordinator jdbcCoordinator; + /** + * Constructs a ResultSetReturnImpl + * + * @param jdbcCoordinator The JdbcCoordinator + */ public ResultSetReturnImpl(JdbcCoordinator jdbcCoordinator) { this.jdbcCoordinator = jdbcCoordinator; } @@ -49,11 +55,11 @@ public class ResultSetReturnImpl implements ResultSetReturn { // this seems needless, Oracle can return an // OracleCallableStatementWrapper that finds its way to this method, // rather than extract(CallableStatement). See HHH-8022. - CallableStatement callableStatement = (CallableStatement) statement; + final CallableStatement callableStatement = (CallableStatement) statement; return extract( callableStatement ); } try { - ResultSet rs = statement.executeQuery(); + final ResultSet rs = statement.executeQuery(); postExtract( rs, statement ); return rs; } @@ -66,8 +72,10 @@ public class ResultSetReturnImpl implements ResultSetReturn { public ResultSet extract(CallableStatement statement) { try { // sql logged by StatementPreparerImpl - ResultSet rs = jdbcCoordinator.getLogicalConnection().getJdbcServices() - .getDialect().getResultSet( statement ); + final ResultSet rs = jdbcCoordinator.getLogicalConnection() + .getJdbcServices() + .getDialect() + .getResultSet( statement ); postExtract( rs, statement ); return rs; } @@ -78,10 +86,9 @@ public class ResultSetReturnImpl implements ResultSetReturn { @Override public ResultSet extract(Statement statement, String sql) { - jdbcCoordinator.getLogicalConnection().getJdbcServices() - .getSqlStatementLogger().logStatement( sql ); + jdbcCoordinator.getLogicalConnection().getJdbcServices().getSqlStatementLogger().logStatement( sql ); try { - ResultSet rs = statement.executeQuery( sql ); + final ResultSet rs = statement.executeQuery( sql ); postExtract( rs, statement ); return rs; } @@ -99,7 +106,7 @@ public class ResultSetReturnImpl implements ResultSetReturn { // do nothing until we hit the resultset } } - ResultSet rs = statement.getResultSet(); + final ResultSet rs = statement.getResultSet(); postExtract( rs, statement ); return rs; } @@ -118,7 +125,7 @@ public class ResultSetReturnImpl implements ResultSetReturn { // do nothing until we hit the resultset } } - ResultSet rs = statement.getResultSet(); + final ResultSet rs = statement.getResultSet(); postExtract( rs, statement ); return rs; } @@ -149,7 +156,7 @@ public class ResultSetReturnImpl implements ResultSetReturn { } } - private final SqlExceptionHelper sqlExceptionHelper() { + private SqlExceptionHelper sqlExceptionHelper() { return jdbcCoordinator.getTransactionCoordinator() .getTransactionContext() .getTransactionEnvironment() @@ -158,7 +165,9 @@ public class ResultSetReturnImpl implements ResultSetReturn { } private void postExtract(ResultSet rs, Statement st) { - if ( rs != null ) jdbcCoordinator.register( rs, st ); + if ( rs != null ) { + jdbcCoordinator.register( rs, st ); + } } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetWrapperImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetWrapperImpl.java index b76819aced..11d7ee3d49 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetWrapperImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetWrapperImpl.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.engine.jdbc.internal; + import java.sql.ResultSet; import org.hibernate.engine.jdbc.ColumnNameCache; @@ -35,15 +36,16 @@ import org.hibernate.engine.jdbc.spi.ResultSetWrapper; * @author Gail Badner */ public class ResultSetWrapperImpl implements ResultSetWrapper { + /** + * Singleton access + */ public static ResultSetWrapper INSTANCE = new ResultSetWrapperImpl(); private ResultSetWrapperImpl() { } - /** - * {@inheritDoc} - */ + @Override public ResultSet wrap(ResultSet resultSet, ColumnNameCache columnNameCache) { return ResultSetWrapperProxy.generateProxy( resultSet, columnNameCache ); } -} \ No newline at end of file +} diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/StatementPreparerImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/StatementPreparerImpl.java index ef579209c4..f7ca3a1340 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/StatementPreparerImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/StatementPreparerImpl.java @@ -37,6 +37,8 @@ import org.hibernate.engine.jdbc.spi.SqlExceptionHelper; import org.hibernate.engine.jdbc.spi.StatementPreparer; /** + * Standard implementation of StatementPreparer + * * @author Steve Ebersole * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) * @author Brett Meyer @@ -44,6 +46,11 @@ import org.hibernate.engine.jdbc.spi.StatementPreparer; class StatementPreparerImpl implements StatementPreparer { private JdbcCoordinatorImpl jdbcCoordinator; + /** + * Construct a StatementPreparerImpl + * + * @param jdbcCoordinator The JdbcCoordinatorImpl + */ StatementPreparerImpl(JdbcCoordinatorImpl jdbcCoordinator) { this.jdbcCoordinator = jdbcCoordinator; } @@ -71,7 +78,7 @@ class StatementPreparerImpl implements StatementPreparer { @Override public Statement createStatement() { try { - Statement statement = connection().createStatement(); + final Statement statement = connection().createStatement(); jdbcCoordinator.register( statement ); return statement; } @@ -141,22 +148,18 @@ class StatementPreparerImpl implements StatementPreparer { if ( ! settings().isScrollableResultSetsEnabled() ) { throw new AssertionFailure("scrollable result sets are not enabled"); } - PreparedStatement ps = new QueryStatementPreparationTemplate( sql ) { + final PreparedStatement ps = new QueryStatementPreparationTemplate( sql ) { public PreparedStatement doPrepare() throws SQLException { return isCallable - ? connection().prepareCall( - sql, scrollMode.toResultSetType(), ResultSet.CONCUR_READ_ONLY - ) - : connection().prepareStatement( - sql, scrollMode.toResultSetType(), ResultSet.CONCUR_READ_ONLY - ); + ? connection().prepareCall( sql, scrollMode.toResultSetType(), ResultSet.CONCUR_READ_ONLY ) + : connection().prepareStatement( sql, scrollMode.toResultSetType(), ResultSet.CONCUR_READ_ONLY ); } }.prepareStatement(); jdbcCoordinator.registerLastQuery( ps ); return ps; } else { - PreparedStatement ps = new QueryStatementPreparationTemplate( sql ) { + final PreparedStatement ps = new QueryStatementPreparationTemplate( sql ) { public PreparedStatement doPrepare() throws SQLException { return isCallable ? connection().prepareCall( sql ) @@ -179,7 +182,7 @@ class StatementPreparerImpl implements StatementPreparer { try { jdbcCoordinator.getLogicalConnection().getJdbcServices().getSqlStatementLogger().logStatement( sql ); - PreparedStatement preparedStatement = doPrepare(); + final PreparedStatement preparedStatement = doPrepare(); setStatementTimeout( preparedStatement ); postProcess( preparedStatement ); return preparedStatement; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/package-info.java new file mode 100644 index 0000000000..a83fec0f71 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/package-info.java @@ -0,0 +1,4 @@ +/** + * Internals for supporting various aspects of JDBC interaction + */ +package org.hibernate.engine.jdbc.internal; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/package-info.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/package-info.java new file mode 100644 index 0000000000..c55e445fdc --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/package-info.java @@ -0,0 +1,4 @@ +/** + * SPI contracts for supporting various aspects of JDBC interaction + */ +package org.hibernate.engine.jdbc.spi; From d2ec51489443672d47690fbaea6ca631335e574f Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Tue, 30 Apr 2013 08:07:24 -0500 Subject: [PATCH 28/57] HHH-8159 - Apply fixups indicated by analysis tools --- build.gradle | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/build.gradle b/build.gradle index dcedcdd7db..8b27b237e1 100644 --- a/build.gradle +++ b/build.gradle @@ -349,8 +349,12 @@ subprojects { subProject -> checkstyleMain.exclude '**/org/hibernate/cfg/*' findbugs { + sourceSets = [ subProject.sourceSets.main, subProject.sourceSets.test ] ignoreFailures = true } + // exclude generated sources + findbugsMain.exclude '**/generated-src/**' + buildDashboard.dependsOn check // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From 9b37f2a297ddf264828a52734a0cf597e429327a Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Tue, 30 Apr 2013 08:29:06 -0500 Subject: [PATCH 29/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../c3p0/internal/C3P0ConnectionProvider.java | 132 ++++++++++-------- .../c3p0/internal/C3P0MessageLogger.java | 63 ++++++--- .../StrategyRegistrationProviderImpl.java | 12 +- .../hibernate/c3p0/internal/package-info.java | 4 + 4 files changed, 130 insertions(+), 81 deletions(-) create mode 100644 hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/package-info.java diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java index f3b3498586..d1745cc25d 100644 --- a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java +++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java @@ -31,6 +31,7 @@ import java.util.Properties; import javax.sql.DataSource; import com.mchange.v2.c3p0.DataSources; + import org.jboss.logging.Logger; import org.hibernate.HibernateException; @@ -53,25 +54,28 @@ import org.hibernate.service.spi.Stoppable; * @author various people * @see ConnectionProvider */ -public class C3P0ConnectionProvider +public class C3P0ConnectionProvider implements ConnectionProvider, Configurable, Stoppable, ServiceRegistryAwareService { - private static final C3P0MessageLogger LOG = Logger.getMessageLogger(C3P0MessageLogger.class, C3P0ConnectionProvider.class.getName()); + private static final C3P0MessageLogger LOG = Logger.getMessageLogger( + C3P0MessageLogger.class, + C3P0ConnectionProvider.class.getName() + ); //swaldman 2006-08-28: define c3p0-style configuration parameters for properties with // hibernate-specific overrides to detect and warn about conflicting // declarations - private final static String C3P0_STYLE_MIN_POOL_SIZE = "c3p0.minPoolSize"; - private final static String C3P0_STYLE_MAX_POOL_SIZE = "c3p0.maxPoolSize"; - private final static String C3P0_STYLE_MAX_IDLE_TIME = "c3p0.maxIdleTime"; - private final static String C3P0_STYLE_MAX_STATEMENTS = "c3p0.maxStatements"; - private final static String C3P0_STYLE_ACQUIRE_INCREMENT = "c3p0.acquireIncrement"; - private final static String C3P0_STYLE_IDLE_CONNECTION_TEST_PERIOD = "c3p0.idleConnectionTestPeriod"; + private static final String C3P0_STYLE_MIN_POOL_SIZE = "c3p0.minPoolSize"; + private static final String C3P0_STYLE_MAX_POOL_SIZE = "c3p0.maxPoolSize"; + private static final String C3P0_STYLE_MAX_IDLE_TIME = "c3p0.maxIdleTime"; + private static final String C3P0_STYLE_MAX_STATEMENTS = "c3p0.maxStatements"; + private static final String C3P0_STYLE_ACQUIRE_INCREMENT = "c3p0.acquireIncrement"; + private static final String C3P0_STYLE_IDLE_CONNECTION_TEST_PERIOD = "c3p0.idleConnectionTestPeriod"; //swaldman 2006-08-28: define c3p0-style configuration parameters for initialPoolSize, which // hibernate sensibly lets default to minPoolSize, but we'll let users // override it with the c3p0-style property if they want. - private final static String C3P0_STYLE_INITIAL_POOL_SIZE = "c3p0.initialPoolSize"; + private static final String C3P0_STYLE_INITIAL_POOL_SIZE = "c3p0.initialPoolSize"; private DataSource ds; private Integer isolation; @@ -105,7 +109,7 @@ public class C3P0ConnectionProvider } @Override - @SuppressWarnings( {"unchecked"}) + @SuppressWarnings({"unchecked"}) public T unwrap(Class unwrapType) { if ( ConnectionProvider.class.equals( unwrapType ) || C3P0ConnectionProvider.class.isAssignableFrom( unwrapType ) ) { @@ -120,46 +124,46 @@ public class C3P0ConnectionProvider } @Override - @SuppressWarnings( {"unchecked"}) + @SuppressWarnings({"unchecked"}) public void configure(Map props) { - String jdbcDriverClass = (String) props.get( Environment.DRIVER ); - String jdbcUrl = (String) props.get( Environment.URL ); - Properties connectionProps = ConnectionProviderInitiator.getConnectionProperties( props ); + final String jdbcDriverClass = (String) props.get( Environment.DRIVER ); + final String jdbcUrl = (String) props.get( Environment.URL ); + final Properties connectionProps = ConnectionProviderInitiator.getConnectionProperties( props ); - LOG.c3p0UsingDriver(jdbcDriverClass, jdbcUrl); - LOG.connectionProperties(ConfigurationHelper.maskOut(connectionProps, "password")); + LOG.c3p0UsingDriver( jdbcDriverClass, jdbcUrl ); + LOG.connectionProperties( ConfigurationHelper.maskOut( connectionProps, "password" ) ); autocommit = ConfigurationHelper.getBoolean( Environment.AUTOCOMMIT, props ); - LOG.autoCommitMode( autocommit ); + LOG.autoCommitMode( autocommit ); - if (jdbcDriverClass == null) { - LOG.jdbcDriverNotSpecified(Environment.DRIVER); + if ( jdbcDriverClass == null ) { + LOG.jdbcDriverNotSpecified( Environment.DRIVER ); } else { try { serviceRegistry.getService( ClassLoaderService.class ).classForName( jdbcDriverClass ); } - catch ( ClassLoadingException e ) { - throw new ClassLoadingException( LOG.jdbcDriverNotFound(jdbcDriverClass), e ); + catch (ClassLoadingException e) { + throw new ClassLoadingException( LOG.jdbcDriverNotFound( jdbcDriverClass ), e ); } } try { //swaldman 2004-02-07: modify to allow null values to signify fall through to c3p0 PoolConfig defaults - Integer minPoolSize = ConfigurationHelper.getInteger( Environment.C3P0_MIN_SIZE, props ); - Integer maxPoolSize = ConfigurationHelper.getInteger( Environment.C3P0_MAX_SIZE, props ); - Integer maxIdleTime = ConfigurationHelper.getInteger( Environment.C3P0_TIMEOUT, props ); - Integer maxStatements = ConfigurationHelper.getInteger( Environment.C3P0_MAX_STATEMENTS, props ); - Integer acquireIncrement = ConfigurationHelper.getInteger( Environment.C3P0_ACQUIRE_INCREMENT, props ); - Integer idleTestPeriod = ConfigurationHelper.getInteger( Environment.C3P0_IDLE_TEST_PERIOD, props ); + final Integer minPoolSize = ConfigurationHelper.getInteger( Environment.C3P0_MIN_SIZE, props ); + final Integer maxPoolSize = ConfigurationHelper.getInteger( Environment.C3P0_MAX_SIZE, props ); + final Integer maxIdleTime = ConfigurationHelper.getInteger( Environment.C3P0_TIMEOUT, props ); + final Integer maxStatements = ConfigurationHelper.getInteger( Environment.C3P0_MAX_STATEMENTS, props ); + final Integer acquireIncrement = ConfigurationHelper.getInteger( Environment.C3P0_ACQUIRE_INCREMENT, props ); + final Integer idleTestPeriod = ConfigurationHelper.getInteger( Environment.C3P0_IDLE_TEST_PERIOD, props ); - Properties c3props = new Properties(); + final Properties c3props = new Properties(); // turn hibernate.c3p0.* into c3p0.*, so c3p0 // gets a chance to see all hibernate.c3p0.* for ( Object o : props.keySet() ) { - if ( ! String.class.isInstance( o ) ) { + if ( !String.class.isInstance( o ) ) { continue; } final String key = (String) o; @@ -182,63 +186,62 @@ public class C3P0ConnectionProvider Environment.C3P0_ACQUIRE_INCREMENT, C3P0_STYLE_ACQUIRE_INCREMENT, props, c3props, acquireIncrement ); setOverwriteProperty( - Environment.C3P0_IDLE_TEST_PERIOD, C3P0_STYLE_IDLE_CONNECTION_TEST_PERIOD, props, c3props, idleTestPeriod + Environment.C3P0_IDLE_TEST_PERIOD, + C3P0_STYLE_IDLE_CONNECTION_TEST_PERIOD, + props, + c3props, + idleTestPeriod ); // revert to traditional hibernate behavior of setting initialPoolSize to minPoolSize // unless otherwise specified with a c3p0.*-style parameter. - Integer initialPoolSize = ConfigurationHelper.getInteger( C3P0_STYLE_INITIAL_POOL_SIZE, props ); + final Integer initialPoolSize = ConfigurationHelper.getInteger( C3P0_STYLE_INITIAL_POOL_SIZE, props ); if ( initialPoolSize == null && minPoolSize != null ) { c3props.put( C3P0_STYLE_INITIAL_POOL_SIZE, String.valueOf( minPoolSize ).trim() ); } - /*DataSource unpooled = DataSources.unpooledDataSource( - jdbcUrl, props.getProperty(Environment.USER), props.getProperty(Environment.PASS) - );*/ - DataSource unpooled = DataSources.unpooledDataSource( jdbcUrl, connectionProps ); + final DataSource unpooled = DataSources.unpooledDataSource( jdbcUrl, connectionProps ); - Map allProps = new HashMap(); + final Map allProps = new HashMap(); allProps.putAll( props ); allProps.putAll( c3props ); ds = DataSources.pooledDataSource( unpooled, allProps ); } - catch ( Exception e ) { - LOG.error(LOG.unableToInstantiateC3p0ConnectionPool(), e); - throw new HibernateException(LOG.unableToInstantiateC3p0ConnectionPool(), e); + catch (Exception e) { + LOG.error( LOG.unableToInstantiateC3p0ConnectionPool(), e ); + throw new HibernateException( LOG.unableToInstantiateC3p0ConnectionPool(), e ); } - String i = (String) props.get( Environment.ISOLATION ); - if (i == null) isolation = null; + final String i = (String) props.get( Environment.ISOLATION ); + if ( i == null ) { + isolation = null; + } else { isolation = Integer.valueOf( i ); - LOG.jdbcIsolationLevel(Environment.isolationLevelToString(isolation)); + LOG.jdbcIsolationLevel( Environment.isolationLevelToString( isolation ) ); } } - public void close() { - try { - DataSources.destroy( ds ); - } - catch ( SQLException sqle ) { - LOG.unableToDestroyC3p0ConnectionPool(sqle); - } - } - @Override public boolean supportsAggressiveRelease() { return false; } - private void setOverwriteProperty(String hibernateStyleKey, String c3p0StyleKey, Map hibp, Properties c3p, Integer value) { + private void setOverwriteProperty( + String hibernateStyleKey, + String c3p0StyleKey, + Map hibp, + Properties c3p, + Integer value) { if ( value != null ) { - String peeledC3p0Key = c3p0StyleKey.substring(5); + final String peeledC3p0Key = c3p0StyleKey.substring( 5 ); c3p.put( peeledC3p0Key, String.valueOf( value ).trim() ); - if ( hibp.containsKey( c3p0StyleKey ) ) { + if ( hibp.containsKey( c3p0StyleKey ) ) { warnPropertyConflict( hibernateStyleKey, c3p0StyleKey ); } - String longC3p0StyleKey = "hibernate." + c3p0StyleKey; + final String longC3p0StyleKey = "hibernate." + c3p0StyleKey; if ( hibp.containsKey( longC3p0StyleKey ) ) { warnPropertyConflict( hibernateStyleKey, longC3p0StyleKey ); } @@ -246,12 +249,27 @@ public class C3P0ConnectionProvider } private void warnPropertyConflict(String hibernateStyle, String c3p0Style) { - LOG.bothHibernateAndC3p0StylesSet(hibernateStyle, c3p0Style, hibernateStyle, c3p0Style); + LOG.bothHibernateAndC3p0StylesSet( hibernateStyle, c3p0Style, hibernateStyle, c3p0Style ); } @Override public void stop() { - close(); + try { + DataSources.destroy( ds ); + } + catch (SQLException sqle) { + LOG.unableToDestroyC3p0ConnectionPool( sqle ); + } + } + + /** + * Close the provider. + * + * @deprecated Use {@link #stop} instead + */ + @Deprecated + public void close() { + stop(); } @Override diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java index 0f37a41e29..5adf334635 100644 --- a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java +++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java @@ -41,29 +41,54 @@ import static org.jboss.logging.Logger.Level.WARN; *

      * New messages must be added after the last message defined to ensure message codes are unique. */ -@MessageLogger( projectCode = "HHH" ) +@MessageLogger(projectCode = "HHH") public interface C3P0MessageLogger extends CoreMessageLogger { - @LogMessage( level = WARN ) - @Message( value = "Both hibernate-style property '%s' and c3p0-style property '%s' have been set in hibernate.properties. " - + "Hibernate-style property '%s' will be used and c3p0-style property '%s' will be ignored!", id = 10001 ) - void bothHibernateAndC3p0StylesSet( String hibernateStyle, - String c3p0Style, - String hibernateStyle2, - String c3p0Style2 ); + /** + * Log a message (WARN) about conflicting {@code hibernate.c3p0.XYZ} and {@code c3p0.XYZ} settings + * + * @param hibernateStyle The {@code hibernate.c3p0} prefixed setting + * @param c3p0Style The {@code c3p0.} prefixed setting + */ + @LogMessage(level = WARN) + @Message(value = "Both hibernate-style property '%1$s' and c3p0-style property '%2$s' have been set in Hibernate " + + "properties. Hibernate-style property '%1$s' will be used and c3p0-style property '2$%s' will be ignored!", id = 10001) + void bothHibernateAndC3p0StylesSet(String hibernateStyle,String c3p0Style); - @LogMessage( level = INFO ) - @Message( value = "C3P0 using driver: %s at URL: %s", id = 10002 ) - void c3p0UsingDriver( String jdbcDriverClass, - String jdbcUrl ); + /** + * Log a message (INFO) about which Driver class is being used. + * + * @param jdbcDriverClass The JDBC Driver class + * @param jdbcUrl The JDBC URL + */ + @LogMessage(level = INFO) + @Message(value = "C3P0 using driver: %s at URL: %s", id = 10002) + void c3p0UsingDriver(String jdbcDriverClass, String jdbcUrl); - @Message( value = "JDBC Driver class not found: %s", id = 10003 ) - String jdbcDriverNotFound( String jdbcDriverClass ); + /** + * Build a message about not being able to find the JDBC driver class + * + * @param jdbcDriverClass The JDBC driver class we could not find + * + * @return The message + */ + @Message(value = "JDBC Driver class not found: %s", id = 10003) + String jdbcDriverNotFound(String jdbcDriverClass); - @LogMessage( level = WARN ) - @Message( value = "Could not destroy C3P0 connection pool", id = 10004 ) - void unableToDestroyC3p0ConnectionPool( @Cause SQLException e ); + /** + * Log a message (WARN) about not being able to stop the underlying c3p0 pool. + * + * @param e The exception when we tried to stop pool + */ + @LogMessage(level = WARN) + @Message(value = "Could not destroy C3P0 connection pool", id = 10004) + void unableToDestroyC3p0ConnectionPool(@Cause SQLException e); - @Message( value = "Could not instantiate C3P0 connection pool", id = 10005 ) - String unableToInstantiateC3p0ConnectionPool(); + /** + * Build a message about not being able to start the underlying c3p0 pool. + * + * @return The message + */ + @Message(value = "Could not instantiate C3P0 connection pool", id = 10005) + String unableToInstantiateC3p0ConnectionPool(); } diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java index 4237221181..b1b98bd9c5 100644 --- a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java +++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/StrategyRegistrationProviderImpl.java @@ -38,16 +38,18 @@ import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; * @author Brett Meyer */ public class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider { - private static final List REGISTRATIONS = Collections.singletonList( - (StrategyRegistration) new SimpleStrategyRegistrationImpl( + (StrategyRegistration) new SimpleStrategyRegistrationImpl( ConnectionProvider.class, C3P0ConnectionProvider.class, "c3p0", C3P0ConnectionProvider.class.getSimpleName(), - "org.hibernate.connection.C3P0ConnectionProvider", // legacy - "org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider" // legacy - ) ); + // legacy + "org.hibernate.connection.C3P0ConnectionProvider", + // legacy + "org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider" + ) + ); @Override @SuppressWarnings("unchecked") diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/package-info.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/package-info.java new file mode 100644 index 0000000000..52b4638e53 --- /dev/null +++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/package-info.java @@ -0,0 +1,4 @@ +/** + * Implementation of ConnectionProvider using the c3p0 Connection pool. + */ +package org.hibernate.c3p0.internal; From bf781d4bf71be743420a62d4aacda2aff665608e Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Tue, 30 Apr 2013 08:36:27 -0500 Subject: [PATCH 30/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../org/hibernate/c3p0/internal/C3P0ConnectionProvider.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java index d1745cc25d..207461b1c5 100644 --- a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java +++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0ConnectionProvider.java @@ -249,7 +249,7 @@ public class C3P0ConnectionProvider } private void warnPropertyConflict(String hibernateStyle, String c3p0Style) { - LOG.bothHibernateAndC3p0StylesSet( hibernateStyle, c3p0Style, hibernateStyle, c3p0Style ); + LOG.bothHibernateAndC3p0StylesSet( hibernateStyle, c3p0Style ); } @Override From fdb30196fcf051616550cb324cfe34c2f9c531db Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Tue, 30 Apr 2013 08:51:04 -0500 Subject: [PATCH 31/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../java/org/hibernate/c3p0/internal/C3P0MessageLogger.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java index 5adf334635..7ff9c6eab0 100644 --- a/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java +++ b/hibernate-c3p0/src/main/java/org/hibernate/c3p0/internal/C3P0MessageLogger.java @@ -52,7 +52,7 @@ public interface C3P0MessageLogger extends CoreMessageLogger { */ @LogMessage(level = WARN) @Message(value = "Both hibernate-style property '%1$s' and c3p0-style property '%2$s' have been set in Hibernate " - + "properties. Hibernate-style property '%1$s' will be used and c3p0-style property '2$%s' will be ignored!", id = 10001) + + "properties. Hibernate-style property '%1$s' will be used and c3p0-style property '%2$s' will be ignored!", id = 10001) void bothHibernateAndC3p0StylesSet(String hibernateStyle,String c3p0Style); /** From 59d1facfb6bf3d015802bfa7acd86b12a182112b Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Tue, 30 Apr 2013 09:26:55 -0500 Subject: [PATCH 32/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../internal/ProxoolConnectionProvider.java | 146 +++++++++--------- .../internal/ProxoolMessageLogger.java | 121 +++++++++++---- .../StrategyRegistrationProviderImpl.java | 9 +- .../proxool/internal/package-info.java | 4 + 4 files changed, 171 insertions(+), 109 deletions(-) create mode 100644 hibernate-proxool/src/main/java/org/hibernate/proxool/internal/package-info.java diff --git a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolConnectionProvider.java b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolConnectionProvider.java index b8a8fbd8cd..bb47c7a9c4 100644 --- a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolConnectionProvider.java +++ b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolConnectionProvider.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2007, 2013, 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. + * 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 @@ -27,32 +27,35 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Map; -import java.util.Properties; -import org.jboss.logging.Logger; import org.logicalcobwebs.proxool.ProxoolException; import org.logicalcobwebs.proxool.ProxoolFacade; import org.logicalcobwebs.proxool.configuration.JAXPConfigurator; import org.logicalcobwebs.proxool.configuration.PropertyConfigurator; +import org.jboss.logging.Logger; + import org.hibernate.HibernateException; import org.hibernate.cfg.Environment; +import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.internal.util.ConfigHelper; import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.service.UnknownUnwrapTypeException; -import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; import org.hibernate.service.spi.Configurable; import org.hibernate.service.spi.Stoppable; /** * A connection provider that uses a Proxool connection pool. Hibernate will use this by * default if the hibernate.proxool.* properties are set. + * * @see ConnectionProvider */ public class ProxoolConnectionProvider implements ConnectionProvider, Configurable, Stoppable { - - public static final ProxoolMessageLogger LOG = Logger.getMessageLogger(ProxoolMessageLogger.class, ProxoolConnectionProvider.class.getName()); + private static final ProxoolMessageLogger LOG = Logger.getMessageLogger( + ProxoolMessageLogger.class, + ProxoolConnectionProvider.class.getName() + ); private static final String PROXOOL_JDBC_STEM = "proxool."; @@ -67,21 +70,20 @@ public class ProxoolConnectionProvider implements ConnectionProvider, Configurab private boolean autocommit; - /** - * Grab a connection - * @return a JDBC connection - * @throws SQLException - */ @Override public Connection getConnection() throws SQLException { - // get a connection from the pool (thru DriverManager, cfr. Proxool doc) - Connection c = DriverManager.getConnection(proxoolAlias); + // get a connection from the pool (thru DriverManager, cfr. Proxool doc) + final Connection c = DriverManager.getConnection( proxoolAlias ); // set the Transaction Isolation if defined - if (isolation!=null) c.setTransactionIsolation( isolation ); + if ( isolation != null ) { + c.setTransactionIsolation( isolation ); + } // toggle autoCommit to false if set - if ( c.getAutoCommit()!=autocommit ) c.setAutoCommit(autocommit); + if ( c.getAutoCommit() != autocommit ) { + c.setAutoCommit( autocommit ); + } // return the connection return c; @@ -94,7 +96,7 @@ public class ProxoolConnectionProvider implements ConnectionProvider, Configurab } @Override - @SuppressWarnings( {"unchecked"}) + @SuppressWarnings({"unchecked"}) public T unwrap(Class unwrapType) { if ( ConnectionProvider.class.equals( unwrapType ) || ProxoolConnectionProvider.class.isAssignableFrom( unwrapType ) ) { @@ -105,39 +107,28 @@ public class ProxoolConnectionProvider implements ConnectionProvider, Configurab } } - /** - * Dispose of a used connection. - * @param conn a JDBC connection - * @throws SQLException - */ @Override public void closeConnection(Connection conn) throws SQLException { conn.close(); } - /** - * Initialize the connection provider from given properties. - * @param props SessionFactory properties - */ @Override - public void configure(Map props) { - + public void configure(Map props) { // Get the configurator files (if available) - String jaxpFile = (String)props.get(Environment.PROXOOL_XML); - String propFile = (String)props.get(Environment.PROXOOL_PROPERTIES); - String externalConfig = (String)props.get(Environment.PROXOOL_EXISTING_POOL); + final String jaxpFile = (String) props.get( Environment.PROXOOL_XML ); + final String propFile = (String) props.get( Environment.PROXOOL_PROPERTIES ); + final String externalConfig = (String) props.get( Environment.PROXOOL_EXISTING_POOL ); // Default the Proxool alias setting - proxoolAlias = (String)props.get(Environment.PROXOOL_POOL_ALIAS); + proxoolAlias = (String) props.get( Environment.PROXOOL_POOL_ALIAS ); // Configured outside of Hibernate (i.e. Servlet container, or Java Bean Container // already has Proxool pools running, and this provider is to just borrow one of these - if ( "true".equals(externalConfig) ) { - + if ( "true".equals( externalConfig ) ) { // Validate that an alias name was provided to determine which pool to use if ( !StringHelper.isNotEmpty( proxoolAlias ) ) { - String msg = LOG.unableToConfigureProxoolProviderToUseExistingInMemoryPool(Environment.PROXOOL_POOL_ALIAS); - LOG.error(msg); + final String msg = LOG.unableToConfigureProxoolProviderToUseExistingInMemoryPool( Environment.PROXOOL_POOL_ALIAS ); + LOG.error( msg ); throw new HibernateException( msg ); } // Append the stem to the proxool pool alias @@ -146,77 +137,79 @@ public class ProxoolConnectionProvider implements ConnectionProvider, Configurab // Set the existing pool flag to true existingPool = true; - LOG.configuringProxoolProviderUsingExistingPool(proxoolAlias); + LOG.configuringProxoolProviderUsingExistingPool( proxoolAlias ); // Configured using the JAXP Configurator } else if ( StringHelper.isNotEmpty( jaxpFile ) ) { - - LOG.configuringProxoolProviderUsingJaxpConfigurator(jaxpFile); + LOG.configuringProxoolProviderUsingJaxpConfigurator( jaxpFile ); // Validate that an alias name was provided to determine which pool to use if ( !StringHelper.isNotEmpty( proxoolAlias ) ) { - String msg = LOG.unableToConfigureProxoolProviderToUseJaxp(Environment.PROXOOL_POOL_ALIAS); - LOG.error(msg); + final String msg = LOG.unableToConfigureProxoolProviderToUseJaxp( Environment.PROXOOL_POOL_ALIAS ); + LOG.error( msg ); throw new HibernateException( msg ); } try { JAXPConfigurator.configure( ConfigHelper.getConfigStreamReader( jaxpFile ), false ); } - catch ( ProxoolException e ) { - String msg = LOG.unableToLoadJaxpConfiguratorFile(jaxpFile); - LOG.error(msg, e); + catch (ProxoolException e) { + final String msg = LOG.unableToLoadJaxpConfiguratorFile( jaxpFile ); + LOG.error( msg, e ); throw new HibernateException( msg, e ); } // Append the stem to the proxool pool alias proxoolAlias = PROXOOL_JDBC_STEM + proxoolAlias; - LOG.configuringProxoolProviderToUsePoolAlias(proxoolAlias); + LOG.configuringProxoolProviderToUsePoolAlias( proxoolAlias ); // Configured using the Properties File Configurator } else if ( StringHelper.isNotEmpty( propFile ) ) { - - LOG.configuringProxoolProviderUsingPropertiesFile(propFile); + LOG.configuringProxoolProviderUsingPropertiesFile( propFile ); // Validate that an alias name was provided to determine which pool to use if ( !StringHelper.isNotEmpty( proxoolAlias ) ) { - String msg = LOG.unableToConfigureProxoolProviderToUsePropertiesFile(Environment.PROXOOL_POOL_ALIAS); - LOG.error(msg); + final String msg = LOG.unableToConfigureProxoolProviderToUsePropertiesFile( Environment.PROXOOL_POOL_ALIAS ); + LOG.error( msg ); throw new HibernateException( msg ); } try { PropertyConfigurator.configure( ConfigHelper.getConfigProperties( propFile ) ); } - catch ( ProxoolException e ) { - String msg = LOG.unableToLoadPropertyConfiguratorFile(propFile); - LOG.error(msg, e); + catch (ProxoolException e) { + final String msg = LOG.unableToLoadPropertyConfiguratorFile( propFile ); + LOG.error( msg, e ); throw new HibernateException( msg, e ); } // Append the stem to the proxool pool alias proxoolAlias = PROXOOL_JDBC_STEM + proxoolAlias; - LOG.configuringProxoolProviderToUsePoolAlias(proxoolAlias); + LOG.configuringProxoolProviderToUsePoolAlias( proxoolAlias ); } // Remember Isolation level - isolation = ConfigurationHelper.getInteger(Environment.ISOLATION, props); - if (isolation != null) LOG.jdbcIsolationLevel(Environment.isolationLevelToString(isolation.intValue())); + isolation = ConfigurationHelper.getInteger( Environment.ISOLATION, props ); + if ( isolation != null ) { + LOG.jdbcIsolationLevel( Environment.isolationLevelToString( isolation.intValue() ) ); + } - autocommit = ConfigurationHelper.getBoolean(Environment.AUTOCOMMIT, props); - LOG.autoCommmitMode(autocommit); + autocommit = ConfigurationHelper.getBoolean( Environment.AUTOCOMMIT, props ); + LOG.autoCommmitMode( autocommit ); } - /** - * Release all resources held by this provider. JavaDoc requires a second sentence. - * @throws HibernateException - */ - public void close() throws HibernateException { + @Override + public boolean supportsAggressiveRelease() { + return false; + } + + @Override + public void stop() { // If the provider was leeching off an existing pool don't close it - if (existingPool) { + if ( existingPool ) { return; } @@ -226,29 +219,28 @@ public class ProxoolConnectionProvider implements ConnectionProvider, Configurab ProxoolFacade.shutdown( 0 ); } else { - ProxoolFacade.removeConnectionPool(proxoolAlias.substring(PROXOOL_JDBC_STEM.length())); + ProxoolFacade.removeConnectionPool( proxoolAlias.substring( PROXOOL_JDBC_STEM.length() ) ); } } catch (Exception e) { // If you're closing down the ConnectionProvider chances are an // is not a real big deal, just warn - String msg = LOG.exceptionClosingProxoolPool(); - LOG.warn(msg, e); - throw new HibernateException(msg, e); + final String msg = LOG.exceptionClosingProxoolPool(); + LOG.warn( msg, e ); + throw new HibernateException( msg, e ); } } /** - * @see ConnectionProvider#supportsAggressiveRelease() + * Release all resources held by this provider. + * + * @throws HibernateException Indicates a problem closing the underlying pool or releasing resources + * + * @deprecated Use {@link #stop} instead */ - @Override - public boolean supportsAggressiveRelease() { - return false; + @Deprecated + public void close() throws HibernateException { + stop(); } - - @Override - public void stop() { - close(); - } } diff --git a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolMessageLogger.java b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolMessageLogger.java index 568f4c98e9..5229bf66d2 100644 --- a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolMessageLogger.java +++ b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/ProxoolMessageLogger.java @@ -37,44 +37,109 @@ import static org.jboss.logging.Logger.Level.INFO; *

      * New messages must be added after the last message defined to ensure message codes are unique. */ -@MessageLogger( projectCode = "HHH" ) +@MessageLogger(projectCode = "HHH") public interface ProxoolMessageLogger extends CoreMessageLogger { - @LogMessage( level = INFO ) - @Message( value = "Autocommit mode: %s", id = 30001 ) - void autoCommmitMode( boolean autocommit ); + /** + * Logs the autocommit mode to be used for pooled connections + * + * @param autocommit The autocommit mode + */ + @LogMessage(level = INFO) + @Message(value = "Autocommit mode: %s", id = 30001) + void autoCommmitMode(boolean autocommit); - @LogMessage( level = INFO ) - @Message( value = "Configuring Proxool Provider to use pool alias: %s", id = 30002 ) - void configuringProxoolProviderToUsePoolAlias( String proxoolAlias ); + /** + * Logs the name of a named pool to be used for configuration information + * + * @param proxoolAlias The name (alias) of the proxool pool + */ + @LogMessage(level = INFO) + @Message(value = "Configuring Proxool Provider to use pool alias: %s", id = 30002) + void configuringProxoolProviderToUsePoolAlias(String proxoolAlias); - @LogMessage( level = INFO ) - @Message( value = "Configuring Proxool Provider using existing pool in memory: %s", id = 30003 ) - void configuringProxoolProviderUsingExistingPool( String proxoolAlias ); + /** + * Logs the name of a named existing pool in memory to be used + * + * @param proxoolAlias The name (alias) of the proxool pool + */ + @LogMessage(level = INFO) + @Message(value = "Configuring Proxool Provider using existing pool in memory: %s", id = 30003) + void configuringProxoolProviderUsingExistingPool(String proxoolAlias); - @LogMessage( level = INFO ) - @Message( value = "Configuring Proxool Provider using JAXPConfigurator: %s", id = 30004 ) - void configuringProxoolProviderUsingJaxpConfigurator( String jaxpFile ); + /** + * Logs a message that the proxool pool will be built using its JAXP (XML) configuration mechanism + * + * @param jaxpFile The XML configuration file to use + */ + @LogMessage(level = INFO) + @Message(value = "Configuring Proxool Provider using JAXPConfigurator: %s", id = 30004) + void configuringProxoolProviderUsingJaxpConfigurator(String jaxpFile); - @LogMessage( level = INFO ) - @Message( value = "Configuring Proxool Provider using Properties File: %s", id = 30005 ) - void configuringProxoolProviderUsingPropertiesFile( String proxoolAlias ); + /** + * Logs a message that the proxool pool will be built using a properties file + * + * @param propFile The properties file to use + */ + @LogMessage(level = INFO) + @Message(value = "Configuring Proxool Provider using Properties File: %s", id = 30005) + void configuringProxoolProviderUsingPropertiesFile(String propFile); - @Message( value = "Exception occured when closing the Proxool pool", id = 30006 ) - String exceptionClosingProxoolPool(); + /** + * Builds a message about not being able to close the underlying proxool pool. + * + * @return The message + */ + @Message(value = "Exception occured when closing the Proxool pool", id = 30006) + String exceptionClosingProxoolPool(); - @Message( value = "Cannot configure Proxool Provider to use an existing in memory pool without the %s property set.", id = 30007 ) - String unableToConfigureProxoolProviderToUseExistingInMemoryPool( String proxoolPoolAlias ); + /** + * Builds a message about invalid configuration + * + * @param proxoolPoolAlias The name (alias) of the proxool pool + * + * @return The message + */ + @Message(value = "Cannot configure Proxool Provider to use an existing in memory pool without the %s property set.", id = 30007) + String unableToConfigureProxoolProviderToUseExistingInMemoryPool(String proxoolPoolAlias); - @Message( value = "Cannot configure Proxool Provider to use JAXP without the %s property set.", id = 30008 ) - String unableToConfigureProxoolProviderToUseJaxp( String proxoolPoolAlias ); + /** + * Builds a message about invalid configuration + * + * @param proxoolPoolAlias The name (alias) of the proxool pool + * + * @return The message + */ + @Message(value = "Cannot configure Proxool Provider to use JAXP without the %s property set.", id = 30008) + String unableToConfigureProxoolProviderToUseJaxp(String proxoolPoolAlias); - @Message( value = "Cannot configure Proxool Provider to use Properties File without the %s property set.", id = 30009 ) - String unableToConfigureProxoolProviderToUsePropertiesFile( String proxoolPoolAlias ); + /** + * Builds a message about invalid configuration + * + * @param proxoolPoolAlias The name (alias) of the proxool pool + * + * @return The message + */ + @Message(value = "Cannot configure Proxool Provider to use Properties File without the %s property set.", id = 30009) + String unableToConfigureProxoolProviderToUsePropertiesFile(String proxoolPoolAlias); - @Message( value = "Proxool Provider unable to load JAXP configurator file: %s", id = 30010 ) - String unableToLoadJaxpConfiguratorFile( String jaxpFile ); + /** + * Builds a message about not being able to find or load the XML configuration file + * + * @param jaxpFile The XML file + * + * @return The message + */ + @Message(value = "Proxool Provider unable to load JAXP configurator file: %s", id = 30010) + String unableToLoadJaxpConfiguratorFile(String jaxpFile); - @Message( value = "Proxool Provider unable to load Property configurator file: %s", id = 30011 ) - String unableToLoadPropertyConfiguratorFile( String propFile ); + /** + * Builds a message about not being able to find or load the properties configuration file + * + * @param propFile The properties file + * + * @return The message + */ + @Message(value = "Proxool Provider unable to load Property configurator file: %s", id = 30011) + String unableToLoadPropertyConfiguratorFile(String propFile); } diff --git a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java index 7104d50399..c5c5c720cf 100644 --- a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java +++ b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java @@ -38,15 +38,16 @@ import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; * @author Brett Meyer */ public class StrategyRegistrationProviderImpl implements StrategyRegistrationProvider { - private static final List REGISTRATIONS = Collections.singletonList( - (StrategyRegistration) new SimpleStrategyRegistrationImpl( + (StrategyRegistration) new SimpleStrategyRegistrationImpl( ConnectionProvider.class, ProxoolConnectionProvider.class, "proxool", ProxoolConnectionProvider.class.getSimpleName(), - "org.hibernate.connection.ProxoolConnectionProvider", // legacy - "org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider" // legacy + // legacy + "org.hibernate.connection.ProxoolConnectionProvider", + // legacy + "org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider" ) ); @Override diff --git a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/package-info.java b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/package-info.java new file mode 100644 index 0000000000..bc3b68bf9e --- /dev/null +++ b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/package-info.java @@ -0,0 +1,4 @@ +/** + * Implementation of ConnectionProvider using the proxool Connection pool. + */ +package org.hibernate.proxool.internal; From 09a54fdc5457c5a2e0c1d3af0472f332063829c6 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Tue, 30 Apr 2013 09:30:04 -0500 Subject: [PATCH 33/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../proxool/internal/StrategyRegistrationProviderImpl.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java index c5c5c720cf..841a7c985d 100644 --- a/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java +++ b/hibernate-proxool/src/main/java/org/hibernate/proxool/internal/StrategyRegistrationProviderImpl.java @@ -48,7 +48,8 @@ public class StrategyRegistrationProviderImpl implements StrategyRegistrationPro "org.hibernate.connection.ProxoolConnectionProvider", // legacy "org.hibernate.service.jdbc.connections.internal.ProxoolConnectionProvider" - ) ); + ) + ); @Override @SuppressWarnings("unchecked") From 97e28200f0eb61d6b59bf782e8fb60559679c7a2 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Tue, 30 Apr 2013 13:27:38 -0500 Subject: [PATCH 34/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../ehcache/AbstractEhcacheRegionFactory.java | 302 ++++---- .../cache/ehcache/EhCacheMessageLogger.java | 116 +++- .../cache/ehcache/EhCacheRegionFactory.java | 154 +++-- .../SingletonEhCacheRegionFactory.java | 140 ++-- .../StrategyRegistrationProviderImpl.java | 8 +- ...HibernateNonstopCacheExceptionHandler.java | 105 +-- .../nonstop/NonstopAccessStrategyFactory.java | 84 +-- ...opAwareCollectionRegionAccessStrategy.java | 105 +-- ...onstopAwareEntityRegionAccessStrategy.java | 141 +--- ...topAwareNaturalIdRegionAccessStrategy.java | 115 +--- .../internal/nonstop/package-info.java | 5 + .../regions/EhcacheCollectionRegion.java | 40 +- .../internal/regions/EhcacheDataRegion.java | 304 ++++---- .../internal/regions/EhcacheEntityRegion.java | 40 +- .../regions/EhcacheGeneralDataRegion.java | 219 +++--- .../regions/EhcacheNaturalIdRegion.java | 32 +- .../regions/EhcacheQueryResultsRegion.java | 12 +- .../regions/EhcacheTimestampsRegion.java | 14 +- .../EhcacheTransactionalDataRegion.java | 92 ++- .../internal/regions/package-info.java | 4 + .../AbstractEhcacheAccessStrategy.java | 34 +- ...bstractReadWriteEhcacheAccessStrategy.java | 649 +++++++++--------- .../EhcacheAccessStrategyFactory.java | 44 +- .../EhcacheAccessStrategyFactoryImpl.java | 198 +++--- ...EhcacheCollectionRegionAccessStrategy.java | 36 +- ...riteEhcacheEntityRegionAccessStrategy.java | 49 +- ...eEhcacheNaturalIdRegionAccessStrategy.java | 75 +- ...EhcacheCollectionRegionAccessStrategy.java | 27 +- ...OnlyEhcacheEntityRegionAccessStrategy.java | 19 +- ...yEhcacheNaturalIdRegionAccessStrategy.java | 56 +- ...EhcacheCollectionRegionAccessStrategy.java | 11 +- ...riteEhcacheEntityRegionAccessStrategy.java | 33 +- ...eEhcacheNaturalIdRegionAccessStrategy.java | 44 +- ...EhcacheCollectionRegionAccessStrategy.java | 47 +- ...onalEhcacheEntityRegionAccessStrategy.java | 73 +- ...lEhcacheNaturalIdRegionAccessStrategy.java | 73 +- .../internal/strategy/package-info.java | 4 + .../internal/util/HibernateEhcacheUtils.java | 129 ++++ .../ehcache/internal/util/HibernateUtil.java | 116 ---- .../ehcache/internal/util/package-info.java | 4 + ...tterBean.java => AbstractEmitterBean.java} | 87 +-- .../ehcache/management/impl/BeanUtils.java | 43 +- .../management/impl/CacheRegionStats.java | 93 +-- .../management/impl/CacheRegionUtils.java | 35 +- .../management/impl/CollectionStats.java | 107 ++- .../management/impl/EhcacheHibernate.java | 14 +- ...EhcacheHibernateMBeanRegistrationImpl.java | 237 +++---- .../management/impl/EhcacheStatsImpl.java | 24 +- .../ehcache/management/impl/EntityStats.java | 18 +- .../management/impl/HibernateStatsImpl.java | 14 +- .../impl/ProviderMBeanRegistrationHelper.java | 260 +++---- .../ehcache/management/impl/QueryStats.java | 18 +- .../ehcache/management/impl/package-info.java | 4 + .../hibernate/cache/ehcache/package-info.java | 4 + 54 files changed, 2312 insertions(+), 2399 deletions(-) create mode 100644 hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/package-info.java create mode 100644 hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/package-info.java create mode 100644 hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/package-info.java create mode 100644 hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateEhcacheUtils.java delete mode 100644 hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateUtil.java create mode 100644 hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/package-info.java rename hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/{BaseEmitterBean.java => AbstractEmitterBean.java} (69%) create mode 100644 hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/package-info.java create mode 100644 hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/package-info.java diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AbstractEhcacheRegionFactory.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AbstractEhcacheRegionFactory.java index 9b9a28c2ec..b12a88e188 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AbstractEhcacheRegionFactory.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AbstractEhcacheRegionFactory.java @@ -29,8 +29,10 @@ import java.util.Properties; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Ehcache; import net.sf.ehcache.util.ClassLoaderUtil; + import org.jboss.logging.Logger; +import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; import org.hibernate.cache.CacheException; import org.hibernate.cache.ehcache.internal.nonstop.NonstopAccessStrategyFactory; import org.hibernate.cache.ehcache.internal.regions.EhcacheCollectionRegion; @@ -40,7 +42,7 @@ import org.hibernate.cache.ehcache.internal.regions.EhcacheQueryResultsRegion; import org.hibernate.cache.ehcache.internal.regions.EhcacheTimestampsRegion; import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory; import org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactoryImpl; -import org.hibernate.cache.ehcache.internal.util.HibernateUtil; +import org.hibernate.cache.ehcache.internal.util.HibernateEhcacheUtils; import org.hibernate.cache.ehcache.management.impl.ProviderMBeanRegistrationHelper; import org.hibernate.cache.spi.CacheDataDescription; import org.hibernate.cache.spi.CollectionRegion; @@ -51,7 +53,6 @@ import org.hibernate.cache.spi.RegionFactory; import org.hibernate.cache.spi.TimestampsRegion; import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cfg.Settings; -import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; import org.hibernate.service.spi.InjectService; /** @@ -65,172 +66,169 @@ import org.hibernate.service.spi.InjectService; */ abstract class AbstractEhcacheRegionFactory implements RegionFactory { - /** - * The Hibernate system property specifying the location of the ehcache configuration file name. - *

      - * If not set, ehcache.xml will be looked for in the root of the classpath. - *

      - * If set to say ehcache-1.xml, ehcache-1.xml will be looked for in the root of the classpath. - */ - public static final String NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME = "net.sf.ehcache.configurationResourceName"; + /** + * The Hibernate system property specifying the location of the ehcache configuration file name. + *

      + * If not set, ehcache.xml will be looked for in the root of the classpath. + *

      + * If set to say ehcache-1.xml, ehcache-1.xml will be looked for in the root of the classpath. + */ + public static final String NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME = "net.sf.ehcache.configurationResourceName"; - private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( - EhCacheMessageLogger.class, - AbstractEhcacheRegionFactory.class.getName() - ); + private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( + EhCacheMessageLogger.class, + AbstractEhcacheRegionFactory.class.getName() + ); - /** - * MBean registration helper class instance for Ehcache Hibernate MBeans. - */ - protected final ProviderMBeanRegistrationHelper mbeanRegistrationHelper = new ProviderMBeanRegistrationHelper(); + /** + * MBean registration helper class instance for Ehcache Hibernate MBeans. + */ + protected final ProviderMBeanRegistrationHelper mbeanRegistrationHelper = new ProviderMBeanRegistrationHelper(); - /** - * Ehcache CacheManager that supplied Ehcache instances for this Hibernate RegionFactory. - */ - protected volatile CacheManager manager; + /** + * Ehcache CacheManager that supplied Ehcache instances for this Hibernate RegionFactory. + */ + protected volatile CacheManager manager; - /** - * Settings object for the Hibernate persistence unit. - */ - protected Settings settings; + /** + * Settings object for the Hibernate persistence unit. + */ + protected Settings settings; - /** - * {@link EhcacheAccessStrategyFactory} for creating various access strategies - */ - protected final EhcacheAccessStrategyFactory accessStrategyFactory = - new NonstopAccessStrategyFactory( new EhcacheAccessStrategyFactoryImpl() ); + /** + * {@link EhcacheAccessStrategyFactory} for creating various access strategies + */ + protected final EhcacheAccessStrategyFactory accessStrategyFactory = + new NonstopAccessStrategyFactory( new EhcacheAccessStrategyFactoryImpl() ); - /** - * Whether to optimize for minimals puts or minimal gets. - *

      - * Indicates whether when operating in non-strict read/write or read-only mode - * Hibernate should optimize the access patterns for minimal puts or minimal gets. - * In Ehcache we default to minimal puts since this should have minimal to no - * affect on unclustered users, and has great benefit for clustered users. - *

      - * This setting can be overridden by setting the "hibernate.cache.use_minimal_puts" - * property in the Hibernate configuration. - * - * @return true, optimize for minimal puts - */ - public boolean isMinimalPutsEnabledByDefault() { - return true; - } + /** + * {@inheritDoc} + *

      + * In Ehcache we default to minimal puts since this should have minimal to no + * affect on unclustered users, and has great benefit for clustered users. + * + * @return true, optimize for minimal puts + */ + @Override + public boolean isMinimalPutsEnabledByDefault() { - /** - * {@inheritDoc} - */ - public long nextTimestamp() { - return net.sf.ehcache.util.Timestamper.next(); - } + return true; + } - /** - * {@inheritDoc} - */ - public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata) - throws CacheException { - return new EhcacheEntityRegion( accessStrategyFactory, getCache( regionName ), settings, metadata, properties ); - } - - @Override - public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata) - throws CacheException { - return new EhcacheNaturalIdRegion( accessStrategyFactory, getCache( regionName ), settings, metadata, properties ); - } + @Override + public long nextTimestamp() { + return net.sf.ehcache.util.Timestamper.next(); + } - /** - * {@inheritDoc} - */ - public CollectionRegion buildCollectionRegion(String regionName, Properties properties, CacheDataDescription metadata) - throws CacheException { - return new EhcacheCollectionRegion( - accessStrategyFactory, - getCache( regionName ), - settings, - metadata, - properties - ); - } + @Override + public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata) + throws CacheException { + return new EhcacheEntityRegion( accessStrategyFactory, getCache( regionName ), settings, metadata, properties ); + } - /** - * {@inheritDoc} - */ - public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException { - return new EhcacheQueryResultsRegion( accessStrategyFactory, getCache( regionName ), properties ); - } + @Override + public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata) + throws CacheException { + return new EhcacheNaturalIdRegion( + accessStrategyFactory, + getCache( regionName ), + settings, + metadata, + properties + ); + } - @InjectService - public void setClassLoaderService(ClassLoaderService classLoaderService) { - this.classLoaderService = classLoaderService; - } + @Override + public CollectionRegion buildCollectionRegion( + String regionName, + Properties properties, + CacheDataDescription metadata) + throws CacheException { + return new EhcacheCollectionRegion( + accessStrategyFactory, + getCache( regionName ), + settings, + metadata, + properties + ); + } - private ClassLoaderService classLoaderService; + @Override + public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException { + return new EhcacheQueryResultsRegion( accessStrategyFactory, getCache( regionName ), properties ); + } - /** - * {@inheritDoc} - */ - public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException { - return new EhcacheTimestampsRegion( accessStrategyFactory, getCache( regionName ), properties ); - } + @InjectService + @SuppressWarnings("UnusedDeclaration") + public void setClassLoaderService(ClassLoaderService classLoaderService) { + this.classLoaderService = classLoaderService; + } - private Ehcache getCache(String name) throws CacheException { - try { - Ehcache cache = manager.getEhcache( name ); - if ( cache == null ) { - LOG.unableToFindEhCacheConfiguration( name ); - manager.addCache( name ); - cache = manager.getEhcache( name ); - LOG.debug( "started EHCache region: " + name ); - } - HibernateUtil.validateEhcache( cache ); - return cache; - } - catch ( net.sf.ehcache.CacheException e ) { - throw new CacheException( e ); - } + private ClassLoaderService classLoaderService; - } + @Override + public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException { + return new EhcacheTimestampsRegion( accessStrategyFactory, getCache( regionName ), properties ); + } - /** - * Load a resource from the classpath. - */ - protected URL loadResource(String configurationResourceName) { - URL url = null; - if ( classLoaderService != null ) { - url = classLoaderService.locateResource( configurationResourceName ); - } - if ( url == null ) { - ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader(); - if ( standardClassloader != null ) { - url = standardClassloader.getResource( configurationResourceName ); - } - if ( url == null ) { - url = AbstractEhcacheRegionFactory.class.getResource( configurationResourceName ); - } - } - if ( LOG.isDebugEnabled() ) { - LOG.debugf( - "Creating EhCacheRegionFactory from a specified resource: %s. Resolved to URL: %s", - configurationResourceName, - url - ); - } - if ( url == null ) { + private Ehcache getCache(String name) throws CacheException { + try { + Ehcache cache = manager.getEhcache( name ); + if ( cache == null ) { + LOG.unableToFindEhCacheConfiguration( name ); + manager.addCache( name ); + cache = manager.getEhcache( name ); + LOG.debug( "started EHCache region: " + name ); + } + HibernateEhcacheUtils.validateEhcache( cache ); + return cache; + } + catch (net.sf.ehcache.CacheException e) { + throw new CacheException( e ); + } - LOG.unableToLoadConfiguration( configurationResourceName ); - } - return url; - } + } - /** - * Default access-type used when the configured using JPA 2.0 config. JPA 2.0 allows @Cacheable(true) to be attached to an - * entity without any access type or usage qualification. - *

      - * We are conservative here in specifying {@link AccessType#READ_WRITE} so as to follow the mantra of "do no harm". - *

      - * This is a Hibernate 3.5 method. - */ - public AccessType getDefaultAccessType() { - return AccessType.READ_WRITE; - } + /** + * Load a resource from the classpath. + */ + protected URL loadResource(String configurationResourceName) { + URL url = null; + if ( classLoaderService != null ) { + url = classLoaderService.locateResource( configurationResourceName ); + } + if ( url == null ) { + final ClassLoader standardClassloader = ClassLoaderUtil.getStandardClassLoader(); + if ( standardClassloader != null ) { + url = standardClassloader.getResource( configurationResourceName ); + } + if ( url == null ) { + url = AbstractEhcacheRegionFactory.class.getResource( configurationResourceName ); + } + } + if ( LOG.isDebugEnabled() ) { + LOG.debugf( + "Creating EhCacheRegionFactory from a specified resource: %s. Resolved to URL: %s", + configurationResourceName, + url + ); + } + if ( url == null ) { + + LOG.unableToLoadConfiguration( configurationResourceName ); + } + return url; + } + + /** + * Default access-type used when the configured using JPA 2.0 config. JPA 2.0 allows @Cacheable(true) to be attached to an + * entity without any access type or usage qualification. + *

      + * We are conservative here in specifying {@link AccessType#READ_WRITE} so as to follow the mantra of "do no harm". + *

      + * This is a Hibernate 3.5 method. + */ + public AccessType getDefaultAccessType() { + return AccessType.READ_WRITE; + } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheMessageLogger.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheMessageLogger.java index c7fdc74ea2..dcceea5bfd 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheMessageLogger.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheMessageLogger.java @@ -37,45 +37,99 @@ import static org.jboss.logging.Logger.Level.WARN; *

      * New messages must be added after the last message defined to ensure message codes are unique. */ -@MessageLogger( projectCode = "HHH" ) +@MessageLogger(projectCode = "HHH") public interface EhCacheMessageLogger extends CoreMessageLogger { - @LogMessage( level = WARN ) - @Message( value = "Attempt to restart an already started EhCacheProvider. Use sessionFactory.close() between repeated calls to " - + "buildSessionFactory. Using previously created EhCacheProvider. If this behaviour is required, consider " - + "using net.sf.ehcache.hibernate.SingletonEhCacheProvider.", id = 20001 ) - void attemptToRestartAlreadyStartedEhCacheProvider(); + /** + * Log a message (WARN) about attempt to start an already started Ehcache region factory + */ + @LogMessage(level = WARN) + @Message( + value = "Attempt to restart an already started EhCacheRegionFactory. Use sessionFactory.close() between " + + "repeated calls to buildSessionFactory. Using previously created EhCacheRegionFactory. If this " + + "behaviour is required, consider using org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory.", + id = 20001 + ) + void attemptToRestartAlreadyStartedEhCacheProvider(); - @LogMessage( level = WARN ) - @Message( value = "Could not find configuration [%s]; using defaults.", id = 20002 ) - void unableToFindConfiguration( String name ); + /** + * Log a message (WARN) about inability to find configuration file + * + * @param name The name of the configuration file + */ + @LogMessage(level = WARN) + @Message(value = "Could not find configuration [%s]; using defaults.", id = 20002) + void unableToFindConfiguration(String name); - @LogMessage( level = WARN ) - @Message( value = "Could not find a specific ehcache configuration for cache named [%s]; using defaults.", id = 20003 ) - void unableToFindEhCacheConfiguration( String name ); + /** + * Log a message (WARN) about inability to find named cache configuration + * + * @param name The name of the cache configuration + */ + @LogMessage(level = WARN) + @Message(value = "Could not find a specific ehcache configuration for cache named [%s]; using defaults.", id = 20003) + void unableToFindEhCacheConfiguration(String name); - @LogMessage( level = WARN ) - @Message( value = "A configurationResourceName was set to %s but the resource could not be loaded from the classpath. Ehcache will configure itself using defaults.", id = 20004 ) - void unableToLoadConfiguration( String configurationResourceName ); + /** + * Logs a message about not being able to resolve the configuration by resource name. + * + * @param configurationResourceName The resource name we attempted to resolve + */ + @LogMessage(level = WARN) + @Message( + value = "A configurationResourceName was set to %s but the resource could not be loaded from the classpath. " + + "Ehcache will configure itself using defaults.", + id = 20004 + ) + void unableToLoadConfiguration(String configurationResourceName); - @LogMessage( level = WARN ) - @Message( value = "The default cache value mode for this Ehcache configuration is \"identity\". This is incompatible with clustered " - + "Hibernate caching - the value mode has therefore been switched to \"serialization\"", id = 20005 ) - void incompatibleCacheValueMode( ); + /** + * Logs a message (WARN) about attempt to use an incompatible + * {@link net.sf.ehcache.config.TerracottaConfiguration.ValueMode}. + */ + @LogMessage(level = WARN) + @Message( + value = "The default cache value mode for this Ehcache configuration is \"identity\". " + + "This is incompatible with clustered Hibernate caching - the value mode has therefore been " + + "switched to \"serialization\"", + id = 20005 + ) + void incompatibleCacheValueMode(); - @LogMessage( level = WARN ) - @Message( value = "The value mode for the cache[%s] is \"identity\". This is incompatible with clustered Hibernate caching - " - + "the value mode has therefore been switched to \"serialization\"", id = 20006 ) - void incompatibleCacheValueModePerCache( String cacheName ); - @LogMessage( level = WARN ) - @Message( value = "read-only cache configured for mutable entity [%s]", id = 20007 ) - void readOnlyCacheConfiguredForMutableEntity( String entityName ); + /** + * Logs a message (WARN) about attempt to use an incompatible + * {@link net.sf.ehcache.config.TerracottaConfiguration.ValueMode}. + * + * @param cacheName The name of the cache whose config attempted to specify value mode. + */ + @LogMessage(level = WARN) + @Message(value = "The value mode for the cache[%s] is \"identity\". This is incompatible with clustered Hibernate caching - " + + "the value mode has therefore been switched to \"serialization\"", id = 20006) + void incompatibleCacheValueModePerCache(String cacheName); - @LogMessage( level = WARN ) - @Message( value = "Cache[%s] Key[%s] Lockable[%s]\n" - + "A soft-locked cache entry was expired by the underlying Ehcache. " - + "If this happens regularly you should consider increasing the cache timeouts and/or capacity limits", id = 20008 ) - void softLockedCacheExpired( String regionName, Object key, String lock); + /** + * Log a message (WARN) about an attempt to specify read-only caching for a mutable entity + * + * @param entityName The name of the entity + */ + @LogMessage(level = WARN) + @Message(value = "read-only cache configured for mutable entity [%s]", id = 20007) + void readOnlyCacheConfiguredForMutableEntity(String entityName); + /** + * Log a message (WARN) about expiry of soft-locked region. + * + * @param regionName The region name + * @param key The cache key + * @param lock The lock + */ + @LogMessage(level = WARN) + @Message( + value = "Cache[%s] Key[%s] Lockable[%s]\n" + + "A soft-locked cache entry was expired by the underlying Ehcache. If this happens regularly you " + + "should consider increasing the cache timeouts and/or capacity limits", + id = 20008 + ) + void softLockedCacheExpired(String regionName, Object key, String lock); } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java index 2ec3a9d920..6b28b6ee25 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java @@ -30,10 +30,11 @@ import java.util.Properties; import net.sf.ehcache.CacheManager; import net.sf.ehcache.config.Configuration; import net.sf.ehcache.config.ConfigurationFactory; + import org.jboss.logging.Logger; import org.hibernate.cache.CacheException; -import org.hibernate.cache.ehcache.internal.util.HibernateUtil; +import org.hibernate.cache.ehcache.internal.util.HibernateEhcacheUtils; import org.hibernate.cfg.Settings; /** @@ -47,85 +48,88 @@ import org.hibernate.cfg.Settings; */ public class EhCacheRegionFactory extends AbstractEhcacheRegionFactory { - private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( - EhCacheMessageLogger.class, - EhCacheRegionFactory.class.getName() - ); + private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( + EhCacheMessageLogger.class, + EhCacheRegionFactory.class.getName() + ); - public EhCacheRegionFactory() { - } + /** + * Creates a non-singleton EhCacheRegionFactory + */ + @SuppressWarnings("UnusedDeclaration") + public EhCacheRegionFactory() { + } - /** - * Creates a non-singleton EhCacheRegionFactory - */ - public EhCacheRegionFactory(Properties prop) { - super(); - } + /** + * Creates a non-singleton EhCacheRegionFactory + * + * @param prop Not used + */ + @SuppressWarnings("UnusedDeclaration") + public EhCacheRegionFactory(Properties prop) { + super(); + } - /** - * {@inheritDoc} - */ - public void start(Settings settings, Properties properties) throws CacheException { - this.settings = settings; - if ( manager != null ) { - LOG.attemptToRestartAlreadyStartedEhCacheProvider(); - return; - } + @Override + public void start(Settings settings, Properties properties) throws CacheException { + this.settings = settings; + if ( manager != null ) { + LOG.attemptToRestartAlreadyStartedEhCacheProvider(); + return; + } - try { - String configurationResourceName = null; - if ( properties != null ) { - configurationResourceName = (String) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME ); - } - if ( configurationResourceName == null || configurationResourceName.length() == 0 ) { - Configuration configuration = ConfigurationFactory.parseConfiguration(); - manager = new CacheManager( configuration ); - } - else { - URL url; - try { - url = new URL( configurationResourceName ); - } - catch ( MalformedURLException e ) { - url = loadResource( configurationResourceName ); - } - Configuration configuration = HibernateUtil.loadAndCorrectConfiguration( url ); - manager = new CacheManager( configuration ); - } - mbeanRegistrationHelper.registerMBean( manager, properties ); - } - catch ( net.sf.ehcache.CacheException e ) { - if ( e.getMessage().startsWith( - "Cannot parseConfiguration CacheManager. Attempt to create a new instance of " + - "CacheManager using the diskStorePath" - ) ) { - throw new CacheException( - "Attempt to restart an already started EhCacheRegionFactory. " + - "Use sessionFactory.close() between repeated calls to buildSessionFactory. " + - "Consider using SingletonEhCacheRegionFactory. Error from ehcache was: " + e.getMessage() - ); - } - else { - throw new CacheException( e ); - } - } - } + try { + String configurationResourceName = null; + if ( properties != null ) { + configurationResourceName = (String) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME ); + } + if ( configurationResourceName == null || configurationResourceName.length() == 0 ) { + final Configuration configuration = ConfigurationFactory.parseConfiguration(); + manager = new CacheManager( configuration ); + } + else { + URL url; + try { + url = new URL( configurationResourceName ); + } + catch (MalformedURLException e) { + url = loadResource( configurationResourceName ); + } + final Configuration configuration = HibernateEhcacheUtils.loadAndCorrectConfiguration( url ); + manager = new CacheManager( configuration ); + } + mbeanRegistrationHelper.registerMBean( manager, properties ); + } + catch (net.sf.ehcache.CacheException e) { + if ( e.getMessage().startsWith( + "Cannot parseConfiguration CacheManager. Attempt to create a new instance of " + + "CacheManager using the diskStorePath" + ) ) { + throw new CacheException( + "Attempt to restart an already started EhCacheRegionFactory. " + + "Use sessionFactory.close() between repeated calls to buildSessionFactory. " + + "Consider using SingletonEhCacheRegionFactory. Error from ehcache was: " + e.getMessage() + ); + } + else { + throw new CacheException( e ); + } + } + } - /** - * {@inheritDoc} - */ - public void stop() { - try { - if ( manager != null ) { - mbeanRegistrationHelper.unregisterMBean(); - manager.shutdown(); - manager = null; - } - } - catch ( net.sf.ehcache.CacheException e ) { - throw new CacheException( e ); - } - } + @Override + public void stop() { + try { + if ( manager != null ) { + mbeanRegistrationHelper.unregisterMBean(); + manager.shutdown(); + manager = null; + } + } + catch (net.sf.ehcache.CacheException e) { + throw new CacheException( e ); + } + } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/SingletonEhCacheRegionFactory.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/SingletonEhCacheRegionFactory.java index fdf533cec8..d51774d263 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/SingletonEhCacheRegionFactory.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/SingletonEhCacheRegionFactory.java @@ -30,10 +30,11 @@ import java.util.concurrent.atomic.AtomicInteger; import net.sf.ehcache.CacheManager; import net.sf.ehcache.config.Configuration; + import org.jboss.logging.Logger; import org.hibernate.cache.CacheException; -import org.hibernate.cache.ehcache.internal.util.HibernateUtil; +import org.hibernate.cache.ehcache.internal.util.HibernateEhcacheUtils; import org.hibernate.cfg.Settings; /** @@ -45,75 +46,80 @@ import org.hibernate.cfg.Settings; * @author Alex Snaps */ public class SingletonEhCacheRegionFactory extends AbstractEhcacheRegionFactory { + private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( + EhCacheMessageLogger.class, + SingletonEhCacheRegionFactory.class.getName() + ); - private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( - EhCacheMessageLogger.class, - SingletonEhCacheRegionFactory.class.getName() - ); - private static final AtomicInteger REFERENCE_COUNT = new AtomicInteger(); + private static final AtomicInteger REFERENCE_COUNT = new AtomicInteger(); - /** - * Returns a representation of the singleton EhCacheRegionFactory - */ - public SingletonEhCacheRegionFactory(Properties prop) { - super(); - } + /** + * Constructs a SingletonEhCacheRegionFactory + */ + @SuppressWarnings("UnusedDeclaration") + public SingletonEhCacheRegionFactory() { + } - /** - * {@inheritDoc} - */ - public void start(Settings settings, Properties properties) throws CacheException { - this.settings = settings; - try { - String configurationResourceName = null; - if ( properties != null ) { - configurationResourceName = (String) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME ); - } - if ( configurationResourceName == null || configurationResourceName.length() == 0 ) { - manager = CacheManager.create(); - REFERENCE_COUNT.incrementAndGet(); - } - else { - URL url; - try { - url = new URL( configurationResourceName ); - } - catch ( MalformedURLException e ) { - if ( !configurationResourceName.startsWith( "/" ) ) { - configurationResourceName = "/" + configurationResourceName; - LOG.debugf( - "prepending / to %s. It should be placed in the root of the classpath rather than in a package.", - configurationResourceName - ); - } - url = loadResource( configurationResourceName ); - } - Configuration configuration = HibernateUtil.loadAndCorrectConfiguration( url ); - manager = CacheManager.create( configuration ); - REFERENCE_COUNT.incrementAndGet(); - } - mbeanRegistrationHelper.registerMBean( manager, properties ); - } - catch ( net.sf.ehcache.CacheException e ) { - throw new CacheException( e ); - } - } + /** + * Constructs a SingletonEhCacheRegionFactory + * + * @param prop Not used + */ + @SuppressWarnings("UnusedDeclaration") + public SingletonEhCacheRegionFactory(Properties prop) { + super(); + } - /** - * {@inheritDoc} - */ - public void stop() { - try { - if ( manager != null ) { - if ( REFERENCE_COUNT.decrementAndGet() == 0 ) { - manager.shutdown(); - } - manager = null; - } - } - catch ( net.sf.ehcache.CacheException e ) { - throw new CacheException( e ); - } - } + @Override + public void start(Settings settings, Properties properties) throws CacheException { + this.settings = settings; + try { + String configurationResourceName = null; + if ( properties != null ) { + configurationResourceName = (String) properties.get( NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME ); + } + if ( configurationResourceName == null || configurationResourceName.length() == 0 ) { + manager = CacheManager.create(); + REFERENCE_COUNT.incrementAndGet(); + } + else { + URL url; + try { + url = new URL( configurationResourceName ); + } + catch (MalformedURLException e) { + if ( !configurationResourceName.startsWith( "/" ) ) { + configurationResourceName = "/" + configurationResourceName; + LOG.debugf( + "prepending / to %s. It should be placed in the root of the classpath rather than in a package.", + configurationResourceName + ); + } + url = loadResource( configurationResourceName ); + } + final Configuration configuration = HibernateEhcacheUtils.loadAndCorrectConfiguration( url ); + manager = CacheManager.create( configuration ); + REFERENCE_COUNT.incrementAndGet(); + } + mbeanRegistrationHelper.registerMBean( manager, properties ); + } + catch (net.sf.ehcache.CacheException e) { + throw new CacheException( e ); + } + } + @Override + public void stop() { + try { + if ( manager != null ) { + if ( REFERENCE_COUNT.decrementAndGet() == 0 ) { + manager.shutdown(); + } + manager = null; + } + } + catch (net.sf.ehcache.CacheException e) { + throw new CacheException( e ); + } + } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/StrategyRegistrationProviderImpl.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/StrategyRegistrationProviderImpl.java index 617fa48472..3cedfe4f0a 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/StrategyRegistrationProviderImpl.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/StrategyRegistrationProviderImpl.java @@ -26,9 +26,9 @@ package org.hibernate.cache.ehcache; import java.util.ArrayList; import java.util.List; +import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl; import org.hibernate.boot.registry.selector.StrategyRegistration; import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; -import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl; import org.hibernate.cache.spi.RegionFactory; /** @@ -49,7 +49,8 @@ public class StrategyRegistrationProviderImpl implements StrategyRegistrationPro EhCacheRegionFactory.class, "ehcache", EhCacheRegionFactory.class.getSimpleName(), - "org.hibernate.cache.EhCacheRegionFactory" // legacy impl class name + // legacy impl class name + "org.hibernate.cache.EhCacheRegionFactory" ) ); @@ -59,7 +60,8 @@ public class StrategyRegistrationProviderImpl implements StrategyRegistrationPro SingletonEhCacheRegionFactory.class, "ehcache-singleton", SingletonEhCacheRegionFactory.class.getSimpleName(), - "org.hibernate.cache.SingletonEhCacheRegionFactory" // legacy impl class name + // legacy impl class name + "org.hibernate.cache.SingletonEhCacheRegionFactory" ) ); diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/HibernateNonstopCacheExceptionHandler.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/HibernateNonstopCacheExceptionHandler.java index af5b77a2e5..ebdf6da9de 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/HibernateNonstopCacheExceptionHandler.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/HibernateNonstopCacheExceptionHandler.java @@ -24,6 +24,7 @@ package org.hibernate.cache.ehcache.internal.nonstop; import net.sf.ehcache.constructs.nonstop.NonStopCacheException; + import org.jboss.logging.Logger; import org.hibernate.cache.ehcache.EhCacheMessageLogger; @@ -35,61 +36,61 @@ import org.hibernate.cache.ehcache.EhCacheMessageLogger; * @author Alex Snaps */ public final class HibernateNonstopCacheExceptionHandler { - /** - * Property name which set as "true" will throw exceptions on timeout with hibernate - */ - public static final String HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY = "ehcache.hibernate.propagateNonStopCacheException"; + /** + * Property name which set as "true" will throw exceptions on timeout with hibernate + */ + public static final String HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY = "ehcache.hibernate.propagateNonStopCacheException"; - /** - * Property name for logging the stack trace of the nonstop cache exception too. False by default - */ - public static final String HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY = "ehcache.hibernate.logNonStopCacheExceptionStackTrace"; + /** + * Property name for logging the stack trace of the nonstop cache exception too. False by default + */ + public static final String HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY = "ehcache.hibernate.logNonStopCacheExceptionStackTrace"; - private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( - EhCacheMessageLogger.class, - HibernateNonstopCacheExceptionHandler.class.getName() - ); - private static final HibernateNonstopCacheExceptionHandler INSTANCE = new HibernateNonstopCacheExceptionHandler(); + private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( + EhCacheMessageLogger.class, + HibernateNonstopCacheExceptionHandler.class.getName() + ); + private static final HibernateNonstopCacheExceptionHandler INSTANCE = new HibernateNonstopCacheExceptionHandler(); - /** - * private constructor - */ - private HibernateNonstopCacheExceptionHandler() { - // private - } + /** + * private constructor + */ + private HibernateNonstopCacheExceptionHandler() { + // private + } - /** - * Returns the singleton instance - * - * @return the singleton instance - */ - public static HibernateNonstopCacheExceptionHandler getInstance() { - return INSTANCE; - } + /** + * Returns the singleton instance + * + * @return the singleton instance + */ + public static HibernateNonstopCacheExceptionHandler getInstance() { + return INSTANCE; + } - /** - * Handle {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}. - * If {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY} system property is set to true, - * rethrows the {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}, otherwise logs the exception. While logging, if - * {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY} is set to true, logs the exception stack - * trace too, otherwise logs the exception message only - * - * @param nonStopCacheException - */ - public void handleNonstopCacheException(NonStopCacheException nonStopCacheException) { - if ( Boolean.getBoolean( HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY ) ) { - throw nonStopCacheException; - } - else { - if ( Boolean.getBoolean( HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY ) ) { - LOG.debug( - "Ignoring NonstopCacheException - " + nonStopCacheException.getMessage(), - nonStopCacheException - ); - } - else { - LOG.debug( "Ignoring NonstopCacheException - " + nonStopCacheException.getMessage() ); - } - } - } + /** + * Handle {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}. + * If {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY} system property is set to true, + * rethrows the {@link net.sf.ehcache.constructs.nonstop.NonStopCacheException}, otherwise logs the exception. While logging, if + * {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY} is set to true, logs the exception stack + * trace too, otherwise logs the exception message only + * + * @param nonStopCacheException The exception to handle + */ + public void handleNonstopCacheException(NonStopCacheException nonStopCacheException) { + if ( Boolean.getBoolean( HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY ) ) { + throw nonStopCacheException; + } + else { + if ( Boolean.getBoolean( HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY ) ) { + LOG.debug( + "Ignoring NonstopCacheException - " + nonStopCacheException.getMessage(), + nonStopCacheException + ); + } + else { + LOG.debug( "Ignoring NonstopCacheException - " + nonStopCacheException.getMessage() ); + } + } + } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAccessStrategyFactory.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAccessStrategyFactory.java index 93ab9c897c..b379584285 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAccessStrategyFactory.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAccessStrategyFactory.java @@ -41,49 +41,49 @@ import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy; */ public class NonstopAccessStrategyFactory implements EhcacheAccessStrategyFactory { - private final EhcacheAccessStrategyFactory actualFactory; - - /** - * Constructor accepting the actual factory - * - * @param actualFactory - */ - public NonstopAccessStrategyFactory(EhcacheAccessStrategyFactory actualFactory) { - this.actualFactory = actualFactory; - } - - /** - * {@inheritDoc} - */ - public EntityRegionAccessStrategy createEntityRegionAccessStrategy(EhcacheEntityRegion entityRegion, AccessType accessType) { - return new NonstopAwareEntityRegionAccessStrategy( - actualFactory.createEntityRegionAccessStrategy( entityRegion, accessType ), - HibernateNonstopCacheExceptionHandler.getInstance() - ); - } - - @Override - public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion naturalIdRegion, - AccessType accessType) { - return new NonstopAwareNaturalIdRegionAccessStrategy( - actualFactory.createNaturalIdRegionAccessStrategy( - naturalIdRegion, - accessType - ), HibernateNonstopCacheExceptionHandler.getInstance() - ); - } + private final EhcacheAccessStrategyFactory actualFactory; /** - * {@inheritDoc} - */ - public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(EhcacheCollectionRegion collectionRegion, - AccessType accessType) { - return new NonstopAwareCollectionRegionAccessStrategy( - actualFactory.createCollectionRegionAccessStrategy( - collectionRegion, - accessType - ), HibernateNonstopCacheExceptionHandler.getInstance() - ); - } + * Constructor accepting the actual factory + * + * @param actualFactory The wrapped RegionAccessStrategy factory + */ + public NonstopAccessStrategyFactory(EhcacheAccessStrategyFactory actualFactory) { + this.actualFactory = actualFactory; + } + + @Override + public EntityRegionAccessStrategy createEntityRegionAccessStrategy( + EhcacheEntityRegion entityRegion, + AccessType accessType) { + return new NonstopAwareEntityRegionAccessStrategy( + actualFactory.createEntityRegionAccessStrategy( entityRegion, accessType ), + HibernateNonstopCacheExceptionHandler.getInstance() + ); + } + + @Override + public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy( + EhcacheNaturalIdRegion naturalIdRegion, + AccessType accessType) { + return new NonstopAwareNaturalIdRegionAccessStrategy( + actualFactory.createNaturalIdRegionAccessStrategy( + naturalIdRegion, + accessType + ), HibernateNonstopCacheExceptionHandler.getInstance() + ); + } + + @Override + public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy( + EhcacheCollectionRegion collectionRegion, + AccessType accessType) { + return new NonstopAwareCollectionRegionAccessStrategy( + actualFactory.createCollectionRegionAccessStrategy( + collectionRegion, + accessType + ), HibernateNonstopCacheExceptionHandler.getInstance() + ); + } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareCollectionRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareCollectionRegionAccessStrategy.java index 3f1f2cc1db..fdd82bd9cf 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareCollectionRegionAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareCollectionRegionAccessStrategy.java @@ -38,188 +38,139 @@ import org.hibernate.cache.spi.access.SoftLock; * @author Alex Snaps */ public class NonstopAwareCollectionRegionAccessStrategy implements CollectionRegionAccessStrategy { - private final CollectionRegionAccessStrategy actualStrategy; private final HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler; /** * Constructor accepting the actual {@link CollectionRegionAccessStrategy} and the {@link HibernateNonstopCacheExceptionHandler} * - * @param actualStrategy - * @param hibernateNonstopExceptionHandler + * @param actualStrategy The wrapped strategy + * @param hibernateNonstopExceptionHandler The exception handler */ - public NonstopAwareCollectionRegionAccessStrategy(CollectionRegionAccessStrategy actualStrategy, - HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) { + public NonstopAwareCollectionRegionAccessStrategy( + CollectionRegionAccessStrategy actualStrategy, + HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) { this.actualStrategy = actualStrategy; this.hibernateNonstopExceptionHandler = hibernateNonstopExceptionHandler; } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#getRegion() - */ + @Override public CollectionRegion getRegion() { return actualStrategy.getRegion(); } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evict(java.lang.Object) - */ + @Override public void evict(Object key) throws CacheException { try { actualStrategy.evict( key ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evictAll() - */ + @Override public void evictAll() throws CacheException { try { actualStrategy.evictAll(); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long) - */ + @Override public Object get(Object key, long txTimestamp) throws CacheException { try { return actualStrategy.get( key, txTimestamp ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return null; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object) - */ + @Override public SoftLock lockItem(Object key, Object version) throws CacheException { try { return actualStrategy.lockItem( key, version ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return null; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockRegion() - */ + @Override public SoftLock lockRegion() throws CacheException { try { return actualStrategy.lockRegion(); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return null; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, - * boolean) - */ + @Override public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { try { return actualStrategy.putFromLoad( key, value, txTimestamp, version, minimalPutOverride ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return false; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object) - */ + @Override public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException { try { return actualStrategy.putFromLoad( key, value, txTimestamp, version ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return false; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#remove(java.lang.Object) - */ + @Override public void remove(Object key) throws CacheException { try { actualStrategy.remove( key ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#removeAll() - */ + @Override public void removeAll() throws CacheException { try { actualStrategy.removeAll(); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock) - */ + @Override public void unlockItem(Object key, SoftLock lock) throws CacheException { try { actualStrategy.unlockItem( key, lock ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockRegion(org.hibernate.cache.spi.access.SoftLock) - */ + @Override public void unlockRegion(SoftLock lock) throws CacheException { try { actualStrategy.unlockRegion( lock ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareEntityRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareEntityRegionAccessStrategy.java index 45f26270d0..e755bd0f28 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareEntityRegionAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareEntityRegionAccessStrategy.java @@ -38,253 +38,186 @@ import org.hibernate.cache.spi.access.SoftLock; * @author Alex Snaps */ public class NonstopAwareEntityRegionAccessStrategy implements EntityRegionAccessStrategy { - private final EntityRegionAccessStrategy actualStrategy; private final HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler; /** * Constructor accepting the actual {@link EntityRegionAccessStrategy} and the {@link HibernateNonstopCacheExceptionHandler} * - * @param actualStrategy - * @param hibernateNonstopExceptionHandler + * @param actualStrategy The wrapped EntityRegionAccessStrategy + * @param hibernateNonstopExceptionHandler The exception handler */ - public NonstopAwareEntityRegionAccessStrategy(EntityRegionAccessStrategy actualStrategy, - HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) { + public NonstopAwareEntityRegionAccessStrategy( + EntityRegionAccessStrategy actualStrategy, + HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) { this.actualStrategy = actualStrategy; this.hibernateNonstopExceptionHandler = hibernateNonstopExceptionHandler; } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#getRegion() - */ + @Override public EntityRegion getRegion() { return actualStrategy.getRegion(); } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#afterInsert(java.lang.Object, java.lang.Object, java.lang.Object) - */ + @Override public boolean afterInsert(Object key, Object value, Object version) throws CacheException { try { return actualStrategy.afterInsert( key, value, version ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return false; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#afterUpdate(java.lang.Object, java.lang.Object, java.lang.Object, - * java.lang.Object, org.hibernate.cache.spi.access.SoftLock) - */ + @Override public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) throws CacheException { try { return actualStrategy.afterUpdate( key, value, currentVersion, previousVersion, lock ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return false; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evict(java.lang.Object) - */ + @Override public void evict(Object key) throws CacheException { try { actualStrategy.evict( key ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evictAll() - */ + @Override public void evictAll() throws CacheException { try { actualStrategy.evictAll(); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long) - */ + @Override public Object get(Object key, long txTimestamp) throws CacheException { try { return actualStrategy.get( key, txTimestamp ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return null; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#insert(java.lang.Object, java.lang.Object, java.lang.Object) - */ + @Override public boolean insert(Object key, Object value, Object version) throws CacheException { try { return actualStrategy.insert( key, value, version ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return false; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object) - */ + @Override public SoftLock lockItem(Object key, Object version) throws CacheException { try { return actualStrategy.lockItem( key, version ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return null; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockRegion() - */ + @Override public SoftLock lockRegion() throws CacheException { try { return actualStrategy.lockRegion(); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return null; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, - * boolean) - */ + @Override public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { try { return actualStrategy.putFromLoad( key, value, txTimestamp, version, minimalPutOverride ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return false; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object) - */ + @Override public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException { try { return actualStrategy.putFromLoad( key, value, txTimestamp, version ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return false; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#remove(java.lang.Object) - */ + @Override public void remove(Object key) throws CacheException { try { actualStrategy.remove( key ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#removeAll() - */ + @Override public void removeAll() throws CacheException { try { actualStrategy.removeAll(); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock) - */ + @Override public void unlockItem(Object key, SoftLock lock) throws CacheException { try { actualStrategy.unlockItem( key, lock ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockRegion(org.hibernate.cache.spi.access.SoftLock) - */ + @Override public void unlockRegion(SoftLock lock) throws CacheException { try { actualStrategy.unlockRegion( lock ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#update(java.lang.Object, java.lang.Object, java.lang.Object, - * java.lang.Object) - */ + @Override public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { try { return actualStrategy.update( key, value, currentVersion, previousVersion ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return false; } } -} \ No newline at end of file +} diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareNaturalIdRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareNaturalIdRegionAccessStrategy.java index 45e8498d5b..b50d6b1e20 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareNaturalIdRegionAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/NonstopAwareNaturalIdRegionAccessStrategy.java @@ -38,28 +38,28 @@ import org.hibernate.cache.spi.access.SoftLock; * @author Alex Snaps */ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegionAccessStrategy { - private final NaturalIdRegionAccessStrategy actualStrategy; private final HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler; /** * Constructor accepting the actual {@link NaturalIdRegionAccessStrategy} and the {@link HibernateNonstopCacheExceptionHandler} * - * @param actualStrategy - * @param hibernateNonstopExceptionHandler + * @param actualStrategy The wrapped NaturalIdRegionAccessStrategy + * @param hibernateNonstopExceptionHandler The exception handler */ - public NonstopAwareNaturalIdRegionAccessStrategy(NaturalIdRegionAccessStrategy actualStrategy, - HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) { + public NonstopAwareNaturalIdRegionAccessStrategy( + NaturalIdRegionAccessStrategy actualStrategy, + HibernateNonstopCacheExceptionHandler hibernateNonstopExceptionHandler) { this.actualStrategy = actualStrategy; this.hibernateNonstopExceptionHandler = hibernateNonstopExceptionHandler; } - + @Override public boolean insert(Object key, Object value) throws CacheException { try { return actualStrategy.insert( key, value ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return false; } @@ -70,7 +70,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio try { return actualStrategy.afterInsert( key, value ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return false; } @@ -81,7 +81,7 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio try { return actualStrategy.update( key, value ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return false; } @@ -92,178 +92,129 @@ public class NonstopAwareNaturalIdRegionAccessStrategy implements NaturalIdRegio try { return actualStrategy.afterUpdate( key, value, lock ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return false; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#getRegion() - */ + @Override public NaturalIdRegion getRegion() { return actualStrategy.getRegion(); } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evict(java.lang.Object) - */ + @Override public void evict(Object key) throws CacheException { try { actualStrategy.evict( key ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#evictAll() - */ + @Override public void evictAll() throws CacheException { try { actualStrategy.evictAll(); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long) - */ + @Override public Object get(Object key, long txTimestamp) throws CacheException { try { return actualStrategy.get( key, txTimestamp ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return null; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object) - */ + @Override public SoftLock lockItem(Object key, Object version) throws CacheException { try { return actualStrategy.lockItem( key, version ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return null; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockRegion() - */ + @Override public SoftLock lockRegion() throws CacheException { try { return actualStrategy.lockRegion(); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return null; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, - * boolean) - */ + @Override public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { try { return actualStrategy.putFromLoad( key, value, txTimestamp, version, minimalPutOverride ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return false; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object) - */ + @Override public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException { try { return actualStrategy.putFromLoad( key, value, txTimestamp, version ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); return false; } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#remove(java.lang.Object) - */ + @Override public void remove(Object key) throws CacheException { try { actualStrategy.remove( key ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#removeAll() - */ + @Override public void removeAll() throws CacheException { try { actualStrategy.removeAll(); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock) - */ + @Override public void unlockItem(Object key, SoftLock lock) throws CacheException { try { actualStrategy.unlockItem( key, lock ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } - /** - * {@inheritDoc} - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockRegion(org.hibernate.cache.spi.access.SoftLock) - */ + @Override public void unlockRegion(SoftLock lock) throws CacheException { try { actualStrategy.unlockRegion( lock ); } - catch ( NonStopCacheException nonStopCacheException ) { + catch (NonStopCacheException nonStopCacheException) { hibernateNonstopExceptionHandler.handleNonstopCacheException( nonStopCacheException ); } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/package-info.java new file mode 100644 index 0000000000..1115173682 --- /dev/null +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/nonstop/package-info.java @@ -0,0 +1,5 @@ +/** + * Support for handling non-stop caches. Really no idea. The Ehcache guys added this and tbh I really do not + * understand the intent + */ +package org.hibernate.cache.ehcache.internal.nonstop; diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheCollectionRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheCollectionRegion.java index d1fc60b8cf..e694bbebea 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheCollectionRegion.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheCollectionRegion.java @@ -47,22 +47,26 @@ import org.hibernate.cfg.Settings; * @author Alex Snaps */ public class EhcacheCollectionRegion extends EhcacheTransactionalDataRegion implements CollectionRegion { + /** + * Constructs an EhcacheCollectionRegion around the given underlying cache. + * + * @param accessStrategyFactory The factory for building needed CollectionRegionAccessStrategy instance + * @param underlyingCache The ehcache cache instance + * @param settings The Hibernate settings + * @param metadata Metadata about the data to be cached in this region + * @param properties Any additional[ properties + */ + public EhcacheCollectionRegion( + EhcacheAccessStrategyFactory accessStrategyFactory, + Ehcache underlyingCache, + Settings settings, + CacheDataDescription metadata, + Properties properties) { + super( accessStrategyFactory, underlyingCache, settings, metadata, properties ); + } - - /** - * Constructs an EhcacheCollectionRegion around the given underlying cache. - * - * @param accessStrategyFactory - */ - public EhcacheCollectionRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Settings settings, - CacheDataDescription metadata, Properties properties) { - super( accessStrategyFactory, underlyingCache, settings, metadata, properties ); - } - - /** - * {@inheritDoc} - */ - public CollectionRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { - return accessStrategyFactory.createCollectionRegionAccessStrategy( this, accessType ); - } -} \ No newline at end of file + @Override + public CollectionRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { + return getAccessStrategyFactory().createCollectionRegionAccessStrategy( this, accessType ); + } +} diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheDataRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheDataRegion.java index dfab454bf9..6f86f13ce7 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheDataRegion.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheDataRegion.java @@ -32,6 +32,7 @@ import java.util.Properties; import net.sf.ehcache.Ehcache; import net.sf.ehcache.constructs.nonstop.NonStopCacheException; import net.sf.ehcache.util.Timestamper; + import org.jboss.logging.Logger; import org.hibernate.cache.CacheException; @@ -52,174 +53,163 @@ import org.hibernate.cache.spi.Region; * @author Alex Snaps */ public abstract class EhcacheDataRegion implements Region { + private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( + EhCacheMessageLogger.class, + EhcacheDataRegion.class.getName() + ); + private static final String CACHE_LOCK_TIMEOUT_PROPERTY = "net.sf.ehcache.hibernate.cache_lock_timeout"; + private static final int DEFAULT_CACHE_LOCK_TIMEOUT = 60000; - private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( - EhCacheMessageLogger.class, - EhcacheDataRegion.class.getName() - ); - private static final String CACHE_LOCK_TIMEOUT_PROPERTY = "net.sf.ehcache.hibernate.cache_lock_timeout"; - private static final int DEFAULT_CACHE_LOCK_TIMEOUT = 60000; - - /** - * Ehcache instance backing this Hibernate data region. - */ - protected final Ehcache cache; - - /** - * The {@link EhcacheAccessStrategyFactory} used for creating various access strategies - */ - protected final EhcacheAccessStrategyFactory accessStrategyFactory; - - private final int cacheLockTimeout; + private final Ehcache cache; + private final EhcacheAccessStrategyFactory accessStrategyFactory; + private final int cacheLockTimeout; - /** - * Create a Hibernate data region backed by the given Ehcache instance. - */ - EhcacheDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Properties properties) { - this.accessStrategyFactory = accessStrategyFactory; - this.cache = cache; - String timeout = properties.getProperty( - CACHE_LOCK_TIMEOUT_PROPERTY, - Integer.toString( DEFAULT_CACHE_LOCK_TIMEOUT ) - ); - this.cacheLockTimeout = Timestamper.ONE_MS * Integer.decode( timeout ); - } + /** + * Create a Hibernate data region backed by the given Ehcache instance. + */ + EhcacheDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Properties properties) { + this.accessStrategyFactory = accessStrategyFactory; + this.cache = cache; + final String timeout = properties.getProperty( + CACHE_LOCK_TIMEOUT_PROPERTY, + Integer.toString( DEFAULT_CACHE_LOCK_TIMEOUT ) + ); + this.cacheLockTimeout = Timestamper.ONE_MS * Integer.decode( timeout ); + } - /** - * {@inheritDoc} - */ - public String getName() { - return cache.getName(); - } + /** + * Ehcache instance backing this Hibernate data region. + */ + protected Ehcache getCache() { + return cache; + } - /** - * {@inheritDoc} - */ - public void destroy() throws CacheException { - try { - cache.getCacheManager().removeCache( cache.getName() ); - } - catch ( IllegalStateException e ) { - //When Spring and Hibernate are both involved this will happen in normal shutdown operation. - //Do not throw an exception, simply log this one. - LOG.debug( "This can happen if multiple frameworks both try to shutdown ehcache", e ); - } - catch ( net.sf.ehcache.CacheException e ) { - if ( e instanceof NonStopCacheException ) { - HibernateNonstopCacheExceptionHandler.getInstance() - .handleNonstopCacheException( (NonStopCacheException) e ); - } - else { - throw new CacheException( e ); - } - } - } + /** + * The {@link org.hibernate.cache.ehcache.internal.strategy.EhcacheAccessStrategyFactory} used for creating + * various access strategies + */ + protected EhcacheAccessStrategyFactory getAccessStrategyFactory() { + return accessStrategyFactory; + } - /** - * {@inheritDoc} - */ - public long getSizeInMemory() { - try { - return cache.calculateInMemorySize(); - } - catch ( Throwable t ) { - if ( t instanceof NonStopCacheException ) { - HibernateNonstopCacheExceptionHandler.getInstance() - .handleNonstopCacheException( (NonStopCacheException) t ); - } - return -1; - } - } + /** + * Return the Ehcache instance backing this Hibernate data region. + * + * @return The underlying ehcache cache + */ + public Ehcache getEhcache() { + return getCache(); + } - /** - * {@inheritDoc} - */ - public long getElementCountInMemory() { - try { - return cache.getMemoryStoreSize(); - } - catch ( net.sf.ehcache.CacheException ce ) { - if ( ce instanceof NonStopCacheException ) { - HibernateNonstopCacheExceptionHandler.getInstance() - .handleNonstopCacheException( (NonStopCacheException) ce ); - return -1; - } - else { - throw new CacheException( ce ); - } - } - } + @Override + public String getName() { + return getCache().getName(); + } - /** - * {@inheritDoc} - */ - public long getElementCountOnDisk() { - try { - return cache.getDiskStoreSize(); - } - catch ( net.sf.ehcache.CacheException ce ) { - if ( ce instanceof NonStopCacheException ) { - HibernateNonstopCacheExceptionHandler.getInstance() - .handleNonstopCacheException( (NonStopCacheException) ce ); - return -1; - } - else { - throw new CacheException( ce ); - } - } - } + @Override + public void destroy() throws CacheException { + try { + getCache().getCacheManager().removeCache( getCache().getName() ); + } + catch (IllegalStateException e) { + //When Spring and Hibernate are both involved this will happen in normal shutdown operation. + //Do not throw an exception, simply log this one. + LOG.debug( "This can happen if multiple frameworks both try to shutdown ehcache", e ); + } + catch (net.sf.ehcache.CacheException e) { + if ( e instanceof NonStopCacheException ) { + HibernateNonstopCacheExceptionHandler.getInstance() + .handleNonstopCacheException( (NonStopCacheException) e ); + } + else { + throw new CacheException( e ); + } + } + } - /** - * {@inheritDoc} - */ - public Map toMap() { - try { - Map result = new HashMap(); - for ( Object key : cache.getKeys() ) { - result.put( key, cache.get( key ).getObjectValue() ); - } - return result; - } - catch ( Exception e ) { - if ( e instanceof NonStopCacheException ) { - HibernateNonstopCacheExceptionHandler.getInstance() - .handleNonstopCacheException( (NonStopCacheException) e ); - return Collections.emptyMap(); - } - else { - throw new CacheException( e ); - } - } - } + @Override + public long getSizeInMemory() { + try { + return getCache().calculateInMemorySize(); + } + catch (Throwable t) { + if ( t instanceof NonStopCacheException ) { + HibernateNonstopCacheExceptionHandler.getInstance() + .handleNonstopCacheException( (NonStopCacheException) t ); + } + return -1; + } + } - /** - * {@inheritDoc} - */ - public long nextTimestamp() { - return Timestamper.next(); - } + @Override + public long getElementCountInMemory() { + try { + return getCache().getMemoryStoreSize(); + } + catch (net.sf.ehcache.CacheException ce) { + if ( ce instanceof NonStopCacheException ) { + HibernateNonstopCacheExceptionHandler.getInstance() + .handleNonstopCacheException( (NonStopCacheException) ce ); + return -1; + } + else { + throw new CacheException( ce ); + } + } + } - /** - * {@inheritDoc} - */ - public int getTimeout() { - return cacheLockTimeout; - } + @Override + public long getElementCountOnDisk() { + try { + return getCache().getDiskStoreSize(); + } + catch (net.sf.ehcache.CacheException ce) { + if ( ce instanceof NonStopCacheException ) { + HibernateNonstopCacheExceptionHandler.getInstance() + .handleNonstopCacheException( (NonStopCacheException) ce ); + return -1; + } + else { + throw new CacheException( ce ); + } + } + } - /** - * Return the Ehcache instance backing this Hibernate data region. - */ - public Ehcache getEhcache() { - return cache; - } + @Override + public Map toMap() { + try { + final Map result = new HashMap(); + for ( Object key : getCache().getKeys() ) { + result.put( key, getCache().get( key ).getObjectValue() ); + } + return result; + } + catch (Exception e) { + if ( e instanceof NonStopCacheException ) { + HibernateNonstopCacheExceptionHandler.getInstance() + .handleNonstopCacheException( (NonStopCacheException) e ); + return Collections.emptyMap(); + } + else { + throw new CacheException( e ); + } + } + } + + @Override + public long nextTimestamp() { + return Timestamper.next(); + } + + @Override + public int getTimeout() { + return cacheLockTimeout; + } + + @Override + public boolean contains(Object key) { + return getCache().isKeyInCache( key ); + } - /** - * Returns true if this region contains data for the given key. - *

      - * This is a Hibernate 3.5 method. - */ - public boolean contains(Object key) { - return cache.isKeyInCache( key ); - } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheEntityRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheEntityRegion.java index 4092c387ea..5423950d03 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheEntityRegion.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheEntityRegion.java @@ -46,22 +46,26 @@ import org.hibernate.cfg.Settings; * @author Alex Snaps */ public class EhcacheEntityRegion extends EhcacheTransactionalDataRegion implements EntityRegion { + /** + * Constructs an EhcacheCollectionRegion around the given underlying cache. + * + * @param accessStrategyFactory The factory for building needed EntityRegionAccessStrategy instance + * @param underlyingCache The ehcache cache instance + * @param settings The Hibernate settings + * @param metadata Metadata about the data to be cached in this region + * @param properties Any additional[ properties + */ + public EhcacheEntityRegion( + EhcacheAccessStrategyFactory accessStrategyFactory, + Ehcache underlyingCache, + Settings settings, + CacheDataDescription metadata, + Properties properties) { + super( accessStrategyFactory, underlyingCache, settings, metadata, properties ); + } - - /** - * Constructs an EhcacheEntityRegion around the given underlying cache. - * - * @param accessStrategyFactory - */ - public EhcacheEntityRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Settings settings, - CacheDataDescription metadata, Properties properties) { - super( accessStrategyFactory, underlyingCache, settings, metadata, properties ); - } - - /** - * {@inheritDoc} - */ - public EntityRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { - return accessStrategyFactory.createEntityRegionAccessStrategy( this, accessType ); - } -} \ No newline at end of file + @Override + public EntityRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { + return getAccessStrategyFactory().createEntityRegionAccessStrategy( this, accessType ); + } +} diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheGeneralDataRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheGeneralDataRegion.java index 8af54afb93..79bbbdeaa4 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheGeneralDataRegion.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheGeneralDataRegion.java @@ -28,6 +28,7 @@ import java.util.Properties; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; import net.sf.ehcache.constructs.nonstop.NonStopCacheException; + import org.jboss.logging.Logger; import org.hibernate.cache.CacheException; @@ -48,119 +49,117 @@ import org.hibernate.cache.spi.GeneralDataRegion; * @author Alex Snaps */ abstract class EhcacheGeneralDataRegion extends EhcacheDataRegion implements GeneralDataRegion { + private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( + EhCacheMessageLogger.class, + EhcacheGeneralDataRegion.class.getName() + ); - private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( - EhCacheMessageLogger.class, - EhcacheGeneralDataRegion.class.getName() - ); + /** + * Constructs an EhcacheGeneralDataRegion around the given underlying cache. + * + * @param accessStrategyFactory The factory for building needed RegionAccessStrategy instance + * @param underlyingCache The ehcache cache instance + * @param properties Any additional[ properties + */ + public EhcacheGeneralDataRegion( + EhcacheAccessStrategyFactory accessStrategyFactory, + Ehcache underlyingCache, + Properties properties) { + super( accessStrategyFactory, underlyingCache, properties ); + } - /** - * Creates an EhcacheGeneralDataRegion using the given Ehcache instance as a backing. - */ - public EhcacheGeneralDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Properties properties) { - super( accessStrategyFactory, cache, properties ); - } + @Override + public Object get(Object key) throws CacheException { + try { + LOG.debugf( "key: %s", key ); + if ( key == null ) { + return null; + } + else { + final Element element = getCache().get( key ); + if ( element == null ) { + LOG.debugf( "Element for key %s is null", key ); + return null; + } + else { + return element.getObjectValue(); + } + } + } + catch (net.sf.ehcache.CacheException e) { + if ( e instanceof NonStopCacheException ) { + HibernateNonstopCacheExceptionHandler.getInstance() + .handleNonstopCacheException( (NonStopCacheException) e ); + return null; + } + else { + throw new CacheException( e ); + } + } + } - /** - * {@inheritDoc} - */ - public Object get(Object key) throws CacheException { - try { - LOG.debugf( "key: %s", key ); - if ( key == null ) { - return null; - } - else { - Element element = cache.get( key ); - if ( element == null ) { - LOG.debugf( "Element for key %s is null", key ); - return null; - } - else { - return element.getObjectValue(); - } - } - } - catch ( net.sf.ehcache.CacheException e ) { - if ( e instanceof NonStopCacheException ) { - HibernateNonstopCacheExceptionHandler.getInstance() - .handleNonstopCacheException( (NonStopCacheException) e ); - return null; - } - else { - throw new CacheException( e ); - } - } - } + @Override + public void put(Object key, Object value) throws CacheException { + LOG.debugf( "key: %s value: %s", key, value ); + try { + final Element element = new Element( key, value ); + getCache().put( element ); + } + catch (IllegalArgumentException e) { + throw new CacheException( e ); + } + catch (IllegalStateException e) { + throw new CacheException( e ); + } + catch (net.sf.ehcache.CacheException e) { + if ( e instanceof NonStopCacheException ) { + HibernateNonstopCacheExceptionHandler.getInstance() + .handleNonstopCacheException( (NonStopCacheException) e ); + } + else { + throw new CacheException( e ); + } + } + } - /** - * {@inheritDoc} - */ - public void put(Object key, Object value) throws CacheException { - LOG.debugf( "key: %s value: %s", key, value ); - try { - Element element = new Element( key, value ); - cache.put( element ); - } - catch ( IllegalArgumentException e ) { - throw new CacheException( e ); - } - catch ( IllegalStateException e ) { - throw new CacheException( e ); - } - catch ( net.sf.ehcache.CacheException e ) { - if ( e instanceof NonStopCacheException ) { - HibernateNonstopCacheExceptionHandler.getInstance() - .handleNonstopCacheException( (NonStopCacheException) e ); - } - else { - throw new CacheException( e ); - } - } - } + @Override + public void evict(Object key) throws CacheException { + try { + getCache().remove( key ); + } + catch (ClassCastException e) { + throw new CacheException( e ); + } + catch (IllegalStateException e) { + throw new CacheException( e ); + } + catch (net.sf.ehcache.CacheException e) { + if ( e instanceof NonStopCacheException ) { + HibernateNonstopCacheExceptionHandler.getInstance() + .handleNonstopCacheException( (NonStopCacheException) e ); + } + else { + throw new CacheException( e ); + } + } + } - /** - * {@inheritDoc} - */ - public void evict(Object key) throws CacheException { - try { - cache.remove( key ); - } - catch ( ClassCastException e ) { - throw new CacheException( e ); - } - catch ( IllegalStateException e ) { - throw new CacheException( e ); - } - catch ( net.sf.ehcache.CacheException e ) { - if ( e instanceof NonStopCacheException ) { - HibernateNonstopCacheExceptionHandler.getInstance() - .handleNonstopCacheException( (NonStopCacheException) e ); - } - else { - throw new CacheException( e ); - } - } - } - - /** - * {@inheritDoc} - */ - public void evictAll() throws CacheException { - try { - cache.removeAll(); - } - catch ( IllegalStateException e ) { - throw new CacheException( e ); - } - catch ( net.sf.ehcache.CacheException e ) { - if ( e instanceof NonStopCacheException ) { - HibernateNonstopCacheExceptionHandler.getInstance() - .handleNonstopCacheException( (NonStopCacheException) e ); - } - else { - throw new CacheException( e ); - } - } - } + @Override + public void evictAll() throws CacheException { + try { + getCache().removeAll(); + } + catch (IllegalStateException e) { + throw new CacheException( e ); + } + catch (net.sf.ehcache.CacheException e) { + if ( e instanceof NonStopCacheException ) { + HibernateNonstopCacheExceptionHandler.getInstance() + .handleNonstopCacheException( (NonStopCacheException) e ); + } + else { + throw new CacheException( e ); + } + } + } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheNaturalIdRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheNaturalIdRegion.java index 92d7c9d227..ab3b03b224 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheNaturalIdRegion.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheNaturalIdRegion.java @@ -47,20 +47,26 @@ import org.hibernate.cfg.Settings; * @author Alex Snaps */ public class EhcacheNaturalIdRegion extends EhcacheTransactionalDataRegion implements NaturalIdRegion { - - - /** - * Constructs an EhcacheNaturalIdRegion around the given underlying cache. - * - * @param accessStrategyFactory - */ - public EhcacheNaturalIdRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Settings settings, - CacheDataDescription metadata, Properties properties) { - super( accessStrategyFactory, underlyingCache, settings, metadata, properties ); - } + /** + * Constructs an EhcacheNaturalIdRegion around the given underlying cache. + * + * @param accessStrategyFactory The factory for building needed NaturalIdRegionAccessStrategy instance + * @param underlyingCache The ehcache cache instance + * @param settings The Hibernate settings + * @param metadata Metadata about the data to be cached in this region + * @param properties Any additional[ properties + */ + public EhcacheNaturalIdRegion( + EhcacheAccessStrategyFactory accessStrategyFactory, + Ehcache underlyingCache, + Settings settings, + CacheDataDescription metadata, + Properties properties) { + super( accessStrategyFactory, underlyingCache, settings, metadata, properties ); + } @Override public NaturalIdRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { - return accessStrategyFactory.createNaturalIdRegionAccessStrategy( this, accessType ); + return getAccessStrategyFactory().createNaturalIdRegionAccessStrategy( this, accessType ); } -} \ No newline at end of file +} diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheQueryResultsRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheQueryResultsRegion.java index f7952f98db..5305af419a 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheQueryResultsRegion.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheQueryResultsRegion.java @@ -37,14 +37,18 @@ import org.hibernate.cache.spi.QueryResultsRegion; * @author Alex Snaps */ public class EhcacheQueryResultsRegion extends EhcacheGeneralDataRegion implements QueryResultsRegion { - /** * Constructs an EhcacheQueryResultsRegion around the given underlying cache. * - * @param accessStrategyFactory + * @param accessStrategyFactory The factory for building needed CollectionRegionAccessStrategy instance + * @param underlyingCache The ehcache cache instance + * @param properties Any additional[ properties */ - public EhcacheQueryResultsRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Properties properties) { + public EhcacheQueryResultsRegion( + EhcacheAccessStrategyFactory accessStrategyFactory, + Ehcache underlyingCache, + Properties properties) { super( accessStrategyFactory, underlyingCache, properties ); } -} \ No newline at end of file +} diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTimestampsRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTimestampsRegion.java index bbc87dfd00..cc3316853e 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTimestampsRegion.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTimestampsRegion.java @@ -38,13 +38,17 @@ import org.hibernate.cache.spi.TimestampsRegion; * @author Alex Snaps */ public class EhcacheTimestampsRegion extends EhcacheGeneralDataRegion implements TimestampsRegion { - /** * Constructs an EhcacheTimestampsRegion around the given underlying cache. * - * @param accessStrategyFactory + * @param accessStrategyFactory The factory for building needed CollectionRegionAccessStrategy instance + * @param underlyingCache The ehcache cache instance + * @param properties Any additional[ properties */ - public EhcacheTimestampsRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Properties properties) { - super(accessStrategyFactory, underlyingCache, properties); + public EhcacheTimestampsRegion( + EhcacheAccessStrategyFactory accessStrategyFactory, + Ehcache underlyingCache, + Properties properties) { + super( accessStrategyFactory, underlyingCache, properties ); } -} \ No newline at end of file +} diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTransactionalDataRegion.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTransactionalDataRegion.java index 60f4e92c9e..d46513cbe6 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTransactionalDataRegion.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/EhcacheTransactionalDataRegion.java @@ -51,13 +51,9 @@ import org.hibernate.cfg.Settings; * @author Alex Snaps */ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements TransactionalDataRegion { - private static final int LOCAL_LOCK_PROVIDER_CONCURRENCY = 128; - /** - * Hibernate settings associated with the persistence unit. - */ - protected final Settings settings; + private final Settings settings; /** * Metadata associated with the objects stored in the region. @@ -69,13 +65,14 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements /** * Construct an transactional Hibernate cache region around the given Ehcache instance. */ - EhcacheTransactionalDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Settings settings, - CacheDataDescription metadata, Properties properties) { + EhcacheTransactionalDataRegion( + EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Settings settings, + CacheDataDescription metadata, Properties properties) { super( accessStrategyFactory, cache, properties ); this.settings = settings; this.metadata = metadata; - Object context = cache.getInternalContext(); + final Object context = cache.getInternalContext(); if ( context instanceof CacheLockProvider ) { this.lockProvider = (CacheLockProvider) context; } @@ -85,7 +82,7 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements } /** - * Return the hibernate settings + * Access the Hibernate settings associated with the persistence unit. * * @return settings */ @@ -93,26 +90,26 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements return settings; } - /** - * {@inheritDoc} - */ + @Override public boolean isTransactionAware() { return false; } - /** - * {@inheritDoc} - */ + @Override public CacheDataDescription getCacheDataDescription() { return metadata; } /** * Get the value mapped to this key, or null if no value is mapped to this key. + * + * @param key The cache key + * + * @return The cached data */ public final Object get(Object key) { try { - Element element = cache.get( key ); + final Element element = getCache().get( key ); if ( element == null ) { return null; } @@ -120,7 +117,7 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements return element.getObjectValue(); } } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { if ( e instanceof NonStopCacheException ) { HibernateNonstopCacheExceptionHandler.getInstance() .handleNonstopCacheException( (NonStopCacheException) e ); @@ -134,19 +131,24 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements /** * Map the given value to the given key, replacing any existing mapping for this key + * + * @param key The cache key + * @param value The data to cache + * + * @throws CacheException Indicates a problem accessing the cache */ public final void put(Object key, Object value) throws CacheException { try { - Element element = new Element( key, value ); - cache.put( element ); + final Element element = new Element( key, value ); + getCache().put( element ); } - catch ( IllegalArgumentException e ) { + catch (IllegalArgumentException e) { throw new CacheException( e ); } - catch ( IllegalStateException e ) { + catch (IllegalStateException e) { throw new CacheException( e ); } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { if ( e instanceof NonStopCacheException ) { HibernateNonstopCacheExceptionHandler.getInstance() .handleNonstopCacheException( (NonStopCacheException) e ); @@ -159,18 +161,22 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements /** * Remove the mapping for this key (if any exists). + * + * @param key The cache key + * + * @throws CacheException Indicates a problem accessing the cache */ public final void remove(Object key) throws CacheException { try { - cache.remove( key ); + getCache().remove( key ); } - catch ( ClassCastException e ) { + catch (ClassCastException e) { throw new CacheException( e ); } - catch ( IllegalStateException e ) { + catch (IllegalStateException e) { throw new CacheException( e ); } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { if ( e instanceof NonStopCacheException ) { HibernateNonstopCacheExceptionHandler.getInstance() .handleNonstopCacheException( (NonStopCacheException) e ); @@ -183,15 +189,17 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements /** * Remove all mapping from this cache region. + * + * @throws CacheException Indicates a problem accessing the cache */ public final void clear() throws CacheException { try { - cache.removeAll(); + getCache().removeAll(); } - catch ( IllegalStateException e ) { + catch (IllegalStateException e) { throw new CacheException( e ); } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { if ( e instanceof NonStopCacheException ) { HibernateNonstopCacheExceptionHandler.getInstance() .handleNonstopCacheException( (NonStopCacheException) e ); @@ -204,12 +212,16 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements /** * Attempts to write lock the mapping for the given key. + * + * @param key The cache key + * + * @throws CacheException Indicates a problem accessing the cache */ public final void writeLock(Object key) { try { lockProvider.getSyncForKey( key ).lock( LockType.WRITE ); } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { if ( e instanceof NonStopCacheException ) { HibernateNonstopCacheExceptionHandler.getInstance() .handleNonstopCacheException( (NonStopCacheException) e ); @@ -222,12 +234,16 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements /** * Attempts to write unlock the mapping for the given key. + * + * @param key The cache key + * + * @throws CacheException Indicates a problem accessing the cache */ public final void writeUnlock(Object key) { try { lockProvider.getSyncForKey( key ).unlock( LockType.WRITE ); } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { if ( e instanceof NonStopCacheException ) { HibernateNonstopCacheExceptionHandler.getInstance() .handleNonstopCacheException( (NonStopCacheException) e ); @@ -240,12 +256,16 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements /** * Attempts to read lock the mapping for the given key. + * + * @param key The cache key + * + * @throws CacheException Indicates a problem accessing the cache */ public final void readLock(Object key) { try { lockProvider.getSyncForKey( key ).lock( LockType.WRITE ); } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { if ( e instanceof NonStopCacheException ) { HibernateNonstopCacheExceptionHandler.getInstance() .handleNonstopCacheException( (NonStopCacheException) e ); @@ -258,12 +278,16 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements /** * Attempts to read unlock the mapping for the given key. + * + * @param key The cache key + * + * @throws CacheException Indicates a problem accessing the cache */ public final void readUnlock(Object key) { try { lockProvider.getSyncForKey( key ).unlock( LockType.WRITE ); } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { if ( e instanceof NonStopCacheException ) { HibernateNonstopCacheExceptionHandler.getInstance() .handleNonstopCacheException( (NonStopCacheException) e ); @@ -279,6 +303,8 @@ public class EhcacheTransactionalDataRegion extends EhcacheDataRegion implements *

      * Independent locks are not locked by the cache when the cache is accessed directly. This means that for an independent lock * lock holds taken through a region method will not block direct access to the cache via other means. + * + * @return true/false. See discussion above. */ public final boolean locksAreIndependentOfCache() { return lockProvider instanceof StripedReadWriteLockSync; diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/package-info.java new file mode 100644 index 0000000000..ff6247faea --- /dev/null +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/regions/package-info.java @@ -0,0 +1,4 @@ +/** + * Defines {@link org.hibernate.cache.spi.RegionFactory} support for the Ehcache integration + */ +package org.hibernate.cache.ehcache.internal.regions; diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/AbstractEhcacheAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/AbstractEhcacheAccessStrategy.java index 8703256b06..260bd0ccff 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/AbstractEhcacheAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/AbstractEhcacheAccessStrategy.java @@ -37,24 +37,34 @@ import org.hibernate.cfg.Settings; * @author Alex Snaps */ abstract class AbstractEhcacheAccessStrategy { - - /** - * The wrapped Hibernate cache region. - */ - protected final T region; - /** - * The settings for this persistence unit. - */ - protected final Settings settings; + private final T region; + private final Settings settings; /** * Create an access strategy wrapping the given region. + * + * @param region The wrapped region. Accessible to subclasses via {@link #region()} + * @param settings The Hibernate settings. Accessible to subclasses via {@link #settings()} */ AbstractEhcacheAccessStrategy(T region, Settings settings) { this.region = region; this.settings = settings; } + /** + * The wrapped Hibernate cache region. + */ + protected T region() { + return region; + } + + /** + * The settings for this persistence unit. + */ + protected Settings settings() { + return settings; + } + /** * This method is a placeholder for method signatures supplied by interfaces pulled in further down the class * hierarchy. @@ -84,6 +94,7 @@ abstract class AbstractEhcacheAccessStrategy - extends AbstractEhcacheAccessStrategy { +abstract class AbstractReadWriteEhcacheAccessStrategy + extends AbstractEhcacheAccessStrategy { - private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( - EhCacheMessageLogger.class, - AbstractReadWriteEhcacheAccessStrategy.class.getName() - ); - private final UUID uuid = UUID.randomUUID(); - private final AtomicLong nextLockId = new AtomicLong(); + private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( + EhCacheMessageLogger.class, + AbstractReadWriteEhcacheAccessStrategy.class.getName() + ); - private final Comparator versionComparator; + private final UUID uuid = UUID.randomUUID(); + private final AtomicLong nextLockId = new AtomicLong(); - /** - * Creates a read/write cache access strategy around the given cache region. - */ - public AbstractReadWriteEhcacheAccessStrategy(T region, Settings settings) { - super( region, settings ); - this.versionComparator = region.getCacheDataDescription().getVersionComparator(); - } + private final Comparator versionComparator; - /** - * Returns null if the item is not readable. Locked items are not readable, nor are items created - * after the start of this transaction. - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long) - * @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#get(java.lang.Object, long) - */ - public final Object get(Object key, long txTimestamp) throws CacheException { - readLockIfNeeded( key ); - try { - Lockable item = (Lockable) region.get( key ); + /** + * Creates a read/write cache access strategy around the given cache region. + */ + public AbstractReadWriteEhcacheAccessStrategy(T region, Settings settings) { + super( region, settings ); + this.versionComparator = region.getCacheDataDescription().getVersionComparator(); + } - boolean readable = item != null && item.isReadable( txTimestamp ); - if ( readable ) { - return item.getValue(); - } - else { - return null; - } - } - finally { - readUnlockIfNeeded( key ); - } - } + /** + * Returns null if the item is not readable. Locked items are not readable, nor are items created + * after the start of this transaction. + * + * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#get(java.lang.Object, long) + * @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#get(java.lang.Object, long) + */ + public final Object get(Object key, long txTimestamp) throws CacheException { + readLockIfNeeded( key ); + try { + final Lockable item = (Lockable) region().get( key ); - /** - * Returns false and fails to put the value if there is an existing un-writeable item mapped to this - * key. - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean) - * @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean) - */ - @Override - public final boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) - throws CacheException { - region.writeLock( key ); - try { - Lockable item = (Lockable) region.get( key ); - boolean writeable = item == null || item.isWriteable( txTimestamp, version, versionComparator ); - if ( writeable ) { - region.put( key, new Item( value, version, region.nextTimestamp() ) ); - return true; - } - else { - return false; - } - } - finally { - region.writeUnlock( key ); - } - } + final boolean readable = item != null && item.isReadable( txTimestamp ); + if ( readable ) { + return item.getValue(); + } + else { + return null; + } + } + finally { + readUnlockIfNeeded( key ); + } + } - /** - * Soft-lock a cache item. - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object) - * @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object) - */ - public final SoftLock lockItem(Object key, Object version) throws CacheException { - region.writeLock( key ); - try { - Lockable item = (Lockable) region.get( key ); - long timeout = region.nextTimestamp() + region.getTimeout(); - final Lock lock = ( item == null ) ? new Lock( timeout, uuid, nextLockId(), version ) : item.lock( - timeout, - uuid, - nextLockId() - ); - region.put( key, lock ); - return lock; - } - finally { - region.writeUnlock( key ); - } - } + /** + * Returns false and fails to put the value if there is an existing un-writeable item mapped to this + * key. + * + * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean) + * @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#putFromLoad(java.lang.Object, java.lang.Object, long, java.lang.Object, boolean) + */ + @Override + public final boolean putFromLoad( + Object key, + Object value, + long txTimestamp, + Object version, + boolean minimalPutOverride) + throws CacheException { + region().writeLock( key ); + try { + final Lockable item = (Lockable) region().get( key ); + final boolean writeable = item == null || item.isWriteable( txTimestamp, version, versionComparator ); + if ( writeable ) { + region().put( key, new Item( value, version, region().nextTimestamp() ) ); + return true; + } + else { + return false; + } + } + finally { + region().writeUnlock( key ); + } + } - /** - * Soft-unlock a cache item. - * - * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock) - * @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock) - */ - public final void unlockItem(Object key, SoftLock lock) throws CacheException { - region.writeLock( key ); - try { - Lockable item = (Lockable) region.get( key ); + /** + * Soft-lock a cache item. + * + * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object) + * @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#lockItem(java.lang.Object, java.lang.Object) + */ + public final SoftLock lockItem(Object key, Object version) throws CacheException { + region().writeLock( key ); + try { + final Lockable item = (Lockable) region().get( key ); + final long timeout = region().nextTimestamp() + region().getTimeout(); + final Lock lock = (item == null) ? new Lock( timeout, uuid, nextLockId(), version ) : item.lock( + timeout, + uuid, + nextLockId() + ); + region().put( key, lock ); + return lock; + } + finally { + region().writeUnlock( key ); + } + } - if ( ( item != null ) && item.isUnlockable( lock ) ) { - decrementLock( key, (Lock) item ); - } - else { - handleLockExpiry( key, item ); - } - } - finally { - region.writeUnlock( key ); - } - } + /** + * Soft-unlock a cache item. + * + * @see org.hibernate.cache.spi.access.EntityRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock) + * @see org.hibernate.cache.spi.access.CollectionRegionAccessStrategy#unlockItem(java.lang.Object, org.hibernate.cache.spi.access.SoftLock) + */ + public final void unlockItem(Object key, SoftLock lock) throws CacheException { + region().writeLock( key ); + try { + final Lockable item = (Lockable) region().get( key ); - private long nextLockId() { - return nextLockId.getAndIncrement(); - } + if ( (item != null) && item.isUnlockable( lock ) ) { + decrementLock( key, (Lock) item ); + } + else { + handleLockExpiry( key, item ); + } + } + finally { + region().writeUnlock( key ); + } + } - /** - * Unlock and re-put the given key, lock combination. - */ - protected void decrementLock(Object key, Lock lock) { - lock.unlock( region.nextTimestamp() ); - region.put( key, lock ); - } + private long nextLockId() { + return nextLockId.getAndIncrement(); + } - /** - * Handle the timeout of a previous lock mapped to this key - */ - protected void handleLockExpiry(Object key, Lockable lock) { - LOG.softLockedCacheExpired( region.getName(), key, lock == null ? "(null)" : lock.toString() ); + /** + * Unlock and re-put the given key, lock combination. + */ + protected void decrementLock(Object key, Lock lock) { + lock.unlock( region().nextTimestamp() ); + region().put( key, lock ); + } - long ts = region.nextTimestamp() + region.getTimeout(); - // create new lock that times out immediately - Lock newLock = new Lock( ts, uuid, nextLockId.getAndIncrement(), null ); - newLock.unlock( ts ); - region.put( key, newLock ); - } + /** + * Handle the timeout of a previous lock mapped to this key + */ + protected void handleLockExpiry(Object key, Lockable lock) { + LOG.softLockedCacheExpired( region().getName(), key, lock == null ? "(null)" : lock.toString() ); - /** - * Read lock the entry for the given key if internal cache locks will not provide correct exclusion. - */ - private void readLockIfNeeded(Object key) { - if ( region.locksAreIndependentOfCache() ) { - region.readLock( key ); - } - } + final long ts = region().nextTimestamp() + region().getTimeout(); + // create new lock that times out immediately + final Lock newLock = new Lock( ts, uuid, nextLockId.getAndIncrement(), null ); + newLock.unlock( ts ); + region().put( key, newLock ); + } - /** - * Read unlock the entry for the given key if internal cache locks will not provide correct exclusion. - */ - private void readUnlockIfNeeded(Object key) { - if ( region.locksAreIndependentOfCache() ) { - region.readUnlock( key ); - } - } + /** + * Read lock the entry for the given key if internal cache locks will not provide correct exclusion. + */ + private void readLockIfNeeded(Object key) { + if ( region().locksAreIndependentOfCache() ) { + region().readLock( key ); + } + } - /** - * Interface type implemented by all wrapper objects in the cache. - */ - protected static interface Lockable { + /** + * Read unlock the entry for the given key if internal cache locks will not provide correct exclusion. + */ + private void readUnlockIfNeeded(Object key) { + if ( region().locksAreIndependentOfCache() ) { + region().readUnlock( key ); + } + } - /** - * Returns true if the enclosed value can be read by a transaction started at the given time. - */ - public boolean isReadable(long txTimestamp); + /** + * Interface type implemented by all wrapper objects in the cache. + */ + protected static interface Lockable { - /** - * Returns true if the enclosed value can be replaced with one of the given version by a - * transaction started at the given time. - */ - public boolean isWriteable(long txTimestamp, Object version, Comparator versionComparator); + /** + * Returns true if the enclosed value can be read by a transaction started at the given time. + */ + public boolean isReadable(long txTimestamp); - /** - * Returns the enclosed value. - */ - public Object getValue(); + /** + * Returns true if the enclosed value can be replaced with one of the given version by a + * transaction started at the given time. + */ + public boolean isWriteable(long txTimestamp, Object version, Comparator versionComparator); - /** - * Returns true if the given lock can be unlocked using the given SoftLock instance as a handle. - */ - public boolean isUnlockable(SoftLock lock); + /** + * Returns the enclosed value. + */ + public Object getValue(); - /** - * Locks this entry, stamping it with the UUID and lockId given, with the lock timeout occuring at the specified - * time. The returned Lock object can be used to unlock the entry in the future. - */ - public Lock lock(long timeout, UUID uuid, long lockId); - } + /** + * Returns true if the given lock can be unlocked using the given SoftLock instance as a handle. + */ + public boolean isUnlockable(SoftLock lock); - /** - * Wrapper type representing unlocked items. - */ - protected final static class Item implements Serializable, Lockable { + /** + * Locks this entry, stamping it with the UUID and lockId given, with the lock timeout occuring at the specified + * time. The returned Lock object can be used to unlock the entry in the future. + */ + public Lock lock(long timeout, UUID uuid, long lockId); + } - private static final long serialVersionUID = 1L; - private final Object value; - private final Object version; - private final long timestamp; + /** + * Wrapper type representing unlocked items. + */ + protected static final class Item implements Serializable, Lockable { + private static final long serialVersionUID = 1L; + private final Object value; + private final Object version; + private final long timestamp; - /** - * Creates an unlocked item wrapping the given value with a version and creation timestamp. - */ - Item(Object value, Object version, long timestamp) { - this.value = value; - this.version = version; - this.timestamp = timestamp; - } + /** + * Creates an unlocked item wrapping the given value with a version and creation timestamp. + */ + Item(Object value, Object version, long timestamp) { + this.value = value; + this.version = version; + this.timestamp = timestamp; + } - /** - * {@inheritDoc} - */ - public boolean isReadable(long txTimestamp) { - return txTimestamp > timestamp; - } + @Override + public boolean isReadable(long txTimestamp) { + return txTimestamp > timestamp; + } - /** - * {@inheritDoc} - */ - public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) { - return version != null && versionComparator.compare( version, newVersion ) < 0; - } + @Override + @SuppressWarnings("unchecked") + public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) { + return version != null && versionComparator.compare( version, newVersion ) < 0; + } - /** - * {@inheritDoc} - */ - public Object getValue() { - return value; - } + @Override + public Object getValue() { + return value; + } - /** - * {@inheritDoc} - */ - public boolean isUnlockable(SoftLock lock) { - return false; - } + @Override + public boolean isUnlockable(SoftLock lock) { + return false; + } - /** - * {@inheritDoc} - */ - public Lock lock(long timeout, UUID uuid, long lockId) { - return new Lock( timeout, uuid, lockId, version ); - } - } + @Override + public Lock lock(long timeout, UUID uuid, long lockId) { + return new Lock( timeout, uuid, lockId, version ); + } + } - /** - * Wrapper type representing locked items. - */ - protected final static class Lock implements Serializable, Lockable, SoftLock { + /** + * Wrapper type representing locked items. + */ + protected static final class Lock implements Serializable, Lockable, SoftLock { + private static final long serialVersionUID = 2L; - private static final long serialVersionUID = 2L; + private final UUID sourceUuid; + private final long lockId; + private final Object version; - private final UUID sourceUuid; - private final long lockId; - private final Object version; + private long timeout; + private boolean concurrent; + private int multiplicity = 1; + private long unlockTimestamp; - private long timeout; - private boolean concurrent; - private int multiplicity = 1; - private long unlockTimestamp; + /** + * Creates a locked item with the given identifiers and object version. + */ + Lock(long timeout, UUID sourceUuid, long lockId, Object version) { + this.timeout = timeout; + this.lockId = lockId; + this.version = version; + this.sourceUuid = sourceUuid; + } - /** - * Creates a locked item with the given identifiers and object version. - */ - Lock(long timeout, UUID sourceUuid, long lockId, Object version) { - this.timeout = timeout; - this.lockId = lockId; - this.version = version; - this.sourceUuid = sourceUuid; - } + @Override + public boolean isReadable(long txTimestamp) { + return false; + } - /** - * {@inheritDoc} - */ - public boolean isReadable(long txTimestamp) { - return false; - } + @Override + @SuppressWarnings({"SimplifiableIfStatement", "unchecked"}) + public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) { + if ( txTimestamp > timeout ) { + // if timedout then allow write + return true; + } + if ( multiplicity > 0 ) { + // if still locked then disallow write + return false; + } + return version == null + ? txTimestamp > unlockTimestamp + : versionComparator.compare( version, newVersion ) < 0; + } - /** - * {@inheritDoc} - */ - public boolean isWriteable(long txTimestamp, Object newVersion, Comparator versionComparator) { - if ( txTimestamp > timeout ) { - // if timedout then allow write - return true; - } - if ( multiplicity > 0 ) { - // if still locked then disallow write - return false; - } - return version == null ? txTimestamp > unlockTimestamp : versionComparator.compare( - version, - newVersion - ) < 0; - } + @Override + public Object getValue() { + return null; + } - /** - * {@inheritDoc} - */ - public Object getValue() { - return null; - } + @Override + public boolean isUnlockable(SoftLock lock) { + return equals( lock ); + } - /** - * {@inheritDoc} - */ - public boolean isUnlockable(SoftLock lock) { - return equals( lock ); - } + @Override + @SuppressWarnings("SimplifiableIfStatement") + public boolean equals(Object o) { + if ( o == this ) { + return true; + } + else if ( o instanceof Lock ) { + return (lockId == ((Lock) o).lockId) && sourceUuid.equals( ((Lock) o).sourceUuid ); + } + else { + return false; + } + } - /** - * {@inheritDoc} - */ - @Override - public boolean equals(Object o) { - if ( o == this ) { - return true; - } - else if ( o instanceof Lock ) { - return ( lockId == ( (Lock) o ).lockId ) && sourceUuid.equals( ( (Lock) o ).sourceUuid ); - } - else { - return false; - } - } + @Override + public int hashCode() { + final int hash = (sourceUuid != null ? sourceUuid.hashCode() : 0); + int temp = (int) lockId; + for ( int i = 1; i < Long.SIZE / Integer.SIZE; i++ ) { + temp ^= (lockId >>> (i * Integer.SIZE)); + } + return hash + temp; + } - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - int hash = ( sourceUuid != null ? sourceUuid.hashCode() : 0 ); - int temp = (int) lockId; - for ( int i = 1; i < Long.SIZE / Integer.SIZE; i++ ) { - temp ^= ( lockId >>> ( i * Integer.SIZE ) ); - } - return hash + temp; - } + /** + * Returns true if this Lock has been concurrently locked by more than one transaction. + */ + public boolean wasLockedConcurrently() { + return concurrent; + } - /** - * Returns true if this Lock has been concurrently locked by more than one transaction. - */ - public boolean wasLockedConcurrently() { - return concurrent; - } + @Override + public Lock lock(long timeout, UUID uuid, long lockId) { + concurrent = true; + multiplicity++; + this.timeout = timeout; + return this; + } - /** - * {@inheritDoc} - */ - public Lock lock(long timeout, UUID uuid, long lockId) { - concurrent = true; - multiplicity++; - this.timeout = timeout; - return this; - } + /** + * Unlocks this Lock, and timestamps the unlock event. + */ + public void unlock(long timestamp) { + if ( --multiplicity == 0 ) { + unlockTimestamp = timestamp; + } + } - /** - * Unlocks this Lock, and timestamps the unlock event. - */ - public void unlock(long timestamp) { - if ( --multiplicity == 0 ) { - unlockTimestamp = timestamp; - } - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder( "Lock Source-UUID:" + sourceUuid + " Lock-ID:" + lockId ); - return sb.toString(); - } - } + @Override + public String toString() { + return "Lock Source-UUID:" + sourceUuid + " Lock-ID:" + lockId; + } + } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/EhcacheAccessStrategyFactory.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/EhcacheAccessStrategyFactory.java index 6265cdae58..c97ff57593 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/EhcacheAccessStrategyFactory.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/EhcacheAccessStrategyFactory.java @@ -32,42 +32,46 @@ import org.hibernate.cache.spi.access.EntityRegionAccessStrategy; import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy; /** - * Factory to create {@link EntityRegionAccessStrategy} + * Factory to create {@link org.hibernate.cache.spi.access.RegionAccessStrategy} instance * * @author Abhishek Sanoujam * @author Alex Snaps */ public interface EhcacheAccessStrategyFactory { - /** * Create {@link EntityRegionAccessStrategy} for the input {@link EhcacheEntityRegion} and {@link AccessType} * - * @param entityRegion - * @param accessType + * @param entityRegion The entity region being wrapped + * @param accessType The type of access to allow to the region * * @return the created {@link EntityRegionAccessStrategy} */ - public EntityRegionAccessStrategy createEntityRegionAccessStrategy(EhcacheEntityRegion entityRegion, AccessType accessType); + public EntityRegionAccessStrategy createEntityRegionAccessStrategy( + EhcacheEntityRegion entityRegion, + AccessType accessType); /** - * Create {@link CollectionRegionAccessStrategy} for the input {@link org.hibernate.cache.ehcache.internal.regions.EhcacheCollectionRegion} and {@link AccessType} + * Create {@link CollectionRegionAccessStrategy} for the input {@link EhcacheCollectionRegion} and {@link AccessType} * - * @param collectionRegion - * @param accessType + * @param collectionRegion The collection region being wrapped + * @param accessType The type of access to allow to the region * * @return the created {@link CollectionRegionAccessStrategy} */ - public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(EhcacheCollectionRegion collectionRegion, - AccessType accessType); - /** - * Create {@link NaturalIdRegionAccessStrategy} for the input {@link org.hibernate.cache.ehcache.internal.regions.EhcacheNaturalIdRegion} and {@link AccessType} - * - * @param naturalIdRegion - * @param accessType - * - * @return the created {@link NaturalIdRegionAccessStrategy} - */ - public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion naturalIdRegion, - AccessType accessType); + public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy( + EhcacheCollectionRegion collectionRegion, + AccessType accessType); + + /** + * Create {@link NaturalIdRegionAccessStrategy} for the input {@link EhcacheNaturalIdRegion} and {@link AccessType} + * + * @param naturalIdRegion The natural-id region being wrapped + * @param accessType The type of access to allow to the region + * + * @return the created {@link NaturalIdRegionAccessStrategy} + */ + public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy( + EhcacheNaturalIdRegion naturalIdRegion, + AccessType accessType); } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/EhcacheAccessStrategyFactoryImpl.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/EhcacheAccessStrategyFactoryImpl.java index 94cc5dc042..7062d5652c 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/EhcacheAccessStrategyFactoryImpl.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/EhcacheAccessStrategyFactoryImpl.java @@ -42,108 +42,108 @@ import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy; */ public class EhcacheAccessStrategyFactoryImpl implements EhcacheAccessStrategyFactory { - private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( - EhCacheMessageLogger.class, - EhcacheAccessStrategyFactoryImpl.class.getName() - ); - - /** - * {@inheritDoc} - */ - public EntityRegionAccessStrategy createEntityRegionAccessStrategy(EhcacheEntityRegion entityRegion, AccessType accessType) { - switch ( accessType ) { - case READ_ONLY: - if ( entityRegion.getCacheDataDescription().isMutable() ) { - LOG.readOnlyCacheConfiguredForMutableEntity( entityRegion.getName() ); - } - return new ReadOnlyEhcacheEntityRegionAccessStrategy( entityRegion, entityRegion.getSettings() ); - case READ_WRITE: - return new ReadWriteEhcacheEntityRegionAccessStrategy( entityRegion, entityRegion.getSettings() ); - - case NONSTRICT_READ_WRITE: - return new NonStrictReadWriteEhcacheEntityRegionAccessStrategy( - entityRegion, - entityRegion.getSettings() - ); - - case TRANSACTIONAL: - return new TransactionalEhcacheEntityRegionAccessStrategy( - entityRegion, - entityRegion.getEhcache(), - entityRegion.getSettings() - ); - default: - throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" ); - - } - - } - - /** - * {@inheritDoc} - */ - public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(EhcacheCollectionRegion collectionRegion, - AccessType accessType) { - switch ( accessType ) { - case READ_ONLY: - if ( collectionRegion.getCacheDataDescription().isMutable() ) { - LOG.readOnlyCacheConfiguredForMutableEntity( collectionRegion.getName() ); - } - return new ReadOnlyEhcacheCollectionRegionAccessStrategy( - collectionRegion, - collectionRegion.getSettings() - ); - case READ_WRITE: - return new ReadWriteEhcacheCollectionRegionAccessStrategy( - collectionRegion, - collectionRegion.getSettings() - ); - case NONSTRICT_READ_WRITE: - return new NonStrictReadWriteEhcacheCollectionRegionAccessStrategy( - collectionRegion, - collectionRegion.getSettings() - ); - case TRANSACTIONAL: - return new TransactionalEhcacheCollectionRegionAccessStrategy( - collectionRegion, collectionRegion.getEhcache(), collectionRegion - .getSettings() - ); - default: - throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" ); - } - } + private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( + EhCacheMessageLogger.class, + EhcacheAccessStrategyFactoryImpl.class.getName() + ); @Override - public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion naturalIdRegion, + public EntityRegionAccessStrategy createEntityRegionAccessStrategy( + EhcacheEntityRegion entityRegion, AccessType accessType) { - switch ( accessType ) { - case READ_ONLY: - if ( naturalIdRegion.getCacheDataDescription().isMutable() ) { - LOG.readOnlyCacheConfiguredForMutableEntity( naturalIdRegion.getName() ); - } - return new ReadOnlyEhcacheNaturalIdRegionAccessStrategy( - naturalIdRegion, - naturalIdRegion.getSettings() - ); - case READ_WRITE: - return new ReadWriteEhcacheNaturalIdRegionAccessStrategy( - naturalIdRegion, - naturalIdRegion.getSettings() - ); - case NONSTRICT_READ_WRITE: - return new NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy( - naturalIdRegion, - naturalIdRegion.getSettings() - ); - case TRANSACTIONAL: - return new TransactionalEhcacheNaturalIdRegionAccessStrategy( - naturalIdRegion, naturalIdRegion.getEhcache(), naturalIdRegion - .getSettings() - ); - default: - throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" ); - } + switch ( accessType ) { + case READ_ONLY: + if ( entityRegion.getCacheDataDescription().isMutable() ) { + LOG.readOnlyCacheConfiguredForMutableEntity( entityRegion.getName() ); + } + return new ReadOnlyEhcacheEntityRegionAccessStrategy( entityRegion, entityRegion.getSettings() ); + case READ_WRITE: + return new ReadWriteEhcacheEntityRegionAccessStrategy( entityRegion, entityRegion.getSettings() ); + + case NONSTRICT_READ_WRITE: + return new NonStrictReadWriteEhcacheEntityRegionAccessStrategy( + entityRegion, + entityRegion.getSettings() + ); + + case TRANSACTIONAL: + return new TransactionalEhcacheEntityRegionAccessStrategy( + entityRegion, + entityRegion.getEhcache(), + entityRegion.getSettings() + ); + default: + throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" ); + + } + } - + @Override + public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy( + EhcacheCollectionRegion collectionRegion, + AccessType accessType) { + switch ( accessType ) { + case READ_ONLY: + if ( collectionRegion.getCacheDataDescription().isMutable() ) { + LOG.readOnlyCacheConfiguredForMutableEntity( collectionRegion.getName() ); + } + return new ReadOnlyEhcacheCollectionRegionAccessStrategy( + collectionRegion, + collectionRegion.getSettings() + ); + case READ_WRITE: + return new ReadWriteEhcacheCollectionRegionAccessStrategy( + collectionRegion, + collectionRegion.getSettings() + ); + case NONSTRICT_READ_WRITE: + return new NonStrictReadWriteEhcacheCollectionRegionAccessStrategy( + collectionRegion, + collectionRegion.getSettings() + ); + case TRANSACTIONAL: + return new TransactionalEhcacheCollectionRegionAccessStrategy( + collectionRegion, collectionRegion.getEhcache(), collectionRegion + .getSettings() + ); + default: + throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" ); + } + } + + @Override + public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy( + EhcacheNaturalIdRegion naturalIdRegion, + AccessType accessType) { + switch ( accessType ) { + case READ_ONLY: + if ( naturalIdRegion.getCacheDataDescription().isMutable() ) { + LOG.readOnlyCacheConfiguredForMutableEntity( naturalIdRegion.getName() ); + } + return new ReadOnlyEhcacheNaturalIdRegionAccessStrategy( + naturalIdRegion, + naturalIdRegion.getSettings() + ); + case READ_WRITE: + return new ReadWriteEhcacheNaturalIdRegionAccessStrategy( + naturalIdRegion, + naturalIdRegion.getSettings() + ); + case NONSTRICT_READ_WRITE: + return new NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy( + naturalIdRegion, + naturalIdRegion.getSettings() + ); + case TRANSACTIONAL: + return new TransactionalEhcacheNaturalIdRegionAccessStrategy( + naturalIdRegion, naturalIdRegion.getEhcache(), naturalIdRegion + .getSettings() + ); + default: + throw new IllegalArgumentException( "unrecognized access strategy type [" + accessType + "]" ); + } + } + + } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheCollectionRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheCollectionRegionAccessStrategy.java index bada4b02bb..959d4e48cb 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheCollectionRegionAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheCollectionRegionAccessStrategy.java @@ -42,58 +42,58 @@ public class NonStrictReadWriteEhcacheCollectionRegionAccessStrategy /** * Create a non-strict read/write access strategy accessing the given collection region. + * + * @param region The wrapped region + * @param settings The Hibernate settings */ public NonStrictReadWriteEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region, Settings settings) { super( region, settings ); } - /** - * {@inheritDoc} - */ + @Override public CollectionRegion getRegion() { - return region; + return region(); } - /** - * {@inheritDoc} - */ + @Override public Object get(Object key, long txTimestamp) throws CacheException { - return region.get( key ); + return region().get( key ); } - /** - * {@inheritDoc} - */ + @Override public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { - if ( minimalPutOverride && region.contains( key ) ) { + if ( minimalPutOverride && region().contains( key ) ) { return false; } else { - region.put( key, value ); + region().put( key, value ); return true; } } /** + * {@inheritDoc} + *

      * Since this is a non-strict read/write strategy item locking is not used. */ + @Override public SoftLock lockItem(Object key, Object version) throws CacheException { return null; } /** + * {@inheritDoc} + *

      * Since this is a non-strict read/write strategy item locking is not used. */ + @Override public void unlockItem(Object key, SoftLock lock) throws CacheException { - region.remove( key ); + region().remove( key ); } - /** - * {@inheritDoc} - */ @Override public void remove(Object key) throws CacheException { - region.remove( key ); + region().remove( key ); } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheEntityRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheEntityRegionAccessStrategy.java index c953ffc71d..9340d2b171 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheEntityRegionAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheEntityRegionAccessStrategy.java @@ -42,90 +42,97 @@ public class NonStrictReadWriteEhcacheEntityRegionAccessStrategy /** * Create a non-strict read/write access strategy accessing the given collection region. + * + * @param region The wrapped region + * @param settings The Hibernate settings */ public NonStrictReadWriteEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region, Settings settings) { super( region, settings ); } - /** - * {@inheritDoc} - */ + @Override public EntityRegion getRegion() { - return region; + return super.region(); } - /** - * {@inheritDoc} - */ + @Override public Object get(Object key, long txTimestamp) throws CacheException { - return region.get( key ); + return region().get( key ); } - /** - * {@inheritDoc} - */ + @Override public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { - if ( minimalPutOverride && region.contains( key ) ) { + if ( minimalPutOverride && region().contains( key ) ) { return false; } else { - region.put( key, value ); + region().put( key, value ); return true; } } /** + * {@inheritDoc} + *

      * Since this is a non-strict read/write strategy item locking is not used. */ + @Override public SoftLock lockItem(Object key, Object version) throws CacheException { return null; } /** + * {@inheritDoc} + *

      * Since this is a non-strict read/write strategy item locking is not used. */ + @Override public void unlockItem(Object key, SoftLock lock) throws CacheException { - region.remove( key ); + region().remove( key ); } /** + * {@inheritDoc} + *

      * Returns false since this is an asynchronous cache access strategy. */ + @Override public boolean insert(Object key, Object value, Object version) throws CacheException { return false; } /** + * {@inheritDoc} + *

      * Returns false since this is a non-strict read/write cache access strategy */ + @Override public boolean afterInsert(Object key, Object value, Object version) throws CacheException { return false; } /** + * {@inheritDoc} + *

      * Removes the entry since this is a non-strict read/write cache strategy. */ + @Override public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { remove( key ); return false; } - /** - * {@inheritDoc} - */ + @Override public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) throws CacheException { unlockItem( key, lock ); return false; } - /** - * {@inheritDoc} - */ @Override public void remove(Object key) throws CacheException { - region.remove( key ); + region().remove( key ); } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy.java index 6f6f8f26fb..1a633ae785 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy.java @@ -42,88 +42,95 @@ public class NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy /** * Create a non-strict read/write access strategy accessing the given NaturalId region. + * + * @param region The wrapped region + * @param settings The Hibernate settings */ public NonStrictReadWriteEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region, Settings settings) { super( region, settings ); } - /** - * {@inheritDoc} - */ + @Override public NaturalIdRegion getRegion() { - return region; + return region(); } - /** - * {@inheritDoc} - */ + @Override public Object get(Object key, long txTimestamp) throws CacheException { - return region.get( key ); + return region().get( key ); } - /** - * {@inheritDoc} - */ + @Override public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { - if ( minimalPutOverride && region.contains( key ) ) { + if ( minimalPutOverride && region().contains( key ) ) { return false; } else { - region.put( key, value ); + region().put( key, value ); return true; } } /** + * {@inheritDoc} + *

      * Since this is a non-strict read/write strategy item locking is not used. */ + @Override public SoftLock lockItem(Object key, Object version) throws CacheException { return null; } /** + * {@inheritDoc} + *

      * Since this is a non-strict read/write strategy item locking is not used. */ + @Override public void unlockItem(Object key, SoftLock lock) throws CacheException { - region.remove( key ); + region().remove( key ); } /** + * {@inheritDoc} + *

      * Returns false since this is an asynchronous cache access strategy. */ - public boolean insert(Object key, Object value ) throws CacheException { - return false; - } - - /** - * Returns false since this is a non-strict read/write cache access strategy - */ - public boolean afterInsert(Object key, Object value ) throws CacheException { - return false; - } - - /** - * Removes the entry since this is a non-strict read/write cache strategy. - */ - public boolean update(Object key, Object value ) throws CacheException { - remove( key ); + @Override + public boolean insert(Object key, Object value) throws CacheException { return false; } /** * {@inheritDoc} + *

      + * Returns false since this is a non-strict read/write cache access strategy */ + @Override + public boolean afterInsert(Object key, Object value) throws CacheException { + return false; + } + + /** + * {@inheritDoc} + *

      + * Removes the entry since this is a non-strict read/write cache strategy. + */ + @Override + public boolean update(Object key, Object value) throws CacheException { + remove( key ); + return false; + } + + @Override public boolean afterUpdate(Object key, Object value, SoftLock lock) throws CacheException { unlockItem( key, lock ); return false; } - /** - * {@inheritDoc} - */ @Override public void remove(Object key) throws CacheException { - region.remove( key ); + region().remove( key ); } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheCollectionRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheCollectionRegionAccessStrategy.java index 449f1b40c7..7469f0e11a 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheCollectionRegionAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheCollectionRegionAccessStrategy.java @@ -42,46 +42,47 @@ public class ReadOnlyEhcacheCollectionRegionAccessStrategy /** * Create a read-only access strategy accessing the given collection region. + * + * @param region The wrapped region + * @param settings The Hibernate settings */ public ReadOnlyEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region, Settings settings) { super( region, settings ); } - /** - * {@inheritDoc} - */ + @Override public CollectionRegion getRegion() { - return region; + return region(); } - /** - * {@inheritDoc} - */ + @Override public Object get(Object key, long txTimestamp) throws CacheException { - return region.get( key ); + return region().get( key ); } - /** - * {@inheritDoc} - */ + @Override public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { - if ( minimalPutOverride && region.contains( key ) ) { + if ( minimalPutOverride && region().contains( key ) ) { return false; } else { - region.put( key, value ); + region().put( key, value ); return true; } } + @Override public SoftLock lockItem(Object key, Object version) throws UnsupportedOperationException { return null; } /** + * {@inheritDoc} + *

      * A no-op since this cache is read-only */ + @Override public void unlockItem(Object key, SoftLock lock) throws CacheException { } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheEntityRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheEntityRegionAccessStrategy.java index acd8fc2c5f..6631922159 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheEntityRegionAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheEntityRegionAccessStrategy.java @@ -30,10 +30,6 @@ import org.hibernate.cache.spi.access.EntityRegionAccessStrategy; import org.hibernate.cache.spi.access.SoftLock; import org.hibernate.cfg.Settings; -/** - * @author Alex Snaps - */ - /** * Ehcache specific read-only entity region access strategy * @@ -45,6 +41,9 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc /** * Create a read-only access strategy accessing the given entity region. + * + * @param region The wrapped region + * @param settings The Hibernate settings */ public ReadOnlyEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region, Settings settings) { super( region, settings ); @@ -54,14 +53,14 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc * {@inheritDoc} */ public EntityRegion getRegion() { - return region; + return region(); } /** * {@inheritDoc} */ public Object get(Object key, long txTimestamp) throws CacheException { - return region.get( key ); + return region().get( key ); } /** @@ -69,11 +68,11 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc */ public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { - if ( minimalPutOverride && region.contains( key ) ) { + if ( minimalPutOverride && region().contains( key ) ) { return false; } else { - region.put( key, value ); + region().put( key, value ); return true; } } @@ -100,7 +99,7 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc * {@inheritDoc} */ public boolean afterInsert(Object key, Object value, Object version) throws CacheException { - region.put( key, value ); + region().put( key, value ); return true; } @@ -123,4 +122,4 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc throws UnsupportedOperationException { throw new UnsupportedOperationException( "Can't write to a readonly object" ); } -} \ No newline at end of file +} diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheNaturalIdRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheNaturalIdRegionAccessStrategy.java index 78d8839266..1e9488507e 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheNaturalIdRegionAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheNaturalIdRegionAccessStrategy.java @@ -42,79 +42,87 @@ public class ReadOnlyEhcacheNaturalIdRegionAccessStrategy /** * Create a read-only access strategy accessing the given NaturalId region. + * + * @param region THe wrapped region + * @param settings The Hibermate settings */ public ReadOnlyEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region, Settings settings) { super( region, settings ); } - /** - * {@inheritDoc} - */ + @Override public NaturalIdRegion getRegion() { - return region; + return region(); } - /** - * {@inheritDoc} - */ + @Override public Object get(Object key, long txTimestamp) throws CacheException { - return region.get( key ); + return region().get( key ); } - /** - * {@inheritDoc} - */ + @Override public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { - if ( minimalPutOverride && region.contains( key ) ) { + if ( minimalPutOverride && region().contains( key ) ) { return false; } else { - region.put( key, value ); + region().put( key, value ); return true; } } + @Override public SoftLock lockItem(Object key, Object version) throws UnsupportedOperationException { return null; } /** + * {@inheritDoc} + *

      * A no-op since this cache is read-only */ + @Override public void unlockItem(Object key, SoftLock lock) throws CacheException { - region.remove( key ); - } - - /** - * This cache is asynchronous hence a no-op - */ - public boolean insert(Object key, Object value ) throws CacheException { - return false; + region().remove( key ); } /** * {@inheritDoc} + *

      + * This cache is asynchronous hence a no-op */ - public boolean afterInsert(Object key, Object value ) throws CacheException { - region.put( key, value ); + @Override + public boolean insert(Object key, Object value) throws CacheException { + return false; + } + + @Override + public boolean afterInsert(Object key, Object value) throws CacheException { + region().put( key, value ); return true; } /** + * {@inheritDoc} + *

      * Throws UnsupportedOperationException since this cache is read-only * * @throws UnsupportedOperationException always */ - public boolean update(Object key, Object value ) throws UnsupportedOperationException { + @Override + public boolean update(Object key, Object value) throws UnsupportedOperationException { throw new UnsupportedOperationException( "Can't write to a readonly object" ); } /** + * {@inheritDoc} + *

      * Throws UnsupportedOperationException since this cache is read-only * * @throws UnsupportedOperationException always */ + @Override public boolean afterUpdate(Object key, Object value, SoftLock lock) throws UnsupportedOperationException { throw new UnsupportedOperationException( "Can't write to a readonly object" ); } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheCollectionRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheCollectionRegionAccessStrategy.java index f43e666afa..36efcd2df9 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheCollectionRegionAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheCollectionRegionAccessStrategy.java @@ -40,15 +40,16 @@ public class ReadWriteEhcacheCollectionRegionAccessStrategy /** * Create a read/write access strategy accessing the given collection region. + * + * @param region The wrapped region + * @param settings The Hibernate settings */ public ReadWriteEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region, Settings settings) { super( region, settings ); } - /** - * {@inheritDoc} - */ + @Override public CollectionRegion getRegion() { - return region; + return region(); } -} \ No newline at end of file +} diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheEntityRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheEntityRegionAccessStrategy.java index 31ecd277e8..1cf14387f0 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheEntityRegionAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheEntityRegionAccessStrategy.java @@ -42,21 +42,25 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy /** * Create a read/write access strategy accessing the given entity region. + * + * @param region The wrapped region + * @param settings The Hibernate settings */ public ReadWriteEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region, Settings settings) { super( region, settings ); } - /** - * {@inheritDoc} - */ + @Override public EntityRegion getRegion() { - return region; + return region(); } /** + * {@inheritDoc} + *

      * A no-op since this is an asynchronous cache access strategy. */ + @Override public boolean insert(Object key, Object value, Object version) throws CacheException { return false; } @@ -66,12 +70,13 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy *

      * Inserts will only succeed if there is no existing value mapped to this key. */ + @Override public boolean afterInsert(Object key, Object value, Object version) throws CacheException { - region.writeLock( key ); + region().writeLock( key ); try { - Lockable item = (Lockable) region.get( key ); + final Lockable item = (Lockable) region().get( key ); if ( item == null ) { - region.put( key, new Item( value, version, region.nextTimestamp() ) ); + region().put( key, new Item( value, version, region().nextTimestamp() ) ); return true; } else { @@ -79,13 +84,16 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy } } finally { - region.writeUnlock( key ); + region().writeUnlock( key ); } } /** + * {@inheritDoc} + *

      * A no-op since this is an asynchronous cache access strategy. */ + @Override public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { return false; @@ -98,12 +106,13 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy * duration of this transaction. It is important to also note that updates will fail if the soft-lock expired during * the course of this transaction. */ + @Override public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) throws CacheException { //what should we do with previousVersion here? - region.writeLock( key ); + region().writeLock( key ); try { - Lockable item = (Lockable) region.get( key ); + final Lockable item = (Lockable) region().get( key ); if ( item != null && item.isUnlockable( lock ) ) { Lock lockItem = (Lock) item; @@ -112,7 +121,7 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy return false; } else { - region.put( key, new Item( value, currentVersion, region.nextTimestamp() ) ); + region().put( key, new Item( value, currentVersion, region().nextTimestamp() ) ); return true; } } @@ -122,7 +131,7 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy } } finally { - region.writeUnlock( key ); + region().writeUnlock( key ); } } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheNaturalIdRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheNaturalIdRegionAccessStrategy.java index 6d287f0bf7..ef40d5dd82 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheNaturalIdRegionAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheNaturalIdRegionAccessStrategy.java @@ -42,22 +42,26 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy /** * Create a read/write access strategy accessing the given NaturalId region. + * + * @param region The wrapped region + * @param settings The Hibernate settings */ public ReadWriteEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region, Settings settings) { super( region, settings ); } - /** - * {@inheritDoc} - */ + @Override public NaturalIdRegion getRegion() { - return region; + return region(); } /** + * {@inheritDoc} + *

      * A no-op since this is an asynchronous cache access strategy. */ - public boolean insert(Object key, Object value ) throws CacheException { + @Override + public boolean insert(Object key, Object value) throws CacheException { return false; } @@ -66,12 +70,13 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy *

      * Inserts will only succeed if there is no existing value mapped to this key. */ - public boolean afterInsert(Object key, Object value ) throws CacheException { - region.writeLock( key ); + @Override + public boolean afterInsert(Object key, Object value) throws CacheException { + region().writeLock( key ); try { - Lockable item = (Lockable) region.get( key ); + final Lockable item = (Lockable) region().get( key ); if ( item == null ) { - region.put( key, new Item( value, null, region.nextTimestamp() ) ); + region().put( key, new Item( value, null, region().nextTimestamp() ) ); return true; } else { @@ -79,15 +84,17 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy } } finally { - region.writeUnlock( key ); + region().writeUnlock( key ); } } /** + * {@inheritDoc} + *

      * A no-op since this is an asynchronous cache access strategy. */ - public boolean update(Object key, Object value ) - throws CacheException { + @Override + public boolean update(Object key, Object value) throws CacheException { return false; } @@ -98,20 +105,21 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy * duration of this transaction. It is important to also note that updates will fail if the soft-lock expired during * the course of this transaction. */ + @Override public boolean afterUpdate(Object key, Object value, SoftLock lock) throws CacheException { //what should we do with previousVersion here? - region.writeLock( key ); + region().writeLock( key ); try { - Lockable item = (Lockable) region.get( key ); + final Lockable item = (Lockable) region().get( key ); if ( item != null && item.isUnlockable( lock ) ) { - Lock lockItem = (Lock) item; + final Lock lockItem = (Lock) item; if ( lockItem.wasLockedConcurrently() ) { decrementLock( key, lockItem ); return false; } else { - region.put( key, new Item( value, null, region.nextTimestamp() ) ); + region().put( key, new Item( value, null, region().nextTimestamp() ) ); return true; } } @@ -121,7 +129,7 @@ public class ReadWriteEhcacheNaturalIdRegionAccessStrategy } } finally { - region.writeUnlock( key ); + region().writeUnlock( key ); } } -} \ No newline at end of file +} diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheCollectionRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheCollectionRegionAccessStrategy.java index e6e120ce97..5b76fbd653 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheCollectionRegionAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheCollectionRegionAccessStrategy.java @@ -53,44 +53,42 @@ public class TransactionalEhcacheCollectionRegionAccessStrategy * @param ehcache the cache. * @param settings the Hibernate settings. */ - public TransactionalEhcacheCollectionRegionAccessStrategy(EhcacheCollectionRegion region, Ehcache ehcache, Settings settings) { + public TransactionalEhcacheCollectionRegionAccessStrategy( + EhcacheCollectionRegion region, + Ehcache ehcache, + Settings settings) { super( region, settings ); this.ehcache = ehcache; } - - /** - * {@inheritDoc} - */ + @Override public Object get(Object key, long txTimestamp) throws CacheException { try { - Element element = ehcache.get( key ); + final Element element = ehcache.get( key ); return element == null ? null : element.getObjectValue(); } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } - /** - * {@inheritDoc} - */ + @Override public CollectionRegion getRegion() { - return region; + return region(); } - /** - * {@inheritDoc} - */ + @Override public SoftLock lockItem(Object key, Object version) throws CacheException { return null; } - /** - * {@inheritDoc} - */ - public boolean putFromLoad(Object key, Object value, long txTimestamp, - Object version, boolean minimalPutOverride) throws CacheException { + @Override + public boolean putFromLoad( + Object key, + Object value, + long txTimestamp, + Object version, + boolean minimalPutOverride) throws CacheException { try { if ( minimalPutOverride && ehcache.get( key ) != null ) { return false; @@ -99,27 +97,22 @@ public class TransactionalEhcacheCollectionRegionAccessStrategy ehcache.put( new Element( key, value ) ); return true; } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } - /** - * {@inheritDoc} - */ @Override public void remove(Object key) throws CacheException { try { ehcache.remove( key ); } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } - /** - * {@inheritDoc} - */ + @Override public void unlockItem(Object key, SoftLock lock) throws CacheException { // no-op } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheEntityRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheEntityRegionAccessStrategy.java index b5ac353cfe..1e0bb318dd 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheEntityRegionAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheEntityRegionAccessStrategy.java @@ -52,48 +52,41 @@ public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhca * @param ehcache the cache. * @param settings the Hibernate settings. */ - public TransactionalEhcacheEntityRegionAccessStrategy(EhcacheEntityRegion region, Ehcache ehcache, Settings settings) { + public TransactionalEhcacheEntityRegionAccessStrategy( + EhcacheEntityRegion region, + Ehcache ehcache, + Settings settings) { super( region, settings ); this.ehcache = ehcache; } - /** - * {@inheritDoc} - */ + @Override public boolean afterInsert(Object key, Object value, Object version) { return false; } - /** - * {@inheritDoc} - */ + @Override public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) { return false; } - /** - * {@inheritDoc} - */ + @Override public Object get(Object key, long txTimestamp) throws CacheException { try { - Element element = ehcache.get( key ); + final Element element = ehcache.get( key ); return element == null ? null : element.getObjectValue(); } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } - /** - * {@inheritDoc} - */ + @Override public EntityRegion getRegion() { - return region; + return region(); } - /** - * {@inheritDoc} - */ + @Override public boolean insert(Object key, Object value, Object version) throws CacheException { //OptimisticCache? versioning? @@ -101,23 +94,23 @@ public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhca ehcache.put( new Element( key, value ) ); return true; } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } - /** - * {@inheritDoc} - */ + @Override public SoftLock lockItem(Object key, Object version) throws CacheException { return null; } - /** - * {@inheritDoc} - */ - public boolean putFromLoad(Object key, Object value, long txTimestamp, - Object version, boolean minimalPutOverride) throws CacheException { + @Override + public boolean putFromLoad( + Object key, + Object value, + long txTimestamp, + Object version, + boolean minimalPutOverride) throws CacheException { try { if ( minimalPutOverride && ehcache.get( key ) != null ) { return false; @@ -126,41 +119,37 @@ public class TransactionalEhcacheEntityRegionAccessStrategy extends AbstractEhca ehcache.put( new Element( key, value ) ); return true; } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } - /** - * {@inheritDoc} - */ @Override public void remove(Object key) throws CacheException { try { ehcache.remove( key ); } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } - /** - * {@inheritDoc} - */ + @Override public void unlockItem(Object key, SoftLock lock) throws CacheException { // no-op } - /** - * {@inheritDoc} - */ - public boolean update(Object key, Object value, Object currentVersion, - Object previousVersion) throws CacheException { + @Override + public boolean update( + Object key, + Object value, + Object currentVersion, + Object previousVersion) throws CacheException { try { ehcache.put( new Element( key, value ) ); return true; } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheNaturalIdRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheNaturalIdRegionAccessStrategy.java index f87461312a..653e036e7d 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheNaturalIdRegionAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/TransactionalEhcacheNaturalIdRegionAccessStrategy.java @@ -53,72 +53,64 @@ public class TransactionalEhcacheNaturalIdRegionAccessStrategy * @param ehcache the cache. * @param settings the Hibernate settings. */ - public TransactionalEhcacheNaturalIdRegionAccessStrategy(EhcacheNaturalIdRegion region, Ehcache ehcache, Settings settings) { + public TransactionalEhcacheNaturalIdRegionAccessStrategy( + EhcacheNaturalIdRegion region, + Ehcache ehcache, + Settings settings) { super( region, settings ); this.ehcache = ehcache; } - /** - * {@inheritDoc} - */ - public boolean afterInsert(Object key, Object value ) { + @Override + public boolean afterInsert(Object key, Object value) { return false; } - /** - * {@inheritDoc} - */ + @Override public boolean afterUpdate(Object key, Object value, SoftLock lock) { return false; } - - /** - * {@inheritDoc} - */ + @Override public Object get(Object key, long txTimestamp) throws CacheException { try { - Element element = ehcache.get( key ); + final Element element = ehcache.get( key ); return element == null ? null : element.getObjectValue(); } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } - /** - * {@inheritDoc} - */ + @Override public NaturalIdRegion getRegion() { - return region; + return region(); } - /** - * {@inheritDoc} - */ - public boolean insert(Object key, Object value ) throws CacheException { + @Override + public boolean insert(Object key, Object value) throws CacheException { //OptimisticCache? versioning? try { ehcache.put( new Element( key, value ) ); return true; } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } - /** - * {@inheritDoc} - */ + @Override public SoftLock lockItem(Object key, Object version) throws CacheException { return null; } - /** - * {@inheritDoc} - */ - public boolean putFromLoad(Object key, Object value, long txTimestamp, - Object version, boolean minimalPutOverride) throws CacheException { + @Override + public boolean putFromLoad( + Object key, + Object value, + long txTimestamp, + Object version, + boolean minimalPutOverride) throws CacheException { try { if ( minimalPutOverride && ehcache.get( key ) != null ) { return false; @@ -127,40 +119,33 @@ public class TransactionalEhcacheNaturalIdRegionAccessStrategy ehcache.put( new Element( key, value ) ); return true; } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } - /** - * {@inheritDoc} - */ @Override public void remove(Object key) throws CacheException { try { ehcache.remove( key ); } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } - /** - * {@inheritDoc} - */ + @Override public void unlockItem(Object key, SoftLock lock) throws CacheException { // no-op } - /** - * {@inheritDoc} - */ - public boolean update(Object key, Object value ) throws CacheException { + @Override + public boolean update(Object key, Object value) throws CacheException { try { ehcache.put( new Element( key, value ) ); return true; } - catch ( net.sf.ehcache.CacheException e ) { + catch (net.sf.ehcache.CacheException e) { throw new CacheException( e ); } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/package-info.java new file mode 100644 index 0000000000..f055c0e74d --- /dev/null +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/package-info.java @@ -0,0 +1,4 @@ +/** + * Defines {@link org.hibernate.cache.spi.access.RegionAccessStrategy} support for the Ehcache integration + */ +package org.hibernate.cache.ehcache.internal.strategy; diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateEhcacheUtils.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateEhcacheUtils.java new file mode 100644 index 0000000000..6167af991e --- /dev/null +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateEhcacheUtils.java @@ -0,0 +1,129 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2011, 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.cache.ehcache.internal.util; + +import java.net.URL; + +import net.sf.ehcache.Ehcache; +import net.sf.ehcache.config.CacheConfiguration; +import net.sf.ehcache.config.Configuration; +import net.sf.ehcache.config.ConfigurationFactory; +import net.sf.ehcache.config.NonstopConfiguration; +import net.sf.ehcache.config.TerracottaConfiguration; +import net.sf.ehcache.config.TerracottaConfiguration.ValueMode; +import net.sf.ehcache.config.TimeoutBehaviorConfiguration.TimeoutBehaviorType; + +import org.jboss.logging.Logger; + +import org.hibernate.cache.CacheException; +import org.hibernate.cache.ehcache.EhCacheMessageLogger; + + +/** + * Copy of Ehcache utils into Hibernate code base + * + * @author Chris Dennis + * @author Abhishek Sanoujam + * @author Alex Snaps + */ +public final class HibernateEhcacheUtils { + private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( + EhCacheMessageLogger.class, + HibernateEhcacheUtils.class.getName() + ); + + private HibernateEhcacheUtils() { + } + + /** + * Create a cache manager configuration from the supplied url, correcting it for Hibernate compatibility. + *

      + * Currently "correcting" for Hibernate compatibility means simply switching any identity based value modes + * to serialization. + * + * @param url The url to load the config from + * + * @return The Ehcache Configuration object + */ + public static Configuration loadAndCorrectConfiguration(URL url) { + final Configuration config = ConfigurationFactory.parseConfiguration( url ); + if ( config.getDefaultCacheConfiguration().isTerracottaClustered() ) { + if ( ValueMode.IDENTITY + .equals( config.getDefaultCacheConfiguration().getTerracottaConfiguration().getValueMode() ) ) { + LOG.incompatibleCacheValueMode(); + config.getDefaultCacheConfiguration() + .getTerracottaConfiguration() + .setValueMode( ValueMode.SERIALIZATION.name() ); + } + setupHibernateTimeoutBehavior( + config.getDefaultCacheConfiguration() + .getTerracottaConfiguration() + .getNonstopConfiguration() + ); + } + + for ( CacheConfiguration cacheConfig : config.getCacheConfigurations().values() ) { + if ( cacheConfig.isTerracottaClustered() ) { + if ( ValueMode.IDENTITY.equals( cacheConfig.getTerracottaConfiguration().getValueMode() ) ) { + LOG.incompatibleCacheValueModePerCache( cacheConfig.getName() ); + cacheConfig.getTerracottaConfiguration().setValueMode( ValueMode.SERIALIZATION.name() ); + } + setupHibernateTimeoutBehavior( cacheConfig.getTerracottaConfiguration().getNonstopConfiguration() ); + } + } + return config; + } + + private static void setupHibernateTimeoutBehavior(NonstopConfiguration nonstopConfig) { + nonstopConfig.getTimeoutBehavior().setType( TimeoutBehaviorType.EXCEPTION.getTypeName() ); + } + + /** + * Validates that the supplied Ehcache instance is valid for use as a Hibernate cache. + * + * @param cache The cache instance + * + * @throws CacheException If any explicit settings on the cache are not validate + */ + public static void validateEhcache(Ehcache cache) throws CacheException { + final CacheConfiguration cacheConfig = cache.getCacheConfiguration(); + + if ( cacheConfig.isTerracottaClustered() ) { + final TerracottaConfiguration tcConfig = cacheConfig.getTerracottaConfiguration(); + switch ( tcConfig.getValueMode() ) { + case IDENTITY: { + throw new CacheException( + "The clustered Hibernate cache " + cache.getName() + " is using IDENTITY value mode.\n" + + "Identity value mode cannot be used with Hibernate cache regions." + ); + } + case SERIALIZATION: + default: { + // this is the recommended valueMode + break; + } + } + } + } +} diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateUtil.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateUtil.java deleted file mode 100644 index 7d66b8820d..0000000000 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/HibernateUtil.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Hibernate, Relational Persistence for Idiomatic Java - * - * Copyright (c) 2011, 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.cache.ehcache.internal.util; - -import java.net.URL; - -import net.sf.ehcache.Ehcache; -import net.sf.ehcache.config.CacheConfiguration; -import net.sf.ehcache.config.Configuration; -import net.sf.ehcache.config.ConfigurationFactory; -import net.sf.ehcache.config.NonstopConfiguration; -import net.sf.ehcache.config.TerracottaConfiguration; -import net.sf.ehcache.config.TerracottaConfiguration.ValueMode; -import net.sf.ehcache.config.TimeoutBehaviorConfiguration.TimeoutBehaviorType; -import org.jboss.logging.Logger; - -import org.hibernate.cache.CacheException; -import org.hibernate.cache.ehcache.EhCacheMessageLogger; - - -/** - * @author Chris Dennis - * @author Abhishek Sanoujam - * @author Alex Snaps - */ -public final class HibernateUtil { - - private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( - EhCacheMessageLogger.class, - HibernateUtil.class.getName() - ); - - private HibernateUtil() { - } - - /** - * Create a cache manager configuration from the supplied url, correcting it for Hibernate compatibility. - *

      - * Currently correcting for Hibernate compatibility means simply switching any identity based value modes to serialization. - */ - public static Configuration loadAndCorrectConfiguration(URL url) { - Configuration config = ConfigurationFactory.parseConfiguration( url ); - if ( config.getDefaultCacheConfiguration().isTerracottaClustered() ) { - if ( ValueMode.IDENTITY - .equals( config.getDefaultCacheConfiguration().getTerracottaConfiguration().getValueMode() ) ) { - LOG.incompatibleCacheValueMode(); - config.getDefaultCacheConfiguration() - .getTerracottaConfiguration() - .setValueMode( ValueMode.SERIALIZATION.name() ); - } - setupHibernateTimeoutBehavior( - config.getDefaultCacheConfiguration() - .getTerracottaConfiguration() - .getNonstopConfiguration() - ); - } - - for ( CacheConfiguration cacheConfig : config.getCacheConfigurations().values() ) { - if ( cacheConfig.isTerracottaClustered() ) { - if ( ValueMode.IDENTITY.equals( cacheConfig.getTerracottaConfiguration().getValueMode() ) ) { - LOG.incompatibleCacheValueModePerCache( cacheConfig.getName() ); - cacheConfig.getTerracottaConfiguration().setValueMode( ValueMode.SERIALIZATION.name() ); - } - setupHibernateTimeoutBehavior( cacheConfig.getTerracottaConfiguration().getNonstopConfiguration() ); - } - } - return config; - } - - private static void setupHibernateTimeoutBehavior(NonstopConfiguration nonstopConfig) { - nonstopConfig.getTimeoutBehavior().setType( TimeoutBehaviorType.EXCEPTION.getTypeName() ); - } - - /** - * Validates that the supplied Ehcache instance is valid for use as a Hibernate cache. - */ - public static void validateEhcache(Ehcache cache) throws CacheException { - CacheConfiguration cacheConfig = cache.getCacheConfiguration(); - - if ( cacheConfig.isTerracottaClustered() ) { - TerracottaConfiguration tcConfig = cacheConfig.getTerracottaConfiguration(); - switch ( tcConfig.getValueMode() ) { - case IDENTITY: - throw new CacheException( - "The clustered Hibernate cache " + cache.getName() + " is using IDENTITY value mode.\n" - + "Identity value mode cannot be used with Hibernate cache regions." - ); - case SERIALIZATION: - default: - // this is the recommended valueMode - break; - } - } - } -} \ No newline at end of file diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/package-info.java new file mode 100644 index 0000000000..5c6a04407f --- /dev/null +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/util/package-info.java @@ -0,0 +1,4 @@ +/** + * Defines utilities used by the Ehcache integration + */ +package org.hibernate.cache.ehcache.internal.util; diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BaseEmitterBean.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/AbstractEmitterBean.java similarity index 69% rename from hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BaseEmitterBean.java rename to hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/AbstractEmitterBean.java index 2c6a6d27f5..5d3f3abc31 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BaseEmitterBean.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/AbstractEmitterBean.java @@ -24,9 +24,6 @@ package org.hibernate.cache.ehcache.management.impl; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicLong; import javax.management.ListenerNotFoundException; import javax.management.MBeanNotificationInfo; import javax.management.NotCompliantMBeanException; @@ -36,64 +33,61 @@ import javax.management.NotificationEmitter; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.StandardMBean; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicLong; /** + * Base MBean impl + * * @author gkeim */ -public abstract class BaseEmitterBean extends StandardMBean implements NotificationEmitter { - /** - * emitter - */ - protected final Emitter emitter = new Emitter(); - - /** - * sequenceNumber - */ - protected final AtomicLong sequenceNumber = new AtomicLong(); - +public abstract class AbstractEmitterBean extends StandardMBean implements NotificationEmitter { + private final Emitter emitter = new Emitter(); + private final AtomicLong sequenceNumber = new AtomicLong(); private final List notificationListeners = new CopyOnWriteArrayList(); /** - * BaseEmitterBean + * Constructs a AbstractEmitterBean * - * @param - * @param mbeanInterface + * @param mbeanInterface The MBean contract + * @param Not used as far as I can see * - * @throws javax.management.NotCompliantMBeanException + * @throws javax.management.NotCompliantMBeanException thrown from JMX super ctor */ - protected BaseEmitterBean(Class mbeanInterface) throws NotCompliantMBeanException { + protected AbstractEmitterBean(Class mbeanInterface) throws NotCompliantMBeanException { super( mbeanInterface ); } /** - * sendNotification + * Sends notification of an event * - * @param eventType + * @param eventType The type of event */ public void sendNotification(String eventType) { sendNotification( eventType, null, null ); } /** - * sendNotification + * Sends notification of an event * - * @param eventType - * @param data + * @param eventType The type of event + * @param data The event data */ public void sendNotification(String eventType, Object data) { sendNotification( eventType, data, null ); } /** - * sendNotification + * Sends notification of an event * - * @param eventType - * @param data - * @param msg + * @param eventType The type of event + * @param data The event data + * @param msg A message */ public void sendNotification(String eventType, Object data, String msg) { - Notification notif = new Notification( + final Notification notification = new Notification( eventType, this, sequenceNumber.incrementAndGet(), @@ -101,9 +95,9 @@ public abstract class BaseEmitterBean extends StandardMBean implements Notificat msg ); if ( data != null ) { - notif.setUserData( data ); + notification.setUserData( data ); } - emitter.sendNotification( notif ); + emitter.sendNotification( notification ); } /** @@ -119,61 +113,42 @@ public abstract class BaseEmitterBean extends StandardMBean implements Notificat */ protected abstract void doDispose(); - /** - * @author gkeim - */ private class Emitter extends NotificationBroadcasterSupport { - /** - * @see javax.management.NotificationBroadcasterSupport#getNotificationInfo() - */ @Override public MBeanNotificationInfo[] getNotificationInfo() { - return BaseEmitterBean.this.getNotificationInfo(); + return AbstractEmitterBean.this.getNotificationInfo(); } } - /** - * @see javax.management.NotificationBroadcaster#addNotificationListener(javax.management.NotificationListener, - * javax.management.NotificationFilter, java.lang.Object) - */ + @Override public void addNotificationListener(NotificationListener notif, NotificationFilter filter, Object callBack) { emitter.addNotificationListener( notif, filter, callBack ); notificationListeners.add( notif ); } - /** - * remove all added notification listeners - */ private void removeAllNotificationListeners() { for ( NotificationListener listener : notificationListeners ) { try { emitter.removeNotificationListener( listener ); } - catch ( ListenerNotFoundException e ) { + catch (ListenerNotFoundException e) { // ignore } } notificationListeners.clear(); } - /** - * @see javax.management.NotificationBroadcaster#getNotificationInfo() - */ + @Override public abstract MBeanNotificationInfo[] getNotificationInfo(); - /** - * @see javax.management.NotificationBroadcaster#removeNotificationListener(javax.management.NotificationListener) - */ + @Override public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { emitter.removeNotificationListener( listener ); notificationListeners.remove( listener ); } - /** - * @see javax.management.NotificationEmitter#removeNotificationListener(javax.management.NotificationListener, - * javax.management.NotificationFilter, java.lang.Object) - */ + @Override public void removeNotificationListener(NotificationListener notif, NotificationFilter filter, Object callBack) throws ListenerNotFoundException { emitter.removeNotificationListener( notif, filter, callBack ); diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BeanUtils.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BeanUtils.java index 1352c0fbfc..afcd716ae7 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BeanUtils.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/BeanUtils.java @@ -36,17 +36,17 @@ public class BeanUtils { /** * Return the named getter method on the bean or null if not found. * - * @param bean - * @param propertyName + * @param bean The bean + * @param propertyName The property to get the getter for * * @return the named getter method */ private static Method getMethod(Object bean, String propertyName) { - StringBuilder sb = new StringBuilder( "get" ).append( Character.toUpperCase( propertyName.charAt( 0 ) ) ); + final StringBuilder sb = new StringBuilder( "get" ).append( Character.toUpperCase( propertyName.charAt( 0 ) ) ); if ( propertyName.length() > 1 ) { sb.append( propertyName.substring( 1 ) ); } - String getterName = sb.toString(); + final String getterName = sb.toString(); for ( Method m : bean.getClass().getMethods() ) { if ( getterName.equals( m.getName() ) && m.getParameterTypes().length == 0 ) { return m; @@ -55,14 +55,6 @@ public class BeanUtils { return null; } - /** - * Return the named field on the bean or null if not found. - * - * @param bean - * @param propertyName - * - * @return the named field - */ private static Field getField(Object bean, String propertyName) { for ( Field f : bean.getClass().getDeclaredFields() ) { if ( propertyName.equals( f.getName() ) ) { @@ -87,8 +79,8 @@ public class BeanUtils { /** * Retrieve a named bean property value. * - * @param bean bean - * @param propertyName + * @param bean The bean instance + * @param propertyName The name of the property whose value to extract * * @return the property value */ @@ -96,24 +88,24 @@ public class BeanUtils { validateArgs( bean, propertyName ); // try getters first - Method getter = getMethod( bean, propertyName ); + final Method getter = getMethod( bean, propertyName ); if ( getter != null ) { try { return getter.invoke( bean ); } - catch ( Exception e ) { + catch (Exception e) { /**/ } } // then try fields - Field field = getField( bean, propertyName ); + final Field field = getField( bean, propertyName ); if ( field != null ) { try { field.setAccessible( true ); return field.get( bean ); } - catch ( Exception e ) { + catch (Exception e) { /**/ } } @@ -124,22 +116,25 @@ public class BeanUtils { /** * Retrieve a Long bean property value. * - * @param bean bean - * @param propertyName + * @param bean The bean instance + * @param propertyName The name of the property whose value to extract * * @return long value * - * @throws NoSuchFieldException + * @throws NoSuchFieldException If the value is null (wow) */ public static long getLongBeanProperty(final Object bean, final String propertyName) throws NoSuchFieldException { validateArgs( bean, propertyName ); - Object o = getBeanProperty( bean, propertyName ); + final Object o = getBeanProperty( bean, propertyName ); if ( o == null ) { throw new NoSuchFieldException( propertyName ); } - else if ( !( o instanceof Number ) ) { + else if ( !(o instanceof Number) ) { throw new IllegalArgumentException( propertyName + " not an Number" ); } - return ( (Number) o ).longValue(); + return ((Number) o).longValue(); + } + + private BeanUtils() { } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionStats.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionStats.java index 677f217d1f..9f1264a56b 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionStats.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionStats.java @@ -23,10 +23,6 @@ */ package org.hibernate.cache.ehcache.management.impl; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeDataSupport; import javax.management.openmbean.CompositeType; @@ -36,10 +32,15 @@ import javax.management.openmbean.SimpleType; import javax.management.openmbean.TabularData; import javax.management.openmbean.TabularDataSupport; import javax.management.openmbean.TabularType; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; import org.hibernate.stat.SecondLevelCacheStatistics; /** + * Bean for exposing region stats + * * @author gkeim */ public class CacheRegionStats implements Serializable { @@ -61,7 +62,7 @@ public class CacheRegionStats implements Serializable { private static final CompositeType COMPOSITE_TYPE; private static final String TABULAR_TYPE_NAME = "Statistics by Cache-region"; private static final String TABULAR_TYPE_DESCRIPTION = "All Cache Region Statistics"; - private static final String[] INDEX_NAMES = new String[] { "region", }; + private static final String[] INDEX_NAMES = new String[] {"region",}; private static final TabularType TABULAR_TYPE; static { @@ -72,7 +73,7 @@ public class CacheRegionStats implements Serializable { ); TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES ); } - catch ( OpenDataException e ) { + catch (OpenDataException e) { throw new RuntimeException( e ); } } @@ -123,7 +124,9 @@ public class CacheRegionStats implements Serializable { protected long elementCountTotal; /** - * @param region + * Construct a CacheRegionStats + * + * @param region The region name */ public CacheRegionStats(String region) { this.region = region; @@ -131,8 +134,10 @@ public class CacheRegionStats implements Serializable { } /** - * @param region - * @param src + * Construct a CacheRegionStats + * + * @param region The region name + * @param src The SecondLevelCacheStatistics reference */ public CacheRegionStats(String region, SecondLevelCacheStatistics src) { this( region ); @@ -146,15 +151,18 @@ public class CacheRegionStats implements Serializable { this.elementCountOnDisk = BeanUtils.getLongBeanProperty( src, "elementCountOnDisk" ); this.elementCountTotal = BeanUtils.getLongBeanProperty( src, "elementCountOnDisk" ); } - catch ( Exception e ) { + catch (Exception e) { e.printStackTrace(); throw new RuntimeException( "Exception retrieving statistics", e ); } } /** - * @param cData + * Construct a CacheRegionStats + * + * @param cData No idea */ + @SuppressWarnings("UnusedAssignment") public CacheRegionStats(final CompositeData cData) { int i = 0; region = (String) cData.get( ITEM_NAMES[i++] ); @@ -168,30 +176,15 @@ public class CacheRegionStats implements Serializable { elementCountTotal = (Long) cData.get( ITEM_NAMES[i++] ); } - private static int safeParseInt(String s) { - try { - return Integer.parseInt( s ); - } - catch ( Exception e ) { - return -1; - } - } - - /** - * @return hit ratio - */ protected double determineHitRatio() { + final long readCount = getHitCount() + getMissCount(); double result = 0; - long readCount = getHitCount() + getMissCount(); if ( readCount > 0 ) { - result = getHitCount() / ( (double) readCount ); + result = getHitCount() / ((double) readCount); } return result; } - /** - * @see java.lang.Object#toString() - */ @Override public String toString() { return "region=" + getRegion() + "shortName=" + getShortName() + ", hitCount=" + getHitCount() + ", missCount=" @@ -200,70 +193,45 @@ public class CacheRegionStats implements Serializable { + getElementCountTotal(); } - /** - * @return region name - */ public String getRegion() { return region; } - /** - * @return short name - */ public String getShortName() { return shortName; } - /** - * @return hit count - */ public long getHitCount() { return hitCount; } - /** - * @return miss count - */ public long getMissCount() { return missCount; } - /** - * @return put count - */ public long getPutCount() { return putCount; } - /** - * @return hit ratio - */ public double getHitRatio() { return hitRatio; } - /** - * @return in-memory element count - */ public long getElementCountInMemory() { return elementCountInMemory; } - /** - * @return on-disk element count - */ public long getElementCountOnDisk() { return elementCountOnDisk; } - /** - * @return total element count - */ public long getElementCountTotal() { return elementCountTotal; } /** + * Convert our state into a JMX CompositeData + * * @return composite data */ public CompositeData toCompositeData() { @@ -276,12 +244,14 @@ public class CacheRegionStats implements Serializable { } ); } - catch ( OpenDataException e ) { + catch (OpenDataException e) { throw new RuntimeException( e ); } } /** + * Convert our state into a JMX TabularData + * * @return tabular data */ public static TabularData newTabularDataInstance() { @@ -289,14 +259,17 @@ public class CacheRegionStats implements Serializable { } /** - * @param tabularData + * Re-build the CacheRegionStats from JMX tabular data + * + * @param tabularData The JMX tabular data * * @return array of region statistics */ + @SuppressWarnings("UnusedDeclaration") public static CacheRegionStats[] fromTabularData(final TabularData tabularData) { - final List countList = new ArrayList( tabularData.size() ); - for ( final Iterator pos = tabularData.values().iterator(); pos.hasNext(); ) { - countList.add( new CacheRegionStats( (CompositeData) pos.next() ) ); + final List countList = new ArrayList( tabularData.size() ); + for ( Object o : tabularData.values() ) { + countList.add( new CacheRegionStats( (CompositeData) o ) ); } return countList.toArray( new CacheRegionStats[countList.size()] ); } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionUtils.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionUtils.java index 023876fa68..267486a6a2 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionUtils.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CacheRegionUtils.java @@ -23,13 +23,14 @@ */ package org.hibernate.cache.ehcache.management.impl; -import java.awt.*; +import java.awt.Color; /** * CacheRegionUtils * * @author gkeim */ +@SuppressWarnings("UnusedDeclaration") public abstract class CacheRegionUtils { /** * HIT_COLOR @@ -49,51 +50,53 @@ public abstract class CacheRegionUtils { /** * HIT_FILL_COLOR */ - public final static Color HIT_FILL_COLOR = CacheRegionUtils.HIT_COLOR.brighter().brighter().brighter(); + public static final Color HIT_FILL_COLOR = CacheRegionUtils.HIT_COLOR.brighter().brighter().brighter(); /** * MISS_FILL_COLOR */ - public final static Color MISS_FILL_COLOR = CacheRegionUtils.MISS_COLOR.brighter().brighter().brighter(); + public static final Color MISS_FILL_COLOR = CacheRegionUtils.MISS_COLOR.brighter().brighter().brighter(); /** * PUT_FILL_COLOR */ - public final static Color PUT_FILL_COLOR = CacheRegionUtils.PUT_COLOR.brighter().brighter().brighter(); + public static final Color PUT_FILL_COLOR = CacheRegionUtils.PUT_COLOR.brighter().brighter().brighter(); /** * HIT_DRAW_COLOR */ - public final static Color HIT_DRAW_COLOR = CacheRegionUtils.HIT_COLOR.darker(); + public static final Color HIT_DRAW_COLOR = CacheRegionUtils.HIT_COLOR.darker(); /** * MISS_DRAW_COLOR */ - public final static Color MISS_DRAW_COLOR = CacheRegionUtils.MISS_COLOR.darker(); + public static final Color MISS_DRAW_COLOR = CacheRegionUtils.MISS_COLOR.darker(); /** * PUT_DRAW_COLOR */ - public final static Color PUT_DRAW_COLOR = CacheRegionUtils.PUT_COLOR.darker(); + public static final Color PUT_DRAW_COLOR = CacheRegionUtils.PUT_COLOR.darker(); /** - * determineShortName + * Determine a short name from the full name * - * @param fullName + * @param fullName The full name + * + * @return The short name */ public static String determineShortName(String fullName) { String result = fullName; if ( fullName != null ) { - String[] comps = fullName.split( "\\." ); + final String[] comps = fullName.split( "\\." ); if ( comps.length == 1 ) { return fullName; } boolean truncate = true; for ( int i = 0; i < comps.length; i++ ) { String comp = comps[i]; - char c = comp.charAt( 0 ); + final char c = comp.charAt( 0 ); if ( truncate && Character.isUpperCase( c ) ) { truncate = false; } @@ -108,16 +111,18 @@ public abstract class CacheRegionUtils { } /** - * join + * Same as Hibernate internal {@link org.hibernate.internal.util.StringHelper#join} methods * - * @param elements - * @param c + * @param elements The things to join + * @param c The separator between elements + * + * @return The joined string */ private static String join(String[] elements, char c) { if ( elements == null ) { return null; } - StringBuilder sb = new StringBuilder(); + final StringBuilder sb = new StringBuilder(); for ( String s : elements ) { sb.append( s ).append( c ); } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CollectionStats.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CollectionStats.java index a6eebe5280..667a3ab8b3 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CollectionStats.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/CollectionStats.java @@ -23,10 +23,6 @@ */ package org.hibernate.cache.ehcache.management.impl; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeDataSupport; import javax.management.openmbean.CompositeType; @@ -36,6 +32,9 @@ import javax.management.openmbean.SimpleType; import javax.management.openmbean.TabularData; import javax.management.openmbean.TabularDataSupport; import javax.management.openmbean.TabularType; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; import org.hibernate.stat.CollectionStatistics; @@ -62,7 +61,7 @@ public class CollectionStats implements Serializable { private static final CompositeType COMPOSITE_TYPE; private static final String TABULAR_TYPE_NAME = "Statistics by Collection"; private static final String TABULAR_TYPE_DESCRIPTION = "All Collection Statistics"; - private static final String[] INDEX_NAMES = new String[] { "roleName", }; + private static final String[] INDEX_NAMES = new String[] {"roleName",}; private static final TabularType TABULAR_TYPE; static { @@ -73,7 +72,7 @@ public class CollectionStats implements Serializable { ); TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES ); } - catch ( OpenDataException e ) { + catch (OpenDataException e) { throw new RuntimeException( e ); } } @@ -115,19 +114,23 @@ public class CollectionStats implements Serializable { /** - * @param roleName + * Constructs a CollectionsStats + * + * @param role The collection role */ - public CollectionStats(String roleName) { - this.roleName = roleName; - this.shortName = CacheRegionUtils.determineShortName( roleName ); + public CollectionStats(String role) { + this.roleName = role; + this.shortName = CacheRegionUtils.determineShortName( role ); } /** - * @param name - * @param src + * Constructs a CollectionsStats + * + * @param role The collection role + * @param src The CollectionStatistics instance */ - public CollectionStats(String name, CollectionStatistics src) { - this( name ); + public CollectionStats(String role, CollectionStatistics src) { + this( role ); try { this.loadCount = BeanUtils.getLongBeanProperty( src, "loadCount" ); @@ -136,15 +139,18 @@ public class CollectionStats implements Serializable { this.removeCount = BeanUtils.getLongBeanProperty( src, "removeCount" ); this.recreateCount = BeanUtils.getLongBeanProperty( src, "recreateCount" ); } - catch ( Exception e ) { + catch (Exception e) { e.printStackTrace(); throw new RuntimeException( "Exception retrieving statistics", e ); } } /** - * @param cData + * Constructs a CollectionsStats from a JMX CompositeData + * + * @param cData The JMX CompositeData */ + @SuppressWarnings("UnusedAssignment") public CollectionStats(final CompositeData cData) { int i = 0; roleName = (String) cData.get( ITEM_NAMES[i++] ); @@ -156,17 +162,10 @@ public class CollectionStats implements Serializable { recreateCount = (Long) cData.get( ITEM_NAMES[i++] ); } - private static int safeParseInt(String s) { - try { - return Integer.parseInt( s ); - } - catch ( Exception e ) { - return -1; - } - } - /** - * @param stats + * Update the internal stats + * + * @param stats The incoming stats */ public void add(CollectionStats stats) { loadCount += stats.getLoadCount(); @@ -176,9 +175,6 @@ public class CollectionStats implements Serializable { recreateCount += stats.getRecreateCount(); } - /** - * toString - */ @Override public String toString() { return "roleName=" + roleName + "shortName=" + shortName + ", loadCount=" + loadCount + ", fetchCount=" @@ -186,86 +182,75 @@ public class CollectionStats implements Serializable { + recreateCount; } - /** - * getRoleName - */ + @SuppressWarnings("UnusedDeclaration") public String getRoleName() { return roleName; } - /** - * getShortName - */ + @SuppressWarnings("UnusedDeclaration") public String getShortName() { return shortName; } - /** - * getLoadCount - */ public long getLoadCount() { return loadCount; } - /** - * getFetchCount - */ public long getFetchCount() { return fetchCount; } - /** - * getUpdateCount - */ public long getUpdateCount() { return updateCount; } - /** - * getRemoveCount - */ public long getRemoveCount() { return removeCount; } - /** - * getRecreateCount - */ public long getRecreateCount() { return recreateCount; } /** - * toCompositeData + * Builds a JMX CompositeData view of our state + * + * @return The JMX CompositeData */ public CompositeData toCompositeData() { try { return new CompositeDataSupport( - COMPOSITE_TYPE, ITEM_NAMES, new Object[] { - roleName, shortName, loadCount, - fetchCount, updateCount, removeCount, recreateCount, - } + COMPOSITE_TYPE, + ITEM_NAMES, + new Object[] { roleName, shortName, loadCount, fetchCount, updateCount, removeCount, recreateCount } ); } - catch ( OpenDataException e ) { + catch (OpenDataException e) { throw new RuntimeException( e ); } } /** - * newTabularDataInstance + * Builds a JMX TabularData + * + * @return JMX TabularData */ public static TabularData newTabularDataInstance() { return new TabularDataSupport( TABULAR_TYPE ); } /** - * fromTabularData + * Re-builds CollectionStats from JMX TabularData + * + * @param tabularData The JMX TabularData + * + * @return The CollectionsStats */ + @SuppressWarnings("UnusedDeclaration") public static CollectionStats[] fromTabularData(final TabularData tabularData) { - final List countList = new ArrayList( tabularData.size() ); - for ( final Iterator pos = tabularData.values().iterator(); pos.hasNext(); ) { - countList.add( new CollectionStats( (CompositeData) pos.next() ) ); + final List countList = new ArrayList( tabularData.size() ); + for ( Object o : tabularData.values() ) { + countList.add( new CollectionStats( (CompositeData) o ) ); } return countList.toArray( new CollectionStats[countList.size()] ); } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernate.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernate.java index d63a0c8407..a978ff6140 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernate.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernate.java @@ -23,12 +23,12 @@ */ package org.hibernate.cache.ehcache.management.impl; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; import javax.management.MBeanNotificationInfo; import javax.management.NotCompliantMBeanException; import javax.management.Notification; import javax.management.openmbean.TabularData; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; import net.sf.ehcache.CacheManager; import net.sf.ehcache.hibernate.management.api.EhcacheHibernateMBean; @@ -44,7 +44,7 @@ import org.hibernate.SessionFactory; * * @author Abhishek Sanoujam */ -public class EhcacheHibernate extends BaseEmitterBean implements EhcacheHibernateMBean { +public class EhcacheHibernate extends AbstractEmitterBean implements EhcacheHibernateMBean { private static final MBeanNotificationInfo NOTIFICATION_INFO; private final AtomicBoolean statsEnabled = new AtomicBoolean( true ); @@ -52,7 +52,7 @@ public class EhcacheHibernate extends BaseEmitterBean implements EhcacheHibernat private volatile HibernateStats hibernateStats = NullHibernateStats.INSTANCE; static { - final String[] notifTypes = new String[] { }; + final String[] notifTypes = new String[] {}; final String name = Notification.class.getName(); final String description = "Ehcache Hibernate Statistics Event"; NOTIFICATION_INFO = new MBeanNotificationInfo( notifTypes, name, description ); @@ -77,7 +77,7 @@ public class EhcacheHibernate extends BaseEmitterBean implements EhcacheHibernat try { hibernateStats = new HibernateStatsImpl( sessionFactory ); } - catch ( Exception e ) { + catch (Exception e) { throw new RuntimeException( e ); } } @@ -588,10 +588,10 @@ public class EhcacheHibernate extends BaseEmitterBean implements EhcacheHibernat } /** - * @see BaseEmitterBean#getNotificationInfo() + * @see AbstractEmitterBean#getNotificationInfo() */ @Override public MBeanNotificationInfo[] getNotificationInfo() { - return new MBeanNotificationInfo[] { NOTIFICATION_INFO }; + return new MBeanNotificationInfo[] {NOTIFICATION_INFO}; } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMBeanRegistrationImpl.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMBeanRegistrationImpl.java index 9605094fb6..738bca7e05 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMBeanRegistrationImpl.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheHibernateMBeanRegistrationImpl.java @@ -23,16 +23,17 @@ */ package org.hibernate.cache.ehcache.management.impl; -import java.lang.management.ManagementFactory; -import java.util.Properties; import javax.management.InstanceAlreadyExistsException; import javax.management.MBeanServer; import javax.management.ObjectName; +import java.lang.management.ManagementFactory; +import java.util.Properties; import net.sf.ehcache.CacheException; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Status; import net.sf.ehcache.event.CacheManagerEventListener; + import org.jboss.logging.Logger; import org.hibernate.SessionFactory; @@ -48,132 +49,132 @@ import org.hibernate.cfg.Environment; * @author Abhishek Sanoujam */ public class EhcacheHibernateMBeanRegistrationImpl - implements EhcacheHibernateMBeanRegistration, CacheManagerEventListener { + implements EhcacheHibernateMBeanRegistration, CacheManagerEventListener { - private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( - EhCacheMessageLogger.class, - EhcacheHibernateMBeanRegistrationImpl.class.getName() - ); - private static final int MAX_MBEAN_REGISTRATION_RETRIES = 50; - private String cacheManagerClusterUUID; - private String registeredCacheManagerName; - private Status status = Status.STATUS_UNINITIALISED; - private volatile EhcacheHibernate ehcacheHibernate; - private volatile ObjectName cacheManagerObjectName; + private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( + EhCacheMessageLogger.class, + EhcacheHibernateMBeanRegistrationImpl.class.getName() + ); + private static final int MAX_MBEAN_REGISTRATION_RETRIES = 50; + private String cacheManagerClusterUUID; + private String registeredCacheManagerName; + private Status status = Status.STATUS_UNINITIALISED; + private volatile EhcacheHibernate ehcacheHibernate; + private volatile ObjectName cacheManagerObjectName; - /** - * {@inheritDoc} - */ - public synchronized void registerMBeanForCacheManager(final CacheManager manager, final Properties properties) - throws Exception { - String sessionFactoryName = properties.getProperty( Environment.SESSION_FACTORY_NAME ); - String name = null; - if ( sessionFactoryName == null ) { - name = manager.getName(); - } - else { - name = "".equals( sessionFactoryName.trim() ) ? manager.getName() : sessionFactoryName; - } - registerBean( name, manager ); - } + /** + * {@inheritDoc} + */ + public synchronized void registerMBeanForCacheManager(final CacheManager manager, final Properties properties) + throws Exception { + String sessionFactoryName = properties.getProperty( Environment.SESSION_FACTORY_NAME ); + String name = null; + if ( sessionFactoryName == null ) { + name = manager.getName(); + } + else { + name = "".equals( sessionFactoryName.trim() ) ? manager.getName() : sessionFactoryName; + } + registerBean( name, manager ); + } - private void registerBean(String name, CacheManager manager) throws Exception { - ehcacheHibernate = new EhcacheHibernate( manager ); - int tries = 0; - boolean success = false; - Exception exception = null; - cacheManagerClusterUUID = manager.getClusterUUID(); - do { - this.registeredCacheManagerName = name; - if ( tries != 0 ) { - registeredCacheManagerName += "_" + tries; - } - try { - // register the CacheManager MBean - MBeanServer mBeanServer = getMBeanServer(); - cacheManagerObjectName = EhcacheHibernateMbeanNames.getCacheManagerObjectName( - cacheManagerClusterUUID, - registeredCacheManagerName - ); - mBeanServer.registerMBean( ehcacheHibernate, cacheManagerObjectName ); - success = true; - break; - } - catch ( InstanceAlreadyExistsException e ) { - success = false; - exception = e; - } - tries++; - } while ( tries < MAX_MBEAN_REGISTRATION_RETRIES ); - if ( !success ) { - throw new Exception( - "Cannot register mbean for CacheManager with name" + manager.getName() + " after " - + MAX_MBEAN_REGISTRATION_RETRIES + " retries. Last tried name=" + registeredCacheManagerName, - exception - ); - } - status = Status.STATUS_ALIVE; - } + private void registerBean(String name, CacheManager manager) throws Exception { + ehcacheHibernate = new EhcacheHibernate( manager ); + int tries = 0; + boolean success = false; + Exception exception = null; + cacheManagerClusterUUID = manager.getClusterUUID(); + do { + this.registeredCacheManagerName = name; + if ( tries != 0 ) { + registeredCacheManagerName += "_" + tries; + } + try { + // register the CacheManager MBean + MBeanServer mBeanServer = getMBeanServer(); + cacheManagerObjectName = EhcacheHibernateMbeanNames.getCacheManagerObjectName( + cacheManagerClusterUUID, + registeredCacheManagerName + ); + mBeanServer.registerMBean( ehcacheHibernate, cacheManagerObjectName ); + success = true; + break; + } + catch (InstanceAlreadyExistsException e) { + success = false; + exception = e; + } + tries++; + } while ( tries < MAX_MBEAN_REGISTRATION_RETRIES ); + if ( !success ) { + throw new Exception( + "Cannot register mbean for CacheManager with name" + manager.getName() + " after " + + MAX_MBEAN_REGISTRATION_RETRIES + " retries. Last tried name=" + registeredCacheManagerName, + exception + ); + } + status = Status.STATUS_ALIVE; + } - private MBeanServer getMBeanServer() { - return ManagementFactory.getPlatformMBeanServer(); - } + private MBeanServer getMBeanServer() { + return ManagementFactory.getPlatformMBeanServer(); + } - /** - * {@inheritDoc} - */ - public void enableHibernateStatisticsSupport(SessionFactory sessionFactory) { - ehcacheHibernate.enableHibernateStatistics( sessionFactory ); - } + /** + * {@inheritDoc} + */ + public void enableHibernateStatisticsSupport(SessionFactory sessionFactory) { + ehcacheHibernate.enableHibernateStatistics( sessionFactory ); + } - /** - * {@inheritDoc} - */ - public synchronized void dispose() throws CacheException { - if ( status == Status.STATUS_SHUTDOWN ) { - return; - } + /** + * {@inheritDoc} + */ + public synchronized void dispose() throws CacheException { + if ( status == Status.STATUS_SHUTDOWN ) { + return; + } - try { - getMBeanServer().unregisterMBean( cacheManagerObjectName ); - } - catch ( Exception e ) { - LOG.warn( - "Error unregistering object instance " + cacheManagerObjectName + " . Error was " + e.getMessage(), - e - ); - } - ehcacheHibernate = null; - cacheManagerObjectName = null; - status = Status.STATUS_SHUTDOWN; - } + try { + getMBeanServer().unregisterMBean( cacheManagerObjectName ); + } + catch (Exception e) { + LOG.warn( + "Error unregistering object instance " + cacheManagerObjectName + " . Error was " + e.getMessage(), + e + ); + } + ehcacheHibernate = null; + cacheManagerObjectName = null; + status = Status.STATUS_SHUTDOWN; + } - /** - * {@inheritDoc} - */ - public synchronized Status getStatus() { - return status; - } + /** + * {@inheritDoc} + */ + public synchronized Status getStatus() { + return status; + } - /** - * No-op in this case - */ - public void init() throws CacheException { - // no-op - } + /** + * No-op in this case + */ + public void init() throws CacheException { + // no-op + } - /** - * No-op in this case - */ - public void notifyCacheAdded(String cacheName) { - // no-op - } + /** + * No-op in this case + */ + public void notifyCacheAdded(String cacheName) { + // no-op + } - /** - * No-op in this case - */ - public void notifyCacheRemoved(String cacheName) { - // no-op - } + /** + * No-op in this case + */ + public void notifyCacheRemoved(String cacheName) { + // no-op + } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheStatsImpl.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheStatsImpl.java index 190c9245a2..b3c90f2727 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheStatsImpl.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EhcacheStatsImpl.java @@ -23,12 +23,12 @@ */ package org.hibernate.cache.ehcache.management.impl; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; import javax.management.MBeanNotificationInfo; import javax.management.NotCompliantMBeanException; import javax.management.Notification; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; @@ -42,7 +42,7 @@ import net.sf.ehcache.management.sampled.SampledCacheManager; * * @author Abhishek Sanoujam */ -public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats { +public class EhcacheStatsImpl extends AbstractEmitterBean implements EhcacheStats { private static final long MILLIS_PER_SECOND = 1000; private static final MBeanNotificationInfo NOTIFICATION_INFO; @@ -156,7 +156,7 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats { */ public double getCacheHitRate() { long now = System.currentTimeMillis(); - double deltaSecs = (double) ( now - statsSince ) / MILLIS_PER_SECOND; + double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND; return getCacheHitCount() / deltaSecs; } @@ -193,7 +193,7 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats { */ public double getCacheMissRate() { long now = System.currentTimeMillis(); - double deltaSecs = (double) ( now - statsSince ) / MILLIS_PER_SECOND; + double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND; return getCacheMissCount() / deltaSecs; } @@ -230,7 +230,7 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats { */ public double getCachePutRate() { long now = System.currentTimeMillis(); - double deltaSecs = (double) ( now - statsSince ) / MILLIS_PER_SECOND; + double deltaSecs = (double) (now - statsSince) / MILLIS_PER_SECOND; return getCachePutCount() / deltaSecs; } @@ -339,8 +339,8 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats { rv.put( name, new int[] { (int) cache.getSampledCacheStatistics().getCacheHitMostRecentSample(), - (int) ( cache.getSampledCacheStatistics().getCacheMissNotFoundMostRecentSample() - + cache.getSampledCacheStatistics().getCacheMissExpiredMostRecentSample() ), + (int) (cache.getSampledCacheStatistics().getCacheMissNotFoundMostRecentSample() + + cache.getSampledCacheStatistics().getCacheMissExpiredMostRecentSample()), (int) cache.getSampledCacheStatistics().getCacheElementPutMostRecentSample(), } ); @@ -388,7 +388,7 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats { } } } - return rv.toArray( new String[] { } ); + return rv.toArray( new String[] {} ); } /** @@ -680,10 +680,10 @@ public class EhcacheStatsImpl extends BaseEmitterBean implements EhcacheStats { } /** - * @see BaseEmitterBean#getNotificationInfo() + * @see AbstractEmitterBean#getNotificationInfo() */ @Override public MBeanNotificationInfo[] getNotificationInfo() { - return new MBeanNotificationInfo[] { NOTIFICATION_INFO }; + return new MBeanNotificationInfo[] {NOTIFICATION_INFO}; } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EntityStats.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EntityStats.java index 6ce06f1cee..a121801db3 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EntityStats.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/EntityStats.java @@ -23,10 +23,6 @@ */ package org.hibernate.cache.ehcache.management.impl; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeDataSupport; import javax.management.openmbean.CompositeType; @@ -36,6 +32,10 @@ import javax.management.openmbean.SimpleType; import javax.management.openmbean.TabularData; import javax.management.openmbean.TabularDataSupport; import javax.management.openmbean.TabularType; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; import org.hibernate.stat.EntityStatistics; @@ -63,7 +63,7 @@ public class EntityStats implements Serializable { private static final CompositeType COMPOSITE_TYPE; private static final String TABULAR_TYPE_NAME = "Statistics by Entity"; private static final String TABULAR_TYPE_DESCRIPTION = "All Entity Statistics"; - private static final String[] INDEX_NAMES = new String[] { "name", }; + private static final String[] INDEX_NAMES = new String[] {"name",}; private static final TabularType TABULAR_TYPE; static { @@ -74,7 +74,7 @@ public class EntityStats implements Serializable { ); TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES ); } - catch ( OpenDataException e ) { + catch (OpenDataException e) { throw new RuntimeException( e ); } } @@ -142,7 +142,7 @@ public class EntityStats implements Serializable { this.fetchCount = BeanUtils.getLongBeanProperty( src, "fetchCount" ); this.optimisticFailureCount = BeanUtils.getLongBeanProperty( src, "optimisticFailureCount" ); } - catch ( Exception e ) { + catch (Exception e) { e.printStackTrace(); throw new RuntimeException( "Exception retrieving statistics", e ); } @@ -167,7 +167,7 @@ public class EntityStats implements Serializable { try { return Integer.parseInt( s ); } - catch ( Exception e ) { + catch (Exception e) { return -1; } } @@ -262,7 +262,7 @@ public class EntityStats implements Serializable { } ); } - catch ( OpenDataException e ) { + catch (OpenDataException e) { throw new RuntimeException( e ); } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/HibernateStatsImpl.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/HibernateStatsImpl.java index f75bfa3ebe..85eed55b05 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/HibernateStatsImpl.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/HibernateStatsImpl.java @@ -23,13 +23,13 @@ */ package org.hibernate.cache.ehcache.management.impl; -import java.util.ArrayList; -import java.util.List; import javax.management.MBeanNotificationInfo; import javax.management.NotCompliantMBeanException; import javax.management.Notification; import javax.management.openmbean.CompositeData; import javax.management.openmbean.TabularData; +import java.util.ArrayList; +import java.util.List; import net.sf.ehcache.hibernate.management.api.HibernateStats; @@ -43,14 +43,14 @@ import org.hibernate.stat.Statistics; * * @author Abhishek Sanoujam */ -public class HibernateStatsImpl extends BaseEmitterBean implements HibernateStats { +public class HibernateStatsImpl extends AbstractEmitterBean implements HibernateStats { private static final double MILLIS_PER_SECOND = 1000; private static final MBeanNotificationInfo NOTIFICATION_INFO; private final SessionFactory sessionFactory; static { - final String[] notifTypes = new String[] { }; + final String[] notifTypes = new String[] {}; final String name = Notification.class.getName(); final String description = "Hibernate Statistics Event"; NOTIFICATION_INFO = new MBeanNotificationInfo( notifTypes, name, description ); @@ -172,7 +172,7 @@ public class HibernateStatsImpl extends BaseEmitterBean implements HibernateStat public double getQueryExecutionRate() { long startTime = getStatistics().getStartTime(); long now = System.currentTimeMillis(); - double deltaSecs = ( now - startTime ) / MILLIS_PER_SECOND; + double deltaSecs = (now - startTime) / MILLIS_PER_SECOND; return getQueryExecutionCount() / deltaSecs; } @@ -321,10 +321,10 @@ public class HibernateStatsImpl extends BaseEmitterBean implements HibernateStat } /** - * @see BaseEmitterBean#getNotificationInfo() + * @see AbstractEmitterBean#getNotificationInfo() */ @Override public MBeanNotificationInfo[] getNotificationInfo() { - return new MBeanNotificationInfo[] { NOTIFICATION_INFO }; + return new MBeanNotificationInfo[] {NOTIFICATION_INFO}; } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/ProviderMBeanRegistrationHelper.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/ProviderMBeanRegistrationHelper.java index 10a4c28caf..648cc17cf6 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/ProviderMBeanRegistrationHelper.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/ProviderMBeanRegistrationHelper.java @@ -31,6 +31,7 @@ import java.util.TimerTask; import java.util.concurrent.atomic.AtomicBoolean; import net.sf.ehcache.CacheManager; + import org.jboss.logging.Logger; import org.hibernate.SessionFactory; @@ -48,141 +49,142 @@ import org.hibernate.internal.SessionFactoryRegistry; * @author Alex Snaps */ public class ProviderMBeanRegistrationHelper { - private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( - EhCacheMessageLogger.class, - ProviderMBeanRegistrationHelper.class.getName() - ); - private static final int MILLIS_PER_SECOND = 1000; - private static final int SLEEP_MILLIS = 500; + private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( + EhCacheMessageLogger.class, + ProviderMBeanRegistrationHelper.class.getName() + ); + private static final int MILLIS_PER_SECOND = 1000; + private static final int SLEEP_MILLIS = 500; - private volatile EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration; + private volatile EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration; - /** - * Registers mbean for the input cache manager and the session factory name - * - * @param manager the backing cachemanager - * @param properties session factory config properties - */ - public void registerMBean(final CacheManager manager, final Properties properties) { - if ( Boolean.getBoolean( "tc.active" ) ) { - ehcacheHibernateMBeanRegistration = new EhcacheHibernateMBeanRegistrationImpl(); - manager.getTimer().scheduleAtFixedRate( - new RegisterMBeansTask( ehcacheHibernateMBeanRegistration, manager, properties ), SLEEP_MILLIS, - SLEEP_MILLIS - ); - } - } + /** + * Registers mbean for the input cache manager and the session factory name + * + * @param manager the backing cachemanager + * @param properties session factory config properties + */ + public void registerMBean(final CacheManager manager, final Properties properties) { + if ( Boolean.getBoolean( "tc.active" ) ) { + ehcacheHibernateMBeanRegistration = new EhcacheHibernateMBeanRegistrationImpl(); + manager.getTimer().scheduleAtFixedRate( + new RegisterMBeansTask( ehcacheHibernateMBeanRegistration, manager, properties ), SLEEP_MILLIS, + SLEEP_MILLIS + ); + } + } - /** - * Unregisters previously registered mbean. - */ - public void unregisterMBean() { - if ( ehcacheHibernateMBeanRegistration != null ) { - ehcacheHibernateMBeanRegistration.dispose(); - ehcacheHibernateMBeanRegistration = null; - } - } + /** + * Unregisters previously registered mbean. + */ + public void unregisterMBean() { + if ( ehcacheHibernateMBeanRegistration != null ) { + ehcacheHibernateMBeanRegistration.dispose(); + ehcacheHibernateMBeanRegistration = null; + } + } - /** - * Task for running mbean registration that can be scheduled in a timer - */ - private static class RegisterMBeansTask extends TimerTask { - private static final int NUM_SECONDS = 30; - private long startTime; - private final AtomicBoolean mbeanRegistered = new AtomicBoolean( false ); - private final EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration; - private final CacheManager manager; - private final Properties properties; + /** + * Task for running mbean registration that can be scheduled in a timer + */ + private static class RegisterMBeansTask extends TimerTask { + private static final int NUM_SECONDS = 30; + private long startTime; + private final AtomicBoolean mbeanRegistered = new AtomicBoolean( false ); + private final EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration; + private final CacheManager manager; + private final Properties properties; - public RegisterMBeansTask(EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration, - CacheManager manager, Properties properties) { - this.ehcacheHibernateMBeanRegistration = ehcacheHibernateMBeanRegistration; - this.manager = manager; - this.properties = properties; - } + public RegisterMBeansTask( + EhcacheHibernateMBeanRegistrationImpl ehcacheHibernateMBeanRegistration, + CacheManager manager, Properties properties) { + this.ehcacheHibernateMBeanRegistration = ehcacheHibernateMBeanRegistration; + this.manager = manager; + this.properties = properties; + } - @Override - public void run() { - LOG.debug( "Running mbean initializer task for ehcache hibernate..." ); - startTime = System.currentTimeMillis(); - if ( mbeanRegistered.compareAndSet( false, true ) ) { - try { - ehcacheHibernateMBeanRegistration.registerMBeanForCacheManager( manager, properties ); - LOG.debug( "Successfully registered bean" ); - } - catch ( Exception e ) { - throw new CacheException( e ); - } - } - SessionFactory sessionFactory = locateSessionFactory(); - if ( sessionFactory == null ) { - LOG.debug( - "SessionFactory is probably still being initialized..." - + " waiting for it to complete before enabling hibernate statistics monitoring via JMX" - ); - if ( System.currentTimeMillis() > startTime + ( NUM_SECONDS * MILLIS_PER_SECOND ) ) { - LOG.info( "Hibernate statistics monitoring through JMX is DISABLED." ); - LOG.info( - "Failed to look up SessionFactory after " + NUM_SECONDS + " seconds using session-factory properties '" - + properties + "'" - ); - this.cancel(); - } - return; - } - else { - ehcacheHibernateMBeanRegistration.enableHibernateStatisticsSupport( sessionFactory ); - LOG.info( "Hibernate statistics monitoring through JMX is ENABLED. " ); - this.cancel(); - } - } + @Override + public void run() { + LOG.debug( "Running mbean initializer task for ehcache hibernate..." ); + startTime = System.currentTimeMillis(); + if ( mbeanRegistered.compareAndSet( false, true ) ) { + try { + ehcacheHibernateMBeanRegistration.registerMBeanForCacheManager( manager, properties ); + LOG.debug( "Successfully registered bean" ); + } + catch (Exception e) { + throw new CacheException( e ); + } + } + SessionFactory sessionFactory = locateSessionFactory(); + if ( sessionFactory == null ) { + LOG.debug( + "SessionFactory is probably still being initialized..." + + " waiting for it to complete before enabling hibernate statistics monitoring via JMX" + ); + if ( System.currentTimeMillis() > startTime + (NUM_SECONDS * MILLIS_PER_SECOND) ) { + LOG.info( "Hibernate statistics monitoring through JMX is DISABLED." ); + LOG.info( + "Failed to look up SessionFactory after " + NUM_SECONDS + " seconds using session-factory properties '" + + properties + "'" + ); + this.cancel(); + } + return; + } + else { + ehcacheHibernateMBeanRegistration.enableHibernateStatisticsSupport( sessionFactory ); + LOG.info( "Hibernate statistics monitoring through JMX is ENABLED. " ); + this.cancel(); + } + } - private SessionFactory locateSessionFactory() { - String jndiName = properties.getProperty( Environment.SESSION_FACTORY_NAME ); - if ( jndiName != null ) { - return SessionFactoryRegistry.INSTANCE.getNamedSessionFactory( jndiName ); - } - try { - Class factoryType = SessionFactoryRegistry.class; - Field instancesField = getField( factoryType, "sessionFactoryMap" ); - if ( instancesField == null ) { - throw new RuntimeException( "Expected 'sessionFactoryMap' field on " + SessionFactoryRegistry.class.getName() ); - } - instancesField.setAccessible( true ); - Map map = (Map) instancesField.get( SessionFactoryRegistry.INSTANCE ); - if ( map == null ) { - return null; - } - Iterator values = map.values().iterator(); - while ( values.hasNext() ) { - SessionFactory sessionFactory = (SessionFactory) values.next(); - Class sessionFactoryType = sessionFactory.getClass(); - Field propertiesField = getField( sessionFactoryType, "properties" ); - if ( propertiesField != null ) { - propertiesField.setAccessible( true ); - Properties props = (Properties) propertiesField.get( sessionFactory ); - if ( props != null && props.equals( properties ) ) { - return sessionFactory; - } - } - } - } - catch ( RuntimeException re ) { - LOG.error( "Error locating Hibernate Session Factory", re ); - } - catch ( IllegalAccessException iae ) { - LOG.error( "Error locating Hibernate Session Factory", iae ); - } - return null; - } - } + private SessionFactory locateSessionFactory() { + String jndiName = properties.getProperty( Environment.SESSION_FACTORY_NAME ); + if ( jndiName != null ) { + return SessionFactoryRegistry.INSTANCE.getNamedSessionFactory( jndiName ); + } + try { + Class factoryType = SessionFactoryRegistry.class; + Field instancesField = getField( factoryType, "sessionFactoryMap" ); + if ( instancesField == null ) { + throw new RuntimeException( "Expected 'sessionFactoryMap' field on " + SessionFactoryRegistry.class.getName() ); + } + instancesField.setAccessible( true ); + Map map = (Map) instancesField.get( SessionFactoryRegistry.INSTANCE ); + if ( map == null ) { + return null; + } + Iterator values = map.values().iterator(); + while ( values.hasNext() ) { + SessionFactory sessionFactory = (SessionFactory) values.next(); + Class sessionFactoryType = sessionFactory.getClass(); + Field propertiesField = getField( sessionFactoryType, "properties" ); + if ( propertiesField != null ) { + propertiesField.setAccessible( true ); + Properties props = (Properties) propertiesField.get( sessionFactory ); + if ( props != null && props.equals( properties ) ) { + return sessionFactory; + } + } + } + } + catch (RuntimeException re) { + LOG.error( "Error locating Hibernate Session Factory", re ); + } + catch (IllegalAccessException iae) { + LOG.error( "Error locating Hibernate Session Factory", iae ); + } + return null; + } + } - private static Field getField(Class c, String fieldName) { - for ( Field field : c.getDeclaredFields() ) { - if ( field.getName().equals( fieldName ) ) { - return field; - } - } - throw new NoSuchFieldError( "Type '" + c + "' has no field '" + fieldName + "'" ); - } + private static Field getField(Class c, String fieldName) { + for ( Field field : c.getDeclaredFields() ) { + if ( field.getName().equals( fieldName ) ) { + return field; + } + } + throw new NoSuchFieldError( "Type '" + c + "' has no field '" + fieldName + "'" ); + } } \ No newline at end of file diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/QueryStats.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/QueryStats.java index 594b3f022f..27c33bea14 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/QueryStats.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/QueryStats.java @@ -23,10 +23,6 @@ */ package org.hibernate.cache.ehcache.management.impl; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; import javax.management.openmbean.CompositeData; import javax.management.openmbean.CompositeDataSupport; import javax.management.openmbean.CompositeType; @@ -36,6 +32,10 @@ import javax.management.openmbean.SimpleType; import javax.management.openmbean.TabularData; import javax.management.openmbean.TabularDataSupport; import javax.management.openmbean.TabularType; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; import org.hibernate.stat.QueryStatistics; @@ -75,7 +75,7 @@ public class QueryStats implements Serializable { private static final CompositeType COMPOSITE_TYPE; private static final String TABULAR_TYPE_NAME = "Statistics by Query"; private static final String TABULAR_TYPE_DESCRIPTION = "All Query Statistics"; - private static final String[] INDEX_NAMES = new String[] { "query", }; + private static final String[] INDEX_NAMES = new String[] {"query",}; private static final TabularType TABULAR_TYPE; static { @@ -86,7 +86,7 @@ public class QueryStats implements Serializable { ); TABULAR_TYPE = new TabularType( TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES ); } - catch ( OpenDataException e ) { + catch (OpenDataException e) { throw new RuntimeException( e ); } } @@ -161,7 +161,7 @@ public class QueryStats implements Serializable { this.executionMinTime = BeanUtils.getLongBeanProperty( src, "executionMinTime" ); } - catch ( Exception e ) { + catch (Exception e) { e.printStackTrace(); throw new RuntimeException( "Exception retrieving statistics", e ); } @@ -187,7 +187,7 @@ public class QueryStats implements Serializable { try { return Integer.parseInt( s ); } - catch ( Exception e ) { + catch (Exception e) { return -1; } } @@ -297,7 +297,7 @@ public class QueryStats implements Serializable { } ); } - catch ( OpenDataException e ) { + catch (OpenDataException e) { throw new RuntimeException( e ); } } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/package-info.java new file mode 100644 index 0000000000..3724875d2c --- /dev/null +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/management/impl/package-info.java @@ -0,0 +1,4 @@ +/** + * Defines JMX support for the Ehcache integration + */ +package org.hibernate.cache.ehcache.management.impl; diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/package-info.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/package-info.java new file mode 100644 index 0000000000..64d91cc77e --- /dev/null +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/package-info.java @@ -0,0 +1,4 @@ +/** + * Defines the integration with Ehcache as a second-level cache service. + */ +package org.hibernate.cache.ehcache; From 20866585f35691fb98b69cff352a4a7ee3f6edcb Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Tue, 30 Apr 2013 14:40:44 -0500 Subject: [PATCH 35/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../osgi/HibernateBundleActivator.java | 37 ++++----- .../hibernate/osgi/OsgiArchiveDescriptor.java | 26 ++++--- .../osgi/OsgiArchiveDescriptorFactory.java | 8 +- .../org/hibernate/osgi/OsgiClassLoader.java | 39 ++++++---- .../org/hibernate/osgi/OsgiJtaPlatform.java | 10 ++- .../osgi/OsgiPersistenceProvider.java | 60 +++++++++------ .../osgi/OsgiPersistenceProviderService.java | 20 +++-- .../java/org/hibernate/osgi/OsgiScanner.java | 6 +- .../osgi/{util => }/OsgiServiceUtil.java | 27 +++++-- .../osgi/OsgiSessionFactoryService.java | 76 ++++++++++--------- .../java/org/hibernate/osgi/package-info.java | 4 + 11 files changed, 195 insertions(+), 118 deletions(-) rename hibernate-osgi/src/main/java/org/hibernate/osgi/{util => }/OsgiServiceUtil.java (72%) create mode 100644 hibernate-osgi/src/main/java/org/hibernate/osgi/package-info.java diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/HibernateBundleActivator.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/HibernateBundleActivator.java index 8bd6824e48..fdf0d1ea89 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/HibernateBundleActivator.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/HibernateBundleActivator.java @@ -51,37 +51,40 @@ import org.osgi.framework.FrameworkUtil; * SessionFactory is registered as an OSGi ServiceFactory -- each requesting * bundle gets its own instance of a SessionFactory. The use of services, * rather than direct use of Configuration, is necessary to shield users - * from ClassLoader issues. See {@link #OsgiSessionFactoryService} for more + * from ClassLoader issues. See {@link OsgiSessionFactoryService} for more * information. * * @author Brett Meyer * @author Tim Ward */ +@SuppressWarnings("UnusedDeclaration") public class HibernateBundleActivator implements BundleActivator { - - private OsgiClassLoader osgiClassLoader; - - private OsgiJtaPlatform osgiJtaPlatform; - @Override + @SuppressWarnings("unchecked") public void start(BundleContext context) throws Exception { - - osgiClassLoader = new OsgiClassLoader(); + // build a ClassLoader that uses all the necessary OSGi bundles, and place it into + // a well-known location so internals can access it + final OsgiClassLoader osgiClassLoader = new OsgiClassLoader(); osgiClassLoader.addBundle( FrameworkUtil.getBundle( Session.class ) ); osgiClassLoader.addBundle( FrameworkUtil.getBundle( HibernatePersistenceProvider.class ) ); ClassLoaderHelper.overridenClassLoader = osgiClassLoader; - osgiJtaPlatform = new OsgiJtaPlatform( context ); + // Build a JtaPlatform specific for this OSGi context + final OsgiJtaPlatform osgiJtaPlatform = new OsgiJtaPlatform( context ); - Dictionary properties = new Hashtable(); - // In order to support existing persistence.xml files, register - // using the legacy provider name. + final Dictionary properties = new Hashtable(); + // In order to support existing persistence.xml files, register using the legacy provider name. properties.put( "javax.persistence.provider", HibernatePersistenceProvider.class.getName() ); - context.registerService( PersistenceProvider.class.getName(), - new OsgiPersistenceProviderService( osgiClassLoader, osgiJtaPlatform, context ), properties ); - - context.registerService( SessionFactory.class.getName(), - new OsgiSessionFactoryService( osgiClassLoader, osgiJtaPlatform, context ), new Hashtable()); + context.registerService( + PersistenceProvider.class.getName(), + new OsgiPersistenceProviderService( osgiClassLoader, osgiJtaPlatform, context ), + properties + ); + context.registerService( + SessionFactory.class.getName(), + new OsgiSessionFactoryService( osgiClassLoader, osgiJtaPlatform, context ), + new Hashtable() + ); } @Override diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiArchiveDescriptor.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiArchiveDescriptor.java index 6a73acca0a..fc554e4216 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiArchiveDescriptor.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiArchiveDescriptor.java @@ -37,18 +37,26 @@ import org.osgi.framework.Bundle; import org.osgi.framework.wiring.BundleWiring; /** + * ArchiveDescriptor implementation for describing archives in the OSGi sense + * * @author Brett Meyer * @author Tim Ward */ public class OsgiArchiveDescriptor implements ArchiveDescriptor { + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + OsgiArchiveDescriptor.class.getName() + ); - private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, - OsgiArchiveDescriptor.class.getName() ); - - private BundleWiring bundleWiring; - - private Bundle persistenceBundle; + private final Bundle persistenceBundle; + private final BundleWiring bundleWiring; + /** + * Creates a OsgiArchiveDescriptor + * + * @param persistenceBundle The bundle being described as an archive + */ + @SuppressWarnings("RedundantCast") public OsgiArchiveDescriptor(Bundle persistenceBundle) { this.persistenceBundle = persistenceBundle; bundleWiring = (BundleWiring) persistenceBundle.adapt( BundleWiring.class ); @@ -56,14 +64,12 @@ public class OsgiArchiveDescriptor implements ArchiveDescriptor { @Override public void visitArchive(ArchiveContext context) { - Collection resources = bundleWiring.listResources( "/", "*", BundleWiring.LISTRESOURCES_RECURSE ); + final Collection resources = bundleWiring.listResources( "/", "*", BundleWiring.LISTRESOURCES_RECURSE ); for ( final String resource : resources ) { - // TODO: Is there a better way to check this? Karaf is including - // directories. + // TODO: Is there a better way to check this? Karaf is including directories. if ( !resource.endsWith( "/" ) ) { try { // TODO: Is using resource as the names correct? - final InputStreamAccess inputStreamAccess = new InputStreamAccess() { @Override public String getStreamName() { diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiArchiveDescriptorFactory.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiArchiveDescriptorFactory.java index 97264cf5b4..81489715a7 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiArchiveDescriptorFactory.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiArchiveDescriptorFactory.java @@ -27,13 +27,19 @@ import org.hibernate.jpa.boot.archive.spi.ArchiveDescriptorFactory; import org.osgi.framework.Bundle; /** + * ArchiveDescriptorFactory implementation for OSGi environments + * * @author Brett Meyer * @author Tim Ward */ public class OsgiArchiveDescriptorFactory implements ArchiveDescriptorFactory { - private Bundle persistenceBundle; + /** + * Creates a OsgiArchiveDescriptorFactory + * + * @param persistenceBundle The OSGi bundle being scanned + */ public OsgiArchiveDescriptorFactory(Bundle persistenceBundle) { this.persistenceBundle = persistenceBundle; } diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiClassLoader.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiClassLoader.java index 2088742d53..d8babd732c 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiClassLoader.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiClassLoader.java @@ -41,15 +41,11 @@ import org.osgi.framework.Bundle; * @author Tim Ward */ public class OsgiClassLoader extends ClassLoader { - private List classLoaders = new ArrayList(); - private List bundles = new ArrayList(); - + private Map> classCache = new HashMap>(); - private Map resourceCache = new HashMap(); - private Map> resourceListCache = new HashMap>(); /** @@ -57,8 +53,8 @@ public class OsgiClassLoader extends ClassLoader { * TODO: Should this throw a different exception or warn if multiple * classes were found? Naming collisions can and do happen in OSGi... */ - @SuppressWarnings("rawtypes") @Override + @SuppressWarnings("rawtypes") protected Class findClass(String name) throws ClassNotFoundException { if ( classCache.containsKey( name ) ) { return classCache.get( name ); @@ -66,7 +62,7 @@ public class OsgiClassLoader extends ClassLoader { for ( Bundle bundle : bundles ) { try { - Class clazz = bundle.loadClass( name ); + final Class clazz = bundle.loadClass( name ); if ( clazz != null ) { classCache.put( name, clazz ); return clazz; @@ -78,7 +74,7 @@ public class OsgiClassLoader extends ClassLoader { for ( ClassLoader classLoader : classLoaders ) { try { - Class clazz = classLoader.loadClass( name ); + final Class clazz = classLoader.loadClass( name ); if ( clazz != null ) { classCache.put( name, clazz ); return clazz; @@ -104,7 +100,7 @@ public class OsgiClassLoader extends ClassLoader { for ( Bundle bundle : bundles ) { try { - URL resource = bundle.getResource( name ); + final URL resource = bundle.getResource( name ); if ( resource != null ) { resourceCache.put( name, resource ); return resource; @@ -116,7 +112,7 @@ public class OsgiClassLoader extends ClassLoader { for ( ClassLoader classLoader : classLoaders ) { try { - URL resource = classLoader.getResource( name ); + final URL resource = classLoader.getResource( name ); if ( resource != null ) { resourceCache.put( name, resource ); return resource; @@ -135,8 +131,8 @@ public class OsgiClassLoader extends ClassLoader { * TODO: Should this throw a different exception or warn if multiple * classes were found? Naming collisions can and do happen in OSGi... */ - @SuppressWarnings("unchecked") @Override + @SuppressWarnings("unchecked") protected Enumeration findResources(String name) { if ( resourceListCache.containsKey( name ) ) { return resourceListCache.get( name ); @@ -146,7 +142,7 @@ public class OsgiClassLoader extends ClassLoader { for ( Bundle bundle : bundles ) { try { - Enumeration resources = bundle.getResources( name ); + final Enumeration resources = bundle.getResources( name ); if ( resources != null ) { enumerations.add( resources ); } @@ -157,7 +153,7 @@ public class OsgiClassLoader extends ClassLoader { for ( ClassLoader classLoader : classLoaders ) { try { - Enumeration resources = classLoader.getResources( name ); + final Enumeration resources = classLoader.getResources( name ); if ( resources != null ) { enumerations.add( resources ); } @@ -166,7 +162,7 @@ public class OsgiClassLoader extends ClassLoader { } } - Enumeration aggEnumeration = new Enumeration() { + final Enumeration aggEnumeration = new Enumeration() { @Override public boolean hasMoreElements() { for ( Enumeration enumeration : enumerations ) { @@ -193,14 +189,27 @@ public class OsgiClassLoader extends ClassLoader { return aggEnumeration; } + /** + * Adds a ClassLoader to the wrapped set of ClassLoaders + * + * @param classLoader The ClassLoader to add + */ public void addClassLoader( ClassLoader classLoader ) { classLoaders.add( classLoader ); } + /** + * Adds a Bundle to the wrapped set of Bundles + * + * @param bundle The Bundle to add + */ public void addBundle( Bundle bundle ) { bundles.add( bundle ); } - + + /** + * Clear all resources. + */ public void clear() { classCache.clear(); resourceCache.clear(); diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiJtaPlatform.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiJtaPlatform.java index 29ae4707d4..5dd4888037 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiJtaPlatform.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiJtaPlatform.java @@ -38,24 +38,28 @@ import org.osgi.framework.ServiceReference; * @author Brett Meyer */ public class OsgiJtaPlatform implements JtaPlatform { - private static final long serialVersionUID = 1L; private BundleContext bundleContext; + /** + * Constructs a OsgiJtaPlatform + * + * @param bundleContext The OSGi bundle context + */ public OsgiJtaPlatform(BundleContext bundleContext) { this.bundleContext = bundleContext; } @Override public TransactionManager retrieveTransactionManager() { - ServiceReference sr = bundleContext.getServiceReference( TransactionManager.class.getName() ); + final ServiceReference sr = bundleContext.getServiceReference( TransactionManager.class.getName() ); return (TransactionManager) bundleContext.getService( sr ); } @Override public UserTransaction retrieveUserTransaction() { - ServiceReference sr = bundleContext.getServiceReference( UserTransaction.class.getName() ); + final ServiceReference sr = bundleContext.getServiceReference( UserTransaction.class.getName() ); return (UserTransaction) bundleContext.getService( sr ); } diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java index 01ccff48ee..23cc77d8b7 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java @@ -37,27 +37,36 @@ import org.hibernate.jpa.HibernatePersistenceProvider; import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; import org.hibernate.jpa.boot.spi.IntegratorProvider; import org.hibernate.jpa.boot.spi.StrategyRegistrationProviderList; -import org.hibernate.osgi.util.OsgiServiceUtil; + import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleReference; /** + * Acts as the PersistenceProvider service in OSGi environments + * * @author Brett Meyer * @author Tim Ward */ public class OsgiPersistenceProvider extends HibernatePersistenceProvider { - private OsgiClassLoader osgiClassLoader; - private OsgiJtaPlatform osgiJtaPlatform; - private Bundle requestingBundle; - private BundleContext context; - public OsgiPersistenceProvider(OsgiClassLoader osgiClassLoader, OsgiJtaPlatform osgiJtaPlatform, - Bundle requestingBundle, BundleContext context) { + /** + * Constructs a OsgiPersistenceProvider + * + * @param osgiClassLoader The ClassLoader we built from OSGi Bundles + * @param osgiJtaPlatform The OSGi-specific JtaPlatform impl we built + * @param requestingBundle The OSGi Bundle requesting the PersistenceProvider + * @param context The OSGi context + */ + public OsgiPersistenceProvider( + OsgiClassLoader osgiClassLoader, + OsgiJtaPlatform osgiJtaPlatform, + Bundle requestingBundle, + BundleContext context) { this.osgiClassLoader = osgiClassLoader; this.osgiJtaPlatform = osgiJtaPlatform; this.requestingBundle = requestingBundle; @@ -68,14 +77,15 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider { // EMFBuilder somehow? @Override + @SuppressWarnings("unchecked") public EntityManagerFactory createEntityManagerFactory(String persistenceUnitName, Map properties) { - properties = generateProperties( properties ); + final Map settings = generateSettings( properties ); // TODO: This needs tested. - properties.put( org.hibernate.jpa.AvailableSettings.SCANNER, new OsgiScanner( requestingBundle ) ); + settings.put( org.hibernate.jpa.AvailableSettings.SCANNER, new OsgiScanner( requestingBundle ) ); // TODO: This is temporary -- for PersistenceXmlParser's use of // ClassLoaderServiceImpl#fromConfigSettings - properties.put( AvailableSettings.ENVIRONMENT_CLASSLOADER, osgiClassLoader ); + settings.put( AvailableSettings.ENVIRONMENT_CLASSLOADER, osgiClassLoader ); osgiClassLoader.addBundle( requestingBundle ); @@ -83,45 +93,49 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider { } @Override + @SuppressWarnings("unchecked") public EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map properties) { - properties = generateProperties( properties ); + final Map settings = generateSettings( properties ); // OSGi ClassLoaders must implement BundleReference - properties.put( org.hibernate.jpa.AvailableSettings.SCANNER, - new OsgiScanner( ( (BundleReference) info.getClassLoader() ).getBundle() ) ); + settings.put( + org.hibernate.jpa.AvailableSettings.SCANNER, + new OsgiScanner( ( (BundleReference) info.getClassLoader() ).getBundle() ) + ); osgiClassLoader.addClassLoader( info.getClassLoader() ); return super.createContainerEntityManagerFactory( info, properties ); } - private Map generateProperties(Map properties) { - if ( properties == null ) { - properties = new HashMap(); + @SuppressWarnings("unchecked") + private Map generateSettings(Map properties) { + final Map settings = new HashMap(); + if ( properties != null ) { + settings.putAll( properties ); } - properties.put( AvailableSettings.JTA_PLATFORM, osgiJtaPlatform ); + settings.put( AvailableSettings.JTA_PLATFORM, osgiJtaPlatform ); final List integrators = OsgiServiceUtil.getServiceImpls( Integrator.class, context ); - IntegratorProvider integratorProvider = new IntegratorProvider() { + final IntegratorProvider integratorProvider = new IntegratorProvider() { @Override public List getIntegrators() { return integrators; } }; - properties.put( EntityManagerFactoryBuilderImpl.INTEGRATOR_PROVIDER, integratorProvider ); + settings.put( EntityManagerFactoryBuilderImpl.INTEGRATOR_PROVIDER, integratorProvider ); final List strategyRegistrationProviders = OsgiServiceUtil.getServiceImpls( StrategyRegistrationProvider.class, context ); - StrategyRegistrationProviderList strategyRegistrationProviderList = new StrategyRegistrationProviderList() { + final StrategyRegistrationProviderList strategyRegistrationProviderList = new StrategyRegistrationProviderList() { @Override public List getStrategyRegistrationProviders() { return strategyRegistrationProviders; } }; - properties.put( EntityManagerFactoryBuilderImpl.STRATEGY_REGISTRATION_PROVIDERS, - strategyRegistrationProviderList ); + settings.put( EntityManagerFactoryBuilderImpl.STRATEGY_REGISTRATION_PROVIDERS, strategyRegistrationProviderList ); - return properties; + return settings; } } diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProviderService.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProviderService.java index 5ab228568f..f3bc51c9a5 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProviderService.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProviderService.java @@ -26,22 +26,28 @@ import org.osgi.framework.ServiceFactory; import org.osgi.framework.ServiceRegistration; /** - * See the description on {@link #OsgiSessionFactoryService}. This class - * is similar, providing an PersistenceProvider as an OSGi Service. + * See the description on {@link OsgiSessionFactoryService}. This class is similar, providing an + * PersistenceProvider as an OSGi Service. * * @author Brett Meyer * @author Tim Ward */ public class OsgiPersistenceProviderService implements ServiceFactory { - private OsgiClassLoader osgiClassLoader; - private OsgiJtaPlatform osgiJtaPlatform; - private BundleContext context; - public OsgiPersistenceProviderService( OsgiClassLoader osgiClassLoader, - OsgiJtaPlatform osgiJtaPlatform, BundleContext context ) { + /** + * Constructs a OsgiPersistenceProviderService + * + * @param osgiClassLoader The OSGi-specific ClassLoader created in HibernateBundleActivator + * @param osgiJtaPlatform The OSGi-specific JtaPlatform created in HibernateBundleActivator + * @param context The OSGi context + */ + public OsgiPersistenceProviderService( + OsgiClassLoader osgiClassLoader, + OsgiJtaPlatform osgiJtaPlatform, + BundleContext context) { this.osgiClassLoader = osgiClassLoader; this.osgiJtaPlatform = osgiJtaPlatform; this.context = context; diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiScanner.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiScanner.java index ac753466ae..aa570348b8 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiScanner.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiScanner.java @@ -31,7 +31,11 @@ import org.osgi.framework.Bundle; * @author Tim Ward */ public class OsgiScanner extends AbstractScannerImpl { - + /** + * Constructs the scanner for finding things in a OSGi bundle + * + * @param persistenceBundle The OSGi Bundle to scan + */ public OsgiScanner(Bundle persistenceBundle) { super( new OsgiArchiveDescriptorFactory( persistenceBundle ) ); } diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/util/OsgiServiceUtil.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiServiceUtil.java similarity index 72% rename from hibernate-osgi/src/main/java/org/hibernate/osgi/util/OsgiServiceUtil.java rename to hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiServiceUtil.java index 0b9ddc0ed4..05e4603d92 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/util/OsgiServiceUtil.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiServiceUtil.java @@ -18,7 +18,7 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ -package org.hibernate.osgi.util; +package org.hibernate.osgi; import java.util.ArrayList; import java.util.Collection; @@ -30,17 +30,29 @@ import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; /** + * Utilities for dealing with OSGi environments + * * @author Brett Meyer */ public class OsgiServiceUtil { + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + OsgiServiceUtil.class.getName() + ); - private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, - OsgiServiceUtil.class.getName() ); - + /** + * Locate all implementors of the given service contract in the given OSGi buindle context + * + * @param contract The service contract for which to locate implementors + * @param context The OSGi bundle context + * @param The Java type of the service to locate + * + * @return All know implementors + */ public static List getServiceImpls(Class contract, BundleContext context) { - List serviceImpls = new ArrayList(); + final List serviceImpls = new ArrayList(); try { - Collection> serviceRefs = context.getServiceReferences( contract, null ); + final Collection> serviceRefs = context.getServiceReferences( contract, null ); for ( ServiceReference serviceRef : serviceRefs ) { serviceImpls.add( context.getService( serviceRef ) ); } @@ -50,4 +62,7 @@ public class OsgiServiceUtil { } return serviceImpls; } + + private OsgiServiceUtil() { + } } diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java index c878136711..af6c57be4d 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java @@ -22,6 +22,11 @@ package org.hibernate.osgi; import java.util.List; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceFactory; +import org.osgi.framework.ServiceRegistration; + import org.hibernate.SessionFactory; import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; @@ -29,12 +34,7 @@ import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; import org.hibernate.integrator.spi.Integrator; -import org.hibernate.osgi.util.OsgiServiceUtil; import org.hibernate.service.ServiceRegistry; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceFactory; -import org.osgi.framework.ServiceRegistration; /** * Hibernate 4.2 and 4.3 still heavily rely on TCCL for ClassLoading. Although @@ -42,28 +42,34 @@ import org.osgi.framework.ServiceRegistration; * unfortunately not available during Configuration. An OSGi * bundle manually creating a SessionFactory would require numerous ClassLoader * tricks (or may be impossible altogether). - * + *

      * In order to fully control the TCCL issues and shield users from the * knowledge, we're requiring that bundles use this OSGi ServiceFactory. It * configures and provides a SessionFactory as an OSGi service. - * + *

      * Note that an OSGi ServiceFactory differs from a Service. The ServiceFactory * allows individual instances of Services to be created and provided to * multiple client Bundles. - * + * * @author Brett Meyer * @author Tim Ward */ public class OsgiSessionFactoryService implements ServiceFactory { - private OsgiClassLoader osgiClassLoader; - private OsgiJtaPlatform osgiJtaPlatform; - private BundleContext context; - public OsgiSessionFactoryService( OsgiClassLoader osgiClassLoader, OsgiJtaPlatform osgiJtaPlatform, - BundleContext context ) { + /** + * Constructs a OsgiSessionFactoryService + * + * @param osgiClassLoader The OSGi-specific ClassLoader created in HibernateBundleActivator + * @param osgiJtaPlatform The OSGi-specific JtaPlatform created in HibernateBundleActivator + * @param context The OSGi context + */ + public OsgiSessionFactoryService( + OsgiClassLoader osgiClassLoader, + OsgiJtaPlatform osgiJtaPlatform, + BundleContext context) { this.osgiClassLoader = osgiClassLoader; this.osgiJtaPlatform = osgiJtaPlatform; this.context = context; @@ -72,33 +78,33 @@ public class OsgiSessionFactoryService implements ServiceFactory { @Override public Object getService(Bundle requestingBundle, ServiceRegistration registration) { osgiClassLoader.addBundle( requestingBundle ); - - Configuration configuration = new Configuration(); + + final Configuration configuration = new Configuration(); configuration.getProperties().put( AvailableSettings.JTA_PLATFORM, osgiJtaPlatform ); - configuration.configure(); - - BootstrapServiceRegistryBuilder builder = new BootstrapServiceRegistryBuilder(); - builder.with( osgiClassLoader ); - - List integrators = OsgiServiceUtil.getServiceImpls( Integrator.class, context ); - for (Integrator integrator : integrators) { - builder.with( integrator ); - } - - List strategyRegistrationProviders - = OsgiServiceUtil.getServiceImpls( StrategyRegistrationProvider.class, context ); - for (StrategyRegistrationProvider strategyRegistrationProvider : strategyRegistrationProviders) { - builder.withStrategySelectors( strategyRegistrationProvider ); - } - - ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder( builder.build() ) - .applySettings(configuration.getProperties()).build(); - return configuration.buildSessionFactory(serviceRegistry); + configuration.configure(); + + final BootstrapServiceRegistryBuilder builder = new BootstrapServiceRegistryBuilder(); + builder.with( osgiClassLoader ); + + final List integrators = OsgiServiceUtil.getServiceImpls( Integrator.class, context ); + for ( Integrator integrator : integrators ) { + builder.with( integrator ); + } + + final List strategyRegistrationProviders + = OsgiServiceUtil.getServiceImpls( StrategyRegistrationProvider.class, context ); + for ( StrategyRegistrationProvider strategyRegistrationProvider : strategyRegistrationProviders ) { + builder.withStrategySelectors( strategyRegistrationProvider ); + } + + final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder( builder.build() ) + .applySettings( configuration.getProperties() ).build(); + return configuration.buildSessionFactory( serviceRegistry ); } @Override public void ungetService(Bundle requestingBundle, ServiceRegistration registration, Object service) { - ( (SessionFactory) service).close(); + ((SessionFactory) service).close(); } } diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/package-info.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/package-info.java new file mode 100644 index 0000000000..bd787f7262 --- /dev/null +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/package-info.java @@ -0,0 +1,4 @@ +/** + * Main OSGi support classes + */ +package org.hibernate.osgi; From 459c061eb62397aaadb751416e5147a8ac3fd7cf Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Tue, 30 Apr 2013 15:31:10 -0500 Subject: [PATCH 36/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../internal/BulkOperationCleanupAction.java | 6 +- .../java/org/hibernate/cfg/HbmBinder.java | 2 +- .../cfg/annotations/CollectionBinder.java | 12 +- .../internal/NaturalIdXrefDelegate.java | 2 +- .../internal/StatefulPersistenceContext.java | 2 +- .../jdbc/internal/JdbcCoordinatorImpl.java | 2 +- .../jdbc/internal/ResultSetWrapperImpl.java | 3 +- .../engine/jdbc/spi/SqlExceptionHelper.java | 402 ++++++++++-------- .../engine/query/spi/NativeSQLQueryPlan.java | 25 +- .../hibernate/engine/spi/AssociationKey.java | 33 +- .../hibernate/engine/spi/CollectionKey.java | 64 +-- .../org/hibernate/engine/spi/EntityKey.java | 45 +- .../engine/spi/LoadQueryInfluencers.java | 2 +- .../org/hibernate/engine/spi/TypedValue.java | 15 +- .../loader/custom/sql/SQLCustomQuery.java | 8 +- 15 files changed, 356 insertions(+), 267 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/action/internal/BulkOperationCleanupAction.java b/hibernate-core/src/main/java/org/hibernate/action/internal/BulkOperationCleanupAction.java index 7423691c76..a40e491f97 100644 --- a/hibernate-core/src/main/java/org/hibernate/action/internal/BulkOperationCleanupAction.java +++ b/hibernate-core/src/main/java/org/hibernate/action/internal/BulkOperationCleanupAction.java @@ -217,7 +217,7 @@ public class BulkOperationCleanupAction implements Executable, Serializable { // nothing to do } - private static class EntityCleanup { + private static class EntityCleanup implements Serializable { private final EntityRegionAccessStrategy cacheAccess; private final SoftLock cacheLock; @@ -232,7 +232,7 @@ public class BulkOperationCleanupAction implements Executable, Serializable { } } - private static class CollectionCleanup { + private static class CollectionCleanup implements Serializable { private final CollectionRegionAccessStrategy cacheAccess; private final SoftLock cacheLock; @@ -247,7 +247,7 @@ public class BulkOperationCleanupAction implements Executable, Serializable { } } - private class NaturalIdCleanup { + private class NaturalIdCleanup implements Serializable { private final NaturalIdRegionAccessStrategy naturalIdCacheAccessStrategy; private final SoftLock cacheLock; diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java index 0062fad513..f3ac7b91eb 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/HbmBinder.java @@ -2969,7 +2969,7 @@ public final class HbmBinder { boolean inheritable = Boolean .valueOf( metaNode.attributeValue( "inherit" ) ) .booleanValue(); - if ( onlyInheritable & !inheritable ) { + if ( onlyInheritable && !inheritable ) { continue; } String name = metaNode.attributeValue( "attribute" ); diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java index 03cf238d6b..cf3cdd2e4c 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/annotations/CollectionBinder.java @@ -1111,7 +1111,11 @@ public abstract class CollectionBinder { XProperty property, PropertyHolder parentPropertyHolder, Mappings mappings) throws MappingException { - PersistentClass collectionEntity = (PersistentClass) persistentClasses.get( collType.getName() ); + if ( property == null ) { + throw new IllegalArgumentException( "null was passed for argument property" ); + } + + final PersistentClass collectionEntity = (PersistentClass) persistentClasses.get( collType.getName() ); final String hqlOrderBy = extractHqlOrderBy( jpaOrderBy ); boolean isCollectionOfEntities = collectionEntity != null; @@ -1241,9 +1245,11 @@ public abstract class CollectionBinder { buildOrderByClauseFromHql( hqlOrderBy, collectionEntity, collValue.getRole() ) ); } - ForeignKey fk = property != null ? property.getAnnotation( ForeignKey.class ) : null; + final ForeignKey fk = property.getAnnotation( ForeignKey.class ); String fkName = fk != null ? fk.inverseName() : ""; - if ( !BinderHelper.isEmptyAnnotationValue( fkName ) ) element.setForeignKeyName( fkName ); + if ( !BinderHelper.isEmptyAnnotationValue( fkName ) ) { + element.setForeignKeyName( fkName ); + } } else if ( anyAnn != null ) { //@ManyToAny diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdXrefDelegate.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdXrefDelegate.java index 4b4da35a4f..29dee5d946 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdXrefDelegate.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/NaturalIdXrefDelegate.java @@ -354,7 +354,7 @@ public class NaturalIdXrefDelegate { /** * Used to put natural id values into collections. Useful mainly to apply equals/hashCode implementations. */ - private static class CachedNaturalId { + private static class CachedNaturalId implements Serializable { private final EntityPersister persister; private final Object[] values; private final Type[] naturalIdTypes; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java b/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java index d7ebff1261..5c10005a1b 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/internal/StatefulPersistenceContext.java @@ -348,7 +348,7 @@ public class StatefulPersistenceContext implements PersistenceContext { // snapshot-cached. final int[] props = persister.getNaturalIdentifierProperties(); final Object[] entitySnapshot = getDatabaseSnapshot( id, persister ); - if ( entitySnapshot == NO_ROW ) { + if ( entitySnapshot == NO_ROW || entitySnapshot == null ) { return null; } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java index 1b2d710344..4dc5bbd544 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/JdbcCoordinatorImpl.java @@ -82,7 +82,7 @@ public class JdbcCoordinatorImpl implements JdbcCoordinator { private final HashMap> xref = new HashMap>(); private final Set unassociatedResultSets = new HashSet(); - private final SqlExceptionHelper exceptionHelper; + private final transient SqlExceptionHelper exceptionHelper; private Statement lastQuery; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetWrapperImpl.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetWrapperImpl.java index 11d7ee3d49..c5cf9d1bd2 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetWrapperImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/internal/ResultSetWrapperImpl.java @@ -33,13 +33,14 @@ import org.hibernate.engine.jdbc.spi.ResultSetWrapper; * Standard Hibernate implementation for wrapping a {@link ResultSet} in a " column name cache" wrapper. * + * @author Steve Ebersole * @author Gail Badner */ public class ResultSetWrapperImpl implements ResultSetWrapper { /** * Singleton access */ - public static ResultSetWrapper INSTANCE = new ResultSetWrapperImpl(); + public static final ResultSetWrapper INSTANCE = new ResultSetWrapperImpl(); private ResultSetWrapperImpl() { } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/SqlExceptionHelper.java b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/SqlExceptionHelper.java index f1d56fb263..26d8b6587c 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/SqlExceptionHelper.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/jdbc/spi/SqlExceptionHelper.java @@ -44,13 +44,15 @@ import org.hibernate.internal.util.StringHelper; * @author Steve Ebersole */ public class SqlExceptionHelper { + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + SqlExceptionHelper.class.getName() + ); - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, SqlExceptionHelper.class.getName()); + private static final String DEFAULT_EXCEPTION_MSG = "SQL Exception"; + private static final String DEFAULT_WARNING_MSG = "SQL Warning"; - public static final String DEFAULT_EXCEPTION_MSG = "SQL Exception"; - public static final String DEFAULT_WARNING_MSG = "SQL Warning"; - - public static final SQLExceptionConverter DEFAULT_CONVERTER = new SQLStateConverter( + private static final SQLExceptionConverter DEFAULT_CONVERTER = new SQLStateConverter( new ViolatedConstraintNameExtracter() { public String extractConstraintName(SQLException e) { return null; @@ -93,206 +95,236 @@ public class SqlExceptionHelper { * @param sqlExceptionConverter The converter to use. */ public void setSqlExceptionConverter(SQLExceptionConverter sqlExceptionConverter) { - this.sqlExceptionConverter = ( sqlExceptionConverter == null ? DEFAULT_CONVERTER : sqlExceptionConverter ); + this.sqlExceptionConverter = (sqlExceptionConverter == null ? DEFAULT_CONVERTER : sqlExceptionConverter); } - // SQLException ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // SQLException ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - /** - * Convert an SQLException using the current converter, doing some logging first. - * - * @param sqlException The exception to convert - * @param message An error message. - * @return The converted exception - */ - public JDBCException convert( SQLException sqlException, - String message ) { - return convert(sqlException, message, "n/a"); - } + /** + * Convert an SQLException using the current converter, doing some logging first. + * + * @param sqlException The exception to convert + * @param message An error message. + * + * @return The converted exception + */ + public JDBCException convert(SQLException sqlException, String message) { + return convert( sqlException, message, "n/a" ); + } - /** - * Convert an SQLException using the current converter, doing some logging first. - * - * @param sqlException The exception to convert - * @param message An error message. - * @param sql The SQL being executed when the exception occurred - * @return The converted exception - */ - public JDBCException convert( SQLException sqlException, - String message, - String sql ) { - logExceptions(sqlException, message + " [" + sql + "]"); - return sqlExceptionConverter.convert(sqlException, message, sql); - } + /** + * Convert an SQLException using the current converter, doing some logging first. + * + * @param sqlException The exception to convert + * @param message An error message. + * @param sql The SQL being executed when the exception occurred + * + * @return The converted exception + */ + public JDBCException convert(SQLException sqlException, String message, String sql) { + logExceptions( sqlException, message + " [" + sql + "]" ); + return sqlExceptionConverter.convert( sqlException, message, sql ); + } - /** - * Log the given (and any nested) exception. - * - * @param sqlException The exception to log - * @param message The message text to use as a preamble. - */ - public void logExceptions( SQLException sqlException, - String message ) { - if (LOG.isEnabled(Level.ERROR)) { - if (LOG.isDebugEnabled()) { - message = StringHelper.isNotEmpty(message) ? message : DEFAULT_EXCEPTION_MSG; - LOG.debug( message, sqlException ); - } - final boolean warnEnabled = LOG.isEnabled( Level.WARN ); - while (sqlException != null) { - if ( warnEnabled ) { - StringBuilder buf = new StringBuilder(30).append("SQL Error: ").append(sqlException.getErrorCode()).append(", SQLState: ").append(sqlException.getSQLState()); - LOG.warn(buf.toString()); - } - LOG.error(sqlException.getMessage()); - sqlException = sqlException.getNextException(); - } - } - } + /** + * Log the given (and any nested) exception. + * + * @param sqlException The exception to log + * @param message The message text to use as a preamble. + */ + public void logExceptions( + SQLException sqlException, + String message) { + if ( LOG.isEnabled( Level.ERROR ) ) { + if ( LOG.isDebugEnabled() ) { + message = StringHelper.isNotEmpty( message ) ? message : DEFAULT_EXCEPTION_MSG; + LOG.debug( message, sqlException ); + } + final boolean warnEnabled = LOG.isEnabled( Level.WARN ); + while ( sqlException != null ) { + if ( warnEnabled ) { + LOG.warn( "SQL Error: " + sqlException.getErrorCode() + ", SQLState: " + sqlException.getSQLState() ); + } + LOG.error( sqlException.getMessage() ); + sqlException = sqlException.getNextException(); + } + } + } - // SQLWarning ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // SQLWarning ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - /** - * Contract for handling {@link SQLWarning warnings} - */ - public static interface WarningHandler { - /** - * Should processing be done? Allows short-circuiting if not. - * - * @return True to process warnings, false otherwise. - */ - public boolean doProcess(); + /** + * Contract for handling {@link SQLWarning warnings} + */ + public static interface WarningHandler { + /** + * Should processing be done? Allows short-circuiting if not. + * + * @return True to process warnings, false otherwise. + */ + public boolean doProcess(); - /** - * Prepare for processing of a {@link SQLWarning warning} stack. - *

      - * Note that the warning here is also the first passed to {@link #handleWarning} - * - * @param warning The first warning in the stack. - */ - public void prepare( SQLWarning warning ); + /** + * Prepare for processing of a {@link SQLWarning warning} stack. + *

      + * Note that the warning here is also the first passed to {@link #handleWarning} + * + * @param warning The first warning in the stack. + */ + public void prepare(SQLWarning warning); - /** - * Handle an individual warning in the stack. - * - * @param warning The warning to handle. - */ - public void handleWarning( SQLWarning warning ); - } + /** + * Handle an individual warning in the stack. + * + * @param warning The warning to handle. + */ + public void handleWarning(SQLWarning warning); + } - /** - * Basic support for {@link WarningHandler} implementations which log - */ - public static abstract class WarningHandlerLoggingSupport implements WarningHandler { - public final void handleWarning( SQLWarning warning ) { - StringBuilder buf = new StringBuilder(30).append("SQL Warning Code: ").append(warning.getErrorCode()).append(", SQLState: ").append(warning.getSQLState()); - logWarning(buf.toString(), warning.getMessage()); - } + /** + * Basic support for {@link WarningHandler} implementations which handle {@link SQLWarning warnings} + */ + public abstract static class WarningHandlerLoggingSupport implements WarningHandler { + @Override + public final void handleWarning(SQLWarning warning) { + logWarning( + "SQL Warning Code: " + warning.getErrorCode() + ", SQLState: " + warning.getSQLState(), + warning.getMessage() + ); + } - /** - * Delegate to log common details of a {@link SQLWarning warning} - * - * @param description A description of the warning - * @param message The warning message - */ - protected abstract void logWarning( String description, - String message ); - } + /** + * Delegate to log common details of a {@link SQLWarning warning} + * + * @param description A description of the warning + * @param message The warning message + */ + protected abstract void logWarning(String description, String message); + } - public static class StandardWarningHandler extends WarningHandlerLoggingSupport { - private final String introMessage; + /** + * Standard SQLWarning handler for logging warnings + */ + public static class StandardWarningHandler extends WarningHandlerLoggingSupport { + private final String introMessage; - public StandardWarningHandler( String introMessage ) { - this.introMessage = introMessage; - } + /** + * Creates a StandardWarningHandler + * + * @param introMessage The introduction message for the hierarchy + */ + public StandardWarningHandler(String introMessage) { + this.introMessage = introMessage; + } - public boolean doProcess() { - return LOG.isEnabled(Level.WARN); - } + @Override + public boolean doProcess() { + return LOG.isEnabled( Level.WARN ); + } - public void prepare( SQLWarning warning ) { - LOG.debug(introMessage, warning); - } + @Override + public void prepare(SQLWarning warning) { + LOG.debug( introMessage, warning ); + } - @Override - protected void logWarning( String description, - String message ) { - LOG.warn(description); - LOG.warn(message); - } - } + @Override + protected void logWarning( + String description, + String message) { + LOG.warn( description ); + LOG.warn( message ); + } + } - public static StandardWarningHandler STANDARD_WARNING_HANDLER = new StandardWarningHandler(DEFAULT_WARNING_MSG); + /** + * Static access to the standard handler for logging warnings + */ + public static final StandardWarningHandler STANDARD_WARNING_HANDLER = new StandardWarningHandler( DEFAULT_WARNING_MSG ); - public void walkWarnings( SQLWarning warning, - WarningHandler handler ) { - if (warning == null || handler.doProcess()) { - return; - } - handler.prepare(warning); - while (warning != null) { - handler.handleWarning(warning); - warning = warning.getNextWarning(); - } - } + /** + * Generic algorithm to walk the hierarchy of SQLWarnings + * + * @param warning The warning to walk + * @param handler The handler + */ + public void walkWarnings( + SQLWarning warning, + WarningHandler handler) { + if ( warning == null || handler.doProcess() ) { + return; + } + handler.prepare( warning ); + while ( warning != null ) { + handler.handleWarning( warning ); + warning = warning.getNextWarning(); + } + } - /** - * Standard (legacy) behavior for logging warnings associated with a JDBC {@link Connection} and clearing them. - *

      - * Calls {@link #handleAndClearWarnings(Connection, WarningHandler)} using {@link #STANDARD_WARNING_HANDLER} - * - * @param connection The JDBC connection potentially containing warnings - */ - public void logAndClearWarnings( Connection connection ) { - handleAndClearWarnings(connection, STANDARD_WARNING_HANDLER); - } + /** + * Standard (legacy) behavior for logging warnings associated with a JDBC {@link Connection} and clearing them. + *

      + * Calls {@link #handleAndClearWarnings(Connection, WarningHandler)} using {@link #STANDARD_WARNING_HANDLER} + * + * @param connection The JDBC connection potentially containing warnings + */ + public void logAndClearWarnings(Connection connection) { + handleAndClearWarnings( connection, STANDARD_WARNING_HANDLER ); + } - /** - * General purpose handling of warnings associated with a JDBC {@link Connection}. - * - * @param connection The JDBC connection potentially containing warnings - * @param handler The handler for each individual warning in the stack. - * @see #walkWarnings - */ - @SuppressWarnings( {"ThrowableResultOfMethodCallIgnored"} ) - public void handleAndClearWarnings( Connection connection, - WarningHandler handler ) { - try { - walkWarnings(connection.getWarnings(), handler); - } catch (SQLException sqle) { - // workaround for WebLogic - LOG.debug("could not log warnings", sqle); - } - try { - // Sybase fail if we don't do that, sigh... - connection.clearWarnings(); - } catch (SQLException sqle) { - LOG.debug("could not clear warnings", sqle); - } - } + /** + * General purpose handling of warnings associated with a JDBC {@link Connection}. + * + * @param connection The JDBC connection potentially containing warnings + * @param handler The handler for each individual warning in the stack. + * + * @see #walkWarnings + */ + @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"}) + public void handleAndClearWarnings( + Connection connection, + WarningHandler handler) { + try { + walkWarnings( connection.getWarnings(), handler ); + } + catch (SQLException sqle) { + // workaround for WebLogic + LOG.debug( "could not log warnings", sqle ); + } + try { + // Sybase fail if we don't do that, sigh... + connection.clearWarnings(); + } + catch (SQLException sqle) { + LOG.debug( "could not clear warnings", sqle ); + } + } - /** - * General purpose handling of warnings associated with a JDBC {@link Statement}. - * - * @param statement The JDBC statement potentially containing warnings - * @param handler The handler for each individual warning in the stack. - * @see #walkWarnings - */ - @SuppressWarnings( {"ThrowableResultOfMethodCallIgnored"} ) - public void handleAndClearWarnings( Statement statement, - WarningHandler handler ) { - try { - walkWarnings(statement.getWarnings(), handler); - } catch (SQLException sqlException) { - // workaround for WebLogic - LOG.debug("could not log warnings", sqlException); - } - try { - // Sybase fail if we don't do that, sigh... - statement.clearWarnings(); - } catch (SQLException sqle) { - LOG.debug("could not clear warnings", sqle); - } - } + /** + * General purpose handling of warnings associated with a JDBC {@link Statement}. + * + * @param statement The JDBC statement potentially containing warnings + * @param handler The handler for each individual warning in the stack. + * + * @see #walkWarnings + */ + @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"}) + public void handleAndClearWarnings( + Statement statement, + WarningHandler handler) { + try { + walkWarnings( statement.getWarnings(), handler ); + } + catch (SQLException sqlException) { + // workaround for WebLogic + LOG.debug( "could not log warnings", sqlException ); + } + try { + // Sybase fail if we don't do that, sigh... + statement.clearWarnings(); + } + catch (SQLException sqle) { + LOG.debug( "could not clear warnings", sqle ); + } + } } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/query/spi/NativeSQLQueryPlan.java b/hibernate-core/src/main/java/org/hibernate/engine/query/spi/NativeSQLQueryPlan.java index e661bfbf4c..84867ca1f4 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/query/spi/NativeSQLQueryPlan.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/query/spi/NativeSQLQueryPlan.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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.engine.query.spi; @@ -53,22 +52,30 @@ import org.hibernate.type.Type; * @author Steve Ebersole */ public class NativeSQLQueryPlan implements Serializable { - private final String sourceQuery; + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + NativeSQLQueryPlan.class.getName() + ); + private final String sourceQuery; private final SQLCustomQuery customQuery; - private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, NativeSQLQueryPlan.class.getName()); - + /** + * Constructs a NativeSQLQueryPlan + * + * @param specification The query spec + * @param factory The SessionFactory + */ public NativeSQLQueryPlan( NativeSQLQuerySpecification specification, SessionFactoryImplementor factory) { this.sourceQuery = specification.getQueryString(); - - customQuery = new SQLCustomQuery( + this.customQuery = new SQLCustomQuery( specification.getQueryString(), specification.getQueryReturns(), specification.getQuerySpaces(), - factory ); + factory + ); } public String getSourceQuery() { diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/AssociationKey.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/AssociationKey.java index 5bf26b72b7..90bb0d380d 100755 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/AssociationKey.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/AssociationKey.java @@ -35,19 +35,36 @@ import java.io.Serializable; public final class AssociationKey implements Serializable { private EntityKey ownerKey; private String propertyName; - + + /** + * Constructs an AssociationKey + * + * @param ownerKey The EntityKey of the association owner + * @param propertyName The name of the property on the owner which defines the association + */ public AssociationKey(EntityKey ownerKey, String propertyName) { this.ownerKey = ownerKey; this.propertyName = propertyName; } - - public boolean equals(Object that) { - AssociationKey key = (AssociationKey) that; - return key.propertyName.equals(propertyName) && - key.ownerKey.equals(ownerKey); + + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } + + final AssociationKey that = (AssociationKey) o; + return ownerKey.equals( that.ownerKey ) + && propertyName.equals( that.propertyName ); } - + + @Override public int hashCode() { - return ownerKey.hashCode() + propertyName.hashCode(); + int result = ownerKey.hashCode(); + result = 31 * result + propertyName.hashCode(); + return result; } } \ No newline at end of file diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/CollectionKey.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/CollectionKey.java index a815db8fcd..9df614a053 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/CollectionKey.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/CollectionKey.java @@ -62,34 +62,26 @@ public final class CollectionKey implements Serializable { private CollectionKey( String role, - Serializable key, - Type keyType, - EntityMode entityMode, - SessionFactoryImplementor factory) { + Serializable key, + Type keyType, + EntityMode entityMode, + SessionFactoryImplementor factory) { this.role = role; this.key = key; this.keyType = keyType; this.entityMode = entityMode; this.factory = factory; - this.hashCode = generateHashCode(); //cache the hashcode + //cache the hash-code + this.hashCode = generateHashCode(); } - public boolean equals(Object other) { - CollectionKey that = (CollectionKey) other; - return that.role.equals(role) && - keyType.isEqual(that.key, key, factory); - } - - public int generateHashCode() { + private int generateHashCode() { int result = 17; result = 37 * result + role.hashCode(); - result = 37 * result + keyType.getHashCode(key, factory); + result = 37 * result + keyType.getHashCode( key, factory ); return result; } - public int hashCode() { - return hashCode; - } public String getRole() { return role; @@ -99,16 +91,38 @@ public final class CollectionKey implements Serializable { return key; } + @Override public String toString() { - return "CollectionKey" + - MessageHelper.collectionInfoString( factory.getCollectionPersister(role), key, factory ); + return "CollectionKey" + + MessageHelper.collectionInfoString( factory.getCollectionPersister( role ), key, factory ); } + @Override + public boolean equals(Object other) { + if ( this == other ) { + return true; + } + if ( other == null || getClass() != other.getClass() ) { + return false; + } + + final CollectionKey that = (CollectionKey) other; + return that.role.equals( role ) + && keyType.isEqual( that.key, key, factory ); + } + + @Override + public int hashCode() { + return hashCode; + } + + /** * Custom serialization routine used during serialization of a * Session/PersistenceContext for increased performance. * * @param oos The stream to which we should write the serial data. + * * @throws java.io.IOException */ public void serialize(ObjectOutputStream oos) throws IOException { @@ -124,19 +138,21 @@ public final class CollectionKey implements Serializable { * * @param ois The stream from which to read the entry. * @param session The session being deserialized. + * * @return The deserialized CollectionKey + * * @throws IOException * @throws ClassNotFoundException */ public static CollectionKey deserialize( ObjectInputStream ois, - SessionImplementor session) throws IOException, ClassNotFoundException { + SessionImplementor session) throws IOException, ClassNotFoundException { return new CollectionKey( - ( String ) ois.readObject(), - ( Serializable ) ois.readObject(), - ( Type ) ois.readObject(), - EntityMode.parse( ( String ) ois.readObject() ), - ( session == null ? null : session.getFactory() ) + (String) ois.readObject(), + (Serializable) ois.readObject(), + (Type) ois.readObject(), + EntityMode.parse( (String) ois.readObject() ), + (session == null ? null : session.getFactory()) ); } } \ No newline at end of file diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/EntityKey.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/EntityKey.java index 61c1409bf7..b78bebf323 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/EntityKey.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/EntityKey.java @@ -55,7 +55,7 @@ public final class EntityKey implements Serializable { /** * Construct a unique identifier for an entity class instance. - *

      + *

      * NOTE : This signature has changed to accommodate both entity mode and multi-tenancy, both of which relate to * the Session to which this key belongs. To help minimize the impact of these changes in the future, the * {@link SessionImplementor#generateEntityKey} method was added to hide the session-specific changes. @@ -68,7 +68,7 @@ public final class EntityKey implements Serializable { if ( id == null ) { throw new AssertionFailure( "null identifier" ); } - this.identifier = id; + this.identifier = id; this.rootEntityName = persister.getRootEntityName(); this.entityName = persister.getEntityName(); this.tenantId = tenantId; @@ -92,11 +92,11 @@ public final class EntityKey implements Serializable { */ private EntityKey( Serializable identifier, - String rootEntityName, - String entityName, - Type identifierType, - boolean batchLoadable, - SessionFactoryImplementor factory, + String rootEntityName, + String entityName, + Type identifierType, + boolean batchLoadable, + SessionFactoryImplementor factory, String tenantId) { this.identifier = identifier; this.rootEntityName = rootEntityName; @@ -129,10 +129,17 @@ public final class EntityKey implements Serializable { @Override public boolean equals(Object other) { - EntityKey otherKey = (EntityKey) other; - return otherKey.rootEntityName.equals(this.rootEntityName) && - identifierType.isEqual(otherKey.identifier, this.identifier, factory) && - EqualsHelper.equals( tenantId, otherKey.tenantId ); + if ( this == other ) { + return true; + } + if ( other == null || getClass() != other.getClass() ) { + return false; + } + + final EntityKey otherKey = (EntityKey) other; + return otherKey.rootEntityName.equals( this.rootEntityName ) + && identifierType.isEqual( otherKey.identifier, this.identifier, factory ) + && EqualsHelper.equals( tenantId, otherKey.tenantId ); } @Override @@ -142,8 +149,8 @@ public final class EntityKey implements Serializable { @Override public String toString() { - return "EntityKey" + - MessageHelper.infoString( factory.getEntityPersister( entityName ), identifier, factory ); + return "EntityKey" + + MessageHelper.infoString( factory.getEntityPersister( entityName ), identifier, factory ); } /** @@ -177,14 +184,14 @@ public final class EntityKey implements Serializable { */ public static EntityKey deserialize( ObjectInputStream ois, - SessionImplementor session) throws IOException, ClassNotFoundException { + SessionImplementor session) throws IOException, ClassNotFoundException { return new EntityKey( - ( Serializable ) ois.readObject(), - (String) ois.readObject(), + (Serializable) ois.readObject(), (String) ois.readObject(), - ( Type ) ois.readObject(), - ois.readBoolean(), - ( session == null ? null : session.getFactory() ), + (String) ois.readObject(), + (Type) ois.readObject(), + ois.readBoolean(), + (session == null ? null : session.getFactory()), (String) ois.readObject() ); } diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/LoadQueryInfluencers.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/LoadQueryInfluencers.java index f7f1bc0ab2..be0c1d76ef 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/LoadQueryInfluencers.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/LoadQueryInfluencers.java @@ -51,7 +51,7 @@ public class LoadQueryInfluencers implements Serializable { * outside the context of any influencers. One such example is * anything created by the session factory. */ - public static LoadQueryInfluencers NONE = new LoadQueryInfluencers(); + public static final LoadQueryInfluencers NONE = new LoadQueryInfluencers(); private final SessionFactoryImplementor sessionFactory; private String internalFetchProfile; diff --git a/hibernate-core/src/main/java/org/hibernate/engine/spi/TypedValue.java b/hibernate-core/src/main/java/org/hibernate/engine/spi/TypedValue.java index bb8ed0b594..bf360d646e 100644 --- a/hibernate-core/src/main/java/org/hibernate/engine/spi/TypedValue.java +++ b/hibernate-core/src/main/java/org/hibernate/engine/spi/TypedValue.java @@ -74,12 +74,15 @@ public final class TypedValue implements Serializable { } @Override public boolean equals(Object other) { - if ( !(other instanceof TypedValue) ) return false; - TypedValue that = (TypedValue) other; - /*return that.type.equals(type) && - EqualsHelper.equals(that.value, value);*/ - return type.getReturnedClass() == that.type.getReturnedClass() && - type.isEqual(that.value, value ); + if ( this == other ) { + return true; + } + if ( other == null || getClass() != other.getClass() ) { + return false; + } + final TypedValue that = (TypedValue) other; + return type.getReturnedClass() == that.type.getReturnedClass() + && type.isEqual( that.value, value ); } } diff --git a/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLCustomQuery.java b/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLCustomQuery.java index d495b6574a..dea83d007e 100755 --- a/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLCustomQuery.java +++ b/hibernate-core/src/main/java/org/hibernate/loader/custom/sql/SQLCustomQuery.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,9 +20,9 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.loader.custom.sql; +import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -50,7 +50,7 @@ import org.hibernate.persister.entity.SQLLoadable; * @author Max Andersen * @author Steve Ebersole */ -public class SQLCustomQuery implements CustomQuery { +public class SQLCustomQuery implements CustomQuery, Serializable { private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, SQLCustomQuery.class.getName() ); From 06fb9e70db2af2b39b8bb932c1b344718ff20944 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Tue, 30 Apr 2013 10:36:38 -0400 Subject: [PATCH 37/57] HHH-7998 - Add TypeContributions contract Conflicts: hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java hibernate-core/src/main/java/org/hibernate/metamodel/internal/MetadataImpl.java hibernate-core/src/main/java/org/hibernate/metamodel/spi/TypeContributor.java --- .../java/org/hibernate/dialect/Dialect.java | 9 +++- .../metamodel/spi/TypeContributions.java | 41 +++++++++++++++++++ .../metamodel/spi/TypeContributor.java | 41 +++++++++++++++++++ 3 files changed, 89 insertions(+), 2 deletions(-) create mode 100644 hibernate-core/src/main/java/org/hibernate/metamodel/spi/TypeContributions.java create mode 100644 hibernate-core/src/main/java/org/hibernate/metamodel/spi/TypeContributor.java diff --git a/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java b/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java index feacda61a6..3a863cf289 100644 --- a/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java +++ b/hibernate-core/src/main/java/org/hibernate/dialect/Dialect.java @@ -39,8 +39,6 @@ import java.util.Map; import java.util.Properties; import java.util.Set; -import org.jboss.logging.Logger; - import org.hibernate.HibernateException; import org.hibernate.LockMode; import org.hibernate.LockOptions; @@ -79,7 +77,9 @@ import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.collections.ArrayHelper; import org.hibernate.internal.util.io.StreamCopier; import org.hibernate.mapping.Column; +import org.hibernate.metamodel.spi.TypeContributions; import org.hibernate.persister.entity.Lockable; +import org.hibernate.service.ServiceRegistry; import org.hibernate.sql.ANSICaseFragment; import org.hibernate.sql.ANSIJoinFragment; import org.hibernate.sql.CaseFragment; @@ -88,6 +88,7 @@ import org.hibernate.sql.JoinFragment; import org.hibernate.type.StandardBasicTypes; import org.hibernate.type.descriptor.sql.ClobTypeDescriptor; import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; +import org.jboss.logging.Logger; /** * Represents a dialect of SQL implemented by a particular RDBMS. Subclasses implement Hibernate compatibility @@ -282,6 +283,10 @@ public abstract class Dialect implements ConversionContext { // database type mapping support ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + public void contributeTypes(TypeContributions typeContributions, ServiceRegistry serviceRegistry) { + // by default, nothing to do + } + /** * Get the name of the database type associated with the given * {@link java.sql.Types} typecode. diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/spi/TypeContributions.java b/hibernate-core/src/main/java/org/hibernate/metamodel/spi/TypeContributions.java new file mode 100644 index 0000000000..630e63b4d0 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/spi/TypeContributions.java @@ -0,0 +1,41 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2012, 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.metamodel.spi; + +import org.hibernate.type.BasicType; +import org.hibernate.usertype.CompositeUserType; +import org.hibernate.usertype.UserType; + +/** + * Defines the target contributing types, whether via dialects or {@link TypeContributor} + * + * @author Steve Ebersole + */ +public interface TypeContributions { + public void contributeType(BasicType type); + + public void contributeType(UserType type, String[] keys); + + public void contributeType(CompositeUserType type, String[] keys); +} diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/spi/TypeContributor.java b/hibernate-core/src/main/java/org/hibernate/metamodel/spi/TypeContributor.java new file mode 100644 index 0000000000..004caef5e6 --- /dev/null +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/spi/TypeContributor.java @@ -0,0 +1,41 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2012, 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.metamodel.spi; + +import org.hibernate.service.ServiceRegistry; + +/** + * Contract for contributing types. + * + * @author Steve Ebersole + */ +public interface TypeContributor { + /** + * Contribute types + * + * @param typeContributions The callback for adding contributed types + * @param serviceRegistry The service registry + */ + public void contribute(TypeContributions typeContributions, ServiceRegistry serviceRegistry); +} From 04fe84994d848536d591b6d592c5cf80fb9386dd Mon Sep 17 00:00:00 2001 From: Brett Meyer Date: Tue, 30 Apr 2013 23:51:44 -0400 Subject: [PATCH 38/57] HHH-7995 Added support for TypeContributors in OSGi. Integrated with envers Conflicts: hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java hibernate-entitymanager/src/main/java/org/hibernate/ejb/Ejb3Configuration.java hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java --- .../java/org/hibernate/cfg/Configuration.java | 48 ++++++++++++++++++- .../metamodel/spi/TypeContributor.java | 3 ++ .../EntityManagerFactoryBuilderImpl.java | 17 +++++++ .../entities/TypeContributorImpl.java | 38 +++++++++++++++ ...rg.hibernate.metamodel.spi.TypeContributor | 1 + .../OSGI-INF/blueprint/blueprint.xml | 3 ++ .../osgi/OsgiPersistenceProvider.java | 12 ++++- .../osgi/OsgiSessionFactoryService.java | 15 ++++-- 8 files changed, 129 insertions(+), 8 deletions(-) create mode 100644 hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/TypeContributorImpl.java create mode 100644 hibernate-envers/src/main/resources/META-INF/services/org.hibernate.metamodel.spi.TypeContributor diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java index e92dc075b7..5f770cb4f0 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/Configuration.java @@ -79,6 +79,7 @@ import org.hibernate.annotations.common.reflection.ReflectionManager; import org.hibernate.annotations.common.reflection.XClass; import org.hibernate.annotations.common.reflection.java.JavaReflectionManager; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.boot.registry.classloading.spi.ClassLoaderService; import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl; import org.hibernate.cfg.annotations.reflection.JPAMetadataProvider; import org.hibernate.context.spi.CurrentTenantIdentifierResolver; @@ -86,6 +87,7 @@ import org.hibernate.dialect.Dialect; import org.hibernate.dialect.MySQLDialect; import org.hibernate.dialect.function.SQLFunction; import org.hibernate.engine.ResultSetMappingDefinition; +import org.hibernate.engine.jdbc.spi.JdbcServices; import org.hibernate.engine.spi.FilterDefinition; import org.hibernate.engine.spi.Mapping; import org.hibernate.engine.spi.NamedQueryDefinition; @@ -133,15 +135,17 @@ import org.hibernate.mapping.SimpleValue; import org.hibernate.mapping.Table; import org.hibernate.mapping.TypeDef; import org.hibernate.mapping.UniqueKey; +import org.hibernate.metamodel.spi.TypeContributions; +import org.hibernate.metamodel.spi.TypeContributor; import org.hibernate.proxy.EntityNotFoundDelegate; import org.hibernate.secure.spi.GrantedPermission; import org.hibernate.secure.spi.JaccPermissionDeclarations; import org.hibernate.service.ServiceRegistry; -import org.hibernate.tool.hbm2ddl.UniqueConstraintSchemaUpdateStrategy; import org.hibernate.tool.hbm2ddl.DatabaseMetadata; import org.hibernate.tool.hbm2ddl.IndexMetadata; import org.hibernate.tool.hbm2ddl.SchemaUpdateScript; import org.hibernate.tool.hbm2ddl.TableMetadata; +import org.hibernate.tool.hbm2ddl.UniqueConstraintSchemaUpdateStrategy; import org.hibernate.tuple.entity.EntityTuplizerFactory; import org.hibernate.type.BasicType; import org.hibernate.type.SerializationException; @@ -223,7 +227,9 @@ public class Configuration implements Serializable { protected Map extendsQueue; protected Map sqlFunctions; + private TypeResolver typeResolver = new TypeResolver(); + private List typeContributorRegistrations = new ArrayList(); private EntityTuplizerFactory entityTuplizerFactory; // private ComponentTuplizerFactory componentTuplizerFactory; todo : HHH-3517 and HHH-1907 @@ -1782,7 +1788,8 @@ public class Configuration implements Serializable { */ public SessionFactory buildSessionFactory(ServiceRegistry serviceRegistry) throws HibernateException { LOG.debugf( "Preparing to build session factory with filters : %s", filterDefinitions ); - + + buildTypeRegistrations( serviceRegistry ); secondPassCompile(); if ( !metadataSourceQueue.isEmpty() ) { LOG.incompleteMappingMetadataCacheProcessing(); @@ -1804,6 +1811,39 @@ public class Configuration implements Serializable { sessionFactoryObserver ); } + + private void buildTypeRegistrations(ServiceRegistry serviceRegistry) { + final TypeContributions typeContributions = new TypeContributions() { + @Override + public void contributeType(BasicType type) { + typeResolver.registerTypeOverride( type ); + } + + @Override + public void contributeType(UserType type, String[] keys) { + typeResolver.registerTypeOverride( type, keys ); + } + + @Override + public void contributeType(CompositeUserType type, String[] keys) { + typeResolver.registerTypeOverride( type, keys ); + } + }; + + // add Dialect contributed types + final Dialect dialect = serviceRegistry.getService( JdbcServices.class ).getDialect(); + dialect.contributeTypes( typeContributions, serviceRegistry ); + + // add TypeContributor contributed types. + ClassLoaderService classLoaderService = serviceRegistry.getService( ClassLoaderService.class ); + for ( TypeContributor contributor : classLoaderService.loadJavaServices( TypeContributor.class ) ) { + contributor.contribute( typeContributions, serviceRegistry ); + } + // from app registrations + for ( TypeContributor contributor : typeContributorRegistrations ) { + contributor.contribute( typeContributions, serviceRegistry ); + } + } /** * Create a {@link SessionFactory} using the properties and mappings in this configuration. The @@ -2510,6 +2550,10 @@ public class Configuration implements Serializable { getTypeResolver().registerTypeOverride( type, keys ); } + public void registerTypeContributor(TypeContributor typeContributor) { + typeContributorRegistrations.add( typeContributor ); + } + public SessionFactoryObserver getSessionFactoryObserver() { return sessionFactoryObserver; } diff --git a/hibernate-core/src/main/java/org/hibernate/metamodel/spi/TypeContributor.java b/hibernate-core/src/main/java/org/hibernate/metamodel/spi/TypeContributor.java index 004caef5e6..4a04173faa 100644 --- a/hibernate-core/src/main/java/org/hibernate/metamodel/spi/TypeContributor.java +++ b/hibernate-core/src/main/java/org/hibernate/metamodel/spi/TypeContributor.java @@ -29,6 +29,9 @@ import org.hibernate.service.ServiceRegistry; * Contract for contributing types. * * @author Steve Ebersole + * + * NOTE: Cherry-pick of HHH-7998 from metamodel. For merging simplicity, just + * keep it in the o.h.metamodel.spi package. */ public interface TypeContributor { /** diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/internal/EntityManagerFactoryBuilderImpl.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/internal/EntityManagerFactoryBuilderImpl.java index 433aa11465..eb3fe79eba 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/internal/EntityManagerFactoryBuilderImpl.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/internal/EntityManagerFactoryBuilderImpl.java @@ -88,6 +88,7 @@ import org.hibernate.jpa.boot.spi.NamedInputStream; import org.hibernate.jpa.boot.spi.PackageDescriptor; import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor; import org.hibernate.jpa.boot.spi.StrategyRegistrationProviderList; +import org.hibernate.jpa.boot.spi.TypeContributorList; import org.hibernate.jpa.event.spi.JpaIntegrator; import org.hibernate.jpa.internal.EntityManagerFactoryImpl; import org.hibernate.jpa.internal.EntityManagerMessageLogger; @@ -97,6 +98,7 @@ import org.hibernate.jpa.internal.util.PersistenceUnitTransactionTypeHelper; import org.hibernate.jpa.spi.IdentifierGeneratorStrategyProvider; import org.hibernate.metamodel.source.annotations.JPADotNames; import org.hibernate.metamodel.source.annotations.JandexHelper; +import org.hibernate.metamodel.spi.TypeContributor; import org.hibernate.proxy.EntityNotFoundDelegate; import org.hibernate.secure.spi.GrantedPermission; import org.hibernate.secure.spi.JaccService; @@ -135,6 +137,11 @@ public class EntityManagerFactoryBuilderImpl implements EntityManagerFactoryBuil * Names a {@link StrategyRegistrationProviderList} */ public static final String STRATEGY_REGISTRATION_PROVIDERS = "hibernate.strategy_registration_provider"; + + /** + * Names a {@link TypeContributorList} + */ + public static final String TYPE_CONTRIBUTORS = "hibernate.type_contributors"; /** * Names a Jandex {@link Index} instance to use. @@ -1166,6 +1173,16 @@ public class EntityManagerFactoryBuilderImpl implements EntityManagerFactoryBuil for ( String packageName : metadataSources.packageNames ) { cfg.addPackage( packageName ); } + + final TypeContributorList typeContributorList + = (TypeContributorList) configurationValues.get( TYPE_CONTRIBUTORS ); + if ( typeContributorList != null ) { + configurationValues.remove( TYPE_CONTRIBUTORS ); + for ( TypeContributor typeContributor : typeContributorList.getTypeContributors() ) { + cfg.registerTypeContributor( typeContributor ); + } + } + return cfg; } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/TypeContributorImpl.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/TypeContributorImpl.java new file mode 100644 index 0000000000..0a49200a26 --- /dev/null +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/TypeContributorImpl.java @@ -0,0 +1,38 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * JBoss, Home of Professional Open Source + * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors + * as indicated by the @authors tag. All rights reserved. + * See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * 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, v. 2.1. + * This program is distributed in the hope that it will be useful, but WITHOUT A + * 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, + * v.2.1 along with this distribution; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ +package org.hibernate.envers.internal.entities; + +import org.hibernate.metamodel.spi.TypeContributions; +import org.hibernate.metamodel.spi.TypeContributor; +import org.hibernate.service.ServiceRegistry; + +/** + * @author Brett Meyer + */ +public class TypeContributorImpl implements TypeContributor { + + @Override + public void contribute(TypeContributions typeContributions, ServiceRegistry serviceRegistry) { + typeContributions.contributeType( new RevisionTypeType(), + new String[] { RevisionTypeType.class.getName() } ); + } + +} diff --git a/hibernate-envers/src/main/resources/META-INF/services/org.hibernate.metamodel.spi.TypeContributor b/hibernate-envers/src/main/resources/META-INF/services/org.hibernate.metamodel.spi.TypeContributor new file mode 100644 index 0000000000..5eeaedd30c --- /dev/null +++ b/hibernate-envers/src/main/resources/META-INF/services/org.hibernate.metamodel.spi.TypeContributor @@ -0,0 +1 @@ +org.hibernate.envers.internal.entities.TypeContributorImpl \ No newline at end of file diff --git a/hibernate-envers/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/hibernate-envers/src/main/resources/OSGI-INF/blueprint/blueprint.xml index 07c01bfc9f..9fc677c57e 100644 --- a/hibernate-envers/src/main/resources/OSGI-INF/blueprint/blueprint.xml +++ b/hibernate-envers/src/main/resources/OSGI-INF/blueprint/blueprint.xml @@ -6,5 +6,8 @@ + + + diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java index 23cc77d8b7..c99715b8e5 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiPersistenceProvider.java @@ -37,7 +37,8 @@ import org.hibernate.jpa.HibernatePersistenceProvider; import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; import org.hibernate.jpa.boot.spi.IntegratorProvider; import org.hibernate.jpa.boot.spi.StrategyRegistrationProviderList; - +import org.hibernate.jpa.boot.spi.TypeContributorList; +import org.hibernate.metamodel.spi.TypeContributor; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.BundleReference; @@ -135,6 +136,15 @@ public class OsgiPersistenceProvider extends HibernatePersistenceProvider { } }; settings.put( EntityManagerFactoryBuilderImpl.STRATEGY_REGISTRATION_PROVIDERS, strategyRegistrationProviderList ); + + final List typeContributors = OsgiServiceUtil.getServiceImpls( TypeContributor.class, context ); + TypeContributorList typeContributorList = new TypeContributorList() { + @Override + public List getTypeContributors() { + return typeContributors; + } + }; + settings.put( EntityManagerFactoryBuilderImpl.TYPE_CONTRIBUTORS, typeContributorList ); return settings; } diff --git a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java index af6c57be4d..71b45387c9 100644 --- a/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java +++ b/hibernate-osgi/src/main/java/org/hibernate/osgi/OsgiSessionFactoryService.java @@ -22,11 +22,6 @@ package org.hibernate.osgi; import java.util.List; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.osgi.framework.ServiceFactory; -import org.osgi.framework.ServiceRegistration; - import org.hibernate.SessionFactory; import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; @@ -34,7 +29,12 @@ import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; import org.hibernate.cfg.AvailableSettings; import org.hibernate.cfg.Configuration; import org.hibernate.integrator.spi.Integrator; +import org.hibernate.metamodel.spi.TypeContributor; import org.hibernate.service.ServiceRegistry; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceFactory; +import org.osgi.framework.ServiceRegistration; /** * Hibernate 4.2 and 4.3 still heavily rely on TCCL for ClassLoading. Although @@ -96,6 +96,11 @@ public class OsgiSessionFactoryService implements ServiceFactory { for ( StrategyRegistrationProvider strategyRegistrationProvider : strategyRegistrationProviders ) { builder.withStrategySelectors( strategyRegistrationProvider ); } + + final List typeContributors = OsgiServiceUtil.getServiceImpls( TypeContributor.class, context ); + for (TypeContributor typeContributor : typeContributors) { + configuration.registerTypeContributor( typeContributor ); + } final ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder( builder.build() ) .applySettings( configuration.getProperties() ).build(); From fe9e2798decfac61dbfd24227288199446690145 Mon Sep 17 00:00:00 2001 From: Brett Meyer Date: Tue, 30 Apr 2013 23:58:25 -0400 Subject: [PATCH 39/57] HHH-7944 envers classloader issues Conflicts: hibernate-envers/src/main/java/org/hibernate/envers/configuration/spi/AuditConfiguration.java --- .../configuration/spi/AuditConfiguration.java | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/spi/AuditConfiguration.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/spi/AuditConfiguration.java index ccf294c410..ce32b2c187 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/spi/AuditConfiguration.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/spi/AuditConfiguration.java @@ -45,6 +45,7 @@ import org.hibernate.envers.internal.synchronization.AuditProcessManager; import org.hibernate.envers.internal.tools.ReflectionTools; import org.hibernate.envers.strategy.AuditStrategy; import org.hibernate.envers.strategy.ValidityAuditStrategy; +import org.hibernate.internal.util.ClassLoaderHelper; import org.hibernate.internal.util.ReflectHelper; import org.hibernate.property.Getter; @@ -104,6 +105,11 @@ public class AuditConfiguration { } public AuditConfiguration(Configuration cfg, ClassLoaderService classLoaderService) { + // TODO: Temporarily allow Envers to continuing using + // hibernate-commons-annotations' for reflection and class loading. + ClassLoader tccl = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader( ClassLoaderHelper.getContextClassLoader() ); + Properties properties = cfg.getProperties(); ReflectionManager reflectionManager = cfg.getReflectionManager(); @@ -124,13 +130,21 @@ public class AuditConfiguration { cfg, reflectionManager, globalCfg, auditEntCfg, auditStrategy, classLoaderService, revInfoCfgResult.getRevisionInfoXmlMapping(), revInfoCfgResult.getRevisionInfoRelationMapping() ); + + Thread.currentThread().setContextClassLoader( tccl ); } private AuditStrategy initializeAuditStrategy(Class revisionInfoClass, PropertyData revisionInfoTimestampData) { AuditStrategy strategy; try { - Class auditStrategyClass = ReflectionTools.loadClass( auditEntCfg.getAuditStrategyName(), classLoaderService ); + Class auditStrategyClass = null; + try { + auditStrategyClass = this.getClass().getClassLoader().loadClass( auditEntCfg.getAuditStrategyName() ); + } + catch (Exception e) { + auditStrategyClass = ReflectionTools.loadClass( auditEntCfg.getAuditStrategyName(), classLoaderService ); + } strategy = (AuditStrategy) ReflectHelper.getDefaultConstructor(auditStrategyClass).newInstance(); } catch ( Exception e ) { From a1d190d6748ed8ec1675659a2f11e5eb63c5210f Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Wed, 1 May 2013 09:23:31 -0500 Subject: [PATCH 40/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../internal/BulkOperationCleanupAction.java | 2 +- .../hibernate/internal/AbstractQueryImpl.java | 2 +- .../org/hibernate/sql/OracleJoinFragment.java | 10 +-- .../java/org/hibernate/dialect/Mocks.java | 2 +- .../event/internal/EventCacheTest.java | 4 +- .../test/annotations/EntityTest.java | 64 +++++++++---------- .../org/hibernate/test/annotations/Sky.java | 2 +- .../CollectionElementTest.java | 6 +- .../hibernate/jpa/test/EntityManagerTest.java | 2 +- .../test/callbacks/CallbackAndDirtyTest.java | 6 +- .../packaging/PackagedEntityManagerTest.java | 2 +- .../IndexedJoinColumnBidirectionalList.java | 24 +++---- ...nceIndexedJoinColumnBidirectionalList.java | 24 +++---- 13 files changed, 75 insertions(+), 75 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/action/internal/BulkOperationCleanupAction.java b/hibernate-core/src/main/java/org/hibernate/action/internal/BulkOperationCleanupAction.java index a40e491f97..ad7dd07a66 100644 --- a/hibernate-core/src/main/java/org/hibernate/action/internal/BulkOperationCleanupAction.java +++ b/hibernate-core/src/main/java/org/hibernate/action/internal/BulkOperationCleanupAction.java @@ -247,7 +247,7 @@ public class BulkOperationCleanupAction implements Executable, Serializable { } } - private class NaturalIdCleanup implements Serializable { + private static class NaturalIdCleanup implements Serializable { private final NaturalIdRegionAccessStrategy naturalIdCacheAccessStrategy; private final SoftLock cacheLock; diff --git a/hibernate-core/src/main/java/org/hibernate/internal/AbstractQueryImpl.java b/hibernate-core/src/main/java/org/hibernate/internal/AbstractQueryImpl.java index 5dfaaeb249..a62ea7d243 100644 --- a/hibernate-core/src/main/java/org/hibernate/internal/AbstractQueryImpl.java +++ b/hibernate-core/src/main/java/org/hibernate/internal/AbstractQueryImpl.java @@ -561,7 +561,7 @@ public abstract class AbstractQueryImpl implements Query { } public Query setCharacter(int position, char val) { - setParameter(position, new Character(val), StandardBasicTypes.CHARACTER); + setParameter( position, Character.valueOf( val ), StandardBasicTypes.CHARACTER ); return this; } diff --git a/hibernate-core/src/main/java/org/hibernate/sql/OracleJoinFragment.java b/hibernate-core/src/main/java/org/hibernate/sql/OracleJoinFragment.java index b9885257bd..585d82e081 100644 --- a/hibernate-core/src/main/java/org/hibernate/sql/OracleJoinFragment.java +++ b/hibernate-core/src/main/java/org/hibernate/sql/OracleJoinFragment.java @@ -129,8 +129,8 @@ public class OracleJoinFragment extends JoinFragment { StringBuilder buf = new StringBuilder( on ); for ( int i = 0; i < buf.length(); i++ ) { char character = buf.charAt( i ); - boolean isInsertPoint = OPERATORS.contains( new Character( character ) ) || - ( character == ' ' && buf.length() > i + 3 && "is ".equals( buf.substring( i + 1, i + 4 ) ) ); + final boolean isInsertPoint = OPERATORS.contains( Character.valueOf( character ) ) + || ( character == ' ' && buf.length() > i + 3 && "is ".equals( buf.substring( i + 1, i + 4 ) ) ); if ( isInsertPoint ) { buf.insert( i, "(+)" ); i += 3; @@ -142,8 +142,8 @@ public class OracleJoinFragment extends JoinFragment { private static final Set OPERATORS = new HashSet(); static { - OPERATORS.add( new Character( '=' ) ); - OPERATORS.add( new Character( '<' ) ); - OPERATORS.add( new Character( '>' ) ); + OPERATORS.add( Character.valueOf( '=' ) ); + OPERATORS.add( Character.valueOf( '<' ) ); + OPERATORS.add( Character.valueOf( '>' ) ); } } diff --git a/hibernate-core/src/test/java/org/hibernate/dialect/Mocks.java b/hibernate-core/src/test/java/org/hibernate/dialect/Mocks.java index 4f79f00497..8f5f371af3 100644 --- a/hibernate-core/src/test/java/org/hibernate/dialect/Mocks.java +++ b/hibernate-core/src/test/java/org/hibernate/dialect/Mocks.java @@ -135,7 +135,7 @@ public class Mocks { } if ( "hashCode".equals( methodName ) ) { - return new Integer( this.hashCode() ); + return Integer.valueOf( this.hashCode() ); } if ( canThrowSQLException( method ) ) { diff --git a/hibernate-core/src/test/java/org/hibernate/event/internal/EventCacheTest.java b/hibernate-core/src/test/java/org/hibernate/event/internal/EventCacheTest.java index ff3576e59e..da97c8f985 100644 --- a/hibernate-core/src/test/java/org/hibernate/event/internal/EventCacheTest.java +++ b/hibernate-core/src/test/java/org/hibernate/event/internal/EventCacheTest.java @@ -127,10 +127,10 @@ public class EventCacheTest extends BaseCoreFunctionalTestCase { Map input = new HashMap(); Object entity1 = new Simple( 1 ); // - Object copy1 = new Integer( 2 ); + Object copy1 = Integer.valueOf( 2 ); input.put(entity1, copy1); Object entity2 = new Simple( 3 ); - Object copy2 = new Integer( 2 ); + Object copy2 = Integer.valueOf( 2 ); input.put(entity2, copy2); cache.putAll(input); diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/EntityTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/EntityTest.java index 9fbdfa7187..fb73f2ab7d 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/EntityTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/EntityTest.java @@ -62,7 +62,7 @@ public class EntityTest extends BaseCoreFunctionalTestCase { Session s = openSession(); Transaction tx = s.beginTransaction(); Flight firstOne = new Flight(); - firstOne.setId( new Long( 1 ) ); + firstOne.setId( Long.valueOf( 1 ) ); firstOne.setName( "AF3202" ); firstOne.setDuration( new Long( 1000000 ) ); firstOne.setDurationInSec( 2000 ); @@ -74,11 +74,11 @@ public class EntityTest extends BaseCoreFunctionalTestCase { //read it s = openSession(); tx = s.beginTransaction(); - firstOne = (Flight) s.get( Flight.class, new Long( 1 ) ); + firstOne = (Flight) s.get( Flight.class, Long.valueOf( 1 ) ); assertNotNull( firstOne ); - assertEquals( new Long( 1 ), firstOne.getId() ); + assertEquals( Long.valueOf( 1 ), firstOne.getId() ); assertEquals( "AF3202", firstOne.getName() ); - assertEquals( new Long( 1000000 ), firstOne.getDuration() ); + assertEquals( Long.valueOf( 1000000 ), firstOne.getDuration() ); assertFalse( "Transient is not working", 2000l == firstOne.getDurationInSec() ); tx.commit(); s.close(); @@ -90,9 +90,9 @@ public class EntityTest extends BaseCoreFunctionalTestCase { Session s = openSession(); Transaction tx = s.beginTransaction(); Flight firstOne = new Flight(); - firstOne.setId( new Long( 1 ) ); + firstOne.setId( Long.valueOf( 1 ) ); firstOne.setName( "AF3202" ); - firstOne.setDuration( new Long( 1000000 ) ); + firstOne.setDuration( Long.valueOf( 1000000 ) ); firstOne.setDurationInSec( 2000 ); s.save( firstOne ); s.flush(); @@ -103,7 +103,7 @@ public class EntityTest extends BaseCoreFunctionalTestCase { s = openSession(); tx = s.beginTransaction(); firstOne = new Flight(); - firstOne.setId( new Long( 1 ) ); + firstOne.setId( Long.valueOf( 1 ) ); firstOne.setName( null ); try { @@ -122,7 +122,7 @@ public class EntityTest extends BaseCoreFunctionalTestCase { s = openSession(); tx = s.beginTransaction(); firstOne = new Flight(); - firstOne.setId( new Long( 1 ) ); + firstOne.setId( Long.valueOf( 1 ) ); firstOne.setName( "AF3202" ); firstOne.setTriggeredData( "should not be insertable" ); tx.commit(); @@ -130,9 +130,9 @@ public class EntityTest extends BaseCoreFunctionalTestCase { s = openSession(); tx = s.beginTransaction(); - firstOne = (Flight) s.get( Flight.class, new Long( 1 ) ); + firstOne = (Flight) s.get( Flight.class, Long.valueOf( 1 ) ); assertNotNull( firstOne ); - assertEquals( new Long( 1 ), firstOne.getId() ); + assertEquals( Long.valueOf( 1 ), firstOne.getId() ); assertEquals( "AF3202", firstOne.getName() ); assertFalse( "should not be insertable".equals( firstOne.getTriggeredData() ) ); firstOne.setName( "BA1234" ); @@ -142,9 +142,9 @@ public class EntityTest extends BaseCoreFunctionalTestCase { s = openSession(); tx = s.beginTransaction(); - firstOne = (Flight) s.get( Flight.class, new Long( 1 ) ); + firstOne = (Flight) s.get( Flight.class, Long.valueOf( 1 ) ); assertNotNull( firstOne ); - assertEquals( new Long( 1 ), firstOne.getId() ); + assertEquals( Long.valueOf( 1 ), firstOne.getId() ); assertEquals( "AF3202", firstOne.getName() ); assertFalse( "should not be updatable".equals( firstOne.getTriggeredData() ) ); tx.commit(); @@ -158,13 +158,13 @@ public class EntityTest extends BaseCoreFunctionalTestCase { s = openSession(); tx = s.beginTransaction(); Sky sky = new Sky(); - sky.id = new Long( 2 ); + sky.id = Long.valueOf( 2 ); sky.color = "blue"; sky.day = "monday"; sky.month = "January"; Sky sameSky = new Sky(); - sameSky.id = new Long( 3 ); + sameSky.id = Long.valueOf( 3 ); sameSky.color = "blue"; sky.day = "tuesday"; sky.month = "January"; @@ -193,19 +193,19 @@ public class EntityTest extends BaseCoreFunctionalTestCase { s = openSession(); tx = s.beginTransaction(); Sky sky = new Sky(); - sky.id = new Long( id++ ); + sky.id = Long.valueOf( id++ ); sky.color = "green"; sky.day = "monday"; sky.month = "March"; Sky otherSky = new Sky(); - otherSky.id = new Long( id++ ); + otherSky.id = Long.valueOf( id++ ); otherSky.color = "red"; otherSky.day = "friday"; otherSky.month = "March"; Sky sameSky = new Sky(); - sameSky.id = new Long( id++ ); + sameSky.id = Long.valueOf( id++ ); sameSky.color = "green"; sameSky.day = "monday"; sameSky.month = "March"; @@ -239,9 +239,9 @@ public class EntityTest extends BaseCoreFunctionalTestCase { Session s = openSession(); Transaction tx = s.beginTransaction(); Flight firstOne = new Flight(); - firstOne.setId( new Long( 2 ) ); + firstOne.setId( Long.valueOf( 2 ) ); firstOne.setName( "AF3202" ); - firstOne.setDuration( new Long( 500 ) ); + firstOne.setDuration( Long.valueOf( 500 ) ); s.save( firstOne ); s.flush(); tx.commit(); @@ -250,15 +250,15 @@ public class EntityTest extends BaseCoreFunctionalTestCase { //read it s = openSession(); tx = s.beginTransaction(); - firstOne = (Flight) s.get( Flight.class, new Long( 2 ) ); + firstOne = (Flight) s.get( Flight.class, Long.valueOf( 2 ) ); tx.commit(); s.close(); //read it again s = openSession(); tx = s.beginTransaction(); - Flight concurrentOne = (Flight) s.get( Flight.class, new Long( 2 ) ); - concurrentOne.setDuration( new Long( 1000 ) ); + Flight concurrentOne = (Flight) s.get( Flight.class, Long.valueOf( 2 ) ); + concurrentOne.setDuration( Long.valueOf( 1000 ) ); s.update( concurrentOne ); tx.commit(); s.close(); @@ -290,22 +290,22 @@ public class EntityTest extends BaseCoreFunctionalTestCase { s = openSession(); tx = s.beginTransaction(); Sky sky = new Sky(); - sky.id = new Long( 1 ); + sky.id = Long.valueOf( 1 ); sky.color = "black"; - Sky.area = "Paris"; + sky.area = "Paris"; sky.day = "23"; sky.month = "1"; s.save( sky ); tx.commit(); s.close(); - Sky.area = "London"; + sky.area = "London"; s = openSession(); tx = s.beginTransaction(); sky = (Sky) s.get( Sky.class, sky.id ); assertNotNull( sky ); assertEquals( "black", sky.color ); - assertFalse( "Paris".equals( Sky.area ) ); + assertFalse( "Paris".equals( sky.area ) ); tx.commit(); s.close(); } @@ -336,9 +336,9 @@ public class EntityTest extends BaseCoreFunctionalTestCase { Session s = openSession(); Transaction tx = s.beginTransaction(); Flight airFrance = new Flight(); - airFrance.setId( new Long( 747 ) ); + airFrance.setId( Long.valueOf( 747 ) ); airFrance.setName( "Paris-Amsterdam" ); - airFrance.setDuration( new Long( 10 ) ); + airFrance.setDuration( Long.valueOf( 10 ) ); airFrance.setFactor( 25 ); s.persist( airFrance ); tx.commit(); @@ -348,7 +348,7 @@ public class EntityTest extends BaseCoreFunctionalTestCase { tx = s.beginTransaction(); airFrance = (Flight) s.get( Flight.class, airFrance.getId() ); assertNotNull( airFrance ); - assertEquals( new Long( 10 ), airFrance.getDuration() ); + assertEquals( Long.valueOf( 10 ), airFrance.getDuration() ); assertFalse( 25 == airFrance.getFactor( false ) ); s.delete( airFrance ); tx.commit(); @@ -360,9 +360,9 @@ public class EntityTest extends BaseCoreFunctionalTestCase { Session s = openSession(); Transaction tx = s.beginTransaction(); Flight airFrance = new Flight(); - airFrance.setId( new Long( 747 ) ); + airFrance.setId( Long.valueOf( 747 ) ); airFrance.setName( "Paris-Amsterdam" ); - airFrance.setDuration( new Long( 10 ) ); + airFrance.setDuration( Long.valueOf( 10 ) ); airFrance.setDepartureDate( new Date( 05, 06, 21, 10, 0, 0 ) ); airFrance.setAlternativeDepartureDate( new GregorianCalendar( 2006, 02, 03, 10, 00 ) ); airFrance.getAlternativeDepartureDate().setTimeZone( TimeZone.getTimeZone( "GMT" ) ); @@ -394,7 +394,7 @@ public class EntityTest extends BaseCoreFunctionalTestCase { Session s = openSession(); Transaction tx = s.beginTransaction(); Flight airFrance = new Flight(); - airFrance.setId( new Long( 747 ) ); + airFrance.setId( Long.valueOf( 747 ) ); airFrance.setName( "Paris-Amsterdam" ); airFrance.setDuration( null ); try { diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/Sky.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/Sky.java index 86edc4e2ba..fbea31e6e2 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/Sky.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/Sky.java @@ -23,5 +23,5 @@ public class Sky implements Serializable { protected String day; @Column(name = "MONTH", nullable = false) protected String month; - static protected String area; + protected String area; } diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/CollectionElementTest.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/CollectionElementTest.java index 0795794bff..0f69d745dd 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/CollectionElementTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/collectionelement/CollectionElementTest.java @@ -63,8 +63,8 @@ public class CollectionElementTest extends BaseCoreFunctionalTestCase { boy.setLastName( "Doe" ); boy.getNickNames().add( "Johnny" ); boy.getNickNames().add( "Thing" ); - boy.getScorePerNickName().put( "Johnny", new Integer( 3 ) ); - boy.getScorePerNickName().put( "Thing", new Integer( 5 ) ); + boy.getScorePerNickName().put( "Johnny", Integer.valueOf( 3 ) ); + boy.getScorePerNickName().put( "Thing", Integer.valueOf( 5 ) ); int[] favNbrs = new int[4]; for (int index = 0; index < favNbrs.length - 1; index++) { favNbrs[index] = index * 3; @@ -87,7 +87,7 @@ public class CollectionElementTest extends BaseCoreFunctionalTestCase { assertTrue( boy.getNickNames().contains( "Thing" ) ); assertNotNull( boy.getScorePerNickName() ); assertTrue( boy.getScorePerNickName().containsKey( "Thing" ) ); - assertEquals( new Integer( 5 ), boy.getScorePerNickName().get( "Thing" ) ); + assertEquals( Integer.valueOf( 5 ), boy.getScorePerNickName().get( "Thing" ) ); assertNotNull( boy.getFavoriteNumbers() ); assertEquals( 3, boy.getFavoriteNumbers()[1] ); assertTrue( boy.getCharacters().contains( Character.CRAFTY ) ); diff --git a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java index bf3be224c3..89360d4a47 100755 --- a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java +++ b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/EntityManagerTest.java @@ -186,7 +186,7 @@ public class EntityManagerTest extends BaseEntityManagerFunctionalTestCase { public void testContains() throws Exception { EntityManager em = getOrCreateEntityManager(); em.getTransaction().begin(); - Integer nonManagedObject = new Integer( 4 ); + Integer nonManagedObject = Integer.valueOf( 4 ); try { em.contains( nonManagedObject ); fail( "Should have raised an exception" ); diff --git a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/callbacks/CallbackAndDirtyTest.java b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/callbacks/CallbackAndDirtyTest.java index 2e171c32d5..eb87a016e6 100644 --- a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/callbacks/CallbackAndDirtyTest.java +++ b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/callbacks/CallbackAndDirtyTest.java @@ -96,9 +96,9 @@ public class CallbackAndDirtyTest extends BaseEntityManagerFunctionalTestCase { manager.getTransaction().commit(); manager.getTransaction().begin(); - mark = manager.find( Employee.class, new Long( ids[0] ) ); - joe = manager.find( Customer.class, new Long( ids[1] ) ); - yomomma = manager.find( Person.class, new Long( ids[2] ) ); + mark = manager.find( Employee.class, Long.valueOf( ids[0] ) ); + joe = manager.find( Customer.class, Long.valueOf( ids[1] ) ); + yomomma = manager.find( Person.class, Long.valueOf( ids[2] ) ); mark.setZip( "30306" ); assertEquals( 1, manager.createQuery( "select p from Person p where p.zip = '30306'" ).getResultList().size() ); diff --git a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/packaging/PackagedEntityManagerTest.java b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/packaging/PackagedEntityManagerTest.java index 2fed86b63a..b319f761d4 100644 --- a/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/packaging/PackagedEntityManagerTest.java +++ b/hibernate-entitymanager/src/test/java/org/hibernate/jpa/test/packaging/PackagedEntityManagerTest.java @@ -460,7 +460,7 @@ public class PackagedEntityManagerTest extends PackagingTestCase { em = emf.createEntityManager(); em.getTransaction().begin(); s = em.find( Scooter.class, s.getModel() ); - assertEquals( new Long( 85 ), s.getSpeed() ); + assertEquals( Long.valueOf( 85 ), s.getSpeed() ); em.remove( s ); em.getTransaction().commit(); em.close(); diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/IndexedJoinColumnBidirectionalList.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/IndexedJoinColumnBidirectionalList.java index a28c9cabf3..ea186da718 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/IndexedJoinColumnBidirectionalList.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/IndexedJoinColumnBidirectionalList.java @@ -204,10 +204,10 @@ public class IndexedJoinColumnBidirectionalList extends BaseEnversJPAFunctionalT assertTrue(rev3.getOwner().equals(ing1)); assertTrue(rev4.getOwner().equals(ing1)); - assertEquals(rev1.getPosition(), new Integer(0)); - assertEquals(rev2.getPosition(), new Integer(0)); - assertEquals(rev3.getPosition(), new Integer(1)); - assertEquals(rev4.getPosition(), new Integer(2)); + assertEquals( rev1.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev2.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev3.getPosition(), Integer.valueOf( 1 ) ); + assertEquals( rev4.getPosition(), Integer.valueOf( 2 ) ); } @Test @@ -225,10 +225,10 @@ public class IndexedJoinColumnBidirectionalList extends BaseEnversJPAFunctionalT assertTrue(rev3.getOwner().equals(ing2)); assertTrue(rev4.getOwner().equals(ing1)); - assertEquals(rev1.getPosition(), new Integer(1)); - assertEquals(rev2.getPosition(), new Integer(0)); - assertEquals(rev3.getPosition(), new Integer(0)); - assertEquals(rev4.getPosition(), new Integer(0)); + assertEquals( rev1.getPosition(), Integer.valueOf( 1 ) ); + assertEquals( rev2.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev3.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev4.getPosition(), Integer.valueOf( 0 ) ); } @Test @@ -245,9 +245,9 @@ public class IndexedJoinColumnBidirectionalList extends BaseEnversJPAFunctionalT assertTrue(rev3.getOwner().equals(ing1)); assertTrue(rev4.getOwner().equals(ing1)); - assertEquals(rev1.getPosition(), new Integer(2)); - assertEquals(rev2.getPosition(), new Integer(1)); - assertEquals(rev3.getPosition(), new Integer(0)); - assertEquals(rev4.getPosition(), new Integer(1)); + assertEquals( rev1.getPosition(), Integer.valueOf( 2 ) ); + assertEquals( rev2.getPosition(), Integer.valueOf( 1 ) ); + assertEquals( rev3.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev4.getPosition(), Integer.valueOf( 1 ) ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/InheritanceIndexedJoinColumnBidirectionalList.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/InheritanceIndexedJoinColumnBidirectionalList.java index 3fa7e5f1d2..a9845ad1f1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/InheritanceIndexedJoinColumnBidirectionalList.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/InheritanceIndexedJoinColumnBidirectionalList.java @@ -209,10 +209,10 @@ public class InheritanceIndexedJoinColumnBidirectionalList extends BaseEnversJPA assertTrue(rev3.getOwner().equals(ing1)); assertTrue(rev4.getOwner().equals(ing1)); - assertEquals(rev1.getPosition(), new Integer(0)); - assertEquals(rev2.getPosition(), new Integer(0)); - assertEquals(rev3.getPosition(), new Integer(1)); - assertEquals(rev4.getPosition(), new Integer(2)); + assertEquals( rev1.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev2.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev3.getPosition(), Integer.valueOf( 1 ) ); + assertEquals( rev4.getPosition(), Integer.valueOf( 2 ) ); } @Test @@ -230,10 +230,10 @@ public class InheritanceIndexedJoinColumnBidirectionalList extends BaseEnversJPA assertTrue(rev3.getOwner().equals(ing2)); assertTrue(rev4.getOwner().equals(ing1)); - assertEquals(rev1.getPosition(), new Integer(1)); - assertEquals(rev2.getPosition(), new Integer(0)); - assertEquals(rev3.getPosition(), new Integer(0)); - assertEquals(rev4.getPosition(), new Integer(0)); + assertEquals( rev1.getPosition(), Integer.valueOf( 1 ) ); + assertEquals( rev2.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev3.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev4.getPosition(), Integer.valueOf( 0 ) ); } @Test @@ -250,9 +250,9 @@ public class InheritanceIndexedJoinColumnBidirectionalList extends BaseEnversJPA assertTrue(rev3.getOwner().equals(ing1)); assertTrue(rev4.getOwner().equals(ing1)); - assertEquals(rev1.getPosition(), new Integer(2)); - assertEquals(rev2.getPosition(), new Integer(1)); - assertEquals(rev3.getPosition(), new Integer(0)); - assertEquals(rev4.getPosition(), new Integer(1)); + assertEquals( rev1.getPosition(), Integer.valueOf( 2 ) ); + assertEquals( rev2.getPosition(), Integer.valueOf( 1 ) ); + assertEquals( rev3.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev4.getPosition(), Integer.valueOf( 1 ) ); } } \ No newline at end of file From 4d04dfc0888bbb59c5a99d5fe13a2d37184eb28d Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Wed, 1 May 2013 10:34:05 -0500 Subject: [PATCH 41/57] HHH-8207 - Locale conversion is broken --- .../type/AttributeConverterTest.java | 7 +- .../type/BasicTypeRegistryTest.java | 11 ++- .../hibernate/{ => test}/type/TypeTest.java | 35 +++++++++- .../java/AbstractDescriptorTest.java | 4 +- .../java/BigDecimalDescriptorTest.java | 4 +- .../java/BigIntegerDescriptorTest.java | 4 +- .../descriptor/java/BlobDescriptorTest.java | 5 +- .../java/BooleanDescriptorTest.java | 4 +- .../java/LocaleTypeDescriptorTest.java | 69 +++++++++++++++++++ .../descriptor/java/StringDescriptorTest.java | 4 +- .../sql/PreparedStatementProxy.java | 2 +- .../type/descriptor/sql/ResultSetProxy.java | 2 +- .../type/descriptor/sql/StringClobImpl.java | 2 +- .../sql/StringValueMappingTest.java | 5 +- 14 files changed, 144 insertions(+), 14 deletions(-) rename hibernate-core/src/test/java/org/hibernate/{ => test}/type/AttributeConverterTest.java (95%) rename hibernate-core/src/test/java/org/hibernate/{ => test}/type/BasicTypeRegistryTest.java (94%) rename hibernate-core/src/test/java/org/hibernate/{ => test}/type/TypeTest.java (90%) rename hibernate-core/src/test/java/org/hibernate/{ => test}/type/descriptor/java/AbstractDescriptorTest.java (97%) rename hibernate-core/src/test/java/org/hibernate/{ => test}/type/descriptor/java/BigDecimalDescriptorTest.java (93%) rename hibernate-core/src/test/java/org/hibernate/{ => test}/type/descriptor/java/BigIntegerDescriptorTest.java (93%) rename hibernate-core/src/test/java/org/hibernate/{ => test}/type/descriptor/java/BlobDescriptorTest.java (92%) rename hibernate-core/src/test/java/org/hibernate/{ => test}/type/descriptor/java/BooleanDescriptorTest.java (93%) create mode 100644 hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/LocaleTypeDescriptorTest.java rename hibernate-core/src/test/java/org/hibernate/{ => test}/type/descriptor/java/StringDescriptorTest.java (93%) rename hibernate-core/src/test/java/org/hibernate/{ => test}/type/descriptor/sql/PreparedStatementProxy.java (98%) rename hibernate-core/src/test/java/org/hibernate/{ => test}/type/descriptor/sql/ResultSetProxy.java (98%) rename hibernate-core/src/test/java/org/hibernate/{ => test}/type/descriptor/sql/StringClobImpl.java (98%) rename hibernate-core/src/test/java/org/hibernate/{ => test}/type/descriptor/sql/StringValueMappingTest.java (95%) diff --git a/hibernate-core/src/test/java/org/hibernate/type/AttributeConverterTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/AttributeConverterTest.java similarity index 95% rename from hibernate-core/src/test/java/org/hibernate/type/AttributeConverterTest.java rename to hibernate-core/src/test/java/org/hibernate/test/type/AttributeConverterTest.java index 4405018174..a1ab1ced22 100644 --- a/hibernate-core/src/test/java/org/hibernate/type/AttributeConverterTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/type/AttributeConverterTest.java @@ -21,7 +21,7 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.type; +package org.hibernate.test.type; import javax.persistence.AttributeConverter; import javax.persistence.Convert; @@ -37,6 +37,9 @@ import org.hibernate.cfg.Configuration; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; import org.hibernate.mapping.SimpleValue; +import org.hibernate.type.AbstractStandardBasicType; +import org.hibernate.type.BasicType; +import org.hibernate.type.Type; import org.hibernate.type.descriptor.java.StringTypeDescriptor; import org.junit.Test; @@ -49,7 +52,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; /** - * Tests the principle of adding "AttributeConverter" to the mix of {@link Type} resolution + * Tests the principle of adding "AttributeConverter" to the mix of {@link org.hibernate.type.Type} resolution * * @author Steve Ebersole */ diff --git a/hibernate-core/src/test/java/org/hibernate/type/BasicTypeRegistryTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/BasicTypeRegistryTest.java similarity index 94% rename from hibernate-core/src/test/java/org/hibernate/type/BasicTypeRegistryTest.java rename to hibernate-core/src/test/java/org/hibernate/test/type/BasicTypeRegistryTest.java index a898e7a17d..ed9b7cc6b3 100644 --- a/hibernate-core/src/test/java/org/hibernate/type/BasicTypeRegistryTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/type/BasicTypeRegistryTest.java @@ -21,7 +21,7 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.type; +package org.hibernate.test.type; import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -33,6 +33,15 @@ import org.junit.Test; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.testing.junit4.BaseUnitTestCase; + +import org.hibernate.type.AbstractSingleColumnStandardBasicType; +import org.hibernate.type.BasicType; +import org.hibernate.type.BasicTypeRegistry; +import org.hibernate.type.CompositeCustomType; +import org.hibernate.type.CustomType; +import org.hibernate.type.Type; +import org.hibernate.type.UUIDBinaryType; +import org.hibernate.type.UUIDCharType; import org.hibernate.type.descriptor.java.StringTypeDescriptor; import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor; import org.hibernate.usertype.CompositeUserType; diff --git a/hibernate-core/src/test/java/org/hibernate/type/TypeTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/TypeTest.java similarity index 90% rename from hibernate-core/src/test/java/org/hibernate/type/TypeTest.java rename to hibernate-core/src/test/java/org/hibernate/test/type/TypeTest.java index 541725b034..3f6a6de910 100644 --- a/hibernate-core/src/test/java/org/hibernate/type/TypeTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/type/TypeTest.java @@ -21,7 +21,7 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.type; +package org.hibernate.test.type; import java.io.Serializable; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; @@ -45,6 +45,39 @@ import org.hibernate.Session; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.internal.util.SerializationHelper; import org.hibernate.internal.util.collections.ArrayHelper; +import org.hibernate.type.AbstractSingleColumnStandardBasicType; +import org.hibernate.type.BigDecimalType; +import org.hibernate.type.BigIntegerType; +import org.hibernate.type.BinaryType; +import org.hibernate.type.BooleanType; +import org.hibernate.type.ByteType; +import org.hibernate.type.CalendarDateType; +import org.hibernate.type.CalendarType; +import org.hibernate.type.CharArrayType; +import org.hibernate.type.CharacterArrayType; +import org.hibernate.type.CharacterType; +import org.hibernate.type.ClassType; +import org.hibernate.type.CurrencyType; +import org.hibernate.type.DateType; +import org.hibernate.type.DoubleType; +import org.hibernate.type.FloatType; +import org.hibernate.type.ImageType; +import org.hibernate.type.IntegerType; +import org.hibernate.type.LocaleType; +import org.hibernate.type.LongType; +import org.hibernate.type.MaterializedBlobType; +import org.hibernate.type.MaterializedClobType; +import org.hibernate.type.NumericBooleanType; +import org.hibernate.type.SerializableType; +import org.hibernate.type.ShortType; +import org.hibernate.type.StringType; +import org.hibernate.type.TextType; +import org.hibernate.type.TimeType; +import org.hibernate.type.TimeZoneType; +import org.hibernate.type.TimestampType; +import org.hibernate.type.TrueFalseType; +import org.hibernate.type.YesNoType; + import org.hibernate.testing.junit4.BaseUnitTestCase; import static org.junit.Assert.assertFalse; diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/AbstractDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/AbstractDescriptorTest.java similarity index 97% rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/java/AbstractDescriptorTest.java rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/AbstractDescriptorTest.java index 312aeaaa14..ba8a2a1c40 100644 --- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/AbstractDescriptorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/AbstractDescriptorTest.java @@ -21,11 +21,13 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.type.descriptor.java; +package org.hibernate.test.type.descriptor.java; import java.io.Serializable; import java.sql.Blob; import java.sql.Clob; +import org.hibernate.type.descriptor.java.JavaTypeDescriptor; + import org.junit.Before; import org.junit.Test; diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BigDecimalDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BigDecimalDescriptorTest.java similarity index 93% rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BigDecimalDescriptorTest.java rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BigDecimalDescriptorTest.java index c3924ffadd..0643102cdc 100644 --- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BigDecimalDescriptorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BigDecimalDescriptorTest.java @@ -21,9 +21,11 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.type.descriptor.java; +package org.hibernate.test.type.descriptor.java; import java.math.BigDecimal; +import org.hibernate.type.descriptor.java.BigDecimalTypeDescriptor; + /** * @author Steve Ebersole */ diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BigIntegerDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BigIntegerDescriptorTest.java similarity index 93% rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BigIntegerDescriptorTest.java rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BigIntegerDescriptorTest.java index fceb752037..76ec3e94bb 100644 --- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BigIntegerDescriptorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BigIntegerDescriptorTest.java @@ -21,9 +21,11 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.type.descriptor.java; +package org.hibernate.test.type.descriptor.java; import java.math.BigInteger; +import org.hibernate.type.descriptor.java.BigIntegerTypeDescriptor; + /** * @author Steve Ebersole */ diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BlobDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BlobDescriptorTest.java similarity index 92% rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BlobDescriptorTest.java rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BlobDescriptorTest.java index 8cdc89ab4e..b5f1cd2935 100644 --- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BlobDescriptorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BlobDescriptorTest.java @@ -21,13 +21,16 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.type.descriptor.java; +package org.hibernate.test.type.descriptor.java; import java.sql.Blob; import java.sql.SQLException; import org.junit.Test; import org.hibernate.engine.jdbc.BlobProxy; +import org.hibernate.type.descriptor.java.BlobTypeDescriptor; +import org.hibernate.type.descriptor.java.DataHelper; +import org.hibernate.type.descriptor.java.PrimitiveByteArrayTypeDescriptor; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BooleanDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BooleanDescriptorTest.java similarity index 93% rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BooleanDescriptorTest.java rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BooleanDescriptorTest.java index 15cb04dd24..a045f548c6 100644 --- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/BooleanDescriptorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/BooleanDescriptorTest.java @@ -21,9 +21,11 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.type.descriptor.java; +package org.hibernate.test.type.descriptor.java; +import org.hibernate.type.descriptor.java.BooleanTypeDescriptor; + /** * @author Steve Ebersole */ diff --git a/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/LocaleTypeDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/LocaleTypeDescriptorTest.java new file mode 100644 index 0000000000..8584106acc --- /dev/null +++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/LocaleTypeDescriptorTest.java @@ -0,0 +1,69 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.type.descriptor.java; + +import java.util.Locale; +import java.util.StringTokenizer; + +import org.hibernate.internal.util.StringHelper; +import org.hibernate.type.descriptor.java.LocaleTypeDescriptor; + +import org.junit.Test; + +import org.hibernate.testing.junit4.BaseUnitTestCase; + +import static org.junit.Assert.assertEquals; + +/** + * Tests of the {@link LocaleTypeDescriptor} class. + * + * @author Christian Beikov + * @author Steve Ebersole + */ +public class LocaleTypeDescriptorTest extends BaseUnitTestCase { + @Test + public void testConversionFromString() { + assertEquals( toLocale( "de", null, null ), LocaleTypeDescriptor.INSTANCE.fromString( "de" ) ); + assertEquals( toLocale( "de", "DE", null ), LocaleTypeDescriptor.INSTANCE.fromString( "de_DE" ) ); + assertEquals( toLocale( null, "DE", null ), LocaleTypeDescriptor.INSTANCE.fromString( "_DE" ) ); + assertEquals( toLocale( null, null, "ch" ), LocaleTypeDescriptor.INSTANCE.fromString( "__ch" ) ); + assertEquals( toLocale( null, "DE", "ch" ), LocaleTypeDescriptor.INSTANCE.fromString( "_DE_ch" ) ); + assertEquals( toLocale( "de", null, "ch" ), LocaleTypeDescriptor.INSTANCE.fromString( "de__ch" ) ); + assertEquals( toLocale( "de", "DE", "ch" ), LocaleTypeDescriptor.INSTANCE.fromString( "de_DE_ch" ) ); + } + + public Locale toLocale(String lang, String region, String variant) { + final Locale.Builder builder = new Locale.Builder(); + if ( StringHelper.isNotEmpty( lang ) ) { + builder.setLanguage( lang ); + } + if ( StringHelper.isNotEmpty( region ) ) { + builder.setRegion( region ); + } + if ( StringHelper.isNotEmpty( variant ) ) { + builder.setVariant( variant ); + } + return builder.build(); + } +} diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/StringDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/StringDescriptorTest.java similarity index 93% rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/java/StringDescriptorTest.java rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/StringDescriptorTest.java index 496358865c..df48304864 100644 --- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/java/StringDescriptorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/StringDescriptorTest.java @@ -21,9 +21,11 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.type.descriptor.java; +package org.hibernate.test.type.descriptor.java; +import org.hibernate.type.descriptor.java.StringTypeDescriptor; + /** * @author Steve Ebersole */ diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/PreparedStatementProxy.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/PreparedStatementProxy.java similarity index 98% rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/PreparedStatementProxy.java rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/PreparedStatementProxy.java index 521f1cd749..2429ed9c2f 100644 --- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/PreparedStatementProxy.java +++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/PreparedStatementProxy.java @@ -21,7 +21,7 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.type.descriptor.sql; +package org.hibernate.test.type.descriptor.sql; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/ResultSetProxy.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/ResultSetProxy.java similarity index 98% rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/ResultSetProxy.java rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/ResultSetProxy.java index 5406a25a75..a8932c1d39 100644 --- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/ResultSetProxy.java +++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/ResultSetProxy.java @@ -21,7 +21,7 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.type.descriptor.sql; +package org.hibernate.test.type.descriptor.sql; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/StringClobImpl.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/StringClobImpl.java similarity index 98% rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/StringClobImpl.java rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/StringClobImpl.java index e7e362c459..3a0246e492 100644 --- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/StringClobImpl.java +++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/StringClobImpl.java @@ -21,7 +21,7 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.type.descriptor.sql; +package org.hibernate.test.type.descriptor.sql; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; diff --git a/hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/StringValueMappingTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/StringValueMappingTest.java similarity index 95% rename from hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/StringValueMappingTest.java rename to hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/StringValueMappingTest.java index 2803819df3..992cb643e1 100644 --- a/hibernate-core/src/test/java/org/hibernate/type/descriptor/sql/StringValueMappingTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/sql/StringValueMappingTest.java @@ -21,7 +21,7 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ -package org.hibernate.type.descriptor.sql; +package org.hibernate.test.type.descriptor.sql; import java.sql.Clob; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -36,6 +36,9 @@ import org.hibernate.type.descriptor.ValueBinder; import org.hibernate.type.descriptor.ValueExtractor; import org.hibernate.type.descriptor.WrapperOptions; import org.hibernate.type.descriptor.java.StringTypeDescriptor; +import org.hibernate.type.descriptor.sql.ClobTypeDescriptor; +import org.hibernate.type.descriptor.sql.SqlTypeDescriptor; +import org.hibernate.type.descriptor.sql.VarcharTypeDescriptor; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; From b39fdbf1f8bfaf0e717deb5b8530bbe52534f665 Mon Sep 17 00:00:00 2001 From: Christian Beikov Date: Sat, 27 Apr 2013 11:54:09 +0300 Subject: [PATCH 42/57] Fix string to locale conversion The original implementation didn't care about leading underscores. StringTokenizer skips leading separators which is actually wrong. new Locale("", "XX").toString() produces "_XX" which can't be converted back to the same locale with the original implementation. --- .../hibernate/type/descriptor/java/LocaleTypeDescriptor.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/LocaleTypeDescriptor.java b/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/LocaleTypeDescriptor.java index 646662ac00..e12f28312f 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/LocaleTypeDescriptor.java +++ b/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/LocaleTypeDescriptor.java @@ -60,8 +60,8 @@ public class LocaleTypeDescriptor extends AbstractTypeDescriptor { public Locale fromString(String string) { StringTokenizer tokens = new StringTokenizer( string, "_" ); - String language = tokens.hasMoreTokens() ? tokens.nextToken() : ""; - String country = tokens.hasMoreTokens() ? tokens.nextToken() : ""; + String language = tokens.hasMoreTokens() && string.charAt(0) != '_' ? tokens.nextToken() : ""; + String country = tokens.hasMoreTokens() && string.charAt(string.indexOf(language) + language.length() + 1) != '_' ? tokens.nextToken() : ""; // Need to account for allowable '_' within the variant String variant = ""; String sep = ""; From 2b20197249e2e94bc22b6d1be54b28458e36211c Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Wed, 1 May 2013 11:28:23 -0500 Subject: [PATCH 43/57] HHH-8207 - Locale conversion is broken --- .../type/descriptor/java/LocaleTypeDescriptor.java | 13 +++++++++---- .../descriptor/java/LocaleTypeDescriptorTest.java | 9 +++++---- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/LocaleTypeDescriptor.java b/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/LocaleTypeDescriptor.java index e12f28312f..72bfe2ddc7 100644 --- a/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/LocaleTypeDescriptor.java +++ b/hibernate-core/src/main/java/org/hibernate/type/descriptor/java/LocaleTypeDescriptor.java @@ -59,10 +59,15 @@ public class LocaleTypeDescriptor extends AbstractTypeDescriptor { } public Locale fromString(String string) { - StringTokenizer tokens = new StringTokenizer( string, "_" ); - String language = tokens.hasMoreTokens() && string.charAt(0) != '_' ? tokens.nextToken() : ""; - String country = tokens.hasMoreTokens() && string.charAt(string.indexOf(language) + language.length() + 1) != '_' ? tokens.nextToken() : ""; - // Need to account for allowable '_' within the variant + // TODO : Ultimately switch to Locale.Builder for this. However, Locale.Builder is Java 7 + + final StringTokenizer tokens = new StringTokenizer( string, "_" ); + final String language = tokens.hasMoreTokens() && string.charAt(0) != '_' ? tokens.nextToken() : ""; + final String country = tokens.hasMoreTokens() && string.charAt(string.indexOf(language) + language.length() + 1) != '_' ? tokens.nextToken() : ""; + + // Need to account for allowable '_' within the variant. The underscore within the variant delimits "subtags". + // Technically the reference spec (IETF BCP 47) also allows dash ("-") as a variant subtag delimiter. + // Note that this code block supports both approaches... String variant = ""; String sep = ""; while ( tokens.hasMoreTokens() ) { diff --git a/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/LocaleTypeDescriptorTest.java b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/LocaleTypeDescriptorTest.java index 8584106acc..0c1da5b205 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/LocaleTypeDescriptorTest.java +++ b/hibernate-core/src/test/java/org/hibernate/test/type/descriptor/java/LocaleTypeDescriptorTest.java @@ -42,15 +42,16 @@ import static org.junit.Assert.assertEquals; * @author Steve Ebersole */ public class LocaleTypeDescriptorTest extends BaseUnitTestCase { + @Test public void testConversionFromString() { assertEquals( toLocale( "de", null, null ), LocaleTypeDescriptor.INSTANCE.fromString( "de" ) ); assertEquals( toLocale( "de", "DE", null ), LocaleTypeDescriptor.INSTANCE.fromString( "de_DE" ) ); assertEquals( toLocale( null, "DE", null ), LocaleTypeDescriptor.INSTANCE.fromString( "_DE" ) ); - assertEquals( toLocale( null, null, "ch" ), LocaleTypeDescriptor.INSTANCE.fromString( "__ch" ) ); - assertEquals( toLocale( null, "DE", "ch" ), LocaleTypeDescriptor.INSTANCE.fromString( "_DE_ch" ) ); - assertEquals( toLocale( "de", null, "ch" ), LocaleTypeDescriptor.INSTANCE.fromString( "de__ch" ) ); - assertEquals( toLocale( "de", "DE", "ch" ), LocaleTypeDescriptor.INSTANCE.fromString( "de_DE_ch" ) ); + assertEquals( toLocale( null, null, "ch123" ), LocaleTypeDescriptor.INSTANCE.fromString( "__ch123" ) ); + assertEquals( toLocale( null, "DE", "ch123" ), LocaleTypeDescriptor.INSTANCE.fromString( "_DE_ch123" ) ); + assertEquals( toLocale( "de", null, "ch123" ), LocaleTypeDescriptor.INSTANCE.fromString( "de__ch123" ) ); + assertEquals( toLocale( "de", "DE", "ch123" ), LocaleTypeDescriptor.INSTANCE.fromString( "de_DE_ch123" ) ); } public Locale toLocale(String lang, String region, String variant) { From 8c9ab58f444284e4f4ccd67fbf08759a53019ff1 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Wed, 1 May 2013 11:52:08 -0500 Subject: [PATCH 44/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../test/java/org/hibernate/event/internal/EventCacheTest.java | 2 +- .../src/test/java/org/hibernate/test/annotations/Sky.java | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/hibernate-core/src/test/java/org/hibernate/event/internal/EventCacheTest.java b/hibernate-core/src/test/java/org/hibernate/event/internal/EventCacheTest.java index da97c8f985..e98b9b46ea 100644 --- a/hibernate-core/src/test/java/org/hibernate/event/internal/EventCacheTest.java +++ b/hibernate-core/src/test/java/org/hibernate/event/internal/EventCacheTest.java @@ -127,7 +127,7 @@ public class EventCacheTest extends BaseCoreFunctionalTestCase { Map input = new HashMap(); Object entity1 = new Simple( 1 ); // - Object copy1 = Integer.valueOf( 2 ); + Object copy1 = Integer.valueOf( 1 ); input.put(entity1, copy1); Object entity2 = new Simple( 3 ); Object copy2 = Integer.valueOf( 2 ); diff --git a/hibernate-core/src/test/java/org/hibernate/test/annotations/Sky.java b/hibernate-core/src/test/java/org/hibernate/test/annotations/Sky.java index fbea31e6e2..4bb6175598 100644 --- a/hibernate-core/src/test/java/org/hibernate/test/annotations/Sky.java +++ b/hibernate-core/src/test/java/org/hibernate/test/annotations/Sky.java @@ -5,6 +5,7 @@ import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; +import javax.persistence.Transient; import javax.persistence.UniqueConstraint; /** @@ -23,5 +24,6 @@ public class Sky implements Serializable { protected String day; @Column(name = "MONTH", nullable = false) protected String month; + @Transient protected String area; } From 07a6abfab9987b4f46ec6951cb335be542fcb307 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Wed, 1 May 2013 13:46:23 -0500 Subject: [PATCH 45/57] HHH-8159 - Apply fixups indicated by analysis tools --- build.gradle | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/build.gradle b/build.gradle index 8b27b237e1..8788526015 100644 --- a/build.gradle +++ b/build.gradle @@ -343,7 +343,13 @@ subprojects { subProject -> ignoreFailures = true } // exclude generated sources - checkstyleMain.exclude '**/generated-src/**' + // unfortunately this nice easy approach does not seem to work : http://forums.gradle.org/gradle/topics/specify_excludes_to_checkstyle_task + //checkstyleMain.exclude '**/generated-src/**' + checkstyleMain.exclude '**/org/hibernate/hql/internal/antlr/**' + checkstyleMain.exclude '**/org/hibernate/hql/internal/antlr/*' + checkstyleMain.exclude '**/org/hibernate/sql/ordering/antlr/*' + checkstyleMain.exclude '**/*_$logger*' + checkstyleMain.exclude '**/org/hibernate/internal/jaxb/**' // because cfg package is a mess mainly from annotation stuff checkstyleMain.exclude '**/org/hibernate/cfg/**' checkstyleMain.exclude '**/org/hibernate/cfg/*' @@ -353,7 +359,13 @@ subprojects { subProject -> ignoreFailures = true } // exclude generated sources - findbugsMain.exclude '**/generated-src/**' + // unfortunately this nice easy approach does not seem to work : http://forums.gradle.org/gradle/topics/specify_excludes_to_checkstyle_task + //findbugsMain.exclude '**/generated-src/**' + findbugsMain.exclude '**/org/hibernate/hql/internal/antlr/**' + findbugsMain.exclude '**/org/hibernate/hql/internal/antlr/*' + findbugsMain.exclude '**/org/hibernate/sql/ordering/antlr/*' + findbugsMain.exclude '**/*_$logger*' + findbugsMain.exclude '**/org/hibernate/internal/jaxb/**' buildDashboard.dependsOn check From 9d134955c4f07de7b928e8c5ecbe727fc59c269d Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Wed, 1 May 2013 14:00:49 -0500 Subject: [PATCH 46/57] HHH-8212 - Add CLA ref to CONTRIBUTING.md --- CONTRIBUTING.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a157cac46f..0ad0a0323a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,18 +8,20 @@ contributing to a minimum, there are a few guidelines we ask that you mind. If you are just getting started with Git, GitHub and/or contributing to Hibernate via GitHub there are a few pre-requisite steps. +* Make sure you have signed a [Contributor License Aggrement](https://cla.jboss.org) (CLA) for the Hibernate project * Make sure you have a [Hibernate Jira account](https://hibernate.onjira.com) * Make sure you have a [GitHub account](https://github.com/signup/free) * [Fork](http://help.github.com/fork-a-repo) the Hibernate repository. As discussed in the linked page, this also includes: * [Set](https://help.github.com/articles/set-up-git) up your local git install * Clone your fork - +* See the wiki pages for setting up your IDE, whether you use [IntelliJ IDEA](https://community.jboss.org/wiki/ContributingToHibernateUsingIntelliJ) +or [Eclipse](https://community.jboss.org/wiki/ContributingToHibernateUsingEclipse). ## Create the working (topic) branch -Create a "topic" branch on which you will work. The convention is to name the branch -using the JIRA issue key. If there is not already a Jira issue covering the work you -want to do, create one. Assuming you will be working from the master branch and working +Create a [topic branch](http://git-scm.com/book/en/Git-Branching-Branching-Workflows#Topic-Branches) on which you +will work. The convention is to name the branch using the JIRA issue key. If there is not already a Jira issue +covering the work you want to do, create one. Assuming you will be working from the master branch and working on the Jira HHH-123 : `git checkout -b HHH-123 master` @@ -39,7 +41,7 @@ appreciated btw), please use rebasing rather than merging. Merging creates "merge commits" that really muck up the project timeline._ ## Submit -* Sign the [Contributor License Agreement](https://cla.jboss.org/index.seam). -* Push your changes to a topic branch in your fork of the repository. +* If you have not already, sign the [Contributor License Agreement](https://cla.jboss.org). +* Push your changes to the topic branch in your fork of the repository. * Initiate a [pull request](http://help.github.com/send-pull-requests/) * Update the Jira issue, adding a comment inclusing a link to the created pull request From 489ee4a734364db37a25a890760fa4a543867d6c Mon Sep 17 00:00:00 2001 From: Brett Meyer Date: Wed, 1 May 2013 14:10:53 -0400 Subject: [PATCH 47/57] HHH-7943 Added support for ehcache and infinispan strategies and OSGi services. Numerous ehcache and infinispan CL fixes. --- .../internal/RegionFactoryInitiator.java | 46 +++++++++++++------ .../org/hibernate/cfg/SettingsFactory.java | 37 +-------------- .../ehcache/AbstractEhcacheRegionFactory.java | 9 ++++ .../cache/ehcache/EhCacheRegionFactory.java | 8 +--- .../StrategyRegistrationProviderImpl.java | 2 + .../OSGI-INF/blueprint/blueprint.xml | 10 ++++ .../infinispan/InfinispanRegionFactory.java | 15 +++++- .../StrategyRegistrationProviderImpl.java | 2 + ...ot.registry.selector.AvailabilityAnnouncer | 0 ...stry.selector.StrategyRegistrationProvider | 1 + .../OSGI-INF/blueprint/blueprint.xml | 10 ++++ 11 files changed, 81 insertions(+), 59 deletions(-) create mode 100644 hibernate-ehcache/src/main/resources/OSGI-INF/blueprint/blueprint.xml delete mode 100644 hibernate-infinispan/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.AvailabilityAnnouncer create mode 100644 hibernate-infinispan/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider create mode 100644 hibernate-infinispan/src/main/resources/OSGI-INF/blueprint/blueprint.xml diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java index ffa33b8e72..4a934b6ad2 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java @@ -28,44 +28,62 @@ import java.util.Map; import org.hibernate.boot.registry.StandardServiceInitiator; import org.hibernate.boot.registry.selector.spi.StrategySelector; import org.hibernate.cache.spi.RegionFactory; +import org.hibernate.cfg.AvailableSettings; +import org.hibernate.internal.CoreMessageLogger; +import org.hibernate.internal.util.config.ConfigurationHelper; import org.hibernate.service.spi.ServiceRegistryImplementor; +import org.jboss.logging.Logger; /** * Initiator for the {@link RegionFactory} service. - * + * * @author Hardy Ferentschik + * @author Brett Meyer */ public class RegionFactoryInitiator implements StandardServiceInitiator { + + private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, + RegionFactoryInitiator.class.getName() ); + /** * Singleton access */ public static final RegionFactoryInitiator INSTANCE = new RegionFactoryInitiator(); - /** - * Property name to use to configure the full qualified class name for the {@code RegionFactory} - */ - public static final String IMPL_NAME = "hibernate.cache.region.factory_class"; - @Override public Class getServiceInitiated() { return RegionFactory.class; } @Override - @SuppressWarnings( { "unchecked" }) + @SuppressWarnings({ "unchecked" }) public RegionFactory initiateService(Map configurationValues, ServiceRegistryImplementor registry) { - final Object setting = configurationValues.get( IMPL_NAME ); - return registry.getService( StrategySelector.class ).resolveDefaultableStrategy( - RegionFactory.class, - setting, - NoCachingRegionFactory.INSTANCE - ); + boolean useSecondLevelCache = ConfigurationHelper.getBoolean( AvailableSettings.USE_SECOND_LEVEL_CACHE, + configurationValues, true ); + boolean useQueryCache = ConfigurationHelper.getBoolean( AvailableSettings.USE_QUERY_CACHE, configurationValues ); + + RegionFactory regionFactory; + + // The cache provider is needed when we either have second-level cache enabled + // or query cache enabled. Note that useSecondLevelCache is enabled by default + if ( useSecondLevelCache || useQueryCache ) { + final Object setting = configurationValues.get( AvailableSettings.CACHE_REGION_FACTORY ); + regionFactory = registry.getService( StrategySelector.class ).resolveDefaultableStrategy( + RegionFactory.class, setting, NoCachingRegionFactory.INSTANCE ); + } + else { + regionFactory = NoCachingRegionFactory.INSTANCE; + } + + LOG.debugf( "Cache region factory : %s", regionFactory.getClass().getName() ); + + return regionFactory; } /** * Map legacy names unto the new corollary. * - * todo this shouldn't be public, nor really static. hack for org.hibernate.cfg.SettingsFactory.createRegionFactory() + * TODO: temporary hack for org.hibernate.cfg.SettingsFactory.createRegionFactory() * * @param name The (possibly legacy) factory name * diff --git a/hibernate-core/src/main/java/org/hibernate/cfg/SettingsFactory.java b/hibernate-core/src/main/java/org/hibernate/cfg/SettingsFactory.java index 67209c644b..7219d08948 100644 --- a/hibernate-core/src/main/java/org/hibernate/cfg/SettingsFactory.java +++ b/hibernate-core/src/main/java/org/hibernate/cfg/SettingsFactory.java @@ -290,9 +290,7 @@ public class SettingsFactory implements Serializable { settings.setQueryCacheFactory( createQueryCacheFactory( properties, serviceRegistry ) ); } - // The cache provider is needed when we either have second-level cache enabled - // or query cache enabled. Note that useSecondLevelCache is enabled by default - settings.setRegionFactory( createRegionFactory( properties, ( useSecondLevelCache || useQueryCache ), serviceRegistry ) ); + settings.setRegionFactory( serviceRegistry.getService( RegionFactory.class ) ); boolean useMinimalPuts = ConfigurationHelper.getBoolean( AvailableSettings.USE_MINIMAL_PUTS, properties, settings.getRegionFactory().isMinimalPutsEnabledByDefault() @@ -437,39 +435,6 @@ public class SettingsFactory implements Serializable { throw new HibernateException( "could not instantiate QueryCacheFactory: " + queryCacheFactoryClassName, e ); } } - - private static RegionFactory createRegionFactory(Properties properties, boolean cachingEnabled, ServiceRegistry serviceRegistry) { - String regionFactoryClassName = RegionFactoryInitiator.mapLegacyNames( - ConfigurationHelper.getString( - AvailableSettings.CACHE_REGION_FACTORY, properties, null - ) - ); - if ( regionFactoryClassName == null || !cachingEnabled) { - regionFactoryClassName = DEF_CACHE_REG_FACTORY; - } - LOG.debugf( "Cache region factory : %s", regionFactoryClassName ); - try { - try { - return (RegionFactory) serviceRegistry.getService( ClassLoaderService.class ) - .classForName( regionFactoryClassName ) - .getConstructor( Properties.class ) - .newInstance( properties ); - } - catch ( NoSuchMethodException e ) { - // no constructor accepting Properties found, try no arg constructor - LOG.debugf( - "%s did not provide constructor accepting java.util.Properties; attempting no-arg constructor.", - regionFactoryClassName - ); - return (RegionFactory) serviceRegistry.getService( ClassLoaderService.class ) - .classForName( regionFactoryClassName ) - .newInstance(); - } - } - catch ( Exception e ) { - throw new HibernateException( "could not instantiate RegionFactory [" + regionFactoryClassName + "]", e ); - } - } //todo remove this once we move to new metamodel public static RegionFactory createRegionFactory(Properties properties, boolean cachingEnabled) { // todo : REMOVE! THIS IS TOTALLY A TEMPORARY HACK FOR org.hibernate.cfg.AnnotationBinder which will be going away diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AbstractEhcacheRegionFactory.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AbstractEhcacheRegionFactory.java index b12a88e188..b935309000 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AbstractEhcacheRegionFactory.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/AbstractEhcacheRegionFactory.java @@ -23,6 +23,7 @@ */ package org.hibernate.cache.ehcache; +import java.net.MalformedURLException; import java.net.URL; import java.util.Properties; @@ -205,6 +206,14 @@ abstract class AbstractEhcacheRegionFactory implements RegionFactory { if ( url == null ) { url = AbstractEhcacheRegionFactory.class.getResource( configurationResourceName ); } + if ( url == null ) { + try { + url = new URL( configurationResourceName ); + } + catch ( MalformedURLException e ) { + // ignore + } + } } if ( LOG.isDebugEnabled() ) { LOG.debugf( diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java index 6b28b6ee25..6dca8d5dae 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java @@ -89,13 +89,7 @@ public class EhCacheRegionFactory extends AbstractEhcacheRegionFactory { manager = new CacheManager( configuration ); } else { - URL url; - try { - url = new URL( configurationResourceName ); - } - catch (MalformedURLException e) { - url = loadResource( configurationResourceName ); - } + URL url = loadResource( configurationResourceName ); final Configuration configuration = HibernateEhcacheUtils.loadAndCorrectConfiguration( url ); manager = new CacheManager( configuration ); } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/StrategyRegistrationProviderImpl.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/StrategyRegistrationProviderImpl.java index 3cedfe4f0a..2c68ca1df8 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/StrategyRegistrationProviderImpl.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/StrategyRegistrationProviderImpl.java @@ -48,6 +48,7 @@ public class StrategyRegistrationProviderImpl implements StrategyRegistrationPro RegionFactory.class, EhCacheRegionFactory.class, "ehcache", + EhCacheRegionFactory.class.getName(), EhCacheRegionFactory.class.getSimpleName(), // legacy impl class name "org.hibernate.cache.EhCacheRegionFactory" @@ -59,6 +60,7 @@ public class StrategyRegistrationProviderImpl implements StrategyRegistrationPro RegionFactory.class, SingletonEhCacheRegionFactory.class, "ehcache-singleton", + SingletonEhCacheRegionFactory.class.getName(), SingletonEhCacheRegionFactory.class.getSimpleName(), // legacy impl class name "org.hibernate.cache.SingletonEhCacheRegionFactory" diff --git a/hibernate-ehcache/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/hibernate-ehcache/src/main/resources/OSGI-INF/blueprint/blueprint.xml new file mode 100644 index 0000000000..fbbb6739e6 --- /dev/null +++ b/hibernate-ehcache/src/main/resources/OSGI-INF/blueprint/blueprint.xml @@ -0,0 +1,10 @@ + + + + + + + + diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java index 3a35625ec0..c1012cb785 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java @@ -1,5 +1,6 @@ package org.hibernate.cache.infinispan; +import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; @@ -388,8 +389,18 @@ public class InfinispanRegionFactory implements RegionFactory { String configLoc = ConfigurationHelper.getString( INFINISPAN_CONFIG_RESOURCE_PROP, properties, DEF_INFINISPAN_CONFIG_RESOURCE); ClassLoader classLoader = ClassLoaderHelper.getContextClassLoader(); - InputStream is = FileLookupFactory.newInstance().lookupFileStrict( - configLoc, classLoader); + InputStream is; + try { + is = FileLookupFactory.newInstance().lookupFileStrict( + configLoc, classLoader); + } + catch ( FileNotFoundException e ) { + // In some environments (ex: OSGi), hibernate-infinispan may not + // be in the app CL. It's important to also try this CL. + classLoader = this.getClass().getClassLoader(); + is = FileLookupFactory.newInstance().lookupFileStrict( + configLoc, classLoader); + } ParserRegistry parserRegistry = new ParserRegistry(classLoader); ConfigurationBuilderHolder holder = parserRegistry.parse(is); diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/StrategyRegistrationProviderImpl.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/StrategyRegistrationProviderImpl.java index 611e0587e5..8197d09ea3 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/StrategyRegistrationProviderImpl.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/StrategyRegistrationProviderImpl.java @@ -47,6 +47,7 @@ public class StrategyRegistrationProviderImpl implements StrategyRegistrationPro RegionFactory.class, InfinispanRegionFactory.class, "infinispan", + InfinispanRegionFactory.class.getName(), InfinispanRegionFactory.class.getSimpleName() ) ); @@ -56,6 +57,7 @@ public class StrategyRegistrationProviderImpl implements StrategyRegistrationPro RegionFactory.class, JndiInfinispanRegionFactory.class, "infinispan-jndi", + JndiInfinispanRegionFactory.class.getName(), JndiInfinispanRegionFactory.class.getSimpleName() ) ); diff --git a/hibernate-infinispan/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.AvailabilityAnnouncer b/hibernate-infinispan/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.AvailabilityAnnouncer deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/hibernate-infinispan/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider b/hibernate-infinispan/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider new file mode 100644 index 0000000000..b59a47b2c6 --- /dev/null +++ b/hibernate-infinispan/src/main/resources/META-INF/services/org.hibernate.boot.registry.selector.StrategyRegistrationProvider @@ -0,0 +1 @@ +org.hibernate.cache.infinispan.StrategyRegistrationProviderImpl \ No newline at end of file diff --git a/hibernate-infinispan/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/hibernate-infinispan/src/main/resources/OSGI-INF/blueprint/blueprint.xml new file mode 100644 index 0000000000..ff3a39ab69 --- /dev/null +++ b/hibernate-infinispan/src/main/resources/OSGI-INF/blueprint/blueprint.xml @@ -0,0 +1,10 @@ + + + + + + + + From 60513d2e2e96445a9090e2dc975e73ef703a52db Mon Sep 17 00:00:00 2001 From: Brett Meyer Date: Wed, 1 May 2013 14:13:22 -0400 Subject: [PATCH 48/57] HHH-7995 Pushing class missed in previous commit --- .../jpa/boot/spi/TypeContributorList.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/TypeContributorList.java diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/TypeContributorList.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/TypeContributorList.java new file mode 100644 index 0000000000..e984c70257 --- /dev/null +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/spi/TypeContributorList.java @@ -0,0 +1,37 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2012, 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.jpa.boot.spi; + +import java.util.List; + +import org.hibernate.metamodel.spi.TypeContributor; + +/** + * @author Brett Meyer + * + * TODO: Not a fan of this name or entry point into EMFBuilderImpl + */ +public interface TypeContributorList { + public List getTypeContributors(); +} From 257d8ee370add4cf228c01229be120ab5648ae2c Mon Sep 17 00:00:00 2001 From: Brett Meyer Date: Wed, 1 May 2013 15:04:16 -0400 Subject: [PATCH 49/57] HHH-7943 Corrected RegionFactoryInitiator for failing inifinispan tests --- .../internal/RegionFactoryInitiator.java | 36 ++++++++++++++----- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java b/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java index 4a934b6ad2..d2f7314f1b 100644 --- a/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java +++ b/hibernate-core/src/main/java/org/hibernate/cache/internal/RegionFactoryInitiator.java @@ -24,7 +24,9 @@ package org.hibernate.cache.internal; import java.util.Map; +import java.util.Properties; +import org.hibernate.HibernateException; import org.hibernate.boot.registry.StandardServiceInitiator; import org.hibernate.boot.registry.selector.spi.StrategySelector; import org.hibernate.cache.spi.RegionFactory; @@ -58,21 +60,39 @@ public class RegionFactoryInitiator implements StandardServiceInitiator regionFactoryClass = registry.getService( StrategySelector.class ) + .selectStrategyImplementor( RegionFactory.class, setting ); + try { + regionFactory = regionFactoryClass.getConstructor( Properties.class ).newInstance( p ); + } + catch ( NoSuchMethodException e ) { + // no constructor accepting Properties found, try no arg constructor + LOG.debugf( + "%s did not provide constructor accepting java.util.Properties; attempting no-arg constructor.", + regionFactoryClass.getSimpleName() ); + regionFactory = regionFactoryClass.getConstructor().newInstance(); + } + } + catch ( Exception e ) { + throw new HibernateException( "could not instantiate RegionFactory [" + setting + "]", e ); + } } LOG.debugf( "Cache region factory : %s", regionFactory.getClass().getName() ); From f83a2013b10a4993a379eb4e50d5acd79c346175 Mon Sep 17 00:00:00 2001 From: Brett Meyer Date: Wed, 1 May 2013 15:34:16 -0400 Subject: [PATCH 50/57] HHH-7943 test fix --- .../cache/infinispan/tm/JBossStandaloneJtaExampleTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/JBossStandaloneJtaExampleTest.java b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/JBossStandaloneJtaExampleTest.java index b0987baad3..e43b8cabe5 100644 --- a/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/JBossStandaloneJtaExampleTest.java +++ b/hibernate-infinispan/src/test/java/org/hibernate/test/cache/infinispan/tm/JBossStandaloneJtaExampleTest.java @@ -252,11 +252,11 @@ public class JBossStandaloneJtaExampleTest { cfg.setProperty(Environment.RELEASE_CONNECTIONS, "auto"); cfg.setProperty(Environment.USE_SECOND_LEVEL_CACHE, "true"); cfg.setProperty(Environment.USE_QUERY_CACHE, "true"); - cfg.setProperty(Environment.CACHE_REGION_FACTORY, - "org.hibernate.test.cache.infinispan.functional.SingleNodeTestCase$TestInfinispanRegionFactory"); Properties envProps = Environment.getProperties(); envProps.put(AvailableSettings.JTA_PLATFORM, new JBossStandAloneJtaPlatform()); + envProps.setProperty(Environment.CACHE_REGION_FACTORY, + "org.hibernate.test.cache.infinispan.functional.SingleNodeTestCase$TestInfinispanRegionFactory"); serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry(envProps); String[] mappings = new String[]{"org/hibernate/test/cache/infinispan/functional/Item.hbm.xml"}; From 1b637030bd53a696cfcadd80d9a7cb3d08d4babb Mon Sep 17 00:00:00 2001 From: Christian Beikov Date: Wed, 1 May 2013 21:25:13 +0200 Subject: [PATCH 51/57] HHH-8215 - Fix for windows build --- .../src/main/groovy/org/hibernate/build/gradle/util/Jdk.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/buildSrc/src/main/groovy/org/hibernate/build/gradle/util/Jdk.java b/buildSrc/src/main/groovy/org/hibernate/build/gradle/util/Jdk.java index 4eb21f61b0..4921414f40 100644 --- a/buildSrc/src/main/groovy/org/hibernate/build/gradle/util/Jdk.java +++ b/buildSrc/src/main/groovy/org/hibernate/build/gradle/util/Jdk.java @@ -129,7 +129,10 @@ public class Jdk { try { final File javaCommand = getJavaExecutable(); - Process javaProcess = Runtime.getRuntime().exec( javaCommand.getAbsolutePath() + " -version" ); + + // Fix build for e.g. windows when path to java command contains spaces + // Using the array for Runtime.exec will make sure that arguments with spaces get quoted + Process javaProcess = Runtime.getRuntime().exec( new String[]{javaCommand.getAbsolutePath(), "-version"} ); try { version = extractVersion( new BufferedReader( new InputStreamReader( javaProcess.getErrorStream() ) ) ); From bfbc0b88a80bf2c4220c077795133f1ebbc7066f Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Wed, 1 May 2013 18:53:55 -0500 Subject: [PATCH 52/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../cache/ehcache/EhCacheRegionFactory.java | 5 +- ...OnlyEhcacheEntityRegionAccessStrategy.java | 29 +- ...riteEhcacheEntityRegionAccessStrategy.java | 2 +- .../infinispan/InfinispanRegionFactory.java | 982 +++++++++--------- .../JndiInfinispanRegionFactory.java | 110 +- .../StrategyRegistrationProviderImpl.java | 6 +- .../cache/infinispan/TypeOverrides.java | 192 ++-- .../access/PutFromLoadValidator.java | 884 ++++++++-------- .../access/TransactionalAccessDelegate.java | 246 ++--- .../cache/infinispan/access/package-info.java | 4 + .../collection/CollectionRegionImpl.java | 54 +- .../collection/TransactionalAccess.java | 108 +- .../infinispan/collection/package-info.java | 4 + .../infinispan/entity/EntityRegionImpl.java | 32 +- .../infinispan/entity/ReadOnlyAccess.java | 39 +- .../entity/TransactionalAccess.java | 136 ++- .../cache/infinispan/entity/package-info.java | 4 + .../impl/BaseGeneralDataRegion.java | 49 +- .../cache/infinispan/impl/BaseRegion.java | 355 ++++--- .../impl/BaseTransactionalDataRegion.java | 49 +- .../cache/infinispan/impl/package-info.java | 4 + .../naturalid/NaturalIdRegionImpl.java | 39 +- .../infinispan/naturalid/ReadOnlyAccess.java | 26 +- .../naturalid/TransactionalAccess.java | 44 +- .../infinispan/naturalid/package-info.java | 4 + .../cache/infinispan/package-info.java | 4 + .../query/QueryResultsRegionImpl.java | 167 +-- .../cache/infinispan/query/package-info.java | 4 + .../ClusteredTimestampsRegionImpl.java | 205 ++-- .../timestamp/TimestampTypeOverrides.java | 22 +- .../timestamp/TimestampsRegionImpl.java | 143 +-- .../infinispan/timestamp/package-info.java | 4 + .../tm/HibernateTransactionManagerLookup.java | 7 +- .../cache/infinispan/tm/package-info.java | 4 + .../util/CacheCommandExtensions.java | 44 +- .../infinispan/util/CacheCommandFactory.java | 93 +- .../infinispan/util/CacheCommandIds.java | 30 +- .../util/CacheCommandInitializer.java | 45 +- .../cache/infinispan/util/Caches.java | 192 ++-- .../infinispan/util/EvictAllCommand.java | 82 +- .../cache/infinispan/util/package-info.java | 4 + 41 files changed, 2528 insertions(+), 1929 deletions(-) create mode 100644 hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/package-info.java create mode 100644 hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/package-info.java create mode 100644 hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/package-info.java create mode 100644 hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/package-info.java create mode 100644 hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/package-info.java create mode 100644 hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/package-info.java create mode 100644 hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/query/package-info.java create mode 100644 hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/package-info.java create mode 100644 hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/tm/package-info.java create mode 100644 hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/package-info.java diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java index 6dca8d5dae..39676cb27e 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/EhCacheRegionFactory.java @@ -23,7 +23,6 @@ */ package org.hibernate.cache.ehcache; -import java.net.MalformedURLException; import java.net.URL; import java.util.Properties; @@ -47,13 +46,11 @@ import org.hibernate.cfg.Settings; * @author Alex Snaps */ public class EhCacheRegionFactory extends AbstractEhcacheRegionFactory { - private static final EhCacheMessageLogger LOG = Logger.getMessageLogger( EhCacheMessageLogger.class, EhCacheRegionFactory.class.getName() ); - /** * Creates a non-singleton EhCacheRegionFactory */ @@ -89,7 +86,7 @@ public class EhCacheRegionFactory extends AbstractEhcacheRegionFactory { manager = new CacheManager( configuration ); } else { - URL url = loadResource( configurationResourceName ); + final URL url = loadResource( configurationResourceName ); final Configuration configuration = HibernateEhcacheUtils.loadAndCorrectConfiguration( url ); manager = new CacheManager( configuration ); } diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheEntityRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheEntityRegionAccessStrategy.java index 6631922159..33ea2d95dd 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheEntityRegionAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadOnlyEhcacheEntityRegionAccessStrategy.java @@ -49,23 +49,17 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc super( region, settings ); } - /** - * {@inheritDoc} - */ + @Override public EntityRegion getRegion() { return region(); } - /** - * {@inheritDoc} - */ + @Override public Object get(Object key, long txTimestamp) throws CacheException { return region().get( key ); } - /** - * {@inheritDoc} - */ + @Override public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { if ( minimalPutOverride && region().contains( key ) ) { @@ -77,47 +71,58 @@ public class ReadOnlyEhcacheEntityRegionAccessStrategy extends AbstractEhcacheAc } } + @Override public SoftLock lockItem(Object key, Object version) throws UnsupportedOperationException { return null; } /** + * {@inheritDoc} + *

      * A no-op since this cache is read-only */ + @Override public void unlockItem(Object key, SoftLock lock) throws CacheException { evict( key ); } /** + * {@inheritDoc} + *

      * This cache is asynchronous hence a no-op */ + @Override public boolean insert(Object key, Object value, Object version) throws CacheException { return false; } - /** - * {@inheritDoc} - */ + @Override public boolean afterInsert(Object key, Object value, Object version) throws CacheException { region().put( key, value ); return true; } /** + * {@inheritDoc} + *

      * Throws UnsupportedOperationException since this cache is read-only * * @throws UnsupportedOperationException always */ + @Override public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) throws UnsupportedOperationException { throw new UnsupportedOperationException( "Can't write to a readonly object" ); } /** + * {@inheritDoc} + *

      * Throws UnsupportedOperationException since this cache is read-only * * @throws UnsupportedOperationException always */ + @Override public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) throws UnsupportedOperationException { throw new UnsupportedOperationException( "Can't write to a readonly object" ); diff --git a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheEntityRegionAccessStrategy.java b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheEntityRegionAccessStrategy.java index 1cf14387f0..bb64495dcf 100644 --- a/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheEntityRegionAccessStrategy.java +++ b/hibernate-ehcache/src/main/java/org/hibernate/cache/ehcache/internal/strategy/ReadWriteEhcacheEntityRegionAccessStrategy.java @@ -115,7 +115,7 @@ public class ReadWriteEhcacheEntityRegionAccessStrategy final Lockable item = (Lockable) region().get( key ); if ( item != null && item.isUnlockable( lock ) ) { - Lock lockItem = (Lock) item; + final Lock lockItem = (Lock) item; if ( lockItem.wasLockedConcurrently() ) { decrementLock( key, lockItem ); return false; diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java index c1012cb785..baf582ec83 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/InfinispanRegionFactory.java @@ -14,6 +14,23 @@ import java.util.Properties; import java.util.Set; import java.util.concurrent.TimeUnit; +import org.infinispan.AdvancedCache; +import org.infinispan.commands.module.ModuleCommandFactory; +import org.infinispan.configuration.cache.CacheMode; +import org.infinispan.configuration.cache.Configuration; +import org.infinispan.configuration.cache.ConfigurationBuilder; +import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; +import org.infinispan.configuration.parsing.ParserRegistry; +import org.infinispan.factories.GlobalComponentRegistry; +import org.infinispan.manager.DefaultCacheManager; +import org.infinispan.manager.EmbeddedCacheManager; +import org.infinispan.transaction.TransactionMode; +import org.infinispan.transaction.lookup.GenericTransactionManagerLookup; +import org.infinispan.util.FileLookupFactory; +import org.infinispan.util.concurrent.IsolationLevel; +import org.infinispan.util.logging.Log; +import org.infinispan.util.logging.LogFactory; + import org.hibernate.cache.CacheException; import org.hibernate.cache.infinispan.collection.CollectionRegionImpl; import org.hibernate.cache.infinispan.entity.EntityRegionImpl; @@ -37,70 +54,54 @@ import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cfg.Settings; import org.hibernate.internal.util.ClassLoaderHelper; import org.hibernate.internal.util.config.ConfigurationHelper; -import org.infinispan.AdvancedCache; -import org.infinispan.commands.module.ModuleCommandFactory; -import org.infinispan.configuration.cache.CacheMode; -import org.infinispan.configuration.cache.Configuration; -import org.infinispan.configuration.cache.ConfigurationBuilder; -import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; -import org.infinispan.configuration.parsing.ParserRegistry; -import org.infinispan.factories.GlobalComponentRegistry; -import org.infinispan.manager.DefaultCacheManager; -import org.infinispan.manager.EmbeddedCacheManager; -import org.infinispan.transaction.TransactionMode; -import org.infinispan.transaction.lookup.GenericTransactionManagerLookup; -import org.infinispan.util.FileLookupFactory; -import org.infinispan.util.concurrent.IsolationLevel; -import org.infinispan.util.logging.Log; -import org.infinispan.util.logging.LogFactory; /** * A {@link RegionFactory} for Infinispan-backed cache * regions. - * + * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ public class InfinispanRegionFactory implements RegionFactory { - private static final Log log = LogFactory.getLog(InfinispanRegionFactory.class); + private static final Log log = LogFactory.getLog( InfinispanRegionFactory.class ); - private static final String PREFIX = "hibernate.cache.infinispan."; + private static final String PREFIX = "hibernate.cache.infinispan."; - private static final String CONFIG_SUFFIX = ".cfg"; + private static final String CONFIG_SUFFIX = ".cfg"; - private static final String STRATEGY_SUFFIX = ".eviction.strategy"; + private static final String STRATEGY_SUFFIX = ".eviction.strategy"; - private static final String WAKE_UP_INTERVAL_SUFFIX = ".eviction.wake_up_interval"; + private static final String WAKE_UP_INTERVAL_SUFFIX = ".eviction.wake_up_interval"; - private static final String MAX_ENTRIES_SUFFIX = ".eviction.max_entries"; + private static final String MAX_ENTRIES_SUFFIX = ".eviction.max_entries"; - private static final String LIFESPAN_SUFFIX = ".expiration.lifespan"; + private static final String LIFESPAN_SUFFIX = ".expiration.lifespan"; - private static final String MAX_IDLE_SUFFIX = ".expiration.max_idle"; + private static final String MAX_IDLE_SUFFIX = ".expiration.max_idle"; // private static final String STATISTICS_SUFFIX = ".statistics"; - /** - * Classpath or filesystem resource containing Infinispan configurations the factory should use. - * - * @see #DEF_INFINISPAN_CONFIG_RESOURCE - */ - public static final String INFINISPAN_CONFIG_RESOURCE_PROP = "hibernate.cache.infinispan.cfg"; + /** + * Classpath or filesystem resource containing Infinispan configurations the factory should use. + * + * @see #DEF_INFINISPAN_CONFIG_RESOURCE + */ + public static final String INFINISPAN_CONFIG_RESOURCE_PROP = "hibernate.cache.infinispan.cfg"; - public static final String INFINISPAN_GLOBAL_STATISTICS_PROP = "hibernate.cache.infinispan.statistics"; + public static final String INFINISPAN_GLOBAL_STATISTICS_PROP = "hibernate.cache.infinispan.statistics"; + + /** + * Property that controls whether Infinispan should interact with the + * transaction manager as a {@link javax.transaction.Synchronization} or as + * an XA resource. If the property is set to true, it will be a + * synchronization, otherwise an XA resource. + * + * @see #DEF_USE_SYNCHRONIZATION + */ + public static final String INFINISPAN_USE_SYNCHRONIZATION_PROP = "hibernate.cache.infinispan.use_synchronization"; - /** - * Property that controls whether Infinispan should interact with the - * transaction manager as a {@link javax.transaction.Synchronization} or as - * an XA resource. If the property is set to true, it will be a - * synchronization, otherwise an XA resource. - * - * @see #DEF_USE_SYNCHRONIZATION - */ - public static final String INFINISPAN_USE_SYNCHRONIZATION_PROP = "hibernate.cache.infinispan.use_synchronization"; - private static final String NATURAL_ID_KEY = "naturalid"; /** @@ -108,505 +109,530 @@ public class InfinispanRegionFactory implements RegionFactory { * * @see #DEF_ENTITY_RESOURCE */ + @SuppressWarnings("UnusedDeclaration") public static final String NATURAL_ID_CACHE_RESOURCE_PROP = PREFIX + NATURAL_ID_KEY + CONFIG_SUFFIX; - private static final String ENTITY_KEY = "entity"; - - /** - * Name of the configuration that should be used for entity caches. - * - * @see #DEF_ENTITY_RESOURCE - */ - public static final String ENTITY_CACHE_RESOURCE_PROP = PREFIX + ENTITY_KEY + CONFIG_SUFFIX; - - private static final String COLLECTION_KEY = "collection"; - - /** - * Name of the configuration that should be used for collection caches. - * No default value, as by default we try to use the same Infinispan cache - * instance we use for entity caching. - * - * @see #ENTITY_CACHE_RESOURCE_PROP - * @see #DEF_ENTITY_RESOURCE - */ - public static final String COLLECTION_CACHE_RESOURCE_PROP = PREFIX + COLLECTION_KEY + CONFIG_SUFFIX; + private static final String ENTITY_KEY = "entity"; - private static final String TIMESTAMPS_KEY = "timestamps"; + /** + * Name of the configuration that should be used for entity caches. + * + * @see #DEF_ENTITY_RESOURCE + */ + public static final String ENTITY_CACHE_RESOURCE_PROP = PREFIX + ENTITY_KEY + CONFIG_SUFFIX; - /** - * Name of the configuration that should be used for timestamp caches. - * - * @see #DEF_TIMESTAMPS_RESOURCE - */ - public static final String TIMESTAMPS_CACHE_RESOURCE_PROP = PREFIX + TIMESTAMPS_KEY + CONFIG_SUFFIX; + private static final String COLLECTION_KEY = "collection"; - private static final String QUERY_KEY = "query"; + /** + * Name of the configuration that should be used for collection caches. + * No default value, as by default we try to use the same Infinispan cache + * instance we use for entity caching. + * + * @see #ENTITY_CACHE_RESOURCE_PROP + * @see #DEF_ENTITY_RESOURCE + */ + @SuppressWarnings("UnusedDeclaration") + public static final String COLLECTION_CACHE_RESOURCE_PROP = PREFIX + COLLECTION_KEY + CONFIG_SUFFIX; - /** - * Name of the configuration that should be used for query caches. - * - * @see #DEF_QUERY_RESOURCE - */ - public static final String QUERY_CACHE_RESOURCE_PROP = PREFIX + QUERY_KEY + CONFIG_SUFFIX; + private static final String TIMESTAMPS_KEY = "timestamps"; - /** - * Default value for {@link #INFINISPAN_CONFIG_RESOURCE_PROP}. Specifies the "infinispan-configs.xml" file in this package. - */ - public static final String DEF_INFINISPAN_CONFIG_RESOURCE = "org/hibernate/cache/infinispan/builder/infinispan-configs.xml"; + /** + * Name of the configuration that should be used for timestamp caches. + * + * @see #DEF_TIMESTAMPS_RESOURCE + */ + @SuppressWarnings("UnusedDeclaration") + public static final String TIMESTAMPS_CACHE_RESOURCE_PROP = PREFIX + TIMESTAMPS_KEY + CONFIG_SUFFIX; - /** - * Default value for {@link #ENTITY_CACHE_RESOURCE_PROP}. - */ - public static final String DEF_ENTITY_RESOURCE = "entity"; + private static final String QUERY_KEY = "query"; - /** - * Default value for {@link #TIMESTAMPS_CACHE_RESOURCE_PROP}. - */ - public static final String DEF_TIMESTAMPS_RESOURCE = "timestamps"; + /** + * Name of the configuration that should be used for query caches. + * + * @see #DEF_QUERY_RESOURCE + */ + public static final String QUERY_CACHE_RESOURCE_PROP = PREFIX + QUERY_KEY + CONFIG_SUFFIX; - /** - * Default value for {@link #QUERY_CACHE_RESOURCE_PROP}. - */ - public static final String DEF_QUERY_RESOURCE = "local-query"; + /** + * Default value for {@link #INFINISPAN_CONFIG_RESOURCE_PROP}. Specifies the "infinispan-configs.xml" file in this package. + */ + public static final String DEF_INFINISPAN_CONFIG_RESOURCE = "org/hibernate/cache/infinispan/builder/infinispan-configs.xml"; - /** - * Default value for {@link #INFINISPAN_USE_SYNCHRONIZATION_PROP}. - */ - public static final boolean DEF_USE_SYNCHRONIZATION = true; + /** + * Default value for {@link #ENTITY_CACHE_RESOURCE_PROP}. + */ + public static final String DEF_ENTITY_RESOURCE = "entity"; - /** - * Name of the pending puts cache. - */ - public static final String PENDING_PUTS_CACHE_NAME = "pending-puts"; + /** + * Default value for {@link #TIMESTAMPS_CACHE_RESOURCE_PROP}. + */ + public static final String DEF_TIMESTAMPS_RESOURCE = "timestamps"; - private EmbeddedCacheManager manager; + /** + * Default value for {@link #QUERY_CACHE_RESOURCE_PROP}. + */ + public static final String DEF_QUERY_RESOURCE = "local-query"; - private final Map typeOverrides = new HashMap(); + /** + * Default value for {@link #INFINISPAN_USE_SYNCHRONIZATION_PROP}. + */ + public static final boolean DEF_USE_SYNCHRONIZATION = true; - private final Set definedConfigurations = new HashSet(); + /** + * Name of the pending puts cache. + */ + public static final String PENDING_PUTS_CACHE_NAME = "pending-puts"; - private org.infinispan.transaction.lookup.TransactionManagerLookup transactionManagerlookup; + private EmbeddedCacheManager manager; - private List regionNames = new ArrayList(); - - /** - * Create a new instance using the default configuration. - */ - public InfinispanRegionFactory() { - } + private final Map typeOverrides = new HashMap(); - /** - * Create a new instance using conifguration properties in props. - * - * @param props - * Environmental properties; currently unused. - */ - public InfinispanRegionFactory(Properties props) { - } + private final Set definedConfigurations = new HashSet(); - /** {@inheritDoc} */ - public CollectionRegion buildCollectionRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException { - if (log.isDebugEnabled()) log.debug("Building collection cache region [" + regionName + "]"); - AdvancedCache cache = getCache(regionName, COLLECTION_KEY, properties); - CollectionRegionImpl region = new CollectionRegionImpl( - cache, regionName, metadata, this); - startRegion(region, regionName); - return region; - } + private org.infinispan.transaction.lookup.TransactionManagerLookup transactionManagerlookup; - /** {@inheritDoc} */ - public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException { - if (log.isDebugEnabled()) log.debug("Building entity cache region [" + regionName + "]"); - AdvancedCache cache = getCache(regionName, ENTITY_KEY, properties); - EntityRegionImpl region = new EntityRegionImpl( - cache, regionName, metadata, this); - startRegion(region, regionName); - return region; - } + private List regionNames = new ArrayList(); + + /** + * Create a new instance using the default configuration. + */ + public InfinispanRegionFactory() { + } + + /** + * Create a new instance using conifguration properties in props. + * + * @param props Environmental properties; currently unused. + */ + @SuppressWarnings("UnusedParameters") + public InfinispanRegionFactory(Properties props) { + } + + @Override + public CollectionRegion buildCollectionRegion( + String regionName, + Properties properties, + CacheDataDescription metadata) throws CacheException { + if ( log.isDebugEnabled() ) { + log.debug( "Building collection cache region [" + regionName + "]" ); + } + final AdvancedCache cache = getCache( regionName, COLLECTION_KEY, properties ); + final CollectionRegionImpl region = new CollectionRegionImpl( cache, regionName, metadata, this ); + startRegion( region, regionName ); + return region; + } + + @Override + public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata) + throws CacheException { + if ( log.isDebugEnabled() ) { + log.debug( "Building entity cache region [" + regionName + "]" ); + } + final AdvancedCache cache = getCache( regionName, ENTITY_KEY, properties ); + final EntityRegionImpl region = new EntityRegionImpl( cache, regionName, metadata, this ); + startRegion( region, regionName ); + return region; + } @Override public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException { - if (log.isDebugEnabled()) { - log.debug("Building natural id cache region [" + regionName + "]"); + if ( log.isDebugEnabled() ) { + log.debug( "Building natural id cache region [" + regionName + "]" ); } - AdvancedCache cache = getCache(regionName, NATURAL_ID_KEY, properties); - NaturalIdRegionImpl region = new NaturalIdRegionImpl( - cache, regionName, metadata, this); - startRegion(region, regionName); + final AdvancedCache cache = getCache( regionName, NATURAL_ID_KEY, properties ); + final NaturalIdRegionImpl region = new NaturalIdRegionImpl( cache, regionName, metadata, this ); + startRegion( region, regionName ); return region; } - - /** - * {@inheritDoc} - */ - public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) - throws CacheException { - if (log.isDebugEnabled()) log.debug("Building query results cache region [" + regionName + "]"); - String cacheName = typeOverrides.get(QUERY_KEY).getCacheName(); - // If region name is not default one, lookup a cache for that region name - if (!regionName.equals("org.hibernate.cache.internal.StandardQueryCache")) - cacheName = regionName; - AdvancedCache cache = getCache(cacheName, QUERY_KEY, properties); - QueryResultsRegionImpl region = new QueryResultsRegionImpl( - cache, regionName, this); - startRegion(region, regionName); - return region; - } + @Override + public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) + throws CacheException { + if ( log.isDebugEnabled() ) { + log.debug( "Building query results cache region [" + regionName + "]" ); + } + String cacheName = typeOverrides.get( QUERY_KEY ).getCacheName(); + // If region name is not default one, lookup a cache for that region name + if ( !regionName.equals( "org.hibernate.cache.internal.StandardQueryCache" ) ) { + cacheName = regionName; + } - /** - * {@inheritDoc} - */ - public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) - throws CacheException { - if (log.isDebugEnabled()) log.debug("Building timestamps cache region [" + regionName + "]"); - AdvancedCache cache = getCache(regionName, TIMESTAMPS_KEY, properties); - TimestampsRegionImpl region = createTimestampsRegion(cache, regionName); - startRegion(region, regionName); - return region; - } + final AdvancedCache cache = getCache( cacheName, QUERY_KEY, properties ); + final QueryResultsRegionImpl region = new QueryResultsRegionImpl( cache, regionName, this ); + startRegion( region, regionName ); + return region; + } - protected TimestampsRegionImpl createTimestampsRegion( - AdvancedCache cache, String regionName) { - if (Caches.isClustered(cache)) - return new ClusteredTimestampsRegionImpl(cache, regionName, this); - else - return new TimestampsRegionImpl(cache, regionName, this); - } + @Override + public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) + throws CacheException { + if ( log.isDebugEnabled() ) { + log.debug( "Building timestamps cache region [" + regionName + "]" ); + } + final AdvancedCache cache = getCache( regionName, TIMESTAMPS_KEY, properties ); + final TimestampsRegionImpl region = createTimestampsRegion( cache, regionName ); + startRegion( region, regionName ); + return region; + } - /** - * {@inheritDoc} - */ - public boolean isMinimalPutsEnabledByDefault() { - return true; - } + protected TimestampsRegionImpl createTimestampsRegion( + AdvancedCache cache, String regionName) { + if ( Caches.isClustered( cache ) ) { + return new ClusteredTimestampsRegionImpl( cache, regionName, this ); + } + else { + return new TimestampsRegionImpl( cache, regionName, this ); + } + } - @Override - public AccessType getDefaultAccessType() { - return AccessType.TRANSACTIONAL; - } + @Override + public boolean isMinimalPutsEnabledByDefault() { + return true; + } - /** - * {@inheritDoc} - */ - public long nextTimestamp() { - return System.currentTimeMillis() / 100; - } - - public void setCacheManager(EmbeddedCacheManager manager) { - this.manager = manager; - } + @Override + public AccessType getDefaultAccessType() { + return AccessType.TRANSACTIONAL; + } - public EmbeddedCacheManager getCacheManager() { - return manager; - } + @Override + public long nextTimestamp() { + return System.currentTimeMillis() / 100; + } - /** - * {@inheritDoc} - */ - public void start(Settings settings, Properties properties) throws CacheException { - log.debug("Starting Infinispan region factory"); - try { - transactionManagerlookup = createTransactionManagerLookup(settings, properties); - manager = createCacheManager(properties); - initGenericDataTypeOverrides(); - Enumeration keys = properties.propertyNames(); - while (keys.hasMoreElements()) { - String key = (String) keys.nextElement(); - int prefixLoc; - if ((prefixLoc = key.indexOf(PREFIX)) != -1) { - dissectProperty(prefixLoc, key, properties); - } - } - defineGenericDataTypeCacheConfigurations(properties); - definePendingPutsCache(); - } catch (CacheException ce) { - throw ce; - } catch (Throwable t) { - throw new CacheException("Unable to start region factory", t); - } - } + public void setCacheManager(EmbeddedCacheManager manager) { + this.manager = manager; + } - private void definePendingPutsCache() { - ConfigurationBuilder builder = new ConfigurationBuilder(); - // A local, lightweight cache for pending puts, which is - // non-transactional and has aggressive expiration settings. - // Locking is still required since the putFromLoad validator - // code uses conditional operations (i.e. putIfAbsent). - builder.clustering().cacheMode(CacheMode.LOCAL) - .transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL) - .expiration().maxIdle(TimeUnit.SECONDS.toMillis(60)) - .storeAsBinary().enabled(false) - .locking().isolationLevel(IsolationLevel.READ_COMMITTED) - .jmxStatistics().disable(); + public EmbeddedCacheManager getCacheManager() { + return manager; + } - manager.defineConfiguration(PENDING_PUTS_CACHE_NAME, builder.build()); - } + @Override + public void start(Settings settings, Properties properties) throws CacheException { + log.debug( "Starting Infinispan region factory" ); + try { + transactionManagerlookup = createTransactionManagerLookup( settings, properties ); + manager = createCacheManager( properties ); + initGenericDataTypeOverrides(); + final Enumeration keys = properties.propertyNames(); + while ( keys.hasMoreElements() ) { + final String key = (String) keys.nextElement(); + int prefixLoc; + if ( (prefixLoc = key.indexOf( PREFIX )) != -1 ) { + dissectProperty( prefixLoc, key, properties ); + } + } + defineGenericDataTypeCacheConfigurations( properties ); + definePendingPutsCache(); + } + catch (CacheException ce) { + throw ce; + } + catch (Throwable t) { + throw new CacheException( "Unable to start region factory", t ); + } + } - protected org.infinispan.transaction.lookup.TransactionManagerLookup createTransactionManagerLookup( - Settings settings, Properties properties) { - return new HibernateTransactionManagerLookup(settings, properties); - } + private void definePendingPutsCache() { + final ConfigurationBuilder builder = new ConfigurationBuilder(); + // A local, lightweight cache for pending puts, which is + // non-transactional and has aggressive expiration settings. + // Locking is still required since the putFromLoad validator + // code uses conditional operations (i.e. putIfAbsent). + builder.clustering().cacheMode( CacheMode.LOCAL ) + .transaction().transactionMode( TransactionMode.NON_TRANSACTIONAL ) + .expiration().maxIdle( TimeUnit.SECONDS.toMillis( 60 ) ) + .storeAsBinary().enabled( false ) + .locking().isolationLevel( IsolationLevel.READ_COMMITTED ) + .jmxStatistics().disable(); - /** - * {@inheritDoc} - */ - public void stop() { - log.debug("Stop region factory"); - stopCacheRegions(); - stopCacheManager(); - } + manager.defineConfiguration( PENDING_PUTS_CACHE_NAME, builder.build() ); + } - protected void stopCacheRegions() { - log.debug("Clear region references"); - getCacheCommandFactory(manager.getCache().getAdvancedCache()) - .clearRegions(regionNames); - regionNames.clear(); - } + protected org.infinispan.transaction.lookup.TransactionManagerLookup createTransactionManagerLookup( + Settings settings, Properties properties) { + return new HibernateTransactionManagerLookup( settings, properties ); + } - protected void stopCacheManager() { - log.debug("Stop cache manager"); - manager.stop(); - } - - /** - * Returns an unmodifiable map containing configured entity/collection type configuration overrides. - * This method should be used primarily for testing/checking purpouses. - * - * @return an unmodifiable map. - */ - public Map getTypeOverrides() { - return Collections.unmodifiableMap(typeOverrides); - } - - public Set getDefinedConfigurations() { - return Collections.unmodifiableSet(definedConfigurations); - } + @Override + public void stop() { + log.debug( "Stop region factory" ); + stopCacheRegions(); + stopCacheManager(); + } - protected EmbeddedCacheManager createCacheManager(Properties properties) throws CacheException { - try { - String configLoc = ConfigurationHelper.getString( - INFINISPAN_CONFIG_RESOURCE_PROP, properties, DEF_INFINISPAN_CONFIG_RESOURCE); - ClassLoader classLoader = ClassLoaderHelper.getContextClassLoader(); - InputStream is; - try { - is = FileLookupFactory.newInstance().lookupFileStrict( - configLoc, classLoader); - } - catch ( FileNotFoundException e ) { - // In some environments (ex: OSGi), hibernate-infinispan may not - // be in the app CL. It's important to also try this CL. - classLoader = this.getClass().getClassLoader(); - is = FileLookupFactory.newInstance().lookupFileStrict( - configLoc, classLoader); - } - ParserRegistry parserRegistry = new ParserRegistry(classLoader); - ConfigurationBuilderHolder holder = parserRegistry.parse(is); + protected void stopCacheRegions() { + log.debug( "Clear region references" ); + getCacheCommandFactory( manager.getCache().getAdvancedCache() ) + .clearRegions( regionNames ); + regionNames.clear(); + } - // Override global jmx statistics exposure - String globalStats = extractProperty( - INFINISPAN_GLOBAL_STATISTICS_PROP, properties); - if (globalStats != null) - holder.getGlobalConfigurationBuilder().globalJmxStatistics() - .enabled(Boolean.parseBoolean(globalStats)); + protected void stopCacheManager() { + log.debug( "Stop cache manager" ); + manager.stop(); + } - return createCacheManager(holder); - } catch (IOException e) { - throw new CacheException("Unable to create default cache manager", e); - } - } + /** + * Returns an unmodifiable map containing configured entity/collection type configuration overrides. + * This method should be used primarily for testing/checking purpouses. + * + * @return an unmodifiable map. + */ + public Map getTypeOverrides() { + return Collections.unmodifiableMap( typeOverrides ); + } - protected EmbeddedCacheManager createCacheManager( - ConfigurationBuilderHolder holder) { - return new DefaultCacheManager(holder, true); - } + public Set getDefinedConfigurations() { + return Collections.unmodifiableSet( definedConfigurations ); + } - private void startRegion(BaseRegion region, String regionName) { - regionNames.add(regionName); - getCacheCommandFactory(region.getCache()).addRegion(regionName, region); - } + protected EmbeddedCacheManager createCacheManager(Properties properties) throws CacheException { + try { + final String configLoc = ConfigurationHelper.getString( + INFINISPAN_CONFIG_RESOURCE_PROP, properties, DEF_INFINISPAN_CONFIG_RESOURCE + ); + ClassLoader classLoader = ClassLoaderHelper.getContextClassLoader(); + InputStream is; + try { + is = FileLookupFactory.newInstance().lookupFileStrict( configLoc, classLoader ); + } + catch (FileNotFoundException e) { + // In some environments (ex: OSGi), hibernate-infinispan may not + // be in the app CL. It's important to also try this CL. + classLoader = this.getClass().getClassLoader(); + is = FileLookupFactory.newInstance().lookupFileStrict( configLoc, classLoader ); + } + final ParserRegistry parserRegistry = new ParserRegistry( classLoader ); + final ConfigurationBuilderHolder holder = parserRegistry.parse( is ); - private Map initGenericDataTypeOverrides() { - TypeOverrides entityOverrides = new TypeOverrides(); - entityOverrides.setCacheName(DEF_ENTITY_RESOURCE); - typeOverrides.put(ENTITY_KEY, entityOverrides); - TypeOverrides collectionOverrides = new TypeOverrides(); - collectionOverrides.setCacheName(DEF_ENTITY_RESOURCE); - typeOverrides.put(COLLECTION_KEY, collectionOverrides); - TypeOverrides naturalIdOverrides = new TypeOverrides(); - naturalIdOverrides.setCacheName(DEF_ENTITY_RESOURCE); - typeOverrides.put(NATURAL_ID_KEY, naturalIdOverrides); - TypeOverrides timestampOverrides = new TimestampTypeOverrides(); - timestampOverrides.setCacheName(DEF_TIMESTAMPS_RESOURCE); - typeOverrides.put(TIMESTAMPS_KEY, timestampOverrides); - TypeOverrides queryOverrides = new TypeOverrides(); - queryOverrides.setCacheName(DEF_QUERY_RESOURCE); - typeOverrides.put(QUERY_KEY, queryOverrides); - return typeOverrides; - } + // Override global jmx statistics exposure + final String globalStats = extractProperty( INFINISPAN_GLOBAL_STATISTICS_PROP, properties ); + if ( globalStats != null ) { + holder.getGlobalConfigurationBuilder().globalJmxStatistics() + .enabled( Boolean.parseBoolean( globalStats ) ); + } - private void dissectProperty(int prefixLoc, String key, Properties properties) { - TypeOverrides cfgOverride; - int suffixLoc; - if (!key.equals(INFINISPAN_CONFIG_RESOURCE_PROP) && (suffixLoc = key.indexOf(CONFIG_SUFFIX)) != -1) { - cfgOverride = getOrCreateConfig(prefixLoc, key, suffixLoc); - cfgOverride.setCacheName(extractProperty(key, properties)); - } else if ((suffixLoc = key.indexOf(STRATEGY_SUFFIX)) != -1) { - cfgOverride = getOrCreateConfig(prefixLoc, key, suffixLoc); - cfgOverride.setEvictionStrategy(extractProperty(key, properties)); - } else if ((suffixLoc = key.indexOf(WAKE_UP_INTERVAL_SUFFIX)) != -1) { - cfgOverride = getOrCreateConfig(prefixLoc, key, suffixLoc); - cfgOverride.setEvictionWakeUpInterval(Long.parseLong(extractProperty(key, properties))); - } else if ((suffixLoc = key.indexOf(MAX_ENTRIES_SUFFIX)) != -1) { - cfgOverride = getOrCreateConfig(prefixLoc, key, suffixLoc); - cfgOverride.setEvictionMaxEntries(Integer.parseInt(extractProperty(key, properties))); - } else if ((suffixLoc = key.indexOf(LIFESPAN_SUFFIX)) != -1) { - cfgOverride = getOrCreateConfig(prefixLoc, key, suffixLoc); - cfgOverride.setExpirationLifespan(Long.parseLong(extractProperty(key, properties))); - } else if ((suffixLoc = key.indexOf(MAX_IDLE_SUFFIX)) != -1) { - cfgOverride = getOrCreateConfig(prefixLoc, key, suffixLoc); - cfgOverride.setExpirationMaxIdle(Long.parseLong(extractProperty(key, properties))); - } - } + return createCacheManager( holder ); + } + catch (IOException e) { + throw new CacheException( "Unable to create default cache manager", e ); + } + } - private String extractProperty(String key, Properties properties) { - String value = ConfigurationHelper.extractPropertyValue(key, properties); - log.debugf("Configuration override via property %s: %s", key, value); - return value; - } + protected EmbeddedCacheManager createCacheManager( + ConfigurationBuilderHolder holder) { + return new DefaultCacheManager( holder, true ); + } - private TypeOverrides getOrCreateConfig(int prefixLoc, String key, int suffixLoc) { - String name = key.substring(prefixLoc + PREFIX.length(), suffixLoc); - TypeOverrides cfgOverride = typeOverrides.get(name); - if (cfgOverride == null) { - cfgOverride = new TypeOverrides(); - typeOverrides.put(name, cfgOverride); - } - return cfgOverride; - } + private void startRegion(BaseRegion region, String regionName) { + regionNames.add( regionName ); + getCacheCommandFactory( region.getCache() ).addRegion( regionName, region ); + } - private void defineGenericDataTypeCacheConfigurations(Properties properties) { - String[] defaultGenericDataTypes = new String[]{ENTITY_KEY, COLLECTION_KEY, TIMESTAMPS_KEY, QUERY_KEY}; - for (String type : defaultGenericDataTypes) { - TypeOverrides override = overrideStatisticsIfPresent(typeOverrides.get(type), properties); - String cacheName = override.getCacheName(); - ConfigurationBuilder builder = new ConfigurationBuilder(); - // Read base configuration - applyConfiguration(cacheName, builder); + private Map initGenericDataTypeOverrides() { + final TypeOverrides entityOverrides = new TypeOverrides(); + entityOverrides.setCacheName( DEF_ENTITY_RESOURCE ); + typeOverrides.put( ENTITY_KEY, entityOverrides ); + final TypeOverrides collectionOverrides = new TypeOverrides(); + collectionOverrides.setCacheName( DEF_ENTITY_RESOURCE ); + typeOverrides.put( COLLECTION_KEY, collectionOverrides ); + final TypeOverrides naturalIdOverrides = new TypeOverrides(); + naturalIdOverrides.setCacheName( DEF_ENTITY_RESOURCE ); + typeOverrides.put( NATURAL_ID_KEY, naturalIdOverrides ); + final TypeOverrides timestampOverrides = new TimestampTypeOverrides(); + timestampOverrides.setCacheName( DEF_TIMESTAMPS_RESOURCE ); + typeOverrides.put( TIMESTAMPS_KEY, timestampOverrides ); + final TypeOverrides queryOverrides = new TypeOverrides(); + queryOverrides.setCacheName( DEF_QUERY_RESOURCE ); + typeOverrides.put( QUERY_KEY, queryOverrides ); + return typeOverrides; + } - // Apply overrides - override.applyTo(builder); - // Configure transaction manager - configureTransactionManager(builder, cacheName, properties); - // Define configuration, validate and then apply - Configuration cfg = builder.build(); - override.validateInfinispanConfiguration(cfg); - manager.defineConfiguration(cacheName, cfg); - definedConfigurations.add(cacheName); - } - } + private void dissectProperty(int prefixLoc, String key, Properties properties) { + final TypeOverrides cfgOverride; + int suffixLoc; + if ( !key.equals( INFINISPAN_CONFIG_RESOURCE_PROP ) && (suffixLoc = key.indexOf( CONFIG_SUFFIX )) != -1 ) { + cfgOverride = getOrCreateConfig( prefixLoc, key, suffixLoc ); + cfgOverride.setCacheName( extractProperty( key, properties ) ); + } + else if ( (suffixLoc = key.indexOf( STRATEGY_SUFFIX )) != -1 ) { + cfgOverride = getOrCreateConfig( prefixLoc, key, suffixLoc ); + cfgOverride.setEvictionStrategy( extractProperty( key, properties ) ); + } + else if ( (suffixLoc = key.indexOf( WAKE_UP_INTERVAL_SUFFIX )) != -1 ) { + cfgOverride = getOrCreateConfig( prefixLoc, key, suffixLoc ); + cfgOverride.setEvictionWakeUpInterval( Long.parseLong( extractProperty( key, properties ) ) ); + } + else if ( (suffixLoc = key.indexOf( MAX_ENTRIES_SUFFIX )) != -1 ) { + cfgOverride = getOrCreateConfig( prefixLoc, key, suffixLoc ); + cfgOverride.setEvictionMaxEntries( Integer.parseInt( extractProperty( key, properties ) ) ); + } + else if ( (suffixLoc = key.indexOf( LIFESPAN_SUFFIX )) != -1 ) { + cfgOverride = getOrCreateConfig( prefixLoc, key, suffixLoc ); + cfgOverride.setExpirationLifespan( Long.parseLong( extractProperty( key, properties ) ) ); + } + else if ( (suffixLoc = key.indexOf( MAX_IDLE_SUFFIX )) != -1 ) { + cfgOverride = getOrCreateConfig( prefixLoc, key, suffixLoc ); + cfgOverride.setExpirationMaxIdle( Long.parseLong( extractProperty( key, properties ) ) ); + } + } - private AdvancedCache getCache(String regionName, String typeKey, Properties properties) { - TypeOverrides regionOverride = typeOverrides.get(regionName); - if (!definedConfigurations.contains(regionName)) { - String templateCacheName; - Configuration regionCacheCfg; - ConfigurationBuilder builder = new ConfigurationBuilder(); - if (regionOverride != null) { - if (log.isDebugEnabled()) log.debug("Cache region specific configuration exists: " + regionOverride); - String cacheName = regionOverride.getCacheName(); - if (cacheName != null) // Region specific override with a given cache name - templateCacheName = cacheName; - else // Region specific override without cache name, so template cache name is generic for data type. - templateCacheName = typeOverrides.get(typeKey).getCacheName(); + private String extractProperty(String key, Properties properties) { + final String value = ConfigurationHelper.extractPropertyValue( key, properties ); + log.debugf( "Configuration override via property %s: %s", key, value ); + return value; + } - // Read template configuration - applyConfiguration(templateCacheName, builder); + private TypeOverrides getOrCreateConfig(int prefixLoc, String key, int suffixLoc) { + final String name = key.substring( prefixLoc + PREFIX.length(), suffixLoc ); + TypeOverrides cfgOverride = typeOverrides.get( name ); + if ( cfgOverride == null ) { + cfgOverride = new TypeOverrides(); + typeOverrides.put( name, cfgOverride ); + } + return cfgOverride; + } - regionOverride = overrideStatisticsIfPresent(regionOverride, properties); - regionOverride.applyTo(builder); + private void defineGenericDataTypeCacheConfigurations(Properties properties) { + final String[] defaultGenericDataTypes = new String[] {ENTITY_KEY, COLLECTION_KEY, TIMESTAMPS_KEY, QUERY_KEY}; + for ( String type : defaultGenericDataTypes ) { + final TypeOverrides override = overrideStatisticsIfPresent( typeOverrides.get( type ), properties ); + final String cacheName = override.getCacheName(); + final ConfigurationBuilder builder = new ConfigurationBuilder(); + // Read base configuration + applyConfiguration( cacheName, builder ); - } else { - // No region specific overrides, template cache name is generic for data type. - templateCacheName = typeOverrides.get(typeKey).getCacheName(); - // Read template configuration - builder.read(manager.getCacheConfiguration(templateCacheName)); - // Apply overrides - typeOverrides.get(typeKey).applyTo(builder); - } - // Configure transaction manager - configureTransactionManager(builder, templateCacheName, properties); - // Define configuration - manager.defineConfiguration(regionName, builder.build()); - definedConfigurations.add(regionName); - } - AdvancedCache cache = manager.getCache(regionName).getAdvancedCache(); - if (!cache.getStatus().allowInvocations()) { - cache.start(); - } - return createCacheWrapper(cache); - } + // Apply overrides + override.applyTo( builder ); + // Configure transaction manager + configureTransactionManager( builder, cacheName, properties ); + // Define configuration, validate and then apply + final Configuration cfg = builder.build(); + override.validateInfinispanConfiguration( cfg ); + manager.defineConfiguration( cacheName, cfg ); + definedConfigurations.add( cacheName ); + } + } - private void applyConfiguration(String cacheName, ConfigurationBuilder builder) { - Configuration cfg = manager.getCacheConfiguration(cacheName); - if (cfg != null) - builder.read(cfg); - } + private AdvancedCache getCache(String regionName, String typeKey, Properties properties) { + TypeOverrides regionOverride = typeOverrides.get( regionName ); + if ( !definedConfigurations.contains( regionName ) ) { + final String templateCacheName; + final ConfigurationBuilder builder = new ConfigurationBuilder(); + if ( regionOverride != null ) { + if ( log.isDebugEnabled() ) { + log.debug( "Cache region specific configuration exists: " + regionOverride ); + } + final String cacheName = regionOverride.getCacheName(); + if ( cacheName != null ) { + // Region specific override with a given cache name + templateCacheName = cacheName; + } + else { + // Region specific override without cache name, so template cache name is generic for data type. + templateCacheName = typeOverrides.get( typeKey ).getCacheName(); + } - private CacheCommandFactory getCacheCommandFactory(AdvancedCache cache) { - GlobalComponentRegistry globalCr = cache.getComponentRegistry() - .getGlobalComponentRegistry(); + // Read template configuration + applyConfiguration( templateCacheName, builder ); - Map factories = - (Map) globalCr - .getComponent("org.infinispan.modules.command.factories"); + regionOverride = overrideStatisticsIfPresent( regionOverride, properties ); + regionOverride.applyTo( builder ); - for (ModuleCommandFactory factory : factories.values()) { - if (factory instanceof CacheCommandFactory) - return (CacheCommandFactory) factory; - } + } + else { + // No region specific overrides, template cache name is generic for data type. + templateCacheName = typeOverrides.get( typeKey ).getCacheName(); + // Read template configuration + builder.read( manager.getCacheConfiguration( templateCacheName ) ); + // Apply overrides + typeOverrides.get( typeKey ).applyTo( builder ); + } + // Configure transaction manager + configureTransactionManager( builder, templateCacheName, properties ); + // Define configuration + manager.defineConfiguration( regionName, builder.build() ); + definedConfigurations.add( regionName ); + } + final AdvancedCache cache = manager.getCache( regionName ).getAdvancedCache(); + if ( !cache.getStatus().allowInvocations() ) { + cache.start(); + } + return createCacheWrapper( cache ); + } - throw new CacheException("Infinispan custom cache command factory not " + - "installed (possibly because the classloader where Infinispan " + - "lives couldn't find the Hibernate Infinispan cache provider)"); - } + private void applyConfiguration(String cacheName, ConfigurationBuilder builder) { + final Configuration cfg = manager.getCacheConfiguration( cacheName ); + if ( cfg != null ) { + builder.read( cfg ); + } + } - protected AdvancedCache createCacheWrapper(AdvancedCache cache) { - return cache; - } + private CacheCommandFactory getCacheCommandFactory(AdvancedCache cache) { + final GlobalComponentRegistry globalCr = cache.getComponentRegistry().getGlobalComponentRegistry(); - private void configureTransactionManager(ConfigurationBuilder builder, - String cacheName, Properties properties) { - // Get existing configuration to verify whether a tm was configured or not. - Configuration baseCfg = manager.getCacheConfiguration(cacheName); - if (baseCfg != null && baseCfg.transaction().transactionMode().isTransactional()) { - String ispnTmLookupClassName = baseCfg.transaction().transactionManagerLookup().getClass().getName(); - String hbTmLookupClassName = org.hibernate.cache.infinispan.tm.HibernateTransactionManagerLookup.class.getName(); - if (GenericTransactionManagerLookup.class.getName().equals(ispnTmLookupClassName)) { - log.debug("Using default Infinispan transaction manager lookup " + - "instance (GenericTransactionManagerLookup), overriding it " + - "with Hibernate transaction manager lookup"); - builder.transaction().transactionManagerLookup(transactionManagerlookup); - } else if (ispnTmLookupClassName != null && !ispnTmLookupClassName.equals(hbTmLookupClassName)) { - log.debug("Infinispan is configured [" + ispnTmLookupClassName + "] with a different transaction manager lookup " + - "class than Hibernate [" + hbTmLookupClassName + "]"); - } else { - // Infinispan TM lookup class null, so apply Hibernate one directly - builder.transaction().transactionManagerLookup(transactionManagerlookup); - } + final Map factories = + (Map) globalCr.getComponent( "org.infinispan.modules.command.factories" ); - String useSyncProp = extractProperty(INFINISPAN_USE_SYNCHRONIZATION_PROP, properties); - boolean useSync = useSyncProp == null ? DEF_USE_SYNCHRONIZATION : Boolean.parseBoolean(useSyncProp); - builder.transaction().useSynchronization(useSync); - } - } + for ( ModuleCommandFactory factory : factories.values() ) { + if ( factory instanceof CacheCommandFactory ) { + return (CacheCommandFactory) factory; + } + } - private TypeOverrides overrideStatisticsIfPresent(TypeOverrides override, Properties properties) { - String globalStats = extractProperty(INFINISPAN_GLOBAL_STATISTICS_PROP, properties); - if (globalStats != null) { - override.setExposeStatistics(Boolean.parseBoolean(globalStats)); - } - return override; - } + throw new CacheException( + "Infinispan custom cache command factory not " + + "installed (possibly because the classloader where Infinispan " + + "lives couldn't find the Hibernate Infinispan cache provider)" + ); + } + + protected AdvancedCache createCacheWrapper(AdvancedCache cache) { + return cache; + } + + private void configureTransactionManager( + ConfigurationBuilder builder, + String cacheName, + Properties properties) { + // Get existing configuration to verify whether a tm was configured or not. + final Configuration baseCfg = manager.getCacheConfiguration( cacheName ); + if ( baseCfg != null && baseCfg.transaction().transactionMode().isTransactional() ) { + final String ispnTmLookupClassName = baseCfg.transaction().transactionManagerLookup().getClass().getName(); + final String hbTmLookupClassName = org.hibernate.cache.infinispan.tm.HibernateTransactionManagerLookup.class.getName(); + if ( GenericTransactionManagerLookup.class.getName().equals( ispnTmLookupClassName ) ) { + log.debug( + "Using default Infinispan transaction manager lookup " + + "instance (GenericTransactionManagerLookup), overriding it " + + "with Hibernate transaction manager lookup" + ); + builder.transaction().transactionManagerLookup( transactionManagerlookup ); + } + else if ( ispnTmLookupClassName != null && !ispnTmLookupClassName.equals( hbTmLookupClassName ) ) { + log.debug( + "Infinispan is configured [" + ispnTmLookupClassName + "] with a different transaction manager lookup " + + "class than Hibernate [" + hbTmLookupClassName + "]" + ); + } + else { + // Infinispan TM lookup class null, so apply Hibernate one directly + builder.transaction().transactionManagerLookup( transactionManagerlookup ); + } + + final String useSyncProp = extractProperty( INFINISPAN_USE_SYNCHRONIZATION_PROP, properties ); + final boolean useSync = useSyncProp == null ? DEF_USE_SYNCHRONIZATION : Boolean.parseBoolean( useSyncProp ); + builder.transaction().useSynchronization( useSync ); + } + } + + private TypeOverrides overrideStatisticsIfPresent(TypeOverrides override, Properties properties) { + final String globalStats = extractProperty( INFINISPAN_GLOBAL_STATISTICS_PROP, properties ); + if ( globalStats != null ) { + override.setExposeStatistics( Boolean.parseBoolean( globalStats ) ); + } + return override; + } } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/JndiInfinispanRegionFactory.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/JndiInfinispanRegionFactory.java index 62bd2999fc..939864a84e 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/JndiInfinispanRegionFactory.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/JndiInfinispanRegionFactory.java @@ -21,74 +21,88 @@ */ package org.hibernate.cache.infinispan; -import java.util.Properties; - import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; +import java.util.Properties; -import org.hibernate.cache.CacheException; -import org.hibernate.internal.util.config.ConfigurationHelper; -import org.hibernate.internal.util.jndi.JndiHelper; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; +import org.hibernate.cache.CacheException; +import org.hibernate.internal.util.config.ConfigurationHelper; +import org.hibernate.internal.util.jndi.JndiHelper; + /** * A {@link org.hibernate.cache.spi.RegionFactory} for Infinispan-backed cache * regions that finds its cache manager in JNDI rather than creating one itself. - * + * * @author Galder Zamarreño * @since 3.5 */ public class JndiInfinispanRegionFactory extends InfinispanRegionFactory { - private static final Log log = LogFactory.getLog(JndiInfinispanRegionFactory.class); + private static final Log log = LogFactory.getLog( JndiInfinispanRegionFactory.class ); - /** - * Specifies the JNDI name under which the {@link EmbeddedCacheManager} to use is bound. - * There is no default value -- the user must specify the property. - */ - public static final String CACHE_MANAGER_RESOURCE_PROP = "hibernate.cache.infinispan.cachemanager"; + /** + * Specifies the JNDI name under which the {@link EmbeddedCacheManager} to use is bound. + * There is no default value -- the user must specify the property. + */ + public static final String CACHE_MANAGER_RESOURCE_PROP = "hibernate.cache.infinispan.cachemanager"; - public JndiInfinispanRegionFactory() { - super(); - } + /** + * Constructs a JndiInfinispanRegionFactory + */ + @SuppressWarnings("UnusedDeclaration") + public JndiInfinispanRegionFactory() { + super(); + } - public JndiInfinispanRegionFactory(Properties props) { - super(props); - } + /** + * Constructs a JndiInfinispanRegionFactory + * + * @param props Any properties to apply (not used). + */ + @SuppressWarnings("UnusedDeclaration") + public JndiInfinispanRegionFactory(Properties props) { + super( props ); + } - @Override - protected EmbeddedCacheManager createCacheManager(Properties properties) throws CacheException { - String name = ConfigurationHelper.getString(CACHE_MANAGER_RESOURCE_PROP, properties, null); - if (name == null) - throw new CacheException("Configuration property " + CACHE_MANAGER_RESOURCE_PROP + " not set"); - return locateCacheManager(name, JndiHelper.extractJndiProperties(properties)); - } + @Override + protected EmbeddedCacheManager createCacheManager(Properties properties) throws CacheException { + final String name = ConfigurationHelper.getString( CACHE_MANAGER_RESOURCE_PROP, properties, null ); + if ( name == null ) { + throw new CacheException( "Configuration property " + CACHE_MANAGER_RESOURCE_PROP + " not set" ); + } + return locateCacheManager( name, JndiHelper.extractJndiProperties( properties ) ); + } - private EmbeddedCacheManager locateCacheManager(String jndiNamespace, Properties jndiProperties) { - Context ctx = null; - try { - ctx = new InitialContext(jndiProperties); - return (EmbeddedCacheManager) ctx.lookup(jndiNamespace); - } catch (NamingException ne) { - String msg = "Unable to retrieve CacheManager from JNDI [" + jndiNamespace + "]"; - log.info(msg, ne); - throw new CacheException( msg ); - } finally { - if (ctx != null) { - try { - ctx.close(); - } catch( NamingException ne ) { - log.info("Unable to release initial context", ne); - } - } - } - } + private EmbeddedCacheManager locateCacheManager(String jndiNamespace, Properties jndiProperties) { + Context ctx = null; + try { + ctx = new InitialContext( jndiProperties ); + return (EmbeddedCacheManager) ctx.lookup( jndiNamespace ); + } + catch (NamingException ne) { + final String msg = "Unable to retrieve CacheManager from JNDI [" + jndiNamespace + "]"; + log.info( msg, ne ); + throw new CacheException( msg ); + } + finally { + if ( ctx != null ) { + try { + ctx.close(); + } + catch (NamingException ne) { + log.info( "Unable to release initial context", ne ); + } + } + } + } - @Override - public void stop() { - // Do not attempt to stop a cache manager because it wasn't created by this region factory. - } + @Override + public void stop() { + // Do not attempt to stop a cache manager because it wasn't created by this region factory. + } } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/StrategyRegistrationProviderImpl.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/StrategyRegistrationProviderImpl.java index 8197d09ea3..59af216b51 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/StrategyRegistrationProviderImpl.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/StrategyRegistrationProviderImpl.java @@ -26,9 +26,9 @@ package org.hibernate.cache.infinispan; import java.util.ArrayList; import java.util.List; +import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl; import org.hibernate.boot.registry.selector.StrategyRegistration; import org.hibernate.boot.registry.selector.StrategyRegistrationProvider; -import org.hibernate.boot.registry.selector.SimpleStrategyRegistrationImpl; import org.hibernate.cache.spi.RegionFactory; /** @@ -43,7 +43,7 @@ public class StrategyRegistrationProviderImpl implements StrategyRegistrationPro final List strategyRegistrations = new ArrayList(); strategyRegistrations.add( - new SimpleStrategyRegistrationImpl( + new SimpleStrategyRegistrationImpl( RegionFactory.class, InfinispanRegionFactory.class, "infinispan", @@ -53,7 +53,7 @@ public class StrategyRegistrationProviderImpl implements StrategyRegistrationPro ); strategyRegistrations.add( - new SimpleStrategyRegistrationImpl( + new SimpleStrategyRegistrationImpl( RegionFactory.class, JndiInfinispanRegionFactory.class, "infinispan-jndi", diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/TypeOverrides.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/TypeOverrides.java index e4ccc1a002..f6e940171e 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/TypeOverrides.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/TypeOverrides.java @@ -32,129 +32,135 @@ import org.infinispan.eviction.EvictionStrategy; import org.hibernate.cache.CacheException; /** - * This class represents Infinispan cache parameters that can be configured via hibernate configuration properties - * for either general entity/collection/query/timestamp data type caches and overrides for individual entity or + * This class represents Infinispan cache parameters that can be configured via hibernate configuration properties + * for either general entity/collection/query/timestamp data type caches and overrides for individual entity or * collection caches. Configuration these properties override previously defined properties in XML file. - * + * * @author Galder Zamarreño * @since 3.5 */ public class TypeOverrides { - private final Set overridden = new HashSet(); + private final Set overridden = new HashSet(); - private String cacheName; + private String cacheName; - private EvictionStrategy evictionStrategy; + private EvictionStrategy evictionStrategy; - private long evictionWakeUpInterval; + private long evictionWakeUpInterval; - private int evictionMaxEntries; + private int evictionMaxEntries; - private long expirationLifespan; + private long expirationLifespan; - private long expirationMaxIdle; + private long expirationMaxIdle; - private boolean isExposeStatistics; + private boolean isExposeStatistics; - public String getCacheName() { - return cacheName; - } + public String getCacheName() { + return cacheName; + } - public void setCacheName(String cacheName) { - this.cacheName = cacheName; - } + public void setCacheName(String cacheName) { + this.cacheName = cacheName; + } - public EvictionStrategy getEvictionStrategy() { - return evictionStrategy; - } + public EvictionStrategy getEvictionStrategy() { + return evictionStrategy; + } - public void setEvictionStrategy(String evictionStrategy) { - markAsOverriden("evictionStrategy"); - this.evictionStrategy = EvictionStrategy.valueOf(uc(evictionStrategy)); - } + public void setEvictionStrategy(String evictionStrategy) { + markAsOverriden( "evictionStrategy" ); + this.evictionStrategy = EvictionStrategy.valueOf( uc( evictionStrategy ) ); + } - public long getEvictionWakeUpInterval() { - return evictionWakeUpInterval; - } + public long getEvictionWakeUpInterval() { + return evictionWakeUpInterval; + } - public void setEvictionWakeUpInterval(long evictionWakeUpInterval) { - markAsOverriden("evictionWakeUpInterval"); - this.evictionWakeUpInterval = evictionWakeUpInterval; - } + public void setEvictionWakeUpInterval(long evictionWakeUpInterval) { + markAsOverriden( "evictionWakeUpInterval" ); + this.evictionWakeUpInterval = evictionWakeUpInterval; + } - public int getEvictionMaxEntries() { - return evictionMaxEntries; - } + public int getEvictionMaxEntries() { + return evictionMaxEntries; + } - public void setEvictionMaxEntries(int evictionMaxEntries) { - markAsOverriden("evictionMaxEntries"); - this.evictionMaxEntries = evictionMaxEntries; - } + public void setEvictionMaxEntries(int evictionMaxEntries) { + markAsOverriden( "evictionMaxEntries" ); + this.evictionMaxEntries = evictionMaxEntries; + } - public long getExpirationLifespan() { - return expirationLifespan; - } + public long getExpirationLifespan() { + return expirationLifespan; + } - public void setExpirationLifespan(long expirationLifespan) { - markAsOverriden("expirationLifespan"); - this.expirationLifespan = expirationLifespan; - } + public void setExpirationLifespan(long expirationLifespan) { + markAsOverriden( "expirationLifespan" ); + this.expirationLifespan = expirationLifespan; + } - public long getExpirationMaxIdle() { - return expirationMaxIdle; - } + public long getExpirationMaxIdle() { + return expirationMaxIdle; + } - public void setExpirationMaxIdle(long expirationMaxIdle) { - markAsOverriden("expirationMaxIdle"); - this.expirationMaxIdle = expirationMaxIdle; - } + public void setExpirationMaxIdle(long expirationMaxIdle) { + markAsOverriden( "expirationMaxIdle" ); + this.expirationMaxIdle = expirationMaxIdle; + } - public boolean isExposeStatistics() { - return isExposeStatistics; - } + public boolean isExposeStatistics() { + return isExposeStatistics; + } - public void setExposeStatistics(boolean isExposeStatistics) { - markAsOverriden("isExposeStatistics"); - this.isExposeStatistics = isExposeStatistics; - } + public void setExposeStatistics(boolean isExposeStatistics) { + markAsOverriden( "isExposeStatistics" ); + this.isExposeStatistics = isExposeStatistics; + } - public void applyTo(ConfigurationBuilder builder) { - if (overridden.contains("evictionStrategy")) - builder.eviction().strategy(evictionStrategy); - if (overridden.contains("evictionWakeUpInterval")) - builder.expiration().wakeUpInterval(evictionWakeUpInterval); - if (overridden.contains("evictionMaxEntries")) - builder.eviction().maxEntries(evictionMaxEntries); - if (overridden.contains("expirationLifespan")) - builder.expiration().lifespan(expirationLifespan); - if (overridden.contains("expirationMaxIdle")) - builder.expiration().maxIdle(expirationMaxIdle); - if (overridden.contains("isExposeStatistics") && isExposeStatistics) - builder.jmxStatistics().enable(); - } + public void applyTo(ConfigurationBuilder builder) { + if ( overridden.contains( "evictionStrategy" ) ) { + builder.eviction().strategy( evictionStrategy ); + } + if ( overridden.contains( "evictionWakeUpInterval" ) ) { + builder.expiration().wakeUpInterval( evictionWakeUpInterval ); + } + if ( overridden.contains( "evictionMaxEntries" ) ) { + builder.eviction().maxEntries( evictionMaxEntries ); + } + if ( overridden.contains( "expirationLifespan" ) ) { + builder.expiration().lifespan( expirationLifespan ); + } + if ( overridden.contains( "expirationMaxIdle" ) ) { + builder.expiration().maxIdle( expirationMaxIdle ); + } + if ( overridden.contains( "isExposeStatistics" ) && isExposeStatistics ) { + builder.jmxStatistics().enable(); + } + } - public void validateInfinispanConfiguration(Configuration cfg) throws CacheException { - // no-op, method overriden - } + public void validateInfinispanConfiguration(Configuration cfg) throws CacheException { + // no-op, method overriden + } - @Override - public String toString() { - return new StringBuilder().append(getClass().getSimpleName()).append('{') - .append("cache=").append(cacheName) - .append(", strategy=").append(evictionStrategy) - .append(", wakeUpInterval=").append(evictionWakeUpInterval) - .append(", maxEntries=").append(evictionMaxEntries) - .append(", lifespan=").append(expirationLifespan) - .append(", maxIdle=").append(expirationMaxIdle) - .append('}').toString(); - } + @Override + public String toString() { + return getClass().getSimpleName() + + '{' + "cache=" + cacheName + + ", strategy=" + evictionStrategy + + ", wakeUpInterval=" + evictionWakeUpInterval + + ", maxEntries=" + evictionMaxEntries + + ", lifespan=" + expirationLifespan + + ", maxIdle=" + expirationMaxIdle + + '}'; + } - private String uc(String s) { - return s == null ? null : s.toUpperCase(Locale.ENGLISH); - } + private String uc(String s) { + return s == null ? null : s.toUpperCase( Locale.ENGLISH ); + } - private void markAsOverriden(String fieldName) { - overridden.add(fieldName); - } + private void markAsOverriden(String fieldName) { + overridden.add( fieldName ); + } } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/PutFromLoadValidator.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/PutFromLoadValidator.java index 003dce0b16..e9c0e704ed 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/PutFromLoadValidator.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/PutFromLoadValidator.java @@ -23,6 +23,9 @@ */ package org.hibernate.cache.infinispan.access; +import javax.transaction.SystemException; +import javax.transaction.Transaction; +import javax.transaction.TransactionManager; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -32,47 +35,45 @@ import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; -import javax.transaction.SystemException; -import javax.transaction.Transaction; -import javax.transaction.TransactionManager; + +import org.infinispan.AdvancedCache; +import org.infinispan.manager.EmbeddedCacheManager; import org.hibernate.cache.CacheException; import org.hibernate.cache.infinispan.InfinispanRegionFactory; -import org.infinispan.AdvancedCache; -import org.infinispan.manager.EmbeddedCacheManager; /** * Encapsulates logic to allow a {@link TransactionalAccessDelegate} to determine * whether a {@link TransactionalAccessDelegate#putFromLoad(Object, Object, long, Object, boolean)} * call should be allowed to update the cache. A putFromLoad has * the potential to store stale data, since the data may have been removed from the - * database and the cache between the time when the data was read from the database + * database and the cache between the time when the data was read from the database * and the actual call to putFromLoad. *

      * The expected usage of this class by a thread that read the cache and did * not find data is: - * + *

      *

        *
      1. Call {@link #registerPendingPut(Object)}
      2. *
      3. Read the database
      4. *
      5. Call {@link #acquirePutFromLoadLock(Object)} *
      6. if above returns false, the thread should not cache the data; - * only if above returns true, put data in the cache and...
      7. + * only if above returns true, put data in the cache and... *
      8. then call {@link #releasePutFromLoadLock(Object)}
      9. *
      *

      - * + *

      *

      * The expected usage by a thread that is taking an action such that any pending * putFromLoad may have stale data and should not cache it is to either * call - * + *

      *

        *
      • {@link #invalidateKey(Object)} (for a single key invalidation)
      • *
      • or {@link #invalidateRegion()} (for a general invalidation all pending puts)
      • *
      *

      - * + *

      *

      * This class also supports the concept of "naked puts", which are calls to * {@link #acquirePutFromLoadLock(Object)} without a preceding {@link #registerPendingPut(Object)} @@ -80,454 +81,477 @@ import org.infinispan.manager.EmbeddedCacheManager; *

      * * @author Brian Stansberry - * * @version $Revision: $ */ public class PutFromLoadValidator { - /** - * Period (in ms) after a removal during which a call to - * {@link #acquirePutFromLoadLock(Object)} that hasn't been - * {@link #registerPendingPut(Object) pre-registered} (aka a "naked put") - * will return false. - * will return false. - */ - public static final long NAKED_PUT_INVALIDATION_PERIOD = TimeUnit.SECONDS.toMillis(20); + /** + * Period (in ms) after a removal during which a call to + * {@link #acquirePutFromLoadLock(Object)} that hasn't been + * {@link #registerPendingPut(Object) pre-registered} (aka a "naked put") + * will return false. + * will return false. + */ + public static final long NAKED_PUT_INVALIDATION_PERIOD = TimeUnit.SECONDS.toMillis( 20 ); - /** - * Used to determine whether the owner of a pending put is a thread or a transaction - */ - private final TransactionManager transactionManager; + /** + * Used to determine whether the owner of a pending put is a thread or a transaction + */ + private final TransactionManager transactionManager; - private final long nakedPutInvalidationPeriod; + private final long nakedPutInvalidationPeriod; - /** - * Registry of expected, future, isPutValid calls. If a key+owner is registered in this map, it - * is not a "naked put" and is allowed to proceed. - */ - private final ConcurrentMap pendingPuts; + /** + * Registry of expected, future, isPutValid calls. If a key+owner is registered in this map, it + * is not a "naked put" and is allowed to proceed. + */ + private final ConcurrentMap pendingPuts; - private final ConcurrentMap recentRemovals = new ConcurrentHashMap(); - /** - * List of recent removals. Used to ensure we don't leak memory via the recentRemovals map - */ - private final List removalsQueue = new LinkedList(); - /** - * The time when the first element in removalsQueue will expire. No reason to do housekeeping on - * the queue before this time. - */ - private volatile long earliestRemovalTimestamp; - /** Lock controlling access to removalsQueue */ - private final Lock removalsLock = new ReentrantLock(); + private final ConcurrentMap recentRemovals = new ConcurrentHashMap(); + /** + * List of recent removals. Used to ensure we don't leak memory via the recentRemovals map + */ + private final List removalsQueue = new LinkedList(); + /** + * The time when the first element in removalsQueue will expire. No reason to do housekeeping on + * the queue before this time. + */ + private volatile long earliestRemovalTimestamp; + /** + * Lock controlling access to removalsQueue + */ + private final Lock removalsLock = new ReentrantLock(); - /** - * The time of the last call to regionRemoved(), plus NAKED_PUT_INVALIDATION_PERIOD. All naked - * puts will be rejected until the current time is greater than this value. - */ - private volatile long invalidationTimestamp; + /** + * The time of the last call to regionRemoved(), plus NAKED_PUT_INVALIDATION_PERIOD. All naked + * puts will be rejected until the current time is greater than this value. + */ + private volatile long invalidationTimestamp; - /** - * Creates a new PutFromLoadValidator. - */ - public PutFromLoadValidator(AdvancedCache cache) { - this(cache, NAKED_PUT_INVALIDATION_PERIOD); - } - - /** - * Constructor variant for use by unit tests; allows control of various timeouts by the test. - */ - public PutFromLoadValidator(AdvancedCache cache, - long nakedPutInvalidationPeriod) { - this(cache.getCacheManager(), cache.getTransactionManager(), - nakedPutInvalidationPeriod); - } - - public PutFromLoadValidator(EmbeddedCacheManager cacheManager, - TransactionManager tm, long nakedPutInvalidationPeriod) { - this.pendingPuts = cacheManager - .getCache(InfinispanRegionFactory.PENDING_PUTS_CACHE_NAME); - this.transactionManager = tm; - this.nakedPutInvalidationPeriod = nakedPutInvalidationPeriod; - } - - // ----------------------------------------------------------------- Public - - /** - * Acquire a lock giving the calling thread the right to put data in the - * cache for the given key. - *

      - * NOTE: A call to this method that returns true - * should always be matched with a call to {@link #releasePutFromLoadLock(Object)}. - *

      - * - * @param key the key - * - * @return true if the lock is acquired and the cache put - * can proceed; false if the data should not be cached - */ - public boolean acquirePutFromLoadLock(Object key) { - boolean valid = false; - boolean locked = false; - long now = System.currentTimeMillis(); - - try { - PendingPutMap pending = pendingPuts.get(key); - if (pending != null) { - locked = pending.acquireLock(100, TimeUnit.MILLISECONDS); - if (locked) { - try { - PendingPut toCancel = pending.remove(getOwnerForPut()); - if (toCancel != null) { - valid = !toCancel.completed; - toCancel.completed = true; - } - } - finally { - if (!valid) { - pending.releaseLock(); - locked = false; - } - } - } - } - else { - // Key wasn't in pendingPuts, so either this is a "naked put" - // or regionRemoved has been called. Check if we can proceed - if (now > invalidationTimestamp) { - Long removedTime = recentRemovals.get(key); - if (removedTime == null || now > removedTime ) { - // It's legal to proceed. But we have to record this key - // in pendingPuts so releasePutFromLoadLock can find it. - // To do this we basically simulate a normal "register - // then acquire lock" pattern - registerPendingPut(key); - locked = acquirePutFromLoadLock(key); - valid = locked; - } - } - } - } - catch (Throwable t) { - if (locked) { - PendingPutMap toRelease = pendingPuts.get(key); - if (toRelease != null) { - toRelease.releaseLock(); - } - } - - if (t instanceof RuntimeException) { - throw (RuntimeException) t; - } else if (t instanceof Error) { - throw (Error) t; - } else { - throw new RuntimeException(t); - } - } - - return valid; - } - - /** - * Releases the lock previously obtained by a call to - * {@link #acquirePutFromLoadLock(Object)} that returned true. - * - * @param key the key - */ - public void releasePutFromLoadLock(Object key) { - PendingPutMap pending = pendingPuts.get(key); - if (pending != null) { - if (pending.size() == 0) { - pendingPuts.remove(key, pending); - } - pending.releaseLock(); - } - } - - /** - * Invalidates any {@link #registerPendingPut(Object) previously registered pending puts} ensuring a subsequent call to - * {@link #acquirePutFromLoadLock(Object)} will return false.

      This method will block until any - * concurrent thread that has {@link #acquirePutFromLoadLock(Object) acquired the putFromLoad lock} for the given key - * has released the lock. This allows the caller to be certain the putFromLoad will not execute after this method - * returns, possibly caching stale data.

      - * - * @param key key identifying data whose pending puts should be invalidated - * @return true if the invalidation was successful; false if a problem occured (which the - * caller should treat as an exception condition) - */ - public boolean invalidateKey(Object key) { - boolean success = true; - - // Invalidate any pending puts - PendingPutMap pending = pendingPuts.get(key); - if (pending != null) { - // This lock should be available very quickly, but we'll be - // very patient waiting for it as callers should treat not - // acquiring it as an exception condition - if (pending.acquireLock(60, TimeUnit.SECONDS)) { - try { - pending.invalidate(); - } - finally { - pending.releaseLock(); - } - } else { - success = false; - } - } - - // Record when this occurred to invalidate later naked puts - RecentRemoval removal = new RecentRemoval(key, this.nakedPutInvalidationPeriod); - recentRemovals.put(key, removal.timestamp); - - // Don't let recentRemovals map become a memory leak - RecentRemoval toClean = null; - boolean attemptClean = removal.timestamp > earliestRemovalTimestamp; - removalsLock.lock(); - try { - removalsQueue.add(removal); - - if (attemptClean) { - if (removalsQueue.size() > 1) { // we have at least one as we - // just added it - toClean = removalsQueue.remove(0); - } - earliestRemovalTimestamp = removalsQueue.get( 0 ).timestamp; - } - } finally { - removalsLock.unlock(); - } - - if (toClean != null) { - Long cleaned = recentRemovals.get(toClean.key); - if (cleaned != null && cleaned.equals(toClean.timestamp)) { - cleaned = recentRemovals.remove(toClean.key); - if (cleaned != null && !cleaned.equals(toClean.timestamp)) { - // Oops; removed the wrong timestamp; restore it - recentRemovals.putIfAbsent(toClean.key, cleaned); - } - } - } - - return success; - } - - /** - * Invalidates all {@link #registerPendingPut(Object) previously registered pending puts} ensuring a subsequent call to - * {@link #acquirePutFromLoadLock(Object)} will return false.

      This method will block until any - * concurrent thread that has {@link #acquirePutFromLoadLock(Object) acquired the putFromLoad lock} for the any key has - * released the lock. This allows the caller to be certain the putFromLoad will not execute after this method returns, - * possibly caching stale data.

      - * - * @return true if the invalidation was successful; false if a problem occured (which the - * caller should treat as an exception condition) - */ - public boolean invalidateRegion() { - - boolean ok = false; - invalidationTimestamp = System.currentTimeMillis() + this.nakedPutInvalidationPeriod; - - try { - - // Acquire the lock for each entry to ensure any ongoing - // work associated with it is completed before we return - for (PendingPutMap entry : pendingPuts.values()) { - if (entry.acquireLock(60, TimeUnit.SECONDS)) { - try { - entry.invalidate(); - } - finally { - entry.releaseLock(); - } - } else { - ok = false; - } - } - - removalsLock.lock(); - try { - recentRemovals.clear(); - removalsQueue.clear(); - - ok = true; - - } finally { - removalsLock.unlock(); - } - } - catch (Exception e) { - ok = false; - } - finally { - earliestRemovalTimestamp = invalidationTimestamp; - } - - return ok; + /** + * Creates a new PutFromLoadValidator. + */ + public PutFromLoadValidator(AdvancedCache cache) { + this( cache, NAKED_PUT_INVALIDATION_PERIOD ); } - /** - * Notifies this validator that it is expected that a database read followed by a subsequent {@link - * #acquirePutFromLoadLock(Object)} call will occur. The intent is this method would be called following a cache miss - * wherein it is expected that a database read plus cache put will occur. Calling this method allows the validator to - * treat the subsequent acquirePutFromLoadLock as if the database read occurred when this method was - * invoked. This allows the validator to compare the timestamp of this call against the timestamp of subsequent removal - * notifications. A put that occurs without this call preceding it is "naked"; i.e the validator must assume the put is - * not valid if any relevant removal has occurred within {@link #NAKED_PUT_INVALIDATION_PERIOD} milliseconds. - * - * @param key key that will be used for subsequent cache put - */ - public void registerPendingPut(Object key) { - PendingPut pendingPut = new PendingPut(getOwnerForPut()); - PendingPutMap pendingForKey = new PendingPutMap(pendingPut); + /** + * Constructor variant for use by unit tests; allows control of various timeouts by the test. + */ + public PutFromLoadValidator( + AdvancedCache cache, + long nakedPutInvalidationPeriod) { + this( + cache.getCacheManager(), cache.getTransactionManager(), + nakedPutInvalidationPeriod + ); + } - for (;;) { - PendingPutMap existing = pendingPuts.putIfAbsent(key, pendingForKey); - if (existing != null) { - if (existing.acquireLock(10, TimeUnit.SECONDS)) { + public PutFromLoadValidator( + EmbeddedCacheManager cacheManager, + TransactionManager tm, long nakedPutInvalidationPeriod) { + this.pendingPuts = cacheManager + .getCache( InfinispanRegionFactory.PENDING_PUTS_CACHE_NAME ); + this.transactionManager = tm; + this.nakedPutInvalidationPeriod = nakedPutInvalidationPeriod; + } - try { - existing.put(pendingPut); - PendingPutMap doublecheck = pendingPuts.putIfAbsent(key, existing); - if (doublecheck == null || doublecheck == existing) { - break; - } - // else we hit a race and need to loop to try again - } - finally { - existing.releaseLock(); - } - } else { - // Can't get the lock; when we come back we'll be a "naked put" - break; - } - } else { - // normal case - break; - } - } - } + // ----------------------------------------------------------------- Public - // -------------------------------------------------------------- Protected + /** + * Acquire a lock giving the calling thread the right to put data in the + * cache for the given key. + *

      + * NOTE: A call to this method that returns true + * should always be matched with a call to {@link #releasePutFromLoadLock(Object)}. + *

      + * + * @param key the key + * + * @return true if the lock is acquired and the cache put + * can proceed; false if the data should not be cached + */ + public boolean acquirePutFromLoadLock(Object key) { + boolean valid = false; + boolean locked = false; + final long now = System.currentTimeMillis(); - /** Only for use by unit tests; may be removed at any time */ - protected int getRemovalQueueLength() { - removalsLock.lock(); - try { - return removalsQueue.size(); - } finally { - removalsLock.unlock(); - } - } + try { + final PendingPutMap pending = pendingPuts.get( key ); + if ( pending != null ) { + locked = pending.acquireLock( 100, TimeUnit.MILLISECONDS ); + if ( locked ) { + try { + final PendingPut toCancel = pending.remove( getOwnerForPut() ); + if ( toCancel != null ) { + valid = !toCancel.completed; + toCancel.completed = true; + } + } + finally { + if ( !valid ) { + pending.releaseLock(); + locked = false; + } + } + } + } + else { + // Key wasn't in pendingPuts, so either this is a "naked put" + // or regionRemoved has been called. Check if we can proceed + if ( now > invalidationTimestamp ) { + final Long removedTime = recentRemovals.get( key ); + if ( removedTime == null || now > removedTime ) { + // It's legal to proceed. But we have to record this key + // in pendingPuts so releasePutFromLoadLock can find it. + // To do this we basically simulate a normal "register + // then acquire lock" pattern + registerPendingPut( key ); + locked = acquirePutFromLoadLock( key ); + valid = locked; + } + } + } + } + catch (Throwable t) { + if ( locked ) { + final PendingPutMap toRelease = pendingPuts.get( key ); + if ( toRelease != null ) { + toRelease.releaseLock(); + } + } - // ---------------------------------------------------------------- Private + if ( t instanceof RuntimeException ) { + throw (RuntimeException) t; + } + else if ( t instanceof Error ) { + throw (Error) t; + } + else { + throw new RuntimeException( t ); + } + } - private Object getOwnerForPut() { - Transaction tx = null; - try { - if (transactionManager != null) { - tx = transactionManager.getTransaction(); - } - } catch (SystemException se) { - throw new CacheException("Could not obtain transaction", se); - } - return tx == null ? Thread.currentThread() : tx; + return valid; + } - } + /** + * Releases the lock previously obtained by a call to + * {@link #acquirePutFromLoadLock(Object)} that returned true. + * + * @param key the key + */ + public void releasePutFromLoadLock(Object key) { + final PendingPutMap pending = pendingPuts.get( key ); + if ( pending != null ) { + if ( pending.size() == 0 ) { + pendingPuts.remove( key, pending ); + } + pending.releaseLock(); + } + } - /** - * Lazy-initialization map for PendingPut. Optimized for the expected usual case where only a - * single put is pending for a given key. - * - * This class is NOT THREAD SAFE. All operations on it must be performed with the lock held. - */ - private static class PendingPutMap { - private PendingPut singlePendingPut; - private Map fullMap; - private final Lock lock = new ReentrantLock(); + /** + * Invalidates any {@link #registerPendingPut(Object) previously registered pending puts} ensuring a subsequent call to + * {@link #acquirePutFromLoadLock(Object)} will return false.

      This method will block until any + * concurrent thread that has {@link #acquirePutFromLoadLock(Object) acquired the putFromLoad lock} for the given key + * has released the lock. This allows the caller to be certain the putFromLoad will not execute after this method + * returns, possibly caching stale data.

      + * + * @param key key identifying data whose pending puts should be invalidated + * + * @return true if the invalidation was successful; false if a problem occured (which the + * caller should treat as an exception condition) + */ + public boolean invalidateKey(Object key) { + boolean success = true; - PendingPutMap(PendingPut singleItem) { - this.singlePendingPut = singleItem; - } + // Invalidate any pending puts + final PendingPutMap pending = pendingPuts.get( key ); + if ( pending != null ) { + // This lock should be available very quickly, but we'll be + // very patient waiting for it as callers should treat not + // acquiring it as an exception condition + if ( pending.acquireLock( 60, TimeUnit.SECONDS ) ) { + try { + pending.invalidate(); + } + finally { + pending.releaseLock(); + } + } + else { + success = false; + } + } - public void put(PendingPut pendingPut) { - if (singlePendingPut == null) { - if (fullMap == null) { - // initial put - singlePendingPut = pendingPut; - } else { - fullMap.put(pendingPut.owner, pendingPut); - } - } else { - // 2nd put; need a map - fullMap = new HashMap(4); - fullMap.put(singlePendingPut.owner, singlePendingPut); - singlePendingPut = null; - fullMap.put(pendingPut.owner, pendingPut); - } - } + // Record when this occurred to invalidate later naked puts + final RecentRemoval removal = new RecentRemoval( key, this.nakedPutInvalidationPeriod ); + recentRemovals.put( key, removal.timestamp ); - public PendingPut remove(Object ownerForPut) { - PendingPut removed = null; - if (fullMap == null) { - if (singlePendingPut != null - && singlePendingPut.owner.equals(ownerForPut)) { - removed = singlePendingPut; - singlePendingPut = null; - } - } else { - removed = fullMap.remove(ownerForPut); - } - return removed; - } + // Don't let recentRemovals map become a memory leak + RecentRemoval toClean = null; + final boolean attemptClean = removal.timestamp > earliestRemovalTimestamp; + removalsLock.lock(); + try { + removalsQueue.add( removal ); - public int size() { - return fullMap == null ? (singlePendingPut == null ? 0 : 1) - : fullMap.size(); - } + if ( attemptClean ) { + if ( removalsQueue.size() > 1 ) { + // we have at least one as we just added it + toClean = removalsQueue.remove( 0 ); + } + earliestRemovalTimestamp = removalsQueue.get( 0 ).timestamp; + } + } + finally { + removalsLock.unlock(); + } - public boolean acquireLock(long time, TimeUnit unit) { - try { - return lock.tryLock(time, unit); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return false; - } - } + if ( toClean != null ) { + Long cleaned = recentRemovals.get( toClean.key ); + if ( cleaned != null && cleaned.equals( toClean.timestamp ) ) { + cleaned = recentRemovals.remove( toClean.key ); + if ( cleaned != null && !cleaned.equals( toClean.timestamp ) ) { + // Oops; removed the wrong timestamp; restore it + recentRemovals.putIfAbsent( toClean.key, cleaned ); + } + } + } - public void releaseLock() { - lock.unlock(); - } + return success; + } - public void invalidate() { - if (singlePendingPut != null) { - singlePendingPut.completed = true; - // Nullify to avoid leaking completed pending puts - singlePendingPut = null; - } else if (fullMap != null) { - for (PendingPut pp : fullMap.values()) { - pp.completed = true; - } - // Nullify to avoid leaking completed pending puts - fullMap = null; - } - } - } + /** + * Invalidates all {@link #registerPendingPut(Object) previously registered pending puts} ensuring a subsequent call to + * {@link #acquirePutFromLoadLock(Object)} will return false.

      This method will block until any + * concurrent thread that has {@link #acquirePutFromLoadLock(Object) acquired the putFromLoad lock} for the any key has + * released the lock. This allows the caller to be certain the putFromLoad will not execute after this method returns, + * possibly caching stale data.

      + * + * @return true if the invalidation was successful; false if a problem occured (which the + * caller should treat as an exception condition) + */ + public boolean invalidateRegion() { - private static class PendingPut { - private final Object owner; - private volatile boolean completed; + boolean ok = false; + invalidationTimestamp = System.currentTimeMillis() + this.nakedPutInvalidationPeriod; - private PendingPut(Object owner) { - this.owner = owner; - } - } + try { - private static class RecentRemoval { - private final Object key; - private final Long timestamp; + // Acquire the lock for each entry to ensure any ongoing + // work associated with it is completed before we return + for ( PendingPutMap entry : pendingPuts.values() ) { + if ( entry.acquireLock( 60, TimeUnit.SECONDS ) ) { + try { + entry.invalidate(); + } + finally { + entry.releaseLock(); + } + } + else { + ok = false; + } + } - private RecentRemoval(Object key, long nakedPutInvalidationPeriod) { - this.key = key; - timestamp = System.currentTimeMillis() + nakedPutInvalidationPeriod; - } - } + removalsLock.lock(); + try { + recentRemovals.clear(); + removalsQueue.clear(); + + ok = true; + + } + finally { + removalsLock.unlock(); + } + } + catch (Exception e) { + ok = false; + } + finally { + earliestRemovalTimestamp = invalidationTimestamp; + } + + return ok; + } + + /** + * Notifies this validator that it is expected that a database read followed by a subsequent {@link + * #acquirePutFromLoadLock(Object)} call will occur. The intent is this method would be called following a cache miss + * wherein it is expected that a database read plus cache put will occur. Calling this method allows the validator to + * treat the subsequent acquirePutFromLoadLock as if the database read occurred when this method was + * invoked. This allows the validator to compare the timestamp of this call against the timestamp of subsequent removal + * notifications. A put that occurs without this call preceding it is "naked"; i.e the validator must assume the put is + * not valid if any relevant removal has occurred within {@link #NAKED_PUT_INVALIDATION_PERIOD} milliseconds. + * + * @param key key that will be used for subsequent cache put + */ + public void registerPendingPut(Object key) { + final PendingPut pendingPut = new PendingPut( getOwnerForPut() ); + final PendingPutMap pendingForKey = new PendingPutMap( pendingPut ); + + for (; ; ) { + final PendingPutMap existing = pendingPuts.putIfAbsent( key, pendingForKey ); + if ( existing != null ) { + if ( existing.acquireLock( 10, TimeUnit.SECONDS ) ) { + + try { + existing.put( pendingPut ); + final PendingPutMap doublecheck = pendingPuts.putIfAbsent( key, existing ); + if ( doublecheck == null || doublecheck == existing ) { + break; + } + // else we hit a race and need to loop to try again + } + finally { + existing.releaseLock(); + } + } + else { + // Can't get the lock; when we come back we'll be a "naked put" + break; + } + } + else { + // normal case + break; + } + } + } + + // -------------------------------------------------------------- Protected + + /** + * Only for use by unit tests; may be removed at any time + */ + protected int getRemovalQueueLength() { + removalsLock.lock(); + try { + return removalsQueue.size(); + } + finally { + removalsLock.unlock(); + } + } + + // ---------------------------------------------------------------- Private + + private Object getOwnerForPut() { + Transaction tx = null; + try { + if ( transactionManager != null ) { + tx = transactionManager.getTransaction(); + } + } + catch (SystemException se) { + throw new CacheException( "Could not obtain transaction", se ); + } + return tx == null ? Thread.currentThread() : tx; + + } + + /** + * Lazy-initialization map for PendingPut. Optimized for the expected usual case where only a + * single put is pending for a given key. + *

      + * This class is NOT THREAD SAFE. All operations on it must be performed with the lock held. + */ + private static class PendingPutMap { + private PendingPut singlePendingPut; + private Map fullMap; + private final Lock lock = new ReentrantLock(); + + PendingPutMap(PendingPut singleItem) { + this.singlePendingPut = singleItem; + } + + public void put(PendingPut pendingPut) { + if ( singlePendingPut == null ) { + if ( fullMap == null ) { + // initial put + singlePendingPut = pendingPut; + } + else { + fullMap.put( pendingPut.owner, pendingPut ); + } + } + else { + // 2nd put; need a map + fullMap = new HashMap( 4 ); + fullMap.put( singlePendingPut.owner, singlePendingPut ); + singlePendingPut = null; + fullMap.put( pendingPut.owner, pendingPut ); + } + } + + public PendingPut remove(Object ownerForPut) { + PendingPut removed = null; + if ( fullMap == null ) { + if ( singlePendingPut != null + && singlePendingPut.owner.equals( ownerForPut ) ) { + removed = singlePendingPut; + singlePendingPut = null; + } + } + else { + removed = fullMap.remove( ownerForPut ); + } + return removed; + } + + public int size() { + return fullMap == null ? (singlePendingPut == null ? 0 : 1) + : fullMap.size(); + } + + public boolean acquireLock(long time, TimeUnit unit) { + try { + return lock.tryLock( time, unit ); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + + public void releaseLock() { + lock.unlock(); + } + + public void invalidate() { + if ( singlePendingPut != null ) { + singlePendingPut.completed = true; + // Nullify to avoid leaking completed pending puts + singlePendingPut = null; + } + else if ( fullMap != null ) { + for ( PendingPut pp : fullMap.values() ) { + pp.completed = true; + } + // Nullify to avoid leaking completed pending puts + fullMap = null; + } + } + } + + private static class PendingPut { + private final Object owner; + private volatile boolean completed; + + private PendingPut(Object owner) { + this.owner = owner; + } + } + + private static class RecentRemoval { + private final Object key; + private final Long timestamp; + + private RecentRemoval(Object key, long nakedPutInvalidationPeriod) { + this.key = key; + timestamp = System.currentTimeMillis() + nakedPutInvalidationPeriod; + } + } } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/TransactionalAccessDelegate.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/TransactionalAccessDelegate.java index b7d22855a9..f3c8490ab2 100755 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/TransactionalAccessDelegate.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/TransactionalAccessDelegate.java @@ -25,158 +25,172 @@ package org.hibernate.cache.infinispan.access; import javax.transaction.Transaction; -import org.hibernate.cache.infinispan.util.Caches; import org.infinispan.AdvancedCache; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.hibernate.cache.CacheException; import org.hibernate.cache.infinispan.impl.BaseRegion; -import org.hibernate.cache.spi.access.CollectionRegionAccessStrategy; -import org.hibernate.cache.spi.access.EntityRegionAccessStrategy; +import org.hibernate.cache.infinispan.util.Caches; import org.hibernate.cache.spi.access.SoftLock; /** * Defines the strategy for transactional access to entity or collection data in a Infinispan instance. - *

      + *

      * The intent of this class is to encapsulate common code and serve as a delegate for - * {@link EntityRegionAccessStrategy} and {@link CollectionRegionAccessStrategy} implementations. - * + * {@link org.hibernate.cache.spi.access.EntityRegionAccessStrategy} + * and {@link org.hibernate.cache.spi.access.CollectionRegionAccessStrategy} implementations. + * * @author Brian Stansberry * @author Galder Zamarreño * @since 3.5 */ public class TransactionalAccessDelegate { - private static final Log log = LogFactory.getLog(TransactionalAccessDelegate.class); - private static final boolean isTrace = log.isTraceEnabled(); - private final AdvancedCache cache; - private final BaseRegion region; - private final PutFromLoadValidator putValidator; - private final AdvancedCache writeCache; + private static final Log log = LogFactory.getLog( TransactionalAccessDelegate.class ); + private static final boolean TRACE_ENABLED = log.isTraceEnabled(); + private final AdvancedCache cache; + private final BaseRegion region; + private final PutFromLoadValidator putValidator; + private final AdvancedCache writeCache; - public TransactionalAccessDelegate(BaseRegion region, PutFromLoadValidator validator) { - this.region = region; - this.cache = region.getCache(); - this.putValidator = validator; - this.writeCache = Caches.ignoreReturnValuesCache(cache); - } + public TransactionalAccessDelegate(BaseRegion region, PutFromLoadValidator validator) { + this.region = region; + this.cache = region.getCache(); + this.putValidator = validator; + this.writeCache = Caches.ignoreReturnValuesCache( cache ); + } - public Object get(Object key, long txTimestamp) throws CacheException { - if (!region.checkValid()) - return null; - Object val = cache.get(key); - if (val == null) - putValidator.registerPendingPut(key); - return val; - } + public Object get(Object key, long txTimestamp) throws CacheException { + if ( !region.checkValid() ) { + return null; + } + Object val = cache.get( key ); + if ( val == null ) { + putValidator.registerPendingPut( key ); + } + return val; + } - public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) { - return putFromLoad(key, value, txTimestamp, version, false); - } + public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) { + return putFromLoad( key, value, txTimestamp, version, false ); + } - public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) - throws CacheException { - if (!region.checkValid()) { - if (isTrace) log.tracef("Region %s not valid", region.getName()); - return false; - } + public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) + throws CacheException { + if ( !region.checkValid() ) { + if ( TRACE_ENABLED ) { + log.tracef( "Region %s not valid", region.getName() ); + } + return false; + } - // In theory, since putForExternalRead is already as minimal as it can - // get, we shouldn't be need this check. However, without the check and - // without https://issues.jboss.org/browse/ISPN-1986, it's impossible to - // know whether the put actually occurred. Knowing this is crucial so - // that Hibernate can expose accurate statistics. - if (minimalPutOverride && cache.containsKey(key)) - return false; + // In theory, since putForExternalRead is already as minimal as it can + // get, we shouldn't be need this check. However, without the check and + // without https://issues.jboss.org/browse/ISPN-1986, it's impossible to + // know whether the put actually occurred. Knowing this is crucial so + // that Hibernate can expose accurate statistics. + if ( minimalPutOverride && cache.containsKey( key ) ) { + return false; + } - if (!putValidator.acquirePutFromLoadLock(key)) { - if (isTrace) log.tracef("Put from load lock not acquired for key %s", key); - return false; - } + if ( !putValidator.acquirePutFromLoadLock( key ) ) { + if ( TRACE_ENABLED ) { + log.tracef( "Put from load lock not acquired for key %s", key ); + } + return false; + } - try { - writeCache.putForExternalRead(key, value); - } finally { - putValidator.releasePutFromLoadLock(key); - } + try { + writeCache.putForExternalRead( key, value ); + } + finally { + putValidator.releasePutFromLoadLock( key ); + } - return true; - } + return true; + } - public SoftLock lockItem(Object key, Object version) throws CacheException { - return null; - } + public SoftLock lockItem(Object key, Object version) throws CacheException { + return null; + } - public SoftLock lockRegion() throws CacheException { - return null; - } + public SoftLock lockRegion() throws CacheException { + return null; + } - public void unlockItem(Object key, SoftLock lock) throws CacheException { - } + public void unlockItem(Object key, SoftLock lock) throws CacheException { + } - public void unlockRegion(SoftLock lock) throws CacheException { - } + public void unlockRegion(SoftLock lock) throws CacheException { + } - public boolean insert(Object key, Object value, Object version) throws CacheException { - if (!region.checkValid()) - return false; + public boolean insert(Object key, Object value, Object version) throws CacheException { + if ( !region.checkValid() ) { + return false; + } - writeCache.put(key, value); - return true; - } + writeCache.put( key, value ); + return true; + } - public boolean afterInsert(Object key, Object value, Object version) throws CacheException { - return false; - } + public boolean afterInsert(Object key, Object value, Object version) throws CacheException { + return false; + } - public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { - // We update whether or not the region is valid. Other nodes - // may have already restored the region so they need to - // be informed of the change. - writeCache.put(key, value); - return true; - } + public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) + throws CacheException { + // We update whether or not the region is valid. Other nodes + // may have already restored the region so they need to + // be informed of the change. + writeCache.put( key, value ); + return true; + } - public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) - throws CacheException { - return false; - } + public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) + throws CacheException { + return false; + } - public void remove(Object key) throws CacheException { - if (!putValidator.invalidateKey(key)) { - throw new CacheException("Failed to invalidate pending putFromLoad calls for key " + key + " from region " + region.getName()); - } - // We update whether or not the region is valid. Other nodes - // may have already restored the region so they need to - // be informed of the change. - writeCache.remove(key); - } + public void remove(Object key) throws CacheException { + if ( !putValidator.invalidateKey( key ) ) { + throw new CacheException( + "Failed to invalidate pending putFromLoad calls for key " + key + " from region " + region.getName() + ); + } + // We update whether or not the region is valid. Other nodes + // may have already restored the region so they need to + // be informed of the change. + writeCache.remove( key ); + } - public void removeAll() throws CacheException { - if (!putValidator.invalidateRegion()) { - throw new CacheException("Failed to invalidate pending putFromLoad calls for region " + region.getName()); - } - cache.clear(); - } + public void removeAll() throws CacheException { + if ( !putValidator.invalidateRegion() ) { + throw new CacheException( "Failed to invalidate pending putFromLoad calls for region " + region.getName() ); + } + cache.clear(); + } - public void evict(Object key) throws CacheException { - if (!putValidator.invalidateKey(key)) { - throw new CacheException("Failed to invalidate pending putFromLoad calls for key " + key + " from region " + region.getName()); - } - writeCache.remove(key); - } + public void evict(Object key) throws CacheException { + if ( !putValidator.invalidateKey( key ) ) { + throw new CacheException( + "Failed to invalidate pending putFromLoad calls for key " + key + " from region " + region.getName() + ); + } + writeCache.remove( key ); + } - public void evictAll() throws CacheException { - if (!putValidator.invalidateRegion()) { - throw new CacheException("Failed to invalidate pending putFromLoad calls for region " + region.getName()); - } - Transaction tx = region.suspend(); - try { - region.invalidateRegion(); // Invalidate the local region and then go remote - Caches.broadcastEvictAll(cache); - } finally { - region.resume(tx); - } - } + public void evictAll() throws CacheException { + if ( !putValidator.invalidateRegion() ) { + throw new CacheException( "Failed to invalidate pending putFromLoad calls for region " + region.getName() ); + } + final Transaction tx = region.suspend(); + try { + region.invalidateRegion(); // Invalidate the local region and then go remote + Caches.broadcastEvictAll( cache ); + } + finally { + region.resume( tx ); + } + } } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/package-info.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/package-info.java new file mode 100644 index 0000000000..cb3a367a43 --- /dev/null +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/access/package-info.java @@ -0,0 +1,4 @@ +/** + * Internal Infinispan-based implementation of the cache region access strategies + */ +package org.hibernate.cache.infinispan.access; diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/CollectionRegionImpl.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/CollectionRegionImpl.java index 8846430811..626575b43e 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/CollectionRegionImpl.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/CollectionRegionImpl.java @@ -1,5 +1,30 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.cache.infinispan.collection; +import org.infinispan.AdvancedCache; + import org.hibernate.cache.CacheException; import org.hibernate.cache.infinispan.access.PutFromLoadValidator; import org.hibernate.cache.infinispan.impl.BaseTransactionalDataRegion; @@ -8,7 +33,6 @@ import org.hibernate.cache.spi.CollectionRegion; import org.hibernate.cache.spi.RegionFactory; import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.access.CollectionRegionAccessStrategy; -import org.infinispan.AdvancedCache; /** * @author Chris Bredesen @@ -17,21 +41,23 @@ import org.infinispan.AdvancedCache; */ public class CollectionRegionImpl extends BaseTransactionalDataRegion implements CollectionRegion { - public CollectionRegionImpl(AdvancedCache cache, String name, - CacheDataDescription metadata, RegionFactory factory) { - super(cache, name, metadata, factory); - } + public CollectionRegionImpl( + AdvancedCache cache, String name, + CacheDataDescription metadata, RegionFactory factory) { + super( cache, name, metadata, factory ); + } - public CollectionRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { - if (AccessType.READ_ONLY.equals(accessType) - || AccessType.TRANSACTIONAL.equals(accessType)) - return new TransactionalAccess(this); + public CollectionRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { + if ( AccessType.READ_ONLY.equals( accessType ) + || AccessType.TRANSACTIONAL.equals( accessType ) ) { + return new TransactionalAccess( this ); + } - throw new CacheException("Unsupported access type [" + accessType.getExternalName() + "]"); - } + throw new CacheException( "Unsupported access type [" + accessType.getExternalName() + "]" ); + } - public PutFromLoadValidator getPutFromLoadValidator() { - return new PutFromLoadValidator(cache); - } + public PutFromLoadValidator getPutFromLoadValidator() { + return new PutFromLoadValidator( cache ); + } } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/TransactionalAccess.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/TransactionalAccess.java index ae344c6406..6116f0fe49 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/TransactionalAccess.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/TransactionalAccess.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.cache.infinispan.collection; import org.hibernate.cache.CacheException; @@ -8,66 +31,67 @@ import org.hibernate.cache.spi.access.SoftLock; /** * Transactional collection region access for Infinispan. - * + * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ class TransactionalAccess implements CollectionRegionAccessStrategy { - private final CollectionRegionImpl region; - - private final TransactionalAccessDelegate delegate; + private final CollectionRegionImpl region; - TransactionalAccess(CollectionRegionImpl region) { - this.region = region; - this.delegate = new TransactionalAccessDelegate(region, region.getPutFromLoadValidator()); - } + private final TransactionalAccessDelegate delegate; - public void evict(Object key) throws CacheException { - delegate.evict(key); - } + TransactionalAccess(CollectionRegionImpl region) { + this.region = region; + this.delegate = new TransactionalAccessDelegate( region, region.getPutFromLoadValidator() ); + } - public void evictAll() throws CacheException { - delegate.evictAll(); - } + public void evict(Object key) throws CacheException { + delegate.evict( key ); + } - public Object get(Object key, long txTimestamp) throws CacheException { - return delegate.get(key, txTimestamp); - } + public void evictAll() throws CacheException { + delegate.evictAll(); + } - public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException { - return delegate.putFromLoad(key, value, txTimestamp, version); - } + public Object get(Object key, long txTimestamp) throws CacheException { + return delegate.get( key, txTimestamp ); + } - public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { - return delegate.putFromLoad(key, value, txTimestamp, version, minimalPutOverride); - } + public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException { + return delegate.putFromLoad( key, value, txTimestamp, version ); + } - public void remove(Object key) throws CacheException { - delegate.remove(key); - } + public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) + throws CacheException { + return delegate.putFromLoad( key, value, txTimestamp, version, minimalPutOverride ); + } - public void removeAll() throws CacheException { - delegate.removeAll(); - } + public void remove(Object key) throws CacheException { + delegate.remove( key ); + } - public CollectionRegion getRegion() { - return region; - } + public void removeAll() throws CacheException { + delegate.removeAll(); + } - public SoftLock lockItem(Object key, Object version) throws CacheException { - return null; - } + public CollectionRegion getRegion() { + return region; + } - public SoftLock lockRegion() throws CacheException { - return null; - } + public SoftLock lockItem(Object key, Object version) throws CacheException { + return null; + } - public void unlockItem(Object key, SoftLock lock) throws CacheException { - } + public SoftLock lockRegion() throws CacheException { + return null; + } - public void unlockRegion(SoftLock lock) throws CacheException { - } + public void unlockItem(Object key, SoftLock lock) throws CacheException { + } + + public void unlockRegion(SoftLock lock) throws CacheException { + } } \ No newline at end of file diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/package-info.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/package-info.java new file mode 100644 index 0000000000..c373eed64a --- /dev/null +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/collection/package-info.java @@ -0,0 +1,4 @@ +/** + * Internal Infinispan-based implementation of the collection cache region + */ +package org.hibernate.cache.infinispan.collection; diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/EntityRegionImpl.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/EntityRegionImpl.java index 7b61bca2b8..725250a8b8 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/EntityRegionImpl.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/EntityRegionImpl.java @@ -1,5 +1,30 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.cache.infinispan.entity; +import org.infinispan.AdvancedCache; + import org.hibernate.cache.CacheException; import org.hibernate.cache.infinispan.access.PutFromLoadValidator; import org.hibernate.cache.infinispan.impl.BaseTransactionalDataRegion; @@ -9,8 +34,6 @@ import org.hibernate.cache.spi.RegionFactory; import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.access.EntityRegionAccessStrategy; -import org.infinispan.AdvancedCache; - /** * @author Chris Bredesen * @author Galder Zamarreño @@ -18,8 +41,9 @@ import org.infinispan.AdvancedCache; */ public class EntityRegionImpl extends BaseTransactionalDataRegion implements EntityRegion { - public EntityRegionImpl(AdvancedCache cache, String name, - CacheDataDescription metadata, RegionFactory factory) { + public EntityRegionImpl( + AdvancedCache cache, String name, + CacheDataDescription metadata, RegionFactory factory) { super( cache, name, metadata, factory ); } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/ReadOnlyAccess.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/ReadOnlyAccess.java index b5724117ab..12843abc66 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/ReadOnlyAccess.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/ReadOnlyAccess.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.cache.infinispan.entity; import org.hibernate.cache.CacheException; @@ -14,19 +37,21 @@ import org.hibernate.cache.spi.access.SoftLock; class ReadOnlyAccess extends TransactionalAccess { ReadOnlyAccess(EntityRegionImpl region) { - super(region); + super( region ); } @Override - public boolean update(Object key, Object value, Object currentVersion, - Object previousVersion) throws CacheException { - throw new UnsupportedOperationException("Illegal attempt to edit read only item"); + public boolean update( + Object key, Object value, Object currentVersion, + Object previousVersion) throws CacheException { + throw new UnsupportedOperationException( "Illegal attempt to edit read only item" ); } @Override - public boolean afterUpdate(Object key, Object value, Object currentVersion, - Object previousVersion, SoftLock lock) throws CacheException { - throw new UnsupportedOperationException("Illegal attempt to edit read only item"); + public boolean afterUpdate( + Object key, Object value, Object currentVersion, + Object previousVersion, SoftLock lock) throws CacheException { + throw new UnsupportedOperationException( "Illegal attempt to edit read only item" ); } } \ No newline at end of file diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/TransactionalAccess.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/TransactionalAccess.java index de0dd89fea..ba3cb95ce8 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/TransactionalAccess.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/TransactionalAccess.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.cache.infinispan.entity; import org.hibernate.cache.CacheException; @@ -8,81 +31,84 @@ import org.hibernate.cache.spi.access.SoftLock; /** * Transactional entity region access for Infinispan. - * + * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ class TransactionalAccess implements EntityRegionAccessStrategy { - - private final EntityRegionImpl region; - - private final TransactionalAccessDelegate delegate; - TransactionalAccess(EntityRegionImpl region) { - this.region = region; - this.delegate = new TransactionalAccessDelegate(region, region.getPutFromLoadValidator()); - } + private final EntityRegionImpl region; - public void evict(Object key) throws CacheException { - delegate.evict(key); - } + private final TransactionalAccessDelegate delegate; - public void evictAll() throws CacheException { - delegate.evictAll(); - } + TransactionalAccess(EntityRegionImpl region) { + this.region = region; + this.delegate = new TransactionalAccessDelegate( region, region.getPutFromLoadValidator() ); + } - public Object get(Object key, long txTimestamp) throws CacheException { - return delegate.get(key, txTimestamp); - } + public void evict(Object key) throws CacheException { + delegate.evict( key ); + } - public EntityRegion getRegion() { - return this.region; - } + public void evictAll() throws CacheException { + delegate.evictAll(); + } - public boolean insert(Object key, Object value, Object version) throws CacheException { - return delegate.insert(key, value, version); - } + public Object get(Object key, long txTimestamp) throws CacheException { + return delegate.get( key, txTimestamp ); + } - public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException { - return delegate.putFromLoad(key, value, txTimestamp, version); - } + public EntityRegion getRegion() { + return this.region; + } - public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { - return delegate.putFromLoad(key, value, txTimestamp, version, minimalPutOverride); - } + public boolean insert(Object key, Object value, Object version) throws CacheException { + return delegate.insert( key, value, version ); + } - public void remove(Object key) throws CacheException { - delegate.remove(key); - } + public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException { + return delegate.putFromLoad( key, value, txTimestamp, version ); + } - public void removeAll() throws CacheException { - delegate.removeAll(); - } + public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) + throws CacheException { + return delegate.putFromLoad( key, value, txTimestamp, version, minimalPutOverride ); + } - public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) throws CacheException { - return delegate.update(key, value, currentVersion, previousVersion); - } + public void remove(Object key) throws CacheException { + delegate.remove( key ); + } - public SoftLock lockItem(Object key, Object version) throws CacheException { - return null; - } + public void removeAll() throws CacheException { + delegate.removeAll(); + } - public SoftLock lockRegion() throws CacheException { - return null; - } + public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) + throws CacheException { + return delegate.update( key, value, currentVersion, previousVersion ); + } - public void unlockItem(Object key, SoftLock lock) throws CacheException { - } + public SoftLock lockItem(Object key, Object version) throws CacheException { + return null; + } - public void unlockRegion(SoftLock lock) throws CacheException { - } + public SoftLock lockRegion() throws CacheException { + return null; + } - public boolean afterInsert(Object key, Object value, Object version) throws CacheException { - return false; - } + public void unlockItem(Object key, SoftLock lock) throws CacheException { + } - public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) throws CacheException { - return false; - } + public void unlockRegion(SoftLock lock) throws CacheException { + } + + public boolean afterInsert(Object key, Object value, Object version) throws CacheException { + return false; + } + + public boolean afterUpdate(Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock) + throws CacheException { + return false; + } } \ No newline at end of file diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/package-info.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/package-info.java new file mode 100644 index 0000000000..3d8e6531f9 --- /dev/null +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/entity/package-info.java @@ -0,0 +1,4 @@ +/** + * Internal Infinispan-based implementation of the entity cache region + */ +package org.hibernate.cache.infinispan.entity; diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.java index 3c33dbf330..b9b722ecd9 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseGeneralDataRegion.java @@ -1,44 +1,49 @@ package org.hibernate.cache.infinispan.impl; -import javax.transaction.TransactionManager; +import org.infinispan.AdvancedCache; import org.hibernate.cache.CacheException; import org.hibernate.cache.infinispan.util.Caches; import org.hibernate.cache.spi.GeneralDataRegion; import org.hibernate.cache.spi.RegionFactory; -import org.infinispan.AdvancedCache; /** * Support for Infinispan {@link GeneralDataRegion} implementors. - * + * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ public abstract class BaseGeneralDataRegion extends BaseRegion implements GeneralDataRegion { + private final AdvancedCache putCache; - private final AdvancedCache putCache; + public BaseGeneralDataRegion( + AdvancedCache cache, String name, + RegionFactory factory) { + super( cache, name, factory ); + this.putCache = Caches.ignoreReturnValuesCache( cache ); + } - public BaseGeneralDataRegion(AdvancedCache cache, String name, - RegionFactory factory) { - super(cache, name, factory); - this.putCache = Caches.ignoreReturnValuesCache(cache); - } + @Override + @SuppressWarnings("unchecked") + public void evict(Object key) throws CacheException { + cache.evict( key ); + } - public void evict(Object key) throws CacheException { - cache.evict(key); - } + @Override + public void evictAll() throws CacheException { + cache.clear(); + } - public void evictAll() throws CacheException { - cache.clear(); - } + @Override + public Object get(Object key) throws CacheException { + return cache.get( key ); + } - public Object get(Object key) throws CacheException { - return cache.get(key); - } - - public void put(Object key, Object value) throws CacheException { - putCache.put(key, value); - } + @Override + @SuppressWarnings("unchecked") + public void put(Object key, Object value) throws CacheException { + putCache.put( key, value ); + } } \ No newline at end of file diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java index 67126ca078..f6d320435e 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseRegion.java @@ -1,20 +1,43 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.cache.infinispan.impl; +import javax.transaction.SystemException; +import javax.transaction.Transaction; +import javax.transaction.TransactionManager; import java.util.Collections; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicReference; -import javax.transaction.SystemException; -import javax.transaction.Transaction; -import javax.transaction.TransactionManager; -import org.hibernate.cache.infinispan.util.Caches; import org.infinispan.AdvancedCache; import org.infinispan.context.Flag; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.hibernate.cache.CacheException; +import org.hibernate.cache.infinispan.util.Caches; import org.hibernate.cache.spi.Region; import org.hibernate.cache.spi.RegionFactory; @@ -22,184 +45,208 @@ import org.hibernate.cache.spi.RegionFactory; * Support for Infinispan {@link Region}s. Handles common "utility" methods for an underlying named * Cache. In other words, this implementation doesn't actually read or write data. Subclasses are * expected to provide core cache interaction appropriate to the semantics needed. - * + * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ public abstract class BaseRegion implements Region { - private static final Log log = LogFactory.getLog(BaseRegion.class); + private static final Log log = LogFactory.getLog( BaseRegion.class ); - private enum InvalidateState { - INVALID, CLEARING, VALID - } + private enum InvalidateState { + INVALID, CLEARING, VALID + } - private final String name; - private final AdvancedCache regionClearCache; - private final TransactionManager tm; - private final Object invalidationMutex = new Object(); - private final AtomicReference invalidateState = - new AtomicReference(InvalidateState.VALID); - private final RegionFactory factory; + private final String name; + private final AdvancedCache regionClearCache; + private final TransactionManager tm; + private final Object invalidationMutex = new Object(); + private final AtomicReference invalidateState = + new AtomicReference( InvalidateState.VALID ); + private final RegionFactory factory; - protected final AdvancedCache cache; + protected final AdvancedCache cache; - public BaseRegion(AdvancedCache cache, String name, RegionFactory factory) { - this.cache = cache; - this.name = name; - this.tm = cache.getTransactionManager(); - this.factory = factory; - this.regionClearCache = cache.withFlags( - Flag.CACHE_MODE_LOCAL, Flag.ZERO_LOCK_ACQUISITION_TIMEOUT); - } + public BaseRegion(AdvancedCache cache, String name, RegionFactory factory) { + this.cache = cache; + this.name = name; + this.tm = cache.getTransactionManager(); + this.factory = factory; + this.regionClearCache = cache.withFlags( + Flag.CACHE_MODE_LOCAL, Flag.ZERO_LOCK_ACQUISITION_TIMEOUT + ); + } - public String getName() { - return name; - } + @Override + public String getName() { + return name; + } - public long getElementCountInMemory() { - if (checkValid()) - return cache.size(); + @Override + public long getElementCountInMemory() { + if ( checkValid() ) { + return cache.size(); + } - return 0; - } + return 0; + } - /** - * Not supported. - * - * @return -1 - */ - public long getElementCountOnDisk() { - return -1; - } + /** + * {@inheritDoc} + *

      + * Not supported; returns -1 + */ + @Override + public long getElementCountOnDisk() { + return -1; + } - /** - * Not supported. - * - * @return -1 - */ - public long getSizeInMemory() { - return -1; - } + /** + * {@inheritDoc} + *

      + * Not supported; returns -1 + */ + @Override + public long getSizeInMemory() { + return -1; + } - public int getTimeout() { - return 600; // 60 seconds - } + @Override + public int getTimeout() { + // 60 seconds + return 600; + } - public long nextTimestamp() { - return factory.nextTimestamp(); - } + @Override + public long nextTimestamp() { + return factory.nextTimestamp(); + } - public Map toMap() { - if (checkValid()) - return cache; + @Override + public Map toMap() { + if ( checkValid() ) { + return cache; + } - return Collections.EMPTY_MAP; - } + return Collections.EMPTY_MAP; + } - public void destroy() throws CacheException { - try { - cache.stop(); - } finally { - cache.removeListener(this); - } - } + @Override + public void destroy() throws CacheException { + try { + cache.stop(); + } + finally { + cache.removeListener( this ); + } + } - public boolean contains(Object key) { - return checkValid() && cache.containsKey(key); - } + @Override + public boolean contains(Object key) { + return checkValid() && cache.containsKey( key ); + } - public boolean checkValid() { - boolean valid = isValid(); - if (!valid) { - synchronized (invalidationMutex) { - if (invalidateState.compareAndSet( - InvalidateState.INVALID, InvalidateState.CLEARING)) { - Transaction tx = suspend(); - try { - // Clear region in a separate transaction - Caches.withinTx(cache, new Callable() { - @Override - public Void call() throws Exception { - regionClearCache.clear(); - return null; - } - }); - invalidateState.compareAndSet( - InvalidateState.CLEARING, InvalidateState.VALID); - } - catch (Exception e) { - if (log.isTraceEnabled()) { - log.trace("Could not invalidate region: " - + e.getLocalizedMessage()); - } - } - finally { - resume(tx); - } - } - } - valid = isValid(); - } - - return valid; - } + public boolean checkValid() { + boolean valid = isValid(); + if ( !valid ) { + synchronized (invalidationMutex) { + if ( invalidateState.compareAndSet( + InvalidateState.INVALID, InvalidateState.CLEARING + ) ) { + Transaction tx = suspend(); + try { + // Clear region in a separate transaction + Caches.withinTx( + cache, new Callable() { + @Override + public Void call() throws Exception { + regionClearCache.clear(); + return null; + } + } + ); + invalidateState.compareAndSet( + InvalidateState.CLEARING, InvalidateState.VALID + ); + } + catch (Exception e) { + if ( log.isTraceEnabled() ) { + log.trace( + "Could not invalidate region: " + + e.getLocalizedMessage() + ); + } + } + finally { + resume( tx ); + } + } + } + valid = isValid(); + } - protected boolean isValid() { - return invalidateState.get() == InvalidateState.VALID; - } + return valid; + } - /** - * Tell the TransactionManager to suspend any ongoing transaction. - * - * @return the transaction that was suspended, or null if - * there wasn't one - */ - public Transaction suspend() { - Transaction tx = null; - try { - if (tm != null) { - tx = tm.suspend(); - } - } catch (SystemException se) { - throw new CacheException("Could not suspend transaction", se); - } - return tx; - } + protected boolean isValid() { + return invalidateState.get() == InvalidateState.VALID; + } - /** - * Tell the TransactionManager to resume the given transaction - * - * @param tx - * the transaction to suspend. May be null. - */ - public void resume(Transaction tx) { - try { - if (tx != null) - tm.resume(tx); - } catch (Exception e) { - throw new CacheException("Could not resume transaction", e); - } - } + /** + * Tell the TransactionManager to suspend any ongoing transaction. + * + * @return the transaction that was suspended, or null if + * there wasn't one + */ + public Transaction suspend() { + Transaction tx = null; + try { + if ( tm != null ) { + tx = tm.suspend(); + } + } + catch (SystemException se) { + throw new CacheException( "Could not suspend transaction", se ); + } + return tx; + } - public void invalidateRegion() { - if (log.isTraceEnabled()) log.trace("Invalidate region: " + name); - invalidateState.set(InvalidateState.INVALID); - } + /** + * Tell the TransactionManager to resume the given transaction + * + * @param tx the transaction to suspend. May be null. + */ + public void resume(Transaction tx) { + try { + if ( tx != null ) { + tm.resume( tx ); + } + } + catch (Exception e) { + throw new CacheException( "Could not resume transaction", e ); + } + } - public TransactionManager getTransactionManager() { - return tm; - } + public void invalidateRegion() { + if ( log.isTraceEnabled() ) { + log.trace( "Invalidate region: " + name ); + } + invalidateState.set( InvalidateState.INVALID ); + } - // Used to satisfy TransactionalDataRegion.isTransactionAware in subclasses - @SuppressWarnings("unused") - public boolean isTransactionAware() { - return tm != null; - } + public TransactionManager getTransactionManager() { + return tm; + } - public AdvancedCache getCache() { - return cache; - } + // Used to satisfy TransactionalDataRegion.isTransactionAware in subclasses + @SuppressWarnings("unused") + public boolean isTransactionAware() { + return tm != null; + } + + public AdvancedCache getCache() { + return cache; + } } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.java index 8c57ad512c..250199458a 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/BaseTransactionalDataRegion.java @@ -1,31 +1,56 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.cache.infinispan.impl; +import org.infinispan.AdvancedCache; + import org.hibernate.cache.spi.CacheDataDescription; import org.hibernate.cache.spi.RegionFactory; import org.hibernate.cache.spi.TransactionalDataRegion; -import org.infinispan.AdvancedCache; /** * Support for Inifinispan {@link org.hibernate.cache.spi.TransactionalDataRegion} implementors. - * + * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ public abstract class BaseTransactionalDataRegion - extends BaseRegion implements TransactionalDataRegion { + extends BaseRegion implements TransactionalDataRegion { - private final CacheDataDescription metadata; + private final CacheDataDescription metadata; - public BaseTransactionalDataRegion(AdvancedCache cache, String name, - CacheDataDescription metadata, RegionFactory factory) { - super(cache, name, factory); - this.metadata = metadata; - } + public BaseTransactionalDataRegion( + AdvancedCache cache, String name, + CacheDataDescription metadata, RegionFactory factory) { + super( cache, name, factory ); + this.metadata = metadata; + } @Override - public CacheDataDescription getCacheDataDescription() { - return metadata; - } + public CacheDataDescription getCacheDataDescription() { + return metadata; + } } \ No newline at end of file diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/package-info.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/package-info.java new file mode 100644 index 0000000000..a29f682aca --- /dev/null +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/impl/package-info.java @@ -0,0 +1,4 @@ +/** + * Internal Infinispan-specific base cache region implementations + */ +package org.hibernate.cache.infinispan.impl; diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/NaturalIdRegionImpl.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/NaturalIdRegionImpl.java index 04aa44ae60..8486d970a2 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/NaturalIdRegionImpl.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/NaturalIdRegionImpl.java @@ -1,5 +1,30 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.cache.infinispan.naturalid; +import org.infinispan.AdvancedCache; + import org.hibernate.cache.CacheException; import org.hibernate.cache.infinispan.access.PutFromLoadValidator; import org.hibernate.cache.infinispan.impl.BaseTransactionalDataRegion; @@ -8,7 +33,6 @@ import org.hibernate.cache.spi.NaturalIdRegion; import org.hibernate.cache.spi.RegionFactory; import org.hibernate.cache.spi.access.AccessType; import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy; -import org.infinispan.AdvancedCache; /** * Natural ID cache region @@ -17,16 +41,17 @@ import org.infinispan.AdvancedCache; * @author Galder Zamarreño */ public class NaturalIdRegionImpl extends BaseTransactionalDataRegion - implements NaturalIdRegion { + implements NaturalIdRegion { - public NaturalIdRegionImpl(AdvancedCache cache, String name, - CacheDataDescription metadata, RegionFactory factory) { - super(cache, name, metadata, factory); + public NaturalIdRegionImpl( + AdvancedCache cache, String name, + CacheDataDescription metadata, RegionFactory factory) { + super( cache, name, metadata, factory ); } @Override public NaturalIdRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { - switch ( accessType ){ + switch ( accessType ) { case READ_ONLY: return new ReadOnlyAccess( this ); case TRANSACTIONAL: @@ -37,7 +62,7 @@ public class NaturalIdRegionImpl extends BaseTransactionalDataRegion } public PutFromLoadValidator getPutFromLoadValidator() { - return new PutFromLoadValidator(cache); + return new PutFromLoadValidator( cache ); } } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/ReadOnlyAccess.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/ReadOnlyAccess.java index 0c173d0a5e..61c1df966a 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/ReadOnlyAccess.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/ReadOnlyAccess.java @@ -1,8 +1,28 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.cache.infinispan.naturalid; -import org.infinispan.util.logging.Log; -import org.infinispan.util.logging.LogFactory; - import org.hibernate.cache.CacheException; import org.hibernate.cache.spi.access.SoftLock; diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/TransactionalAccess.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/TransactionalAccess.java index fd159eb69a..97dc96212f 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/TransactionalAccess.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/TransactionalAccess.java @@ -1,8 +1,30 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.cache.infinispan.naturalid; import org.hibernate.cache.CacheException; import org.hibernate.cache.infinispan.access.TransactionalAccessDelegate; -import org.hibernate.cache.spi.EntityRegion; import org.hibernate.cache.spi.NaturalIdRegion; import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy; import org.hibernate.cache.spi.access.SoftLock; @@ -21,12 +43,12 @@ class TransactionalAccess implements NaturalIdRegionAccessStrategy { @Override public boolean insert(Object key, Object value) throws CacheException { - return delegate.insert(key, value, null); + return delegate.insert( key, value, null ); } @Override public boolean update(Object key, Object value) throws CacheException { - return delegate.update(key, value, null, null); + return delegate.update( key, value, null, null ); } @Override @@ -88,14 +110,14 @@ class TransactionalAccess implements NaturalIdRegionAccessStrategy { public void unlockRegion(SoftLock lock) throws CacheException { } - @Override - public boolean afterInsert(Object key, Object value) throws CacheException { - return false; - } + @Override + public boolean afterInsert(Object key, Object value) throws CacheException { + return false; + } - @Override - public boolean afterUpdate(Object key, Object value, SoftLock lock) throws CacheException { - return false; - } + @Override + public boolean afterUpdate(Object key, Object value, SoftLock lock) throws CacheException { + return false; + } } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/package-info.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/package-info.java new file mode 100644 index 0000000000..9e9ca0e9aa --- /dev/null +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/naturalid/package-info.java @@ -0,0 +1,4 @@ +/** + * Internal Infinispan-based implementation of the natural-id cache region + */ +package org.hibernate.cache.infinispan.naturalid; diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/package-info.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/package-info.java new file mode 100644 index 0000000000..61598abc25 --- /dev/null +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/package-info.java @@ -0,0 +1,4 @@ +/** + * Defines the integration with Infinispan as a second-level cache service. + */ +package org.hibernate.cache.infinispan; diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/query/QueryResultsRegionImpl.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/query/QueryResultsRegionImpl.java index 0bc905662b..69182290f8 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/query/QueryResultsRegionImpl.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/query/QueryResultsRegionImpl.java @@ -1,14 +1,38 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.cache.infinispan.query; import javax.transaction.Transaction; +import org.infinispan.AdvancedCache; +import org.infinispan.context.Flag; + import org.hibernate.cache.CacheException; import org.hibernate.cache.infinispan.impl.BaseTransactionalDataRegion; import org.hibernate.cache.infinispan.util.Caches; import org.hibernate.cache.spi.QueryResultsRegion; import org.hibernate.cache.spi.RegionFactory; -import org.infinispan.AdvancedCache; -import org.infinispan.context.Flag; /** * @author Chris Bredesen @@ -17,80 +41,91 @@ import org.infinispan.context.Flag; */ public class QueryResultsRegionImpl extends BaseTransactionalDataRegion implements QueryResultsRegion { - private final AdvancedCache evictCache; - private final AdvancedCache putCache; - private final AdvancedCache getCache; + private final AdvancedCache evictCache; + private final AdvancedCache putCache; + private final AdvancedCache getCache; - public QueryResultsRegionImpl(AdvancedCache cache, String name, RegionFactory factory) { - super(cache, name, null, factory); - // If Infinispan is using INVALIDATION for query cache, we don't want to propagate changes. - // We use the Timestamps cache to manage invalidation - boolean localOnly = Caches.isInvalidationCache(cache); + public QueryResultsRegionImpl(AdvancedCache cache, String name, RegionFactory factory) { + super( cache, name, null, factory ); + // If Infinispan is using INVALIDATION for query cache, we don't want to propagate changes. + // We use the Timestamps cache to manage invalidation + final boolean localOnly = Caches.isInvalidationCache( cache ); - this.evictCache = localOnly ? Caches.localCache(cache) : cache; + this.evictCache = localOnly ? Caches.localCache( cache ) : cache; - this.putCache = localOnly ? - Caches.failSilentWriteCache(cache, Flag.CACHE_MODE_LOCAL) : - Caches.failSilentWriteCache(cache); + this.putCache = localOnly ? + Caches.failSilentWriteCache( cache, Flag.CACHE_MODE_LOCAL ) : + Caches.failSilentWriteCache( cache ); - this.getCache = Caches.failSilentReadCache(cache); - } + this.getCache = Caches.failSilentReadCache( cache ); + } - public void evict(Object key) throws CacheException { - evictCache.remove(key); - } + @Override + public void evict(Object key) throws CacheException { + evictCache.remove( key ); + } - public void evictAll() throws CacheException { - Transaction tx = suspend(); - try { - invalidateRegion(); // Invalidate the local region and then go remote - Caches.broadcastEvictAll(cache); - } finally { - resume(tx); - } - } + @Override + public void evictAll() throws CacheException { + final Transaction tx = suspend(); + try { + // Invalidate the local region and then go remote + invalidateRegion(); + Caches.broadcastEvictAll( cache ); + } + finally { + resume( tx ); + } + } - public Object get(Object key) throws CacheException { - // If the region is not valid, skip cache store to avoid going remote to retrieve the query. - // The aim of this is to maintain same logic/semantics as when state transfer was configured. - // TODO: Once https://issues.jboss.org/browse/ISPN-835 has been resolved, revert to state transfer and remove workaround - boolean skipCacheStore = false; - if (!isValid()) - skipCacheStore = true; + @Override + public Object get(Object key) throws CacheException { + // If the region is not valid, skip cache store to avoid going remote to retrieve the query. + // The aim of this is to maintain same logic/semantics as when state transfer was configured. + // TODO: Once https://issues.jboss.org/browse/ISPN-835 has been resolved, revert to state transfer and remove workaround + boolean skipCacheStore = false; + if ( !isValid() ) { + skipCacheStore = true; + } - if (!checkValid()) - return null; + if ( !checkValid() ) { + return null; + } - // 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 - if (skipCacheStore) - return getCache.withFlags(Flag.SKIP_CACHE_STORE).get(key); - else - return getCache.get(key); - } + // 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 + if ( skipCacheStore ) { + return getCache.withFlags( Flag.SKIP_CACHE_STORE ).get( key ); + } + else { + return getCache.get( key ); + } + } - public void put(Object key, Object value) throws CacheException { - if (checkValid()) { - // Here we don't want to suspend the tx. If we do: - // 1) We might be caching query results that reflect uncommitted - // changes. No tx == no WL on cache node, so other threads - // can prematurely see those query results - // 2) No tx == immediate replication. More overhead, plus we - // spread issue #1 above around the cluster + @Override + @SuppressWarnings("unchecked") + public void put(Object key, Object value) throws CacheException { + if ( checkValid() ) { + // Here we don't want to suspend the tx. If we do: + // 1) We might be caching query results that reflect uncommitted + // changes. No tx == no WL on cache node, so other threads + // can prematurely see those query results + // 2) No tx == immediate replication. More overhead, plus we + // spread issue #1 above around the cluster - // Add a zero (or quite low) timeout option so we don't block. - // Ignore any TimeoutException. Basically we forego caching the - // query result in order to avoid blocking. - // Reads are done with suspended tx, so they should not hold the - // lock for long. Not caching the query result is OK, since - // any subsequent read will just see the old result with its - // out-of-date timestamp; that result will be discarded and the - // db query performed again. - putCache.put(key, value); - } - } + // Add a zero (or quite low) timeout option so we don't block. + // Ignore any TimeoutException. Basically we forego caching the + // query result in order to avoid blocking. + // Reads are done with suspended tx, so they should not hold the + // lock for long. Not caching the query result is OK, since + // any subsequent read will just see the old result with its + // out-of-date timestamp; that result will be discarded and the + // db query performed again. + putCache.put( key, value ); + } + } } \ No newline at end of file diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/query/package-info.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/query/package-info.java new file mode 100644 index 0000000000..1bc5d26f4c --- /dev/null +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/query/package-info.java @@ -0,0 +1,4 @@ +/** + * Internal Infinispan-based implementation of the "query results" cache region + */ +package org.hibernate.cache.infinispan.query; diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/ClusteredTimestampsRegionImpl.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/ClusteredTimestampsRegionImpl.java index 5914160a2e..83f490af9c 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/ClusteredTimestampsRegionImpl.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/ClusteredTimestampsRegionImpl.java @@ -20,12 +20,13 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ - package org.hibernate.cache.infinispan.timestamp; -import org.hibernate.cache.CacheException; -import org.hibernate.cache.infinispan.util.Caches; -import org.hibernate.cache.spi.RegionFactory; +import javax.transaction.Transaction; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + import org.infinispan.AdvancedCache; import org.infinispan.context.Flag; import org.infinispan.notifications.Listener; @@ -34,10 +35,9 @@ import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; -import javax.transaction.Transaction; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; +import org.hibernate.cache.CacheException; +import org.hibernate.cache.infinispan.util.Caches; +import org.hibernate.cache.spi.RegionFactory; /** * Timestamp cache region for clustered environments. @@ -48,105 +48,118 @@ import java.util.concurrent.ConcurrentHashMap; @Listener public class ClusteredTimestampsRegionImpl extends TimestampsRegionImpl { - /** - * Maintains a local (authoritative) cache of timestamps along with the - * replicated cache held in Infinispan. It listens for changes in the - * cache and updates the local cache accordingly. This approach allows - * timestamp changes to be replicated asynchronously. - */ - private final Map localCache = new ConcurrentHashMap(); + /** + * Maintains a local (authoritative) cache of timestamps along with the + * replicated cache held in Infinispan. It listens for changes in the + * cache and updates the local cache accordingly. This approach allows + * timestamp changes to be replicated asynchronously. + */ + private final Map localCache = new ConcurrentHashMap(); - public ClusteredTimestampsRegionImpl(AdvancedCache cache, - String name, RegionFactory factory) { - super(cache, name, factory); - cache.addListener(this); - populateLocalCache(); - } + public ClusteredTimestampsRegionImpl( + AdvancedCache cache, + String name, RegionFactory factory) { + super( cache, name, factory ); + cache.addListener( this ); + populateLocalCache(); + } - @Override - protected AdvancedCache getTimestampsPutCache(AdvancedCache cache) { - return Caches.asyncWriteCache(cache, Flag.SKIP_LOCKING); - } + @Override + protected AdvancedCache getTimestampsPutCache(AdvancedCache cache) { + return Caches.asyncWriteCache( cache, Flag.SKIP_LOCKING ); + } - @Override - public Object get(Object key) throws CacheException { - Object value = localCache.get(key); + @Override + @SuppressWarnings("unchecked") + public Object get(Object key) throws CacheException { + Object value = localCache.get( key ); - // If the region is not valid, skip cache store to avoid going remote to retrieve the query. - // The aim of this is to maintain same logic/semantics as when state transfer was configured. - // TODO: Once https://issues.jboss.org/browse/ISPN-835 has been resolved, revert to state transfer and remove workaround - boolean skipCacheStore = false; - if (!isValid()) - skipCacheStore = true; + // If the region is not valid, skip cache store to avoid going remote to retrieve the query. + // The aim of this is to maintain same logic/semantics as when state transfer was configured. + // TODO: Once https://issues.jboss.org/browse/ISPN-835 has been resolved, revert to state transfer and remove workaround + boolean skipCacheStore = false; + if ( !isValid() ) { + skipCacheStore = true; + } - if (value == null && checkValid()) { - if (skipCacheStore) - value = cache.withFlags(Flag.SKIP_CACHE_STORE).get(key); - else - value = cache.get(key); + if ( value == null && checkValid() ) { + if ( skipCacheStore ) { + value = cache.withFlags( Flag.SKIP_CACHE_STORE ).get( key ); + } + else { + value = cache.get( key ); + } - if (value != null) - localCache.put(key, value); - } - return value; - } + if ( value != null ) { + localCache.put( key, value ); + } + } + return value; + } - @Override - public void evictAll() throws CacheException { - // TODO Is this a valid operation on a timestamps cache? - Transaction tx = suspend(); - try { - invalidateRegion(); // Invalidate the local region and then go remote - Caches.broadcastEvictAll(cache); - } finally { - resume(tx); - } - } + @Override + public void evictAll() throws CacheException { + // TODO Is this a valid operation on a timestamps cache? + final Transaction tx = suspend(); + try { + // Invalidate the local region and then go remote + invalidateRegion(); + Caches.broadcastEvictAll( cache ); + } + finally { + resume( tx ); + } + } - @Override - public void invalidateRegion() { - super.invalidateRegion(); // Invalidate first - localCache.clear(); - } + @Override + public void invalidateRegion() { + // Invalidate first + super.invalidateRegion(); + localCache.clear(); + } - @Override - public void destroy() throws CacheException { - localCache.clear(); - cache.removeListener(this); - super.destroy(); - } + @Override + public void destroy() throws CacheException { + localCache.clear(); + cache.removeListener( this ); + super.destroy(); + } - /** - * Brings all data from the distributed cache into our local cache. - */ - private void populateLocalCache() { - Set children = cache.keySet(); - for (Object key : children) - get(key); - } + /** + * Brings all data from the distributed cache into our local cache. + */ + private void populateLocalCache() { + final Set children = cache.keySet(); + for ( Object key : children ) { + get( key ); + } + } - /** - * Monitors cache events and updates the local cache - * - * @param event - */ - @CacheEntryModified - @SuppressWarnings("unused") - public void nodeModified(CacheEntryModifiedEvent event) { - if (!event.isPre()) - localCache.put(event.getKey(), event.getValue()); - } + /** + * Monitors cache events and updates the local cache + * + * @param event The event + */ + @CacheEntryModified + @SuppressWarnings({"unused", "unchecked"}) + public void nodeModified(CacheEntryModifiedEvent event) { + if ( !event.isPre() ) { + localCache.put( event.getKey(), event.getValue() ); + } + } - /** - * Monitors cache events and updates the local cache - * - * @param event - */ - @CacheEntryRemoved - @SuppressWarnings("unused") - public void nodeRemoved(CacheEntryRemovedEvent event) { - if (event.isPre()) return; - localCache.remove(event.getKey()); - } + /** + * Monitors cache events and updates the local cache + * + * @param event The event + */ + @CacheEntryRemoved + @SuppressWarnings("unused") + public void nodeRemoved(CacheEntryRemovedEvent event) { + if ( event.isPre() ) { + return; + } + localCache.remove( event.getKey() ); + } } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampTypeOverrides.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampTypeOverrides.java index c965982ca2..b58ddf3370 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampTypeOverrides.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampTypeOverrides.java @@ -29,21 +29,21 @@ import org.hibernate.cache.infinispan.TypeOverrides; /** * TimestampTypeOverrides. - * + * * @author Galder Zamarreño * @since 3.5 */ public class TimestampTypeOverrides extends TypeOverrides { - @Override - public void validateInfinispanConfiguration(Configuration cfg) throws CacheException { - if (cfg.clustering().cacheMode().isInvalidation()) { - throw new CacheException("Timestamp cache cannot be configured with invalidation"); - } - EvictionStrategy strategy = cfg.eviction().strategy(); - if (!strategy.equals(EvictionStrategy.NONE)) { - throw new CacheException("Timestamp cache cannot be configured with eviction"); - } - } + @Override + public void validateInfinispanConfiguration(Configuration cfg) throws CacheException { + if ( cfg.clustering().cacheMode().isInvalidation() ) { + throw new CacheException( "Timestamp cache cannot be configured with invalidation" ); + } + final EvictionStrategy strategy = cfg.eviction().strategy(); + if ( !strategy.equals( EvictionStrategy.NONE ) ) { + throw new CacheException( "Timestamp cache cannot be configured with eviction" ); + } + } } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampsRegionImpl.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampsRegionImpl.java index fc1d505ed5..2d8aca302d 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampsRegionImpl.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/TimestampsRegionImpl.java @@ -1,89 +1,114 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.cache.infinispan.timestamp; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; import javax.transaction.Transaction; -import org.hibernate.cache.infinispan.util.Caches; import org.infinispan.AdvancedCache; import org.infinispan.context.Flag; -import org.infinispan.notifications.Listener; -import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; -import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; -import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; -import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import org.hibernate.cache.CacheException; import org.hibernate.cache.infinispan.impl.BaseGeneralDataRegion; +import org.hibernate.cache.infinispan.util.Caches; import org.hibernate.cache.spi.RegionFactory; import org.hibernate.cache.spi.TimestampsRegion; /** * Defines the behavior of the timestamps cache region for Infinispan. - * + * * @author Chris Bredesen * @author Galder Zamarreño * @since 3.5 */ public class TimestampsRegionImpl extends BaseGeneralDataRegion implements TimestampsRegion { - private final AdvancedCache removeCache; - private final AdvancedCache timestampsPutCache; + private final AdvancedCache removeCache; + private final AdvancedCache timestampsPutCache; - public TimestampsRegionImpl(AdvancedCache cache, String name, - RegionFactory factory) { - super(cache, name, factory); - this.removeCache = Caches.ignoreReturnValuesCache(cache); + public TimestampsRegionImpl( + AdvancedCache cache, String name, + RegionFactory factory) { + super( cache, name, factory ); + this.removeCache = Caches.ignoreReturnValuesCache( cache ); - // Skip locking when updating timestamps to provide better performance - // under highly concurrent insert scenarios, where update timestamps - // for an entity/collection type are constantly updated, creating - // contention. - // - // The worst it can happen is that an earlier an earlier timestamp - // (i.e. ts=1) will override a later on (i.e. ts=2), so it means that - // in highly concurrent environments, queries might be considered stale - // earlier in time. The upside is that inserts/updates are way faster - // in local set ups. - this.timestampsPutCache = getTimestampsPutCache(cache); - } + // Skip locking when updating timestamps to provide better performance + // under highly concurrent insert scenarios, where update timestamps + // for an entity/collection type are constantly updated, creating + // contention. + // + // The worst it can happen is that an earlier an earlier timestamp + // (i.e. ts=1) will override a later on (i.e. ts=2), so it means that + // in highly concurrent environments, queries might be considered stale + // earlier in time. The upside is that inserts/updates are way faster + // in local set ups. + this.timestampsPutCache = getTimestampsPutCache( cache ); + } - protected AdvancedCache getTimestampsPutCache(AdvancedCache cache) { - return Caches.ignoreReturnValuesCache(cache, Flag.SKIP_LOCKING); - } + protected AdvancedCache getTimestampsPutCache(AdvancedCache cache) { + return Caches.ignoreReturnValuesCache( cache, Flag.SKIP_LOCKING ); + } - @Override - public void evict(Object key) throws CacheException { - // TODO Is this a valid operation on a timestamps cache? - removeCache.remove(key); - } + @Override + public void evict(Object key) throws CacheException { + // TODO Is this a valid operation on a timestamps cache? + removeCache.remove( key ); + } - public void evictAll() throws CacheException { - // TODO Is this a valid operation on a timestamps cache? - Transaction tx = suspend(); - try { - invalidateRegion(); // Invalidate the local region - } finally { - resume(tx); - } - } + @Override + public void evictAll() throws CacheException { + // TODO Is this a valid operation on a timestamps cache? + final Transaction tx = suspend(); + try { + // Invalidate the local region + invalidateRegion(); + } + finally { + resume( tx ); + } + } - public Object get(Object key) throws CacheException { - if (checkValid()) - return cache.get(key); - return null; - } + @Override + public Object get(Object key) throws CacheException { + if ( checkValid() ) { + return cache.get( key ); + } - public void put(final Object key, final Object value) throws CacheException { - try { - // We ensure ASYNC semantics (JBCACHE-1175) and make sure previous - // value is not loaded from cache store cos it's not needed. - timestampsPutCache.put(key, value); - } catch (Exception e) { - throw new CacheException(e); - } - } + return null; + } + + @Override + @SuppressWarnings("unchecked") + public void put(final Object key, final Object value) throws CacheException { + try { + // We ensure ASYNC semantics (JBCACHE-1175) and make sure previous + // value is not loaded from cache store cos it's not needed. + timestampsPutCache.put( key, value ); + } + catch (Exception e) { + throw new CacheException( e ); + } + } } \ No newline at end of file diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/package-info.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/package-info.java new file mode 100644 index 0000000000..6eb29e1bfe --- /dev/null +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/timestamp/package-info.java @@ -0,0 +1,4 @@ +/** + * Internal Infinispan-based implementation of the "update timestamps" cache region + */ +package org.hibernate.cache.infinispan.timestamp; diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/tm/HibernateTransactionManagerLookup.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/tm/HibernateTransactionManagerLookup.java index a64909a1f9..071a827782 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/tm/HibernateTransactionManagerLookup.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/tm/HibernateTransactionManagerLookup.java @@ -21,15 +21,15 @@ */ package org.hibernate.cache.infinispan.tm; -import java.util.Properties; import javax.transaction.TransactionManager; +import java.util.Properties; import org.hibernate.cfg.Settings; import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform; /** * HibernateTransactionManagerLookup. - * + * * @author Galder Zamarreño * @since 3.5 */ @@ -39,9 +39,10 @@ public class HibernateTransactionManagerLookup implements org.infinispan.transac public HibernateTransactionManagerLookup(Settings settings, Properties properties) { this.jtaPlatform = settings != null ? settings.getJtaPlatform() : null; } + @Override public TransactionManager getTransactionManager() throws Exception { return jtaPlatform == null ? null : jtaPlatform.retrieveTransactionManager(); } - + } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/tm/package-info.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/tm/package-info.java new file mode 100644 index 0000000000..c1471e58b8 --- /dev/null +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/tm/package-info.java @@ -0,0 +1,4 @@ +/** + * Internal bridging between Infinispan and Hibernate notions of talking to JTA + */ +package org.hibernate.cache.infinispan.tm; diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandExtensions.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandExtensions.java index 17293a2998..bdcbff9149 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandExtensions.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandExtensions.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.cache.infinispan.util; import org.infinispan.commands.module.ExtendedModuleCommandFactory; @@ -11,18 +34,17 @@ import org.infinispan.commands.module.ModuleCommandInitializer; * @since 4.0 */ public class CacheCommandExtensions implements ModuleCommandExtensions { + final CacheCommandFactory cacheCommandFactory = new CacheCommandFactory(); + final CacheCommandInitializer cacheCommandInitializer = new CacheCommandInitializer(); - final CacheCommandFactory cacheCommandFactory = new CacheCommandFactory(); - final CacheCommandInitializer cacheCommandInitializer = new CacheCommandInitializer(); + @Override + public ExtendedModuleCommandFactory getModuleCommandFactory() { + return cacheCommandFactory; + } - @Override - public ExtendedModuleCommandFactory getModuleCommandFactory() { - return cacheCommandFactory; - } - - @Override - public ModuleCommandInitializer getModuleCommandInitializer() { - return cacheCommandInitializer; - } + @Override + public ModuleCommandInitializer getModuleCommandInitializer() { + return cacheCommandInitializer; + } } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandFactory.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandFactory.java index 8200cdbc68..158ab4fb9f 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandFactory.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandFactory.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.cache.infinispan.util; import java.util.HashMap; @@ -19,45 +42,45 @@ import org.hibernate.cache.infinispan.impl.BaseRegion; * @since 4.0 */ public class CacheCommandFactory implements ExtendedModuleCommandFactory { + private ConcurrentMap allRegions = + new ConcurrentHashMap(); - private ConcurrentMap allRegions = - new ConcurrentHashMap(); + public void addRegion(String regionName, BaseRegion region) { + allRegions.put( regionName, region ); + } - public void addRegion(String regionName, BaseRegion region) { - allRegions.put(regionName, region); - } + public void clearRegions(List regionNames) { + for ( String regionName : regionNames ) { + allRegions.remove( regionName ); + } + } - public void clearRegions(List regionNames) { - for (String regionName : regionNames) - allRegions.remove(regionName); - } + @Override + public Map> getModuleCommands() { + final Map> map = new HashMap>( 3 ); + map.put( CacheCommandIds.EVICT_ALL, EvictAllCommand.class ); + return map; + } - @Override - public Map> getModuleCommands() { - Map> map = new HashMap>(3); - map.put(CacheCommandIds.EVICT_ALL, EvictAllCommand.class); - return map; - } + @Override + public CacheRpcCommand fromStream(byte commandId, Object[] args, String cacheName) { + CacheRpcCommand c; + switch ( commandId ) { + case CacheCommandIds.EVICT_ALL: + c = new EvictAllCommand( cacheName, allRegions.get( cacheName ) ); + break; + default: + throw new IllegalArgumentException( "Not registered to handle command id " + commandId ); + } + c.setParameters( commandId, args ); + return c; + } - @Override - public CacheRpcCommand fromStream(byte commandId, Object[] args, String cacheName) { - CacheRpcCommand c; - switch (commandId) { - case CacheCommandIds.EVICT_ALL: - c = new EvictAllCommand(cacheName, allRegions.get(cacheName)); - break; - default: - throw new IllegalArgumentException("Not registered to handle command id " + commandId); - } - c.setParameters(commandId, args); - return c; - } - - @Override - public ReplicableCommand fromStream(byte commandId, Object[] args) { - // Should not be called while this factory only - // provides cache specific replicable commands. - return null; - } + @Override + public ReplicableCommand fromStream(byte commandId, Object[] args) { + // Should not be called while this factory only + // provides cache specific replicable commands. + return null; + } } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandIds.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandIds.java index 480c939248..e99e778b9f 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandIds.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandIds.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.cache.infinispan.util; /** @@ -7,7 +30,8 @@ package org.hibernate.cache.infinispan.util; * @since 4.0 */ public interface CacheCommandIds { - - byte EVICT_ALL = 120; - + /** + * The "evict all" command id + */ + public static final byte EVICT_ALL = 120; } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandInitializer.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandInitializer.java index aa408eb34c..78cb46faed 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandInitializer.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/CacheCommandInitializer.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.cache.infinispan.util; import org.infinispan.commands.ReplicableCommand; @@ -11,17 +34,17 @@ import org.infinispan.commands.module.ModuleCommandInitializer; */ public class CacheCommandInitializer implements ModuleCommandInitializer { - public EvictAllCommand buildEvictAllCommand(String regionName) { - // No need to pass region factory because no information on that object - // is sent around the cluster. However, when the command factory builds - // and evict all command remotely, it does need to initialize it with - // the right region factory so that it can call it back. - return new EvictAllCommand(regionName); - } + public EvictAllCommand buildEvictAllCommand(String regionName) { + // No need to pass region factory because no information on that object + // is sent around the cluster. However, when the command factory builds + // and evict all command remotely, it does need to initialize it with + // the right region factory so that it can call it back. + return new EvictAllCommand( regionName ); + } - @Override - public void initializeReplicableCommand(ReplicableCommand c, boolean isRemote) { - // No need to initialize... - } + @Override + public void initializeReplicableCommand(ReplicableCommand c, boolean isRemote) { + // No need to initialize... + } } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/Caches.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/Caches.java index 0cef6bdd19..42adb0c333 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/Caches.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/Caches.java @@ -20,17 +20,16 @@ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ - package org.hibernate.cache.infinispan.util; -import org.infinispan.AdvancedCache; -import org.infinispan.context.Flag; -import org.infinispan.remoting.rpc.RpcManager; - import javax.transaction.Status; import javax.transaction.TransactionManager; import java.util.concurrent.Callable; +import org.infinispan.AdvancedCache; +import org.infinispan.context.Flag; +import org.infinispan.remoting.rpc.RpcManager; + /** * Helper for dealing with Infinispan cache instances. * @@ -39,103 +38,118 @@ import java.util.concurrent.Callable; */ public class Caches { - private Caches() { - // Suppresses default constructor, ensuring non-instantiability. - } + private Caches() { + // Suppresses default constructor, ensuring non-instantiability. + } - public static T withinTx(AdvancedCache cache, - Callable c) throws Exception { - // Retrieve transaction manager - return withinTx(cache.getTransactionManager(), c); - } + public static T withinTx( + AdvancedCache cache, + Callable c) throws Exception { + // Retrieve transaction manager + return withinTx( cache.getTransactionManager(), c ); + } - public static T withinTx(TransactionManager tm, - Callable c) throws Exception { - tm.begin(); - try { - return c.call(); - } catch (Exception e) { - tm.setRollbackOnly(); - throw e; - } finally { - if (tm.getStatus() == Status.STATUS_ACTIVE) tm.commit(); - else tm.rollback(); - } - } + public static T withinTx( + TransactionManager tm, + Callable c) throws Exception { + tm.begin(); + try { + return c.call(); + } + catch (Exception e) { + tm.setRollbackOnly(); + throw e; + } + finally { + if ( tm.getStatus() == Status.STATUS_ACTIVE ) { + tm.commit(); + } + else { + tm.rollback(); + } + } + } - public static AdvancedCache localCache(AdvancedCache cache) { - return cache.withFlags(Flag.CACHE_MODE_LOCAL); - } + public static AdvancedCache localCache(AdvancedCache cache) { + return cache.withFlags( Flag.CACHE_MODE_LOCAL ); + } - public static AdvancedCache ignoreReturnValuesCache(AdvancedCache cache) { - return cache.withFlags(Flag.SKIP_CACHE_LOAD, Flag.SKIP_REMOTE_LOOKUP); - } + public static AdvancedCache ignoreReturnValuesCache(AdvancedCache cache) { + return cache.withFlags( Flag.SKIP_CACHE_LOAD, Flag.SKIP_REMOTE_LOOKUP ); + } - public static AdvancedCache ignoreReturnValuesCache( - AdvancedCache cache, Flag extraFlag) { - return cache.withFlags( - Flag.SKIP_CACHE_LOAD, Flag.SKIP_REMOTE_LOOKUP, extraFlag); - } + public static AdvancedCache ignoreReturnValuesCache( + AdvancedCache cache, Flag extraFlag) { + return cache.withFlags( + Flag.SKIP_CACHE_LOAD, Flag.SKIP_REMOTE_LOOKUP, extraFlag + ); + } - public static AdvancedCache asyncWriteCache(AdvancedCache cache, - Flag extraFlag) { - return cache.withFlags( - Flag.SKIP_CACHE_LOAD, - Flag.SKIP_REMOTE_LOOKUP, - Flag.FORCE_ASYNCHRONOUS, - extraFlag); - } + public static AdvancedCache asyncWriteCache( + AdvancedCache cache, + Flag extraFlag) { + return cache.withFlags( + Flag.SKIP_CACHE_LOAD, + Flag.SKIP_REMOTE_LOOKUP, + Flag.FORCE_ASYNCHRONOUS, + extraFlag + ); + } - public static AdvancedCache failSilentWriteCache(AdvancedCache cache) { - return cache.withFlags( - Flag.FAIL_SILENTLY, - Flag.ZERO_LOCK_ACQUISITION_TIMEOUT, - Flag.SKIP_CACHE_LOAD, - Flag.SKIP_REMOTE_LOOKUP); - } + public static AdvancedCache failSilentWriteCache(AdvancedCache cache) { + return cache.withFlags( + Flag.FAIL_SILENTLY, + Flag.ZERO_LOCK_ACQUISITION_TIMEOUT, + Flag.SKIP_CACHE_LOAD, + Flag.SKIP_REMOTE_LOOKUP + ); + } - public static AdvancedCache failSilentWriteCache(AdvancedCache cache, - Flag extraFlag) { - return cache.withFlags( - Flag.FAIL_SILENTLY, - Flag.ZERO_LOCK_ACQUISITION_TIMEOUT, - Flag.SKIP_CACHE_LOAD, - Flag.SKIP_REMOTE_LOOKUP, - extraFlag); - } + public static AdvancedCache failSilentWriteCache( + AdvancedCache cache, + Flag extraFlag) { + return cache.withFlags( + Flag.FAIL_SILENTLY, + Flag.ZERO_LOCK_ACQUISITION_TIMEOUT, + Flag.SKIP_CACHE_LOAD, + Flag.SKIP_REMOTE_LOOKUP, + extraFlag + ); + } - public static AdvancedCache failSilentReadCache(AdvancedCache cache) { - return cache.withFlags( - Flag.FAIL_SILENTLY, - Flag.ZERO_LOCK_ACQUISITION_TIMEOUT); - } + public static AdvancedCache failSilentReadCache(AdvancedCache cache) { + return cache.withFlags( + Flag.FAIL_SILENTLY, + Flag.ZERO_LOCK_ACQUISITION_TIMEOUT + ); + } - public static void broadcastEvictAll(AdvancedCache cache) { - RpcManager rpcManager = cache.getRpcManager(); - if (rpcManager != null) { - // Only broadcast evict all if it's clustered - CacheCommandInitializer factory = cache.getComponentRegistry() - .getComponent(CacheCommandInitializer.class); - boolean isSync = isSynchronousCache(cache); + public static void broadcastEvictAll(AdvancedCache cache) { + final RpcManager rpcManager = cache.getRpcManager(); + if ( rpcManager != null ) { + // Only broadcast evict all if it's clustered + final CacheCommandInitializer factory = cache.getComponentRegistry() + .getComponent( CacheCommandInitializer.class ); + final boolean isSync = isSynchronousCache( cache ); - EvictAllCommand cmd = factory.buildEvictAllCommand(cache.getName()); - rpcManager.broadcastRpcCommand(cmd, isSync); - } - } + final EvictAllCommand cmd = factory.buildEvictAllCommand( cache.getName() ); + rpcManager.broadcastRpcCommand( cmd, isSync ); + } + } - public static boolean isInvalidationCache(AdvancedCache cache) { - return cache.getCacheConfiguration() - .clustering().cacheMode().isInvalidation(); - } + public static boolean isInvalidationCache(AdvancedCache cache) { + return cache.getCacheConfiguration() + .clustering().cacheMode().isInvalidation(); + } - public static boolean isSynchronousCache(AdvancedCache cache) { - return cache.getCacheConfiguration() - .clustering().cacheMode().isSynchronous(); - } + public static boolean isSynchronousCache(AdvancedCache cache) { + return cache.getCacheConfiguration() + .clustering().cacheMode().isSynchronous(); + } - public static boolean isClustered(AdvancedCache cache) { - return cache.getCacheConfiguration() - .clustering().cacheMode().isClustered(); - } + public static boolean isClustered(AdvancedCache cache) { + return cache.getCacheConfiguration() + .clustering().cacheMode().isClustered(); + } } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/EvictAllCommand.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/EvictAllCommand.java index 98bb888e8f..5ea96d28aa 100644 --- a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/EvictAllCommand.java +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/EvictAllCommand.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.cache.infinispan.util; import org.infinispan.commands.remote.BaseRpcCommand; @@ -13,41 +36,42 @@ import org.hibernate.cache.infinispan.impl.BaseRegion; */ public class EvictAllCommand extends BaseRpcCommand { - private final BaseRegion region; + private final BaseRegion region; - public EvictAllCommand(String regionName, BaseRegion region) { - super(regionName); // region name and cache names are the same... - this.region = region; - } + public EvictAllCommand(String regionName, BaseRegion region) { + // region name and cache names are the same... + super( regionName ); + this.region = region; + } - public EvictAllCommand(String regionName) { - this(regionName, null); - } + public EvictAllCommand(String regionName) { + this( regionName, null ); + } - @Override - public Object perform(InvocationContext ctx) throws Throwable { - region.invalidateRegion(); - return null; - } + @Override + public Object perform(InvocationContext ctx) throws Throwable { + region.invalidateRegion(); + return null; + } - @Override - public byte getCommandId() { - return CacheCommandIds.EVICT_ALL; - } + @Override + public byte getCommandId() { + return CacheCommandIds.EVICT_ALL; + } - @Override - public Object[] getParameters() { - return new Object[0]; - } + @Override + public Object[] getParameters() { + return new Object[0]; + } - @Override - public void setParameters(int commandId, Object[] parameters) { - // No-op - } + @Override + public void setParameters(int commandId, Object[] parameters) { + // No-op + } - @Override - public boolean isReturnValueExpected() { - return false; - } + @Override + public boolean isReturnValueExpected() { + return false; + } } diff --git a/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/package-info.java b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/package-info.java new file mode 100644 index 0000000000..15126a21c9 --- /dev/null +++ b/hibernate-infinispan/src/main/java/org/hibernate/cache/infinispan/util/package-info.java @@ -0,0 +1,4 @@ +/** + * Internal utilities for the Infinispan integration + */ +package org.hibernate.cache.infinispan.util; From ad1d1ab8b4fa166de59bfcfbe57622e71b2448f9 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Wed, 1 May 2013 22:42:16 -0500 Subject: [PATCH 53/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../org/hibernate/jpa/AvailableSettings.java | 39 ++++++- .../jpa/HibernateEntityManagerFactory.java | 8 ++ .../jpa/HibernatePersistenceProvider.java | 6 +- .../java/org/hibernate/jpa/QueryHints.java | 54 ++++++++-- .../org/hibernate/jpa/SchemaGenAction.java | 10 ++ .../boot/archive/internal/ArchiveHelper.java | 102 ++++++++++-------- .../internal/ExplodedArchiveDescriptor.java | 9 ++ .../JarFileBasedArchiveDescriptor.java | 11 +- .../JarInputStreamBasedArchiveDescriptor.java | 9 +- .../JarProtocolArchiveDescriptor.java | 9 +- .../StandardArchiveDescriptorFactory.java | 5 + .../boot/archive/internal/package-info.java | 4 + .../spi/AbstractArchiveDescriptor.java | 3 + .../jpa/boot/archive/spi/ArchiveContext.java | 20 ++++ .../boot/archive/spi/ArchiveDescriptor.java | 5 + .../archive/spi/ArchiveDescriptorFactory.java | 41 ++++++- .../jpa/boot/archive/spi/ArchiveEntry.java | 6 +- .../boot/archive/spi/ArchiveEntryHandler.java | 6 ++ .../boot/archive/spi/ArchiveException.java | 17 ++- .../jpa/boot/archive/spi/package-info.java | 15 +++ .../java/org/hibernate/jpa/package-info.java | 4 + 21 files changed, 316 insertions(+), 67 deletions(-) create mode 100644 hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/package-info.java create mode 100644 hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/package-info.java create mode 100644 hibernate-entitymanager/src/main/java/org/hibernate/jpa/package-info.java diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/AvailableSettings.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/AvailableSettings.java index 3cc0c0c108..86fe0150be 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/AvailableSettings.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/AvailableSettings.java @@ -23,9 +23,6 @@ */ package org.hibernate.jpa; - -import org.hibernate.internal.util.StringHelper; - /** * Defines the available HEM settings, both JPA-defined as well as Hibernate-specific *

      @@ -444,7 +441,10 @@ public interface AvailableSettings { * Consider this as experimental * It is not recommended to set up this property, the configuration is stored * in the JNDI in a serialized form + * + * @deprecated Configuration going away. */ + @Deprecated public static final String CONFIGURATION_JNDI_NAME = "hibernate.ejb.configuration_jndi_name"; /** @@ -463,13 +463,21 @@ public interface AvailableSettings { /** * List of classes names * Internal use only + * + * @deprecated Was never intended for external use */ + @Deprecated + @SuppressWarnings("UnusedDeclaration") public static final String CLASS_NAMES = "hibernate.ejb.classes"; /** * List of annotated packages * Internal use only + * + * @deprecated Was never intended for external use */ + @Deprecated + @SuppressWarnings("UnusedDeclaration") public static final String PACKAGE_NAMES = "hibernate.ejb.packages"; /** @@ -509,9 +517,34 @@ public interface AvailableSettings { public static final String XML_FILE_NAMES = "hibernate.ejb.xml_files"; public static final String HBXML_FILES = "hibernate.hbmxml.files"; public static final String LOADED_CLASSES = "hibernate.ejb.loaded.classes"; + + /** + * Deprecated + * + * @deprecated Use {@link org.hibernate.cfg.AvailableSettings#JACC_CONTEXT_ID} instead + */ + @Deprecated public static final String JACC_CONTEXT_ID = org.hibernate.cfg.AvailableSettings.JACC_CONTEXT_ID; + + /** + * Deprecated + * + * @deprecated Use {@link org.hibernate.cfg.AvailableSettings#JACC_PREFIX} instead + */ + @Deprecated public static final String JACC_PREFIX = org.hibernate.cfg.AvailableSettings.JACC_PREFIX; + + /** + * Deprecated + * + * @deprecated Use {@link org.hibernate.cfg.AvailableSettings#JACC_ENABLED} instead + */ + @Deprecated public static final String JACC_ENABLED = org.hibernate.cfg.AvailableSettings.JACC_ENABLED; + + /** + * Used to pass along the name of the persistence unit. + */ public static final String PERSISTENCE_UNIT_NAME = "hibernate.ejb.persistenceUnitName"; } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/HibernateEntityManagerFactory.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/HibernateEntityManagerFactory.java index 0e9e5c36dd..34314cd5ca 100755 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/HibernateEntityManagerFactory.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/HibernateEntityManagerFactory.java @@ -42,5 +42,13 @@ public interface HibernateEntityManagerFactory extends EntityManagerFactory, Ser */ public SessionFactory getSessionFactory(); + /** + * Retrieve the EntityTypeImpl by name. Use of the Hibernate O/RM notion the "entity name" allows support + * for non-strictly-JPA models to be used in JPA APIs + * + * @param entityName The entity name + * + * @return The EntityTypeImpl + */ public EntityTypeImpl getEntityTypeByName(String entityName); } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/HibernatePersistenceProvider.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/HibernatePersistenceProvider.java index a20a468232..2226d6555c 100755 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/HibernatePersistenceProvider.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/HibernatePersistenceProvider.java @@ -80,7 +80,7 @@ public class HibernatePersistenceProvider implements PersistenceProvider { final Map integration = wrap( properties ); final List units; try { - units = PersistenceXmlParser.locatePersistenceUnits( integration ); + units = PersistenceXmlParser.locatePersistenceUnits( integration ); } catch (RuntimeException e) { log.debug( "Unable to locate persistence units", e ); @@ -106,7 +106,7 @@ public class HibernatePersistenceProvider implements PersistenceProvider { persistenceUnitName ); - boolean matches = persistenceUnitName == null || persistenceUnit.getName().equals( persistenceUnitName ); + final boolean matches = persistenceUnitName == null || persistenceUnit.getName().equals( persistenceUnitName ); if ( !matches ) { log.debug( "Excluding from consideration due to name mis-match" ); continue; @@ -146,7 +146,7 @@ public class HibernatePersistenceProvider implements PersistenceProvider { public void generateSchema(PersistenceUnitInfo info, Map map) { log.tracef( "Starting generateSchema : PUI.name=%s", info.getPersistenceUnitName() ); - EntityManagerFactoryBuilder builder = Bootstrap.getEntityManagerFactoryBuilder( info, map ); + final EntityManagerFactoryBuilder builder = Bootstrap.getEntityManagerFactoryBuilder( info, map ); builder.generateSchema(); } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/QueryHints.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/QueryHints.java index e06fd91fdf..a2c35a0517 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/QueryHints.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/QueryHints.java @@ -26,23 +26,62 @@ import java.util.HashSet; import java.util.Set; /** - * TODO : javadoc + * Defines the supported JPA query hints * * @author Steve Ebersole */ public class QueryHints { /** - * @deprecated HINT_TIMEOUT (org.hibernate.timeout), - * instead use SPEC_HINT_TIMEOUT (javax.persistence.query.timeout) + * The hint key for specifying a query timeout per Hibernate O/RM, which defines the timeout in seconds. + * + * @deprecated use {@link #SPEC_HINT_TIMEOUT} instead + */ + @Deprecated + public static final String HINT_TIMEOUT = "org.hibernate.timeout"; + + /** + * The hint key for specifying a query timeout per JPA, which defines the timeout in milliseconds + */ + public static final String SPEC_HINT_TIMEOUT = "javax.persistence.query.timeout"; + + /** + * The hint key for specifying a comment which is to be embedded into the SQL sent to the database. */ - public static final String HINT_TIMEOUT = "org.hibernate.timeout"; // Query timeout in seconds - public static final String SPEC_HINT_TIMEOUT = "javax.persistence.query.timeout"; // timeout in milliseconds public static final String HINT_COMMENT = "org.hibernate.comment"; + + /** + * The hint key for specifying a JDBC fetch size, used when executing the resulting SQL. + */ public static final String HINT_FETCH_SIZE = "org.hibernate.fetchSize"; - public static final String HINT_CACHE_REGION = "org.hibernate.cacheRegion"; + + /** + * The hint key for specifying whether the query results should be cached for the next (cached) execution of the + * "same query". + */ public static final String HINT_CACHEABLE = "org.hibernate.cacheable"; + + /** + * The hint key for specifying the name of the cache region (within Hibernate's query result cache region) + * to use for storing the query results. + */ + public static final String HINT_CACHE_REGION = "org.hibernate.cacheRegion"; + + /** + * The hint key for specifying that objects loaded into the persistence context as a result of this query execution + * should be associated with the persistence context as read-only. + */ public static final String HINT_READONLY = "org.hibernate.readOnly"; + + /** + * The hint key for specifying the cache mode ({@link org.hibernate.CacheMode}) to be in effect for the + * execution of the hinted query. + */ public static final String HINT_CACHE_MODE = "org.hibernate.cacheMode"; + + /** + * The hint key for specifying the flush mode ({@link org.hibernate.FlushMode}) to be in effect for the + * execution of the hinted query. + */ public static final String HINT_FLUSH_MODE = "org.hibernate.flushMode"; private static final Set HINTS = buildHintsSet(); @@ -64,4 +103,7 @@ public class QueryHints { public static Set getDefinedHints() { return HINTS; } + + private QueryHints() { + } } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/SchemaGenAction.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/SchemaGenAction.java index 1a9a63b771..3590f9cf74 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/SchemaGenAction.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/SchemaGenAction.java @@ -93,10 +93,20 @@ public enum SchemaGenAction { ); } + /** + * Does this action include creations? + * + * @return {@code true} if this action is either {@link #CREATE} or {@link #BOTH} + */ public boolean includesCreate() { return this == CREATE || this == BOTH; } + /** + * Does this action include drops? + * + * @return {@code true} if this action is either {@link #DROP} or {@link #BOTH} + */ public boolean includesDrop() { return this == DROP || this == BOTH; } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/ArchiveHelper.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/ArchiveHelper.java index 76caf4db9c..1b5c765bb8 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/ArchiveHelper.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/ArchiveHelper.java @@ -36,6 +36,8 @@ import org.jboss.logging.Logger; import org.hibernate.jpa.boot.archive.spi.ArchiveException; /** + * Helper for dealing with archives + * * @author Emmanuel Bernard * @author Steve Ebersole */ @@ -54,32 +56,36 @@ public class ArchiveHelper { public static URL getJarURLFromURLEntry(URL url, String entry) throws IllegalArgumentException { URL jarUrl; String file = url.getFile(); - if ( ! entry.startsWith( "/" ) ) entry = "/" + entry; + if ( ! entry.startsWith( "/" ) ) { + entry = "/" + entry; + } file = file.substring( 0, file.length() - entry.length() ); - if ( file.endsWith( "!" ) ) file = file.substring( 0, file.length() - 1 ); + if ( file.endsWith( "!" ) ) { + file = file.substring( 0, file.length() - 1 ); + } try { - String protocol = url.getProtocol(); + final String protocol = url.getProtocol(); - if ( "jar".equals( protocol ) - || "wsjar".equals( protocol ) ) { //Websphere has it's own way + if ( "jar".equals( protocol ) || "wsjar".equals( protocol ) ) { //Original URL is like jar:protocol + //WebSphere has it's own way jarUrl = new URL( file ); if ( "file".equals( jarUrl.getProtocol() ) ) { - //not escaped, need to voodoo if ( file.indexOf( ' ' ) != -1 ) { - //not escaped, need to voodoo - jarUrl = new File( jarUrl.getFile() ).toURI().toURL(); //goes by toURI to escape the path + //not escaped, need to voodoo; goes by toURI to escape the path + jarUrl = new File( jarUrl.getFile() ).toURI().toURL(); } - } //otherwise left as is + } } - else if ( "zip".equals( protocol ) //Weblogic has it's own way - || "code-source".equals( url.getProtocol() ) //OC4J prevent ejb.jar access (ie everything without path) - || "file".equals( protocol ) //if no wrapping is done - ) { + else if ( "zip".equals( protocol ) + //OC4J prevent ejb.jar access (ie everything without path) + || "code-source".equals( url.getProtocol() ) + //if no wrapping is done + || "file".equals( protocol ) ) { //we have extracted the zip file, so it should be read as a file if ( file.indexOf( ' ' ) != -1 ) { - //not escaped, need to voodoo - jarUrl = new File(file).toURI().toURL(); //goes by toURI to escape the path + //not escaped, need to voodoo; goes by toURI to escape the path + jarUrl = new File(file).toURI().toURL(); } else { jarUrl = new File(file).toURL(); @@ -92,7 +98,7 @@ public class ArchiveHelper { jarUrl = new URL( protocol, url.getHost(), url.getPort(), file ); } //HHH-6442: Arquilian - catch ( final MalformedURLException murle ) { + catch ( final MalformedURLException e ) { //Just use the provided URL as-is, likely it has a URLStreamHandler //associated w/ the instance jarUrl = url; @@ -104,13 +110,17 @@ public class ArchiveHelper { "Unable to determine JAR Url from " + url + ". Cause: " + e.getMessage() ); } - log.trace("JAR URL from URL Entry: " + url + " >> " + jarUrl); + log.trace( "JAR URL from URL Entry: " + url + " >> " + jarUrl ); return jarUrl; } /** * get the URL from a given path string * + * @param jarPath The path that represents a URL + * + * @return The resolved URL reference + * * @throws IllegalArgumentException is something goes wrong */ public static URL getURLFromPath(String jarPath) { @@ -131,30 +141,17 @@ public class ArchiveHelper { return jarUrl; } - public static String unqualifiedJarFileName(URL jarUrl) { - // todo : weak algorithm subject to AOOBE - String fileName = jarUrl.getFile(); - int exclamation = fileName.lastIndexOf( "!" ); - if (exclamation != -1) { - fileName = fileName.substring( 0, exclamation ); - } - - int slash = fileName.lastIndexOf( "/" ); - if ( slash != -1 ) { - fileName = fileName.substring( - fileName.lastIndexOf( "/" ) + 1, - fileName.length() - ); - } - - if ( fileName.length() > 4 && fileName.endsWith( "ar" ) && fileName.charAt( fileName.length() - 4 ) == '.' ) { - fileName = fileName.substring( 0, fileName.length() - 4 ); - } - - return fileName; - } - - public static byte[] getBytesFromInputStreamSafely(InputStream inputStream) { + /** + * Extracts the bytes out of an InputStream. This form is the same as {@link #getBytesFromInputStream} + * except that any {@link IOException} are wrapped as (runtime) {@link ArchiveException} + * + * @param inputStream The stream from which to extract bytes. + * + * @return The bytes + * + * @throws ArchiveException Indicates a problem accessing the stream + */ + public static byte[] getBytesFromInputStreamSafely(InputStream inputStream) throws ArchiveException { try { return getBytesFromInputStream( inputStream ); } @@ -163,18 +160,30 @@ public class ArchiveHelper { } } + /** + * Extracts the bytes out of an InputStream. + * + * @param inputStream The stream from which to extract bytes. + * + * @return The bytes + * + * @throws IOException Indicates a problem accessing the stream + * + * @see #getBytesFromInputStreamSafely(java.io.InputStream) + */ public static byte[] getBytesFromInputStream(InputStream inputStream) throws IOException { // Optimized by HHH-7835 int size; - List data = new LinkedList(); - int bufferSize = 4096; + final List data = new LinkedList(); + final int bufferSize = 4096; byte[] tmpByte = new byte[bufferSize]; int offset = 0; int total = 0; for ( ;; ) { size = inputStream.read( tmpByte, offset, bufferSize - offset ); - if ( size == -1 ) + if ( size == -1 ) { break; + } offset += size; @@ -186,7 +195,7 @@ public class ArchiveHelper { } } - byte[] result = new byte[total + offset]; + final byte[] result = new byte[total + offset]; int count = 0; for ( byte[] arr : data ) { System.arraycopy( arr, 0, result, count * arr.length, arr.length ); @@ -196,4 +205,7 @@ public class ArchiveHelper { return result; } + + private ArchiveHelper() { + } } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/ExplodedArchiveDescriptor.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/ExplodedArchiveDescriptor.java index 50a64a1a2f..2b5fed3ac9 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/ExplodedArchiveDescriptor.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/ExplodedArchiveDescriptor.java @@ -43,6 +43,8 @@ import org.hibernate.jpa.boot.spi.InputStreamAccess; import org.hibernate.jpa.internal.EntityManagerMessageLogger; /** + * Descriptor for exploded (directory) archives + * * @author Steve Ebersole */ public class ExplodedArchiveDescriptor extends AbstractArchiveDescriptor { @@ -51,6 +53,13 @@ public class ExplodedArchiveDescriptor extends AbstractArchiveDescriptor { ExplodedArchiveDescriptor.class.getName() ); + /** + * Constructs an ExplodedArchiveDescriptor + * + * @param archiveDescriptorFactory The factory creating this + * @param archiveUrl The directory URL + * @param entryBasePrefix the base (within the url) that described the prefix for entries within the archive + */ public ExplodedArchiveDescriptor( ArchiveDescriptorFactory archiveDescriptorFactory, URL archiveUrl, diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarFileBasedArchiveDescriptor.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarFileBasedArchiveDescriptor.java index d601d69ae2..259647b041 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarFileBasedArchiveDescriptor.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarFileBasedArchiveDescriptor.java @@ -55,6 +55,13 @@ public class JarFileBasedArchiveDescriptor extends AbstractArchiveDescriptor { JarFileBasedArchiveDescriptor.class.getName() ); + /** + * Constructs a JarFileBasedArchiveDescriptor + * + * @param archiveDescriptorFactory The factory creating this + * @param archiveUrl The url to the JAR file + * @param entry The prefix for entries within the JAR url + */ public JarFileBasedArchiveDescriptor( ArchiveDescriptorFactory archiveDescriptorFactory, URL archiveUrl, @@ -87,7 +94,7 @@ public class JarFileBasedArchiveDescriptor extends AbstractArchiveDescriptor { // This algorithm assumes that the zipped file is only the URL root (including entry), not // just any random entry try { - InputStream is = new BufferedInputStream( jarFile.getInputStream( zipEntry ) ); + final InputStream is = new BufferedInputStream( jarFile.getInputStream( zipEntry ) ); try { final JarInputStream jarInputStream = new JarInputStream( is ); ZipEntry subZipEntry = jarInputStream.getNextEntry(); @@ -173,7 +180,7 @@ public class JarFileBasedArchiveDescriptor extends AbstractArchiveDescriptor { private JarFile resolveJarFileReference() { try { - String filePart = getArchiveUrl().getFile(); + final String filePart = getArchiveUrl().getFile(); if ( filePart != null && filePart.indexOf( ' ' ) != -1 ) { // unescaped (from the container), keep as is return new JarFile( getArchiveUrl().getFile() ); diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarInputStreamBasedArchiveDescriptor.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarInputStreamBasedArchiveDescriptor.java index 3b7b338535..6a39400040 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarInputStreamBasedArchiveDescriptor.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarInputStreamBasedArchiveDescriptor.java @@ -52,6 +52,13 @@ public class JarInputStreamBasedArchiveDescriptor extends AbstractArchiveDescrip JarInputStreamBasedArchiveDescriptor.class.getName() ); + /** + * Constructs a JarInputStreamBasedArchiveDescriptor + * + * @param archiveDescriptorFactory The factory creating this + * @param url The url to the JAR file + * @param entry The prefix for entries within the JAR url + */ public JarInputStreamBasedArchiveDescriptor( ArchiveDescriptorFactory archiveDescriptorFactory, URL url, @@ -74,7 +81,7 @@ public class JarInputStreamBasedArchiveDescriptor extends AbstractArchiveDescrip try { JarEntry jarEntry; while ( ( jarEntry = jarInputStream.getNextJarEntry() ) != null ) { - String jarEntryName = jarEntry.getName(); + final String jarEntryName = jarEntry.getName(); if ( getEntryBasePrefix() != null && ! jarEntryName.startsWith( getEntryBasePrefix() ) ) { continue; } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarProtocolArchiveDescriptor.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarProtocolArchiveDescriptor.java index 4eaa7d8748..d25c981308 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarProtocolArchiveDescriptor.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/JarProtocolArchiveDescriptor.java @@ -38,6 +38,13 @@ import org.hibernate.jpa.boot.archive.spi.ArchiveDescriptorFactory; public class JarProtocolArchiveDescriptor implements ArchiveDescriptor { private final ArchiveDescriptor delegateDescriptor; + /** + * Constructs a JarProtocolArchiveDescriptor + * + * @param archiveDescriptorFactory The factory creating this + * @param url The url to the JAR file + * @param incomingEntry The prefix for entries within the JAR url + */ public JarProtocolArchiveDescriptor( ArchiveDescriptorFactory archiveDescriptorFactory, URL url, @@ -60,7 +67,7 @@ public class JarProtocolArchiveDescriptor implements ArchiveDescriptor { subEntry = urlFile.substring( subEntryIndex + 1 ); } - URL fileUrl = archiveDescriptorFactory.getJarURLFromURLEntry( url, subEntry ); + final URL fileUrl = archiveDescriptorFactory.getJarURLFromURLEntry( url, subEntry ); delegateDescriptor = archiveDescriptorFactory.buildArchiveDescriptor( fileUrl, subEntry ); } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/StandardArchiveDescriptorFactory.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/StandardArchiveDescriptorFactory.java index e502570140..5b974c2a12 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/StandardArchiveDescriptorFactory.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/StandardArchiveDescriptorFactory.java @@ -32,10 +32,15 @@ import org.hibernate.jpa.boot.archive.spi.ArchiveDescriptor; import org.hibernate.jpa.boot.archive.spi.ArchiveDescriptorFactory; /** + * Standard implementation of ArchiveDescriptorFactory + * * @author Emmanuel Bernard * @author Steve Ebersole */ public class StandardArchiveDescriptorFactory implements ArchiveDescriptorFactory { + /** + * Singleton access + */ public static final StandardArchiveDescriptorFactory INSTANCE = new StandardArchiveDescriptorFactory(); @Override diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/package-info.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/package-info.java new file mode 100644 index 0000000000..7fe8de9a17 --- /dev/null +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/internal/package-info.java @@ -0,0 +1,4 @@ +/** + * The internals of archive scanning support + */ +package org.hibernate.jpa.boot.archive.internal; diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/AbstractArchiveDescriptor.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/AbstractArchiveDescriptor.java index 00f92c6a0b..4e69a02f6c 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/AbstractArchiveDescriptor.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/AbstractArchiveDescriptor.java @@ -33,6 +33,8 @@ import org.hibernate.jpa.boot.archive.internal.ArchiveHelper; import org.hibernate.jpa.boot.spi.InputStreamAccess; /** + * Base support for ArchiveDescriptor implementors. + * * @author Steve Ebersole */ public abstract class AbstractArchiveDescriptor implements ArchiveDescriptor { @@ -57,6 +59,7 @@ public abstract class AbstractArchiveDescriptor implements ArchiveDescriptor { return entryBasePrefix.startsWith( "/" ) ? entryBasePrefix.substring( 1 ) : entryBasePrefix; } + @SuppressWarnings("UnusedDeclaration") protected ArchiveDescriptorFactory getArchiveDescriptorFactory() { return archiveDescriptorFactory; } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveContext.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveContext.java index 8674cc6bb5..eeea27eca4 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveContext.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveContext.java @@ -26,12 +26,32 @@ package org.hibernate.jpa.boot.archive.spi; import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor; /** + * Describes the context for visiting the entries within an archive + * * @author Steve Ebersole */ public interface ArchiveContext { + /** + * The persistence-unit descriptor which led to this archive being scanned. + * + * @return The persistence-unit descriptor + */ public PersistenceUnitDescriptor getPersistenceUnitDescriptor(); + /** + * Is the archive described (and being visited) the root url for the persistence-unit? + * + * @return {@code true} if it is the root url + */ public boolean isRootUrl(); + /** + * Get the handler for the given entry, which generally is indicated by the entry type (a {@code .class} file, a + * mapping file, etc). + * + * @param entry The archive entry + * + * @return The appropriate handler for the entry + */ public ArchiveEntryHandler obtainArchiveEntryHandler(ArchiveEntry entry); } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveDescriptor.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveDescriptor.java index b9d07dee0d..8cd12792b2 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveDescriptor.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveDescriptor.java @@ -30,5 +30,10 @@ package org.hibernate.jpa.boot.archive.spi; * @author Emmanuel Bernard */ public interface ArchiveDescriptor { + /** + * Perform visitation using the given context + * + * @param archiveContext The visitation context + */ public void visitArchive(ArchiveContext archiveContext); } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveDescriptorFactory.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveDescriptorFactory.java index 441b531b25..937a34d546 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveDescriptorFactory.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveDescriptorFactory.java @@ -31,9 +31,48 @@ import java.net.URL; * @author Steve Ebersole */ public interface ArchiveDescriptorFactory { + /** + * Build a descriptor of the archive indicated by the given url + * + * @param url The url to the archive + * + * @return The descriptor + */ public ArchiveDescriptor buildArchiveDescriptor(URL url); - public ArchiveDescriptor buildArchiveDescriptor(URL jarUrl, String entry); + /** + * Build a descriptor of the archive indicated by the path relative to the given url + * + * @param url The url to the archive + * @param path The path within the given url that refers to the archive + * + * @return The descriptor + */ + public ArchiveDescriptor buildArchiveDescriptor(URL url, String path); + + /** + * Given a URL which defines an entry within a JAR (really any "bundled archive" such as a jar file, zip, etc) + * and an entry within that JAR, find the URL to the JAR itself. + * + * @param url The URL to an entry within a JAR + * @param entry The entry that described the thing referred to by the URL relative to the JAR + * + * @return The URL to the JAR + * + * @throws IllegalArgumentException Generally indicates a problem with malformed urls. + */ public URL getJarURLFromURLEntry(URL url, String entry) throws IllegalArgumentException; + + /** + * Not used! + * + * @param jarPath The jar path + * + * @return The url from the path? + * + * @deprecated Not used! + */ + @Deprecated + @SuppressWarnings("UnusedDeclaration") public URL getURLFromPath(String jarPath); } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveEntry.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveEntry.java index 7d7e9185e0..eeaaf85f79 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveEntry.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveEntry.java @@ -34,7 +34,7 @@ public interface ArchiveEntry { /** * Get the entry's name * - * @return + * @return The name */ public String getName(); @@ -42,14 +42,14 @@ public interface ArchiveEntry { * Get the relative name of the entry within the archive. Typically what we are looking for here is * the ClassLoader resource lookup name. * - * @return + * @return The name relative to the archive root */ public String getNameWithinArchive(); /** * Get access to the stream for the entry * - * @return + * @return Obtain stream access to the entry */ public InputStreamAccess getStreamAccess(); } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveEntryHandler.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveEntryHandler.java index 3fce3402c0..3110b78c87 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveEntryHandler.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveEntryHandler.java @@ -29,5 +29,11 @@ package org.hibernate.jpa.boot.archive.spi; * @author Steve Ebersole */ public interface ArchiveEntryHandler { + /** + * Handle the entry + * + * @param entry The entry to handle + * @param context The visitation context + */ public void handleEntry(ArchiveEntry entry, ArchiveContext context); } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveException.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveException.java index 1257502318..204ac79b00 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveException.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/ArchiveException.java @@ -26,14 +26,27 @@ package org.hibernate.jpa.boot.archive.spi; import org.hibernate.HibernateException; /** + * Indicates a problem accessing or visiting the archive + * * @author Steve Ebersole */ public class ArchiveException extends HibernateException { + /** + * Constructs an ArchiveException + * + * @param message Message explaining the exception condition + */ public ArchiveException(String message) { super( message ); } - public ArchiveException(String message, Throwable root) { - super( message, root ); + /** + * Constructs an ArchiveException + * + * @param message Message explaining the exception condition + * @param cause The underlying cause + */ + public ArchiveException(String message, Throwable cause) { + super( message, cause ); } } diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/package-info.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/package-info.java new file mode 100644 index 0000000000..0f7106647d --- /dev/null +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/boot/archive/spi/package-info.java @@ -0,0 +1,15 @@ +/** + * Defines the SPI for support of "scanning" of "archives". + *

      + * Scanning might mean:

        + *
      • searching for classes/packages that define certain interfaces
      • + *
      • locating named resources
      • + *
      + * And "archive" might mean:
        + *
      • a {@code .jar} file
      • + *
      • an exploded directory
      • + *
      • an OSGi bundle
      • + *
      • etc
      • + *
      + */ +package org.hibernate.jpa.boot.archive.spi; diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/package-info.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/package-info.java new file mode 100644 index 0000000000..36f0de3969 --- /dev/null +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/package-info.java @@ -0,0 +1,4 @@ +/** + * Defines Hibernate implementation of Java Persistence specification. + */ +package org.hibernate.jpa; From 364a47f2c746a5eeb1642102580a9daa8bc27fc9 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Thu, 2 May 2013 10:01:16 -0500 Subject: [PATCH 54/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../org/hibernate/envers/AuditJoinTable.java | 43 +- .../org/hibernate/envers/AuditMappedBy.java | 26 +- .../org/hibernate/envers/AuditOverride.java | 46 +- .../org/hibernate/envers/AuditOverrides.java | 28 +- .../org/hibernate/envers/AuditReader.java | 358 ++--- .../hibernate/envers/AuditReaderFactory.java | 75 +- .../java/org/hibernate/envers/AuditTable.java | 26 +- .../java/org/hibernate/envers/Audited.java | 52 +- .../CrossTypeRevisionChangesReader.java | 122 +- .../envers/DefaultRevisionEntity.java | 98 +- ...rackingModifiedEntitiesRevisionEntity.java | 97 +- .../EntityTrackingRevisionListener.java | 50 +- .../hibernate/envers/ModificationStore.java | 6 +- .../hibernate/envers/ModifiedEntityNames.java | 24 + .../java/org/hibernate/envers/NotAudited.java | 6 +- .../envers/RelationTargetAuditMode.java | 4 +- .../org/hibernate/envers/RevisionEntity.java | 12 +- .../hibernate/envers/RevisionListener.java | 18 +- .../org/hibernate/envers/RevisionNumber.java | 2 +- .../hibernate/envers/RevisionTimestamp.java | 2 +- .../org/hibernate/envers/RevisionType.java | 74 +- .../hibernate/envers/SecondaryAuditTable.java | 9 +- .../envers/SecondaryAuditTables.java | 7 +- .../envers/configuration/EnversSettings.java | 29 +- .../internal/AuditEntitiesConfiguration.java | 6 +- .../internal/ClassesAuditingData.java | 172 ++- .../internal/EntitiesConfigurator.java | 182 +-- .../internal/GlobalConfiguration.java | 13 +- .../internal/PersistentClassGraphDefiner.java | 66 +- .../internal/RevisionInfoConfiguration.java | 614 +++++---- .../RevisionInfoConfigurationResult.java | 34 +- .../metadata/AuditEntityNameRegister.java | 99 +- .../metadata/AuditMetadataGenerator.java | 958 +++++++------ .../internal/metadata/AuditTableData.java | 50 +- .../metadata/BasicMetadataGenerator.java | 84 +- .../metadata/CollectionMetadataGenerator.java | 1214 ++++++++++------- .../metadata/ComponentMetadataGenerator.java | 63 +- .../metadata/EntityXmlMappingData.java | 61 +- .../metadata/IdMetadataGenerator.java | 261 ++-- .../internal/metadata/InheritanceType.java | 58 +- .../internal/metadata/MetadataTools.java | 586 ++++---- .../metadata/QueryGeneratorBuilder.java | 122 +- .../ToOneRelationMetadataGenerator.java | 220 +-- .../reader/AnnotationsMetadataReader.java | 117 +- .../reader/AuditedPropertiesHolder.java | 34 +- .../reader/AuditedPropertiesReader.java | 769 ++++++----- .../metadata/reader/ClassAuditingData.java | 77 +- .../ComponentAuditedPropertiesReader.java | 62 +- .../reader/ComponentAuditingData.java | 27 +- .../reader/PersistentPropertiesSource.java | 27 + .../metadata/reader/PropertyAuditingData.java | 183 +-- .../configuration/spi/AuditConfiguration.java | 53 +- .../enhanced/OrderedSequenceGenerator.java | 24 + .../enhanced/SequenceIdRevisionEntity.java | 116 +- ...rackingModifiedEntitiesRevisionEntity.java | 83 +- .../BaseEnversCollectionEventListener.java | 193 +-- .../event/spi/BaseEnversEventListener.java | 88 +- .../envers/event/spi/EnversIntegrator.java | 70 +- .../envers/event/spi/EnversListener.java | 5 + .../EnversListenerDuplicationStrategy.java | 3 + ...stCollectionRecreateEventListenerImpl.java | 12 +- .../EnversPostDeleteEventListenerImpl.java | 22 +- .../EnversPostInsertEventListenerImpl.java | 31 +- .../EnversPostUpdateEventListenerImpl.java | 32 +- ...sPreCollectionRemoveEventListenerImpl.java | 10 +- ...sPreCollectionUpdateEventListenerImpl.java | 10 +- .../envers/exception/AuditException.java | 21 +- .../envers/exception/NotAuditedException.java | 20 +- .../RevisionDoesNotExistException.java | 39 +- .../envers/internal/EnversMessageLogger.java | 13 +- .../entities/EntitiesConfigurations.java | 180 +-- .../entities/EntityConfiguration.java | 214 ++- .../internal/entities/EntityInstantiator.java | 207 +-- .../internal/entities/IdMappingData.java | 43 +- .../internal/entities/PropertyData.java | 119 +- .../entities/RelationDescription.java | 114 +- .../internal/entities/RelationType.java | 53 +- .../internal/entities/RevisionTypeType.java | 100 +- .../entities/TypeContributorImpl.java | 46 +- .../mapper/ComponentPropertyMapper.java | 147 +- .../mapper/CompositeMapperBuilder.java | 12 +- .../mapper/ExtendedPropertyMapper.java | 12 +- .../entities/mapper/MultiPropertyMapper.java | 265 ++-- .../PersistentCollectionChangeData.java | 89 +- .../entities/mapper/PropertyMapper.java | 73 +- .../entities/mapper/SimpleMapperBuilder.java | 9 +- .../entities/mapper/SinglePropertyMapper.java | 126 +- .../mapper/SubclassPropertyMapper.java | 155 ++- .../mapper/id/AbstractCompositeIdMapper.java | 59 +- .../entities/mapper/id/AbstractIdMapper.java | 134 +- .../entities/mapper/id/EmbeddedIdMapper.java | 133 +- .../internal/entities/mapper/id/IdMapper.java | 131 +- .../entities/mapper/id/MultipleIdMapper.java | 111 +- .../mapper/id/QueryParameterData.java | 79 +- .../mapper/id/SimpleIdMapperBuilder.java | 5 +- .../entities/mapper/id/SingleIdMapper.java | 167 +-- .../relation/AbstractCollectionMapper.java | 279 ++-- .../relation/AbstractOneToOneMapper.java | 120 +- .../mapper/relation/AbstractToOneMapper.java | 183 ++- .../relation/BasicCollectionMapper.java | 66 +- .../relation/CommonCollectionMapperData.java | 67 +- .../mapper/relation/ListCollectionMapper.java | 93 +- .../mapper/relation/MapCollectionMapper.java | 92 +- .../mapper/relation/MiddleComponentData.java | 30 +- .../mapper/relation/MiddleIdData.java | 89 +- .../relation/OneToOneNotOwningMapper.java | 41 +- .../OneToOnePrimaryKeyJoinColumnMapper.java | 110 +- .../relation/SortedMapCollectionMapper.java | 34 +- .../relation/SortedSetCollectionMapper.java | 28 +- .../mapper/relation/ToOneEntityLoader.java | 63 +- .../mapper/relation/ToOneIdMapper.java | 139 +- .../component/MiddleComponentMapper.java | 70 +- .../component/MiddleDummyComponentMapper.java | 33 +- .../MiddleEmbeddableComponentMapper.java | 54 +- .../MiddleMapKeyIdComponentMapper.java | 51 +- .../MiddleMapKeyPropertyComponentMapper.java | 52 +- .../MiddleRelatedComponentMapper.java | 46 +- .../MiddleSimpleComponentMapper.java | 52 +- .../MiddleStraightComponentMapper.java | 53 +- .../AbstractDelegateSessionImplementor.java | 298 ++-- .../lazy/ToOneDelegateSessionImplementor.java | 56 +- .../AbstractCollectionInitializor.java | 58 +- .../ArrayCollectionInitializor.java | 65 +- .../BasicCollectionInitializor.java | 101 +- .../lazy/initializor/Initializor.java | 6 +- .../ListCollectionInitializor.java | 95 +- .../initializor/MapCollectionInitializor.java | 102 +- .../SortedMapCollectionInitializor.java | 58 +- .../SortedSetCollectionInitializor.java | 50 +- .../relation/lazy/proxy/CollectionProxy.java | 176 +-- .../mapper/relation/lazy/proxy/ListProxy.java | 107 +- .../mapper/relation/lazy/proxy/MapProxy.java | 171 +-- .../mapper/relation/lazy/proxy/SetProxy.java | 17 +- .../relation/lazy/proxy/SortedMapProxy.java | 213 +-- .../relation/lazy/proxy/SortedSetProxy.java | 71 +- .../query/AbstractRelationQueryGenerator.java | 20 +- .../query/OneAuditEntityQueryGenerator.java | 29 +- .../query/OneEntityQueryGenerator.java | 35 +- .../mapper/relation/query/QueryConstants.java | 41 +- .../query/RelationQueryGenerator.java | 10 +- .../query/ThreeEntityQueryGenerator.java | 119 +- .../TwoEntityOneAuditedQueryGenerator.java | 40 +- .../query/TwoEntityQueryGenerator.java | 94 +- .../internal/reader/AuditReaderImpl.java | 492 +++---- .../reader/AuditReaderImplementor.java | 14 +- .../CrossTypeRevisionChangesReaderImpl.java | 196 ++- .../internal/reader/FirstLevelCache.java | 136 +- .../DefaultRevisionInfoGenerator.java | 132 +- ...ModifiedEntitiesRevisionInfoGenerator.java | 80 +- .../ModifiedEntityNamesReader.java | 40 +- .../revisioninfo/RevisionInfoGenerator.java | 18 +- .../RevisionInfoNumberReader.java | 21 +- .../RevisionInfoQueryCreator.java | 53 +- .../synchronization/AuditProcess.java | 188 +-- .../synchronization/AuditProcessManager.java | 51 +- .../synchronization/EntityChangeNotifier.java | 78 +- .../synchronization/SessionCacheCleaner.java | 57 +- .../work/AbstractAuditWorkUnit.java | 106 +- .../synchronization/work/AddWorkUnit.java | 106 +- .../synchronization/work/AuditWorkUnit.java | 56 +- .../work/CollectionChangeWorkUnit.java | 108 +- .../synchronization/work/DelWorkUnit.java | 115 +- .../FakeBidirectionalRelationWorkUnit.java | 317 +++-- .../synchronization/work/ModWorkUnit.java | 113 +- .../PersistentCollectionChangeWorkUnit.java | 311 +++-- .../work/WorkUnitMergeDispatcher.java | 19 +- .../work/WorkUnitMergeVisitor.java | 19 +- .../envers/internal/tools/ArgumentsTools.java | 4 +- .../envers/internal/tools/ArraysTools.java | 8 +- .../envers/internal/tools/EntityTools.java | 43 +- .../envers/internal/tools/MappingTools.java | 29 +- .../envers/internal/tools/MutableBoolean.java | 34 +- .../envers/internal/tools/MutableInteger.java | 40 +- .../internal/tools/ReflectionTools.java | 46 +- .../envers/internal/tools/StringTools.java | 6 +- .../envers/internal/tools/Tools.java | 10 +- .../envers/internal/tools/Triple.java | 87 +- .../internal/tools/graph/GraphDefiner.java | 17 +- .../tools/graph/GraphTopologicalSort.java | 64 +- .../internal/tools/graph/TopologicalSort.java | 58 +- .../envers/internal/tools/graph/Vertex.java | 70 +- .../internal/tools/query/Parameters.java | 374 ++--- .../internal/tools/query/QueryBuilder.java | 313 ++--- .../internal/tools/query/UpdateBuilder.java | 127 +- .../hibernate/envers/query/AuditEntity.java | 107 +- .../hibernate/envers/query/AuditQuery.java | 29 +- .../envers/query/AuditQueryCreator.java | 318 +++-- .../criteria/AggregatedAuditExpression.java | 89 +- .../query/criteria/AuditConjunction.java | 40 +- .../envers/query/criteria/AuditCriterion.java | 5 +- .../query/criteria/AuditDisjunction.java | 40 +- .../envers/query/criteria/AuditId.java | 6 +- .../envers/query/criteria/AuditProperty.java | 227 +-- .../envers/query/criteria/AuditRelatedId.java | 17 +- .../query/criteria/ExtendableCriterion.java | 2 +- .../internal/BetweenAuditExpression.java | 40 +- .../criteria/internal/CriteriaTools.java | 60 +- .../internal/IdentifierEqAuditExpression.java | 24 +- .../criteria/internal/InAuditExpression.java | 31 +- .../internal/LogicalAuditExpression.java | 29 +- .../criteria/internal/NotAuditExpression.java | 17 +- .../internal/NotNullAuditExpression.java | 35 +- .../internal/NullAuditExpression.java | 35 +- .../internal/PropertyAuditExpression.java | 36 +- .../internal/RelatedAuditExpression.java | 49 +- .../internal/RevisionTypeAuditExpression.java | 21 +- .../internal/SimpleAuditExpression.java | 55 +- .../internal/impl/AbstractAuditQuery.java | 283 ++-- .../impl/EntitiesAtRevisionQuery.java | 124 +- .../impl/EntitiesModifiedAtRevisionQuery.java | 68 +- .../internal/impl/RevisionsOfEntityQuery.java | 174 +-- .../internal/property/EntityPropertyName.java | 15 +- .../property/ModifiedFlagPropertyName.java | 18 +- .../property/OriginalIdPropertyName.java | 17 +- .../internal/property/PropertyNameGetter.java | 12 +- .../property/RevisionNumberPropertyName.java | 7 +- .../RevisionPropertyPropertyName.java | 15 +- .../property/RevisionTypePropertyName.java | 7 +- .../envers/query/order/AuditOrder.java | 11 +- .../order/internal/PropertyAuditOrder.java | 18 +- .../query/projection/AuditProjection.java | 11 +- .../internal/PropertyAuditProjection.java | 24 +- .../envers/strategy/AuditStrategy.java | 137 +- .../envers/strategy/DefaultAuditStrategy.java | 145 +- .../strategy/ValidTimeAuditStrategy.java | 9 +- .../strategy/ValidityAuditStrategy.java | 305 +++-- .../java/org/hibernate/envers/tools/Pair.java | 74 +- .../tools/hbm2ddl/EnversSchemaGenerator.java | 73 +- .../test/java/ee/estonia/entities/Child.java | 98 +- .../test/java/ee/estonia/entities/Parent.java | 118 +- .../envers/test/AbstractEnversTest.java | 26 +- .../envers/test/AbstractOneSessionTest.java | 61 +- .../test/BaseEnversFunctionalTestCase.java | 27 +- .../test/BaseEnversJPAFunctionalTestCase.java | 35 +- .../hibernate/envers/test/EnversRunner.java | 109 +- .../org/hibernate/envers/test/Priority.java | 3 +- .../test/entities/IntNoAutoIdTestEntity.java | 95 +- .../envers/test/entities/IntTestEntity.java | 95 +- .../test/entities/IntTestPrivSeqEntity.java | 99 +- .../test/entities/PrimitiveTestEntity.java | 61 +- .../test/entities/StrIntTestEntity.java | 123 +- .../envers/test/entities/StrTestEntity.java | 95 +- .../entities/StrTestEntityComparator.java | 10 +- .../test/entities/StrTestNoProxyEntity.java | 22 +- .../test/entities/StrTestPrivSeqEntity.java | 99 +- .../test/entities/UnversionedEntity.java | 117 +- .../entities/UnversionedStrTestEntity.java | 93 +- .../collection/EmbeddableListEntity1.java | 18 +- .../collection/EmbeddableListEntity2.java | 18 +- .../collection/EmbeddableMapEntity.java | 18 +- .../collection/EmbeddableSetEntity.java | 18 +- .../entities/collection/EnumSetEntity.java | 108 +- .../collection/MultipleCollectionEntity.java | 24 +- .../MultipleCollectionRefEntity1.java | 2 +- .../MultipleCollectionRefEntity2.java | 2 +- .../entities/collection/StringListEntity.java | 81 +- .../entities/collection/StringMapEntity.java | 81 +- .../entities/collection/StringSetEntity.java | 79 +- .../test/entities/components/Component1.java | 83 +- .../test/entities/components/Component2.java | 83 +- .../test/entities/components/Component3.java | 39 +- .../test/entities/components/Component4.java | 26 +- .../components/ComponentSetTestEntity.java | 43 +- .../components/ComponentTestEntity.java | 123 +- .../components/DefaultValueComponent1.java | 22 +- .../components/DefaultValueComponent2.java | 18 +- .../DefaultValueComponentTestEntity.java | 24 +- .../components/UniquePropsEntity.java | 106 +- .../UniquePropsNotAuditedEntity.java | 108 +- .../relations/ManyToOneComponent.java | 44 +- .../ManyToOneComponentTestEntity.java | 73 +- .../relations/ManyToOneEagerComponent.java | 18 +- .../NotAuditedManyToOneComponent.java | 45 +- ...otAuditedManyToOneComponentTestEntity.java | 73 +- .../relations/OneToManyComponent.java | 47 +- .../OneToManyComponentTestEntity.java | 73 +- .../test/entities/customtype/Component.java | 77 +- .../customtype/CompositeCustomTypeEntity.java | 93 +- .../customtype/CompositeTestUserType.java | 168 +-- .../entities/customtype/EnumTypeEntity.java | 29 +- .../ParametrizedCustomTypeEntity.java | 93 +- .../customtype/ParametrizedTestUserType.java | 118 +- .../customtype/UnspecifiedEnumTypeEntity.java | 29 +- .../ids/CompositeDateIdTestEntity.java | 89 +- .../envers/test/entities/ids/CustomEnum.java | 16 +- .../test/entities/ids/CustomEnumUserType.java | 102 +- .../envers/test/entities/ids/DateEmbId.java | 85 +- .../test/entities/ids/DateIdTestEntity.java | 91 +- .../envers/test/entities/ids/EmbId.java | 85 +- .../test/entities/ids/EmbIdTestEntity.java | 87 +- .../entities/ids/EmbIdWithCustomType.java | 85 +- .../ids/EmbIdWithCustomTypeTestEntity.java | 81 +- .../ids/ManyToOneIdNotAuditedTestEntity.java | 75 +- .../ids/ManyToOneNotAuditedEmbId.java | 59 +- .../envers/test/entities/ids/MulId.java | 83 +- .../test/entities/ids/MulIdTestEntity.java | 111 +- .../entities/ids/UnusualIdNamingEntity.java | 20 +- .../entities/manytomany/ListOwnedEntity.java | 114 +- .../entities/manytomany/ListOwningEntity.java | 113 +- .../entities/manytomany/MapOwnedEntity.java | 114 +- .../entities/manytomany/MapOwningEntity.java | 117 +- .../entities/manytomany/SetOwnedEntity.java | 114 +- .../entities/manytomany/SetOwningEntity.java | 113 +- .../entities/manytomany/SortedSetEntity.java | 116 +- .../manytomany/WhereJoinTableEntity.java | 137 +- .../biowned/ListBiowning1Entity.java | 123 +- .../biowned/ListBiowning2Entity.java | 123 +- .../manytomany/sametable/Child1Entity.java | 121 +- .../manytomany/sametable/Child2Entity.java | 121 +- .../manytomany/sametable/ParentEntity.java | 141 +- .../unidirectional/JoinTableEntity.java | 28 +- .../unidirectional/ListUniEntity.java | 113 +- .../M2MIndexedListTargetNotAuditedEntity.java | 117 +- .../M2MTargetNotAuditedEntity.java | 39 +- .../unidirectional/MapUniEntity.java | 116 +- .../unidirectional/SetUniEntity.java | 113 +- .../TargetNotAuditedEntity.java | 21 +- .../onetomany/CollectionRefEdEntity.java | 114 +- .../onetomany/CollectionRefIngEntity.java | 119 +- .../entities/onetomany/ListRefEdEntity.java | 114 +- .../entities/onetomany/ListRefIngEntity.java | 115 +- .../entities/onetomany/SetRefEdEntity.java | 114 +- .../entities/onetomany/SetRefIngEntity.java | 123 +- ...stJoinColumnBidirectionalRefEdEntity1.java | 122 +- ...stJoinColumnBidirectionalRefEdEntity2.java | 122 +- ...stJoinColumnBidirectionalRefIngEntity.java | 139 +- .../detached/DoubleSetRefCollEntity.java | 136 +- ...istJoinColumnBidirectionalRefEdEntity.java | 138 +- ...stJoinColumnBidirectionalRefIngEntity.java | 132 +- ...irectionalInheritanceRefEdChildEntity.java | 93 +- ...rectionalInheritanceRefEdParentEntity.java | 122 +- ...nBidirectionalInheritanceRefIngEntity.java | 130 +- ...istJoinColumnBidirectionalRefEdEntity.java | 120 +- ...stJoinColumnBidirectionalRefIngEntity.java | 128 +- .../onetomany/detached/ListRefCollEntity.java | 114 +- .../detached/SetJoinColumnRefCollEntity.java | 118 +- .../onetomany/detached/SetRefCollEntity.java | 114 +- .../detached/ids/SetRefCollEntityEmbId.java | 114 +- .../detached/ids/SetRefCollEntityMulId.java | 138 +- ...stJoinColumnBidirectionalRefIngEntity.java | 90 +- ...stJoinColumnBidirectionalRefIngEntity.java | 132 +- ...istJoinColumnBidirectionalRefEdEntity.java | 138 +- .../onetomany/ids/SetRefEdEmbIdEntity.java | 114 +- .../onetomany/ids/SetRefEdMulIdEntity.java | 148 +- .../onetomany/ids/SetRefIngEmbIdEntity.java | 115 +- .../onetomany/ids/SetRefIngMulIdEntity.java | 151 +- ...rectionalEagerAnnotationRefEdOneToOne.java | 20 +- ...ectionalEagerAnnotationRefIngOneToOne.java | 20 +- .../BidirectionalEagerHbmRefEdPK.java | 23 +- .../BidirectionalEagerHbmRefIngPK.java | 23 +- .../reventity/CustomDataRevEntity.java | 70 +- .../reventity/CustomDateRevEntity.java | 91 +- .../CustomPropertyAccessRevEntity.java | 86 +- .../entities/reventity/CustomRevEntity.java | 86 +- .../CustomRevEntityColumnMapping.java | 90 +- .../AnnotatedTrackingRevisionEntity.java | 122 +- .../CustomTrackingRevisionEntity.java | 118 +- .../CustomTrackingRevisionListener.java | 17 +- .../ExtendedRevisionEntity.java | 16 +- .../ExtendedRevisionListener.java | 8 +- .../ModifiedEntityTypeEntity.java | 93 +- .../test/integration/accesstype/Country.java | 33 +- .../accesstype/FieldAccessType.java | 64 +- .../accesstype/FieldAccessTypeEntity.java | 101 +- .../accesstype/ImmutableClassAccessType.java | 35 +- .../accesstype/MixedAccessType.java | 70 +- .../accesstype/MixedAccessTypeEntity.java | 119 +- .../accesstype/PropertyAccessType.java | 74 +- .../accesstype/PropertyAccessTypeEntity.java | 119 +- .../auditReader/AuditReaderAPITest.java | 83 +- .../auditReader/AuditedTestEntity.java | 87 +- .../auditReader/NotAuditedTestEntity.java | 85 +- .../integration/basic/BasicTestEntity1.java | 115 +- .../integration/basic/BasicTestEntity2.java | 113 +- .../integration/basic/BasicTestEntity3.java | 111 +- .../integration/basic/BasicTestEntity4.java | 111 +- .../basic/ColumnScalePrecisionTest.java | 83 +- .../envers/test/integration/basic/Delete.java | 158 +-- .../integration/basic/EmptyStringTest.java | 83 +- .../integration/basic/GlobalVersioned.java | 64 +- .../basic/ManyOperationsInTransaction.java | 142 +- .../test/integration/basic/NoneAudited.java | 36 +- .../test/integration/basic/NotVersioned.java | 56 +- .../integration/basic/NullProperties.java | 108 +- .../basic/OutsideTransactionTest.java | 163 +-- .../basic/RegisterUserEventListenersTest.java | 39 +- .../basic/ScalePrecisionEntity.java | 100 +- .../envers/test/integration/basic/Simple.java | 62 +- .../basic/SingleOperationInTransaction.java | 206 +-- .../basic/TransactionRollbackBehaviour.java | 33 +- .../basic/UnversionedPropertiesChange.java | 82 +- .../basic/UnversionedProperty.java | 70 +- .../integration/cache/OneToManyCache.java | 152 +-- .../test/integration/cache/OneToOneCache.java | 86 +- .../test/integration/cache/QueryCache.java | 80 +- .../DetachedMultipleCollectionChangeTest.java | 45 +- .../test/integration/collection/EnumSet.java | 151 +- .../integration/collection/StringList.java | 124 +- .../integration/collection/StringMap.java | 144 +- .../integration/collection/StringSet.java | 124 +- .../embeddable/BasicEmbeddableCollection.java | 13 +- .../collection/embeddable/DarkCharacter.java | 22 +- .../embeddable/EmbeddableList1.java | 18 +- .../embeddable/EmbeddableList2.java | 20 +- .../collection/embeddable/EmbeddableMap.java | 27 +- .../collection/embeddable/EmbeddableSet.java | 18 +- .../collection/embeddable/Name.java | 20 +- .../collection/mapkey/ComponentMapKey.java | 108 +- .../mapkey/ComponentMapKeyEntity.java | 81 +- .../collection/mapkey/IdMapKey.java | 92 +- .../collection/mapkey/IdMapKeyEntity.java | 81 +- .../AbstractCollectionChangeTest.java | 86 +- .../CollectionChangeNoRevisionTest.java | 15 +- .../CollectionChangeRevisionTest.java | 19 +- .../collection/norevision/Name.java | 53 +- .../collection/norevision/Person.java | 50 +- .../integration/components/Components.java | 224 +-- .../components/DefaultValueComponents.java | 450 +++--- .../components/PropertiesGroupTest.java | 115 +- .../collections/CollectionOfComponents.java | 73 +- .../dynamic/AuditedDynamicComponentTest.java | 15 +- .../NotAuditedDynamicComponentTest.java | 28 +- .../NotAuditedDynamicMapComponent.java | 26 +- .../relations/ManyToOneInComponent.java | 116 +- .../NotAuditedManyToOneInComponent.java | 104 +- .../relations/OneToManyInComponent.java | 113 +- .../customtype/CompositeCustom.java | 89 +- .../integration/customtype/EnumTypeTest.java | 17 +- .../customtype/ObjectUserType.java | 19 +- .../customtype/ObjectUserTypeEntity.java | 29 +- .../customtype/ObjectUserTypeTest.java | 16 +- .../customtype/ParametrizedCustom.java | 75 +- .../customtype/UnspecifiedEnumTypeTest.java | 50 +- .../test/integration/data/DateTestEntity.java | 105 +- .../envers/test/integration/data/Dates.java | 64 +- .../test/integration/data/EnumTestEntity.java | 120 +- .../envers/test/integration/data/Enums.java | 64 +- .../data/LobSerializableTestEntity.java | 90 +- .../integration/data/LobSerializables.java | 77 +- .../test/integration/data/LobTestEntity.java | 149 +- .../envers/test/integration/data/Lobs.java | 83 +- .../test/integration/data/SerObject.java | 53 +- .../data/SerializableTestEntity.java | 89 +- .../test/integration/data/Serializables.java | 62 +- .../entityNames/auditedEntity/Person.java | 19 +- .../ReadEntityWhitEntityNameTest.java | 215 +-- .../entityNames/manyToManyAudited/Car.java | 18 +- .../entityNames/manyToManyAudited/Person.java | 21 +- .../ReadEntityWithAuditedManyToManyTest.java | 182 +-- .../entityNames/oneToManyAudited/Car.java | 18 +- .../entityNames/oneToManyAudited/Person.java | 19 +- .../ReadEntityWithAuditedCollectionTest.java | 178 +-- .../entityNames/oneToManyNotAudited/Car.java | 20 +- .../oneToManyNotAudited/Person.java | 18 +- .../ReadEntityWithAuditedCollectionTest.java | 180 ++- .../singleAssociatedAudited/Car.java | 33 +- .../singleAssociatedAudited/Person.java | 19 +- .../ReadEntityAssociatedAuditedTest.java | 173 ++- ...ingleDomainObjectToMultipleTablesTest.java | 83 +- .../singleAssociatedNotAudited/Car.java | 20 +- .../singleAssociatedNotAudited/Person.java | 18 +- .../ReadEntityAssociatedNotAuditedTest.java | 179 +-- .../integration/flush/AbstractFlushTest.java | 45 +- .../integration/flush/DoubleFlushAddDel.java | 60 +- .../integration/flush/DoubleFlushAddMod.java | 100 +- .../integration/flush/DoubleFlushModDel.java | 96 +- .../integration/flush/DoubleFlushModMod.java | 98 +- .../test/integration/flush/ManualFlush.java | 116 +- .../flush/ManualFlushAutoCommitDisabled.java | 10 +- .../hashcode/ChangingHashcode.java | 104 +- .../test/integration/hashcode/WikiImage.java | 13 +- .../test/integration/hashcode/WikiPage.java | 21 +- .../test/integration/ids/CompositeDateId.java | 72 +- .../test/integration/ids/CompositeIds.java | 294 ++-- .../envers/test/integration/ids/DateId.java | 68 +- .../ids/ManyToOneIdNotAudited.java | 51 +- .../test/integration/ids/embeddedid/Item.java | 90 +- .../integration/ids/embeddedid/ItemId.java | 118 +- .../integration/ids/embeddedid/Producer.java | 94 +- .../ids/embeddedid/PurchaseOrder.java | 135 +- .../RelationInsideEmbeddableTest.java | 125 +- .../integration/ids/idclass/ClassType.java | 84 +- .../ids/idclass/IdClassWithRelationTest.java | 167 +-- .../ids/idclass/RelationalClassId.java | 86 +- .../integration/ids/idclass/SampleClass.java | 128 +- .../ProtectedConstructorEntity.java | 24 +- .../ProtectedConstructorTest.java | 19 +- .../protectedmodifier/WrappedStringId.java | 12 +- .../inheritance/joined/ChildAuditing.java | 88 +- .../inheritance/joined/ChildEntity.java | 69 +- .../inheritance/joined/ChildNullAuditing.java | 88 +- .../inheritance/joined/ParentAuditing.java | 92 +- .../inheritance/joined/ParentEntity.java | 87 +- .../joined/childrelation/ChildIngEntity.java | 85 +- .../childrelation/ChildReferencing.java | 134 +- .../childrelation/ParentNotIngEntity.java | 87 +- .../childrelation/ReferencedEntity.java | 77 +- .../joined/emptychild/EmptyChildAuditing.java | 86 +- .../joined/emptychild/EmptyChildEntity.java | 3 +- .../joined/emptychild/ParentEntity.java | 87 +- .../joined/notownedrelation/Address.java | 59 +- .../joined/notownedrelation/Contact.java | 67 +- .../NotOwnedBidirectional.java | 114 +- .../notownedrelation/PersonalContact.java | 19 +- .../ChildPrimaryKeyJoinAuditing.java | 110 +- .../ChildPrimaryKeyJoinEntity.java | 73 +- .../joined/relation/ChildIngEntity.java | 69 +- .../joined/relation/ParentIngEntity.java | 103 +- .../relation/ParentReferencingChildTest.java | 109 +- .../inheritance/joined/relation/Person.java | 70 +- .../relation/PolymorphicCollection.java | 104 +- .../joined/relation/ReferencedEntity.java | 77 +- .../joined/relation/RightsSubject.java | 112 +- .../inheritance/joined/relation/Role.java | 90 +- .../AbstractContainedEntity.java | 19 +- .../unidirectional/AbstractSetEntity.java | 29 +- .../unidirectional/ContainedEntity.java | 3 +- .../relation/unidirectional/SetEntity.java | 1 + .../UnidirectionalDoubleAbstract.java | 54 +- .../MixedInheritanceStrategiesEntityTest.java | 180 +-- .../mixed/entities/AbstractActivity.java | 26 +- .../mixed/entities/AbstractCheckActivity.java | 44 +- .../inheritance/mixed/entities/Activity.java | 2 +- .../mixed/entities/ActivityId.java | 8 +- .../mixed/entities/CheckInActivity.java | 30 +- .../mixed/entities/NormalActivity.java | 30 +- .../inheritance/single/ChildAuditing.java | 86 +- .../inheritance/single/ChildEntity.java | 77 +- .../inheritance/single/ParentAuditing.java | 92 +- .../inheritance/single/ParentEntity.java | 95 +- .../single/childrelation/ChildIngEntity.java | 93 +- .../childrelation/ChildReferencing.java | 132 +- .../childrelation/ParentNotIngEntity.java | 95 +- .../childrelation/ReferencedEntity.java | 73 +- .../discriminatorformula/ChildEntity.java | 74 +- .../discriminatorformula/ClassTypeEntity.java | 78 +- .../DiscriminatorFormulaTest.java | 218 +-- .../discriminatorformula/ParentEntity.java | 118 +- .../single/notownedrelation/Address.java | 56 +- .../single/notownedrelation/Contact.java | 62 +- .../NotOwnedBidirectional.java | 124 +- .../notownedrelation/PersonalContact.java | 5 +- .../single/relation/ChildIngEntity.java | 77 +- .../single/relation/ParentIngEntity.java | 111 +- .../relation/PolymorphicCollection.java | 102 +- .../single/relation/ReferencedEntity.java | 63 +- .../tableperclass/ChildAuditing.java | 88 +- .../tableperclass/ChildEntity.java | 69 +- .../tableperclass/ParentAuditing.java | 92 +- .../tableperclass/ParentEntity.java | 87 +- .../AuditedAbstractParentTest.java | 11 +- .../childrelation/ChildIngEntity.java | 85 +- .../childrelation/ChildReferencing.java | 134 +- .../childrelation/ParentNotIngEntity.java | 87 +- .../childrelation/ReferencedEntity.java | 77 +- .../notownedrelation/Address.java | 59 +- .../notownedrelation/Contact.java | 67 +- .../NotOwnedBidirectional.java | 114 +- .../notownedrelation/PersonalContact.java | 19 +- .../relation/ChildIngEntity.java | 69 +- .../relation/ParentIngEntity.java | 103 +- .../relation/PolymorphicCollection.java | 104 +- .../relation/ReferencedEntity.java | 77 +- .../interfaces/components/Component1.java | 15 +- .../components/ComponentTestEntity.java | 39 +- .../interfaces/components/IComponent.java | 1 + .../components/InterfacesComponents.java | 84 +- .../allAudited/AbstractAllAuditedTest.java | 179 +-- .../hbm/allAudited/AuditedImplementor.java | 2 +- .../hbm/allAudited/NonAuditedImplementor.java | 2 - .../hbm/allAudited/SimpleInterface.java | 10 +- .../joined/JoinedAllAuditedTest.java | 8 +- .../subclass/SubclassAllAuditedTest.java | 8 +- .../allAudited/union/UnionAllAuditedTest.java | 8 +- .../AbstractPropertiesAuditedTest.java | 65 +- .../propertiesAudited/AuditedImplementor.java | 4 +- .../propertiesAudited/SimpleInterface.java | 14 +- .../joined/JoinedPropertiesAuditedTest.java | 5 +- .../SubclassPropertiesAuditedTest.java | 3 +- .../union/UnionPropertiesAuditedTest.java | 5 +- .../AbstractPropertiesAudited2Test.java | 63 +- .../AuditedImplementor.java | 4 +- .../NonAuditedImplementor.java | 3 +- .../propertiesAudited2/SimpleInterface.java | 14 +- .../joined/JoinedPropertiesAudited2Test.java | 2 +- .../SubclassPropertiesAudited2Test.java | 7 +- .../union/UnionPropertiesAudited2Test.java | 5 +- .../relation/InterfacesRelation.java | 108 +- .../interfaces/relation/SetRefEdEntity.java | 92 +- .../interfaces/relation/SetRefIngEntity.java | 123 +- .../integration/jta/JtaExceptionListener.java | 66 +- .../test/integration/jta/JtaTransaction.java | 100 +- .../integration/manytomany/BasicList.java | 261 ++-- .../test/integration/manytomany/BasicMap.java | 208 +-- .../test/integration/manytomany/BasicSet.java | 258 ++-- .../manytomany/BasicWhereJoinTable.java | 222 +-- .../CustomComparatorEntityTest.java | 346 ++--- .../manytomany/biowned/BasicBiowned.java | 285 ++-- .../inverseToSuperclass/DetailSubclass.java | 1 + .../inverseToSuperclass/DetailSubclass2.java | 3 +- .../inverseToSuperclass/DetailSuperclass.java | 1 + .../ManyToManyInverseToSuperclassTest.java | 35 +- .../inverseToSuperclass/Master.java | 1 + .../manytomany/sametable/BasicSametable.java | 425 +++--- .../manytomany/ternary/TernaryMap.java | 224 +-- .../manytomany/ternary/TernaryMapEntity.java | 81 +- .../manytomany/ternary/TernaryMapFlush.java | 152 +-- .../unidirectional/BasicUniList.java | 196 +-- .../unidirectional/BasicUniMap.java | 136 +- .../unidirectional/BasicUniSet.java | 196 +-- .../unidirectional/JoinTableDetachedTest.java | 24 +- .../M2MIndexedListNotAuditedTarget.java | 154 ++- .../M2MRelationNotAuditedTarget.java | 115 +- .../bidirectional/ImplicitMappedByTest.java | 151 +- .../bidirectional/ManyToOneOwning.java | 122 +- .../bidirectional/OneToManyOwned.java | 122 +- .../RelationNotAuditedTarget.java | 110 +- .../test/integration/merge/AddDelTest.java | 95 +- .../integration/merge/GivenIdStrEntity.java | 88 +- .../AbstractModifiedFlagsEntityTest.java | 66 +- .../AbstractModifiedFlagsOneSessionTest.java | 10 +- .../modifiedflags/HasChangedAPITest.java | 64 +- .../HasChangedAuditedManyToManyTest.java | 135 +- .../HasChangedBidirectional2.java | 112 +- .../HasChangedChildAuditing.java | 76 +- .../HasChangedChildReferencing.java | 88 +- .../HasChangedComponentCollection.java | 11 +- .../HasChangedComponentMapKey.java | 118 +- .../modifiedflags/HasChangedComponents.java | 225 +-- .../HasChangedCompositeCustom.java | 68 +- .../HasChangedDetachedMultipleCollection.java | 9 +- ...ngedDoubleJoinColumnBidirectionalList.java | 277 ++-- .../modifiedflags/HasChangedEnumSet.java | 102 +- .../HasChangedForDefaultNotUsing.java | 172 ++- .../modifiedflags/HasChangedIdMapKey.java | 74 +- .../modifiedflags/HasChangedManualFlush.java | 9 +- .../HasChangedManyToOneInComponent.java | 83 +- .../modifiedflags/HasChangedMergeTest.java | 9 +- .../HasChangedNotOwnedBidirectional.java | 84 +- .../HasChangedNullProperties.java | 112 +- .../HasChangedOneToManyInComponent.java | 80 +- .../modifiedflags/HasChangedStringMap.java | 126 +- .../modifiedflags/HasChangedStringSet.java | 114 +- .../HasChangedUnversionedProperties.java | 76 +- .../modifiedflags/ModifiedFlagSuffix.java | 83 +- .../entities/PartialModifiedFlagsEntity.java | 136 +- .../WithModifiedFlagReferencingEntity.java | 108 +- .../multiplerelations/Address.java | 136 +- .../MultipleAssociationsTest.java | 290 ++-- .../integration/multiplerelations/Person.java | 140 +- .../test/integration/naming/BasicNaming.java | 119 +- .../naming/DetachedNamingTestEntity.java | 119 +- .../naming/EstonianTableAlias.java | 60 +- .../test/integration/naming/JoinNaming.java | 142 +- .../naming/JoinNamingRefEdEntity.java | 118 +- .../naming/JoinNamingRefIngEntity.java | 121 +- .../integration/naming/NamingTestEntity1.java | 95 +- .../naming/OneToManyUnidirectionalNaming.java | 138 +- .../naming/VersionsJoinTableNaming.java | 144 +- .../VersionsJoinTableRangeComponent.java | 43 +- ...ionsJoinTableRangeComponentNamingTest.java | 154 ++- ...ionsJoinTableRangeComponentTestEntity.java | 109 +- ...ionsJoinTableRangeTestAlternateEntity.java | 39 +- .../VersionsJoinTableRangeTestEntity.java | 37 +- ...onsJoinTableRangeTestEntitySuperClass.java | 36 +- .../naming/VersionsJoinTableTestEntity.java | 117 +- .../integration/naming/ids/EmbIdNaming.java | 89 +- .../naming/ids/JoinEmbIdNaming.java | 169 ++- .../ids/JoinEmbIdNamingRefEdEntity.java | 116 +- .../ids/JoinEmbIdNamingRefIngEntity.java | 123 +- .../naming/ids/JoinMulIdNaming.java | 169 ++- .../ids/JoinMulIdNamingRefEdEntity.java | 138 +- .../ids/JoinMulIdNamingRefIngEntity.java | 134 +- .../integration/naming/ids/MulIdNaming.java | 89 +- .../naming/quotation/QuotedFieldsEntity.java | 136 +- .../naming/quotation/QuotedFieldsTest.java | 152 ++- .../notinsertable/NotInsertable.java | 62 +- .../NotInsertableTestEntity.java | 113 +- .../manytoone/ManyToOneNotInsertable.java | 95 +- .../ManyToOneNotInsertableEntity.java | 12 +- .../manytoone/NotInsertableEntityType.java | 36 +- .../PropertyNotUpdatableEntity.java | 150 +- .../PropertyNotUpdatableTest.java | 164 ++- .../onetomany/BasicCollection.java | 212 +-- .../test/integration/onetomany/BasicList.java | 189 +-- .../test/integration/onetomany/BasicSet.java | 214 +-- .../onetomany/BasicSetWithEmbId.java | 198 +-- .../onetomany/BasicSetWithMulId.java | 198 +-- .../onetomany/BasicSetWithNullsDelete.java | 332 ++--- .../onetomany/BidirectionalMapKey.java | 100 +- .../onetomany/InverseSideChanges.java | 88 +- .../onetomany/RefEdMapKeyEntity.java | 81 +- .../onetomany/RefIngMapKeyEntity.java | 85 +- .../onetomany/detached/BasicDetachedList.java | 138 +- .../onetomany/detached/BasicDetachedSet.java | 136 +- .../detached/BasicDetachedSetWithEmbId.java | 139 +- .../detached/BasicDetachedSetWithMulId.java | 139 +- .../detached/BasicJoinColumnSet.java | 141 +- .../detached/DataChangesDetachedSet.java | 96 +- .../onetomany/detached/DetachedTest.java | 16 +- .../onetomany/detached/DoubleDetachedSet.java | 133 +- .../DoubleJoinColumnBidirectionalList.java | 597 +++++--- .../IndexedJoinColumnBidirectionalList.java | 469 ++++--- ...nceIndexedJoinColumnBidirectionalList.java | 466 ++++--- .../detached/JoinColumnBidirectionalList.java | 377 +++-- ...olumnBidirectionalListWithInheritance.java | 245 ++-- .../onetomany/embeddedid/Constant.java | 92 +- .../onetomany/embeddedid/MapsIdTest.java | 215 +-- .../onetomany/embeddedid/Person.java | 134 +- .../onetomany/embeddedid/PersonTuple.java | 260 ++-- .../onetomany/hierarchy/HierarchyTest.java | 149 +- .../integration/onetomany/hierarchy/Node.java | 146 +- .../inverseToSuperclass/DetailSubclass.java | 1 + .../inverseToSuperclass/DetailSubclass2.java | 3 +- .../inverseToSuperclass/DetailSuperclass.java | 1 + .../onetomany/inverseToSuperclass/Master.java | 1 + .../OneToManyInverseToSuperclassTest.java | 65 +- .../onetoone/bidirectional/BiRefEdEntity.java | 109 +- .../bidirectional/BiRefIngEntity.java | 109 +- .../onetoone/bidirectional/Bidirectional.java | 112 +- .../bidirectional/Bidirectional2.java | 166 +-- .../BidirectionalEagerAnnotationTest.java | 5 +- .../BidirectionalEagerHbmTest.java | 7 +- .../bidirectional/BidirectionalNoNulls.java | 134 +- .../bidirectional/ids/BiEmbIdRefEdEntity.java | 109 +- .../ids/BiEmbIdRefIngEntity.java | 109 +- .../bidirectional/ids/BiMulIdRefEdEntity.java | 123 +- .../ids/BiMulIdRefIngEntity.java | 123 +- .../bidirectional/ids/EmbIdBidirectional.java | 126 +- .../bidirectional/ids/MulIdBidirectional.java | 126 +- .../primarykeyjoincolumn/Account.java | 122 +- .../AccountNotAuditedOwners.java | 136 +- .../NotAuditedNoProxyPerson.java | 122 +- .../NotAuditedProxyPerson.java | 122 +- .../OneToOneWithPrimaryKeyJoinTest.java | 214 +-- .../primarykeyjoincolumn/Person.java | 116 +- .../unidirectional/UniRefEdEntity.java | 82 +- .../unidirectional/UniRefIngEntity.java | 102 +- .../unidirectional/UniRefIngMulIdEntity.java | 110 +- .../unidirectional/Unidirectional.java | 166 +-- .../UnidirectionalMulIdWithNulls.java | 66 +- .../UnidirectionalWithNulls.java | 140 +- .../primitive/PrimitiveAddDelete.java | 86 +- .../properties/PropertiesTestEntity.java | 89 +- .../UnversionedOptimisticLockingField.java | 51 +- ...versionedOptimisticLockingFieldEntity.java | 87 +- .../properties/VersionsProperties.java | 66 +- .../proxy/AuditedCollectionProxyTest.java | 88 +- .../integration/proxy/ProxyIdentifier.java | 72 +- .../proxy/QueryingWithProxyObjectTest.java | 85 +- .../proxy/RemovedObjectQueryTest.java | 29 +- .../integration/query/AggregateQuery.java | 148 +- .../query/CustomRevEntityQuery.java | 130 +- .../integration/query/DeletedEntities.java | 92 +- .../query/MaximalizePropertyQuery.java | 171 +-- .../integration/query/NullPropertyQuery.java | 140 +- .../integration/query/OrderByLimitQuery.java | 176 +-- .../query/RevisionConstraintQuery.java | 282 ++-- .../test/integration/query/SimpleQuery.java | 494 ++++--- .../integration/query/StoreDeletedData.java | 22 +- .../query/ids/EmbIdOneToManyQuery.java | 294 ++-- .../query/ids/MulIdOneToManyQuery.java | 280 ++-- .../ReadWriteExpressionChange.java | 81 +- .../readwriteexpression/Staff.java | 34 +- .../reference/BidirectionalReference.java | 148 +- .../integration/reference/GreetingPO.java | 17 +- .../integration/reference/GreetingSetPO.java | 19 +- .../reventity/CountingRevisionListener.java | 10 +- .../test/integration/reventity/Custom.java | 171 +-- .../integration/reventity/CustomBoxed.java | 171 +-- .../reventity/CustomBoxedRevEntity.java | 89 +- .../reventity/CustomColumnMapping.java | 148 +- .../integration/reventity/CustomDate.java | 151 +- .../reventity/CustomNoListener.java | 126 +- .../reventity/CustomPropertyAccess.java | 149 +- .../reventity/DifferentDBSchemaTest.java | 103 +- .../reventity/ExceptionListener.java | 39 +- .../reventity/ExceptionListenerRevEntity.java | 86 +- .../GloballyConfiguredRevListenerTest.java | 37 +- .../test/integration/reventity/Inherited.java | 171 +-- .../test/integration/reventity/Listener.java | 183 +-- .../reventity/ListenerRevEntity.java | 100 +- ...LongRevEntityInheritanceChildAuditing.java | 31 +- .../integration/reventity/LongRevNumber.java | 102 +- .../reventity/LongRevNumberRevEntity.java | 88 +- .../MonotonicRevisionNumberTest.java | 9 +- .../OverrideCustomRevListenerTest.java | 3 +- .../OverrideDefaultRevListenerTest.java | 3 +- .../TestExceptionRevisionListener.java | 6 +- .../reventity/TestRevisionListener.java | 9 +- .../AnnotatedTrackingEntitiesTest.java | 5 +- .../CustomTrackingEntitiesTest.java | 123 +- .../DefaultTrackingEntitiesTest.java | 267 ++-- .../EntityNamesTest.java | 106 +- .../ExtendedRevisionEntityTest.java | 29 +- .../TrackingEntitiesMultipleChangesTest.java | 121 +- .../revfordate/RevisionForDate.java | 128 +- .../sameids/SameIdTestEntity1.java | 87 +- .../sameids/SameIdTestEntity2.java | 87 +- .../test/integration/sameids/SameIds.java | 83 +- .../integration/secondary/BasicSecondary.java | 90 +- .../secondary/NamingSecondary.java | 90 +- .../secondary/SecondaryNamingTestEntity.java | 113 +- .../secondary/SecondaryTestEntity.java | 113 +- .../secondary/ids/EmbIdSecondary.java | 88 +- .../secondary/ids/MulIdSecondary.java | 88 +- .../ids/SecondaryEmbIdTestEntity.java | 111 +- .../ids/SecondaryMulIdTestEntity.java | 135 +- .../serialization/SerializingCollection.java | 74 +- .../ValidityAuditStrategyManyToManyTest.java | 182 +-- ...tyAuditStrategyRevEndTestCustomRevEnt.java | 482 ++++--- .../ValidityAuditStrategyRevEndTsTest.java | 493 ++++--- .../AuditedMethodMappedSuperclass.java | 13 +- .../NotAuditedSubclassEntity.java | 21 +- .../AuditedAllSubclassEntity.java | 81 +- .../MappedSubclassingAllAuditedTest.java | 89 +- .../AuditedMethodSubclassEntity.java | 83 +- .../MappedSubclassingMethodAuditedTest.java | 88 +- .../AuditedAllMappedSuperclass.java | 13 +- .../NotAuditedSubclassEntity.java | 21 +- .../AuditedAllSubclassEntity.java | 83 +- .../MappedSubclassingAllAuditedTest.java | 89 +- .../AuditedMethodSubclassEntity.java | 85 +- .../MappedSubclassingMethodAuditedTest.java | 90 +- .../auditoverride/AuditClassOverrideTest.java | 120 +- .../AuditPropertyOverrideTest.java | 148 +- .../auditoverride/AuditedBaseEntity.java | 118 +- .../auditoverride/AuditedSpecialEntity.java | 82 +- .../superclass/auditoverride/BaseEntity.java | 122 +- .../ClassOverrideAuditedEntity.java | 82 +- .../ClassOverrideNotAuditedEntity.java | 82 +- .../auditoverride/ExtendedBaseEntity.java | 114 +- .../auditoverride/MixedOverrideEntity.java | 86 +- .../auditoverride/MixedOverrideTest.java | 71 +- .../auditoverride/NotAuditedBaseEntity.java | 118 +- .../auditoverride/PropertyOverrideEntity.java | 86 +- .../TransitiveOverrideEntity.java | 92 +- .../auditparents/BabyCompleteEntity.java | 73 +- .../auditparents/ChildCompleteEntity.java | 74 +- .../ChildMultipleParentsEntity.java | 74 +- .../auditparents/ChildSingleParentEntity.java | 74 +- .../ExplicitTransitiveChildEntity.java | 68 +- .../ImplicitTransitiveChildEntity.java | 68 +- .../auditparents/MappedGrandparentEntity.java | 102 +- .../auditparents/MappedParentEntity.java | 85 +- .../MultipleAuditParentsTest.java | 109 +- .../auditparents/SingleAuditParentsTest.java | 114 +- .../auditparents/TotalAuditParentsTest.java | 110 +- .../TransitiveAuditParentsTest.java | 151 +- .../auditparents/TransitiveParentEntity.java | 68 +- .../integration/tools/SchemaExportTest.java | 70 +- .../AbstractEntityManagerTest.java | 111 +- .../performance/AbstractPerformanceTest.java | 107 +- .../test/performance/AllPerformance.java | 9 +- .../performance/ComplexInsertPerformance.java | 104 +- .../EvictAuditDataAfterCommitTest.java | 149 +- .../InsertsOneTransactionPerformance.java | 40 +- .../test/performance/InsertsPerformance.java | 44 +- .../test/performance/UpdatesPerformance.java | 74 +- .../performance/complex/ChildEntity1.java | 119 +- .../performance/complex/ChildEntity2.java | 105 +- .../test/performance/complex/RootEntity.java | 199 +-- .../envers/test/tools/TestTools.java | 2 +- .../envers/test/various/Address.java | 135 +- .../envers/test/various/HsqlTest.java | 98 +- .../hibernate/envers/test/various/Person.java | 111 +- shared/config/checkstyle/checkstyle.xml | 1 + 867 files changed, 45715 insertions(+), 37131 deletions(-) diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/AuditJoinTable.java b/hibernate-envers/src/main/java/org/hibernate/envers/AuditJoinTable.java index 894bcbc559..2a22d3a9f1 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/AuditJoinTable.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/AuditJoinTable.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,11 +22,12 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers; + +import javax.persistence.JoinColumn; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import javax.persistence.JoinColumn; /** * @author Adam Warski (adam at warski dot org) @@ -34,25 +35,25 @@ import javax.persistence.JoinColumn; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD}) public @interface AuditJoinTable { - /** - * @return Name of the join table. Defaults to a concatenation of the names of the primary table of the entity - * owning the association and of the primary table of the entity referenced by the association. - */ - String name() default ""; + /** + * Name of the join table. Defaults to a concatenation of the names of the primary table of the entity + * owning the association and of the primary table of the entity referenced by the association. + */ + String name() default ""; - /** - * @return The schema of the join table. Defaults to the schema of the entity owning the association. - */ - String schema() default ""; + /** + * The schema of the join table. Defaults to the schema of the entity owning the association. + */ + String schema() default ""; - /** - * @return The catalog of the join table. Defaults to the catalog of the entity owning the association. - */ - String catalog() default ""; + /** + * The catalog of the join table. Defaults to the catalog of the entity owning the association. + */ + String catalog() default ""; - /** - * @return The foreign key columns of the join table which reference the primary table of the entity that does not - * own the association (i.e. the inverse side of the association). - */ - JoinColumn[] inverseJoinColumns() default {}; + /** + * The foreign key columns of the join table which reference the primary table of the entity that does not + * own the association (i.e. the inverse side of the association). + */ + JoinColumn[] inverseJoinColumns() default {}; } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/AuditMappedBy.java b/hibernate-envers/src/main/java/org/hibernate/envers/AuditMappedBy.java index e5b1c4aeb4..8c86beea7e 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/AuditMappedBy.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/AuditMappedBy.java @@ -1,4 +1,5 @@ package org.hibernate.envers; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -11,7 +12,7 @@ import java.lang.annotation.Target; * the many side. Then, Envers won't use a join table to audit this relation, but will store changes as in a normal * bi-directional relation. *

      - * + *

      *

      * This annotation is experimental and may change in future releases. *

      @@ -21,16 +22,17 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD}) public @interface AuditMappedBy { - /** - * @return Name of the property in the related entity which maps back to this entity. The property should be - * mapped with {@code @ManyToOne} and {@code @Column(insertable=false, updatable=false)}. - */ - String mappedBy(); + /** + * Name of the property in the related entity which maps back to this entity. The property should be + * mapped with {@code @ManyToOne} and {@code @Column(insertable=false, updatable=false)}. + */ + String mappedBy(); - /** - * @return Name of the property in the related entity which maps to the position column. Should be specified only - * for indexed collection, when @{@link org.hibernate.annotations.IndexColumn} is used on the collection. - * The property should be mapped with {@code @Column(insertable=false, updatable=false)}. - */ - String positionMappedBy() default ""; + /** + * Name of the property in the related entity which maps to the position column. Should be specified only + * for indexed collection, when @{@link org.hibernate.annotations.IndexColumn} or + * {@link javax.persistence.OrderColumn} is used on the collection. The property should be mapped with + * {@code @Column(insertable=false, updatable=false)}. + */ + String positionMappedBy() default ""; } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/AuditOverride.java b/hibernate-envers/src/main/java/org/hibernate/envers/AuditOverride.java index 96dfea8dd1..0b5059fdad 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/AuditOverride.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/AuditOverride.java @@ -1,7 +1,30 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers; + import java.lang.annotation.Retention; import java.lang.annotation.Target; -import javax.persistence.MappedSuperclass; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; @@ -10,43 +33,44 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * The {@code AuditingOverride} annotation is used to override the auditing - * behavior of a superclass or single property inherited from {@link MappedSuperclass} + * behavior of a superclass or single property inherited from {@link javax.persistence.MappedSuperclass} * type, or attribute inside an embedded component. * * @author Erik-Berndt Scheper * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) + * * @see javax.persistence.Embedded * @see javax.persistence.Embeddable - * @see javax.persistence.MappedSuperclass + * @see javax.persistence.MappedSuperclass * @see javax.persistence.AssociationOverride * @see AuditJoinTable */ -@Target({ TYPE, METHOD, FIELD }) +@Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME) public @interface AuditOverride { /** - * @return Name of the field (or property) whose mapping is being overridden. Allows empty value if + * Name of the field (or property) whose mapping is being overridden. Allows empty value if * {@link AuditOverride} is used to change auditing behavior of all attributes inherited from - * {@link MappedSuperclass} type. + * {@link javax.persistence.MappedSuperclass} type. */ String name() default ""; /** - * @return Indicates if the field (or property) is audited; defaults to {@code true}. + * Indicates if the field (or property) is audited; defaults to {@code true}. */ boolean isAudited() default true; /** - * @return New {@link AuditJoinTable} used for this field (or property). Its value + * New {@link AuditJoinTable} used for this field (or property). Its value * is ignored if {@link #isAudited()} equals to {@code false}. */ AuditJoinTable auditJoinTable() default @AuditJoinTable; /** - * @return Specifies class which field (or property) mapping is being overridden. Required if - * {@link AuditOverride} is used to change auditing behavior of attributes inherited from {@link MappedSuperclass} - * type. + * Specifies class which field (or property) mapping is being overridden. Required if + * {@link AuditOverride} is used to change auditing behavior of attributes inherited from + * {@link javax.persistence.MappedSuperclass} type. */ Class forClass() default void.class; } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/AuditOverrides.java b/hibernate-envers/src/main/java/org/hibernate/envers/AuditOverrides.java index b4b4e095de..4f86cee9ae 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/AuditOverrides.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/AuditOverrides.java @@ -1,4 +1,28 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers; + import java.lang.annotation.Retention; import java.lang.annotation.Target; @@ -21,11 +45,11 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; * @see AuditJoinTable * @see AuditOverride */ -@Target({ TYPE, METHOD, FIELD }) +@Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME) public @interface AuditOverrides { /** - * @return An array of {@link AuditOverride} values, to define the new auditing + * An array of {@link AuditOverride} values, to define the new auditing * behavior. */ AuditOverride[] value(); diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/AuditReader.java b/hibernate-envers/src/main/java/org/hibernate/envers/AuditReader.java index 498a8ff22d..1230339e2b 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/AuditReader.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/AuditReader.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -40,207 +40,241 @@ import org.hibernate.envers.query.AuditQueryCreator; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public interface AuditReader { - /** - * Find an entity by primary key at the given revision. - * @param cls Class of the entity. - * @param primaryKey Primary key of the entity. - * @param revision Revision in which to get the entity. - * @return The found entity instance at the given revision (its properties may be partially filled - * if not all properties are audited) or null, if an entity with that id didn't exist at that - * revision. - * @throws IllegalArgumentException If cls or primaryKey is null or revision is less or equal to 0. - * @throws NotAuditedException When entities of the given class are not audited. - * @throws IllegalStateException If the associated entity manager is closed. - */ - T find(Class cls, Object primaryKey, Number revision) throws - IllegalArgumentException, NotAuditedException, IllegalStateException; - - /** - * Find an entity by primary key at the given revision with the specified entityName. - * @param cls Class of the entity. - * @param entityName Name of the entity (if can't be guessed basing on the {@code cls}). - * @param primaryKey Primary key of the entity. - * @param revision Revision in which to get the entity. - * @return The found entity instance at the given revision (its properties may be partially filled - * if not all properties are audited) or null, if an entity with that id didn't exist at that - * revision. - * @throws IllegalArgumentException If cls or primaryKey is null or revision is less or equal to 0. - * @throws NotAuditedException When entities of the given class are not audited. - * @throws IllegalStateException If the associated entity manager is closed. - */ - T find(Class cls, String entityName, Object primaryKey, + /** + * Find an entity by primary key at the given revision. + * + * @param cls Class of the entity. + * @param primaryKey Primary key of the entity. + * @param revision Revision in which to get the entity. + * @param The type of the entity to find + * + * @return The found entity instance at the given revision (its properties may be partially filled + * if not all properties are audited) or null, if an entity with that id didn't exist at that + * revision. + * + * @throws IllegalArgumentException If cls or primaryKey is null or revision is less or equal to 0. + * @throws NotAuditedException When entities of the given class are not audited. + * @throws IllegalStateException If the associated entity manager is closed. + */ + T find(Class cls, Object primaryKey, Number revision) throws + IllegalArgumentException, NotAuditedException, IllegalStateException; + + /** + * Find an entity by primary key at the given revision with the specified entityName. + * + * @param cls Class of the entity. + * @param entityName Name of the entity (if can't be guessed basing on the {@code cls}). + * @param primaryKey Primary key of the entity. + * @param revision Revision in which to get the entity. + * @param The type of the entity to find + * + * @return The found entity instance at the given revision (its properties may be partially filled + * if not all properties are audited) or null, if an entity with that id didn't exist at that + * revision. + * + * @throws IllegalArgumentException If cls or primaryKey is null or revision is less or equal to 0. + * @throws NotAuditedException When entities of the given class are not audited. + * @throws IllegalStateException If the associated entity manager is closed. + */ + T find( + Class cls, String entityName, Object primaryKey, Number revision) throws IllegalArgumentException, NotAuditedException, IllegalStateException; - /** - * Find an entity by primary key at the given revision with the specified entityName, - * possibly including deleted entities in the search. - * @param cls Class of the entity. - * @param entityName Name of the entity (if can't be guessed basing on the {@code cls}). - * @param primaryKey Primary key of the entity. - * @param revision Revision in which to get the entity. - * @param includeDeletions Whether to include deleted entities in the search. - * @return The found entity instance at the given revision (its properties may be partially filled - * if not all properties are audited) or null, if an entity with that id didn't exist at that - * revision. - * @throws IllegalArgumentException If cls or primaryKey is null or revision is less or equal to 0. - * @throws NotAuditedException When entities of the given class are not audited. - * @throws IllegalStateException If the associated entity manager is closed. - */ - T find(Class cls, String entityName, Object primaryKey, + /** + * Find an entity by primary key at the given revision with the specified entityName, + * possibly including deleted entities in the search. + * + * @param cls Class of the entity. + * @param entityName Name of the entity (if can't be guessed basing on the {@code cls}). + * @param primaryKey Primary key of the entity. + * @param revision Revision in which to get the entity. + * @param includeDeletions Whether to include deleted entities in the search. + * @param The type of the entity to find + * + * @return The found entity instance at the given revision (its properties may be partially filled + * if not all properties are audited) or null, if an entity with that id didn't exist at that + * revision. + * + * @throws IllegalArgumentException If cls or primaryKey is null or revision is less or equal to 0. + * @throws NotAuditedException When entities of the given class are not audited. + * @throws IllegalStateException If the associated entity manager is closed. + */ + T find( + Class cls, String entityName, Object primaryKey, Number revision, boolean includeDeletions) throws IllegalArgumentException, NotAuditedException, IllegalStateException; - - /** - * Get a list of revision numbers, at which an entity was modified. - * @param cls Class of the entity. - * @param primaryKey Primary key of the entity. - * @return A list of revision numbers, at which the entity was modified, sorted in ascending order (so older - * revisions come first). - * @throws NotAuditedException When entities of the given class are not audited. - * @throws IllegalArgumentException If cls or primaryKey is null. - * @throws IllegalStateException If the associated entity manager is closed. - */ - List getRevisions(Class cls, Object primaryKey) - throws IllegalArgumentException, NotAuditedException, IllegalStateException; - - /** - * Get a list of revision numbers, at which an entity was modified, looking by entityName. - * @param cls Class of the entity. - * @param entityName Name of the entity (if can't be guessed basing on the {@code cls}). - * @param primaryKey Primary key of the entity. - * @return A list of revision numbers, at which the entity was modified, sorted in ascending order (so older - * revisions come first). - * @throws NotAuditedException When entities of the given class are not audited. - * @throws IllegalArgumentException If cls or primaryKey is null. - * @throws IllegalStateException If the associated entity manager is closed. - */ - List getRevisions(Class cls, String entityName, Object primaryKey) + + /** + * Get a list of revision numbers, at which an entity was modified. + * + * @param cls Class of the entity. + * @param primaryKey Primary key of the entity. + * + * @return A list of revision numbers, at which the entity was modified, sorted in ascending order (so older + * revisions come first). + * + * @throws NotAuditedException When entities of the given class are not audited. + * @throws IllegalArgumentException If cls or primaryKey is null. + * @throws IllegalStateException If the associated entity manager is closed. + */ + List getRevisions(Class cls, Object primaryKey) + throws IllegalArgumentException, NotAuditedException, IllegalStateException; + + /** + * Get a list of revision numbers, at which an entity was modified, looking by entityName. + * + * @param cls Class of the entity. + * @param entityName Name of the entity (if can't be guessed basing on the {@code cls}). + * @param primaryKey Primary key of the entity. + * + * @return A list of revision numbers, at which the entity was modified, sorted in ascending order (so older + * revisions come first). + * + * @throws NotAuditedException When entities of the given class are not audited. + * @throws IllegalArgumentException If cls or primaryKey is null. + * @throws IllegalStateException If the associated entity manager is closed. + */ + List getRevisions(Class cls, String entityName, Object primaryKey) throws IllegalArgumentException, NotAuditedException, IllegalStateException; - /** - * Get the date, at which a revision was created. - * @param revision Number of the revision for which to get the date. - * @return Date of commiting the given revision. - * @throws IllegalArgumentException If revision is less or equal to 0. - * @throws RevisionDoesNotExistException If the revision does not exist. - * @throws IllegalStateException If the associated entity manager is closed. - */ - Date getRevisionDate(Number revision) throws IllegalArgumentException, RevisionDoesNotExistException, - IllegalStateException; - - /** - * Gets the revision number, that corresponds to the given date. More precisely, returns - * the number of the highest revision, which was created on or before the given date. So: - * getRevisionDate(getRevisionNumberForDate(date)) <= date and - * getRevisionDate(getRevisionNumberForDate(date)+1) > date. - * @param date Date for which to get the revision. - * @return Revision number corresponding to the given date. - * @throws IllegalStateException If the associated entity manager is closed. - * @throws RevisionDoesNotExistException If the given date is before the first revision. - * @throws IllegalArgumentException If date is null. - */ - Number getRevisionNumberForDate(Date date) throws IllegalStateException, RevisionDoesNotExistException, - IllegalArgumentException; - - /** - * A helper method; should be used only if a custom revision entity is used. See also {@link RevisionEntity}. - * @param revisionEntityClass Class of the revision entity. Should be annotated with {@link RevisionEntity}. - * @param revision Number of the revision for which to get the data. - * @return Entity containing data for the given revision. - * @throws IllegalArgumentException If revision is less or equal to 0 or if the class of the revision entity - * is invalid. - * @throws RevisionDoesNotExistException If the revision does not exist. - * @throws IllegalStateException If the associated entity manager is closed. - */ - T findRevision(Class revisionEntityClass, Number revision) throws IllegalArgumentException, - RevisionDoesNotExistException, IllegalStateException; - - /** - * Find a map of revisions using the revision numbers specified. - * - * @param revisionEntityClass - * Class of the revision entity. Should be annotated with - * {@link RevisionEntity}. - * @param revisions - * Revision numbers of the revision for which to get the data. - * @return A map of revision number and the given revision entity. - * @throws IllegalArgumentException - * If a revision number is less or equal to 0 or if the class of - * the revision entity is invalid. - * @throws IllegalStateException - * If the associated entity manager is closed. + /** + * Get the date, at which a revision was created. + * + * @param revision Number of the revision for which to get the date. + * + * @return Date of commiting the given revision. + * + * @throws IllegalArgumentException If revision is less or equal to 0. + * @throws RevisionDoesNotExistException If the revision does not exist. + * @throws IllegalStateException If the associated entity manager is closed. */ - Map findRevisions(Class revisionEntityClass, + Date getRevisionDate(Number revision) throws IllegalArgumentException, RevisionDoesNotExistException, + IllegalStateException; + + /** + * Gets the revision number, that corresponds to the given date. More precisely, returns + * the number of the highest revision, which was created on or before the given date. So: + * getRevisionDate(getRevisionNumberForDate(date)) <= date and + * getRevisionDate(getRevisionNumberForDate(date)+1) > date. + * + * @param date Date for which to get the revision. + * + * @return Revision number corresponding to the given date. + * + * @throws IllegalStateException If the associated entity manager is closed. + * @throws RevisionDoesNotExistException If the given date is before the first revision. + * @throws IllegalArgumentException If date is null. + */ + Number getRevisionNumberForDate(Date date) throws IllegalStateException, RevisionDoesNotExistException, + IllegalArgumentException; + + /** + * A helper method; should be used only if a custom revision entity is used. See also {@link RevisionEntity}. + * + * @param revisionEntityClass Class of the revision entity. Should be annotated with {@link RevisionEntity}. + * @param revision Number of the revision for which to get the data. + * @param The type of the revision entity to find + * + * @return Entity containing data for the given revision. + * + * @throws IllegalArgumentException If revision is less or equal to 0 or if the class of the revision entity + * is invalid. + * @throws RevisionDoesNotExistException If the revision does not exist. + * @throws IllegalStateException If the associated entity manager is closed. + */ + T findRevision(Class revisionEntityClass, Number revision) throws IllegalArgumentException, + RevisionDoesNotExistException, IllegalStateException; + + /** + * Find a map of revisions using the revision numbers specified. + * + * @param revisionEntityClass Class of the revision entity. Should be annotated with + * {@link RevisionEntity}. + * @param revisions Revision numbers of the revision for which to get the data. + * @param The type of the revision entity to find + * + * @return A map of revision number and the given revision entity. + * + * @throws IllegalArgumentException If a revision number is less or equal to 0 or if the class of + * the revision entity is invalid. + * @throws IllegalStateException If the associated entity manager is closed. + */ + Map findRevisions( + Class revisionEntityClass, Set revisions) throws IllegalArgumentException, IllegalStateException; - + /** * Gets an instance of the current revision entity, to which any entries in the audit tables will be bound. * Please note the if {@code persist} is {@code false}, and no audited entities are modified in this session, * then the obtained revision entity instance won't be persisted. If {@code persist} is {@code true}, the revision * entity instance will always be persisted, regardless of whether audited entities are changed or not. + * * @param revisionEntityClass Class of the revision entity. Should be annotated with {@link RevisionEntity}. * @param persist If the revision entity is not yet persisted, should it become persisted. This way, the primary * identifier (id) will be filled (if it's assigned by the DB) and available, but the revision entity will be * persisted even if there are no changes to audited entities. Otherwise, the revision number (id) can be * {@code null}. + * @param The type of the revision entity to find + * * @return The current revision entity, to which any entries in the audit tables will be bound. */ T getCurrentRevision(Class revisionEntityClass, boolean persist); - /** - * - * @return A query creator, associated with this AuditReader instance, with which queries can be - * created and later executed. Shouldn't be used after the associated Session or EntityManager - * is closed. - */ - AuditQueryCreator createQuery(); + /** + * Creates an audit query + * + * @return A query creator, associated with this AuditReader instance, with which queries can be + * created and later executed. Shouldn't be used after the associated Session or EntityManager + * is closed. + */ + AuditQueryCreator createQuery(); - /** + /** * Checks if the entityClass was configured to be audited. Calling * isEntityNameAudited() with the string of the class name will return the * same value. - * - * @param entityClass - * Class of the entity asking for audit support - * @return true if the entityClass is audited. - */ - boolean isEntityClassAudited(Class entityClass); - + * + * @param entityClass Class of the entity asking for audit support + * + * @return true if the entityClass is audited. + */ + boolean isEntityClassAudited(Class entityClass); + /** * Checks if the entityName was configured to be audited. - * + * * @param entityName EntityName of the entity asking for audit support. + * * @return true if the entityName is audited. */ - boolean isEntityNameAudited(String entityName); + boolean isEntityNameAudited(String entityName); /** - * - * @param entity - * that was obtained previously from the same AuditReader. - * + * @param entity that was obtained previously from the same AuditReader. + * * @return the entityName for the given entity, null in case the entity is * not associated with this AuditReader instance. */ String getEntityName(Object primaryKey, Number revision, Object entity) throws HibernateException; - /** - * @return Basic implementation of {@link CrossTypeRevisionChangesReader} interface. Raises an exception if the default - * mechanism of tracking entity names modified during revisions has not been enabled. - * @throws AuditException If none of the following conditions is satisfied: - *
        - *
      • org.hibernate.envers.track_entities_changed_in_revision - * parameter is set to true.
      • - *
      • Custom revision entity (annotated with {@link RevisionEntity}) - * extends {@link DefaultTrackingModifiedEntitiesRevisionEntity} base class.
      • - *
      • Custom revision entity (annotated with {@link RevisionEntity}) encapsulates a field - * marked with {@link ModifiedEntityNames} interface.
      • - *
      - */ - public CrossTypeRevisionChangesReader getCrossTypeRevisionChangesReader() throws AuditException; + /** + * @return Basic implementation of {@link CrossTypeRevisionChangesReader} interface. Raises an exception if the default + * mechanism of tracking entity names modified during revisions has not been enabled. + * + * @throws AuditException If none of the following conditions is satisfied: + *
        + *
      • org.hibernate.envers.track_entities_changed_in_revision + * parameter is set to true.
      • + *
      • Custom revision entity (annotated with {@link RevisionEntity}) + * extends {@link DefaultTrackingModifiedEntitiesRevisionEntity} base class.
      • + *
      • Custom revision entity (annotated with {@link RevisionEntity}) encapsulates a field + * marked with {@link ModifiedEntityNames} interface.
      • + *
      + */ + public CrossTypeRevisionChangesReader getCrossTypeRevisionChangesReader() throws AuditException; } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/AuditReaderFactory.java b/hibernate-envers/src/main/java/org/hibernate/envers/AuditReaderFactory.java index 74302e7fb9..c19facf355 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/AuditReaderFactory.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/AuditReaderFactory.java @@ -38,20 +38,25 @@ import org.hibernate.event.spi.PostInsertEventListener; * @author Adam Warski (adam at warski dot org) */ public class AuditReaderFactory { - private AuditReaderFactory() { } + private AuditReaderFactory() { + } - /** - * Create an audit reader associated with an open session. - * @param session An open session. - * @return An audit reader associated with the given sesison. It shouldn't be used - * after the session is closed. - * @throws AuditException When the given required listeners aren't installed. - */ - public static AuditReader get(Session session) throws AuditException { - SessionImplementor sessionImpl; - if (!(session instanceof SessionImplementor)) { + /** + * Create an audit reader associated with an open session. + * + * @param session An open session. + * + * @return An audit reader associated with the given sesison. It shouldn't be used + * after the session is closed. + * + * @throws AuditException When the given required listeners aren't installed. + */ + public static AuditReader get(Session session) throws AuditException { + SessionImplementor sessionImpl; + if ( !(session instanceof SessionImplementor) ) { sessionImpl = (SessionImplementor) session.getSessionFactory().getCurrentSession(); - } else { + } + else { sessionImpl = (SessionImplementor) session; } @@ -61,37 +66,41 @@ public class AuditReaderFactory { .getServiceRegistry() .getService( EventListenerRegistry.class ); - for ( PostInsertEventListener listener : listenerRegistry.getEventListenerGroup( EventType.POST_INSERT ).listeners() ) { + for ( PostInsertEventListener listener : listenerRegistry.getEventListenerGroup( EventType.POST_INSERT ) + .listeners() ) { if ( listener instanceof EnversListener ) { // todo : slightly different from original code in that I am not checking the other listener groups... return new AuditReaderImpl( - ( (EnversListener) listener ).getAuditConfiguration(), + ((EnversListener) listener).getAuditConfiguration(), session, sessionImpl ); } } - throw new AuditException( "Envers listeners were not properly registered" ); - } + throw new AuditException( "Envers listeners were not properly registered" ); + } - /** - * Create an audit reader associated with an open entity manager. - * @param entityManager An open entity manager. - * @return An audit reader associated with the given entity manager. It shouldn't be used - * after the entity manager is closed. - * @throws AuditException When the given entity manager is not based on Hibernate, or if the required - * listeners aren't installed. - */ - public static AuditReader get(EntityManager entityManager) throws AuditException { - if (entityManager.getDelegate() instanceof Session) { - return get((Session) entityManager.getDelegate()); - } + /** + * Create an audit reader associated with an open entity manager. + * + * @param entityManager An open entity manager. + * + * @return An audit reader associated with the given entity manager. It shouldn't be used + * after the entity manager is closed. + * + * @throws AuditException When the given entity manager is not based on Hibernate, or if the required + * listeners aren't installed. + */ + public static AuditReader get(EntityManager entityManager) throws AuditException { + if ( entityManager.getDelegate() instanceof Session ) { + return get( (Session) entityManager.getDelegate() ); + } - if (entityManager.getDelegate() instanceof EntityManager) { - return get((EntityManager) entityManager.getDelegate()); - } + if ( entityManager.getDelegate() instanceof EntityManager ) { + return get( (EntityManager) entityManager.getDelegate() ); + } - throw new AuditException("Hibernate EntityManager not present!"); - } + throw new AuditException( "Hibernate EntityManager not present!" ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/AuditTable.java b/hibernate-envers/src/main/java/org/hibernate/envers/AuditTable.java index dfeaed32cc..d4e5b91c23 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/AuditTable.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/AuditTable.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -33,15 +34,18 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface AuditTable { - String value(); + /** + * The name of the table + */ + String value(); - /** - * @return The schema of the table. Defaults to the schema of the annotated entity. - */ - String schema() default ""; + /** + * The schema of the table. Defaults to the schema of the annotated entity. + */ + String schema() default ""; - /** - * @return The catalog of the table. Defaults to the catalog of the annotated entity. - */ - String catalog() default ""; + /** + * The catalog of the table. Defaults to the catalog of the annotated entity. + */ + String catalog() default ""; } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/Audited.java b/hibernate-envers/src/main/java/org/hibernate/envers/Audited.java index f37e768677..5afb0f5905 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/Audited.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/Audited.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -30,6 +31,7 @@ import java.lang.annotation.Target; /** * When applied to a class, indicates that all of its properties should be audited. * When applied to a field, indicates that this field should be audited. + * * @author Adam Warski (adam at warski dot org) * @author Tomasz Bech * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) @@ -38,33 +40,37 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD}) public @interface Audited { - ModificationStore modStore() default ModificationStore.FULL; + /** + * Specifies modification store to use + */ + ModificationStore modStore() default ModificationStore.FULL; /** - * @return Specifies if the entity that is the target of the relation should be audited or not. If not, then when + * Specifies if the entity that is the target of the relation should be audited or not. If not, then when * reading a historic version an audited entity, the relation will always point to the "current" entity. * This is useful for dictionary-like entities, which don't change and don't need to be audited. */ - RelationTargetAuditMode targetAuditMode() default RelationTargetAuditMode.AUDITED; + RelationTargetAuditMode targetAuditMode() default RelationTargetAuditMode.AUDITED; - /** - * @return Specifies the superclasses for which properties should be audited, even if the superclasses are not - * annotated with {@link Audited}. Causes all properties of the listed classes to be audited, just as if the - * classes had {@link Audited} annotation applied on the class level. - * - * The scope of this functionality is limited to the class hierarchy of the annotated entity. - * - * If a parent type lists any of its parent types using this attribute, all properties in the specified classes - * will also be audited. - * - * @deprecated Use {@code @AuditOverride(forClass=SomeEntity.class)} instead. - */ - Class[] auditParents() default {}; + /** + * Specifies the superclasses for which properties should be audited, even if the superclasses are not + * annotated with {@link Audited}. Causes all properties of the listed classes to be audited, just as if the + * classes had {@link Audited} annotation applied on the class level. + *

      + * The scope of this functionality is limited to the class hierarchy of the annotated entity. + *

      + * If a parent type lists any of its parent types using this attribute, all properties in the specified classes + * will also be audited. + * + * @deprecated Use {@code @AuditOverride(forClass=SomeEntity.class)} instead. + */ + @Deprecated + Class[] auditParents() default {}; - /** - * @return Should a modification flag be stored for each property in the annotated class or for the annotated - * property. The flag stores information if a property has been changed at a given revision. - * This can be used for example in queries. - */ + /** + * Should a modification flag be stored for each property in the annotated class or for the annotated + * property. The flag stores information if a property has been changed at a given revision. + * This can be used for example in queries. + */ boolean withModifiedFlag() default false; } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/CrossTypeRevisionChangesReader.java b/hibernate-envers/src/main/java/org/hibernate/envers/CrossTypeRevisionChangesReader.java index f488ae0e36..d7675cb7e6 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/CrossTypeRevisionChangesReader.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/CrossTypeRevisionChangesReader.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers; import java.util.List; @@ -10,52 +33,67 @@ import org.hibernate.envers.tools.Pair; * Queries that allow retrieving snapshots of all entities (regardless of their particular type) changed in the given * revision. Note that this API can be legally used only when default mechanism of tracking modified entity names * is enabled. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public interface CrossTypeRevisionChangesReader { - /** - * Find all entities changed (added, updated and removed) in a given revision. Executes n+1 SQL queries, - * where n is a number of different entity classes modified within specified revision. - * @param revision Revision number. - * @return Snapshots of all audited entities changed in a given revision. - * @throws IllegalStateException If the associated entity manager is closed. - * @throws IllegalArgumentException If a revision number is null, less or equal to 0. - */ - public List findEntities(Number revision) throws IllegalStateException, IllegalArgumentException; + /** + * Find all entities changed (added, updated and removed) in a given revision. Executes n+1 SQL queries, + * where n is a number of different entity classes modified within specified revision. + * + * @param revision Revision number. + * + * @return Snapshots of all audited entities changed in a given revision. + * + * @throws IllegalStateException If the associated entity manager is closed. + * @throws IllegalArgumentException If a revision number is null, less or equal to 0. + */ + public List findEntities(Number revision) throws IllegalStateException, IllegalArgumentException; - /** - * Find all entities changed (added, updated or removed) in a given revision. Executes n+1 SQL queries, - * where n is a number of different entity classes modified within specified revision. - * @param revision Revision number. - * @param revisionType Type of modification. - * @return Snapshots of all audited entities changed in a given revision and filtered by modification type. - * @throws IllegalStateException If the associated entity manager is closed. - * @throws IllegalArgumentException If a revision number is {@code null}, less or equal to 0. - */ - public List findEntities(Number revision, RevisionType revisionType) throws IllegalStateException, - IllegalArgumentException; + /** + * Find all entities changed (added, updated or removed) in a given revision. Executes n+1 SQL queries, + * where n is a number of different entity classes modified within specified revision. + * + * @param revision Revision number. + * @param revisionType Type of modification. + * + * @return Snapshots of all audited entities changed in a given revision and filtered by modification type. + * + * @throws IllegalStateException If the associated entity manager is closed. + * @throws IllegalArgumentException If a revision number is {@code null}, less or equal to 0. + */ + public List findEntities(Number revision, RevisionType revisionType) throws IllegalStateException, + IllegalArgumentException; - /** - * Find all entities changed (added, updated and removed) in a given revision grouped by modification type. - * Executes mn+1 SQL queries, where: - *
        - *
      • n - number of different entity classes modified within specified revision. - *
      • m - number of different revision types. See {@link RevisionType} enum. - *
      - * @param revision Revision number. - * @return Map containing lists of entity snapshots grouped by modification operation (e.g. addition, update, removal). - * @throws IllegalStateException If the associated entity manager is closed. - * @throws IllegalArgumentException If a revision number is {@code null}, less or equal to 0. - */ - public Map> findEntitiesGroupByRevisionType(Number revision) throws IllegalStateException, - IllegalArgumentException; + /** + * Find all entities changed (added, updated and removed) in a given revision grouped by modification type. + * Executes mn+1 SQL queries, where: + *
        + *
      • n - number of different entity classes modified within specified revision. + *
      • m - number of different revision types. See {@link RevisionType} enum. + *
      + * + * @param revision Revision number. + * + * @return Map containing lists of entity snapshots grouped by modification operation (e.g. addition, update, removal). + * + * @throws IllegalStateException If the associated entity manager is closed. + * @throws IllegalArgumentException If a revision number is {@code null}, less or equal to 0. + */ + public Map> findEntitiesGroupByRevisionType(Number revision) + throws IllegalStateException, + IllegalArgumentException; - /** - * Returns set of entity names and corresponding Java classes modified in a given revision. - * @param revision Revision number. - * @return Set of entity names and corresponding Java classes modified in a given revision. - * @throws IllegalStateException If the associated entity manager is closed. - * @throws IllegalArgumentException If a revision number is {@code null}, less or equal to 0. - */ - public Set> findEntityTypes(Number revision) throws IllegalStateException, IllegalArgumentException; + /** + * Returns set of entity names and corresponding Java classes modified in a given revision. + * + * @param revision Revision number. + * + * @return Set of entity names and corresponding Java classes modified in a given revision. + * + * @throws IllegalStateException If the associated entity manager is closed. + * @throws IllegalArgumentException If a revision number is {@code null}, less or equal to 0. + */ + public Set> findEntityTypes(Number revision) + throws IllegalStateException, IllegalArgumentException; } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/DefaultRevisionEntity.java b/hibernate-envers/src/main/java/org/hibernate/envers/DefaultRevisionEntity.java index 13d32a2629..539144bdd0 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/DefaultRevisionEntity.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/DefaultRevisionEntity.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,13 +22,14 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers; -import java.io.Serializable; -import java.text.DateFormat; -import java.util.Date; + import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import javax.persistence.Transient; +import java.io.Serializable; +import java.text.DateFormat; +import java.util.Date; /** * @author Adam Warski (adam at warski dot org) @@ -36,56 +37,61 @@ import javax.persistence.Transient; @MappedSuperclass public class DefaultRevisionEntity implements Serializable { private static final long serialVersionUID = 8530213963961662300L; - - @Id - @GeneratedValue - @RevisionNumber - private int id; - @RevisionTimestamp - private long timestamp; + @Id + @GeneratedValue + @RevisionNumber + private int id; - public int getId() { - return id; - } + @RevisionTimestamp + private long timestamp; - public void setId(int id) { - this.id = id; - } + public int getId() { + return id; + } - @Transient - public Date getRevisionDate() { - return new Date(timestamp); - } + public void setId(int id) { + this.id = id; + } - public long getTimestamp() { - return timestamp; - } + @Transient + public Date getRevisionDate() { + return new Date( timestamp ); + } - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } + public long getTimestamp() { + return timestamp; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof DefaultRevisionEntity)) return false; + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } - DefaultRevisionEntity that = (DefaultRevisionEntity) o; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof DefaultRevisionEntity) ) { + return false; + } - if (id != that.id) return false; - if (timestamp != that.timestamp) return false; + final DefaultRevisionEntity that = (DefaultRevisionEntity) o; + return id == that.id + && timestamp == that.timestamp; + } - return true; - } + @Override + public int hashCode() { + int result; + result = id; + result = 31 * result + (int) (timestamp ^ (timestamp >>> 32)); + return result; + } - public int hashCode() { - int result; - result = id; - result = 31 * result + (int) (timestamp ^ (timestamp >>> 32)); - return result; - } - - public String toString() { - return "DefaultRevisionEntity(id = " + id + ", revisionDate = " + DateFormat.getDateTimeInstance().format(getRevisionDate()) + ")"; - } + @Override + public String toString() { + return "DefaultRevisionEntity(id = " + id + + ", revisionDate = " + DateFormat.getDateTimeInstance().format( getRevisionDate() ) + ")"; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/DefaultTrackingModifiedEntitiesRevisionEntity.java b/hibernate-envers/src/main/java/org/hibernate/envers/DefaultTrackingModifiedEntitiesRevisionEntity.java index ca4969ff9c..b6ee60687e 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/DefaultTrackingModifiedEntitiesRevisionEntity.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/DefaultTrackingModifiedEntitiesRevisionEntity.java @@ -1,13 +1,36 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers; -import java.util.HashSet; -import java.util.Set; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.MappedSuperclass; +import java.util.HashSet; +import java.util.Set; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; @@ -16,45 +39,57 @@ import org.hibernate.annotations.FetchMode; * Extension of standard {@link DefaultRevisionEntity} that allows tracking entity names changed in each revision. * This revision entity is implicitly used when {@code org.hibernate.envers.track_entities_changed_in_revision} * parameter is set to {@code true}. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @MappedSuperclass public class DefaultTrackingModifiedEntitiesRevisionEntity extends DefaultRevisionEntity { - @ElementCollection(fetch = FetchType.EAGER) - @JoinTable(name = "REVCHANGES", joinColumns = @JoinColumn(name = "REV")) - @Column(name = "ENTITYNAME") - @Fetch(FetchMode.JOIN) - @ModifiedEntityNames - private Set modifiedEntityNames = new HashSet(); + @ElementCollection(fetch = FetchType.EAGER) + @JoinTable(name = "REVCHANGES", joinColumns = @JoinColumn(name = "REV")) + @Column(name = "ENTITYNAME") + @Fetch(FetchMode.JOIN) + @ModifiedEntityNames + private Set modifiedEntityNames = new HashSet(); - public Set getModifiedEntityNames() { - return modifiedEntityNames; - } + public Set getModifiedEntityNames() { + return modifiedEntityNames; + } - public void setModifiedEntityNames(Set modifiedEntityNames) { - this.modifiedEntityNames = modifiedEntityNames; - } + public void setModifiedEntityNames(Set modifiedEntityNames) { + this.modifiedEntityNames = modifiedEntityNames; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof DefaultTrackingModifiedEntitiesRevisionEntity)) return false; - if (!super.equals(o)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof DefaultTrackingModifiedEntitiesRevisionEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - DefaultTrackingModifiedEntitiesRevisionEntity that = (DefaultTrackingModifiedEntitiesRevisionEntity) o; + final DefaultTrackingModifiedEntitiesRevisionEntity that = (DefaultTrackingModifiedEntitiesRevisionEntity) o; - if (modifiedEntityNames != null ? !modifiedEntityNames.equals(that.modifiedEntityNames) - : that.modifiedEntityNames != null) return false; + if ( modifiedEntityNames != null ? !modifiedEntityNames.equals( that.modifiedEntityNames ) + : that.modifiedEntityNames != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (modifiedEntityNames != null ? modifiedEntityNames.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (modifiedEntityNames != null ? modifiedEntityNames.hashCode() : 0); + return result; + } - public String toString() { - return "DefaultTrackingModifiedEntitiesRevisionEntity(" + super.toString() + ", modifiedEntityNames = " + modifiedEntityNames + ")"; - } + @Override + public String toString() { + return "DefaultTrackingModifiedEntitiesRevisionEntity(" + super.toString() + ", modifiedEntityNames = " + modifiedEntityNames + ")"; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/EntityTrackingRevisionListener.java b/hibernate-envers/src/main/java/org/hibernate/envers/EntityTrackingRevisionListener.java index 0366b7f183..6fb9139249 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/EntityTrackingRevisionListener.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/EntityTrackingRevisionListener.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers; import java.io.Serializable; @@ -5,19 +28,22 @@ import java.io.Serializable; /** * Extension of standard {@link RevisionListener} that notifies whenever an entity instance has been * added, modified or removed within current revision boundaries. - * @see RevisionListener + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) + * @see RevisionListener */ public interface EntityTrackingRevisionListener extends RevisionListener { - /** - * Called after audited entity data has been persisted. - * @param entityClass Audited entity class. - * @param entityName Name of the audited entity. May be useful when Java class is mapped multiple times, - * potentially to different tables. - * @param entityId Identifier of modified entity. - * @param revisionType Modification type (addition, update or removal). - * @param revisionEntity An instance of the entity annotated with {@link RevisionEntity}. - */ - void entityChanged(Class entityClass, String entityName, Serializable entityId, RevisionType revisionType, - Object revisionEntity); + /** + * Called after audited entity data has been persisted. + * + * @param entityClass Audited entity class. + * @param entityName Name of the audited entity. May be useful when Java class is mapped multiple times, + * potentially to different tables. + * @param entityId Identifier of modified entity. + * @param revisionType Modification type (addition, update or removal). + * @param revisionEntity An instance of the entity annotated with {@link RevisionEntity}. + */ + void entityChanged( + Class entityClass, String entityName, Serializable entityId, RevisionType revisionType, + Object revisionEntity); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/ModificationStore.java b/hibernate-envers/src/main/java/org/hibernate/envers/ModificationStore.java index dfc471068b..802dab8181 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/ModificationStore.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/ModificationStore.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -28,5 +28,5 @@ package org.hibernate.envers; * @author Adam Warski (adam at warski dot org) */ public enum ModificationStore { - FULL + FULL } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/ModifiedEntityNames.java b/hibernate-envers/src/main/java/org/hibernate/envers/ModifiedEntityNames.java index 1bd81775dd..cf02555434 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/ModifiedEntityNames.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/ModifiedEntityNames.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers; import java.lang.annotation.ElementType; @@ -8,6 +31,7 @@ import java.lang.annotation.Target; /** * Marks a property which holds entity names that have been modified during each revision. * This annotation expects field of {@literal Set} type. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @Retention(RetentionPolicy.RUNTIME) diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/NotAudited.java b/hibernate-envers/src/main/java/org/hibernate/envers/NotAudited.java index 4281014749..385589a478 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/NotAudited.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/NotAudited.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -29,6 +30,7 @@ import java.lang.annotation.Target; /** * When applied to a field, indicates that this field should not be audited. + * * @author Sebastian Komander */ @Retention(RetentionPolicy.RUNTIME) diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/RelationTargetAuditMode.java b/hibernate-envers/src/main/java/org/hibernate/envers/RelationTargetAuditMode.java index 1725a5e946..8b0e4d6808 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/RelationTargetAuditMode.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/RelationTargetAuditMode.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionEntity.java b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionEntity.java index 37328ff5b9..e8882a141e 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionEntity.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionEntity.java @@ -34,15 +34,15 @@ import java.lang.annotation.Target; * and a long-valued property annotated with {@link RevisionTimestamp}. The {@link DefaultRevisionEntity} * already has those two fields, so you may extend it, but you may also write your own revision entity * from scratch. - * + * * @author Adam Warski (adam at warski dot org) */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface RevisionEntity { - /** - * @return The optional listener that will be used to fill in the custom revision entity. - * May also be specified using the {@code org.hibernate.envers.revision_listener} configuration property. - */ - Class value() default RevisionListener.class; + /** + * The optional listener that will be used to fill in the custom revision entity. + * May also be specified using the {@code org.hibernate.envers.revision_listener} configuration property. + */ + Class value() default RevisionListener.class; } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionListener.java b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionListener.java index 26956d5dc0..a49eed8530 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionListener.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionListener.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -27,13 +27,15 @@ package org.hibernate.envers; /** * An implementation of this class, having a no-arg constructor, should be passed as an argument to the * {@link RevisionEntity} annotation. + * * @author Adam Warski (adam at warski dot org) */ public interface RevisionListener { - /** - * Called when a new revision is created. - * @param revisionEntity An instance of the entity annotated with {@link RevisionEntity}, which will be persisted - * after this method returns. All properties on this entity that are to be persisted should be set by this method. - */ - void newRevision(Object revisionEntity); + /** + * Called when a new revision is created. + * + * @param revisionEntity An instance of the entity annotated with {@link RevisionEntity}, which will be persisted + * after this method returns. All properties on this entity that are to be persisted should be set by this method. + */ + void newRevision(Object revisionEntity); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionNumber.java b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionNumber.java index 290b6b2c2e..26fa3749b9 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionNumber.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionNumber.java @@ -33,7 +33,7 @@ import java.lang.annotation.Target; * {@link RevisionListener}. Values of this property should form a strictly-increasing sequence * of numbers. The value of this property won't be set by Envers. In most cases, this should be * an auto-generated database-assigned primary id. - * + * * @author Adam Warski (adam at warski dot org) * @author Sanne Grinovero */ diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionTimestamp.java b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionTimestamp.java index 967ed178af..c27b70c770 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionTimestamp.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionTimestamp.java @@ -31,7 +31,7 @@ import java.lang.annotation.Target; /** * Marks a property which will hold the timestamp of the revision in a revision entity, see * {@link RevisionListener}. The value of this property will be automatically set by Envers. - * + * * @author Adam Warski (adam at warski dot org) * @author Sanne Grinovero */ diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionType.java b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionType.java index 79ab421292..a24e2f55a1 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/RevisionType.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/RevisionType.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -26,43 +26,51 @@ package org.hibernate.envers; /** * Type of the revision. + * * @author Adam Warski (adam at warski dot org) */ public enum RevisionType { - /** - * Indicates that the entity was added (persisted) at that revision. - */ - ADD((byte) 0), - /** - * Indicates that the entity was modified (one or more of its fields) at that revision. - */ - MOD((byte) 1), - /** - * Indicates that the entity was deleted (removed) at that revision. - */ - DEL((byte) 2); + /** + * Indicates that the entity was added (persisted) at that revision. + */ + ADD( (byte) 0 ), + /** + * Indicates that the entity was modified (one or more of its fields) at that revision. + */ + MOD( (byte) 1 ), + /** + * Indicates that the entity was deleted (removed) at that revision. + */ + DEL( (byte) 2 ); - private Byte representation; + private Byte representation; - RevisionType(byte representation) { - this.representation = representation; - } + RevisionType(byte representation) { + this.representation = representation; + } - public Byte getRepresentation() { - return representation; - } + public Byte getRepresentation() { + return representation; + } - public static RevisionType fromRepresentation(Object representation) { - if (representation == null || !(representation instanceof Byte)) { - return null; - } + public static RevisionType fromRepresentation(Object representation) { + if ( representation == null || !(representation instanceof Byte) ) { + return null; + } - switch ((Byte) representation) { - case 0: return ADD; - case 1: return MOD; - case 2: return DEL; - } - - throw new IllegalArgumentException("Unknown representation: " + representation); - } + switch ( (Byte) representation ) { + case 0: { + return ADD; + } + case 1: { + return MOD; + } + case 2: { + return DEL; + } + default: { + throw new IllegalArgumentException( "Unknown representation: " + representation ); + } + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/SecondaryAuditTable.java b/hibernate-envers/src/main/java/org/hibernate/envers/SecondaryAuditTable.java index bb26ef2be8..da566e7dd6 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/SecondaryAuditTable.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/SecondaryAuditTable.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -33,7 +34,7 @@ import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface SecondaryAuditTable { - String secondaryTableName(); + String secondaryTableName(); - String secondaryAuditTableName(); + String secondaryAuditTableName(); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/SecondaryAuditTables.java b/hibernate-envers/src/main/java/org/hibernate/envers/SecondaryAuditTables.java index ea7a81a625..97d80a178a 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/SecondaryAuditTables.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/SecondaryAuditTables.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -33,5 +34,5 @@ import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface SecondaryAuditTables { - SecondaryAuditTable[] value(); + SecondaryAuditTable[] value(); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/EnversSettings.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/EnversSettings.java index a2eb5c7e76..374428cefe 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/EnversSettings.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/EnversSettings.java @@ -1,7 +1,28 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.configuration; -import org.hibernate.envers.strategy.DefaultAuditStrategy; - /** * Configuration property names. * @@ -69,7 +90,7 @@ public interface EnversSettings { public static final String AUDIT_TABLE_SUFFIX = "org.hibernate.envers.audit_table_suffix"; /** - * Audit strategy. Defaults to {@link DefaultAuditStrategy}. + * Audit strategy. Defaults to {@link org.hibernate.envers.strategy.DefaultAuditStrategy}. */ public static final String AUDIT_STRATEGY = "org.hibernate.envers.audit_strategy"; @@ -99,7 +120,7 @@ public interface EnversSettings { * Defaults to {@literal REVEND_TSTMP}. */ public static final String AUDIT_STRATEGY_VALIDITY_REVEND_TIMESTAMP_FIELD_NAME = "org.hibernate.envers.audit_strategy_validity_revend_timestamp_field_name"; - + /** * Name of column used for storing ordinal of the change in sets of embeddable elements. Defaults to {@literal SETORDINAL}. */ diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/AuditEntitiesConfiguration.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/AuditEntitiesConfiguration.java index 1460ec3b4a..ae0a63010a 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/AuditEntitiesConfiguration.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/AuditEntitiesConfiguration.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -59,7 +59,7 @@ public class AuditEntitiesConfiguration { private final boolean revisionEndTimestampEnabled; private final String revisionEndTimestampFieldName; - + private final String embeddableSetOrdinalPropertyName; public AuditEntitiesConfiguration(Properties properties, String revisionInfoEntityName) { diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/ClassesAuditingData.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/ClassesAuditingData.java index d9a95069f3..6a8ed4f48f 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/ClassesAuditingData.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/ClassesAuditingData.java @@ -1,4 +1,28 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.configuration.internal; + import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; @@ -15,84 +39,100 @@ import org.hibernate.mapping.PersistentClass; /** * A helper class holding auditing meta-data for all persistent classes. + * * @author Adam Warski (adam at warski dot org) */ public class ClassesAuditingData { + private static final EnversMessageLogger LOG = Logger.getMessageLogger( + EnversMessageLogger.class, + ClassesAuditingData.class.getName() + ); - public static final EnversMessageLogger LOG = Logger.getMessageLogger(EnversMessageLogger.class, ClassesAuditingData.class.getName()); + private final Map entityNameToAuditingData = new HashMap(); + private final Map persistentClassToAuditingData = new LinkedHashMap(); - private final Map entityNameToAuditingData = new HashMap(); - private final Map persistentClassToAuditingData = new LinkedHashMap(); + /** + * Stores information about auditing meta-data for the given class. + * + * @param pc Persistent class. + * @param cad Auditing meta-data for the given class. + */ + public void addClassAuditingData(PersistentClass pc, ClassAuditingData cad) { + entityNameToAuditingData.put( pc.getEntityName(), cad ); + persistentClassToAuditingData.put( pc, cad ); + } - /** - * Stores information about auditing meta-data for the given class. - * @param pc Persistent class. - * @param cad Auditing meta-data for the given class. - */ - public void addClassAuditingData(PersistentClass pc, ClassAuditingData cad) { - entityNameToAuditingData.put(pc.getEntityName(), cad); - persistentClassToAuditingData.put(pc, cad); - } + /** + * @return A collection of all auditing meta-data for persistent classes. + */ + public Collection> getAllClassAuditedData() { + return persistentClassToAuditingData.entrySet(); + } - /** - * @return A collection of all auditing meta-data for persistent classes. - */ - public Collection> getAllClassAuditedData() { - return persistentClassToAuditingData.entrySet(); - } + /** + * @param entityName Name of the entity. + * + * @return Auditing meta-data for the given entity. + */ + public ClassAuditingData getClassAuditingData(String entityName) { + return entityNameToAuditingData.get( entityName ); + } - /** - * @param entityName Name of the entity. - * @return Auditing meta-data for the given entity. - */ - public ClassAuditingData getClassAuditingData(String entityName) { - return entityNameToAuditingData.get(entityName); - } + /** + * After all meta-data is read, updates calculated fields. This includes: + *
        + *
      • setting {@code forceInsertable} to {@code true} for properties specified by {@code @AuditMappedBy}
      • + *
      + */ + public void updateCalculatedFields() { + for ( Map.Entry classAuditingDataEntry : persistentClassToAuditingData.entrySet() ) { + final PersistentClass pc = classAuditingDataEntry.getKey(); + final ClassAuditingData classAuditingData = classAuditingDataEntry.getValue(); + for ( String propertyName : classAuditingData.getPropertyNames() ) { + final PropertyAuditingData propertyAuditingData = classAuditingData.getPropertyAuditingData( propertyName ); + // If a property had the @AuditMappedBy annotation, setting the referenced fields to be always insertable. + if ( propertyAuditingData.getAuditMappedBy() != null ) { + final String referencedEntityName = MappingTools.getReferencedEntityName( + pc.getProperty( propertyName ).getValue() + ); - /** - * After all meta-data is read, updates calculated fields. This includes: - *
        - *
      • setting {@code forceInsertable} to {@code true} for properties specified by {@code @AuditMappedBy}
      • - *
      - */ - public void updateCalculatedFields() { - for (Map.Entry classAuditingDataEntry : persistentClassToAuditingData.entrySet()) { - PersistentClass pc = classAuditingDataEntry.getKey(); - ClassAuditingData classAuditingData = classAuditingDataEntry.getValue(); - for (String propertyName : classAuditingData.getPropertyNames()) { - PropertyAuditingData propertyAuditingData = classAuditingData.getPropertyAuditingData(propertyName); - // If a property had the @AuditMappedBy annotation, setting the referenced fields to be always insertable. - if (propertyAuditingData.getAuditMappedBy() != null) { - String referencedEntityName = MappingTools.getReferencedEntityName(pc.getProperty(propertyName).getValue()); + final ClassAuditingData referencedClassAuditingData = entityNameToAuditingData.get( referencedEntityName ); - ClassAuditingData referencedClassAuditingData = entityNameToAuditingData.get(referencedEntityName); + forcePropertyInsertable( + referencedClassAuditingData, propertyAuditingData.getAuditMappedBy(), + pc.getEntityName(), referencedEntityName + ); - forcePropertyInsertable(referencedClassAuditingData, propertyAuditingData.getAuditMappedBy(), - pc.getEntityName(), referencedEntityName); + forcePropertyInsertable( + referencedClassAuditingData, propertyAuditingData.getPositionMappedBy(), + pc.getEntityName(), referencedEntityName + ); + } + } + } + } - forcePropertyInsertable(referencedClassAuditingData, propertyAuditingData.getPositionMappedBy(), - pc.getEntityName(), referencedEntityName); - } - } - } - } + private void forcePropertyInsertable( + ClassAuditingData classAuditingData, String propertyName, + String entityName, String referencedEntityName) { + if ( propertyName != null ) { + if ( classAuditingData.getPropertyAuditingData( propertyName ) == null ) { + throw new MappingException( + "@AuditMappedBy points to a property that doesn't exist: " + + referencedEntityName + "." + propertyName + ); + } - private void forcePropertyInsertable(ClassAuditingData classAuditingData, String propertyName, - String entityName, String referencedEntityName) { - if (propertyName != null) { - if (classAuditingData.getPropertyAuditingData(propertyName) == null) { - throw new MappingException("@AuditMappedBy points to a property that doesn't exist: " + - referencedEntityName + "." + propertyName); - } + LOG.debugf( + "Non-insertable property %s.%s will be made insertable because a matching @AuditMappedBy was found in the %s entity", + referencedEntityName, + propertyName, + entityName + ); - LOG.debugf("Non-insertable property %s.%s will be made insertable because a matching @AuditMappedBy was found in the %s entity", - referencedEntityName, - propertyName, - entityName); - - classAuditingData - .getPropertyAuditingData(propertyName) - .setForceInsertable(true); - } - } + classAuditingData + .getPropertyAuditingData( propertyName ) + .setForceInsertable( true ); + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/EntitiesConfigurator.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/EntitiesConfigurator.java index a12f588edb..540e439c4c 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/EntitiesConfigurator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/EntitiesConfigurator.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -57,108 +57,118 @@ import org.hibernate.mapping.PersistentClass; * @author Adam Warski (adam at warski dot org) */ public class EntitiesConfigurator { - public EntitiesConfigurations configure(Configuration cfg, ReflectionManager reflectionManager, - GlobalConfiguration globalCfg, AuditEntitiesConfiguration verEntCfg, - AuditStrategy auditStrategy, ClassLoaderService classLoaderService, - Document revisionInfoXmlMapping, Element revisionInfoRelationMapping) { - // Creating a name register to capture all audit entity names created. - AuditEntityNameRegister auditEntityNameRegister = new AuditEntityNameRegister(); - DOMWriter writer = new DOMWriter(); + public EntitiesConfigurations configure( + Configuration cfg, ReflectionManager reflectionManager, + GlobalConfiguration globalCfg, AuditEntitiesConfiguration verEntCfg, + AuditStrategy auditStrategy, ClassLoaderService classLoaderService, + Document revisionInfoXmlMapping, Element revisionInfoRelationMapping) { + // Creating a name register to capture all audit entity names created. + final AuditEntityNameRegister auditEntityNameRegister = new AuditEntityNameRegister(); + final DOMWriter writer = new DOMWriter(); - // Sorting the persistent class topologically - superclass always before subclass - Iterator classes = GraphTopologicalSort.sort(new PersistentClassGraphDefiner(cfg)).iterator(); + // Sorting the persistent class topologically - superclass always before subclass + final Iterator classes = GraphTopologicalSort.sort( new PersistentClassGraphDefiner( cfg ) ) + .iterator(); - ClassesAuditingData classesAuditingData = new ClassesAuditingData(); - Map xmlMappings = new HashMap(); + final ClassesAuditingData classesAuditingData = new ClassesAuditingData(); + final Map xmlMappings = new HashMap(); - // Reading metadata from annotations - while (classes.hasNext()) { - PersistentClass pc = classes.next(); + // Reading metadata from annotations + while ( classes.hasNext() ) { + final PersistentClass pc = classes.next(); - // Collecting information from annotations on the persistent class pc - AnnotationsMetadataReader annotationsMetadataReader = - new AnnotationsMetadataReader(globalCfg, reflectionManager, pc); - ClassAuditingData auditData = annotationsMetadataReader.getAuditData(); + // Collecting information from annotations on the persistent class pc + final AnnotationsMetadataReader annotationsMetadataReader = + new AnnotationsMetadataReader( globalCfg, reflectionManager, pc ); + final ClassAuditingData auditData = annotationsMetadataReader.getAuditData(); - classesAuditingData.addClassAuditingData(pc, auditData); - } + classesAuditingData.addClassAuditingData( pc, auditData ); + } - // Now that all information is read we can update the calculated fields. - classesAuditingData.updateCalculatedFields(); + // Now that all information is read we can update the calculated fields. + classesAuditingData.updateCalculatedFields(); - AuditMetadataGenerator auditMetaGen = new AuditMetadataGenerator(cfg, globalCfg, verEntCfg, auditStrategy, - classLoaderService, revisionInfoRelationMapping, auditEntityNameRegister); + final AuditMetadataGenerator auditMetaGen = new AuditMetadataGenerator( + cfg, globalCfg, verEntCfg, auditStrategy, + classLoaderService, revisionInfoRelationMapping, auditEntityNameRegister + ); - // First pass - for (Map.Entry pcDatasEntry : classesAuditingData.getAllClassAuditedData()) { - PersistentClass pc = pcDatasEntry.getKey(); - ClassAuditingData auditData = pcDatasEntry.getValue(); + // First pass + for ( Map.Entry pcDatasEntry : classesAuditingData.getAllClassAuditedData() ) { + final PersistentClass pc = pcDatasEntry.getKey(); + final ClassAuditingData auditData = pcDatasEntry.getValue(); - EntityXmlMappingData xmlMappingData = new EntityXmlMappingData(); - if (auditData.isAudited()) { - if (!StringTools.isEmpty(auditData.getAuditTable().value())) { - verEntCfg.addCustomAuditTableName(pc.getEntityName(), auditData.getAuditTable().value()); - } + final EntityXmlMappingData xmlMappingData = new EntityXmlMappingData(); + if ( auditData.isAudited() ) { + if ( !StringTools.isEmpty( auditData.getAuditTable().value() ) ) { + verEntCfg.addCustomAuditTableName( pc.getEntityName(), auditData.getAuditTable().value() ); + } - auditMetaGen.generateFirstPass(pc, auditData, xmlMappingData, true); - } else { - auditMetaGen.generateFirstPass(pc, auditData, xmlMappingData, false); + auditMetaGen.generateFirstPass( pc, auditData, xmlMappingData, true ); + } + else { + auditMetaGen.generateFirstPass( pc, auditData, xmlMappingData, false ); } - xmlMappings.put(pc, xmlMappingData); - } + xmlMappings.put( pc, xmlMappingData ); + } - // Second pass - for (Map.Entry pcDatasEntry : classesAuditingData.getAllClassAuditedData()) { - EntityXmlMappingData xmlMappingData = xmlMappings.get(pcDatasEntry.getKey()); + // Second pass + for ( Map.Entry pcDatasEntry : classesAuditingData.getAllClassAuditedData() ) { + final EntityXmlMappingData xmlMappingData = xmlMappings.get( pcDatasEntry.getKey() ); - if (pcDatasEntry.getValue().isAudited()) { - auditMetaGen.generateSecondPass(pcDatasEntry.getKey(), pcDatasEntry.getValue(), xmlMappingData); - try { - cfg.addDocument(writer.write(xmlMappingData.getMainXmlMapping())); - //writeDocument(xmlMappingData.getMainXmlMapping()); + if ( pcDatasEntry.getValue().isAudited() ) { + auditMetaGen.generateSecondPass( pcDatasEntry.getKey(), pcDatasEntry.getValue(), xmlMappingData ); + try { + cfg.addDocument( writer.write( xmlMappingData.getMainXmlMapping() ) ); + //writeDocument(xmlMappingData.getMainXmlMapping()); - for (Document additionalMapping : xmlMappingData.getAdditionalXmlMappings()) { - cfg.addDocument(writer.write(additionalMapping)); - //writeDocument(additionalMapping); - } - } catch (DocumentException e) { - throw new MappingException(e); - } - } - } + for ( Document additionalMapping : xmlMappingData.getAdditionalXmlMappings() ) { + cfg.addDocument( writer.write( additionalMapping ) ); + //writeDocument(additionalMapping); + } + } + catch (DocumentException e) { + throw new MappingException( e ); + } + } + } - // Only if there are any versioned classes - if (auditMetaGen.getEntitiesConfigurations().size() > 0) { - try { - if (revisionInfoXmlMapping != null) { - //writeDocument(revisionInfoXmlMapping); - cfg.addDocument(writer.write(revisionInfoXmlMapping)); - } - } catch (DocumentException e) { - throw new MappingException(e); - } - } + // Only if there are any versioned classes + if ( auditMetaGen.getEntitiesConfigurations().size() > 0 ) { + try { + if ( revisionInfoXmlMapping != null ) { + //writeDocument(revisionInfoXmlMapping); + cfg.addDocument( writer.write( revisionInfoXmlMapping ) ); + } + } + catch (DocumentException e) { + throw new MappingException( e ); + } + } - return new EntitiesConfigurations(auditMetaGen.getEntitiesConfigurations(), - auditMetaGen.getNotAuditedEntitiesConfigurations()); - } + return new EntitiesConfigurations( + auditMetaGen.getEntitiesConfigurations(), + auditMetaGen.getNotAuditedEntitiesConfigurations() + ); + } - @SuppressWarnings({"UnusedDeclaration"}) - private void writeDocument(Document e) { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - Writer w = new PrintWriter(baos); + @SuppressWarnings({"UnusedDeclaration"}) + private void writeDocument(Document e) { + final ByteArrayOutputStream baos = new ByteArrayOutputStream(); + final Writer w = new PrintWriter( baos ); - try { - XMLWriter xw = new XMLWriter(w, new OutputFormat(" ", true)); - xw.write(e); - w.flush(); - } catch (IOException e1) { - e1.printStackTrace(); - } + try { + final XMLWriter xw = new XMLWriter( w, new OutputFormat( " ", true ) ); + xw.write( e ); + w.flush(); + } + catch (IOException e1) { + e1.printStackTrace(); + } - System.out.println("-----------"); - System.out.println(baos.toString()); - System.out.println("-----------"); - } + System.out.println( "-----------" ); + System.out.println( baos.toString() ); + System.out.println( "-----------" ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/GlobalConfiguration.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/GlobalConfiguration.java index 295f9d4585..658451430f 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/GlobalConfiguration.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/GlobalConfiguration.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -116,13 +116,16 @@ public class GlobalConfiguration { EnversSettings.MODIFIED_FLAG_SUFFIX, properties, "_MOD" ); - String revisionListenerClassName = properties.getProperty( EnversSettings.REVISION_LISTENER, null ); + final String revisionListenerClassName = properties.getProperty( EnversSettings.REVISION_LISTENER, null ); if ( revisionListenerClassName != null ) { try { revisionListenerClass = ReflectionTools.loadClass( revisionListenerClassName, classLoaderService ); } - catch ( ClassLoadingException e ) { - throw new MappingException( "Revision listener class not found: " + revisionListenerClassName + ".", e ); + catch (ClassLoadingException e) { + throw new MappingException( + "Revision listener class not found: " + revisionListenerClassName + ".", + e + ); } } else { diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/PersistentClassGraphDefiner.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/PersistentClassGraphDefiner.java index f82ef769a5..c26a22474a 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/PersistentClassGraphDefiner.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/PersistentClassGraphDefiner.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.configuration.internal; + import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -34,43 +35,48 @@ import org.hibernate.mapping.PersistentClass; /** * Defines a graph, where the vertexes are all persistent classes, and there is an edge from * p.c. A to p.c. B iff A is a superclass of B. + * * @author Adam Warski (adam at warski dot org) */ public class PersistentClassGraphDefiner implements GraphDefiner { - private Configuration cfg; + private Configuration cfg; - public PersistentClassGraphDefiner(Configuration cfg) { - this.cfg = cfg; - } + public PersistentClassGraphDefiner(Configuration cfg) { + this.cfg = cfg; + } - public String getRepresentation(PersistentClass pc) { - return pc.getEntityName(); - } + @Override + public String getRepresentation(PersistentClass pc) { + return pc.getEntityName(); + } - public PersistentClass getValue(String entityName) { - return cfg.getClassMapping(entityName); - } + @Override + public PersistentClass getValue(String entityName) { + return cfg.getClassMapping( entityName ); + } - @SuppressWarnings({"unchecked"}) - private void addNeighbours(List neighbours, Iterator subclassIterator) { - while (subclassIterator.hasNext()) { - PersistentClass subclass = subclassIterator.next(); - neighbours.add(subclass); - addNeighbours(neighbours, (Iterator) subclass.getSubclassIterator()); - } - } + @SuppressWarnings({"unchecked"}) + private void addNeighbours(List neighbours, Iterator subclassIterator) { + while ( subclassIterator.hasNext() ) { + final PersistentClass subclass = subclassIterator.next(); + neighbours.add( subclass ); + addNeighbours( neighbours, (Iterator) subclass.getSubclassIterator() ); + } + } - @SuppressWarnings({"unchecked"}) - public List getNeighbours(PersistentClass pc) { - List neighbours = new ArrayList(); + @Override + @SuppressWarnings({"unchecked"}) + public List getNeighbours(PersistentClass pc) { + final List neighbours = new ArrayList(); - addNeighbours(neighbours, (Iterator) pc.getSubclassIterator()); + addNeighbours( neighbours, (Iterator) pc.getSubclassIterator() ); - return neighbours; - } + return neighbours; + } - @SuppressWarnings({"unchecked"}) - public List getValues() { - return Tools.iteratorToList( cfg.getClassMappings() ); - } + @Override + @SuppressWarnings({"unchecked"}) + public List getValues() { + return Tools.iteratorToList( cfg.getClassMappings() ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/RevisionInfoConfiguration.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/RevisionInfoConfiguration.java index 7e14efa32b..104b96fa6c 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/RevisionInfoConfiguration.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/RevisionInfoConfiguration.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,10 +22,11 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.configuration.internal; + +import javax.persistence.Column; import java.util.Date; import java.util.Iterator; import java.util.Set; -import javax.persistence.Column; import org.dom4j.Document; import org.dom4j.Element; @@ -65,301 +66,394 @@ import org.hibernate.type.Type; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class RevisionInfoConfiguration { - private String revisionInfoEntityName; - private PropertyData revisionInfoIdData; - private PropertyData revisionInfoTimestampData; - private PropertyData modifiedEntityNamesData; - private Type revisionInfoTimestampType; - private GlobalConfiguration globalCfg; + private String revisionInfoEntityName; + private PropertyData revisionInfoIdData; + private PropertyData revisionInfoTimestampData; + private PropertyData modifiedEntityNamesData; + private Type revisionInfoTimestampType; + private GlobalConfiguration globalCfg; - private String revisionPropType; - private String revisionPropSqlType; + private String revisionPropType; + private String revisionPropSqlType; - public RevisionInfoConfiguration(GlobalConfiguration globalCfg) { - this.globalCfg = globalCfg; - if (globalCfg.isUseRevisionEntityWithNativeId()) { - revisionInfoEntityName = "org.hibernate.envers.DefaultRevisionEntity"; - } else { - revisionInfoEntityName = "org.hibernate.envers.enhanced.SequenceIdRevisionEntity"; - } - revisionInfoIdData = new PropertyData("id", "id", "field", null); - revisionInfoTimestampData = new PropertyData("timestamp", "timestamp", "field", null); - modifiedEntityNamesData = new PropertyData("modifiedEntityNames", "modifiedEntityNames", "field", null); - revisionInfoTimestampType = new LongType(); + public RevisionInfoConfiguration(GlobalConfiguration globalCfg) { + this.globalCfg = globalCfg; + if ( globalCfg.isUseRevisionEntityWithNativeId() ) { + revisionInfoEntityName = "org.hibernate.envers.DefaultRevisionEntity"; + } + else { + revisionInfoEntityName = "org.hibernate.envers.enhanced.SequenceIdRevisionEntity"; + } + revisionInfoIdData = new PropertyData( "id", "id", "field", null ); + revisionInfoTimestampData = new PropertyData( "timestamp", "timestamp", "field", null ); + modifiedEntityNamesData = new PropertyData( "modifiedEntityNames", "modifiedEntityNames", "field", null ); + revisionInfoTimestampType = new LongType(); - revisionPropType = "integer"; - } + revisionPropType = "integer"; + } - private Document generateDefaultRevisionInfoXmlMapping() { - Document document = XMLHelper.getDocumentFactory().createDocument(); + private Document generateDefaultRevisionInfoXmlMapping() { + final Document document = XMLHelper.getDocumentFactory().createDocument(); - Element class_mapping = MetadataTools.createEntity(document, new AuditTableData(null, null, globalCfg.getDefaultSchemaName(), globalCfg.getDefaultCatalogName()), null, null); + final Element classMapping = MetadataTools.createEntity( + document, + new AuditTableData( null, null, globalCfg.getDefaultSchemaName(), globalCfg.getDefaultCatalogName() ), + null, + null + ); - class_mapping.addAttribute("name", revisionInfoEntityName); - class_mapping.addAttribute("table", "REVINFO"); + classMapping.addAttribute( "name", revisionInfoEntityName ); + classMapping.addAttribute( "table", "REVINFO" ); - Element idProperty = MetadataTools.addNativelyGeneratedId(class_mapping, revisionInfoIdData.getName(), - revisionPropType, globalCfg.isUseRevisionEntityWithNativeId()); - MetadataTools.addColumn(idProperty, "REV", null, null, null, null, null, null, false); + final Element idProperty = MetadataTools.addNativelyGeneratedId( + classMapping, + revisionInfoIdData.getName(), + revisionPropType, + globalCfg.isUseRevisionEntityWithNativeId() + ); + MetadataTools.addColumn( idProperty, "REV", null, null, null, null, null, null, false ); - Element timestampProperty = MetadataTools.addProperty(class_mapping, revisionInfoTimestampData.getName(), - revisionInfoTimestampType.getName(), true, false); - MetadataTools.addColumn(timestampProperty, "REVTSTMP", null, null, null, null, null, null, false); + final Element timestampProperty = MetadataTools.addProperty( + classMapping, + revisionInfoTimestampData.getName(), + revisionInfoTimestampType.getName(), + true, + false + ); + MetadataTools.addColumn( timestampProperty, "REVTSTMP", null, null, null, null, null, null, false ); - if (globalCfg.isTrackEntitiesChangedInRevision()) { - generateEntityNamesTrackingTableMapping(class_mapping, "modifiedEntityNames", - globalCfg.getDefaultSchemaName(), globalCfg.getDefaultCatalogName(), - "REVCHANGES", "REV", "ENTITYNAME", "string"); - } + if ( globalCfg.isTrackEntitiesChangedInRevision() ) { + generateEntityNamesTrackingTableMapping( + classMapping, + "modifiedEntityNames", + globalCfg.getDefaultSchemaName(), + globalCfg.getDefaultCatalogName(), + "REVCHANGES", + "REV", + "ENTITYNAME", + "string" + ); + } - return document; - } + return document; + } - /** - * Generates mapping that represents a set of primitive types.
      - * - * <set name="propertyName" table="joinTableName" schema="joinTableSchema" catalog="joinTableCatalog" - *      cascade="persist, delete" lazy="false" fetch="join">
      - *    <key column="joinTablePrimaryKeyColumnName" />
      - *    <element type="joinTableValueColumnType">
      - *       <column name="joinTableValueColumnName" />
      - *    </element>
      - * </set> - *
      - */ - private void generateEntityNamesTrackingTableMapping(Element class_mapping, String propertyName, - String joinTableSchema, String joinTableCatalog, String joinTableName, - String joinTablePrimaryKeyColumnName, String joinTableValueColumnName, - String joinTableValueColumnType) { - Element set = class_mapping.addElement("set"); - set.addAttribute("name", propertyName); - set.addAttribute("table", joinTableName); - set.addAttribute("schema", joinTableSchema); - set.addAttribute("catalog", joinTableCatalog); - set.addAttribute("cascade", "persist, delete"); - set.addAttribute("fetch", "join"); - set.addAttribute("lazy", "false"); - Element key = set.addElement("key"); - key.addAttribute("column", joinTablePrimaryKeyColumnName); - Element element = set.addElement("element"); - element.addAttribute("type", joinTableValueColumnType); - Element column = element.addElement("column"); - column.addAttribute("name", joinTableValueColumnName); - } + /** + * Generates mapping that represents a set of primitive types.
      + * + * <set name="propertyName" table="joinTableName" schema="joinTableSchema" catalog="joinTableCatalog" + *      cascade="persist, delete" lazy="false" fetch="join">
      + *    <key column="joinTablePrimaryKeyColumnName" />
      + *    <element type="joinTableValueColumnType">
      + *       <column name="joinTableValueColumnName" />
      + *    </element>
      + * </set> + *
      + */ + private void generateEntityNamesTrackingTableMapping( + Element classMapping, + String propertyName, + String joinTableSchema, + String joinTableCatalog, + String joinTableName, + String joinTablePrimaryKeyColumnName, + String joinTableValueColumnName, + String joinTableValueColumnType) { + final Element set = classMapping.addElement( "set" ); + set.addAttribute( "name", propertyName ); + set.addAttribute( "table", joinTableName ); + set.addAttribute( "schema", joinTableSchema ); + set.addAttribute( "catalog", joinTableCatalog ); + set.addAttribute( "cascade", "persist, delete" ); + set.addAttribute( "fetch", "join" ); + set.addAttribute( "lazy", "false" ); + final Element key = set.addElement( "key" ); + key.addAttribute( "column", joinTablePrimaryKeyColumnName ); + final Element element = set.addElement( "element" ); + element.addAttribute( "type", joinTableValueColumnType ); + final Element column = element.addElement( "column" ); + column.addAttribute( "name", joinTableValueColumnName ); + } - private Element generateRevisionInfoRelationMapping() { - Document document = XMLHelper.getDocumentFactory().createDocument(); - Element rev_rel_mapping = document.addElement("key-many-to-one"); - rev_rel_mapping.addAttribute("type", revisionPropType); - rev_rel_mapping.addAttribute("class", revisionInfoEntityName); + private Element generateRevisionInfoRelationMapping() { + final Document document = XMLHelper.getDocumentFactory().createDocument(); + final Element revRelMapping = document.addElement( "key-many-to-one" ); + revRelMapping.addAttribute( "type", revisionPropType ); + revRelMapping.addAttribute( "class", revisionInfoEntityName ); - if (revisionPropSqlType != null) { - // Putting a fake name to make Hibernate happy. It will be replaced later anyway. - MetadataTools.addColumn(rev_rel_mapping, "*" , null, null, null, revisionPropSqlType, null, null, false); - } + if ( revisionPropSqlType != null ) { + // Putting a fake name to make Hibernate happy. It will be replaced later anyway. + MetadataTools.addColumn( revRelMapping, "*", null, null, null, revisionPropSqlType, null, null, false ); + } - return rev_rel_mapping; - } + return revRelMapping; + } - private void searchForRevisionInfoCfgInProperties(XClass clazz, ReflectionManager reflectionManager, - MutableBoolean revisionNumberFound, MutableBoolean revisionTimestampFound, - MutableBoolean modifiedEntityNamesFound, String accessType) { - for (XProperty property : clazz.getDeclaredProperties(accessType)) { - RevisionNumber revisionNumber = property.getAnnotation(RevisionNumber.class); - RevisionTimestamp revisionTimestamp = property.getAnnotation(RevisionTimestamp.class); - ModifiedEntityNames modifiedEntityNames = property.getAnnotation(ModifiedEntityNames.class); + private void searchForRevisionInfoCfgInProperties( + XClass clazz, + ReflectionManager reflectionManager, + MutableBoolean revisionNumberFound, + MutableBoolean revisionTimestampFound, + MutableBoolean modifiedEntityNamesFound, + String accessType) { + for ( XProperty property : clazz.getDeclaredProperties( accessType ) ) { + final RevisionNumber revisionNumber = property.getAnnotation( RevisionNumber.class ); + final RevisionTimestamp revisionTimestamp = property.getAnnotation( RevisionTimestamp.class ); + final ModifiedEntityNames modifiedEntityNames = property.getAnnotation( ModifiedEntityNames.class ); - if (revisionNumber != null) { - if (revisionNumberFound.isSet()) { - throw new MappingException("Only one property may be annotated with @RevisionNumber!"); - } + if ( revisionNumber != null ) { + if ( revisionNumberFound.isSet() ) { + throw new MappingException( "Only one property may be annotated with @RevisionNumber!" ); + } - XClass revisionNumberClass = property.getType(); - if (reflectionManager.equals(revisionNumberClass, Integer.class) || - reflectionManager.equals(revisionNumberClass, Integer.TYPE)) { - revisionInfoIdData = new PropertyData(property.getName(), property.getName(), accessType, null); - revisionNumberFound.set(); - } else if (reflectionManager.equals(revisionNumberClass, Long.class) || - reflectionManager.equals(revisionNumberClass, Long.TYPE)) { - revisionInfoIdData = new PropertyData(property.getName(), property.getName(), accessType, null); - revisionNumberFound.set(); + final XClass revisionNumberClass = property.getType(); + if ( reflectionManager.equals( revisionNumberClass, Integer.class ) || + reflectionManager.equals( revisionNumberClass, Integer.TYPE ) ) { + revisionInfoIdData = new PropertyData( property.getName(), property.getName(), accessType, null ); + revisionNumberFound.set(); + } + else if ( reflectionManager.equals( revisionNumberClass, Long.class ) || + reflectionManager.equals( revisionNumberClass, Long.TYPE ) ) { + revisionInfoIdData = new PropertyData( property.getName(), property.getName(), accessType, null ); + revisionNumberFound.set(); - // The default is integer - revisionPropType = "long"; - } else { - throw new MappingException("The field annotated with @RevisionNumber must be of type " + - "int, Integer, long or Long"); - } + // The default is integer + revisionPropType = "long"; + } + else { + throw new MappingException( + "The field annotated with @RevisionNumber must be of type " + + "int, Integer, long or Long" + ); + } - // Getting the @Column definition of the revision number property, to later use that info to - // generate the same mapping for the relation from an audit table's revision number to the - // revision entity revision number. - Column revisionPropColumn = property.getAnnotation(Column.class); - if (revisionPropColumn != null) { - revisionPropSqlType = revisionPropColumn.columnDefinition(); - } - } + // Getting the @Column definition of the revision number property, to later use that info to + // generate the same mapping for the relation from an audit table's revision number to the + // revision entity revision number. + final Column revisionPropColumn = property.getAnnotation( Column.class ); + if ( revisionPropColumn != null ) { + revisionPropSqlType = revisionPropColumn.columnDefinition(); + } + } - if (revisionTimestamp != null) { - if (revisionTimestampFound.isSet()) { - throw new MappingException("Only one property may be annotated with @RevisionTimestamp!"); - } + if ( revisionTimestamp != null ) { + if ( revisionTimestampFound.isSet() ) { + throw new MappingException( "Only one property may be annotated with @RevisionTimestamp!" ); + } - XClass revisionTimestampClass = property.getType(); - if (reflectionManager.equals(revisionTimestampClass, Long.class) || - reflectionManager.equals(revisionTimestampClass, Long.TYPE) || - reflectionManager.equals(revisionTimestampClass, Date.class) || - reflectionManager.equals(revisionTimestampClass, java.sql.Date.class)) { - revisionInfoTimestampData = new PropertyData(property.getName(), property.getName(), accessType, null); - revisionTimestampFound.set(); - } else { - throw new MappingException("The field annotated with @RevisionTimestamp must be of type " + - "long, Long, java.util.Date or java.sql.Date"); - } - } + final XClass revisionTimestampClass = property.getType(); + if ( reflectionManager.equals( revisionTimestampClass, Long.class ) || + reflectionManager.equals( revisionTimestampClass, Long.TYPE ) || + reflectionManager.equals( revisionTimestampClass, Date.class ) || + reflectionManager.equals( revisionTimestampClass, java.sql.Date.class ) ) { + revisionInfoTimestampData = new PropertyData( + property.getName(), + property.getName(), + accessType, + null + ); + revisionTimestampFound.set(); + } + else { + throw new MappingException( + "The field annotated with @RevisionTimestamp must be of type " + + "long, Long, java.util.Date or java.sql.Date" + ); + } + } - if (modifiedEntityNames != null) { - if (modifiedEntityNamesFound.isSet()) { - throw new MappingException("Only one property may be annotated with @ModifiedEntityNames!"); - } - XClass modifiedEntityNamesClass = property.getType(); - if (reflectionManager.equals(modifiedEntityNamesClass, Set.class) && - reflectionManager.equals(property.getElementClass(), String.class)) { - modifiedEntityNamesData = new PropertyData(property.getName(), property.getName(), accessType, null); - modifiedEntityNamesFound.set(); - } else { - throw new MappingException("The field annotated with @ModifiedEntityNames must be of Set type."); - } - } - } - } + if ( modifiedEntityNames != null ) { + if ( modifiedEntityNamesFound.isSet() ) { + throw new MappingException( "Only one property may be annotated with @ModifiedEntityNames!" ); + } + final XClass modifiedEntityNamesClass = property.getType(); + if ( reflectionManager.equals( modifiedEntityNamesClass, Set.class ) && + reflectionManager.equals( property.getElementClass(), String.class ) ) { + modifiedEntityNamesData = new PropertyData( + property.getName(), + property.getName(), + accessType, + null + ); + modifiedEntityNamesFound.set(); + } + else { + throw new MappingException( + "The field annotated with @ModifiedEntityNames must be of Set type." + ); + } + } + } + } - private void searchForRevisionInfoCfg(XClass clazz, ReflectionManager reflectionManager, - MutableBoolean revisionNumberFound, MutableBoolean revisionTimestampFound, - MutableBoolean modifiedEntityNamesFound) { - XClass superclazz = clazz.getSuperclass(); - if (!"java.lang.Object".equals(superclazz.getName())) { - searchForRevisionInfoCfg(superclazz, reflectionManager, revisionNumberFound, revisionTimestampFound, modifiedEntityNamesFound); - } + private void searchForRevisionInfoCfg( + XClass clazz, ReflectionManager reflectionManager, + MutableBoolean revisionNumberFound, MutableBoolean revisionTimestampFound, + MutableBoolean modifiedEntityNamesFound) { + final XClass superclazz = clazz.getSuperclass(); + if ( !"java.lang.Object".equals( superclazz.getName() ) ) { + searchForRevisionInfoCfg( + superclazz, + reflectionManager, + revisionNumberFound, + revisionTimestampFound, + modifiedEntityNamesFound + ); + } - searchForRevisionInfoCfgInProperties(clazz, reflectionManager, revisionNumberFound, revisionTimestampFound, - modifiedEntityNamesFound, "field"); - searchForRevisionInfoCfgInProperties(clazz, reflectionManager, revisionNumberFound, revisionTimestampFound, - modifiedEntityNamesFound, "property"); - } + searchForRevisionInfoCfgInProperties( + clazz, reflectionManager, revisionNumberFound, revisionTimestampFound, + modifiedEntityNamesFound, "field" + ); + searchForRevisionInfoCfgInProperties( + clazz, reflectionManager, revisionNumberFound, revisionTimestampFound, + modifiedEntityNamesFound, "property" + ); + } - public RevisionInfoConfigurationResult configure(Configuration cfg, ReflectionManager reflectionManager) { - Iterator classes = cfg.getClassMappings(); - boolean revisionEntityFound = false; - RevisionInfoGenerator revisionInfoGenerator = null; + public RevisionInfoConfigurationResult configure(Configuration cfg, ReflectionManager reflectionManager) { + boolean revisionEntityFound = false; + RevisionInfoGenerator revisionInfoGenerator = null; + Class revisionInfoClass = null; - Class revisionInfoClass = null; + final Iterator classes = cfg.getClassMappings(); + while ( classes.hasNext() ) { + PersistentClass pc = classes.next(); + XClass clazz; + try { + clazz = reflectionManager.classForName( pc.getClassName(), this.getClass() ); + } + catch (ClassNotFoundException e) { + throw new MappingException( e ); + } - while (classes.hasNext()) { - PersistentClass pc = classes.next(); - XClass clazz; - try { - clazz = reflectionManager.classForName(pc.getClassName(), this.getClass()); - } catch (ClassNotFoundException e) { - throw new MappingException(e); - } + final RevisionEntity revisionEntity = clazz.getAnnotation( RevisionEntity.class ); + if ( revisionEntity != null ) { + if ( revisionEntityFound ) { + throw new MappingException( "Only one entity may be annotated with @RevisionEntity!" ); + } - RevisionEntity revisionEntity = clazz.getAnnotation(RevisionEntity.class); - if (revisionEntity != null) { - if (revisionEntityFound) { - throw new MappingException("Only one entity may be annotated with @RevisionEntity!"); - } + // Checking if custom revision entity isn't audited + if ( clazz.getAnnotation( Audited.class ) != null ) { + throw new MappingException( "An entity annotated with @RevisionEntity cannot be audited!" ); + } - // Checking if custom revision entity isn't audited - if (clazz.getAnnotation(Audited.class) != null) { - throw new MappingException("An entity annotated with @RevisionEntity cannot be audited!"); - } + revisionEntityFound = true; - revisionEntityFound = true; + final MutableBoolean revisionNumberFound = new MutableBoolean(); + final MutableBoolean revisionTimestampFound = new MutableBoolean(); + final MutableBoolean modifiedEntityNamesFound = new MutableBoolean(); - MutableBoolean revisionNumberFound = new MutableBoolean(); - MutableBoolean revisionTimestampFound = new MutableBoolean(); - MutableBoolean modifiedEntityNamesFound = new MutableBoolean(); + searchForRevisionInfoCfg( + clazz, + reflectionManager, + revisionNumberFound, + revisionTimestampFound, + modifiedEntityNamesFound + ); - searchForRevisionInfoCfg(clazz, reflectionManager, revisionNumberFound, revisionTimestampFound, modifiedEntityNamesFound); + if ( !revisionNumberFound.isSet() ) { + throw new MappingException( + "An entity annotated with @RevisionEntity must have a field annotated " + + "with @RevisionNumber!" + ); + } - if (!revisionNumberFound.isSet()) { - throw new MappingException("An entity annotated with @RevisionEntity must have a field annotated " + - "with @RevisionNumber!"); - } + if ( !revisionTimestampFound.isSet() ) { + throw new MappingException( + "An entity annotated with @RevisionEntity must have a field annotated " + + "with @RevisionTimestamp!" + ); + } - if (!revisionTimestampFound.isSet()) { - throw new MappingException("An entity annotated with @RevisionEntity must have a field annotated " + - "with @RevisionTimestamp!"); - } + revisionInfoEntityName = pc.getEntityName(); + revisionInfoClass = pc.getMappedClass(); + final Class revisionListenerClass = getRevisionListenerClass( revisionEntity.value() ); + revisionInfoTimestampType = pc.getProperty( revisionInfoTimestampData.getName() ).getType(); + if ( globalCfg.isTrackEntitiesChangedInRevision() + || (globalCfg.isUseRevisionEntityWithNativeId() && DefaultTrackingModifiedEntitiesRevisionEntity.class + .isAssignableFrom( revisionInfoClass )) + || (!globalCfg.isUseRevisionEntityWithNativeId() && SequenceIdTrackingModifiedEntitiesRevisionEntity.class + .isAssignableFrom( revisionInfoClass )) + || modifiedEntityNamesFound.isSet() ) { + // If tracking modified entities parameter is enabled, custom revision info entity is a subtype + // of DefaultTrackingModifiedEntitiesRevisionEntity class, or @ModifiedEntityNames annotation is used. + revisionInfoGenerator = new DefaultTrackingModifiedEntitiesRevisionInfoGenerator( + revisionInfoEntityName, + revisionInfoClass, revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate(), + modifiedEntityNamesData + ); + globalCfg.setTrackEntitiesChangedInRevision( true ); + } + else { + revisionInfoGenerator = new DefaultRevisionInfoGenerator( + revisionInfoEntityName, revisionInfoClass, + revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate() + ); + } + } + } - revisionInfoEntityName = pc.getEntityName(); - revisionInfoClass = pc.getMappedClass(); - Class revisionListenerClass = getRevisionListenerClass(revisionEntity.value()); - revisionInfoTimestampType = pc.getProperty(revisionInfoTimestampData.getName()).getType(); - if (globalCfg.isTrackEntitiesChangedInRevision() - || (globalCfg.isUseRevisionEntityWithNativeId() && DefaultTrackingModifiedEntitiesRevisionEntity.class.isAssignableFrom(revisionInfoClass)) - || (!globalCfg.isUseRevisionEntityWithNativeId() && SequenceIdTrackingModifiedEntitiesRevisionEntity.class.isAssignableFrom(revisionInfoClass)) - || modifiedEntityNamesFound.isSet()) { - // If tracking modified entities parameter is enabled, custom revision info entity is a subtype - // of DefaultTrackingModifiedEntitiesRevisionEntity class, or @ModifiedEntityNames annotation is used. - revisionInfoGenerator = new DefaultTrackingModifiedEntitiesRevisionInfoGenerator(revisionInfoEntityName, - revisionInfoClass, revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate(), - modifiedEntityNamesData); - globalCfg.setTrackEntitiesChangedInRevision(true); - } else { - revisionInfoGenerator = new DefaultRevisionInfoGenerator(revisionInfoEntityName, revisionInfoClass, - revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate()); - } - } - } + // In case of a custom revision info generator, the mapping will be null. + Document revisionInfoXmlMapping = null; - // In case of a custom revision info generator, the mapping will be null. - Document revisionInfoXmlMapping = null; + final Class revisionListenerClass = getRevisionListenerClass( RevisionListener.class ); - Class revisionListenerClass = getRevisionListenerClass(RevisionListener.class); + if ( revisionInfoGenerator == null ) { + if ( globalCfg.isTrackEntitiesChangedInRevision() ) { + revisionInfoClass = globalCfg.isUseRevisionEntityWithNativeId() ? + DefaultTrackingModifiedEntitiesRevisionEntity.class + : + SequenceIdTrackingModifiedEntitiesRevisionEntity.class; + revisionInfoEntityName = revisionInfoClass.getName(); + revisionInfoGenerator = new DefaultTrackingModifiedEntitiesRevisionInfoGenerator( + revisionInfoEntityName, revisionInfoClass, + revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate(), modifiedEntityNamesData + ); + } + else { + revisionInfoClass = globalCfg.isUseRevisionEntityWithNativeId() ? DefaultRevisionEntity.class + : SequenceIdRevisionEntity.class; + revisionInfoGenerator = new DefaultRevisionInfoGenerator( + revisionInfoEntityName, revisionInfoClass, + revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate() + ); + } + revisionInfoXmlMapping = generateDefaultRevisionInfoXmlMapping(); + } - if (revisionInfoGenerator == null) { - if (globalCfg.isTrackEntitiesChangedInRevision()) { - revisionInfoClass = globalCfg.isUseRevisionEntityWithNativeId() ? DefaultTrackingModifiedEntitiesRevisionEntity.class - : SequenceIdTrackingModifiedEntitiesRevisionEntity.class; - revisionInfoEntityName = revisionInfoClass.getName(); - revisionInfoGenerator = new DefaultTrackingModifiedEntitiesRevisionInfoGenerator(revisionInfoEntityName, revisionInfoClass, - revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate(), modifiedEntityNamesData); - } else { - revisionInfoClass = globalCfg.isUseRevisionEntityWithNativeId() ? DefaultRevisionEntity.class - : SequenceIdRevisionEntity.class; - revisionInfoGenerator = new DefaultRevisionInfoGenerator(revisionInfoEntityName, revisionInfoClass, - revisionListenerClass, revisionInfoTimestampData, isTimestampAsDate()); - } - revisionInfoXmlMapping = generateDefaultRevisionInfoXmlMapping(); - } + return new RevisionInfoConfigurationResult( + revisionInfoGenerator, revisionInfoXmlMapping, + new RevisionInfoQueryCreator( + revisionInfoEntityName, revisionInfoIdData.getName(), + revisionInfoTimestampData.getName(), isTimestampAsDate() + ), + generateRevisionInfoRelationMapping(), + new RevisionInfoNumberReader( revisionInfoClass, revisionInfoIdData ), + globalCfg.isTrackEntitiesChangedInRevision() ? new ModifiedEntityNamesReader( + revisionInfoClass, + modifiedEntityNamesData + ) + : null, + revisionInfoEntityName, revisionInfoClass, revisionInfoTimestampData + ); + } - return new RevisionInfoConfigurationResult( - revisionInfoGenerator, revisionInfoXmlMapping, - new RevisionInfoQueryCreator(revisionInfoEntityName, revisionInfoIdData.getName(), - revisionInfoTimestampData.getName(), isTimestampAsDate()), - generateRevisionInfoRelationMapping(), - new RevisionInfoNumberReader(revisionInfoClass, revisionInfoIdData), - globalCfg.isTrackEntitiesChangedInRevision() ? new ModifiedEntityNamesReader(revisionInfoClass, modifiedEntityNamesData) - : null, - revisionInfoEntityName, revisionInfoClass, revisionInfoTimestampData); - } + private boolean isTimestampAsDate() { + final String typename = revisionInfoTimestampType.getName(); + return "date".equals( typename ) || "time".equals( typename ) || "timestamp".equals( typename ); + } - private boolean isTimestampAsDate() { - String typename = revisionInfoTimestampType.getName(); - return "date".equals(typename) || "time".equals(typename) || "timestamp".equals(typename); - } - - /** - * @param defaultListener Revision listener that shall be applied if {@code org.hibernate.envers.revision_listener} - * parameter has not been set. - * @return Revision listener. - */ - private Class getRevisionListenerClass(Class defaultListener) { - if (globalCfg.getRevisionListenerClass() != null) { - return globalCfg.getRevisionListenerClass(); - } - return defaultListener; - } + /** + * @param defaultListener Revision listener that shall be applied if {@code org.hibernate.envers.revision_listener} + * parameter has not been set. + * + * @return Revision listener. + */ + private Class getRevisionListenerClass(Class defaultListener) { + if ( globalCfg.getRevisionListenerClass() != null ) { + return globalCfg.getRevisionListenerClass(); + } + return defaultListener; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/RevisionInfoConfigurationResult.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/RevisionInfoConfigurationResult.java index 0b89067929..33267cfc33 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/RevisionInfoConfigurationResult.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/RevisionInfoConfigurationResult.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.configuration.internal; import org.dom4j.Document; @@ -23,11 +46,12 @@ public class RevisionInfoConfigurationResult { private final Class revisionInfoClass; private final PropertyData revisionInfoTimestampData; - RevisionInfoConfigurationResult(RevisionInfoGenerator revisionInfoGenerator, - Document revisionInfoXmlMapping, RevisionInfoQueryCreator revisionInfoQueryCreator, - Element revisionInfoRelationMapping, RevisionInfoNumberReader revisionInfoNumberReader, - ModifiedEntityNamesReader modifiedEntityNamesReader, String revisionInfoEntityName, - Class revisionInfoClass, PropertyData revisionInfoTimestampData) { + RevisionInfoConfigurationResult( + RevisionInfoGenerator revisionInfoGenerator, + Document revisionInfoXmlMapping, RevisionInfoQueryCreator revisionInfoQueryCreator, + Element revisionInfoRelationMapping, RevisionInfoNumberReader revisionInfoNumberReader, + ModifiedEntityNamesReader modifiedEntityNamesReader, String revisionInfoEntityName, + Class revisionInfoClass, PropertyData revisionInfoTimestampData) { this.revisionInfoGenerator = revisionInfoGenerator; this.revisionInfoXmlMapping = revisionInfoXmlMapping; this.revisionInfoQueryCreator = revisionInfoQueryCreator; diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/AuditEntityNameRegister.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/AuditEntityNameRegister.java index c2d00fdcf6..8f5b76a05c 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/AuditEntityNameRegister.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/AuditEntityNameRegister.java @@ -1,4 +1,28 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.configuration.internal.metadata; + import java.util.HashSet; import java.util.Set; @@ -6,46 +30,49 @@ import org.hibernate.MappingException; /** * A register of all audit entity names used so far. + * * @author Adam Warski (adam at warski dot org) */ public class AuditEntityNameRegister { - private final Set auditEntityNames = new HashSet(); + private final Set auditEntityNames = new HashSet(); - /** - * @param auditEntityName Name of the audit entity. - * @return True if the given audit entity name is already used. - */ - private boolean check(String auditEntityName) { - return auditEntityNames.contains(auditEntityName); - } - - /** - * Register an audit entity name. If the name is already registered, an exception is thrown. - * @param auditEntityName Name of the audit entity. - */ - public void register(String auditEntityName) { - if (auditEntityNames.contains(auditEntityName)) { - throw new MappingException("The audit entity name '" + auditEntityName + "' is already registered."); - } - - auditEntityNames.add(auditEntityName); - } - - /** - * Creates a unique (not yet registered) audit entity name by appending consecutive numbers to the base - * name. If the base name is not yet used, it is returned unmodified. + /** + * @param auditEntityName Name of the audit entity. * - * @param baseAuditEntityName The base entity name. - * - * @return A unique audit entity name - */ - public String createUnique(final String baseAuditEntityName) { - String auditEntityName = baseAuditEntityName; - int count = 1; - while (check(auditEntityName)) { - auditEntityName = baseAuditEntityName + count++; - } + * @return True if the given audit entity name is already used. + */ + private boolean check(String auditEntityName) { + return auditEntityNames.contains( auditEntityName ); + } - return auditEntityName; - } + /** + * Register an audit entity name. If the name is already registered, an exception is thrown. + * + * @param auditEntityName Name of the audit entity. + */ + public void register(String auditEntityName) { + if ( auditEntityNames.contains( auditEntityName ) ) { + throw new MappingException( "The audit entity name '" + auditEntityName + "' is already registered." ); + } + + auditEntityNames.add( auditEntityName ); + } + + /** + * Creates a unique (not yet registered) audit entity name by appending consecutive numbers to the base + * name. If the base name is not yet used, it is returned unmodified. + * + * @param baseAuditEntityName The base entity name. + * + * @return A unique audit entity name + */ + public String createUnique(final String baseAuditEntityName) { + String auditEntityName = baseAuditEntityName; + int count = 1; + while ( check( auditEntityName ) ) { + auditEntityName = baseAuditEntityName + count++; + } + + return auditEntityName; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/AuditMetadataGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/AuditMetadataGenerator.java index a0994f789e..a117e85c96 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/AuditMetadataGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/AuditMetadataGenerator.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -28,6 +28,7 @@ import java.util.Iterator; import java.util.Map; import org.dom4j.Element; + import org.jboss.logging.Logger; import org.hibernate.MappingException; @@ -73,124 +74,167 @@ import org.hibernate.type.Type; * @author Michal Skowronek (mskowr at o2 dot pl) */ public final class AuditMetadataGenerator { + private static final EnversMessageLogger LOG = Logger.getMessageLogger( + EnversMessageLogger.class, + AuditMetadataGenerator.class.getName() + ); - public static final EnversMessageLogger LOG = Logger.getMessageLogger(EnversMessageLogger.class, AuditMetadataGenerator.class.getName()); - - private final Configuration cfg; - private final GlobalConfiguration globalCfg; - private final AuditEntitiesConfiguration verEntCfg; - private final AuditStrategy auditStrategy; + private final Configuration cfg; + private final GlobalConfiguration globalCfg; + private final AuditEntitiesConfiguration verEntCfg; + private final AuditStrategy auditStrategy; private final ClassLoaderService classLoaderService; - private final Element revisionInfoRelationMapping; + private final Element revisionInfoRelationMapping; - /* - * Generators for different kinds of property values/types. - */ - private final BasicMetadataGenerator basicMetadataGenerator; + /* + * Generators for different kinds of property values/types. + */ + private final BasicMetadataGenerator basicMetadataGenerator; private final ComponentMetadataGenerator componentMetadataGenerator; - private final IdMetadataGenerator idMetadataGenerator; - private final ToOneRelationMetadataGenerator toOneRelationMetadataGenerator; + private final IdMetadataGenerator idMetadataGenerator; + private final ToOneRelationMetadataGenerator toOneRelationMetadataGenerator; - /* - * Here information about already generated mappings will be accumulated. - */ - private final Map entitiesConfigurations; - private final Map notAuditedEntitiesConfigurations; + /* + * Here information about already generated mappings will be accumulated. + */ + private final Map entitiesConfigurations; + private final Map notAuditedEntitiesConfigurations; - private final AuditEntityNameRegister auditEntityNameRegister; + private final AuditEntityNameRegister auditEntityNameRegister; - // Map entity name -> (join descriptor -> element describing the "versioned" join) - private final Map> entitiesJoins; + // Map entity name -> (join descriptor -> element describing the "versioned" join) + private final Map> entitiesJoins; - public AuditMetadataGenerator(Configuration cfg, GlobalConfiguration globalCfg, - AuditEntitiesConfiguration verEntCfg, - AuditStrategy auditStrategy, ClassLoaderService classLoaderService, - Element revisionInfoRelationMapping, - AuditEntityNameRegister auditEntityNameRegister) { - this.cfg = cfg; - this.globalCfg = globalCfg; - this.verEntCfg = verEntCfg; - this.auditStrategy = auditStrategy; + public AuditMetadataGenerator( + Configuration cfg, GlobalConfiguration globalCfg, + AuditEntitiesConfiguration verEntCfg, + AuditStrategy auditStrategy, ClassLoaderService classLoaderService, + Element revisionInfoRelationMapping, + AuditEntityNameRegister auditEntityNameRegister) { + this.cfg = cfg; + this.globalCfg = globalCfg; + this.verEntCfg = verEntCfg; + this.auditStrategy = auditStrategy; this.classLoaderService = classLoaderService; - this.revisionInfoRelationMapping = revisionInfoRelationMapping; + this.revisionInfoRelationMapping = revisionInfoRelationMapping; - this.basicMetadataGenerator = new BasicMetadataGenerator(); - this.componentMetadataGenerator = new ComponentMetadataGenerator(this); - this.idMetadataGenerator = new IdMetadataGenerator(this); - this.toOneRelationMetadataGenerator = new ToOneRelationMetadataGenerator(this); + this.basicMetadataGenerator = new BasicMetadataGenerator(); + this.componentMetadataGenerator = new ComponentMetadataGenerator( this ); + this.idMetadataGenerator = new IdMetadataGenerator( this ); + this.toOneRelationMetadataGenerator = new ToOneRelationMetadataGenerator( this ); - this.auditEntityNameRegister = auditEntityNameRegister; + this.auditEntityNameRegister = auditEntityNameRegister; - entitiesConfigurations = new HashMap(); - notAuditedEntitiesConfigurations = new HashMap(); - entitiesJoins = new HashMap>(); - } + entitiesConfigurations = new HashMap(); + notAuditedEntitiesConfigurations = new HashMap(); + entitiesJoins = new HashMap>(); + } - /** - * Clones the revision info relation mapping, so that it can be added to other mappings. Also, the name of - * the property and the column are set properly. - * @return A revision info mapping, which can be added to other mappings (has no parent). - */ - private Element cloneAndSetupRevisionInfoRelationMapping() { - Element rev_mapping = (Element) revisionInfoRelationMapping.clone(); - rev_mapping.addAttribute("name", verEntCfg.getRevisionFieldName()); + /** + * Clones the revision info relation mapping, so that it can be added to other mappings. Also, the name of + * the property and the column are set properly. + * + * @return A revision info mapping, which can be added to other mappings (has no parent). + */ + private Element cloneAndSetupRevisionInfoRelationMapping() { + final Element revMapping = (Element) revisionInfoRelationMapping.clone(); + revMapping.addAttribute( "name", verEntCfg.getRevisionFieldName() ); - MetadataTools.addOrModifyColumn(rev_mapping, verEntCfg.getRevisionFieldName()); + MetadataTools.addOrModifyColumn( revMapping, verEntCfg.getRevisionFieldName() ); - return rev_mapping; - } + return revMapping; + } - void addRevisionInfoRelation(Element any_mapping) { - any_mapping.add(cloneAndSetupRevisionInfoRelationMapping()); - } + void addRevisionInfoRelation(Element anyMapping) { + anyMapping.add( cloneAndSetupRevisionInfoRelationMapping() ); + } - void addRevisionType(Element any_mapping, Element any_mapping_end) { - Element revTypeProperty = MetadataTools.addProperty(any_mapping, verEntCfg.getRevisionTypePropName(), - verEntCfg.getRevisionTypePropType(), true, false); - revTypeProperty.addAttribute("type", "org.hibernate.envers.internal.entities.RevisionTypeType"); + void addRevisionType(Element anyMapping, Element anyMappingEnd) { + final Element revTypeProperty = MetadataTools.addProperty( + anyMapping, + verEntCfg.getRevisionTypePropName(), + verEntCfg.getRevisionTypePropType(), + true, + false + ); + revTypeProperty.addAttribute( "type", "org.hibernate.envers.internal.entities.RevisionTypeType" ); - // Adding the end revision, if appropriate - addEndRevision(any_mapping_end); - } + // Adding the end revision, if appropriate + addEndRevision( anyMappingEnd ); + } - private void addEndRevision(Element any_mapping ) { - // Add the end-revision field, if the appropriate strategy is used. - if (auditStrategy instanceof ValidityAuditStrategy) { - Element end_rev_mapping = (Element) revisionInfoRelationMapping.clone(); - end_rev_mapping.setName("many-to-one"); - end_rev_mapping.addAttribute("name", verEntCfg.getRevisionEndFieldName()); - MetadataTools.addOrModifyColumn(end_rev_mapping, verEntCfg.getRevisionEndFieldName()); + private void addEndRevision(Element anyMapping) { + // Add the end-revision field, if the appropriate strategy is used. + if ( auditStrategy instanceof ValidityAuditStrategy ) { + final Element endRevMapping = (Element) revisionInfoRelationMapping.clone(); + endRevMapping.setName( "many-to-one" ); + endRevMapping.addAttribute( "name", verEntCfg.getRevisionEndFieldName() ); + MetadataTools.addOrModifyColumn( endRevMapping, verEntCfg.getRevisionEndFieldName() ); - any_mapping.add(end_rev_mapping); + anyMapping.add( endRevMapping ); - if (verEntCfg.isRevisionEndTimestampEnabled()) { - // add a column for the timestamp of the end revision - String revisionInfoTimestampSqlType = TimestampType.INSTANCE.getName(); - Element timestampProperty = MetadataTools.addProperty(any_mapping, verEntCfg.getRevisionEndTimestampFieldName(), revisionInfoTimestampSqlType, true, true, false); - MetadataTools.addColumn(timestampProperty, verEntCfg.getRevisionEndTimestampFieldName(), null, null, null, null, null, null); - } - } - } + if ( verEntCfg.isRevisionEndTimestampEnabled() ) { + // add a column for the timestamp of the end revision + final String revisionInfoTimestampSqlType = TimestampType.INSTANCE.getName(); + final Element timestampProperty = MetadataTools.addProperty( + anyMapping, + verEntCfg.getRevisionEndTimestampFieldName(), + revisionInfoTimestampSqlType, + true, + true, + false + ); + MetadataTools.addColumn( + timestampProperty, + verEntCfg.getRevisionEndTimestampFieldName(), + null, + null, + null, + null, + null, + null + ); + } + } + } - private void addValueInFirstPass(Element parent, Value value, CompositeMapperBuilder currentMapper, String entityName, - EntityXmlMappingData xmlMappingData, PropertyAuditingData propertyAuditingData, - boolean insertable, boolean processModifiedFlag) { - Type type = value.getType(); + private void addValueInFirstPass( + Element parent, + Value value, + CompositeMapperBuilder currentMapper, + String entityName, + EntityXmlMappingData xmlMappingData, + PropertyAuditingData propertyAuditingData, + boolean insertable, + boolean processModifiedFlag) { + final Type type = value.getType(); + final boolean isBasic = basicMetadataGenerator.addBasic( + parent, + propertyAuditingData, + value, + currentMapper, + insertable, + false + ); - if (basicMetadataGenerator.addBasic(parent, propertyAuditingData, value, currentMapper, insertable, false)) { + if ( isBasic ) { // The property was mapped by the basic generator. - } else if (type instanceof ComponentType) { - componentMetadataGenerator.addComponent(parent, propertyAuditingData, value, currentMapper, - entityName, xmlMappingData, true); - } else { - if (!processedInSecondPass(type)) { + } + else if ( type instanceof ComponentType ) { + componentMetadataGenerator.addComponent( + parent, propertyAuditingData, value, currentMapper, + entityName, xmlMappingData, true + ); + } + else { + if ( !processedInSecondPass( type ) ) { // If we got here in the first pass, it means the basic mapper didn't map it, and none of the // above branches either. - throwUnsupportedTypeException(type, entityName, propertyAuditingData.getName()); + throwUnsupportedTypeException( type, entityName, propertyAuditingData.getName() ); } return; } - addModifiedFlagIfNeeded(parent, propertyAuditingData, processModifiedFlag); + addModifiedFlagIfNeeded( parent, propertyAuditingData, processModifiedFlag ); } private boolean processedInSecondPass(Type type) { @@ -198,79 +242,143 @@ public final class AuditMetadataGenerator { type instanceof OneToOneType || type instanceof CollectionType; } - private void addValueInSecondPass(Element parent, Value value, CompositeMapperBuilder currentMapper, String entityName, - EntityXmlMappingData xmlMappingData, PropertyAuditingData propertyAuditingData, - boolean insertable, boolean processModifiedFlag) { - Type type = value.getType(); + private void addValueInSecondPass( + Element parent, + Value value, + CompositeMapperBuilder currentMapper, + String entityName, + EntityXmlMappingData xmlMappingData, + PropertyAuditingData propertyAuditingData, + boolean insertable, + boolean processModifiedFlag) { + final Type type = value.getType(); - if (type instanceof ComponentType) { - componentMetadataGenerator.addComponent(parent, propertyAuditingData, value, currentMapper, - entityName, xmlMappingData, false); - return;// mod flag field has been already generated in first pass - } else if (type instanceof ManyToOneType) { - toOneRelationMetadataGenerator.addToOne(parent, propertyAuditingData, value, currentMapper, - entityName, insertable); - } else if (type instanceof OneToOneType) { - OneToOne oneToOne = (OneToOne) value; - if (oneToOne.getReferencedPropertyName() != null) { - toOneRelationMetadataGenerator.addOneToOneNotOwning(propertyAuditingData, value, - currentMapper, entityName); - } else { - // @OneToOne relation marked with @PrimaryKeyJoinColumn - toOneRelationMetadataGenerator.addOneToOnePrimaryKeyJoinColumn(propertyAuditingData, value, - currentMapper, entityName, insertable); - } - } else if (type instanceof CollectionType) { - CollectionMetadataGenerator collectionMetadataGenerator = new CollectionMetadataGenerator(this, - (Collection) value, currentMapper, entityName, xmlMappingData, - propertyAuditingData); - collectionMetadataGenerator.addCollection(); - } else { + if ( type instanceof ComponentType ) { + componentMetadataGenerator.addComponent( + parent, + propertyAuditingData, + value, + currentMapper, + entityName, + xmlMappingData, + false + ); + // mod flag field has been already generated in first pass return; } - addModifiedFlagIfNeeded(parent, propertyAuditingData, processModifiedFlag); + else if ( type instanceof ManyToOneType ) { + toOneRelationMetadataGenerator.addToOne( + parent, + propertyAuditingData, + value, + currentMapper, + entityName, + insertable + ); + } + else if ( type instanceof OneToOneType ) { + final OneToOne oneToOne = (OneToOne) value; + if ( oneToOne.getReferencedPropertyName() != null ) { + toOneRelationMetadataGenerator.addOneToOneNotOwning( + propertyAuditingData, + value, + currentMapper, + entityName + ); + } + else { + // @OneToOne relation marked with @PrimaryKeyJoinColumn + toOneRelationMetadataGenerator.addOneToOnePrimaryKeyJoinColumn( + propertyAuditingData, + value, + currentMapper, + entityName, + insertable + ); + } + } + else if ( type instanceof CollectionType ) { + final CollectionMetadataGenerator collectionMetadataGenerator = new CollectionMetadataGenerator( + this, + (Collection) value, + currentMapper, + entityName, + xmlMappingData, + propertyAuditingData + ); + collectionMetadataGenerator.addCollection(); + } + else { + return; + } + addModifiedFlagIfNeeded( parent, propertyAuditingData, processModifiedFlag ); } - private void addModifiedFlagIfNeeded(Element parent, PropertyAuditingData propertyAuditingData, boolean processModifiedFlag) { - if (processModifiedFlag && propertyAuditingData.isUsingModifiedFlag()) { - MetadataTools.addModifiedFlagProperty(parent, + private void addModifiedFlagIfNeeded( + Element parent, + PropertyAuditingData propertyAuditingData, + boolean processModifiedFlag) { + if ( processModifiedFlag && propertyAuditingData.isUsingModifiedFlag() ) { + MetadataTools.addModifiedFlagProperty( + parent, propertyAuditingData.getName(), - globalCfg.getModifiedFlagSuffix()); + globalCfg.getModifiedFlagSuffix() + ); } } - void addValue(Element parent, Value value, CompositeMapperBuilder currentMapper, String entityName, - EntityXmlMappingData xmlMappingData, PropertyAuditingData propertyAuditingData, - boolean insertable, boolean firstPass, boolean processModifiedFlag) { - if (firstPass) { - addValueInFirstPass(parent, value, currentMapper, entityName, - xmlMappingData, propertyAuditingData, insertable, processModifiedFlag); - } else { - addValueInSecondPass(parent, value, currentMapper, entityName, - xmlMappingData, propertyAuditingData, insertable, processModifiedFlag); + void addValue( + Element parent, Value value, CompositeMapperBuilder currentMapper, String entityName, + EntityXmlMappingData xmlMappingData, PropertyAuditingData propertyAuditingData, + boolean insertable, boolean firstPass, boolean processModifiedFlag) { + if ( firstPass ) { + addValueInFirstPass( + parent, value, currentMapper, entityName, + xmlMappingData, propertyAuditingData, insertable, processModifiedFlag + ); + } + else { + addValueInSecondPass( + parent, value, currentMapper, entityName, + xmlMappingData, propertyAuditingData, insertable, processModifiedFlag + ); } } - private void addProperties(Element parent, Iterator properties, CompositeMapperBuilder currentMapper, - ClassAuditingData auditingData, String entityName, EntityXmlMappingData xmlMappingData, - boolean firstPass) { - while (properties.hasNext()) { - Property property = properties.next(); - String propertyName = property.getName(); - PropertyAuditingData propertyAuditingData = auditingData.getPropertyAuditingData(propertyName); - if (propertyAuditingData != null) { - addValue(parent, property.getValue(), currentMapper, entityName, xmlMappingData, propertyAuditingData, - property.isInsertable(), firstPass, true); - } - } - } + private void addProperties( + Element parent, + Iterator properties, + CompositeMapperBuilder currentMapper, + ClassAuditingData auditingData, + String entityName, + EntityXmlMappingData xmlMappingData, + boolean firstPass) { + while ( properties.hasNext() ) { + final Property property = properties.next(); + final String propertyName = property.getName(); + final PropertyAuditingData propertyAuditingData = auditingData.getPropertyAuditingData( propertyName ); + if ( propertyAuditingData != null ) { + addValue( + parent, + property.getValue(), + currentMapper, + entityName, + xmlMappingData, + propertyAuditingData, + property.isInsertable(), + firstPass, + true + ); + } + } + } private boolean checkPropertiesAudited(Iterator properties, ClassAuditingData auditingData) { - while (properties.hasNext()) { - Property property = properties.next(); - String propertyName = property.getName(); - PropertyAuditingData propertyAuditingData = auditingData.getPropertyAuditingData(propertyName); - if (propertyAuditingData == null) { + while ( properties.hasNext() ) { + final Property property = properties.next(); + final String propertyName = property.getName(); + final PropertyAuditingData propertyAuditingData = auditingData.getPropertyAuditingData( propertyName ); + if ( propertyAuditingData == null ) { return false; } } @@ -278,325 +386,385 @@ public final class AuditMetadataGenerator { return true; } - protected String getSchema(String schemaFromAnnotation, Table table) { - // Get the schema from the annotation ... - String schema = schemaFromAnnotation; - // ... if empty, try using the default ... - if (StringTools.isEmpty(schema)) { - schema = globalCfg.getDefaultSchemaName(); + protected String getSchema(String schemaFromAnnotation, Table table) { + // Get the schema from the annotation ... + String schema = schemaFromAnnotation; + // ... if empty, try using the default ... + if ( StringTools.isEmpty( schema ) ) { + schema = globalCfg.getDefaultSchemaName(); - // ... if still empty, use the same as the normal table. - if (StringTools.isEmpty(schema)) { - schema = table.getSchema(); - } - } + // ... if still empty, use the same as the normal table. + if ( StringTools.isEmpty( schema ) ) { + schema = table.getSchema(); + } + } - return schema; - } + return schema; + } - protected String getCatalog(String catalogFromAnnotation, Table table) { - // Get the catalog from the annotation ... - String catalog = catalogFromAnnotation; - // ... if empty, try using the default ... - if (StringTools.isEmpty(catalog)) { - catalog = globalCfg.getDefaultCatalogName(); + protected String getCatalog(String catalogFromAnnotation, Table table) { + // Get the catalog from the annotation ... + String catalog = catalogFromAnnotation; + // ... if empty, try using the default ... + if ( StringTools.isEmpty( catalog ) ) { + catalog = globalCfg.getDefaultCatalogName(); - // ... if still empty, use the same as the normal table. - if (StringTools.isEmpty(catalog)) { - catalog = table.getCatalog(); - } - } + // ... if still empty, use the same as the normal table. + if ( StringTools.isEmpty( catalog ) ) { + catalog = table.getCatalog(); + } + } - return catalog; - } + return catalog; + } - @SuppressWarnings({"unchecked"}) - private void createJoins(PersistentClass pc, Element parent, ClassAuditingData auditingData) { - Iterator joins = pc.getJoinIterator(); + @SuppressWarnings({"unchecked"}) + private void createJoins(PersistentClass pc, Element parent, ClassAuditingData auditingData) { + final Iterator joins = pc.getJoinIterator(); + final Map joinElements = new HashMap(); + entitiesJoins.put( pc.getEntityName(), joinElements ); - Map joinElements = new HashMap(); - entitiesJoins.put(pc.getEntityName(), joinElements); - - while (joins.hasNext()) { - Join join = joins.next(); + while ( joins.hasNext() ) { + Join join = joins.next(); // Checking if all of the join properties are audited - if (!checkPropertiesAudited(join.getPropertyIterator(), auditingData)) { + if ( !checkPropertiesAudited( join.getPropertyIterator(), auditingData ) ) { continue; } - // Determining the table name. If there is no entry in the dictionary, just constructing the table name - // as if it was an entity (by appending/prepending configured strings). - String originalTableName = join.getTable().getName(); - String auditTableName = auditingData.getSecondaryTableDictionary().get(originalTableName); - if (auditTableName == null) { - auditTableName = verEntCfg.getAuditEntityName(originalTableName); - } - - String schema = getSchema(auditingData.getAuditTable().schema(), join.getTable()); - String catalog = getCatalog(auditingData.getAuditTable().catalog(), join.getTable()); - - Element joinElement = MetadataTools.createJoin(parent, auditTableName, schema, catalog); - joinElements.put(join, joinElement); - - Element joinKey = joinElement.addElement("key"); - MetadataTools.addColumns(joinKey, join.getKey().getColumnIterator()); - MetadataTools.addColumn(joinKey, verEntCfg.getRevisionFieldName(), null, null, null, null, null, null); - } - } - - @SuppressWarnings({"unchecked"}) - private void addJoins(PersistentClass pc, CompositeMapperBuilder currentMapper, ClassAuditingData auditingData, - String entityName, EntityXmlMappingData xmlMappingData,boolean firstPass) { - Iterator joins = pc.getJoinIterator(); - - while (joins.hasNext()) { - Join join = joins.next(); - Element joinElement = entitiesJoins.get(entityName).get(join); - - if (joinElement != null) { - addProperties(joinElement, join.getPropertyIterator(), currentMapper, auditingData, entityName, - xmlMappingData, firstPass); + // Determining the table name. If there is no entry in the dictionary, just constructing the table name + // as if it was an entity (by appending/prepending configured strings). + final String originalTableName = join.getTable().getName(); + String auditTableName = auditingData.getSecondaryTableDictionary().get( originalTableName ); + if ( auditTableName == null ) { + auditTableName = verEntCfg.getAuditEntityName( originalTableName ); } - } - } - @SuppressWarnings({"unchecked"}) - private Triple generateMappingData( - PersistentClass pc, EntityXmlMappingData xmlMappingData, AuditTableData auditTableData, - IdMappingData idMapper) { - Element class_mapping = MetadataTools.createEntity(xmlMappingData.getMainXmlMapping(), auditTableData, - pc.getDiscriminatorValue(), pc.isAbstract()); - ExtendedPropertyMapper propertyMapper = new MultiPropertyMapper(); + final String schema = getSchema( auditingData.getAuditTable().schema(), join.getTable() ); + final String catalog = getCatalog( auditingData.getAuditTable().catalog(), join.getTable() ); - // Checking if there is a discriminator column - if (pc.getDiscriminator() != null) { - Element discriminator_element = class_mapping.addElement("discriminator"); - // Database column or SQL formula allowed to distinguish entity types - MetadataTools.addColumnsOrFormulas(discriminator_element, pc.getDiscriminator().getColumnIterator()); - discriminator_element.addAttribute("type", pc.getDiscriminator().getType().getName()); - } + final Element joinElement = MetadataTools.createJoin( parent, auditTableName, schema, catalog ); + joinElements.put( join, joinElement ); - // Adding the id mapping - class_mapping.add((Element) idMapper.getXmlMapping().clone()); + final Element joinKey = joinElement.addElement( "key" ); + MetadataTools.addColumns( joinKey, join.getKey().getColumnIterator() ); + MetadataTools.addColumn( joinKey, verEntCfg.getRevisionFieldName(), null, null, null, null, null, null ); + } + } - // Adding the "revision type" property - addRevisionType(class_mapping, class_mapping); + @SuppressWarnings({"unchecked"}) + private void addJoins( + PersistentClass pc, + CompositeMapperBuilder currentMapper, + ClassAuditingData auditingData, + String entityName, + EntityXmlMappingData xmlMappingData, + boolean firstPass) { + final Iterator joins = pc.getJoinIterator(); - return Triple.make(class_mapping, propertyMapper, null); - } + while ( joins.hasNext() ) { + final Join join = joins.next(); + final Element joinElement = entitiesJoins.get( entityName ).get( join ); - private Triple generateInheritanceMappingData( - PersistentClass pc, EntityXmlMappingData xmlMappingData, AuditTableData auditTableData, - String inheritanceMappingType) { - String extendsEntityName = verEntCfg.getAuditEntityName(pc.getSuperclass().getEntityName()); - Element class_mapping = MetadataTools.createSubclassEntity(xmlMappingData.getMainXmlMapping(), - inheritanceMappingType, auditTableData, extendsEntityName, pc.getDiscriminatorValue(), pc.isAbstract()); + if ( joinElement != null ) { + addProperties( + joinElement, + join.getPropertyIterator(), + currentMapper, + auditingData, + entityName, + xmlMappingData, + firstPass + ); + } + } + } - // The id and revision type is already mapped in the parent + @SuppressWarnings({"unchecked"}) + private Triple generateMappingData( + PersistentClass pc, EntityXmlMappingData xmlMappingData, AuditTableData auditTableData, + IdMappingData idMapper) { + final Element classMapping = MetadataTools.createEntity( + xmlMappingData.getMainXmlMapping(), + auditTableData, + pc.getDiscriminatorValue(), + pc.isAbstract() + ); + final ExtendedPropertyMapper propertyMapper = new MultiPropertyMapper(); - // Getting the property mapper of the parent - when mapping properties, they need to be included - String parentEntityName = pc.getSuperclass().getEntityName(); + // Checking if there is a discriminator column + if ( pc.getDiscriminator() != null ) { + final Element discriminatorElement = classMapping.addElement( "discriminator" ); + // Database column or SQL formula allowed to distinguish entity types + MetadataTools.addColumnsOrFormulas( discriminatorElement, pc.getDiscriminator().getColumnIterator() ); + discriminatorElement.addAttribute( "type", pc.getDiscriminator().getType().getName() ); + } - EntityConfiguration parentConfiguration = entitiesConfigurations.get(parentEntityName); - if (parentConfiguration == null) { - throw new MappingException("Entity '" + pc.getEntityName() + "' is audited, but its superclass: '" + - parentEntityName + "' is not."); - } + // Adding the id mapping + classMapping.add( (Element) idMapper.getXmlMapping().clone() ); - ExtendedPropertyMapper parentPropertyMapper = parentConfiguration.getPropertyMapper(); - ExtendedPropertyMapper propertyMapper = new SubclassPropertyMapper(new MultiPropertyMapper(), parentPropertyMapper); + // Adding the "revision type" property + addRevisionType( classMapping, classMapping ); - return Triple.make(class_mapping, propertyMapper, parentEntityName); - } + return Triple.make( classMapping, propertyMapper, null ); + } - @SuppressWarnings({"unchecked"}) - public void generateFirstPass(PersistentClass pc, ClassAuditingData auditingData, - EntityXmlMappingData xmlMappingData, boolean isAudited) { - String schema = getSchema(auditingData.getAuditTable().schema(), pc.getTable()); - String catalog = getCatalog(auditingData.getAuditTable().catalog(), pc.getTable()); + private Triple generateInheritanceMappingData( + PersistentClass pc, EntityXmlMappingData xmlMappingData, AuditTableData auditTableData, + String inheritanceMappingType) { + final String extendsEntityName = verEntCfg.getAuditEntityName( pc.getSuperclass().getEntityName() ); + final Element classMapping = MetadataTools.createSubclassEntity( + xmlMappingData.getMainXmlMapping(), + inheritanceMappingType, + auditTableData, + extendsEntityName, + pc.getDiscriminatorValue(), + pc.isAbstract() + ); - if (!isAudited) { - String entityName = pc.getEntityName(); - IdMappingData idMapper = idMetadataGenerator.addId(pc, false); + // The id and revision type is already mapped in the parent - if (idMapper == null) { - // Unsupported id mapping, e.g. key-many-to-one. If the entity is used in auditing, an exception - // will be thrown later on. - LOG.debugf("Unable to create auditing id mapping for entity %s, because of an unsupported Hibernate id mapping (e.g. key-many-to-one)", - entityName); - return; - } + // Getting the property mapper of the parent - when mapping properties, they need to be included + final String parentEntityName = pc.getSuperclass().getEntityName(); - ExtendedPropertyMapper propertyMapper = null; - String parentEntityName = null; - EntityConfiguration entityCfg = new EntityConfiguration(entityName, pc.getClassName(), idMapper, propertyMapper, - parentEntityName); - notAuditedEntitiesConfigurations.put(entityName, entityCfg); + final EntityConfiguration parentConfiguration = entitiesConfigurations.get( parentEntityName ); + if ( parentConfiguration == null ) { + throw new MappingException( + "Entity '" + pc.getEntityName() + "' is audited, but its superclass: '" + + parentEntityName + "' is not." + ); + } + + final ExtendedPropertyMapper parentPropertyMapper = parentConfiguration.getPropertyMapper(); + final ExtendedPropertyMapper propertyMapper = new SubclassPropertyMapper( + new MultiPropertyMapper(), + parentPropertyMapper + ); + + return Triple.make( classMapping, propertyMapper, parentEntityName ); + } + + @SuppressWarnings({"unchecked"}) + public void generateFirstPass( + PersistentClass pc, + ClassAuditingData auditingData, + EntityXmlMappingData xmlMappingData, + boolean isAudited) { + final String schema = getSchema( auditingData.getAuditTable().schema(), pc.getTable() ); + final String catalog = getCatalog( auditingData.getAuditTable().catalog(), pc.getTable() ); + + if ( !isAudited ) { + final String entityName = pc.getEntityName(); + final IdMappingData idMapper = idMetadataGenerator.addId( pc, false ); + + if ( idMapper == null ) { + // Unsupported id mapping, e.g. key-many-to-one. If the entity is used in auditing, an exception + // will be thrown later on. + LOG.debugf( + "Unable to create auditing id mapping for entity %s, because of an unsupported Hibernate id mapping (e.g. key-many-to-one)", + entityName + ); + return; + } + + final ExtendedPropertyMapper propertyMapper = null; + final String parentEntityName = null; + final EntityConfiguration entityCfg = new EntityConfiguration( + entityName, + pc.getClassName(), + idMapper, + propertyMapper, + parentEntityName + ); + notAuditedEntitiesConfigurations.put( entityName, entityCfg ); return; } - String entityName = pc.getEntityName(); - LOG.debugf("Generating first-pass auditing mapping for entity %s", entityName); + final String entityName = pc.getEntityName(); + LOG.debugf( "Generating first-pass auditing mapping for entity %s", entityName ); - String auditEntityName = verEntCfg.getAuditEntityName(entityName); - String auditTableName = verEntCfg.getAuditTableName(entityName, pc.getTable().getName()); + final String auditEntityName = verEntCfg.getAuditEntityName( entityName ); + final String auditTableName = verEntCfg.getAuditTableName( entityName, pc.getTable().getName() ); - // Registering the audit entity name, now that it is known - auditEntityNameRegister.register(auditEntityName); + // Registering the audit entity name, now that it is known + auditEntityNameRegister.register( auditEntityName ); - AuditTableData auditTableData = new AuditTableData(auditEntityName, auditTableName, schema, catalog); + final AuditTableData auditTableData = new AuditTableData( auditEntityName, auditTableName, schema, catalog ); - // Generating a mapping for the id - IdMappingData idMapper = idMetadataGenerator.addId(pc, true); + // Generating a mapping for the id + final IdMappingData idMapper = idMetadataGenerator.addId( pc, true ); - InheritanceType inheritanceType = InheritanceType.get(pc); + final InheritanceType inheritanceType = InheritanceType.get( pc ); - // These properties will be read from the mapping data - final Element class_mapping; - final ExtendedPropertyMapper propertyMapper; - final String parentEntityName; + // These properties will be read from the mapping data + final Element classMapping; + final ExtendedPropertyMapper propertyMapper; + final String parentEntityName; - final Triple mappingData; + final Triple mappingData; - // Reading the mapping data depending on inheritance type (if any) - switch (inheritanceType) { - case NONE: - mappingData = generateMappingData(pc, xmlMappingData, auditTableData, idMapper); - break; + // Reading the mapping data depending on inheritance type (if any) + switch ( inheritanceType ) { + case NONE: + mappingData = generateMappingData( pc, xmlMappingData, auditTableData, idMapper ); + break; - case SINGLE: - mappingData = generateInheritanceMappingData(pc, xmlMappingData, auditTableData, "subclass"); - break; + case SINGLE: + mappingData = generateInheritanceMappingData( pc, xmlMappingData, auditTableData, "subclass" ); + break; - case JOINED: - mappingData = generateInheritanceMappingData(pc, xmlMappingData, auditTableData, "joined-subclass"); + case JOINED: + mappingData = generateInheritanceMappingData( pc, xmlMappingData, auditTableData, "joined-subclass" ); - // Adding the "key" element with all id columns... - Element keyMapping = mappingData.getFirst().addElement("key"); - MetadataTools.addColumns(keyMapping, pc.getTable().getPrimaryKey().columnIterator()); + // Adding the "key" element with all id columns... + final Element keyMapping = mappingData.getFirst().addElement( "key" ); + MetadataTools.addColumns( keyMapping, pc.getTable().getPrimaryKey().columnIterator() ); - // ... and the revision number column, read from the revision info relation mapping. - keyMapping.add((Element) cloneAndSetupRevisionInfoRelationMapping().element("column").clone()); - break; + // ... and the revision number column, read from the revision info relation mapping. + keyMapping.add( (Element) cloneAndSetupRevisionInfoRelationMapping().element( "column" ).clone() ); + break; - case TABLE_PER_CLASS: - mappingData = generateInheritanceMappingData(pc, xmlMappingData, auditTableData, "union-subclass"); - break; + case TABLE_PER_CLASS: + mappingData = generateInheritanceMappingData( pc, xmlMappingData, auditTableData, "union-subclass" ); + break; - default: - throw new AssertionError("Impossible enum value."); - } + default: + throw new AssertionError( "Impossible enum value." ); + } - class_mapping = mappingData.getFirst(); - propertyMapper = mappingData.getSecond(); - parentEntityName = mappingData.getThird(); + classMapping = mappingData.getFirst(); + propertyMapper = mappingData.getSecond(); + parentEntityName = mappingData.getThird(); - xmlMappingData.setClassMapping(class_mapping); + xmlMappingData.setClassMapping( classMapping ); - // Mapping unjoined properties - addProperties(class_mapping, pc.getUnjoinedPropertyIterator(), propertyMapper, - auditingData, pc.getEntityName(), xmlMappingData, - true); + // Mapping unjoined properties + addProperties( + classMapping, pc.getUnjoinedPropertyIterator(), propertyMapper, + auditingData, pc.getEntityName(), xmlMappingData, + true + ); - // Creating and mapping joins (first pass) - createJoins(pc, class_mapping, auditingData); - addJoins(pc, propertyMapper, auditingData, pc.getEntityName(), xmlMappingData, true); + // Creating and mapping joins (first pass) + createJoins( pc, classMapping, auditingData ); + addJoins( pc, propertyMapper, auditingData, pc.getEntityName(), xmlMappingData, true ); - // Storing the generated configuration - EntityConfiguration entityCfg = new EntityConfiguration(auditEntityName, pc.getClassName(), idMapper, - propertyMapper, parentEntityName); - entitiesConfigurations.put(pc.getEntityName(), entityCfg); - } + // Storing the generated configuration + final EntityConfiguration entityCfg = new EntityConfiguration( + auditEntityName, + pc.getClassName(), + idMapper, + propertyMapper, + parentEntityName + ); + entitiesConfigurations.put( pc.getEntityName(), entityCfg ); + } - @SuppressWarnings({"unchecked"}) - public void generateSecondPass(PersistentClass pc, ClassAuditingData auditingData, - EntityXmlMappingData xmlMappingData) { - String entityName = pc.getEntityName(); - LOG.debugf("Generating second-pass auditing mapping for entity %s", entityName); + @SuppressWarnings({"unchecked"}) + public void generateSecondPass( + PersistentClass pc, + ClassAuditingData auditingData, + EntityXmlMappingData xmlMappingData) { + final String entityName = pc.getEntityName(); + LOG.debugf( "Generating second-pass auditing mapping for entity %s", entityName ); - CompositeMapperBuilder propertyMapper = entitiesConfigurations.get(entityName).getPropertyMapper(); + final CompositeMapperBuilder propertyMapper = entitiesConfigurations.get( entityName ).getPropertyMapper(); - // Mapping unjoined properties - Element parent = xmlMappingData.getClassMapping(); + // Mapping unjoined properties + final Element parent = xmlMappingData.getClassMapping(); - addProperties(parent, pc.getUnjoinedPropertyIterator(), - propertyMapper, auditingData, entityName, xmlMappingData, false); + addProperties( + parent, + pc.getUnjoinedPropertyIterator(), + propertyMapper, + auditingData, + entityName, + xmlMappingData, + false + ); - // Mapping joins (second pass) - addJoins(pc, propertyMapper, auditingData, entityName, xmlMappingData, false); - } + // Mapping joins (second pass) + addJoins( pc, propertyMapper, auditingData, entityName, xmlMappingData, false ); + } - public Map getEntitiesConfigurations() { - return entitiesConfigurations; - } + public Map getEntitiesConfigurations() { + return entitiesConfigurations; + } - // Getters for generators and configuration + // Getters for generators and configuration - BasicMetadataGenerator getBasicMetadataGenerator() { - return basicMetadataGenerator; - } + BasicMetadataGenerator getBasicMetadataGenerator() { + return basicMetadataGenerator; + } - Configuration getCfg() { - return cfg; - } + Configuration getCfg() { + return cfg; + } - GlobalConfiguration getGlobalCfg() { - return globalCfg; - } + GlobalConfiguration getGlobalCfg() { + return globalCfg; + } - AuditEntitiesConfiguration getVerEntCfg() { - return verEntCfg; - } + AuditEntitiesConfiguration getVerEntCfg() { + return verEntCfg; + } - AuditStrategy getAuditStrategy() { - return auditStrategy; - } + AuditStrategy getAuditStrategy() { + return auditStrategy; + } ClassLoaderService getClassLoaderService() { return classLoaderService; } - AuditEntityNameRegister getAuditEntityNameRegister() { - return auditEntityNameRegister; - } + AuditEntityNameRegister getAuditEntityNameRegister() { + return auditEntityNameRegister; + } - void throwUnsupportedTypeException(Type type, String entityName, String propertyName) { - String message = "Type not supported for auditing: " + type.getClass().getName() + - ", on entity " + entityName + ", property '" + propertyName + "'."; + void throwUnsupportedTypeException(Type type, String entityName, String propertyName) { + final String message = "Type not supported for auditing: " + type.getClass().getName() + + ", on entity " + entityName + ", property '" + propertyName + "'."; - throw new MappingException(message); - } + throw new MappingException( message ); + } - /** - * Reads the id mapping data of a referenced entity. - * @param entityName Name of the entity which is the source of the relation. - * @param referencedEntityName Name of the entity which is the target of the relation. - * @param propertyAuditingData Auditing data of the property that is the source of the relation. - * @param allowNotAuditedTarget Are not-audited target entities allowed. - * @throws MappingException If a relation from an audited to a non-audited entity is detected, which is not - * mapped using {@link RelationTargetAuditMode#NOT_AUDITED}. - * @return The id mapping data of the related entity. - */ - IdMappingData getReferencedIdMappingData(String entityName, String referencedEntityName, - PropertyAuditingData propertyAuditingData, - boolean allowNotAuditedTarget) { - EntityConfiguration configuration = getEntitiesConfigurations().get(referencedEntityName); - if (configuration == null) { - RelationTargetAuditMode relationTargetAuditMode = propertyAuditingData.getRelationTargetAuditMode(); - configuration = getNotAuditedEntitiesConfigurations().get(referencedEntityName); + /** + * Reads the id mapping data of a referenced entity. + * + * @param entityName Name of the entity which is the source of the relation. + * @param referencedEntityName Name of the entity which is the target of the relation. + * @param propertyAuditingData Auditing data of the property that is the source of the relation. + * @param allowNotAuditedTarget Are not-audited target entities allowed. + * + * @return The id mapping data of the related entity. + * + * @throws MappingException If a relation from an audited to a non-audited entity is detected, which is not + * mapped using {@link RelationTargetAuditMode#NOT_AUDITED}. + */ + IdMappingData getReferencedIdMappingData( + String entityName, String referencedEntityName, + PropertyAuditingData propertyAuditingData, + boolean allowNotAuditedTarget) { + EntityConfiguration configuration = getEntitiesConfigurations().get( referencedEntityName ); + if ( configuration == null ) { + final RelationTargetAuditMode relationTargetAuditMode = propertyAuditingData.getRelationTargetAuditMode(); + configuration = getNotAuditedEntitiesConfigurations().get( referencedEntityName ); - if (configuration == null || !allowNotAuditedTarget || !RelationTargetAuditMode.NOT_AUDITED.equals(relationTargetAuditMode)) { - throw new MappingException("An audited relation from " + entityName + "." - + propertyAuditingData.getName() + " to a not audited entity " + referencedEntityName + "!" - + (allowNotAuditedTarget ? - " Such mapping is possible, but has to be explicitly defined using @Audited(targetAuditMode = NOT_AUDITED)." : - "")); + if ( configuration == null || !allowNotAuditedTarget || !RelationTargetAuditMode.NOT_AUDITED.equals( + relationTargetAuditMode + ) ) { + throw new MappingException( + "An audited relation from " + entityName + "." + + propertyAuditingData.getName() + " to a not audited entity " + referencedEntityName + "!" + + (allowNotAuditedTarget ? + " Such mapping is possible, but has to be explicitly defined using @Audited(targetAuditMode = NOT_AUDITED)." : + "") + ); } } - return configuration.getIdMappingData(); - } + return configuration.getIdMappingData(); + } /** * Get the notAuditedEntitiesConfigurations property. diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/AuditTableData.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/AuditTableData.java index 3d68cfcd2b..fb20152f25 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/AuditTableData.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/AuditTableData.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -21,41 +21,41 @@ * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ - package org.hibernate.envers.configuration.internal.metadata; /** * Holds information necessary to create an audit table: its name, schema and catalog, as well as the audit * entity name. + * * @author Adam Warski (adam at warski dot org) */ public class AuditTableData { - private final String auditEntityName; - private final String auditTableName; - private final String schema; - private final String catalog; + private final String auditEntityName; + private final String auditTableName; + private final String schema; + private final String catalog; - public AuditTableData(String auditEntityName, String auditTableName, String schema, String catalog) { - this.auditEntityName = auditEntityName; - this.auditTableName = auditTableName; - this.schema = schema; - this.catalog = catalog; - } + public AuditTableData(String auditEntityName, String auditTableName, String schema, String catalog) { + this.auditEntityName = auditEntityName; + this.auditTableName = auditTableName; + this.schema = schema; + this.catalog = catalog; + } - public String getAuditEntityName() { - return auditEntityName; - } + public String getAuditEntityName() { + return auditEntityName; + } - public String getAuditTableName() { - return auditTableName; - } + public String getAuditTableName() { + return auditTableName; + } - public String getSchema() { - return schema; - } + public String getSchema() { + return schema; + } - public String getCatalog() { - return catalog; - } + public String getCatalog() { + return catalog; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/BasicMetadataGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/BasicMetadataGenerator.java index 62cdf89678..27e5ebe671 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/BasicMetadataGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/BasicMetadataGenerator.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -40,47 +40,54 @@ import org.hibernate.usertype.DynamicParameterizedType; /** * Generates metadata for basic properties: immutable types (including enums). + * * @author Adam Warski (adam at warski dot org) */ public final class BasicMetadataGenerator { - @SuppressWarnings({ "unchecked" }) - boolean addBasic(Element parent, PropertyAuditingData propertyAuditingData, - Value value, SimpleMapperBuilder mapper, boolean insertable, boolean key) { - Type type = value.getType(); + @SuppressWarnings({"unchecked"}) + boolean addBasic( + Element parent, PropertyAuditingData propertyAuditingData, + Value value, SimpleMapperBuilder mapper, boolean insertable, boolean key) { + final Type type = value.getType(); - if ( type instanceof BasicType || type instanceof SerializableToBlobType || - "org.hibernate.type.PrimitiveByteArrayBlobType".equals( type.getClass().getName() ) ) { + if ( type instanceof BasicType + || type instanceof SerializableToBlobType + || "org.hibernate.type.PrimitiveByteArrayBlobType".equals( type.getClass().getName() ) ) { if ( parent != null ) { - boolean addNestedType = ( value instanceof SimpleValue ) && ( (SimpleValue) value ).getTypeParameters() != null; + final boolean addNestedType = (value instanceof SimpleValue) + && ((SimpleValue) value).getTypeParameters() != null; String typeName = type.getName(); if ( typeName == null ) { typeName = type.getClass().getName(); } - Element prop_mapping = MetadataTools.addProperty( - parent, propertyAuditingData.getName(), - addNestedType ? null : typeName, propertyAuditingData.isForceInsertable() || insertable, key + final Element propMapping = MetadataTools.addProperty( + parent, + propertyAuditingData.getName(), + addNestedType ? null : typeName, + propertyAuditingData.isForceInsertable() || insertable, + key ); - MetadataTools.addColumns( prop_mapping, value.getColumnIterator() ); + MetadataTools.addColumns( propMapping, value.getColumnIterator() ); if ( addNestedType ) { - Properties typeParameters = ( (SimpleValue) value ).getTypeParameters(); - Element type_mapping = prop_mapping.addElement( "type" ); - type_mapping.addAttribute( "name", typeName ); + final Properties typeParameters = ((SimpleValue) value).getTypeParameters(); + final Element typeMapping = propMapping.addElement( "type" ); + typeMapping.addAttribute( "name", typeName ); if ( "org.hibernate.type.EnumType".equals( typeName ) ) { // Proper handling of enumeration type - mapEnumerationType( type_mapping, type, typeParameters ); + mapEnumerationType( typeMapping, type, typeParameters ); } else { // By default copying all Hibernate properties for ( Object object : typeParameters.keySet() ) { - String keyType = (String) object; - String property = typeParameters.getProperty( keyType ); + final String keyType = (String) object; + final String property = typeParameters.getProperty( keyType ); if ( property != null ) { - type_mapping.addElement( "param" ).addAttribute( "name", keyType ).setText( property ); + typeMapping.addElement( "param" ).addAttribute( "name", keyType ).setText( property ); } } } @@ -101,32 +108,43 @@ public final class BasicMetadataGenerator { private void mapEnumerationType(Element parent, Type type, Properties parameters) { if ( parameters.getProperty( EnumType.ENUM ) != null ) { - parent.addElement( "param" ).addAttribute( "name", EnumType.ENUM ).setText( parameters.getProperty( EnumType.ENUM ) ); + parent.addElement( "param" ) + .addAttribute( "name", EnumType.ENUM ) + .setText( parameters.getProperty( EnumType.ENUM ) ); } else { - parent.addElement( "param" ).addAttribute( "name", EnumType.ENUM ).setText( type.getReturnedClass().getName() ); + parent.addElement( "param" ).addAttribute( "name", EnumType.ENUM ).setText( + type.getReturnedClass() + .getName() + ); } if ( parameters.getProperty( EnumType.NAMED ) != null ) { - parent.addElement( "param" ).addAttribute( "name", EnumType.NAMED ).setText( parameters.getProperty( EnumType.NAMED ) ); + parent.addElement( "param" ).addAttribute( "name", EnumType.NAMED ).setText( + parameters.getProperty( + EnumType.NAMED + ) + ); } else if ( parameters.get( DynamicParameterizedType.XPROPERTY ) != null ) { // Case of annotations. parent.addElement( "param" ).addAttribute( "name", EnumType.NAMED ) - .setText( "" + !( (EnumType) ( (CustomType) type ).getUserType() ).isOrdinal() ); - } - else { - // Otherwise we assume that the choice between ordinal and named representation has been omitted. - // Call to EnumType#isOrdinal() would always return the default Types.INTEGER. We let Hibernate - // to choose the proper strategy during runtime. + .setText( "" + !((EnumType) ((CustomType) type).getUserType()).isOrdinal() ); } + // Otherwise we assume that the choice between ordinal and named representation has been omitted. + // Call to EnumType#isOrdinal() would always return the default Types.INTEGER. We let Hibernate + // to choose the proper strategy during runtime. } - @SuppressWarnings({ "unchecked" }) - boolean addManyToOne(Element parent, PropertyAuditingData propertyAuditingData, Value value, SimpleMapperBuilder mapper) { - Type type = value.getType(); + @SuppressWarnings({"unchecked"}) + boolean addManyToOne( + Element parent, + PropertyAuditingData propertyAuditingData, + Value value, + SimpleMapperBuilder mapper) { + final Type type = value.getType(); // A null mapper occurs when adding to composite-id element - Element manyToOneElement = parent.addElement( mapper != null ? "many-to-one" : "key-many-to-one" ); + final Element manyToOneElement = parent.addElement( mapper != null ? "many-to-one" : "key-many-to-one" ); manyToOneElement.addAttribute( "name", propertyAuditingData.getName() ); manyToOneElement.addAttribute( "class", type.getName() ); MetadataTools.addColumns( manyToOneElement, value.getColumnIterator() ); diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/CollectionMetadataGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/CollectionMetadataGenerator.java index 8ed1b9db3f..708baea3a4 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/CollectionMetadataGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/CollectionMetadataGenerator.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -23,6 +23,7 @@ */ package org.hibernate.envers.configuration.internal.metadata; +import javax.persistence.JoinColumn; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -32,9 +33,9 @@ import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; -import javax.persistence.JoinColumn; import org.dom4j.Element; + import org.jboss.logging.Logger; import org.hibernate.MappingException; @@ -102,380 +103,502 @@ import org.hibernate.type.Type; /** * Generates metadata for a collection-valued property. + * * @author Adam Warski (adam at warski dot org) * @author HernпїЅn Chanfreau */ public final class CollectionMetadataGenerator { + private static final EnversMessageLogger LOG = Logger.getMessageLogger( + EnversMessageLogger.class, + CollectionMetadataGenerator.class.getName() + ); - public static final EnversMessageLogger LOG = Logger.getMessageLogger(EnversMessageLogger.class, CollectionMetadataGenerator.class.getName()); + private final AuditMetadataGenerator mainGenerator; + private final String propertyName; + private final Collection propertyValue; + private final CompositeMapperBuilder currentMapper; + private final String referencingEntityName; + private final EntityXmlMappingData xmlMappingData; + private final PropertyAuditingData propertyAuditingData; - private final AuditMetadataGenerator mainGenerator; - private final String propertyName; - private final Collection propertyValue; - private final CompositeMapperBuilder currentMapper; - private final String referencingEntityName; - private final EntityXmlMappingData xmlMappingData; - private final PropertyAuditingData propertyAuditingData; - - private final EntityConfiguration referencingEntityConfiguration; - /** - * Null if this collection isn't a relation to another entity. - */ - private final String referencedEntityName; + private final EntityConfiguration referencingEntityConfiguration; + /** + * Null if this collection isn't a relation to another entity. + */ + private final String referencedEntityName; /** - * @param mainGenerator Main generator, giving access to configuration and the basic mapper. - * @param propertyValue Value of the collection, as mapped by Hibernate. - * @param currentMapper Mapper, to which the appropriate {@link PropertyMapper} will be added. - * @param referencingEntityName Name of the entity that owns this collection. - * @param xmlMappingData In case this collection requires a middle table, additional mapping documents will - * be created using this object. - * @param propertyAuditingData Property auditing (meta-)data. Among other things, holds the name of the - * property that references the collection in the referencing entity, the user data for middle (join) - * table and the value of the @MapKey annotation, if there was one. - */ - public CollectionMetadataGenerator(AuditMetadataGenerator mainGenerator, - Collection propertyValue, CompositeMapperBuilder currentMapper, - String referencingEntityName, EntityXmlMappingData xmlMappingData, - PropertyAuditingData propertyAuditingData) { - this.mainGenerator = mainGenerator; - this.propertyValue = propertyValue; - this.currentMapper = currentMapper; - this.referencingEntityName = referencingEntityName; - this.xmlMappingData = xmlMappingData; - this.propertyAuditingData = propertyAuditingData; + * @param mainGenerator Main generator, giving access to configuration and the basic mapper. + * @param propertyValue Value of the collection, as mapped by Hibernate. + * @param currentMapper Mapper, to which the appropriate {@link PropertyMapper} will be added. + * @param referencingEntityName Name of the entity that owns this collection. + * @param xmlMappingData In case this collection requires a middle table, additional mapping documents will + * be created using this object. + * @param propertyAuditingData Property auditing (meta-)data. Among other things, holds the name of the + * property that references the collection in the referencing entity, the user data for middle (join) + * table and the value of the @MapKey annotation, if there was one. + */ + public CollectionMetadataGenerator( + AuditMetadataGenerator mainGenerator, + Collection propertyValue, CompositeMapperBuilder currentMapper, + String referencingEntityName, EntityXmlMappingData xmlMappingData, + PropertyAuditingData propertyAuditingData) { + this.mainGenerator = mainGenerator; + this.propertyValue = propertyValue; + this.currentMapper = currentMapper; + this.referencingEntityName = referencingEntityName; + this.xmlMappingData = xmlMappingData; + this.propertyAuditingData = propertyAuditingData; - this.propertyName = propertyAuditingData.getName(); + this.propertyName = propertyAuditingData.getName(); - referencingEntityConfiguration = mainGenerator.getEntitiesConfigurations().get(referencingEntityName); - if (referencingEntityConfiguration == null) { - throw new MappingException("Unable to read auditing configuration for " + referencingEntityName + "!"); - } + referencingEntityConfiguration = mainGenerator.getEntitiesConfigurations().get( referencingEntityName ); + if ( referencingEntityConfiguration == null ) { + throw new MappingException( "Unable to read auditing configuration for " + referencingEntityName + "!" ); + } - referencedEntityName = MappingTools.getReferencedEntityName(propertyValue.getElement()); - } + referencedEntityName = MappingTools.getReferencedEntityName( propertyValue.getElement() ); + } - void addCollection() { - Type type = propertyValue.getType(); - Value value = propertyValue.getElement(); + void addCollection() { + final Type type = propertyValue.getType(); + final Value value = propertyValue.getElement(); - boolean oneToManyAttachedType = type instanceof BagType || type instanceof SetType || type instanceof MapType || type instanceof ListType; - boolean inverseOneToMany = (value instanceof OneToMany) && (propertyValue.isInverse()); - boolean owningManyToOneWithJoinTableBidirectional = (value instanceof ManyToOne) && (propertyAuditingData.getRelationMappedBy() != null); - boolean fakeOneToManyBidirectional = (value instanceof OneToMany) && (propertyAuditingData.getAuditMappedBy() != null); + final boolean oneToManyAttachedType = type instanceof BagType || type instanceof SetType || type instanceof MapType || type instanceof ListType; + final boolean inverseOneToMany = (value instanceof OneToMany) && (propertyValue.isInverse()); + final boolean owningManyToOneWithJoinTableBidirectional = (value instanceof ManyToOne) && (propertyAuditingData.getRelationMappedBy() != null); + final boolean fakeOneToManyBidirectional = (value instanceof OneToMany) && (propertyAuditingData.getAuditMappedBy() != null); - if (oneToManyAttachedType && (inverseOneToMany || fakeOneToManyBidirectional || owningManyToOneWithJoinTableBidirectional)) { - // A one-to-many relation mapped using @ManyToOne and @OneToMany(mappedBy="...") - addOneToManyAttached(fakeOneToManyBidirectional); - } else { - // All other kinds of relations require a middle (join) table. - addWithMiddleTable(); - } - } + if ( oneToManyAttachedType && (inverseOneToMany || fakeOneToManyBidirectional || owningManyToOneWithJoinTableBidirectional) ) { + // A one-to-many relation mapped using @ManyToOne and @OneToMany(mappedBy="...") + addOneToManyAttached( fakeOneToManyBidirectional ); + } + else { + // All other kinds of relations require a middle (join) table. + addWithMiddleTable(); + } + } - private MiddleIdData createMiddleIdData(IdMappingData idMappingData, String prefix, String entityName) { - return new MiddleIdData(mainGenerator.getVerEntCfg(), idMappingData, prefix, entityName, - mainGenerator.getEntitiesConfigurations().containsKey(entityName)); - } + private MiddleIdData createMiddleIdData(IdMappingData idMappingData, String prefix, String entityName) { + return new MiddleIdData( + mainGenerator.getVerEntCfg(), idMappingData, prefix, entityName, + mainGenerator.getEntitiesConfigurations().containsKey( entityName ) + ); + } - @SuppressWarnings({"unchecked"}) - private void addOneToManyAttached(boolean fakeOneToManyBidirectional) { - LOG.debugf("Adding audit mapping for property %s.%s: one-to-many collection, using a join column on the referenced entity", - referencingEntityName, - propertyName); + @SuppressWarnings({"unchecked"}) + private void addOneToManyAttached(boolean fakeOneToManyBidirectional) { + LOG.debugf( + "Adding audit mapping for property %s.%s: one-to-many collection, using a join column on the referenced entity", + referencingEntityName, + propertyName + ); - String mappedBy = getMappedBy(propertyValue); + final String mappedBy = getMappedBy( propertyValue ); - IdMappingData referencedIdMapping = mainGenerator.getReferencedIdMappingData(referencingEntityName, - referencedEntityName, propertyAuditingData, false); - IdMappingData referencingIdMapping = referencingEntityConfiguration.getIdMappingData(); + final IdMappingData referencedIdMapping = mainGenerator.getReferencedIdMappingData( + referencingEntityName, + referencedEntityName, + propertyAuditingData, + false + ); + final IdMappingData referencingIdMapping = referencingEntityConfiguration.getIdMappingData(); - // Generating the id mappers data for the referencing side of the relation. - MiddleIdData referencingIdData = createMiddleIdData(referencingIdMapping, - mappedBy + "_", referencingEntityName); + // Generating the id mappers data for the referencing side of the relation. + final MiddleIdData referencingIdData = createMiddleIdData( + referencingIdMapping, + mappedBy + "_", + referencingEntityName + ); - // And for the referenced side. The prefixed mapper won't be used (as this collection isn't persisted - // in a join table, so the prefix value is arbitrary). - MiddleIdData referencedIdData = createMiddleIdData(referencedIdMapping, - null, referencedEntityName); + // And for the referenced side. The prefixed mapper won't be used (as this collection isn't persisted + // in a join table, so the prefix value is arbitrary). + final MiddleIdData referencedIdData = createMiddleIdData( + referencedIdMapping, + null, referencedEntityName + ); - // Generating the element mapping. - MiddleComponentData elementComponentData = new MiddleComponentData( - new MiddleRelatedComponentMapper(referencedIdData), 0); + // Generating the element mapping. + final MiddleComponentData elementComponentData = new MiddleComponentData( + new MiddleRelatedComponentMapper( referencedIdData ), 0 + ); - // Generating the index mapping, if an index exists. It can only exists in case a javax.persistence.MapKey - // annotation is present on the entity. So the middleEntityXml will be not be used. The queryGeneratorBuilder - // will only be checked for nullnes. - MiddleComponentData indexComponentData = addIndex(null, null); + // Generating the index mapping, if an index exists. It can only exists in case a javax.persistence.MapKey + // annotation is present on the entity. So the middleEntityXml will be not be used. The queryGeneratorBuilder + // will only be checked for nullnes. + MiddleComponentData indexComponentData = addIndex( null, null ); - // Generating the query generator - it should read directly from the related entity. - RelationQueryGenerator queryGenerator = new OneAuditEntityQueryGenerator(mainGenerator.getGlobalCfg(), - mainGenerator.getVerEntCfg(), mainGenerator.getAuditStrategy(), - referencingIdData, referencedEntityName, referencedIdData, isEmbeddableElementType()); + // Generating the query generator - it should read directly from the related entity. + final RelationQueryGenerator queryGenerator = new OneAuditEntityQueryGenerator( + mainGenerator.getGlobalCfg(), + mainGenerator.getVerEntCfg(), + mainGenerator.getAuditStrategy(), + referencingIdData, + referencedEntityName, + referencedIdData, + isEmbeddableElementType() + ); - // Creating common mapper data. - CommonCollectionMapperData commonCollectionMapperData = new CommonCollectionMapperData( - mainGenerator.getVerEntCfg(), referencedEntityName, - propertyAuditingData.getPropertyData(), - referencingIdData, queryGenerator); + // Creating common mapper data. + final CommonCollectionMapperData commonCollectionMapperData = new CommonCollectionMapperData( + mainGenerator.getVerEntCfg(), referencedEntityName, + propertyAuditingData.getPropertyData(), + referencingIdData, queryGenerator + ); - PropertyMapper fakeBidirectionalRelationMapper; - PropertyMapper fakeBidirectionalRelationIndexMapper; - if (fakeOneToManyBidirectional) { - // In case of a fake many-to-one bidirectional relation, we have to generate a mapper which maps - // the mapped-by property name to the id of the related entity (which is the owner of the collection). - String auditMappedBy = propertyAuditingData.getAuditMappedBy(); + PropertyMapper fakeBidirectionalRelationMapper; + PropertyMapper fakeBidirectionalRelationIndexMapper; + if ( fakeOneToManyBidirectional ) { + // In case of a fake many-to-one bidirectional relation, we have to generate a mapper which maps + // the mapped-by property name to the id of the related entity (which is the owner of the collection). + final String auditMappedBy = propertyAuditingData.getAuditMappedBy(); - // Creating a prefixed relation mapper. - IdMapper relMapper = referencingIdMapping.getIdMapper().prefixMappedProperties( - MappingTools.createToOneRelationPrefix(auditMappedBy)); + // Creating a prefixed relation mapper. + final IdMapper relMapper = referencingIdMapping.getIdMapper().prefixMappedProperties( + MappingTools.createToOneRelationPrefix( auditMappedBy ) + ); - fakeBidirectionalRelationMapper = new ToOneIdMapper( - relMapper, - // The mapper will only be used to map from entity to map, so no need to provide other details - // when constructing the PropertyData. - new PropertyData(auditMappedBy, null, null, null), - referencingEntityName, false); + fakeBidirectionalRelationMapper = new ToOneIdMapper( + relMapper, + // The mapper will only be used to map from entity to map, so no need to provide other details + // when constructing the PropertyData. + new PropertyData( auditMappedBy, null, null, null ), + referencingEntityName, false + ); - // Checking if there's an index defined. If so, adding a mapper for it. - if (propertyAuditingData.getPositionMappedBy() != null) { - String positionMappedBy = propertyAuditingData.getPositionMappedBy(); - fakeBidirectionalRelationIndexMapper = new SinglePropertyMapper(new PropertyData(positionMappedBy, null, null, null)); + // Checking if there's an index defined. If so, adding a mapper for it. + if ( propertyAuditingData.getPositionMappedBy() != null ) { + final String positionMappedBy = propertyAuditingData.getPositionMappedBy(); + fakeBidirectionalRelationIndexMapper = new SinglePropertyMapper( + new PropertyData( + positionMappedBy, + null, + null, + null + ) + ); - // Also, overwriting the index component data to properly read the index. - indexComponentData = new MiddleComponentData(new MiddleStraightComponentMapper(positionMappedBy), 0); - } else { - fakeBidirectionalRelationIndexMapper = null; - } - } else { - fakeBidirectionalRelationMapper = null; - fakeBidirectionalRelationIndexMapper = null; - } + // Also, overwriting the index component data to properly read the index. + indexComponentData = new MiddleComponentData( + new MiddleStraightComponentMapper( positionMappedBy ), + 0 + ); + } + else { + fakeBidirectionalRelationIndexMapper = null; + } + } + else { + fakeBidirectionalRelationMapper = null; + fakeBidirectionalRelationIndexMapper = null; + } - // Checking the type of the collection and adding an appropriate mapper. - addMapper(commonCollectionMapperData, elementComponentData, indexComponentData); + // Checking the type of the collection and adding an appropriate mapper. + addMapper( commonCollectionMapperData, elementComponentData, indexComponentData ); - // Storing information about this relation. - referencingEntityConfiguration.addToManyNotOwningRelation(propertyName, mappedBy, - referencedEntityName, referencingIdData.getPrefixedMapper(), fakeBidirectionalRelationMapper, - fakeBidirectionalRelationIndexMapper); - } + // Storing information about this relation. + referencingEntityConfiguration.addToManyNotOwningRelation( + propertyName, + mappedBy, + referencedEntityName, + referencingIdData.getPrefixedMapper(), + fakeBidirectionalRelationMapper, + fakeBidirectionalRelationIndexMapper + ); + } - /** - * Adds mapping of the id of a related entity to the given xml mapping, prefixing the id with the given prefix. - * @param xmlMapping Mapping, to which to add the xml. - * @param prefix Prefix for the names of properties which will be prepended to properties that form the id. - * @param columnNameIterator Iterator over the column names that will be used for properties that form the id. - * @param relatedIdMapping Id mapping data of the related entity. - */ - @SuppressWarnings({"unchecked"}) - private void addRelatedToXmlMapping(Element xmlMapping, String prefix, - MetadataTools.ColumnNameIterator columnNameIterator, - IdMappingData relatedIdMapping) { - Element properties = (Element) relatedIdMapping.getXmlRelationMapping().clone(); - MetadataTools.prefixNamesInPropertyElement(properties, prefix, columnNameIterator, true, true); - for (Element idProperty : (java.util.List) properties.elements()) { - xmlMapping.add((Element) idProperty.clone()); - } - } + /** + * Adds mapping of the id of a related entity to the given xml mapping, prefixing the id with the given prefix. + * + * @param xmlMapping Mapping, to which to add the xml. + * @param prefix Prefix for the names of properties which will be prepended to properties that form the id. + * @param columnNameIterator Iterator over the column names that will be used for properties that form the id. + * @param relatedIdMapping Id mapping data of the related entity. + */ + @SuppressWarnings({"unchecked"}) + private void addRelatedToXmlMapping( + Element xmlMapping, String prefix, + MetadataTools.ColumnNameIterator columnNameIterator, + IdMappingData relatedIdMapping) { + final Element properties = (Element) relatedIdMapping.getXmlRelationMapping().clone(); + MetadataTools.prefixNamesInPropertyElement( properties, prefix, columnNameIterator, true, true ); + for ( Element idProperty : (java.util.List) properties.elements() ) { + xmlMapping.add( (Element) idProperty.clone() ); + } + } - private String getMiddleTableName(Collection value, String entityName) { - // We check how Hibernate maps the collection. - if (value.getElement() instanceof OneToMany && !value.isInverse()) { - // This must be a @JoinColumn+@OneToMany mapping. Generating the table name, as Hibernate doesn't use a - // middle table for mapping this relation. - return StringTools.getLastComponent(entityName) + "_" + StringTools.getLastComponent(MappingTools.getReferencedEntityName(value.getElement())); - } - // Hibernate uses a middle table for mapping this relation, so we get it's name directly. - return value.getCollectionTable().getName(); - } + private String getMiddleTableName(Collection value, String entityName) { + // We check how Hibernate maps the collection. + if ( value.getElement() instanceof OneToMany && !value.isInverse() ) { + // This must be a @JoinColumn+@OneToMany mapping. Generating the table name, as Hibernate doesn't use a + // middle table for mapping this relation. + return StringTools.getLastComponent( entityName ) + "_" + StringTools.getLastComponent( + MappingTools.getReferencedEntityName( + value.getElement() + ) + ); + } + // Hibernate uses a middle table for mapping this relation, so we get it's name directly. + return value.getCollectionTable().getName(); + } - @SuppressWarnings({"unchecked"}) - private void addWithMiddleTable() { + @SuppressWarnings({"unchecked"}) + private void addWithMiddleTable() { - LOG.debugf("Adding audit mapping for property %s.%s: collection with a join table", referencingEntityName, propertyName); + LOG.debugf( + "Adding audit mapping for property %s.%s: collection with a join table", + referencingEntityName, + propertyName + ); - // Generating the name of the middle table - String auditMiddleTableName; - String auditMiddleEntityName; - if (!StringTools.isEmpty(propertyAuditingData.getJoinTable().name())) { - auditMiddleTableName = propertyAuditingData.getJoinTable().name(); - auditMiddleEntityName = propertyAuditingData.getJoinTable().name(); - } else { - String middleTableName = getMiddleTableName(propertyValue, referencingEntityName); - auditMiddleTableName = mainGenerator.getVerEntCfg().getAuditTableName(null, middleTableName); - auditMiddleEntityName = mainGenerator.getVerEntCfg().getAuditEntityName(middleTableName); - } + // Generating the name of the middle table + String auditMiddleTableName; + String auditMiddleEntityName; + if ( !StringTools.isEmpty( propertyAuditingData.getJoinTable().name() ) ) { + auditMiddleTableName = propertyAuditingData.getJoinTable().name(); + auditMiddleEntityName = propertyAuditingData.getJoinTable().name(); + } + else { + final String middleTableName = getMiddleTableName( propertyValue, referencingEntityName ); + auditMiddleTableName = mainGenerator.getVerEntCfg().getAuditTableName( null, middleTableName ); + auditMiddleEntityName = mainGenerator.getVerEntCfg().getAuditEntityName( middleTableName ); + } - LOG.debugf("Using join table name: %s", auditMiddleTableName); + LOG.debugf( "Using join table name: %s", auditMiddleTableName ); - // Generating the XML mapping for the middle entity, only if the relation isn't inverse. - // If the relation is inverse, will be later checked by comparing middleEntityXml with null. - Element middleEntityXml; - if (!propertyValue.isInverse()) { - // Generating a unique middle entity name - auditMiddleEntityName = mainGenerator.getAuditEntityNameRegister().createUnique(auditMiddleEntityName); + // Generating the XML mapping for the middle entity, only if the relation isn't inverse. + // If the relation is inverse, will be later checked by comparing middleEntityXml with null. + Element middleEntityXml; + if ( !propertyValue.isInverse() ) { + // Generating a unique middle entity name + auditMiddleEntityName = mainGenerator.getAuditEntityNameRegister().createUnique( auditMiddleEntityName ); - // Registering the generated name - mainGenerator.getAuditEntityNameRegister().register(auditMiddleEntityName); + // Registering the generated name + mainGenerator.getAuditEntityNameRegister().register( auditMiddleEntityName ); - middleEntityXml = createMiddleEntityXml(auditMiddleTableName, auditMiddleEntityName, propertyValue.getWhere()); - } else { - middleEntityXml = null; - } + middleEntityXml = createMiddleEntityXml( + auditMiddleTableName, + auditMiddleEntityName, + propertyValue.getWhere() + ); + } + else { + middleEntityXml = null; + } - // ****** - // Generating the mapping for the referencing entity (it must be an entity). - // ****** - // Getting the id-mapping data of the referencing entity (the entity that "owns" this collection). - IdMappingData referencingIdMapping = referencingEntityConfiguration.getIdMappingData(); + // ****** + // Generating the mapping for the referencing entity (it must be an entity). + // ****** + // Getting the id-mapping data of the referencing entity (the entity that "owns" this collection). + final IdMappingData referencingIdMapping = referencingEntityConfiguration.getIdMappingData(); - // Only valid for an inverse relation; null otherwise. - String mappedBy; + // Only valid for an inverse relation; null otherwise. + String mappedBy; - // The referencing prefix is always for a related entity. So it has always the "_" at the end added. - String referencingPrefixRelated; - String referencedPrefix; + // The referencing prefix is always for a related entity. So it has always the "_" at the end added. + String referencingPrefixRelated; + String referencedPrefix; - if (propertyValue.isInverse()) { - // If the relation is inverse, then referencedEntityName is not null. - mappedBy = getMappedBy(propertyValue.getCollectionTable(), mainGenerator.getCfg().getClassMapping(referencedEntityName)); + if ( propertyValue.isInverse() ) { + // If the relation is inverse, then referencedEntityName is not null. + mappedBy = getMappedBy( + propertyValue.getCollectionTable(), + mainGenerator.getCfg().getClassMapping( referencedEntityName ) + ); - referencingPrefixRelated = mappedBy + "_"; - referencedPrefix = StringTools.getLastComponent(referencedEntityName); - } else { - mappedBy = null; + referencingPrefixRelated = mappedBy + "_"; + referencedPrefix = StringTools.getLastComponent( referencedEntityName ); + } + else { + mappedBy = null; - referencingPrefixRelated = StringTools.getLastComponent(referencingEntityName) + "_"; - referencedPrefix = referencedEntityName == null ? "element" : propertyName; - } + referencingPrefixRelated = StringTools.getLastComponent( referencingEntityName ) + "_"; + referencedPrefix = referencedEntityName == null ? "element" : propertyName; + } - // Storing the id data of the referencing entity: original mapper, prefixed mapper and entity name. - MiddleIdData referencingIdData = createMiddleIdData(referencingIdMapping, - referencingPrefixRelated, referencingEntityName); + // Storing the id data of the referencing entity: original mapper, prefixed mapper and entity name. + final MiddleIdData referencingIdData = createMiddleIdData( + referencingIdMapping, + referencingPrefixRelated, + referencingEntityName + ); - // Creating a query generator builder, to which additional id data will be added, in case this collection - // references some entities (either from the element or index). At the end, this will be used to build - // a query generator to read the raw data collection from the middle table. - QueryGeneratorBuilder queryGeneratorBuilder = new QueryGeneratorBuilder(mainGenerator.getGlobalCfg(), - mainGenerator.getVerEntCfg(), mainGenerator.getAuditStrategy(), referencingIdData, - auditMiddleEntityName, isEmbeddableElementType()); + // Creating a query generator builder, to which additional id data will be added, in case this collection + // references some entities (either from the element or index). At the end, this will be used to build + // a query generator to read the raw data collection from the middle table. + final QueryGeneratorBuilder queryGeneratorBuilder = new QueryGeneratorBuilder( + mainGenerator.getGlobalCfg(), + mainGenerator.getVerEntCfg(), + mainGenerator.getAuditStrategy(), + referencingIdData, + auditMiddleEntityName, + isEmbeddableElementType() + ); - // Adding the XML mapping for the referencing entity, if the relation isn't inverse. - if (middleEntityXml != null) { - // Adding related-entity (in this case: the referencing's entity id) id mapping to the xml. - addRelatedToXmlMapping(middleEntityXml, referencingPrefixRelated, - MetadataTools.getColumnNameIterator(propertyValue.getKey().getColumnIterator()), - referencingIdMapping); - } + // Adding the XML mapping for the referencing entity, if the relation isn't inverse. + if ( middleEntityXml != null ) { + // Adding related-entity (in this case: the referencing's entity id) id mapping to the xml. + addRelatedToXmlMapping( + middleEntityXml, referencingPrefixRelated, + MetadataTools.getColumnNameIterator( propertyValue.getKey().getColumnIterator() ), + referencingIdMapping + ); + } - // ****** - // Generating the element mapping. - // ****** - MiddleComponentData elementComponentData = addValueToMiddleTable(propertyValue.getElement(), middleEntityXml, - queryGeneratorBuilder, referencedPrefix, propertyAuditingData.getJoinTable().inverseJoinColumns()); + // ****** + // Generating the element mapping. + // ****** + final MiddleComponentData elementComponentData = addValueToMiddleTable( + propertyValue.getElement(), + middleEntityXml, + queryGeneratorBuilder, + referencedPrefix, + propertyAuditingData.getJoinTable().inverseJoinColumns() + ); - // ****** - // Generating the index mapping, if an index exists. - // ****** - MiddleComponentData indexComponentData = addIndex(middleEntityXml, queryGeneratorBuilder); + // ****** + // Generating the index mapping, if an index exists. + // ****** + final MiddleComponentData indexComponentData = addIndex( middleEntityXml, queryGeneratorBuilder ); - // ****** - // Generating the property mapper. - // ****** - // Building the query generator. - RelationQueryGenerator queryGenerator = queryGeneratorBuilder.build(elementComponentData, indexComponentData); + // ****** + // Generating the property mapper. + // ****** + // Building the query generator. + final RelationQueryGenerator queryGenerator = queryGeneratorBuilder.build( elementComponentData, indexComponentData ); - // Creating common data - CommonCollectionMapperData commonCollectionMapperData = new CommonCollectionMapperData( - mainGenerator.getVerEntCfg(), auditMiddleEntityName, - propertyAuditingData.getPropertyData(), - referencingIdData, queryGenerator); + // Creating common data + final CommonCollectionMapperData commonCollectionMapperData = new CommonCollectionMapperData( + mainGenerator.getVerEntCfg(), + auditMiddleEntityName, + propertyAuditingData.getPropertyData(), + referencingIdData, + queryGenerator + ); - // Checking the type of the collection and adding an appropriate mapper. - addMapper(commonCollectionMapperData, elementComponentData, indexComponentData); + // Checking the type of the collection and adding an appropriate mapper. + addMapper( commonCollectionMapperData, elementComponentData, indexComponentData ); - // ****** - // Storing information about this relation. - // ****** - storeMiddleEntityRelationInformation(mappedBy); - } + // ****** + // Storing information about this relation. + // ****** + storeMiddleEntityRelationInformation( mappedBy ); + } - private MiddleComponentData addIndex(Element middleEntityXml, QueryGeneratorBuilder queryGeneratorBuilder) { - if (propertyValue instanceof IndexedCollection) { - IndexedCollection indexedValue = (IndexedCollection) propertyValue; - String mapKey = propertyAuditingData.getMapKey(); - if (mapKey == null) { - // This entity doesn't specify a javax.persistence.MapKey. Mapping it to the middle entity. - return addValueToMiddleTable(indexedValue.getIndex(), middleEntityXml, - queryGeneratorBuilder, "mapkey", null); - } else { - IdMappingData referencedIdMapping = mainGenerator.getEntitiesConfigurations() - .get(referencedEntityName).getIdMappingData(); - int currentIndex = queryGeneratorBuilder == null ? 0 : queryGeneratorBuilder.getCurrentIndex(); - if ("".equals(mapKey)) { - // The key of the map is the id of the entity. - return new MiddleComponentData(new MiddleMapKeyIdComponentMapper(mainGenerator.getVerEntCfg(), - referencedIdMapping.getIdMapper()), currentIndex); - } else { - // The key of the map is a property of the entity. - return new MiddleComponentData(new MiddleMapKeyPropertyComponentMapper(mapKey, - propertyAuditingData.getAccessType()), currentIndex); - } - } - } else { - // No index - creating a dummy mapper. - return new MiddleComponentData(new MiddleDummyComponentMapper(), 0); - } - } + private MiddleComponentData addIndex(Element middleEntityXml, QueryGeneratorBuilder queryGeneratorBuilder) { + if ( propertyValue instanceof IndexedCollection ) { + final IndexedCollection indexedValue = (IndexedCollection) propertyValue; + final String mapKey = propertyAuditingData.getMapKey(); + if ( mapKey == null ) { + // This entity doesn't specify a javax.persistence.MapKey. Mapping it to the middle entity. + return addValueToMiddleTable( + indexedValue.getIndex(), + middleEntityXml, + queryGeneratorBuilder, + "mapkey", + null + ); + } + else { + final IdMappingData referencedIdMapping = mainGenerator.getEntitiesConfigurations() + .get( referencedEntityName ).getIdMappingData(); + final int currentIndex = queryGeneratorBuilder == null ? 0 : queryGeneratorBuilder.getCurrentIndex(); + if ( "".equals( mapKey ) ) { + // The key of the map is the id of the entity. + return new MiddleComponentData( + new MiddleMapKeyIdComponentMapper( + mainGenerator.getVerEntCfg(), + referencedIdMapping.getIdMapper() + ), + currentIndex + ); + } + else { + // The key of the map is a property of the entity. + return new MiddleComponentData( + new MiddleMapKeyPropertyComponentMapper( + mapKey, + propertyAuditingData.getAccessType() + ), + currentIndex + ); + } + } + } + else { + // No index - creating a dummy mapper. + return new MiddleComponentData( new MiddleDummyComponentMapper(), 0 ); + } + } - /** - * - * @param value Value, which should be mapped to the middle-table, either as a relation to another entity, - * or as a simple value. - * @param xmlMapping If not null, xml mapping for this value is added to this element. - * @param queryGeneratorBuilder In case value is a relation to another entity, information about it - * should be added to the given. - * @param prefix Prefix for proeprty names of related entities identifiers. - * @param joinColumns Names of columns to use in the xml mapping, if this array isn't null and has any elements. - * @return Data for mapping this component. - */ - @SuppressWarnings({"unchecked"}) - private MiddleComponentData addValueToMiddleTable(Value value, Element xmlMapping, - QueryGeneratorBuilder queryGeneratorBuilder, - String prefix, JoinColumn[] joinColumns) { - Type type = value.getType(); - if (type instanceof ManyToOneType) { - String prefixRelated = prefix + "_"; + /** + * @param value Value, which should be mapped to the middle-table, either as a relation to another entity, + * or as a simple value. + * @param xmlMapping If not null, xml mapping for this value is added to this element. + * @param queryGeneratorBuilder In case value is a relation to another entity, information about it + * should be added to the given. + * @param prefix Prefix for proeprty names of related entities identifiers. + * @param joinColumns Names of columns to use in the xml mapping, if this array isn't null and has any elements. + * + * @return Data for mapping this component. + */ + @SuppressWarnings({"unchecked"}) + private MiddleComponentData addValueToMiddleTable( + Value value, + Element xmlMapping, + QueryGeneratorBuilder queryGeneratorBuilder, + String prefix, + JoinColumn[] joinColumns) { + final Type type = value.getType(); + if ( type instanceof ManyToOneType ) { + final String prefixRelated = prefix + "_"; - String referencedEntityName = MappingTools.getReferencedEntityName(value); + final String referencedEntityName = MappingTools.getReferencedEntityName( value ); - IdMappingData referencedIdMapping = mainGenerator.getReferencedIdMappingData(referencingEntityName, - referencedEntityName, propertyAuditingData, true); + final IdMappingData referencedIdMapping = mainGenerator.getReferencedIdMappingData( + referencingEntityName, + referencedEntityName, + propertyAuditingData, + true + ); - // Adding related-entity (in this case: the referenced entities id) id mapping to the xml only if the - // relation isn't inverse (so when xmlMapping is not null). - if (xmlMapping != null) { - addRelatedToXmlMapping(xmlMapping, prefixRelated, - joinColumns != null && joinColumns.length > 0 - ? MetadataTools.getColumnNameIterator(joinColumns) - : MetadataTools.getColumnNameIterator(value.getColumnIterator()), - referencedIdMapping); - } + // Adding related-entity (in this case: the referenced entities id) id mapping to the xml only if the + // relation isn't inverse (so when xmlMapping is not null). + if ( xmlMapping != null ) { + addRelatedToXmlMapping( + xmlMapping, prefixRelated, + joinColumns != null && joinColumns.length > 0 + ? MetadataTools.getColumnNameIterator( joinColumns ) + : MetadataTools.getColumnNameIterator( value.getColumnIterator() ), + referencedIdMapping + ); + } - // Storing the id data of the referenced entity: original mapper, prefixed mapper and entity name. - MiddleIdData referencedIdData = createMiddleIdData(referencedIdMapping, - prefixRelated, referencedEntityName); - // And adding it to the generator builder. - queryGeneratorBuilder.addRelation(referencedIdData); + // Storing the id data of the referenced entity: original mapper, prefixed mapper and entity name. + final MiddleIdData referencedIdData = createMiddleIdData( + referencedIdMapping, + prefixRelated, + referencedEntityName + ); + // And adding it to the generator builder. + queryGeneratorBuilder.addRelation( referencedIdData ); - return new MiddleComponentData(new MiddleRelatedComponentMapper(referencedIdData), - queryGeneratorBuilder.getCurrentIndex()); - } else if ( type instanceof ComponentType ) { + return new MiddleComponentData( + new MiddleRelatedComponentMapper( referencedIdData ), + queryGeneratorBuilder.getCurrentIndex() + ); + } + else if ( type instanceof ComponentType ) { // Collection of embeddable elements. final Component component = (Component) value; - final Class componentClass = ReflectionTools.loadClass( component.getComponentClassName(), mainGenerator.getClassLoaderService() ); - final MiddleEmbeddableComponentMapper componentMapper = new MiddleEmbeddableComponentMapper( new MultiPropertyMapper(), componentClass ); + final Class componentClass = ReflectionTools.loadClass( + component.getComponentClassName(), + mainGenerator.getClassLoaderService() + ); + final MiddleEmbeddableComponentMapper componentMapper = new MiddleEmbeddableComponentMapper( + new MultiPropertyMapper(), + componentClass + ); final Element parentXmlMapping = xmlMapping.getParent(); final ComponentAuditingData auditData = new ComponentAuditingData(); @@ -489,27 +612,40 @@ public final class CollectionMetadataGenerator { // Emulating first pass. for ( String auditedPropertyName : auditData.getPropertyNames() ) { - PropertyAuditingData nestedAuditingData = auditData.getPropertyAuditingData( auditedPropertyName ); + final PropertyAuditingData nestedAuditingData = auditData.getPropertyAuditingData( auditedPropertyName ); mainGenerator.addValue( - parentXmlMapping, component.getProperty( auditedPropertyName ).getValue(), componentMapper, - prefix, xmlMappingData, nestedAuditingData, true, true, true + parentXmlMapping, + component.getProperty( auditedPropertyName ).getValue(), + componentMapper, + prefix, xmlMappingData, + nestedAuditingData, + true, + true, + true ); } // Emulating second pass so that the relations can be mapped too. for ( String auditedPropertyName : auditData.getPropertyNames() ) { - PropertyAuditingData nestedAuditingData = auditData.getPropertyAuditingData( auditedPropertyName ); + final PropertyAuditingData nestedAuditingData = auditData.getPropertyAuditingData( auditedPropertyName ); mainGenerator.addValue( - parentXmlMapping, component.getProperty( auditedPropertyName ).getValue(), - componentMapper, referencingEntityName, xmlMappingData, nestedAuditingData, - true, false, true + parentXmlMapping, + component.getProperty( auditedPropertyName ).getValue(), + componentMapper, + referencingEntityName, + xmlMappingData, + nestedAuditingData, + true, + false, + true ); } // Add an additional column holding a number to make each entry unique within the set. // Embeddable properties may contain null values, so cannot be stored within composite primary key. if ( propertyValue.isSet() ) { - final String setOrdinalPropertyName = mainGenerator.getVerEntCfg().getEmbeddableSetOrdinalPropertyName(); + final String setOrdinalPropertyName = mainGenerator.getVerEntCfg() + .getEmbeddableSetOrdinalPropertyName(); final Element ordinalProperty = MetadataTools.addProperty( xmlMapping, setOrdinalPropertyName, "integer", true, true ); @@ -519,96 +655,185 @@ public final class CollectionMetadataGenerator { } return new MiddleComponentData( componentMapper, 0 ); - } else { - // Last but one parameter: collection components are always insertable - boolean mapped = mainGenerator.getBasicMetadataGenerator().addBasic(xmlMapping, - new PropertyAuditingData(prefix, "field", ModificationStore.FULL, RelationTargetAuditMode.AUDITED, null, null, false), - value, null, true, true); + } + else { + // Last but one parameter: collection components are always insertable + final boolean mapped = mainGenerator.getBasicMetadataGenerator().addBasic( + xmlMapping, + new PropertyAuditingData( + prefix, + "field", + ModificationStore.FULL, + RelationTargetAuditMode.AUDITED, + null, + null, + false + ), + value, + null, + true, + true + ); - if (mapped) { - // Simple values are always stored in the first item of the array returned by the query generator. - return new MiddleComponentData(new MiddleSimpleComponentMapper(mainGenerator.getVerEntCfg(), prefix), 0); - } else { - mainGenerator.throwUnsupportedTypeException(type, referencingEntityName, propertyName); - // Impossible to get here. - throw new AssertionError(); - } - } - } + if ( mapped ) { + // Simple values are always stored in the first item of the array returned by the query generator. + return new MiddleComponentData( + new MiddleSimpleComponentMapper( mainGenerator.getVerEntCfg(), prefix ), + 0 + ); + } + else { + mainGenerator.throwUnsupportedTypeException( type, referencingEntityName, propertyName ); + // Impossible to get here. + throw new AssertionError(); + } + } + } - private void addMapper(CommonCollectionMapperData commonCollectionMapperData, MiddleComponentData elementComponentData, - MiddleComponentData indexComponentData) { - Type type = propertyValue.getType(); - boolean embeddableElementType = isEmbeddableElementType(); - if (type instanceof SortedSetType) { - currentMapper.addComposite( propertyAuditingData.getPropertyData(), new SortedSetCollectionMapper( - commonCollectionMapperData, TreeSet.class, SortedSetProxy.class, elementComponentData, - propertyValue.getComparator(), embeddableElementType, embeddableElementType ) ); - } else if (type instanceof SetType) { - currentMapper.addComposite( propertyAuditingData.getPropertyData(), new BasicCollectionMapper( - commonCollectionMapperData, HashSet.class, SetProxy.class, elementComponentData, - embeddableElementType, embeddableElementType ) ); - } else if (type instanceof SortedMapType) { - // Indexed collection, so indexComponentData is not null. - currentMapper.addComposite(propertyAuditingData.getPropertyData(), - new SortedMapCollectionMapper(commonCollectionMapperData, - TreeMap.class, SortedMapProxy.class, elementComponentData, indexComponentData, propertyValue.getComparator(), - embeddableElementType)); - } else if (type instanceof MapType) { - // Indexed collection, so indexComponentData is not null. - currentMapper.addComposite(propertyAuditingData.getPropertyData(), - new MapCollectionMapper(commonCollectionMapperData, - HashMap.class, MapProxy.class, elementComponentData, indexComponentData, embeddableElementType)); - } else if (type instanceof BagType) { - currentMapper.addComposite( propertyAuditingData.getPropertyData(), new BasicCollectionMapper( - commonCollectionMapperData, ArrayList.class, ListProxy.class, elementComponentData, - embeddableElementType, embeddableElementType ) ); - } else if (type instanceof ListType) { - // Indexed collection, so indexComponentData is not null. - currentMapper.addComposite(propertyAuditingData.getPropertyData(), - new ListCollectionMapper(commonCollectionMapperData, - elementComponentData, indexComponentData, embeddableElementType)); - } else { - mainGenerator.throwUnsupportedTypeException(type, referencingEntityName, propertyName); - } - } + private void addMapper( + CommonCollectionMapperData commonCollectionMapperData, + MiddleComponentData elementComponentData, + MiddleComponentData indexComponentData) { + final Type type = propertyValue.getType(); + final boolean embeddableElementType = isEmbeddableElementType(); + if ( type instanceof SortedSetType ) { + currentMapper.addComposite( + propertyAuditingData.getPropertyData(), + new SortedSetCollectionMapper( + commonCollectionMapperData, + TreeSet.class, + SortedSetProxy.class, + elementComponentData, + propertyValue.getComparator(), + embeddableElementType, + embeddableElementType + ) + ); + } + else if ( type instanceof SetType ) { + currentMapper.addComposite( + propertyAuditingData.getPropertyData(), + new BasicCollectionMapper( + commonCollectionMapperData, + HashSet.class, + SetProxy.class, + elementComponentData, + embeddableElementType, + embeddableElementType + ) + ); + } + else if ( type instanceof SortedMapType ) { + // Indexed collection, so indexComponentData is not null. + currentMapper.addComposite( + propertyAuditingData.getPropertyData(), + new SortedMapCollectionMapper( + commonCollectionMapperData, + TreeMap.class, + SortedMapProxy.class, + elementComponentData, + indexComponentData, + propertyValue.getComparator(), + embeddableElementType + ) + ); + } + else if ( type instanceof MapType ) { + // Indexed collection, so indexComponentData is not null. + currentMapper.addComposite( + propertyAuditingData.getPropertyData(), + new MapCollectionMapper( + commonCollectionMapperData, + HashMap.class, + MapProxy.class, + elementComponentData, + indexComponentData, + embeddableElementType + ) + ); + } + else if ( type instanceof BagType ) { + currentMapper.addComposite( + propertyAuditingData.getPropertyData(), + new BasicCollectionMapper( + commonCollectionMapperData, + ArrayList.class, + ListProxy.class, + elementComponentData, + embeddableElementType, + embeddableElementType + ) + ); + } + else if ( type instanceof ListType ) { + // Indexed collection, so indexComponentData is not null. + currentMapper.addComposite( + propertyAuditingData.getPropertyData(), + new ListCollectionMapper( + commonCollectionMapperData, + elementComponentData, + indexComponentData, + embeddableElementType + ) + ); + } + else { + mainGenerator.throwUnsupportedTypeException( type, referencingEntityName, propertyName ); + } + } - private void storeMiddleEntityRelationInformation(String mappedBy) { - // Only if this is a relation (when there is a referenced entity). - if (referencedEntityName != null) { - if (propertyValue.isInverse()) { - referencingEntityConfiguration.addToManyMiddleNotOwningRelation(propertyName, mappedBy, referencedEntityName); - } else { - referencingEntityConfiguration.addToManyMiddleRelation(propertyName, referencedEntityName); - } - } - } + private void storeMiddleEntityRelationInformation(String mappedBy) { + // Only if this is a relation (when there is a referenced entity). + if ( referencedEntityName != null ) { + if ( propertyValue.isInverse() ) { + referencingEntityConfiguration.addToManyMiddleNotOwningRelation( + propertyName, + mappedBy, + referencedEntityName + ); + } + else { + referencingEntityConfiguration.addToManyMiddleRelation( propertyName, referencedEntityName ); + } + } + } - private Element createMiddleEntityXml(String auditMiddleTableName, String auditMiddleEntityName, String where) { - String schema = mainGenerator.getSchema(propertyAuditingData.getJoinTable().schema(), propertyValue.getCollectionTable()); - String catalog = mainGenerator.getCatalog(propertyAuditingData.getJoinTable().catalog(), propertyValue.getCollectionTable()); + private Element createMiddleEntityXml(String auditMiddleTableName, String auditMiddleEntityName, String where) { + final String schema = mainGenerator.getSchema( + propertyAuditingData.getJoinTable().schema(), + propertyValue.getCollectionTable() + ); + final String catalog = mainGenerator.getCatalog( + propertyAuditingData.getJoinTable().catalog(), + propertyValue.getCollectionTable() + ); - Element middleEntityXml = MetadataTools.createEntity(xmlMappingData.newAdditionalMapping(), - new AuditTableData(auditMiddleEntityName, auditMiddleTableName, schema, catalog), null, null); - Element middleEntityXmlId = middleEntityXml.addElement("composite-id"); + final Element middleEntityXml = MetadataTools.createEntity( + xmlMappingData.newAdditionalMapping(), + new AuditTableData( auditMiddleEntityName, auditMiddleTableName, schema, catalog ), null, null + ); + final Element middleEntityXmlId = middleEntityXml.addElement( "composite-id" ); - // If there is a where clause on the relation, adding it to the middle entity. - if (where != null) { - middleEntityXml.addAttribute("where", where); - } + // If there is a where clause on the relation, adding it to the middle entity. + if ( where != null ) { + middleEntityXml.addAttribute( "where", where ); + } - middleEntityXmlId.addAttribute("name", mainGenerator.getVerEntCfg().getOriginalIdPropName()); + middleEntityXmlId.addAttribute( "name", mainGenerator.getVerEntCfg().getOriginalIdPropName() ); - // Adding the revision number as a foreign key to the revision info entity to the composite id of the - // middle table. - mainGenerator.addRevisionInfoRelation(middleEntityXmlId); + // Adding the revision number as a foreign key to the revision info entity to the composite id of the + // middle table. + mainGenerator.addRevisionInfoRelation( middleEntityXmlId ); - // Adding the revision type property to the entity xml. - mainGenerator.addRevisionType(isEmbeddableElementType() ? middleEntityXmlId : middleEntityXml, middleEntityXml); + // Adding the revision type property to the entity xml. + mainGenerator.addRevisionType( + isEmbeddableElementType() ? middleEntityXmlId : middleEntityXml, + middleEntityXml + ); - // All other properties should also be part of the primary key of the middle entity. - return middleEntityXmlId; - } + // All other properties should also be part of the primary key of the middle entity. + return middleEntityXmlId; + } /** * Checks if the collection element is of {@link ComponentType} type. @@ -617,107 +842,118 @@ public final class CollectionMetadataGenerator { return propertyValue.getElement().getType() instanceof ComponentType; } - private String getMappedBy(Collection collectionValue) { - PersistentClass referencedClass = null; - if (collectionValue.getElement() instanceof OneToMany) { - OneToMany oneToManyValue = (OneToMany) collectionValue.getElement(); - referencedClass = oneToManyValue.getAssociatedClass(); - } else if (collectionValue.getElement() instanceof ManyToOne) { - // Case for bi-directional relation with @JoinTable on the owning @ManyToOne side. - ManyToOne manyToOneValue = (ManyToOne) collectionValue.getElement(); - referencedClass = manyToOneValue.getMappings().getClass(manyToOneValue.getReferencedEntityName()); - } + private String getMappedBy(Collection collectionValue) { + PersistentClass referencedClass = null; + if ( collectionValue.getElement() instanceof OneToMany ) { + final OneToMany oneToManyValue = (OneToMany) collectionValue.getElement(); + referencedClass = oneToManyValue.getAssociatedClass(); + } + else if ( collectionValue.getElement() instanceof ManyToOne ) { + // Case for bi-directional relation with @JoinTable on the owning @ManyToOne side. + final ManyToOne manyToOneValue = (ManyToOne) collectionValue.getElement(); + referencedClass = manyToOneValue.getMappings().getClass( manyToOneValue.getReferencedEntityName() ); + } - // If there's an @AuditMappedBy specified, returning it directly. - String auditMappedBy = propertyAuditingData.getAuditMappedBy(); - if (auditMappedBy != null) { - return auditMappedBy; - } + // If there's an @AuditMappedBy specified, returning it directly. + final String auditMappedBy = propertyAuditingData.getAuditMappedBy(); + if ( auditMappedBy != null ) { + return auditMappedBy; + } - // searching in referenced class - String mappedBy = this.searchMappedBy(referencedClass, collectionValue); + // searching in referenced class + String mappedBy = this.searchMappedBy( referencedClass, collectionValue ); - if(mappedBy == null) { - LOG.debugf("Going to search the mapped by attribute for %s in superclasses of entity: %s", - propertyName, - referencedClass.getClassName()); + if ( mappedBy == null ) { + LOG.debugf( + "Going to search the mapped by attribute for %s in superclasses of entity: %s", + propertyName, + referencedClass.getClassName() + ); - PersistentClass tempClass = referencedClass; - while ((mappedBy == null) && (tempClass.getSuperclass() != null)) { - LOG.debugf("Searching in superclass: %s", tempClass.getSuperclass().getClassName()); - mappedBy = this.searchMappedBy(tempClass.getSuperclass(), collectionValue); + PersistentClass tempClass = referencedClass; + while ( (mappedBy == null) && (tempClass.getSuperclass() != null) ) { + LOG.debugf( "Searching in superclass: %s", tempClass.getSuperclass().getClassName() ); + mappedBy = this.searchMappedBy( tempClass.getSuperclass(), collectionValue ); tempClass = tempClass.getSuperclass(); } - } + } - if(mappedBy == null) { - throw new MappingException("Unable to read the mapped by attribute for " + propertyName + " in " - + referencedClass.getClassName() + "!"); - } + if ( mappedBy == null ) { + throw new MappingException( + "Unable to read the mapped by attribute for " + propertyName + " in " + + referencedClass.getClassName() + "!" + ); + } - return mappedBy; - } + return mappedBy; + } - @SuppressWarnings({"unchecked"}) - private String searchMappedBy(PersistentClass referencedClass, Collection collectionValue) { - Iterator assocClassProps = referencedClass.getPropertyIterator(); - while (assocClassProps.hasNext()) { - Property property = assocClassProps.next(); + @SuppressWarnings({"unchecked"}) + private String searchMappedBy(PersistentClass referencedClass, Collection collectionValue) { + final Iterator assocClassProps = referencedClass.getPropertyIterator(); + while ( assocClassProps.hasNext() ) { + final Property property = assocClassProps.next(); - if (Tools.iteratorsContentEqual(property.getValue().getColumnIterator(), - collectionValue.getKey().getColumnIterator())) { - return property.getName(); - } - } - return null; - } - - private String getMappedBy(Table collectionTable, PersistentClass referencedClass) { - // If there's an @AuditMappedBy specified, returning it directly. - String auditMappedBy = propertyAuditingData.getAuditMappedBy(); - if (auditMappedBy != null) { - return auditMappedBy; - } - - // searching in referenced class - String mappedBy = this.searchMappedBy(referencedClass, collectionTable); - - // not found on referenced class, searching on superclasses - if(mappedBy == null) { - LOG.debugf("Going to search the mapped by attribute for %s in superclasses of entity: %s", - propertyName, - referencedClass.getClassName()); - - PersistentClass tempClass = referencedClass; - while ((mappedBy == null) && (tempClass.getSuperclass() != null)) { - LOG.debugf("Searching in superclass: %s", tempClass.getSuperclass().getClassName()); - mappedBy = this.searchMappedBy(tempClass.getSuperclass(), collectionTable); - tempClass = tempClass.getSuperclass(); + if ( Tools.iteratorsContentEqual( + property.getValue().getColumnIterator(), + collectionValue.getKey().getColumnIterator() + ) ) { + return property.getName(); } - } + } + return null; + } - if(mappedBy == null) { - throw new MappingException("Unable to read the mapped by attribute for " + propertyName + " in " - + referencedClass.getClassName() + "!"); - } + private String getMappedBy(Table collectionTable, PersistentClass referencedClass) { + // If there's an @AuditMappedBy specified, returning it directly. + final String auditMappedBy = propertyAuditingData.getAuditMappedBy(); + if ( auditMappedBy != null ) { + return auditMappedBy; + } - return mappedBy; - } + // searching in referenced class + String mappedBy = this.searchMappedBy( referencedClass, collectionTable ); - @SuppressWarnings({"unchecked"}) - private String searchMappedBy(PersistentClass referencedClass, Table collectionTable) { - Iterator properties = referencedClass.getPropertyIterator(); - while (properties.hasNext()) { - Property property = properties.next(); - if (property.getValue() instanceof Collection) { - // The equality is intentional. We want to find a collection property with the same collection table. - //noinspection ObjectEquality - if (((Collection) property.getValue()).getCollectionTable() == collectionTable) { - return property.getName(); - } - } - } - return null; - } + // not found on referenced class, searching on superclasses + if ( mappedBy == null ) { + LOG.debugf( + "Going to search the mapped by attribute for %s in superclasses of entity: %s", + propertyName, + referencedClass.getClassName() + ); + + PersistentClass tempClass = referencedClass; + while ( (mappedBy == null) && (tempClass.getSuperclass() != null) ) { + LOG.debugf( "Searching in superclass: %s", tempClass.getSuperclass().getClassName() ); + mappedBy = this.searchMappedBy( tempClass.getSuperclass(), collectionTable ); + tempClass = tempClass.getSuperclass(); + } + } + + if ( mappedBy == null ) { + throw new MappingException( + "Unable to read the mapped by attribute for " + propertyName + " in " + + referencedClass.getClassName() + "!" + ); + } + + return mappedBy; + } + + @SuppressWarnings({"unchecked"}) + private String searchMappedBy(PersistentClass referencedClass, Table collectionTable) { + final Iterator properties = referencedClass.getPropertyIterator(); + while ( properties.hasNext() ) { + final Property property = properties.next(); + if ( property.getValue() instanceof Collection ) { + // The equality is intentional. We want to find a collection property with the same collection table. + //noinspection ObjectEquality + if ( ((Collection) property.getValue()).getCollectionTable() == collectionTable ) { + return property.getName(); + } + } + } + return null; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/ComponentMetadataGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/ComponentMetadataGenerator.java index b1efd5c803..103a17e9f5 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/ComponentMetadataGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/ComponentMetadataGenerator.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.configuration.internal.metadata; import java.util.Iterator; @@ -14,6 +37,7 @@ import org.hibernate.mapping.Value; /** * Generates metadata for components. + * * @author Adam Warski (adam at warski dot org) */ public final class ComponentMetadataGenerator { @@ -24,29 +48,38 @@ public final class ComponentMetadataGenerator { } @SuppressWarnings({"unchecked"}) - public void addComponent(Element parent, PropertyAuditingData propertyAuditingData, - Value value, CompositeMapperBuilder mapper, String entityName, - EntityXmlMappingData xmlMappingData, boolean firstPass) { - Component prop_component = (Component) value; + public void addComponent( + Element parent, PropertyAuditingData propertyAuditingData, + Value value, CompositeMapperBuilder mapper, String entityName, + EntityXmlMappingData xmlMappingData, boolean firstPass) { + final Component propComponent = (Component) value; - Class componentClass = ReflectionTools.loadClass( prop_component.getComponentClassName(), mainGenerator.getClassLoaderService() ); - CompositeMapperBuilder componentMapper = mapper.addComponent( propertyAuditingData.getPropertyData(), componentClass ); + final Class componentClass = ReflectionTools.loadClass( + propComponent.getComponentClassName(), + mainGenerator.getClassLoaderService() + ); + final CompositeMapperBuilder componentMapper = mapper.addComponent( + propertyAuditingData.getPropertyData(), + componentClass + ); // The property auditing data must be for a component. - ComponentAuditingData componentAuditingData = (ComponentAuditingData) propertyAuditingData; + final ComponentAuditingData componentAuditingData = (ComponentAuditingData) propertyAuditingData; // Adding all properties of the component - Iterator properties = (Iterator) prop_component.getPropertyIterator(); - while (properties.hasNext()) { - Property property = properties.next(); + final Iterator properties = (Iterator) propComponent.getPropertyIterator(); + while ( properties.hasNext() ) { + final Property property = properties.next(); - PropertyAuditingData componentPropertyAuditingData = - componentAuditingData.getPropertyAuditingData(property.getName()); + final PropertyAuditingData componentPropertyAuditingData = + componentAuditingData.getPropertyAuditingData( property.getName() ); // Checking if that property is audited - if (componentPropertyAuditingData != null) { - mainGenerator.addValue(parent, property.getValue(), componentMapper, entityName, xmlMappingData, - componentPropertyAuditingData, property.isInsertable(), firstPass, false); + if ( componentPropertyAuditingData != null ) { + mainGenerator.addValue( + parent, property.getValue(), componentMapper, entityName, xmlMappingData, + componentPropertyAuditingData, property.isInsertable(), firstPass, false + ); } } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/EntityXmlMappingData.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/EntityXmlMappingData.java index 7584d16643..8132442490 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/EntityXmlMappingData.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/EntityXmlMappingData.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.configuration.internal.metadata; + import java.util.ArrayList; import java.util.List; @@ -33,39 +34,39 @@ import org.dom4j.Element; * @author Adam Warski (adam at warski dot org) */ public class EntityXmlMappingData { - private Document mainXmlMapping; - private List additionalXmlMappings; - /** - * The xml element that maps the class. The root can be one of the folowing elements: - * class, subclass, union-subclass, joined-subclass - */ - private Element classMapping; + private Document mainXmlMapping; + private List additionalXmlMappings; + /** + * The xml element that maps the class. The root can be one of the folowing elements: + * class, subclass, union-subclass, joined-subclass + */ + private Element classMapping; - public EntityXmlMappingData() { - mainXmlMapping = DocumentHelper.createDocument(); - additionalXmlMappings = new ArrayList(); - } + public EntityXmlMappingData() { + mainXmlMapping = DocumentHelper.createDocument(); + additionalXmlMappings = new ArrayList(); + } - public Document getMainXmlMapping() { - return mainXmlMapping; - } + public Document getMainXmlMapping() { + return mainXmlMapping; + } - public List getAdditionalXmlMappings() { - return additionalXmlMappings; - } + public List getAdditionalXmlMappings() { + return additionalXmlMappings; + } - public Document newAdditionalMapping() { - Document additionalMapping = DocumentHelper.createDocument(); - additionalXmlMappings.add(additionalMapping); + public Document newAdditionalMapping() { + Document additionalMapping = DocumentHelper.createDocument(); + additionalXmlMappings.add( additionalMapping ); - return additionalMapping; - } + return additionalMapping; + } - public Element getClassMapping() { - return classMapping; - } + public Element getClassMapping() { + return classMapping; + } - public void setClassMapping(Element classMapping) { - this.classMapping = classMapping; - } + public void setClassMapping(Element classMapping) { + this.classMapping = classMapping; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/IdMetadataGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/IdMetadataGenerator.java index d0064390cc..aa03697b1e 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/IdMetadataGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/IdMetadataGenerator.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.configuration.internal.metadata; + import java.util.Iterator; import org.dom4j.Element; @@ -47,127 +48,181 @@ import org.hibernate.type.Type; /** * Generates metadata for primary identifiers (ids) of versions entities. + * * @author Adam Warski (adam at warski dot org) */ public final class IdMetadataGenerator { - private final AuditMetadataGenerator mainGenerator; + private final AuditMetadataGenerator mainGenerator; - IdMetadataGenerator(AuditMetadataGenerator auditMetadataGenerator) { - mainGenerator = auditMetadataGenerator; - } + IdMetadataGenerator(AuditMetadataGenerator auditMetadataGenerator) { + mainGenerator = auditMetadataGenerator; + } - @SuppressWarnings({"unchecked"}) - private boolean addIdProperties(Element parent, Iterator properties, SimpleMapperBuilder mapper, boolean key, - boolean audited) { - while (properties.hasNext()) { - Property property = properties.next(); - Type propertyType = property.getType(); - if (!"_identifierMapper".equals(property.getName())) { - boolean added = false; - if (propertyType instanceof ManyToOneType) { - added = mainGenerator.getBasicMetadataGenerator().addManyToOne(parent, - getIdPersistentPropertyAuditingData(property), - property.getValue(), mapper); - } else { - // Last but one parameter: ids are always insertable - added = mainGenerator.getBasicMetadataGenerator().addBasic(parent, - getIdPersistentPropertyAuditingData(property), - property.getValue(), mapper, true, key); - } - if (!added) { - // If the entity is audited, and a non-supported id component is used, throwing an exception. - // If the entity is not audited, then we simply don't support this entity, even in - // target relation mode not audited. - if (audited) { - throw new MappingException("Type not supported: " + propertyType.getClass().getName()); - } else { - return false; - } - } - } - } + @SuppressWarnings({"unchecked"}) + private boolean addIdProperties( + Element parent, + Iterator properties, + SimpleMapperBuilder mapper, + boolean key, + boolean audited) { + while ( properties.hasNext() ) { + final Property property = properties.next(); + final Type propertyType = property.getType(); + if ( !"_identifierMapper".equals( property.getName() ) ) { + boolean added = false; + if ( propertyType instanceof ManyToOneType ) { + added = mainGenerator.getBasicMetadataGenerator().addManyToOne( + parent, + getIdPersistentPropertyAuditingData( property ), + property.getValue(), + mapper + ); + } + else { + // Last but one parameter: ids are always insertable + added = mainGenerator.getBasicMetadataGenerator().addBasic( + parent, + getIdPersistentPropertyAuditingData( property ), + property.getValue(), + mapper, + true, + key + ); + } + if ( !added ) { + // If the entity is audited, and a non-supported id component is used, throwing an exception. + // If the entity is not audited, then we simply don't support this entity, even in + // target relation mode not audited. + if ( audited ) { + throw new MappingException( "Type not supported: " + propertyType.getClass().getName() ); + } + else { + return false; + } + } + } + } - return true; - } + return true; + } - @SuppressWarnings({"unchecked"}) - IdMappingData addId(PersistentClass pc, boolean audited) { - // Xml mapping which will be used for relations - Element rel_id_mapping = new DefaultElement("properties"); - // Xml mapping which will be used for the primary key of the versions table - Element orig_id_mapping = new DefaultElement("composite-id"); + @SuppressWarnings({"unchecked"}) + IdMappingData addId(PersistentClass pc, boolean audited) { + // Xml mapping which will be used for relations + final Element relIdMapping = new DefaultElement( "properties" ); + // Xml mapping which will be used for the primary key of the versions table + final Element origIdMapping = new DefaultElement( "composite-id" ); - Property id_prop = pc.getIdentifierProperty(); - Component id_mapper = pc.getIdentifierMapper(); + final Property idProp = pc.getIdentifierProperty(); + final Component idMapper = pc.getIdentifierMapper(); - // Checking if the id mapping is supported - if (id_mapper == null && id_prop == null) { - return null; - } + // Checking if the id mapping is supported + if ( idMapper == null && idProp == null ) { + return null; + } - SimpleIdMapperBuilder mapper; - if (id_mapper != null) { - // Multiple id - - Class componentClass = ReflectionTools.loadClass( - ( (Component) pc.getIdentifier() ).getComponentClassName(), mainGenerator.getClassLoaderService() + SimpleIdMapperBuilder mapper; + if ( idMapper != null ) { + // Multiple id + final Class componentClass = ReflectionTools.loadClass( + ( (Component) pc.getIdentifier() ).getComponentClassName(), + mainGenerator.getClassLoaderService() ); mapper = new MultipleIdMapper( componentClass ); - if (!addIdProperties(rel_id_mapping, (Iterator) id_mapper.getPropertyIterator(), mapper, false, audited)) { - return null; - } + if ( !addIdProperties( + relIdMapping, + (Iterator) idMapper.getPropertyIterator(), + mapper, + false, + audited + ) ) { + return null; + } - // null mapper - the mapping where already added the first time, now we only want to generate the xml - if (!addIdProperties(orig_id_mapping, (Iterator) id_mapper.getPropertyIterator(), null, true, audited)) { - return null; - } - } else if (id_prop.isComposite()) { - // Embedded id - - Component id_component = (Component) id_prop.getValue(); - Class embeddableClass = ReflectionTools.loadClass( - id_component.getComponentClassName(), mainGenerator.getClassLoaderService() + // null mapper - the mapping where already added the first time, now we only want to generate the xml + if ( !addIdProperties( + origIdMapping, + (Iterator) idMapper.getPropertyIterator(), + null, + true, + audited + ) ) { + return null; + } + } + else if ( idProp.isComposite() ) { + // Embedded id + final Component idComponent = (Component) idProp.getValue(); + final Class embeddableClass = ReflectionTools.loadClass( + idComponent.getComponentClassName(), + mainGenerator.getClassLoaderService() ); - mapper = new EmbeddedIdMapper( getIdPropertyData(id_prop), embeddableClass ); - if (!addIdProperties(rel_id_mapping, (Iterator) id_component.getPropertyIterator(), mapper, false, audited)) { - return null; - } + mapper = new EmbeddedIdMapper( getIdPropertyData( idProp ), embeddableClass ); + if ( !addIdProperties( + relIdMapping, + (Iterator) idComponent.getPropertyIterator(), + mapper, + false, + audited + ) ) { + return null; + } - // null mapper - the mapping where already added the first time, now we only want to generate the xml - if (!addIdProperties(orig_id_mapping, (Iterator) id_component.getPropertyIterator(), null, true, audited)) { - return null; - } - } else { - // Single id - - mapper = new SingleIdMapper(); + // null mapper - the mapping where already added the first time, now we only want to generate the xml + if ( !addIdProperties( + origIdMapping, + (Iterator) idComponent.getPropertyIterator(), + null, + true, + audited + ) ) { + return null; + } + } + else { + // Single id + mapper = new SingleIdMapper(); - // Last but one parameter: ids are always insertable - mainGenerator.getBasicMetadataGenerator().addBasic(rel_id_mapping, - getIdPersistentPropertyAuditingData(id_prop), - id_prop.getValue(), mapper, true, false); + // Last but one parameter: ids are always insertable + mainGenerator.getBasicMetadataGenerator().addBasic( + relIdMapping, + getIdPersistentPropertyAuditingData( idProp ), + idProp.getValue(), + mapper, + true, + false + ); - // null mapper - the mapping where already added the first time, now we only want to generate the xml - mainGenerator.getBasicMetadataGenerator().addBasic(orig_id_mapping, - getIdPersistentPropertyAuditingData(id_prop), - id_prop.getValue(), null, true, true); - } + // null mapper - the mapping where already added the first time, now we only want to generate the xml + mainGenerator.getBasicMetadataGenerator().addBasic( + origIdMapping, + getIdPersistentPropertyAuditingData( idProp ), + idProp.getValue(), + null, + true, + true + ); + } - orig_id_mapping.addAttribute("name", mainGenerator.getVerEntCfg().getOriginalIdPropName()); + origIdMapping.addAttribute( "name", mainGenerator.getVerEntCfg().getOriginalIdPropName() ); - // Adding a relation to the revision entity (effectively: the "revision number" property) - mainGenerator.addRevisionInfoRelation(orig_id_mapping); + // Adding a relation to the revision entity (effectively: the "revision number" property) + mainGenerator.addRevisionInfoRelation( origIdMapping ); - return new IdMappingData(mapper, orig_id_mapping, rel_id_mapping); - } + return new IdMappingData( mapper, origIdMapping, relIdMapping ); + } - private PropertyData getIdPropertyData(Property property) { - return new PropertyData(property.getName(), property.getName(), property.getPropertyAccessorName(), - ModificationStore.FULL); - } + private PropertyData getIdPropertyData(Property property) { + return new PropertyData( + property.getName(), property.getName(), property.getPropertyAccessorName(), + ModificationStore.FULL + ); + } - private PropertyAuditingData getIdPersistentPropertyAuditingData(Property property) { - return new PropertyAuditingData(property.getName(), property.getPropertyAccessorName(), - ModificationStore.FULL, RelationTargetAuditMode.AUDITED, null, null, false); - } + private PropertyAuditingData getIdPersistentPropertyAuditingData(Property property) { + return new PropertyAuditingData( + property.getName(), property.getPropertyAccessorName(), + ModificationStore.FULL, RelationTargetAuditMode.AUDITED, null, null, false + ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/InheritanceType.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/InheritanceType.java index 87cb5a7f0c..e912f525ff 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/InheritanceType.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/InheritanceType.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.configuration.internal.metadata; + import org.hibernate.MappingException; import org.hibernate.mapping.JoinedSubclass; import org.hibernate.mapping.PersistentClass; @@ -33,33 +34,36 @@ import org.hibernate.mapping.UnionSubclass; * @author Adam Warski (adam at warski dot org) */ public enum InheritanceType { - NONE, - JOINED, - SINGLE, - TABLE_PER_CLASS; + NONE, + JOINED, + SINGLE, + TABLE_PER_CLASS; - /** - * @param pc The class for which to get the inheritance type. - * @return The inheritance type of this class. NONE, if this class does not inherit from - * another persisten class. - */ - public static InheritanceType get(PersistentClass pc) { - PersistentClass superclass = pc.getSuperclass(); - if (superclass == null) { - return InheritanceType.NONE; - } + /** + * @param pc The class for which to get the inheritance type. + * + * @return The inheritance type of this class. NONE, if this class does not inherit from + * another persistent class. + */ + public static InheritanceType get(PersistentClass pc) { + final PersistentClass superclass = pc.getSuperclass(); + if ( superclass == null ) { + return InheritanceType.NONE; + } - // We assume that every subclass is of the same type. - Subclass subclass = (Subclass) superclass.getSubclassIterator().next(); + // We assume that every subclass is of the same type. + final Subclass subclass = (Subclass) superclass.getSubclassIterator().next(); - if (subclass instanceof SingleTableSubclass) { - return InheritanceType.SINGLE; - } else if (subclass instanceof JoinedSubclass) { - return InheritanceType.JOINED; - } else if (subclass instanceof UnionSubclass) { - return InheritanceType.TABLE_PER_CLASS; - } + if ( subclass instanceof SingleTableSubclass ) { + return InheritanceType.SINGLE; + } + else if ( subclass instanceof JoinedSubclass ) { + return InheritanceType.JOINED; + } + else if ( subclass instanceof UnionSubclass ) { + return InheritanceType.TABLE_PER_CLASS; + } - throw new MappingException("Unknown subclass class: " + subclass.getClass()); - } + throw new MappingException( "Unknown subclass class: " + subclass.getClass() ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/MetadataTools.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/MetadataTools.java index 5bc51020c2..98863cae25 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/MetadataTools.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/MetadataTools.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,8 +22,9 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.configuration.internal.metadata; -import java.util.Iterator; + import javax.persistence.JoinColumn; +import java.util.Iterator; import org.dom4j.Attribute; import org.dom4j.Document; @@ -41,52 +42,72 @@ import org.hibernate.mapping.Selectable; */ public class MetadataTools { - public static Element addNativelyGeneratedId(Element parent, String name, String type, - boolean useRevisionEntityWithNativeId) { - Element id_mapping = parent.addElement("id"); - id_mapping.addAttribute("name", name).addAttribute("type", type); + public static Element addNativelyGeneratedId( + Element parent, String name, String type, + boolean useRevisionEntityWithNativeId) { + final Element idMapping = parent.addElement( "id" ); + idMapping.addAttribute( "name", name ).addAttribute( "type", type ); - Element generator_mapping = id_mapping.addElement("generator"); - if (useRevisionEntityWithNativeId) { - generator_mapping.addAttribute("class", "native"); - } else { - generator_mapping.addAttribute("class", "org.hibernate.envers.enhanced.OrderedSequenceGenerator"); - generator_mapping.addElement("param").addAttribute("name", "sequence_name").setText("REVISION_GENERATOR"); - generator_mapping.addElement("param").addAttribute("name", "table_name").setText("REVISION_GENERATOR"); - generator_mapping.addElement("param").addAttribute("name", "initial_value").setText("1"); - generator_mapping.addElement("param").addAttribute("name", "increment_size").setText("1"); - } -// generator_mapping.addAttribute("class", "sequence"); -// generator_mapping.addElement("param").addAttribute("name", "sequence").setText("custom"); + final Element generatorMapping = idMapping.addElement( "generator" ); + if ( useRevisionEntityWithNativeId ) { + generatorMapping.addAttribute( "class", "native" ); + } + else { + generatorMapping.addAttribute( "class", "org.hibernate.envers.enhanced.OrderedSequenceGenerator" ); + generatorMapping.addElement( "param" ).addAttribute( "name", "sequence_name" ).setText( + "REVISION_GENERATOR" + ); + generatorMapping.addElement( "param" ) + .addAttribute( "name", "table_name" ) + .setText( "REVISION_GENERATOR" ); + generatorMapping.addElement( "param" ).addAttribute( "name", "initial_value" ).setText( "1" ); + generatorMapping.addElement( "param" ).addAttribute( "name", "increment_size" ).setText( "1" ); + } +// generatorMapping.addAttribute("class", "sequence"); +// generatorMapping.addElement("param").addAttribute("name", "sequence").setText("custom"); - return id_mapping; - } + return idMapping; + } - public static Element addProperty(Element parent, String name, String type, boolean insertable, boolean updateable, boolean key) { - Element prop_mapping; - if (key) { - prop_mapping = parent.addElement("key-property"); - } else { - prop_mapping = parent.addElement("property"); - } + public static Element addProperty( + Element parent, + String name, + String type, + boolean insertable, + boolean updateable, + boolean key) { + final Element propMapping; + if ( key ) { + propMapping = parent.addElement( "key-property" ); + } + else { + propMapping = parent.addElement( "property" ); + } - prop_mapping.addAttribute("name", name); - prop_mapping.addAttribute("insert", Boolean.toString(insertable)); - prop_mapping.addAttribute("update", Boolean.toString(updateable)); + propMapping.addAttribute( "name", name ); + propMapping.addAttribute( "insert", Boolean.toString( insertable ) ); + propMapping.addAttribute( "update", Boolean.toString( updateable ) ); - if (type != null) { - prop_mapping.addAttribute("type", type); - } + if ( type != null ) { + propMapping.addAttribute( "type", type ); + } - return prop_mapping; - } + return propMapping; + } - public static Element addProperty(Element parent, String name, String type, boolean insertable, boolean key) { - return addProperty(parent, name, type, insertable, false, key); - } + public static Element addProperty(Element parent, String name, String type, boolean insertable, boolean key) { + return addProperty( parent, name, type, insertable, false, key ); + } public static Element addModifiedFlagProperty(Element parent, String propertyName, String suffix) { - return addProperty(parent, getModifiedFlagPropertyName(propertyName, suffix), "boolean", true, false, false); + return addProperty( + parent, + getModifiedFlagPropertyName( propertyName, suffix ), + "boolean", + true, + false, + false + ); } public static String getModifiedFlagPropertyName(String propertyName, String suffix) { @@ -94,256 +115,319 @@ public class MetadataTools { } private static void addOrModifyAttribute(Element parent, String name, String value) { - Attribute attribute = parent.attribute(name); - if (attribute == null) { - parent.addAttribute(name, value); - } else { - attribute.setValue(value); - } - } - - /** - * Column name shall be wrapped with '`' signs if quotation required. - */ - public static Element addOrModifyColumn(Element parent, String name) { - Element column_mapping = parent.element("column"); - - if (column_mapping == null) { - return addColumn(parent, name, null, null, null, null, null, null); - } - - if (!StringTools.isEmpty(name)) { - addOrModifyAttribute(column_mapping, "name", name); - } - - return column_mapping; - } - - /** - * Adds new column element. Method assumes that the value of name attribute is already - * wrapped with '`' signs if quotation required. It shall be invoked when column name is taken directly from configuration - * file and not from {@link org.hibernate.mapping.PersistentClass} descriptor. - */ - public static Element addColumn(Element parent, String name, Integer length, Integer scale, Integer precision, - String sqlType, String customRead, String customWrite) { - return addColumn(parent, name, length, scale, precision, sqlType, customRead, customWrite, false); - } - - public static Element addColumn(Element parent, String name, Integer length, Integer scale, Integer precision, - String sqlType, String customRead, String customWrite, boolean quoted) { - Element column_mapping = parent.addElement("column"); - - column_mapping.addAttribute("name", quoted ? "`" + name + "`" : name); - if (length != null) { - column_mapping.addAttribute("length", length.toString()); - } - if (scale != null) { - column_mapping.addAttribute("scale", Integer.toString(scale)); + final Attribute attribute = parent.attribute( name ); + if ( attribute == null ) { + parent.addAttribute( name, value ); } - if (precision != null) { - column_mapping.addAttribute("precision", Integer.toString(precision)); + else { + attribute.setValue( value ); } - if (!StringTools.isEmpty(sqlType)) { - column_mapping.addAttribute("sql-type", sqlType); - } + } - if (!StringTools.isEmpty(customRead)) { - column_mapping.addAttribute("read", customRead); - } - if (!StringTools.isEmpty(customWrite)) { - column_mapping.addAttribute("write", customWrite); - } + /** + * Column name shall be wrapped with '`' signs if quotation required. + */ + public static Element addOrModifyColumn(Element parent, String name) { + final Element columnMapping = parent.element( "column" ); - return column_mapping; - } + if ( columnMapping == null ) { + return addColumn( parent, name, null, null, null, null, null, null ); + } - private static Element createEntityCommon(Document document, String type, AuditTableData auditTableData, - String discriminatorValue, Boolean isAbstract) { - Element hibernate_mapping = document.addElement("hibernate-mapping"); - hibernate_mapping.addAttribute("auto-import", "false"); + if ( !StringTools.isEmpty( name ) ) { + addOrModifyAttribute( columnMapping, "name", name ); + } - Element class_mapping = hibernate_mapping.addElement(type); + return columnMapping; + } - if (auditTableData.getAuditEntityName() != null) { - class_mapping.addAttribute("entity-name", auditTableData.getAuditEntityName()); - } + /** + * Adds new column element. Method assumes that the value of name attribute is already + * wrapped with '`' signs if quotation required. It shall be invoked when column name is taken directly from configuration + * file and not from {@link org.hibernate.mapping.PersistentClass} descriptor. + */ + public static Element addColumn( + Element parent, + String name, + Integer length, + Integer scale, + Integer precision, + String sqlType, + String customRead, + String customWrite) { + return addColumn( parent, name, length, scale, precision, sqlType, customRead, customWrite, false ); + } - if (discriminatorValue != null) { - class_mapping.addAttribute("discriminator-value", discriminatorValue); - } + public static Element addColumn( + Element parent, + String name, + Integer length, + Integer scale, + Integer precision, + String sqlType, + String customRead, + String customWrite, + boolean quoted) { + final Element columnMapping = parent.addElement( "column" ); - if (!StringTools.isEmpty(auditTableData.getAuditTableName())) { - class_mapping.addAttribute("table", auditTableData.getAuditTableName()); - } + columnMapping.addAttribute( "name", quoted ? "`" + name + "`" : name ); + if ( length != null ) { + columnMapping.addAttribute( "length", length.toString() ); + } + if ( scale != null ) { + columnMapping.addAttribute( "scale", Integer.toString( scale ) ); + } + if ( precision != null ) { + columnMapping.addAttribute( "precision", Integer.toString( precision ) ); + } + if ( !StringTools.isEmpty( sqlType ) ) { + columnMapping.addAttribute( "sql-type", sqlType ); + } - if (!StringTools.isEmpty(auditTableData.getSchema())) { - class_mapping.addAttribute("schema", auditTableData.getSchema()); - } + if ( !StringTools.isEmpty( customRead ) ) { + columnMapping.addAttribute( "read", customRead ); + } + if ( !StringTools.isEmpty( customWrite ) ) { + columnMapping.addAttribute( "write", customWrite ); + } - if (!StringTools.isEmpty(auditTableData.getCatalog())) { - class_mapping.addAttribute("catalog", auditTableData.getCatalog()); - } + return columnMapping; + } - if (isAbstract != null) { - class_mapping.addAttribute("abstract", isAbstract.toString()); - } + private static Element createEntityCommon( + Document document, + String type, + AuditTableData auditTableData, + String discriminatorValue, + Boolean isAbstract) { + final Element hibernateMapping = document.addElement( "hibernate-mapping" ); + hibernateMapping.addAttribute( "auto-import", "false" ); - return class_mapping; - } + final Element classMapping = hibernateMapping.addElement( type ); - public static Element createEntity(Document document, AuditTableData auditTableData, String discriminatorValue, - Boolean isAbstract) { - return createEntityCommon(document, "class", auditTableData, discriminatorValue, isAbstract); - } + if ( auditTableData.getAuditEntityName() != null ) { + classMapping.addAttribute( "entity-name", auditTableData.getAuditEntityName() ); + } - public static Element createSubclassEntity(Document document, String subclassType, AuditTableData auditTableData, - String extendsEntityName, String discriminatorValue, Boolean isAbstract) { - Element class_mapping = createEntityCommon(document, subclassType, auditTableData, discriminatorValue, isAbstract); + if ( discriminatorValue != null ) { + classMapping.addAttribute( "discriminator-value", discriminatorValue ); + } - class_mapping.addAttribute("extends", extendsEntityName); + if ( !StringTools.isEmpty( auditTableData.getAuditTableName() ) ) { + classMapping.addAttribute( "table", auditTableData.getAuditTableName() ); + } - return class_mapping; - } + if ( !StringTools.isEmpty( auditTableData.getSchema() ) ) { + classMapping.addAttribute( "schema", auditTableData.getSchema() ); + } - public static Element createJoin(Element parent, String tableName, - String schema, String catalog) { - Element join_mapping = parent.addElement("join"); + if ( !StringTools.isEmpty( auditTableData.getCatalog() ) ) { + classMapping.addAttribute( "catalog", auditTableData.getCatalog() ); + } - join_mapping.addAttribute("table", tableName); + if ( isAbstract != null ) { + classMapping.addAttribute( "abstract", isAbstract.toString() ); + } - if (!StringTools.isEmpty(schema)) { - join_mapping.addAttribute("schema", schema); - } + return classMapping; + } - if (!StringTools.isEmpty(catalog)) { - join_mapping.addAttribute("catalog", catalog); - } + public static Element createEntity( + Document document, + AuditTableData auditTableData, + String discriminatorValue, + Boolean isAbstract) { + return createEntityCommon( document, "class", auditTableData, discriminatorValue, isAbstract ); + } - return join_mapping; - } + public static Element createSubclassEntity( + Document document, + String subclassType, + AuditTableData auditTableData, + String extendsEntityName, + String discriminatorValue, + Boolean isAbstract) { + final Element classMapping = createEntityCommon( + document, + subclassType, + auditTableData, + discriminatorValue, + isAbstract + ); - public static void addColumns(Element any_mapping, Iterator selectables) { - while ( selectables.hasNext() ) { + classMapping.addAttribute( "extends", extendsEntityName ); + + return classMapping; + } + + public static Element createJoin( + Element parent, + String tableName, + String schema, + String catalog) { + final Element joinMapping = parent.addElement( "join" ); + + joinMapping.addAttribute( "table", tableName ); + + if ( !StringTools.isEmpty( schema ) ) { + joinMapping.addAttribute( "schema", schema ); + } + + if ( !StringTools.isEmpty( catalog ) ) { + joinMapping.addAttribute( "catalog", catalog ); + } + + return joinMapping; + } + + public static void addColumns(Element anyMapping, Iterator selectables) { + while ( selectables.hasNext() ) { final Selectable selectable = (Selectable) selectables.next(); if ( selectable.isFormula() ) { throw new FormulaNotSupportedException(); } - addColumn( any_mapping, (Column) selectable ); - } - } - - /** - * Adds column element with the following attributes (unless empty): name, - * length, scale, precision, sql-type, read - * and write. - * @param any_mapping Parent element. - * @param column Column descriptor. - */ - public static void addColumn(Element any_mapping, Column column) { - addColumn(any_mapping, column.getName(), column.getLength(), column.getScale(), column.getPrecision(), - column.getSqlType(), column.getCustomRead(), column.getCustomWrite(), column.isQuoted()); - } - - @SuppressWarnings({"unchecked"}) - private static void changeNamesInColumnElement(Element element, ColumnNameIterator columnNameIterator) { - Iterator properties = element.elementIterator(); - while (properties.hasNext()) { - Element property = properties.next(); - - if ("column".equals(property.getName())) { - Attribute nameAttr = property.attribute("name"); - if (nameAttr != null) { - nameAttr.setText(columnNameIterator.next()); - } - } - } - } - - @SuppressWarnings({"unchecked"}) - public static void prefixNamesInPropertyElement(Element element, String prefix, ColumnNameIterator columnNameIterator, - boolean changeToKey, boolean insertable) { - Iterator properties = element.elementIterator(); - while (properties.hasNext()) { - Element property = properties.next(); - - if ("property".equals(property.getName()) || "many-to-one".equals(property.getName())) { - Attribute nameAttr = property.attribute("name"); - if (nameAttr != null) { - nameAttr.setText(prefix + nameAttr.getText()); - } - - changeNamesInColumnElement(property, columnNameIterator); - - if (changeToKey) { - property.setName("key-" + property.getName()); - } - - if ("property".equals(property.getName())) { - Attribute insert = property.attribute("insert"); - insert.setText(Boolean.toString(insertable)); - } - } - } - } - - /** - * Adds formula element. - * @param element Parent element. - * @param formula Formula descriptor. - */ - public static void addFormula(Element element, Formula formula) { - element.addElement("formula").setText(formula.getText()); - } - - /** - * Adds all column or formula elements. - * @param element Parent element. - * @param columnIterator Iterator pointing at {@link org.hibernate.mapping.Column} and/or - * {@link org.hibernate.mapping.Formula} objects. - */ - public static void addColumnsOrFormulas(Element element, Iterator columnIterator) { - while (columnIterator.hasNext()) { - Object o = columnIterator.next(); - if (o instanceof Column) { - addColumn(element, (Column) o); - } else if (o instanceof Formula) { - addFormula(element, (Formula) o); - } - } - } - - /** - * An iterator over column names. - */ - public static abstract class ColumnNameIterator implements Iterator { + addColumn( anyMapping, (Column) selectable ); + } } - public static ColumnNameIterator getColumnNameIterator(final Iterator selectableIterator) { - return new ColumnNameIterator() { - public boolean hasNext() { + /** + * Adds column element with the following attributes (unless empty): name, + * length, scale, precision, sql-type, read + * and write. + * + * @param anyMapping Parent element. + * @param column Column descriptor. + */ + public static void addColumn(Element anyMapping, Column column) { + addColumn( + anyMapping, + column.getName(), + column.getLength(), + column.getScale(), + column.getPrecision(), + column.getSqlType(), + column.getCustomRead(), + column.getCustomWrite(), + column.isQuoted() + ); + } + + @SuppressWarnings({"unchecked"}) + private static void changeNamesInColumnElement(Element element, ColumnNameIterator columnNameIterator) { + final Iterator properties = element.elementIterator(); + while ( properties.hasNext() ) { + final Element property = properties.next(); + + if ( "column".equals( property.getName() ) ) { + final Attribute nameAttr = property.attribute( "name" ); + if ( nameAttr != null ) { + nameAttr.setText( columnNameIterator.next() ); + } + } + } + } + + @SuppressWarnings({"unchecked"}) + public static void prefixNamesInPropertyElement( + Element element, + String prefix, + ColumnNameIterator columnNameIterator, + boolean changeToKey, + boolean insertable) { + final Iterator properties = element.elementIterator(); + while ( properties.hasNext() ) { + final Element property = properties.next(); + + if ( "property".equals( property.getName() ) || "many-to-one".equals( property.getName() ) ) { + final Attribute nameAttr = property.attribute( "name" ); + if ( nameAttr != null ) { + nameAttr.setText( prefix + nameAttr.getText() ); + } + + changeNamesInColumnElement( property, columnNameIterator ); + + if ( changeToKey ) { + property.setName( "key-" + property.getName() ); + } + + if ( "property".equals( property.getName() ) ) { + final Attribute insert = property.attribute( "insert" ); + insert.setText( Boolean.toString( insertable ) ); + } + } + } + } + + /** + * Adds formula element. + * + * @param element Parent element. + * @param formula Formula descriptor. + */ + public static void addFormula(Element element, Formula formula) { + element.addElement( "formula" ).setText( formula.getText() ); + } + + /** + * Adds all column or formula elements. + * + * @param element Parent element. + * @param columnIterator Iterator pointing at {@link org.hibernate.mapping.Column} and/or + * {@link org.hibernate.mapping.Formula} objects. + */ + public static void addColumnsOrFormulas(Element element, Iterator columnIterator) { + while ( columnIterator.hasNext() ) { + final Object o = columnIterator.next(); + if ( o instanceof Column ) { + addColumn( element, (Column) o ); + } + else if ( o instanceof Formula ) { + addFormula( element, (Formula) o ); + } + } + } + + /** + * An iterator over column names. + */ + public static abstract class ColumnNameIterator implements Iterator { + } + + public static ColumnNameIterator getColumnNameIterator(final Iterator selectableIterator) { + return new ColumnNameIterator() { + public boolean hasNext() { return selectableIterator.hasNext(); } - public String next() { + public String next() { final Selectable next = selectableIterator.next(); if ( next.isFormula() ) { throw new FormulaNotSupportedException(); } - return ( (Column) next ).getName(); + return ((Column) next).getName(); } - public void remove() { + public void remove() { selectableIterator.remove(); } - }; - } + }; + } - public static ColumnNameIterator getColumnNameIterator(final JoinColumn[] joinColumns) { - return new ColumnNameIterator() { - int counter = 0; - public boolean hasNext() { return counter < joinColumns.length; } - public String next() { return joinColumns[counter++].name(); } - public void remove() { throw new UnsupportedOperationException(); } - }; - } + public static ColumnNameIterator getColumnNameIterator(final JoinColumn[] joinColumns) { + return new ColumnNameIterator() { + int counter = 0; + + public boolean hasNext() { + return counter < joinColumns.length; + } + + public String next() { + return joinColumns[counter++].name(); + } + + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/QueryGeneratorBuilder.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/QueryGeneratorBuilder.java index 4312097d19..c7912f74c5 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/QueryGeneratorBuilder.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/QueryGeneratorBuilder.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.configuration.internal.metadata; + import java.util.ArrayList; import java.util.List; @@ -40,64 +41,83 @@ import org.hibernate.envers.strategy.AuditStrategy; /** * Builds query generators, for reading collection middle tables, along with any related entities. * The related entities information can be added gradually, and when complete, the query generator can be built. + * * @author Adam Warski (adam at warski dot org) */ public final class QueryGeneratorBuilder { - private final GlobalConfiguration globalCfg; - private final AuditEntitiesConfiguration verEntCfg; - private final AuditStrategy auditStrategy; - private final MiddleIdData referencingIdData; - private final String auditMiddleEntityName; - private final List idDatas; + private final GlobalConfiguration globalCfg; + private final AuditEntitiesConfiguration verEntCfg; + private final AuditStrategy auditStrategy; + private final MiddleIdData referencingIdData; + private final String auditMiddleEntityName; + private final List idDatas; private final boolean revisionTypeInId; - QueryGeneratorBuilder(GlobalConfiguration globalCfg, AuditEntitiesConfiguration verEntCfg, - AuditStrategy auditStrategy, MiddleIdData referencingIdData, String auditMiddleEntityName, - boolean revisionTypeInId) { - this.globalCfg = globalCfg; - this.verEntCfg = verEntCfg; - this.auditStrategy = auditStrategy; - this.referencingIdData = referencingIdData; - this.auditMiddleEntityName = auditMiddleEntityName; + QueryGeneratorBuilder( + GlobalConfiguration globalCfg, + AuditEntitiesConfiguration verEntCfg, + AuditStrategy auditStrategy, + MiddleIdData referencingIdData, + String auditMiddleEntityName, + boolean revisionTypeInId) { + this.globalCfg = globalCfg; + this.verEntCfg = verEntCfg; + this.auditStrategy = auditStrategy; + this.referencingIdData = referencingIdData; + this.auditMiddleEntityName = auditMiddleEntityName; this.revisionTypeInId = revisionTypeInId; - idDatas = new ArrayList(); - } + idDatas = new ArrayList(); + } - void addRelation(MiddleIdData idData) { - idDatas.add(idData); - } + void addRelation(MiddleIdData idData) { + idDatas.add( idData ); + } - RelationQueryGenerator build(MiddleComponentData... componentDatas) { - if (idDatas.size() == 0) { - return new OneEntityQueryGenerator(verEntCfg, auditStrategy, auditMiddleEntityName, referencingIdData, - revisionTypeInId, componentDatas); - } else if (idDatas.size() == 1) { - if (idDatas.get(0).isAudited()) { - return new TwoEntityQueryGenerator(globalCfg, verEntCfg, auditStrategy, auditMiddleEntityName, referencingIdData, - idDatas.get(0), revisionTypeInId, componentDatas); - } else { - return new TwoEntityOneAuditedQueryGenerator(verEntCfg, auditStrategy, auditMiddleEntityName, referencingIdData, - idDatas.get(0), revisionTypeInId, componentDatas); - } - } else if (idDatas.size() == 2) { - // All entities must be audited. - if (!idDatas.get(0).isAudited() || !idDatas.get(1).isAudited()) { - throw new MappingException("Ternary relations using @Audited(targetAuditMode = NOT_AUDITED) are not supported."); - } + RelationQueryGenerator build(MiddleComponentData... componentDatas) { + if ( idDatas.size() == 0 ) { + return new OneEntityQueryGenerator( + verEntCfg, auditStrategy, auditMiddleEntityName, referencingIdData, + revisionTypeInId, componentDatas + ); + } + else if ( idDatas.size() == 1 ) { + if ( idDatas.get( 0 ).isAudited() ) { + return new TwoEntityQueryGenerator( + globalCfg, verEntCfg, auditStrategy, auditMiddleEntityName, referencingIdData, + idDatas.get( 0 ), revisionTypeInId, componentDatas + ); + } + else { + return new TwoEntityOneAuditedQueryGenerator( + verEntCfg, auditStrategy, auditMiddleEntityName, referencingIdData, + idDatas.get( 0 ), revisionTypeInId, componentDatas + ); + } + } + else if ( idDatas.size() == 2 ) { + // All entities must be audited. + if ( !idDatas.get( 0 ).isAudited() || !idDatas.get( 1 ).isAudited() ) { + throw new MappingException( + "Ternary relations using @Audited(targetAuditMode = NOT_AUDITED) are not supported." + ); + } - return new ThreeEntityQueryGenerator(globalCfg, verEntCfg, auditStrategy, auditMiddleEntityName, referencingIdData, - idDatas.get(0), idDatas.get(1), revisionTypeInId, componentDatas); - } else { - throw new IllegalStateException("Illegal number of related entities."); - } - } + return new ThreeEntityQueryGenerator( + globalCfg, verEntCfg, auditStrategy, auditMiddleEntityName, referencingIdData, + idDatas.get( 0 ), idDatas.get( 1 ), revisionTypeInId, componentDatas + ); + } + else { + throw new IllegalStateException( "Illegal number of related entities." ); + } + } - /** - * @return Current index of data in the array, which will be the element of a list, returned when executing a query - * generated by the built query generator. - */ - int getCurrentIndex() { - return idDatas.size(); - } + /** + * @return Current index of data in the array, which will be the element of a list, returned when executing a query + * generated by the built query generator. + */ + int getCurrentIndex() { + return idDatas.size(); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/ToOneRelationMetadataGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/ToOneRelationMetadataGenerator.java index 2e644d8e11..b18179dc39 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/ToOneRelationMetadataGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/ToOneRelationMetadataGenerator.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.configuration.internal.metadata; + import org.dom4j.Element; import org.hibernate.MappingException; @@ -41,121 +42,166 @@ import org.hibernate.mapping.Value; /** * Generates metadata for to-one relations (reference-valued properties). + * * @author Adam Warski (adam at warski dot org) * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public final class ToOneRelationMetadataGenerator { - private final AuditMetadataGenerator mainGenerator; + private final AuditMetadataGenerator mainGenerator; - ToOneRelationMetadataGenerator(AuditMetadataGenerator auditMetadataGenerator) { - mainGenerator = auditMetadataGenerator; - } + ToOneRelationMetadataGenerator(AuditMetadataGenerator auditMetadataGenerator) { + mainGenerator = auditMetadataGenerator; + } - @SuppressWarnings({"unchecked"}) - void addToOne(Element parent, PropertyAuditingData propertyAuditingData, Value value, - CompositeMapperBuilder mapper, String entityName, boolean insertable) { - String referencedEntityName = ((ToOne) value).getReferencedEntityName(); + @SuppressWarnings({"unchecked"}) + void addToOne( + Element parent, + PropertyAuditingData propertyAuditingData, + Value value, + CompositeMapperBuilder mapper, + String entityName, + boolean insertable) { + final String referencedEntityName = ((ToOne) value).getReferencedEntityName(); - IdMappingData idMapping = mainGenerator.getReferencedIdMappingData(entityName, referencedEntityName, - propertyAuditingData, true); + final IdMappingData idMapping = mainGenerator.getReferencedIdMappingData( + entityName, + referencedEntityName, + propertyAuditingData, + true + ); - String lastPropertyPrefix = MappingTools.createToOneRelationPrefix(propertyAuditingData.getName()); + final String lastPropertyPrefix = MappingTools.createToOneRelationPrefix( propertyAuditingData.getName() ); - // Generating the id mapper for the relation - IdMapper relMapper = idMapping.getIdMapper().prefixMappedProperties(lastPropertyPrefix); + // Generating the id mapper for the relation + final IdMapper relMapper = idMapping.getIdMapper().prefixMappedProperties( lastPropertyPrefix ); - // Storing information about this relation - mainGenerator.getEntitiesConfigurations().get(entityName).addToOneRelation( - propertyAuditingData.getName(), referencedEntityName, relMapper, insertable); + // Storing information about this relation + mainGenerator.getEntitiesConfigurations().get( entityName ).addToOneRelation( + propertyAuditingData.getName(), + referencedEntityName, + relMapper, + insertable + ); - // If the property isn't insertable, checking if this is not a "fake" bidirectional many-to-one relationship, - // that is, when the one side owns the relation (and is a collection), and the many side is non insertable. - // When that's the case and the user specified to store this relation without a middle table (using - // @AuditMappedBy), we have to make the property insertable for the purposes of Envers. In case of changes to - // the entity that didn't involve the relation, it's value will then be stored properly. In case of changes - // to the entity that did involve the relation, it's the responsibility of the collection side to store the - // proper data. - boolean nonInsertableFake; - if (!insertable && propertyAuditingData.isForceInsertable()) { - nonInsertableFake = true; - insertable = true; - } else { - nonInsertableFake = false; - } + // If the property isn't insertable, checking if this is not a "fake" bidirectional many-to-one relationship, + // that is, when the one side owns the relation (and is a collection), and the many side is non insertable. + // When that's the case and the user specified to store this relation without a middle table (using + // @AuditMappedBy), we have to make the property insertable for the purposes of Envers. In case of changes to + // the entity that didn't involve the relation, it's value will then be stored properly. In case of changes + // to the entity that did involve the relation, it's the responsibility of the collection side to store the + // proper data. + boolean nonInsertableFake; + if ( !insertable && propertyAuditingData.isForceInsertable() ) { + nonInsertableFake = true; + insertable = true; + } + else { + nonInsertableFake = false; + } - // Adding an element to the mapping corresponding to the references entity id's - Element properties = (Element) idMapping.getXmlRelationMapping().clone(); - properties.addAttribute("name", propertyAuditingData.getName()); + // Adding an element to the mapping corresponding to the references entity id's + final Element properties = (Element) idMapping.getXmlRelationMapping().clone(); + properties.addAttribute( "name", propertyAuditingData.getName() ); - MetadataTools.prefixNamesInPropertyElement(properties, lastPropertyPrefix, - MetadataTools.getColumnNameIterator(value.getColumnIterator()), false, insertable); + MetadataTools.prefixNamesInPropertyElement( + properties, + lastPropertyPrefix, + MetadataTools.getColumnNameIterator( value.getColumnIterator() ), + false, + insertable + ); // Extracting related id properties from properties tag - for (Object o : properties.content()) { - Element element = (Element) o; - element.setParent(null); - parent.add(element); + for ( Object o : properties.content() ) { + final Element element = (Element) o; + element.setParent( null ); + parent.add( element ); } // Adding mapper for the id - PropertyData propertyData = propertyAuditingData.getPropertyData(); - mapper.addComposite(propertyData, new ToOneIdMapper(relMapper, propertyData, referencedEntityName, nonInsertableFake)); - } + final PropertyData propertyData = propertyAuditingData.getPropertyData(); + mapper.addComposite( + propertyData, + new ToOneIdMapper( relMapper, propertyData, referencedEntityName, nonInsertableFake ) + ); + } - @SuppressWarnings({"unchecked"}) - void addOneToOneNotOwning(PropertyAuditingData propertyAuditingData, Value value, - CompositeMapperBuilder mapper, String entityName) { - OneToOne propertyValue = (OneToOne) value; + @SuppressWarnings({"unchecked"}) + void addOneToOneNotOwning( + PropertyAuditingData propertyAuditingData, + Value value, + CompositeMapperBuilder mapper, + String entityName) { + final OneToOne propertyValue = (OneToOne) value; + final String owningReferencePropertyName = propertyValue.getReferencedPropertyName(); - String owningReferencePropertyName = propertyValue.getReferencedPropertyName(); // mappedBy + final EntityConfiguration configuration = mainGenerator.getEntitiesConfigurations().get( entityName ); + if ( configuration == null ) { + throw new MappingException( "An audited relation to a non-audited entity " + entityName + "!" ); + } - EntityConfiguration configuration = mainGenerator.getEntitiesConfigurations().get(entityName); - if (configuration == null) { - throw new MappingException("An audited relation to a non-audited entity " + entityName + "!"); - } + final IdMappingData ownedIdMapping = configuration.getIdMappingData(); - IdMappingData ownedIdMapping = configuration.getIdMappingData(); + if ( ownedIdMapping == null ) { + throw new MappingException( "An audited relation to a non-audited entity " + entityName + "!" ); + } - if (ownedIdMapping == null) { - throw new MappingException("An audited relation to a non-audited entity " + entityName + "!"); - } + final String lastPropertyPrefix = MappingTools.createToOneRelationPrefix( owningReferencePropertyName ); + final String referencedEntityName = propertyValue.getReferencedEntityName(); - String lastPropertyPrefix = MappingTools.createToOneRelationPrefix(owningReferencePropertyName); - String referencedEntityName = propertyValue.getReferencedEntityName(); + // Generating the id mapper for the relation + final IdMapper ownedIdMapper = ownedIdMapping.getIdMapper().prefixMappedProperties( lastPropertyPrefix ); - // Generating the id mapper for the relation - IdMapper ownedIdMapper = ownedIdMapping.getIdMapper().prefixMappedProperties(lastPropertyPrefix); + // Storing information about this relation + mainGenerator.getEntitiesConfigurations().get( entityName ).addToOneNotOwningRelation( + propertyAuditingData.getName(), + owningReferencePropertyName, + referencedEntityName, + ownedIdMapper + ); - // Storing information about this relation - mainGenerator.getEntitiesConfigurations().get(entityName).addToOneNotOwningRelation( - propertyAuditingData.getName(), owningReferencePropertyName, - referencedEntityName, ownedIdMapper); + // Adding mapper for the id + final PropertyData propertyData = propertyAuditingData.getPropertyData(); + mapper.addComposite( + propertyData, + new OneToOneNotOwningMapper( entityName, referencedEntityName, owningReferencePropertyName, propertyData ) + ); + } - // Adding mapper for the id - PropertyData propertyData = propertyAuditingData.getPropertyData(); - mapper.addComposite(propertyData, new OneToOneNotOwningMapper(entityName, referencedEntityName, - owningReferencePropertyName, propertyData)); - } + @SuppressWarnings({"unchecked"}) + void addOneToOnePrimaryKeyJoinColumn( + PropertyAuditingData propertyAuditingData, + Value value, + CompositeMapperBuilder mapper, + String entityName, + boolean insertable) { + final String referencedEntityName = ((ToOne) value).getReferencedEntityName(); - @SuppressWarnings({"unchecked"}) - void addOneToOnePrimaryKeyJoinColumn(PropertyAuditingData propertyAuditingData, Value value, - CompositeMapperBuilder mapper, String entityName, boolean insertable) { - String referencedEntityName = ((ToOne) value).getReferencedEntityName(); + final IdMappingData idMapping = mainGenerator.getReferencedIdMappingData( + entityName, + referencedEntityName, + propertyAuditingData, + true + ); - IdMappingData idMapping = mainGenerator.getReferencedIdMappingData(entityName, referencedEntityName, - propertyAuditingData, true); + final String lastPropertyPrefix = MappingTools.createToOneRelationPrefix( propertyAuditingData.getName() ); - String lastPropertyPrefix = MappingTools.createToOneRelationPrefix(propertyAuditingData.getName()); + // Generating the id mapper for the relation + final IdMapper relMapper = idMapping.getIdMapper().prefixMappedProperties( lastPropertyPrefix ); - // Generating the id mapper for the relation - IdMapper relMapper = idMapping.getIdMapper().prefixMappedProperties(lastPropertyPrefix); + // Storing information about this relation + mainGenerator.getEntitiesConfigurations().get( entityName ).addToOneRelation( + propertyAuditingData.getName(), + referencedEntityName, + relMapper, + insertable + ); - // Storing information about this relation - mainGenerator.getEntitiesConfigurations().get(entityName).addToOneRelation(propertyAuditingData.getName(), - referencedEntityName, relMapper, insertable); - - // Adding mapper for the id - PropertyData propertyData = propertyAuditingData.getPropertyData(); - mapper.addComposite(propertyData, new OneToOnePrimaryKeyJoinColumnMapper(entityName, referencedEntityName, propertyData)); - } + // Adding mapper for the id + final PropertyData propertyData = propertyAuditingData.getPropertyData(); + mapper.addComposite( + propertyData, + new OneToOnePrimaryKeyJoinColumnMapper( entityName, referencedEntityName, propertyData ) + ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/AnnotationsMetadataReader.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/AnnotationsMetadataReader.java index 0a3b5d512e..88f21f9f44 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/AnnotationsMetadataReader.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/AnnotationsMetadataReader.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.configuration.internal.metadata.reader; + import java.lang.annotation.Annotation; import java.util.Iterator; @@ -39,6 +40,7 @@ import org.hibernate.mapping.Property; /** * A helper class to read versioning meta-data from annotations on a persistent class. + * * @author Adam Warski (adam at warski dot org) * @author Sebastian Komander */ @@ -53,8 +55,9 @@ public final class AnnotationsMetadataReader { */ private final ClassAuditingData auditData; - public AnnotationsMetadataReader(GlobalConfiguration globalCfg, ReflectionManager reflectionManager, - PersistentClass pc) { + public AnnotationsMetadataReader( + GlobalConfiguration globalCfg, ReflectionManager reflectionManager, + PersistentClass pc) { this.globalCfg = globalCfg; this.reflectionManager = reflectionManager; this.pc = pc; @@ -63,71 +66,95 @@ public final class AnnotationsMetadataReader { } private ModificationStore getDefaultAudited(XClass clazz) { - Audited defaultAudited = clazz.getAnnotation(Audited.class); + final Audited defaultAudited = clazz.getAnnotation( Audited.class ); - if (defaultAudited != null) { + if ( defaultAudited != null ) { return defaultAudited.modStore(); - } else { + } + else { return null; } } private void addAuditTable(XClass clazz) { - AuditTable auditTable = clazz.getAnnotation(AuditTable.class); - if (auditTable != null) { - auditData.setAuditTable(auditTable); - } else { - auditData.setAuditTable(getDefaultAuditTable()); + final AuditTable auditTable = clazz.getAnnotation( AuditTable.class ); + if ( auditTable != null ) { + auditData.setAuditTable( auditTable ); + } + else { + auditData.setAuditTable( getDefaultAuditTable() ); } } private void addAuditSecondaryTables(XClass clazz) { // Getting information on secondary tables - SecondaryAuditTable secondaryVersionsTable1 = clazz.getAnnotation(SecondaryAuditTable.class); - if (secondaryVersionsTable1 != null) { - auditData.getSecondaryTableDictionary().put(secondaryVersionsTable1.secondaryTableName(), - secondaryVersionsTable1.secondaryAuditTableName()); + final SecondaryAuditTable secondaryVersionsTable1 = clazz.getAnnotation( SecondaryAuditTable.class ); + if ( secondaryVersionsTable1 != null ) { + auditData.getSecondaryTableDictionary().put( + secondaryVersionsTable1.secondaryTableName(), + secondaryVersionsTable1.secondaryAuditTableName() + ); } - SecondaryAuditTables secondaryAuditTables = clazz.getAnnotation(SecondaryAuditTables.class); - if (secondaryAuditTables != null) { - for (SecondaryAuditTable secondaryAuditTable2 : secondaryAuditTables.value()) { - auditData.getSecondaryTableDictionary().put(secondaryAuditTable2.secondaryTableName(), - secondaryAuditTable2.secondaryAuditTableName()); + final SecondaryAuditTables secondaryAuditTables = clazz.getAnnotation( SecondaryAuditTables.class ); + if ( secondaryAuditTables != null ) { + for ( SecondaryAuditTable secondaryAuditTable2 : secondaryAuditTables.value() ) { + auditData.getSecondaryTableDictionary().put( + secondaryAuditTable2.secondaryTableName(), + secondaryAuditTable2.secondaryAuditTableName() + ); } } } public ClassAuditingData getAuditData() { - if (pc.getClassName() == null) { + if ( pc.getClassName() == null ) { return auditData; } try { - XClass xclass = reflectionManager.classForName(pc.getClassName(), this.getClass()); + final XClass xclass = reflectionManager.classForName( pc.getClassName(), this.getClass() ); - ModificationStore defaultStore = getDefaultAudited(xclass); - if (defaultStore != null) { - auditData.setDefaultAudited(true); + final ModificationStore defaultStore = getDefaultAudited( xclass ); + if ( defaultStore != null ) { + auditData.setDefaultAudited( true ); } - new AuditedPropertiesReader(defaultStore, new PersistentClassPropertiesSource(xclass), auditData, - globalCfg, reflectionManager, "").read(); + new AuditedPropertiesReader( + defaultStore, + new PersistentClassPropertiesSource( xclass ), + auditData, + globalCfg, + reflectionManager, + "" + ).read(); - addAuditTable(xclass); - addAuditSecondaryTables(xclass); - } catch (ClassNotFoundException e) { - throw new MappingException(e); + addAuditTable( xclass ); + addAuditSecondaryTables( xclass ); + } + catch (ClassNotFoundException e) { + throw new MappingException( e ); } return auditData; } private AuditTable defaultAuditTable = new AuditTable() { - public String value() { return ""; } - public String schema() { return ""; } - public String catalog() { return ""; } - public Class annotationType() { return this.getClass(); } + public String value() { + return ""; + } + + public String schema() { + return ""; + } + + public String catalog() { + return ""; + } + + public Class annotationType() { + return this.getClass(); + } }; private AuditTable getDefaultAuditTable() { @@ -137,11 +164,21 @@ public final class AnnotationsMetadataReader { private class PersistentClassPropertiesSource implements PersistentPropertiesSource { private final XClass xclass; - private PersistentClassPropertiesSource(XClass xclass) { this.xclass = xclass; } + private PersistentClassPropertiesSource(XClass xclass) { + this.xclass = xclass; + } @SuppressWarnings({"unchecked"}) - public Iterator getPropertyIterator() { return pc.getPropertyIterator(); } - public Property getProperty(String propertyName) { return pc.getProperty(propertyName); } - public XClass getXClass() { return xclass; } + public Iterator getPropertyIterator() { + return pc.getPropertyIterator(); + } + + public Property getProperty(String propertyName) { + return pc.getProperty( propertyName ); + } + + public XClass getXClass() { + return xclass; + } } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/AuditedPropertiesHolder.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/AuditedPropertiesHolder.java index 5cd511c74b..73e488013a 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/AuditedPropertiesHolder.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/AuditedPropertiesHolder.java @@ -1,14 +1,39 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.configuration.internal.metadata.reader; /** * Implementations hold other audited properties. + * * @author Adam Warski (adam at warski dot org) * @author Hern&aacut;n Chanfreau */ public interface AuditedPropertiesHolder { /** * Add an audited property. + * * @param propertyName Name of the audited property. * @param auditingData Data for the audited property. */ @@ -16,19 +41,20 @@ public interface AuditedPropertiesHolder { /** * @param propertyName Name of a property. + * * @return Auditing data for the property. */ PropertyAuditingData getPropertyAuditingData(String propertyName); - - + + /** * @return true if the holder contains any audited property */ boolean isEmpty(); - + /** * @return true if the holder contains the given audited property */ boolean contains(String propertyName); - + } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/AuditedPropertiesReader.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/AuditedPropertiesReader.java index feab0942e4..a76050504a 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/AuditedPropertiesReader.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/AuditedPropertiesReader.java @@ -1,5 +1,32 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.configuration.internal.metadata.reader; +import javax.persistence.JoinColumn; +import javax.persistence.MapKey; +import javax.persistence.OneToMany; +import javax.persistence.Version; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.Collections; @@ -7,10 +34,6 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; -import javax.persistence.JoinColumn; -import javax.persistence.MapKey; -import javax.persistence.OneToMany; -import javax.persistence.Version; import org.hibernate.MappingException; import org.hibernate.annotations.common.reflection.ReflectionManager; @@ -65,12 +88,13 @@ public class AuditedPropertiesReader { private final Set overriddenAuditedClasses; private final Set overriddenNotAuditedClasses; - public AuditedPropertiesReader(ModificationStore defaultStore, - PersistentPropertiesSource persistentPropertiesSource, - AuditedPropertiesHolder auditedPropertiesHolder, - GlobalConfiguration globalCfg, - ReflectionManager reflectionManager, - String propertyNamePrefix) { + public AuditedPropertiesReader( + ModificationStore defaultStore, + PersistentPropertiesSource persistentPropertiesSource, + AuditedPropertiesHolder auditedPropertiesHolder, + GlobalConfiguration globalCfg, + ReflectionManager reflectionManager, + String propertyNamePrefix) { this.defaultStore = defaultStore; this.persistentPropertiesSource = persistentPropertiesSource; this.auditedPropertiesHolder = auditedPropertiesHolder; @@ -93,245 +117,300 @@ public class AuditedPropertiesReader { // First reading the access types for the persistent properties. readPersistentPropertiesAccess(); - // Retrieve classes and properties that are explicitly marked for auditing process by any superclass - // of currently mapped entity or itself. - XClass clazz = persistentPropertiesSource.getXClass(); - readAuditOverrides(clazz); + // Retrieve classes and properties that are explicitly marked for auditing process by any superclass + // of currently mapped entity or itself. + final XClass clazz = persistentPropertiesSource.getXClass(); + readAuditOverrides( clazz ); - // Adding all properties from the given class. - addPropertiesFromClass(clazz); + // Adding all properties from the given class. + addPropertiesFromClass( clazz ); } - /** - * Recursively constructs sets of audited and not audited properties and classes which behavior has been overridden - * using {@link AuditOverride} annotation. - * @param clazz Class that is being processed. Currently mapped entity shall be passed during first invocation. - */ - private void readAuditOverrides(XClass clazz) { - /* TODO: Code to remove with @Audited.auditParents - start. */ - Audited allClassAudited = clazz.getAnnotation(Audited.class); - if (allClassAudited != null && allClassAudited.auditParents().length > 0) { - for (Class c : allClassAudited.auditParents()) { - XClass parentClass = reflectionManager.toXClass(c); - checkSuperclass(clazz, parentClass); - if (!overriddenNotAuditedClasses.contains(parentClass)) { - // If the class has not been marked as not audited by the subclass. - overriddenAuditedClasses.add(parentClass); - } - } - } + /** + * Recursively constructs sets of audited and not audited properties and classes which behavior has been overridden + * using {@link AuditOverride} annotation. + * + * @param clazz Class that is being processed. Currently mapped entity shall be passed during first invocation. + */ + private void readAuditOverrides(XClass clazz) { + /* TODO: Code to remove with @Audited.auditParents - start. */ + final Audited allClassAudited = clazz.getAnnotation( Audited.class ); + if ( allClassAudited != null && allClassAudited.auditParents().length > 0 ) { + for ( Class c : allClassAudited.auditParents() ) { + final XClass parentClass = reflectionManager.toXClass( c ); + checkSuperclass( clazz, parentClass ); + if ( !overriddenNotAuditedClasses.contains( parentClass ) ) { + // If the class has not been marked as not audited by the subclass. + overriddenAuditedClasses.add( parentClass ); + } + } + } /* TODO: Code to remove with @Audited.auditParents - finish. */ - List auditOverrides = computeAuditOverrides(clazz); - for (AuditOverride auditOverride : auditOverrides) { - if (auditOverride.forClass() != void.class) { - XClass overrideClass = reflectionManager.toXClass(auditOverride.forClass()); - checkSuperclass(clazz, overrideClass); - String propertyName = auditOverride.name(); - if (!StringTools.isEmpty(propertyName)) { - // Override @Audited annotation on property level. - XProperty property = getProperty(overrideClass, propertyName); - if (auditOverride.isAudited()) { - if (!overriddenNotAuditedProperties.contains(property)) { - // If the property has not been marked as not audited by the subclass. - overriddenAuditedProperties.add(property); - } - } else { - if (!overriddenAuditedProperties.contains(property)) { - // If the property has not been marked as audited by the subclass. - overriddenNotAuditedProperties.add(property); - } - } - } else { - // Override @Audited annotation on class level. - if (auditOverride.isAudited()) { - if (!overriddenNotAuditedClasses.contains(overrideClass)) { - // If the class has not been marked as not audited by the subclass. - overriddenAuditedClasses.add(overrideClass); - } - } else { - if (!overriddenAuditedClasses.contains(overrideClass)) { - // If the class has not been marked as audited by the subclass. - overriddenNotAuditedClasses.add(overrideClass); - } - } - } - } - } - XClass superclass = clazz.getSuperclass(); - if (!clazz.isInterface() && !Object.class.getName().equals(superclass.getName())) { - readAuditOverrides(superclass); - } - } + final List auditOverrides = computeAuditOverrides( clazz ); + for ( AuditOverride auditOverride : auditOverrides ) { + if ( auditOverride.forClass() != void.class ) { + final XClass overrideClass = reflectionManager.toXClass( auditOverride.forClass() ); + checkSuperclass( clazz, overrideClass ); + final String propertyName = auditOverride.name(); + if ( !StringTools.isEmpty( propertyName ) ) { + // Override @Audited annotation on property level. + final XProperty property = getProperty( overrideClass, propertyName ); + if ( auditOverride.isAudited() ) { + if ( !overriddenNotAuditedProperties.contains( property ) ) { + // If the property has not been marked as not audited by the subclass. + overriddenAuditedProperties.add( property ); + } + } + else { + if ( !overriddenAuditedProperties.contains( property ) ) { + // If the property has not been marked as audited by the subclass. + overriddenNotAuditedProperties.add( property ); + } + } + } + else { + // Override @Audited annotation on class level. + if ( auditOverride.isAudited() ) { + if ( !overriddenNotAuditedClasses.contains( overrideClass ) ) { + // If the class has not been marked as not audited by the subclass. + overriddenAuditedClasses.add( overrideClass ); + } + } + else { + if ( !overriddenAuditedClasses.contains( overrideClass ) ) { + // If the class has not been marked as audited by the subclass. + overriddenNotAuditedClasses.add( overrideClass ); + } + } + } + } + } + final XClass superclass = clazz.getSuperclass(); + if ( !clazz.isInterface() && !Object.class.getName().equals( superclass.getName() ) ) { + readAuditOverrides( superclass ); + } + } - /** - * @param clazz Source class. - * @return List of @AuditOverride annotations applied at class level. - */ - private List computeAuditOverrides(XClass clazz) { - AuditOverrides auditOverrides = clazz.getAnnotation(AuditOverrides.class); - AuditOverride auditOverride = clazz.getAnnotation(AuditOverride.class); - if (auditOverrides == null && auditOverride != null) { - return Arrays.asList(auditOverride); - } else if (auditOverrides != null && auditOverride == null) { - return Arrays.asList(auditOverrides.value()); - } else if (auditOverrides != null && auditOverride != null) { - throw new MappingException("@AuditOverrides annotation should encapsulate all @AuditOverride declarations. " + - "Please revise Envers annotations applied to class " + clazz.getName() + "."); - } - return Collections.EMPTY_LIST; - } + /** + * @param clazz Source class. + * + * @return List of @AuditOverride annotations applied at class level. + */ + private List computeAuditOverrides(XClass clazz) { + final AuditOverrides auditOverrides = clazz.getAnnotation( AuditOverrides.class ); + final AuditOverride auditOverride = clazz.getAnnotation( AuditOverride.class ); + if ( auditOverrides == null && auditOverride != null ) { + return Arrays.asList( auditOverride ); + } + else if ( auditOverrides != null && auditOverride == null ) { + return Arrays.asList( auditOverrides.value() ); + } + else if ( auditOverrides != null && auditOverride != null ) { + throw new MappingException( + "@AuditOverrides annotation should encapsulate all @AuditOverride declarations. " + + "Please revise Envers annotations applied to class " + clazz.getName() + "." + ); + } + return Collections.emptyList(); + } - /** - * Checks whether one class is assignable from another. If not {@link MappingException} is thrown. - * @param child Subclass. - * @param parent Superclass. - */ - private void checkSuperclass(XClass child, XClass parent) { - if (!parent.isAssignableFrom(child)) { - throw new MappingException("Class " + parent.getName() + " is not assignable from " + child.getName() + ". " + - "Please revise Envers annotations applied to " + child.getName() + " type."); - } - } + /** + * Checks whether one class is assignable from another. If not {@link MappingException} is thrown. + * + * @param child Subclass. + * @param parent Superclass. + */ + private void checkSuperclass(XClass child, XClass parent) { + if ( !parent.isAssignableFrom( child ) ) { + throw new MappingException( + "Class " + parent.getName() + " is not assignable from " + child.getName() + ". " + + "Please revise Envers annotations applied to " + child.getName() + " type." + ); + } + } - /** - * Checks whether class contains property with a given name. If not {@link MappingException} is thrown. - * @param clazz Class. - * @param propertyName Property name. - * @return Property object. - */ - private XProperty getProperty(XClass clazz, String propertyName) { - XProperty property = ReflectionTools.getProperty(clazz, propertyName); - if (property == null) { - throw new MappingException("Property '" + propertyName + "' not found in class " + clazz.getName() + ". " + - "Please revise Envers annotations applied to class " + persistentPropertiesSource.getXClass() + "."); - } - return property; - } + /** + * Checks whether class contains property with a given name. If not {@link MappingException} is thrown. + * + * @param clazz Class. + * @param propertyName Property name. + * + * @return Property object. + */ + private XProperty getProperty(XClass clazz, String propertyName) { + final XProperty property = ReflectionTools.getProperty( clazz, propertyName ); + if ( property == null ) { + throw new MappingException( + "Property '" + propertyName + "' not found in class " + clazz.getName() + ". " + + "Please revise Envers annotations applied to class " + persistentPropertiesSource.getXClass() + "." + ); + } + return property; + } private void readPersistentPropertiesAccess() { - Iterator propertyIter = persistentPropertiesSource.getPropertyIterator(); - while (propertyIter.hasNext()) { - Property property = propertyIter.next(); - addPersistentProperty(property); - if ("embedded".equals(property.getPropertyAccessorName()) && property.getName().equals(property.getNodeName())) { + final Iterator propertyIter = persistentPropertiesSource.getPropertyIterator(); + while ( propertyIter.hasNext() ) { + final Property property = propertyIter.next(); + addPersistentProperty( property ); + if ( "embedded".equals( property.getPropertyAccessorName() ) && property.getName() + .equals( property.getNodeName() ) ) { // If property name equals node name and embedded accessor type is used, processing component // has been defined with tag. See HHH-6636 JIRA issue. - createPropertiesGroupMapping(property); + createPropertiesGroupMapping( property ); } } } - private void addPersistentProperty(Property property) { - if ("field".equals(property.getPropertyAccessorName())) { - fieldAccessedPersistentProperties.add(property.getName()); - } else { - propertyAccessedPersistentProperties.add(property.getName()); - } - } + private void addPersistentProperty(Property property) { + if ( "field".equals( property.getPropertyAccessorName() ) ) { + fieldAccessedPersistentProperties.add( property.getName() ); + } + else { + propertyAccessedPersistentProperties.add( property.getName() ); + } + } - private void createPropertiesGroupMapping(Property property) { - Component component = (Component) property.getValue(); - Iterator componentProperties = component.getPropertyIterator(); - while (componentProperties.hasNext()) { - Property componentProperty = componentProperties.next(); - propertiesGroupMapping.put(componentProperty.getName(), component.getNodeName()); - } - } + @SuppressWarnings("unchecked") + private void createPropertiesGroupMapping(Property property) { + final Component component = (Component) property.getValue(); + final Iterator componentProperties = component.getPropertyIterator(); + while ( componentProperties.hasNext() ) { + final Property componentProperty = componentProperties.next(); + propertiesGroupMapping.put( componentProperty.getName(), component.getNodeName() ); + } + } - /** - * @param clazz Class which properties are currently being added. - * @return {@link Audited} annotation of specified class. If processed type hasn't been explicitly marked, method - * checks whether given class exists in {@link AuditedPropertiesReader#overriddenAuditedClasses} collection. - * In case of success, {@link Audited} configuration of currently mapped entity is returned, otherwise - * {@code null}. If processed type exists in {@link AuditedPropertiesReader#overriddenNotAuditedClasses} - * collection, the result is also {@code null}. - */ - private Audited computeAuditConfiguration(XClass clazz) { - Audited allClassAudited = clazz.getAnnotation(Audited.class); - // If processed class is not explicitly marked with @Audited annotation, check whether auditing is - // forced by any of its child entities configuration (@AuditedOverride.forClass). - if (allClassAudited == null && overriddenAuditedClasses.contains(clazz)) { - // Declared audited parent copies @Audited.modStore and @Audited.targetAuditMode configuration from - // currently mapped entity. - allClassAudited = persistentPropertiesSource.getXClass().getAnnotation(Audited.class); - if (allClassAudited == null) { - // If parent class declares @Audited on the field/property level. - allClassAudited = DEFAULT_AUDITED; - } - } else if (allClassAudited != null && overriddenNotAuditedClasses.contains(clazz)) { - return null; - } - return allClassAudited; - } + /** + * @param clazz Class which properties are currently being added. + * + * @return {@link Audited} annotation of specified class. If processed type hasn't been explicitly marked, method + * checks whether given class exists in {@link AuditedPropertiesReader#overriddenAuditedClasses} collection. + * In case of success, {@link Audited} configuration of currently mapped entity is returned, otherwise + * {@code null}. If processed type exists in {@link AuditedPropertiesReader#overriddenNotAuditedClasses} + * collection, the result is also {@code null}. + */ + private Audited computeAuditConfiguration(XClass clazz) { + Audited allClassAudited = clazz.getAnnotation( Audited.class ); + // If processed class is not explicitly marked with @Audited annotation, check whether auditing is + // forced by any of its child entities configuration (@AuditedOverride.forClass). + if ( allClassAudited == null && overriddenAuditedClasses.contains( clazz ) ) { + // Declared audited parent copies @Audited.modStore and @Audited.targetAuditMode configuration from + // currently mapped entity. + allClassAudited = persistentPropertiesSource.getXClass().getAnnotation( Audited.class ); + if ( allClassAudited == null ) { + // If parent class declares @Audited on the field/property level. + allClassAudited = DEFAULT_AUDITED; + } + } + else if ( allClassAudited != null && overriddenNotAuditedClasses.contains( clazz ) ) { + return null; + } + return allClassAudited; + } - /** - * Recursively adds all audited properties of entity class and its superclasses. - * @param clazz Currently processed class. - */ - private void addPropertiesFromClass(XClass clazz) { - Audited allClassAudited = computeAuditConfiguration(clazz); + /** + * Recursively adds all audited properties of entity class and its superclasses. + * + * @param clazz Currently processed class. + */ + private void addPropertiesFromClass(XClass clazz) { + final Audited allClassAudited = computeAuditConfiguration( clazz ); //look in the class - addFromProperties(clazz.getDeclaredProperties("field"), "field", fieldAccessedPersistentProperties, allClassAudited); - addFromProperties(clazz.getDeclaredProperties("property"), "property", propertyAccessedPersistentProperties, allClassAudited); - - if(allClassAudited != null || !auditedPropertiesHolder.isEmpty()) { - XClass superclazz = clazz.getSuperclass(); - if (!clazz.isInterface() && !"java.lang.Object".equals(superclazz.getName())) { - addPropertiesFromClass(superclazz); + addFromProperties( + clazz.getDeclaredProperties( "field" ), + "field", + fieldAccessedPersistentProperties, + allClassAudited + ); + addFromProperties( + clazz.getDeclaredProperties( "property" ), + "property", + propertyAccessedPersistentProperties, + allClassAudited + ); + + if ( allClassAudited != null || !auditedPropertiesHolder.isEmpty() ) { + final XClass superclazz = clazz.getSuperclass(); + if ( !clazz.isInterface() && !"java.lang.Object".equals( superclazz.getName() ) ) { + addPropertiesFromClass( superclazz ); } } } - private void addFromProperties(Iterable properties, String accessType, Set persistentProperties, Audited allClassAudited) { - for (XProperty property : properties) { + private void addFromProperties( + Iterable properties, + String accessType, + Set persistentProperties, + Audited allClassAudited) { + for ( XProperty property : properties ) { // If this is not a persistent property, with the same access type as currently checked, // it's not audited as well. // If the property was already defined by the subclass, is ignored by superclasses - if ((persistentProperties.contains(property.getName()) && (!auditedPropertiesHolder - .contains(property.getName())))) { - Value propertyValue = persistentPropertiesSource.getProperty(property.getName()).getValue(); - if (propertyValue instanceof Component) { - this.addFromComponentProperty(property, accessType, (Component)propertyValue, allClassAudited); - } else { - this.addFromNotComponentProperty(property, accessType, allClassAudited); + if ( persistentProperties.contains( property.getName() ) + && !auditedPropertiesHolder.contains( property.getName() ) ) { + final Value propertyValue = persistentPropertiesSource.getProperty( property.getName() ).getValue(); + if ( propertyValue instanceof Component ) { + this.addFromComponentProperty( property, accessType, (Component) propertyValue, allClassAudited ); } - } else if (propertiesGroupMapping.containsKey(property.getName())) { + else { + this.addFromNotComponentProperty( property, accessType, allClassAudited ); + } + } + else if ( propertiesGroupMapping.containsKey( property.getName() ) ) { // Retrieve embedded component name based on class field. - final String embeddedName = propertiesGroupMapping.get(property.getName()); - if (!auditedPropertiesHolder.contains(embeddedName)) { + final String embeddedName = propertiesGroupMapping.get( property.getName() ); + if ( !auditedPropertiesHolder.contains( embeddedName ) ) { // Manage properties mapped within tag. - Value propertyValue = persistentPropertiesSource.getProperty(embeddedName).getValue(); - this.addFromPropertiesGroup(embeddedName, property, accessType, (Component)propertyValue, allClassAudited); + final Value propertyValue = persistentPropertiesSource.getProperty( embeddedName ).getValue(); + this.addFromPropertiesGroup( + embeddedName, + property, + accessType, + (Component) propertyValue, + allClassAudited + ); } } } } - private void addFromPropertiesGroup(String embeddedName, XProperty property, String accessType, Component propertyValue, - Audited allClassAudited) { - ComponentAuditingData componentData = new ComponentAuditingData(); - boolean isAudited = fillPropertyData(property, componentData, accessType, allClassAudited); - if (isAudited) { + private void addFromPropertiesGroup( + String embeddedName, + XProperty property, + String accessType, + Component propertyValue, + Audited allClassAudited) { + final ComponentAuditingData componentData = new ComponentAuditingData(); + final boolean isAudited = fillPropertyData( property, componentData, accessType, allClassAudited ); + if ( isAudited ) { // EntityPersister.getPropertyNames() returns name of embedded component instead of class field. - componentData.setName(embeddedName); + componentData.setName( embeddedName ); // Marking component properties as placed directly in class (not inside another component). - componentData.setBeanName(null); + componentData.setBeanName( null ); - PersistentPropertiesSource componentPropertiesSource = new ComponentPropertiesSource( reflectionManager, propertyValue ); - AuditedPropertiesReader audPropReader = new AuditedPropertiesReader( + final PersistentPropertiesSource componentPropertiesSource = new ComponentPropertiesSource( + reflectionManager, + propertyValue + ); + final AuditedPropertiesReader audPropReader = new AuditedPropertiesReader( ModificationStore.FULL, componentPropertiesSource, componentData, globalCfg, reflectionManager, - propertyNamePrefix + MappingTools.createComponentPrefix(embeddedName) + propertyNamePrefix + MappingTools.createComponentPrefix( embeddedName ) ); audPropReader.read(); - auditedPropertiesHolder.addPropertyAuditingData(embeddedName, componentData); + auditedPropertiesHolder.addPropertyAuditingData( embeddedName, componentData ); } } - private void addFromComponentProperty(XProperty property, String accessType, Component propertyValue, Audited allClassAudited) { - ComponentAuditingData componentData = new ComponentAuditingData(); - boolean isAudited = fillPropertyData( property, componentData, accessType, allClassAudited ); + private void addFromComponentProperty( + XProperty property, + String accessType, + Component propertyValue, + Audited allClassAudited) { + final ComponentAuditingData componentData = new ComponentAuditingData(); + final boolean isAudited = fillPropertyData( property, componentData, accessType, allClassAudited ); if ( propertyValue.isDynamic() ) { if ( isAudited ) { @@ -343,12 +422,16 @@ public class AuditedPropertiesReader { return; } - PersistentPropertiesSource componentPropertiesSource = new ComponentPropertiesSource( + final PersistentPropertiesSource componentPropertiesSource = new ComponentPropertiesSource( reflectionManager, propertyValue ); - ComponentAuditedPropertiesReader audPropReader = new ComponentAuditedPropertiesReader( - ModificationStore.FULL, componentPropertiesSource, componentData, globalCfg, reflectionManager, + final ComponentAuditedPropertiesReader audPropReader = new ComponentAuditedPropertiesReader( + ModificationStore.FULL, + componentPropertiesSource, + componentData, + globalCfg, + reflectionManager, propertyNamePrefix + MappingTools.createComponentPrefix( property.getName() ) ); audPropReader.read(); @@ -359,85 +442,102 @@ public class AuditedPropertiesReader { } } - private void addFromNotComponentProperty(XProperty property, String accessType, Audited allClassAudited){ - PropertyAuditingData propertyData = new PropertyAuditingData(); - boolean isAudited = fillPropertyData(property, propertyData, accessType, allClassAudited); + private void addFromNotComponentProperty(XProperty property, String accessType, Audited allClassAudited) { + final PropertyAuditingData propertyData = new PropertyAuditingData(); + final boolean isAudited = fillPropertyData( property, propertyData, accessType, allClassAudited ); - if (isAudited) { + if ( isAudited ) { // Now we know that the property is audited - auditedPropertiesHolder.addPropertyAuditingData(property.getName(), propertyData); + auditedPropertiesHolder.addPropertyAuditingData( property.getName(), propertyData ); } } - - + + /** * Checks if a property is audited and if yes, fills all of its data. + * * @param property Property to check. * @param propertyData Property data, on which to set this property's modification store. * @param accessType Access type for the property. + * * @return False if this property is not audited. */ - private boolean fillPropertyData(XProperty property, PropertyAuditingData propertyData, - String accessType, Audited allClassAudited) { + private boolean fillPropertyData( + XProperty property, + PropertyAuditingData propertyData, + String accessType, + Audited allClassAudited) { // check if a property is declared as not audited to exclude it // useful if a class is audited but some properties should be excluded - NotAudited unVer = property.getAnnotation(NotAudited.class); - if ((unVer != null && !overriddenAuditedProperties.contains(property)) || overriddenNotAuditedProperties.contains(property)) { + final NotAudited unVer = property.getAnnotation( NotAudited.class ); + if ( (unVer != null + && !overriddenAuditedProperties.contains( property )) + || overriddenNotAuditedProperties.contains( property ) ) { return false; - } else { + } + else { // if the optimistic locking field has to be unversioned and the current property // is the optimistic locking field, don't audit it - if (globalCfg.isDoNotAuditOptimisticLockingField()) { - Version jpaVer = property.getAnnotation(Version.class); - if (jpaVer != null) { + if ( globalCfg.isDoNotAuditOptimisticLockingField() ) { + final Version jpaVer = property.getAnnotation( Version.class ); + if ( jpaVer != null ) { return false; } } } - - if(!this.checkAudited(property, propertyData, allClassAudited)){ + + if ( !this.checkAudited( property, propertyData, allClassAudited ) ) { return false; } - String propertyName = propertyNamePrefix + property.getName(); - propertyData.setName(propertyName); + final String propertyName = propertyNamePrefix + property.getName(); + propertyData.setName( propertyName ); propertyData.setModifiedFlagName( - MetadataTools.getModifiedFlagPropertyName( - propertyName, - globalCfg.getModifiedFlagSuffix())); - propertyData.setBeanName(property.getName()); - propertyData.setAccessType(accessType); + MetadataTools.getModifiedFlagPropertyName( + propertyName, + globalCfg.getModifiedFlagSuffix() + ) + ); + propertyData.setBeanName( property.getName() ); + propertyData.setAccessType( accessType ); - addPropertyJoinTables(property, propertyData); - addPropertyAuditingOverrides(property, propertyData); - if (!processPropertyAuditingOverrides(property, propertyData)) { - return false; // not audited due to AuditOverride annotation + addPropertyJoinTables( property, propertyData ); + addPropertyAuditingOverrides( property, propertyData ); + if ( !processPropertyAuditingOverrides( property, propertyData ) ) { + // not audited due to AuditOverride annotation + return false; } - addPropertyMapKey(property, propertyData); - setPropertyAuditMappedBy(property, propertyData); - setPropertyRelationMappedBy(property, propertyData); + addPropertyMapKey( property, propertyData ); + setPropertyAuditMappedBy( property, propertyData ); + setPropertyRelationMappedBy( property, propertyData ); return true; } - protected boolean checkAudited(XProperty property, + protected boolean checkAudited( + XProperty property, PropertyAuditingData propertyData, Audited allClassAudited) { // Checking if this property is explicitly audited or if all properties are. - Audited aud = (property.isAnnotationPresent(Audited.class)) ? (property.getAnnotation(Audited.class)) : allClassAudited; - if (aud == null && overriddenAuditedProperties.contains(property) && !overriddenNotAuditedProperties.contains(property)) { + Audited aud = (property.isAnnotationPresent( Audited.class )) + ? property.getAnnotation( Audited.class ) + : allClassAudited; + if ( aud == null + && overriddenAuditedProperties.contains( property ) + && !overriddenNotAuditedProperties.contains( property ) ) { // Assigning @Audited defaults. If anyone needs to customize those values in the future, // appropriate fields shall be added to @AuditOverride annotation. aud = DEFAULT_AUDITED; } - if (aud != null) { - propertyData.setStore(aud.modStore()); - propertyData.setRelationTargetAuditMode(aud.targetAuditMode()); - propertyData.setUsingModifiedFlag(checkUsingModifiedFlag(aud)); + if ( aud != null ) { + propertyData.setStore( aud.modStore() ); + propertyData.setRelationTargetAuditMode( aud.targetAuditMode() ); + propertyData.setUsingModifiedFlag( checkUsingModifiedFlag( aud ) ); return true; - } else { + } + else { return false; } } @@ -447,121 +547,172 @@ public class AuditedPropertiesReader { globalCfg.isGlobalWithModifiedFlag() : aud.withModifiedFlag(); } - private void setPropertyRelationMappedBy(XProperty property, PropertyAuditingData propertyData) { - OneToMany oneToMany = property.getAnnotation(OneToMany.class); - if (oneToMany != null && !"".equals(oneToMany.mappedBy())) { - propertyData.setRelationMappedBy(oneToMany.mappedBy()); - } - } + private void setPropertyRelationMappedBy(XProperty property, PropertyAuditingData propertyData) { + final OneToMany oneToMany = property.getAnnotation( OneToMany.class ); + if ( oneToMany != null && !"".equals( oneToMany.mappedBy() ) ) { + propertyData.setRelationMappedBy( oneToMany.mappedBy() ); + } + } private void setPropertyAuditMappedBy(XProperty property, PropertyAuditingData propertyData) { - AuditMappedBy auditMappedBy = property.getAnnotation(AuditMappedBy.class); - if (auditMappedBy != null) { - propertyData.setAuditMappedBy(auditMappedBy.mappedBy()); - if (!"".equals(auditMappedBy.positionMappedBy())) { - propertyData.setPositionMappedBy(auditMappedBy.positionMappedBy()); - } - } - } + final AuditMappedBy auditMappedBy = property.getAnnotation( AuditMappedBy.class ); + if ( auditMappedBy != null ) { + propertyData.setAuditMappedBy( auditMappedBy.mappedBy() ); + if ( !"".equals( auditMappedBy.positionMappedBy() ) ) { + propertyData.setPositionMappedBy( auditMappedBy.positionMappedBy() ); + } + } + } private void addPropertyMapKey(XProperty property, PropertyAuditingData propertyData) { - MapKey mapKey = property.getAnnotation(MapKey.class); - if (mapKey != null) { - propertyData.setMapKey(mapKey.name()); + final MapKey mapKey = property.getAnnotation( MapKey.class ); + if ( mapKey != null ) { + propertyData.setMapKey( mapKey.name() ); } } private void addPropertyJoinTables(XProperty property, PropertyAuditingData propertyData) { // first set the join table based on the AuditJoinTable annotation - AuditJoinTable joinTable = property.getAnnotation(AuditJoinTable.class); - if (joinTable != null) { - propertyData.setJoinTable(joinTable); - } else { - propertyData.setJoinTable(DEFAULT_AUDIT_JOIN_TABLE); + final AuditJoinTable joinTable = property.getAnnotation( AuditJoinTable.class ); + if ( joinTable != null ) { + propertyData.setJoinTable( joinTable ); + } + else { + propertyData.setJoinTable( DEFAULT_AUDIT_JOIN_TABLE ); } } - /*** + /** * Add the {@link AuditOverride} annotations. * * @param property the property being processed * @param propertyData the Envers auditing data for this property */ private void addPropertyAuditingOverrides(XProperty property, PropertyAuditingData propertyData) { - AuditOverride annotationOverride = property.getAnnotation(AuditOverride.class); - if (annotationOverride != null) { - propertyData.addAuditingOverride(annotationOverride); + final AuditOverride annotationOverride = property.getAnnotation( AuditOverride.class ); + if ( annotationOverride != null ) { + propertyData.addAuditingOverride( annotationOverride ); } - AuditOverrides annotationOverrides = property.getAnnotation(AuditOverrides.class); - if (annotationOverrides != null) { - propertyData.addAuditingOverrides(annotationOverrides); + final AuditOverrides annotationOverrides = property.getAnnotation( AuditOverrides.class ); + if ( annotationOverrides != null ) { + propertyData.addAuditingOverrides( annotationOverrides ); } } /** * Process the {@link AuditOverride} annotations for this property. * - * @param property - * the property for which the {@link AuditOverride} - * annotations are being processed - * @param propertyData - * the Envers auditing data for this property + * @param property the property for which the {@link AuditOverride} + * annotations are being processed + * @param propertyData the Envers auditing data for this property + * * @return {@code false} if isAudited() of the override annotation was set to */ private boolean processPropertyAuditingOverrides(XProperty property, PropertyAuditingData propertyData) { // if this property is part of a component, process all override annotations - if (this.auditedPropertiesHolder instanceof ComponentAuditingData) { - List overrides = ((ComponentAuditingData) this.auditedPropertiesHolder).getAuditingOverrides(); - for (AuditOverride override : overrides) { - if (property.getName().equals(override.name())) { + if ( this.auditedPropertiesHolder instanceof ComponentAuditingData ) { + final List overrides = ( (ComponentAuditingData) this.auditedPropertiesHolder ).getAuditingOverrides(); + for ( AuditOverride override : overrides ) { + if ( property.getName().equals( override.name() ) ) { // the override applies to this property - if (!override.isAudited()) { + if ( !override.isAudited() ) { return false; - } else { - if (override.auditJoinTable() != null) { - propertyData.setJoinTable(override.auditJoinTable()); + } + else { + if ( override.auditJoinTable() != null ) { + propertyData.setJoinTable( override.auditJoinTable() ); } } } } - + } return true; } - private static Audited DEFAULT_AUDITED = new Audited() { - public ModificationStore modStore() { return ModificationStore.FULL; } - public RelationTargetAuditMode targetAuditMode() { return RelationTargetAuditMode.AUDITED; } - public Class[] auditParents() { return new Class[0]; } - public boolean withModifiedFlag() { return false; } - public Class annotationType() { return this.getClass(); } - }; + private static final Audited DEFAULT_AUDITED = new Audited() { + @Override + public ModificationStore modStore() { + return ModificationStore.FULL; + } - private static AuditJoinTable DEFAULT_AUDIT_JOIN_TABLE = new AuditJoinTable() { - public String name() { return ""; } - public String schema() { return ""; } - public String catalog() { return ""; } - public JoinColumn[] inverseJoinColumns() { return new JoinColumn[0]; } - public Class annotationType() { return this.getClass(); } + @Override + public RelationTargetAuditMode targetAuditMode() { + return RelationTargetAuditMode.AUDITED; + } + + @Override + public Class[] auditParents() { + return new Class[0]; + } + + @Override + public boolean withModifiedFlag() { + return false; + } + + @Override + public Class annotationType() { + return this.getClass(); + } }; - public static class ComponentPropertiesSource implements PersistentPropertiesSource { + private static final AuditJoinTable DEFAULT_AUDIT_JOIN_TABLE = new AuditJoinTable() { + @Override + public String name() { + return ""; + } + + @Override + public String schema() { + return ""; + } + + @Override + public String catalog() { + return ""; + } + + @Override + public JoinColumn[] inverseJoinColumns() { + return new JoinColumn[0]; + } + + @Override + public Class annotationType() { + return this.getClass(); + } + }; + + public static class ComponentPropertiesSource implements PersistentPropertiesSource { private final XClass xclass; private final Component component; public ComponentPropertiesSource(ReflectionManager reflectionManager, Component component) { try { - this.xclass = reflectionManager.classForName(component.getComponentClassName(), this.getClass()); - } catch (ClassNotFoundException e) { - throw new MappingException(e); + this.xclass = reflectionManager.classForName( component.getComponentClassName(), this.getClass() ); + } + catch (ClassNotFoundException e) { + throw new MappingException( e ); } this.component = component; } + @Override @SuppressWarnings({"unchecked"}) - public Iterator getPropertyIterator() { return component.getPropertyIterator(); } - public Property getProperty(String propertyName) { return component.getProperty(propertyName); } - public XClass getXClass() { return xclass; } + public Iterator getPropertyIterator() { + return component.getPropertyIterator(); + } + + @Override + public Property getProperty(String propertyName) { + return component.getProperty( propertyName ); + } + + @Override + public XClass getXClass() { + return xclass; + } } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/ClassAuditingData.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/ClassAuditingData.java index 785c11fd75..ed20a7f5bf 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/ClassAuditingData.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/ClassAuditingData.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.configuration.internal.metadata.reader; + import java.util.Map; import org.hibernate.envers.AuditTable; @@ -32,12 +33,12 @@ import static org.hibernate.envers.internal.tools.Tools.newHashMap; * @author Adam Warski (adam at warski dot org) * @author Sebastian Komander * @author Hern&aacut;n Chanfreau -*/ + */ public class ClassAuditingData implements AuditedPropertiesHolder { - private final Map properties; - private final Map secondaryTableDictionary; + private final Map properties; + private final Map secondaryTableDictionary; - private AuditTable auditTable; + private AuditTable auditTable; /** * True if the class is audited globally (this helps to cover the cases when there are no fields in the class, @@ -45,48 +46,52 @@ public class ClassAuditingData implements AuditedPropertiesHolder { */ private boolean defaultAudited; - public ClassAuditingData() { - properties = newHashMap(); - secondaryTableDictionary = newHashMap(); - } - - public boolean isEmpty() { - return properties.isEmpty(); - } - - public void addPropertyAuditingData(String propertyName, PropertyAuditingData auditingData) { - properties.put(propertyName, auditingData); + public ClassAuditingData() { + properties = newHashMap(); + secondaryTableDictionary = newHashMap(); } - public PropertyAuditingData getPropertyAuditingData(String propertyName) { - return properties.get(propertyName); - } + @Override + public boolean isEmpty() { + return properties.isEmpty(); + } - public Iterable getPropertyNames() { - return properties.keySet(); - } + @Override + public void addPropertyAuditingData(String propertyName, PropertyAuditingData auditingData) { + properties.put( propertyName, auditingData ); + } - public Map getSecondaryTableDictionary() { - return secondaryTableDictionary; - } + @Override + public PropertyAuditingData getPropertyAuditingData(String propertyName) { + return properties.get( propertyName ); + } - public AuditTable getAuditTable() { - return auditTable; - } + public Iterable getPropertyNames() { + return properties.keySet(); + } - public void setAuditTable(AuditTable auditTable) { - this.auditTable = auditTable; - } + public Map getSecondaryTableDictionary() { + return secondaryTableDictionary; + } + + public AuditTable getAuditTable() { + return auditTable; + } + + public void setAuditTable(AuditTable auditTable) { + this.auditTable = auditTable; + } public void setDefaultAudited(boolean defaultAudited) { this.defaultAudited = defaultAudited; } public boolean isAudited() { - return defaultAudited || properties.size() > 0; - } - + return defaultAudited || properties.size() > 0; + } + + @Override public boolean contains(String propertyName) { - return properties.containsKey(propertyName); + return properties.containsKey( propertyName ); } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/ComponentAuditedPropertiesReader.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/ComponentAuditedPropertiesReader.java index 3e970cfe78..fa7d250237 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/ComponentAuditedPropertiesReader.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/ComponentAuditedPropertiesReader.java @@ -1,4 +1,28 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.configuration.internal.metadata.reader; + import org.hibernate.annotations.common.reflection.ReflectionManager; import org.hibernate.annotations.common.reflection.XProperty; import org.hibernate.envers.Audited; @@ -7,34 +31,40 @@ import org.hibernate.envers.configuration.internal.GlobalConfiguration; /** * Reads the audited properties for components. - * + * * @author Hern&aacut;n Chanfreau * @author Michal Skowronek (mskowr at o2 dot pl) */ public class ComponentAuditedPropertiesReader extends AuditedPropertiesReader { - public ComponentAuditedPropertiesReader(ModificationStore defaultStore, + public ComponentAuditedPropertiesReader( + ModificationStore defaultStore, PersistentPropertiesSource persistentPropertiesSource, AuditedPropertiesHolder auditedPropertiesHolder, GlobalConfiguration globalCfg, ReflectionManager reflectionManager, String propertyNamePrefix) { - super(defaultStore, persistentPropertiesSource, auditedPropertiesHolder, - globalCfg, reflectionManager, propertyNamePrefix); + super( + defaultStore, persistentPropertiesSource, auditedPropertiesHolder, + globalCfg, reflectionManager, propertyNamePrefix + ); } - + @Override - protected boolean checkAudited(XProperty property, - PropertyAuditingData propertyData, Audited allClassAudited) { + protected boolean checkAudited( + XProperty property, + PropertyAuditingData propertyData, + Audited allClassAudited) { // Checking if this property is explicitly audited or if all properties are. - Audited aud = property.getAnnotation(Audited.class); - if (aud != null) { - propertyData.setStore(aud.modStore()); - propertyData.setRelationTargetAuditMode(aud.targetAuditMode()); - propertyData.setUsingModifiedFlag(checkUsingModifiedFlag(aud)); - } else { - propertyData.setStore(ModificationStore.FULL); - } - return true; + final Audited aud = property.getAnnotation( Audited.class ); + if ( aud != null ) { + propertyData.setStore( aud.modStore() ); + propertyData.setRelationTargetAuditMode( aud.targetAuditMode() ); + propertyData.setUsingModifiedFlag( checkUsingModifiedFlag( aud ) ); + } + else { + propertyData.setStore( ModificationStore.FULL ); + } + return true; } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/ComponentAuditingData.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/ComponentAuditingData.java index 60c3ff2299..754c26bc60 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/ComponentAuditingData.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/ComponentAuditingData.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,9 +20,9 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.envers.configuration.internal.metadata.reader; + import java.util.Map; import java.util.Set; @@ -30,6 +30,7 @@ import static org.hibernate.envers.internal.tools.Tools.newHashMap; /** * Audit mapping meta-data for component. + * * @author Adam Warski (adam at warski dot org) * @author Hern&aacut;n Chanfreau */ @@ -40,21 +41,25 @@ public class ComponentAuditingData extends PropertyAuditingData implements Audit this.properties = newHashMap(); } + @Override public boolean isEmpty() { return properties.isEmpty(); } + @Override public void addPropertyAuditingData(String propertyName, PropertyAuditingData auditingData) { - properties.put(propertyName, auditingData); + properties.put( propertyName, auditingData ); } - public PropertyAuditingData getPropertyAuditingData(String propertyName) { - return properties.get(propertyName); - } - - public boolean contains(String propertyName) { - return properties.containsKey(propertyName); - } + @Override + public PropertyAuditingData getPropertyAuditingData(String propertyName) { + return properties.get( propertyName ); + } + + @Override + public boolean contains(String propertyName) { + return properties.containsKey( propertyName ); + } public Set getPropertyNames() { return properties.keySet(); diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/PersistentPropertiesSource.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/PersistentPropertiesSource.java index 864d5382b7..b4832e5f91 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/PersistentPropertiesSource.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/PersistentPropertiesSource.java @@ -1,4 +1,28 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.configuration.internal.metadata.reader; + import java.util.Iterator; import org.hibernate.annotations.common.reflection.XClass; @@ -6,10 +30,13 @@ import org.hibernate.mapping.Property; /** * A source of data on persistent properties of a class or component. + * * @author Adam Warski (adam at warski dot org) */ public interface PersistentPropertiesSource { Iterator getPropertyIterator(); + Property getProperty(String propertyName); + XClass getXClass(); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/PropertyAuditingData.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/PropertyAuditingData.java index 500ad95403..85d4424c8d 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/PropertyAuditingData.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/PropertyAuditingData.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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,9 +20,9 @@ * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA - * */ package org.hibernate.envers.configuration.internal.metadata.reader; + import java.util.ArrayList; import java.util.List; @@ -38,45 +38,46 @@ import org.hibernate.envers.internal.entities.PropertyData; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class PropertyAuditingData { - private String name; + private String name; private String beanName; - private ModificationStore store; - private String mapKey; - private AuditJoinTable joinTable; - private String accessType; - private final List auditJoinTableOverrides = new ArrayList(0); + private ModificationStore store; + private String mapKey; + private AuditJoinTable joinTable; + private String accessType; + private final List auditJoinTableOverrides = new ArrayList( 0 ); private RelationTargetAuditMode relationTargetAuditMode; - private String auditMappedBy; - private String relationMappedBy; - private String positionMappedBy; - private boolean forceInsertable; + private String auditMappedBy; + private String relationMappedBy; + private String positionMappedBy; + private boolean forceInsertable; private boolean usingModifiedFlag; private String modifiedFlagName; public PropertyAuditingData() { - } + } - public PropertyAuditingData(String name, String accessType, ModificationStore store, - RelationTargetAuditMode relationTargetAuditMode, - String auditMappedBy, String positionMappedBy, - boolean forceInsertable) { - this.name = name; + public PropertyAuditingData( + String name, String accessType, ModificationStore store, + RelationTargetAuditMode relationTargetAuditMode, + String auditMappedBy, String positionMappedBy, + boolean forceInsertable) { + this.name = name; this.beanName = name; - this.accessType = accessType; - this.store = store; + this.accessType = accessType; + this.store = store; this.relationTargetAuditMode = relationTargetAuditMode; - this.auditMappedBy = auditMappedBy; - this.positionMappedBy = positionMappedBy; - this.forceInsertable = forceInsertable; - } + this.auditMappedBy = auditMappedBy; + this.positionMappedBy = positionMappedBy; + this.forceInsertable = forceInsertable; + } public String getName() { - return name; - } + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } public String getBeanName() { return beanName; @@ -87,77 +88,79 @@ public class PropertyAuditingData { } public ModificationStore getStore() { - return store; - } + return store; + } - public void setStore(ModificationStore store) { - this.store = store; - } + public void setStore(ModificationStore store) { + this.store = store; + } - public String getMapKey() { - return mapKey; - } + public String getMapKey() { + return mapKey; + } - public void setMapKey(String mapKey) { - this.mapKey = mapKey; - } + public void setMapKey(String mapKey) { + this.mapKey = mapKey; + } - public AuditJoinTable getJoinTable() { - return joinTable; - } + public AuditJoinTable getJoinTable() { + return joinTable; + } - public void setJoinTable(AuditJoinTable joinTable) { - this.joinTable = joinTable; - } + public void setJoinTable(AuditJoinTable joinTable) { + this.joinTable = joinTable; + } - public String getAccessType() { - return accessType; - } + public String getAccessType() { + return accessType; + } - public void setAccessType(String accessType) { - this.accessType = accessType; - } + public void setAccessType(String accessType) { + this.accessType = accessType; + } - public PropertyData getPropertyData() { - return new PropertyData(name, beanName, accessType, store, - usingModifiedFlag, modifiedFlagName); - } + public PropertyData getPropertyData() { + return new PropertyData( + name, beanName, accessType, store, + usingModifiedFlag, modifiedFlagName + ); + } public List getAuditingOverrides() { return auditJoinTableOverrides; } - public String getAuditMappedBy() { - return auditMappedBy; - } + public String getAuditMappedBy() { + return auditMappedBy; + } - public void setAuditMappedBy(String auditMappedBy) { - this.auditMappedBy = auditMappedBy; - } + public void setAuditMappedBy(String auditMappedBy) { + this.auditMappedBy = auditMappedBy; + } - public String getRelationMappedBy() { - return relationMappedBy; - } + public String getRelationMappedBy() { + return relationMappedBy; + } - public void setRelationMappedBy(String relationMappedBy) { - this.relationMappedBy = relationMappedBy; - } + public void setRelationMappedBy(String relationMappedBy) { + this.relationMappedBy = relationMappedBy; + } - public String getPositionMappedBy() { - return positionMappedBy; - } + public String getPositionMappedBy() { + return positionMappedBy; + } - public void setPositionMappedBy(String positionMappedBy) { - this.positionMappedBy = positionMappedBy; - } + public void setPositionMappedBy(String positionMappedBy) { + this.positionMappedBy = positionMappedBy; + } - public boolean isForceInsertable() { - return forceInsertable; - } + public boolean isForceInsertable() { + return forceInsertable; + } - public void setForceInsertable(boolean forceInsertable) { - this.forceInsertable = forceInsertable; - } + public void setForceInsertable(boolean forceInsertable) { + this.forceInsertable = forceInsertable; + } public boolean isUsingModifiedFlag() { return usingModifiedFlag; @@ -172,25 +175,25 @@ public class PropertyAuditingData { } public void addAuditingOverride(AuditOverride annotation) { - if (annotation != null) { - String overrideName = annotation.name(); + if ( annotation != null ) { + final String overrideName = annotation.name(); boolean present = false; - for (AuditOverride current : auditJoinTableOverrides) { - if (current.name().equals(overrideName)) { + for ( AuditOverride current : auditJoinTableOverrides ) { + if ( current.name().equals( overrideName ) ) { present = true; break; } } - if (!present) { - auditJoinTableOverrides.add(annotation); + if ( !present ) { + auditJoinTableOverrides.add( annotation ); } } } public void addAuditingOverrides(AuditOverrides annotationOverrides) { - if (annotationOverrides != null) { - for (AuditOverride annotation : annotationOverrides.value()) { - addAuditingOverride(annotation); + if ( annotationOverrides != null ) { + for ( AuditOverride annotation : annotationOverrides.value() ) { + addAuditingOverride( annotation ); } } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/spi/AuditConfiguration.java b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/spi/AuditConfiguration.java index ce32b2c187..2675a1a541 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/configuration/spi/AuditConfiguration.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/configuration/spi/AuditConfiguration.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -107,30 +107,30 @@ public class AuditConfiguration { public AuditConfiguration(Configuration cfg, ClassLoaderService classLoaderService) { // TODO: Temporarily allow Envers to continuing using // hibernate-commons-annotations' for reflection and class loading. - ClassLoader tccl = Thread.currentThread().getContextClassLoader(); + final ClassLoader tccl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader( ClassLoaderHelper.getContextClassLoader() ); - - Properties properties = cfg.getProperties(); - ReflectionManager reflectionManager = cfg.getReflectionManager(); - globalCfg = new GlobalConfiguration( properties, classLoaderService ); - RevisionInfoConfiguration revInfoCfg = new RevisionInfoConfiguration( globalCfg ); - RevisionInfoConfigurationResult revInfoCfgResult = revInfoCfg.configure( cfg, reflectionManager ); - auditEntCfg = new AuditEntitiesConfiguration( properties, revInfoCfgResult.getRevisionInfoEntityName() ); - auditProcessManager = new AuditProcessManager( revInfoCfgResult.getRevisionInfoGenerator() ); - revisionInfoQueryCreator = revInfoCfgResult.getRevisionInfoQueryCreator(); - revisionInfoNumberReader = revInfoCfgResult.getRevisionInfoNumberReader(); - modifiedEntityNamesReader = revInfoCfgResult.getModifiedEntityNamesReader(); + final Properties properties = cfg.getProperties(); + + final ReflectionManager reflectionManager = cfg.getReflectionManager(); + this.globalCfg = new GlobalConfiguration( properties, classLoaderService ); + final RevisionInfoConfiguration revInfoCfg = new RevisionInfoConfiguration( globalCfg ); + final RevisionInfoConfigurationResult revInfoCfgResult = revInfoCfg.configure( cfg, reflectionManager ); + this.auditEntCfg = new AuditEntitiesConfiguration( properties, revInfoCfgResult.getRevisionInfoEntityName() ); + this.auditProcessManager = new AuditProcessManager( revInfoCfgResult.getRevisionInfoGenerator() ); + this.revisionInfoQueryCreator = revInfoCfgResult.getRevisionInfoQueryCreator(); + this.revisionInfoNumberReader = revInfoCfgResult.getRevisionInfoNumberReader(); + this.modifiedEntityNamesReader = revInfoCfgResult.getModifiedEntityNamesReader(); this.classLoaderService = classLoaderService; - auditStrategy = initializeAuditStrategy( + this.auditStrategy = initializeAuditStrategy( revInfoCfgResult.getRevisionInfoClass(), revInfoCfgResult.getRevisionInfoTimestampData() ); - entCfg = new EntitiesConfigurator().configure( + this.entCfg = new EntitiesConfigurator().configure( cfg, reflectionManager, globalCfg, auditEntCfg, auditStrategy, classLoaderService, revInfoCfgResult.getRevisionInfoXmlMapping(), revInfoCfgResult.getRevisionInfoRelationMapping() ); - + Thread.currentThread().setContextClassLoader( tccl ); } @@ -143,11 +143,14 @@ public class AuditConfiguration { auditStrategyClass = this.getClass().getClassLoader().loadClass( auditEntCfg.getAuditStrategyName() ); } catch (Exception e) { - auditStrategyClass = ReflectionTools.loadClass( auditEntCfg.getAuditStrategyName(), classLoaderService ); + auditStrategyClass = ReflectionTools.loadClass( + auditEntCfg.getAuditStrategyName(), + classLoaderService + ); } - strategy = (AuditStrategy) ReflectHelper.getDefaultConstructor(auditStrategyClass).newInstance(); + strategy = (AuditStrategy) ReflectHelper.getDefaultConstructor( auditStrategyClass ).newInstance(); } - catch ( Exception e ) { + catch (Exception e) { throw new MappingException( String.format( "Unable to create AuditStrategy[%s] instance.", auditEntCfg.getAuditStrategyName() ), e @@ -156,27 +159,25 @@ public class AuditConfiguration { if ( strategy instanceof ValidityAuditStrategy ) { // further initialization required - Getter revisionTimestampGetter = ReflectionTools.getGetter( revisionInfoClass, revisionInfoTimestampData ); + final Getter revisionTimestampGetter = ReflectionTools.getGetter( revisionInfoClass, revisionInfoTimestampData ); ( (ValidityAuditStrategy) strategy ).setRevisionTimestampGetter( revisionTimestampGetter ); } return strategy; } - // - - private static Map cfgs = new WeakHashMap(); + private static final Map CFGS = new WeakHashMap(); public synchronized static AuditConfiguration getFor(Configuration cfg) { return getFor( cfg, null ); } public synchronized static AuditConfiguration getFor(Configuration cfg, ClassLoaderService classLoaderService) { - AuditConfiguration verCfg = cfgs.get( cfg ); + AuditConfiguration verCfg = CFGS.get( cfg ); if ( verCfg == null ) { verCfg = new AuditConfiguration( cfg, classLoaderService ); - cfgs.put( cfg, verCfg ); + CFGS.put( cfg, verCfg ); cfg.buildMappings(); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/enhanced/OrderedSequenceGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/enhanced/OrderedSequenceGenerator.java index 9747280269..d25753b39e 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/enhanced/OrderedSequenceGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/enhanced/OrderedSequenceGenerator.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.enhanced; import org.hibernate.HibernateException; @@ -8,6 +31,7 @@ import org.hibernate.internal.util.StringHelper; /** * Revision number generator has to produce values in ascending order (gaps may occur). + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class OrderedSequenceGenerator extends SequenceStyleGenerator { diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/enhanced/SequenceIdRevisionEntity.java b/hibernate-envers/src/main/java/org/hibernate/envers/enhanced/SequenceIdRevisionEntity.java index 41a78fdebc..540f629693 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/enhanced/SequenceIdRevisionEntity.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/enhanced/SequenceIdRevisionEntity.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -23,13 +23,13 @@ */ package org.hibernate.envers.enhanced; -import java.io.Serializable; -import java.text.DateFormat; -import java.util.Date; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import javax.persistence.Transient; +import java.io.Serializable; +import java.text.DateFormat; +import java.util.Date; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @@ -42,64 +42,72 @@ import org.hibernate.envers.RevisionTimestamp; */ @MappedSuperclass public class SequenceIdRevisionEntity implements Serializable { - private static final long serialVersionUID = 4159156677698841902L; - - @Id - @GeneratedValue(generator = "RevisionNumberSequenceGenerator") - @GenericGenerator(name = "RevisionNumberSequenceGenerator", - strategy = "org.hibernate.envers.enhanced.OrderedSequenceGenerator", - parameters = {@Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "sequence_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1") - } - ) - @RevisionNumber - private int id; + private static final long serialVersionUID = 4159156677698841902L; - @RevisionTimestamp - private long timestamp; + @Id + @GeneratedValue(generator = "RevisionNumberSequenceGenerator") + @GenericGenerator( + name = "RevisionNumberSequenceGenerator", + strategy = "org.hibernate.envers.enhanced.OrderedSequenceGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "sequence_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1") + } + ) + @RevisionNumber + private int id; - public int getId() { - return id; - } + @RevisionTimestamp + private long timestamp; - public void setId(int id) { - this.id = id; - } + public int getId() { + return id; + } - @Transient - public Date getRevisionDate() { - return new Date(timestamp); - } + public void setId(int id) { + this.id = id; + } - public long getTimestamp() { - return timestamp; - } + @Transient + public Date getRevisionDate() { + return new Date( timestamp ); + } - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } + public long getTimestamp() { + return timestamp; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SequenceIdRevisionEntity )) return false; + @SuppressWarnings("UnusedDeclaration") + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } - SequenceIdRevisionEntity that = (SequenceIdRevisionEntity) o; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SequenceIdRevisionEntity) ) { + return false; + } - if (id != that.id) return false; - if (timestamp != that.timestamp) return false; + final SequenceIdRevisionEntity that = (SequenceIdRevisionEntity) o; + return id == that.id && timestamp == that.timestamp; + } - return true; - } + @Override + public int hashCode() { + int result = id; + result = 31 * result + (int) (timestamp ^ (timestamp >>> 32)); + return result; + } - public int hashCode() { - int result = id; - result = 31 * result + (int) (timestamp ^ (timestamp >>> 32)); - return result; - } - - public String toString() { - return "SequenceIdRevisionEntity(id = " + id + ", revisionDate = " + DateFormat.getDateTimeInstance().format(getRevisionDate()) + ")"; - } + @Override + public String toString() { + return "SequenceIdRevisionEntity(id = " + id + ", revisionDate = " + DateFormat.getDateTimeInstance().format( + getRevisionDate() + ) + ")"; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/enhanced/SequenceIdTrackingModifiedEntitiesRevisionEntity.java b/hibernate-envers/src/main/java/org/hibernate/envers/enhanced/SequenceIdTrackingModifiedEntitiesRevisionEntity.java index 889cd723cb..3c037b6ffb 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/enhanced/SequenceIdTrackingModifiedEntitiesRevisionEntity.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/enhanced/SequenceIdTrackingModifiedEntitiesRevisionEntity.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -23,14 +23,14 @@ */ package org.hibernate.envers.enhanced; -import java.util.HashSet; -import java.util.Set; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.MappedSuperclass; +import java.util.HashSet; +import java.util.Set; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; @@ -40,45 +40,60 @@ import org.hibernate.envers.ModifiedEntityNames; * Extension of standard {@link SequenceIdRevisionEntity} that allows tracking entity names changed in each revision. * This revision entity is implicitly used when {@code org.hibernate.envers.track_entities_changed_in_revision} * parameter is set to {@code true}. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @MappedSuperclass public class SequenceIdTrackingModifiedEntitiesRevisionEntity extends SequenceIdRevisionEntity { - @ElementCollection(fetch = FetchType.EAGER) - @JoinTable(name = "REVCHANGES", joinColumns = @JoinColumn(name = "REV")) - @Column(name = "ENTITYNAME") - @Fetch(FetchMode.JOIN) - @ModifiedEntityNames - private Set modifiedEntityNames = new HashSet(); + @ElementCollection(fetch = FetchType.EAGER) + @JoinTable(name = "REVCHANGES", joinColumns = @JoinColumn(name = "REV")) + @Column(name = "ENTITYNAME") + @Fetch(FetchMode.JOIN) + @ModifiedEntityNames + private Set modifiedEntityNames = new HashSet(); - public Set getModifiedEntityNames() { - return modifiedEntityNames; - } + @SuppressWarnings("UnusedDeclaration") + public Set getModifiedEntityNames() { + return modifiedEntityNames; + } - public void setModifiedEntityNames(Set modifiedEntityNames) { - this.modifiedEntityNames = modifiedEntityNames; - } + @SuppressWarnings("UnusedDeclaration") + public void setModifiedEntityNames(Set modifiedEntityNames) { + this.modifiedEntityNames = modifiedEntityNames; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SequenceIdTrackingModifiedEntitiesRevisionEntity )) return false; - if (!super.equals(o)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SequenceIdTrackingModifiedEntitiesRevisionEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - SequenceIdTrackingModifiedEntitiesRevisionEntity that = (SequenceIdTrackingModifiedEntitiesRevisionEntity) o; + final SequenceIdTrackingModifiedEntitiesRevisionEntity that = (SequenceIdTrackingModifiedEntitiesRevisionEntity) o; - if (modifiedEntityNames != null ? !modifiedEntityNames.equals(that.modifiedEntityNames) - : that.modifiedEntityNames != null) return false; + if ( modifiedEntityNames == null ) { + return that.modifiedEntityNames == null; + } + else { + return modifiedEntityNames.equals( that.modifiedEntityNames ); + } + } - return true; - } + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (modifiedEntityNames != null ? modifiedEntityNames.hashCode() : 0); + return result; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (modifiedEntityNames != null ? modifiedEntityNames.hashCode() : 0); - return result; - } - - public String toString() { - return "SequenceIdTrackingModifiedEntitiesRevisionEntity(" + super.toString() + ", modifiedEntityNames = " + modifiedEntityNames + ")"; - } + @Override + public String toString() { + return "SequenceIdTrackingModifiedEntitiesRevisionEntity(" + super.toString() + + ", modifiedEntityNames = " + modifiedEntityNames + ")"; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/BaseEnversCollectionEventListener.java b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/BaseEnversCollectionEventListener.java index b8fe96286f..ab7a00547a 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/BaseEnversCollectionEventListener.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/BaseEnversCollectionEventListener.java @@ -57,40 +57,40 @@ public abstract class BaseEnversCollectionEventListener extends BaseEnversEventL super( enversConfiguration ); } - protected final CollectionEntry getCollectionEntry(AbstractCollectionEvent event) { - return event.getSession().getPersistenceContext().getCollectionEntry(event.getCollection()); - } + protected final CollectionEntry getCollectionEntry(AbstractCollectionEvent event) { + return event.getSession().getPersistenceContext().getCollectionEntry( event.getCollection() ); + } - protected final void onCollectionAction( + protected final void onCollectionAction( AbstractCollectionEvent event, PersistentCollection newColl, Serializable oldColl, CollectionEntry collectionEntry) { - if ( shouldGenerateRevision( event ) ) { - checkIfTransactionInProgress(event.getSession()); - - AuditProcess auditProcess = getAuditConfiguration().getSyncManager().get(event.getSession()); + if ( shouldGenerateRevision( event ) ) { + checkIfTransactionInProgress( event.getSession() ); - String entityName = event.getAffectedOwnerEntityName(); - String ownerEntityName = ((AbstractCollectionPersister) collectionEntry.getLoadedPersister()).getOwnerEntityName(); - String referencingPropertyName = collectionEntry.getRole().substring(ownerEntityName.length() + 1); + final AuditProcess auditProcess = getAuditConfiguration().getSyncManager().get( event.getSession() ); - // Checking if this is not a "fake" many-to-one bidirectional relation. The relation description may be - // null in case of collections of non-entities. - RelationDescription rd = searchForRelationDescription( entityName, referencingPropertyName ); - if ( rd != null && rd.getMappedByPropertyName() != null ) { - generateFakeBidirecationalRelationWorkUnits( + final String entityName = event.getAffectedOwnerEntityName(); + final String ownerEntityName = ((AbstractCollectionPersister) collectionEntry.getLoadedPersister()).getOwnerEntityName(); + final String referencingPropertyName = collectionEntry.getRole().substring( ownerEntityName.length() + 1 ); + + // Checking if this is not a "fake" many-to-one bidirectional relation. The relation description may be + // null in case of collections of non-entities. + final RelationDescription rd = searchForRelationDescription( entityName, referencingPropertyName ); + if ( rd != null && rd.getMappedByPropertyName() != null ) { + generateFakeBidirecationalRelationWorkUnits( auditProcess, newColl, oldColl, entityName, - referencingPropertyName, + referencingPropertyName, event, rd ); - } + } else { - PersistentCollectionChangeWorkUnit workUnit = new PersistentCollectionChangeWorkUnit( + final PersistentCollectionChangeWorkUnit workUnit = new PersistentCollectionChangeWorkUnit( event.getSession(), entityName, getAuditConfiguration(), @@ -102,9 +102,9 @@ public abstract class BaseEnversCollectionEventListener extends BaseEnversEventL ); auditProcess.addWorkUnit( workUnit ); - if (workUnit.containsWork()) { - // There are some changes: a revision needs also be generated for the collection owner - auditProcess.addWorkUnit( + if ( workUnit.containsWork() ) { + // There are some changes: a revision needs also be generated for the collection owner + auditProcess.addWorkUnit( new CollectionChangeWorkUnit( event.getSession(), event.getAffectedOwnerEntityName(), @@ -115,15 +115,17 @@ public abstract class BaseEnversCollectionEventListener extends BaseEnversEventL ) ); - generateBidirectionalCollectionChangeWorkUnits( auditProcess, event, workUnit, rd ); - } - } - } - } + generateBidirectionalCollectionChangeWorkUnits( auditProcess, event, workUnit, rd ); + } + } + } + } /** * Forces persistent collection initialization. + * * @param event Collection event. + * * @return Stored snapshot. */ protected Serializable initializeCollection(AbstractCollectionEvent event) { @@ -133,7 +135,9 @@ public abstract class BaseEnversCollectionEventListener extends BaseEnversEventL /** * Checks whether modification of not-owned relation field triggers new revision and owner entity is versioned. + * * @param event Collection event. + * * @return {@code true} if revision based on given event should be generated, {@code false} otherwise. */ protected boolean shouldGenerateRevision(AbstractCollectionEvent event) { @@ -142,27 +146,27 @@ public abstract class BaseEnversCollectionEventListener extends BaseEnversEventL && getAuditConfiguration().getEntCfg().isVersioned( entityName ); } - /** - * Looks up a relation description corresponding to the given property in the given entity. If no description is - * found in the given entity, the parent entity is checked (so that inherited relations work). + /** + * Looks up a relation description corresponding to the given property in the given entity. If no description is + * found in the given entity, the parent entity is checked (so that inherited relations work). * - * @param entityName Name of the entity, in which to start looking. - * @param referencingPropertyName The name of the property. - * - * @return A found relation description corresponding to the given entity or {@code null}, if no description can - * be found. - */ - private RelationDescription searchForRelationDescription(String entityName, String referencingPropertyName) { - EntityConfiguration configuration = getAuditConfiguration().getEntCfg().get( entityName ); - RelationDescription rd = configuration.getRelationDescription(referencingPropertyName); - if ( rd == null && configuration.getParentEntityName() != null ) { - return searchForRelationDescription( configuration.getParentEntityName(), referencingPropertyName ); - } + * @param entityName Name of the entity, in which to start looking. + * @param referencingPropertyName The name of the property. + * + * @return A found relation description corresponding to the given entity or {@code null}, if no description can + * be found. + */ + private RelationDescription searchForRelationDescription(String entityName, String referencingPropertyName) { + final EntityConfiguration configuration = getAuditConfiguration().getEntCfg().get( entityName ); + final RelationDescription rd = configuration.getRelationDescription( referencingPropertyName ); + if ( rd == null && configuration.getParentEntityName() != null ) { + return searchForRelationDescription( configuration.getParentEntityName(), referencingPropertyName ); + } - return rd; - } + return rd; + } - private void generateFakeBidirecationalRelationWorkUnits( + private void generateFakeBidirecationalRelationWorkUnits( AuditProcess auditProcess, PersistentCollection newColl, Serializable oldColl, @@ -170,41 +174,47 @@ public abstract class BaseEnversCollectionEventListener extends BaseEnversEventL String referencingPropertyName, AbstractCollectionEvent event, RelationDescription rd) { - // First computing the relation changes - List collectionChanges = getAuditConfiguration() + // First computing the relation changes + final List collectionChanges = getAuditConfiguration() .getEntCfg() .get( collectionEntityName ) .getPropertyMapper() - .mapCollectionChanges( event.getSession(), referencingPropertyName, newColl, oldColl, event.getAffectedOwnerIdOrNull() ); + .mapCollectionChanges( + event.getSession(), + referencingPropertyName, + newColl, + oldColl, + event.getAffectedOwnerIdOrNull() + ); - // Getting the id mapper for the related entity, as the work units generated will corrspond to the related - // entities. - String relatedEntityName = rd.getToEntityName(); - IdMapper relatedIdMapper = getAuditConfiguration().getEntCfg().get(relatedEntityName).getIdMapper(); + // Getting the id mapper for the related entity, as the work units generated will correspond to the related + // entities. + final String relatedEntityName = rd.getToEntityName(); + final IdMapper relatedIdMapper = getAuditConfiguration().getEntCfg().get( relatedEntityName ).getIdMapper(); - // For each collection change, generating the bidirectional work unit. - for ( PersistentCollectionChangeData changeData : collectionChanges ) { - Object relatedObj = changeData.getChangedElement(); - Serializable relatedId = (Serializable) relatedIdMapper.mapToIdFromEntity(relatedObj); - RevisionType revType = (RevisionType) changeData.getData().get( + // For each collection change, generating the bidirectional work unit. + for ( PersistentCollectionChangeData changeData : collectionChanges ) { + final Object relatedObj = changeData.getChangedElement(); + final Serializable relatedId = (Serializable) relatedIdMapper.mapToIdFromEntity( relatedObj ); + final RevisionType revType = (RevisionType) changeData.getData().get( getAuditConfiguration().getAuditEntCfg().getRevisionTypePropName() ); - // This can be different from relatedEntityName, in case of inheritance (the real entity may be a subclass - // of relatedEntityName). - String realRelatedEntityName = event.getSession().bestGuessEntityName(relatedObj); + // This can be different from relatedEntityName, in case of inheritance (the real entity may be a subclass + // of relatedEntityName). + final String realRelatedEntityName = event.getSession().bestGuessEntityName( relatedObj ); - // By default, the nested work unit is a collection change work unit. - AuditWorkUnit nestedWorkUnit = new CollectionChangeWorkUnit( + // By default, the nested work unit is a collection change work unit. + final AuditWorkUnit nestedWorkUnit = new CollectionChangeWorkUnit( event.getSession(), realRelatedEntityName, rd.getMappedByPropertyName(), getAuditConfiguration(), - relatedId, + relatedId, relatedObj ); - auditProcess.addWorkUnit( + auditProcess.addWorkUnit( new FakeBidirectionalRelationWorkUnit( event.getSession(), realRelatedEntityName, @@ -218,10 +228,10 @@ public abstract class BaseEnversCollectionEventListener extends BaseEnversEventL nestedWorkUnit ) ); - } + } - // We also have to generate a collection change work unit for the owning entity. - auditProcess.addWorkUnit( + // We also have to generate a collection change work unit for the owning entity. + auditProcess.addWorkUnit( new CollectionChangeWorkUnit( event.getSession(), collectionEntityName, @@ -231,44 +241,47 @@ public abstract class BaseEnversCollectionEventListener extends BaseEnversEventL event.getAffectedOwnerOrNull() ) ); - } + } - private void generateBidirectionalCollectionChangeWorkUnits( + private void generateBidirectionalCollectionChangeWorkUnits( AuditProcess auditProcess, AbstractCollectionEvent event, PersistentCollectionChangeWorkUnit workUnit, RelationDescription rd) { - // Checking if this is enabled in configuration ... - if ( ! getAuditConfiguration().getGlobalCfg().isGenerateRevisionsForCollections() ) { - return; - } + // Checking if this is enabled in configuration ... + if ( !getAuditConfiguration().getGlobalCfg().isGenerateRevisionsForCollections() ) { + return; + } - // Checking if this is not a bidirectional relation - then, a revision needs also be generated for - // the other side of the relation. - // relDesc can be null if this is a collection of simple values (not a relation). - if ( rd != null && rd.isBidirectional() ) { - String relatedEntityName = rd.getToEntityName(); - IdMapper relatedIdMapper = getAuditConfiguration().getEntCfg().get( relatedEntityName ).getIdMapper(); + // Checking if this is not a bidirectional relation - then, a revision needs also be generated for + // the other side of the relation. + // relDesc can be null if this is a collection of simple values (not a relation). + if ( rd != null && rd.isBidirectional() ) { + final String relatedEntityName = rd.getToEntityName(); + final IdMapper relatedIdMapper = getAuditConfiguration().getEntCfg().get( relatedEntityName ).getIdMapper(); - Set toPropertyNames = getAuditConfiguration().getEntCfg() - .getToPropertyNames(event.getAffectedOwnerEntityName(), rd.getFromPropertyName(), relatedEntityName); - String toPropertyName = toPropertyNames.iterator().next(); + final Set toPropertyNames = getAuditConfiguration().getEntCfg().getToPropertyNames( + event.getAffectedOwnerEntityName(), + rd.getFromPropertyName(), + relatedEntityName + ); + final String toPropertyName = toPropertyNames.iterator().next(); - for ( PersistentCollectionChangeData changeData : workUnit.getCollectionChanges() ) { - Object relatedObj = changeData.getChangedElement(); - Serializable relatedId = (Serializable) relatedIdMapper.mapToIdFromEntity( relatedObj ); + for ( PersistentCollectionChangeData changeData : workUnit.getCollectionChanges() ) { + final Object relatedObj = changeData.getChangedElement(); + final Serializable relatedId = (Serializable) relatedIdMapper.mapToIdFromEntity( relatedObj ); - auditProcess.addWorkUnit( + auditProcess.addWorkUnit( new CollectionChangeWorkUnit( event.getSession(), - event.getSession().bestGuessEntityName(relatedObj), + event.getSession().bestGuessEntityName( relatedObj ), toPropertyName, getAuditConfiguration(), relatedId, relatedObj ) ); - } - } - } + } + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/BaseEnversEventListener.java b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/BaseEnversEventListener.java index 6e4e4e2408..f65fcef4a9 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/BaseEnversEventListener.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/BaseEnversEventListener.java @@ -66,72 +66,84 @@ public abstract class BaseEnversEventListener implements EnversListener { Object[] oldState, SessionImplementor session) { // Checking if this is enabled in configuration ... - if ( ! enversConfiguration.getGlobalCfg().isGenerateRevisionsForCollections() ) { + if ( !enversConfiguration.getGlobalCfg().isGenerateRevisionsForCollections() ) { return; } // Checks every property of the entity, if it is an "owned" to-one relation to another entity. // If the value of that property changed, and the relation is bi-directional, a new revision // for the related entity is generated. - String[] propertyNames = entityPersister.getPropertyNames(); + final String[] propertyNames = entityPersister.getPropertyNames(); - for ( int i=0; i toPropertyNames = enversConfiguration.getEntCfg() - .getToPropertyNames(fromEntityName, relDesc.getFromPropertyName(), toEntityName); - String toPropertyName = toPropertyNames.iterator().next(); + final Set toPropertyNames = enversConfiguration.getEntCfg().getToPropertyNames( + fromEntityName, + relDesc.getFromPropertyName(), + toEntityName + ); + final String toPropertyName = toPropertyNames.iterator().next(); - auditProcess.addWorkUnit(new CollectionChangeWorkUnit(session, toEntityName, - toPropertyName, enversConfiguration, id, value)); + auditProcess.addWorkUnit( + new CollectionChangeWorkUnit( + session, toEntityName, + toPropertyName, enversConfiguration, id, value + ) + ); } - protected void checkIfTransactionInProgress(SessionImplementor session) { - if (!session.isTransactionInProgress()) { - // Historical data would not be flushed to audit tables if outside of active transaction - // (AuditProcess#doBeforeTransactionCompletion(SessionImplementor) not executed). - throw new AuditException("Unable to create revision because of non-active transaction"); - } - } + protected void checkIfTransactionInProgress(SessionImplementor session) { + if ( !session.isTransactionInProgress() ) { + // Historical data would not be flushed to audit tables if outside of active transaction + // (AuditProcess#doBeforeTransactionCompletion(SessionImplementor) not executed). + throw new AuditException( "Unable to create revision because of non-active transaction" ); + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversIntegrator.java b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversIntegrator.java index 36abe0f220..6afdc5e10f 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversIntegrator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversIntegrator.java @@ -43,8 +43,15 @@ import org.hibernate.service.spi.SessionFactoryServiceRegistry; * @author Steve Ebersole */ public class EnversIntegrator implements Integrator { - private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, EnversIntegrator.class.getName() ); + private static final CoreMessageLogger LOG = Logger.getMessageLogger( + CoreMessageLogger.class, + EnversIntegrator.class.getName() + ); + /** + * The name of a configuration setting that can be used to control whether auto registration of envers listeners + * should happen or not. Default is true + */ public static final String AUTO_REGISTER = "hibernate.listeners.envers.autoRegister"; @Override @@ -52,25 +59,55 @@ public class EnversIntegrator implements Integrator { Configuration configuration, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) { - final boolean autoRegister = ConfigurationHelper.getBoolean( AUTO_REGISTER, configuration.getProperties(), true ); + final boolean autoRegister = ConfigurationHelper.getBoolean( + AUTO_REGISTER, + configuration.getProperties(), + true + ); if ( !autoRegister ) { LOG.debug( "Skipping Envers listener auto registration" ); return; } - EventListenerRegistry listenerRegistry = serviceRegistry.getService( EventListenerRegistry.class ); + final EventListenerRegistry listenerRegistry = serviceRegistry.getService( EventListenerRegistry.class ); listenerRegistry.addDuplicationStrategy( EnversListenerDuplicationStrategy.INSTANCE ); - final AuditConfiguration enversConfiguration = AuditConfiguration.getFor( configuration, serviceRegistry.getService( ClassLoaderService.class ) ); + final AuditConfiguration enversConfiguration = AuditConfiguration.getFor( + configuration, + serviceRegistry.getService( + ClassLoaderService.class + ) + ); - if (enversConfiguration.getEntCfg().hasAuditedEntities()) { - listenerRegistry.appendListeners( EventType.POST_DELETE, new EnversPostDeleteEventListenerImpl( enversConfiguration ) ); - listenerRegistry.appendListeners( EventType.POST_INSERT, new EnversPostInsertEventListenerImpl( enversConfiguration ) ); - listenerRegistry.appendListeners( EventType.POST_UPDATE, new EnversPostUpdateEventListenerImpl( enversConfiguration ) ); - listenerRegistry.appendListeners( EventType.POST_COLLECTION_RECREATE, new EnversPostCollectionRecreateEventListenerImpl( enversConfiguration ) ); - listenerRegistry.appendListeners( EventType.PRE_COLLECTION_REMOVE, new EnversPreCollectionRemoveEventListenerImpl( enversConfiguration ) ); - listenerRegistry.appendListeners( EventType.PRE_COLLECTION_UPDATE, new EnversPreCollectionUpdateEventListenerImpl( enversConfiguration ) ); - } + if ( enversConfiguration.getEntCfg().hasAuditedEntities() ) { + listenerRegistry.appendListeners( + EventType.POST_DELETE, new EnversPostDeleteEventListenerImpl( + enversConfiguration + ) + ); + listenerRegistry.appendListeners( + EventType.POST_INSERT, new EnversPostInsertEventListenerImpl( + enversConfiguration + ) + ); + listenerRegistry.appendListeners( + EventType.POST_UPDATE, new EnversPostUpdateEventListenerImpl( + enversConfiguration + ) + ); + listenerRegistry.appendListeners( + EventType.POST_COLLECTION_RECREATE, + new EnversPostCollectionRecreateEventListenerImpl( enversConfiguration ) + ); + listenerRegistry.appendListeners( + EventType.PRE_COLLECTION_REMOVE, + new EnversPreCollectionRemoveEventListenerImpl( enversConfiguration ) + ); + listenerRegistry.appendListeners( + EventType.PRE_COLLECTION_UPDATE, + new EnversPreCollectionUpdateEventListenerImpl( enversConfiguration ) + ); + } } @Override @@ -84,9 +121,10 @@ public class EnversIntegrator implements Integrator { * @see org.hibernate.integrator.spi.Integrator#integrate(org.hibernate.metamodel.source.MetadataImplementor, org.hibernate.engine.spi.SessionFactoryImplementor, org.hibernate.service.spi.SessionFactoryServiceRegistry) */ @Override - public void integrate( MetadataImplementor metadata, - SessionFactoryImplementor sessionFactory, - SessionFactoryServiceRegistry serviceRegistry ) { - // TODO: implement + public void integrate( + MetadataImplementor metadata, + SessionFactoryImplementor sessionFactory, + SessionFactoryServiceRegistry serviceRegistry) { + // TODO: implement } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversListener.java b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversListener.java index 9cd8086635..cd8f36ef90 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversListener.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversListener.java @@ -31,5 +31,10 @@ import org.hibernate.envers.configuration.spi.AuditConfiguration; * @author Steve Ebersole */ public interface EnversListener { + /** + * Get the Envers AuditConfiguration + * + * @return The Envers AuditConfiguration + */ public AuditConfiguration getAuditConfiguration(); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversListenerDuplicationStrategy.java b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversListenerDuplicationStrategy.java index d5442adc83..a4a3c4b55d 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversListenerDuplicationStrategy.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversListenerDuplicationStrategy.java @@ -31,6 +31,9 @@ import org.hibernate.event.service.spi.DuplicationStrategy; * @author Steve Ebersole */ public class EnversListenerDuplicationStrategy implements DuplicationStrategy { + /** + * Singleton access + */ public static final EnversListenerDuplicationStrategy INSTANCE = new EnversListenerDuplicationStrategy(); @Override diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPostCollectionRecreateEventListenerImpl.java b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPostCollectionRecreateEventListenerImpl.java index 64c615dc4b..0a88a50a05 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPostCollectionRecreateEventListenerImpl.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPostCollectionRecreateEventListenerImpl.java @@ -29,12 +29,14 @@ import org.hibernate.event.spi.PostCollectionRecreateEvent; import org.hibernate.event.spi.PostCollectionRecreateEventListener; /** + * Envers-specific collection recreation event listener + * * @author Adam Warski (adam at warski dot org) * @author HernпїЅn Chanfreau * @author Steve Ebersole */ public class EnversPostCollectionRecreateEventListenerImpl - extends BaseEnversCollectionEventListener + extends BaseEnversCollectionEventListener implements PostCollectionRecreateEventListener { protected EnversPostCollectionRecreateEventListenerImpl(AuditConfiguration enversConfiguration) { @@ -43,9 +45,9 @@ public class EnversPostCollectionRecreateEventListenerImpl @Override public void onPostRecreateCollection(PostCollectionRecreateEvent event) { - CollectionEntry collectionEntry = getCollectionEntry( event ); - if ( ! collectionEntry.getLoadedPersister().isInverse() ) { - onCollectionAction( event, event.getCollection(), null, collectionEntry ); - } + final CollectionEntry collectionEntry = getCollectionEntry( event ); + if ( !collectionEntry.getLoadedPersister().isInverse() ) { + onCollectionAction( event, event.getCollection(), null, collectionEntry ); + } } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPostDeleteEventListenerImpl.java b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPostDeleteEventListenerImpl.java index 9782e25d79..79cacd10e3 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPostDeleteEventListenerImpl.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPostDeleteEventListenerImpl.java @@ -32,6 +32,8 @@ import org.hibernate.event.spi.PostDeleteEventListener; import org.hibernate.persister.entity.EntityPersister; /** + * Envers-specific entity (post) deletion event listener + * * @author Adam Warski (adam at warski dot org) * @author HernпїЅn Chanfreau * @author Steve Ebersole @@ -43,30 +45,30 @@ public class EnversPostDeleteEventListenerImpl extends BaseEnversEventListener i @Override public void onPostDelete(PostDeleteEvent event) { - String entityName = event.getPersister().getEntityName(); + final String entityName = event.getPersister().getEntityName(); - if ( getAuditConfiguration().getEntCfg().isVersioned( entityName ) ) { - checkIfTransactionInProgress(event.getSession()); + if ( getAuditConfiguration().getEntCfg().isVersioned( entityName ) ) { + checkIfTransactionInProgress( event.getSession() ); - AuditProcess auditProcess = getAuditConfiguration().getSyncManager().get( event.getSession() ); + final AuditProcess auditProcess = getAuditConfiguration().getSyncManager().get( event.getSession() ); - AuditWorkUnit workUnit = new DelWorkUnit( + final AuditWorkUnit workUnit = new DelWorkUnit( event.getSession(), event.getPersister().getEntityName(), getAuditConfiguration(), - event.getId(), + event.getId(), event.getPersister(), event.getDeletedState() ); - auditProcess.addWorkUnit( workUnit ); + auditProcess.addWorkUnit( workUnit ); - if ( workUnit.containsWork() ) { - generateBidirectionalCollectionChangeWorkUnits( + if ( workUnit.containsWork() ) { + generateBidirectionalCollectionChangeWorkUnits( auditProcess, event.getPersister(), entityName, null, - event.getDeletedState(), + event.getDeletedState(), event.getSession() ); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPostInsertEventListenerImpl.java b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPostInsertEventListenerImpl.java index e0e8d48b2c..db3c1d1853 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPostInsertEventListenerImpl.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPostInsertEventListenerImpl.java @@ -32,44 +32,47 @@ import org.hibernate.event.spi.PostInsertEventListener; import org.hibernate.persister.entity.EntityPersister; /** + * Envers-specific entity (post) insertion event listener + * * @author Adam Warski (adam at warski dot org) * @author HernпїЅn Chanfreau * @author Steve Ebersole */ public class EnversPostInsertEventListenerImpl extends BaseEnversEventListener implements PostInsertEventListener { - public EnversPostInsertEventListenerImpl(AuditConfiguration enversConfiguration) { + protected EnversPostInsertEventListenerImpl(AuditConfiguration enversConfiguration) { super( enversConfiguration ); } - public void onPostInsert(PostInsertEvent event) { - String entityName = event.getPersister().getEntityName(); + @Override + public void onPostInsert(PostInsertEvent event) { + final String entityName = event.getPersister().getEntityName(); - if ( getAuditConfiguration().getEntCfg().isVersioned( entityName ) ) { - checkIfTransactionInProgress(event.getSession()); + if ( getAuditConfiguration().getEntCfg().isVersioned( entityName ) ) { + checkIfTransactionInProgress( event.getSession() ); - AuditProcess auditProcess = getAuditConfiguration().getSyncManager().get(event.getSession()); + final AuditProcess auditProcess = getAuditConfiguration().getSyncManager().get( event.getSession() ); - AuditWorkUnit workUnit = new AddWorkUnit( + final AuditWorkUnit workUnit = new AddWorkUnit( event.getSession(), event.getPersister().getEntityName(), getAuditConfiguration(), - event.getId(), + event.getId(), event.getPersister(), event.getState() ); - auditProcess.addWorkUnit( workUnit ); + auditProcess.addWorkUnit( workUnit ); - if ( workUnit.containsWork() ) { - generateBidirectionalCollectionChangeWorkUnits( + if ( workUnit.containsWork() ) { + generateBidirectionalCollectionChangeWorkUnits( auditProcess, event.getPersister(), entityName, event.getState(), - null, + null, event.getSession() ); - } - } + } + } } @Override diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPostUpdateEventListenerImpl.java b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPostUpdateEventListenerImpl.java index ea399a5c63..956bf01a38 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPostUpdateEventListenerImpl.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPostUpdateEventListenerImpl.java @@ -32,6 +32,8 @@ import org.hibernate.event.spi.PostUpdateEventListener; import org.hibernate.persister.entity.EntityPersister; /** + * Envers-specific entity (post) update event listener + * * @author Adam Warski (adam at warski dot org) * @author HernпїЅn Chanfreau * @author Steve Ebersole @@ -43,43 +45,41 @@ public class EnversPostUpdateEventListenerImpl extends BaseEnversEventListener i @Override public void onPostUpdate(PostUpdateEvent event) { - String entityName = event.getPersister().getEntityName(); + final String entityName = event.getPersister().getEntityName(); - if ( getAuditConfiguration().getEntCfg().isVersioned(entityName) ) { - checkIfTransactionInProgress(event.getSession()); - - AuditProcess auditProcess = getAuditConfiguration().getSyncManager().get(event.getSession()); + if ( getAuditConfiguration().getEntCfg().isVersioned( entityName ) ) { + checkIfTransactionInProgress( event.getSession() ); + final AuditProcess auditProcess = getAuditConfiguration().getSyncManager().get( event.getSession() ); final Object[] newDbState = postUpdateDBState( event ); - - AuditWorkUnit workUnit = new ModWorkUnit( + final AuditWorkUnit workUnit = new ModWorkUnit( event.getSession(), event.getPersister().getEntityName(), getAuditConfiguration(), - event.getId(), + event.getId(), event.getPersister(), newDbState, event.getOldState() ); - auditProcess.addWorkUnit( workUnit ); + auditProcess.addWorkUnit( workUnit ); - if ( workUnit.containsWork() ) { - generateBidirectionalCollectionChangeWorkUnits( + if ( workUnit.containsWork() ) { + generateBidirectionalCollectionChangeWorkUnits( auditProcess, event.getPersister(), entityName, newDbState, - event.getOldState(), + event.getOldState(), event.getSession() ); - } - } + } + } } private Object[] postUpdateDBState(PostUpdateEvent event) { - Object[] newDbState = event.getState().clone(); + final Object[] newDbState = event.getState().clone(); if ( event.getOldState() != null ) { - EntityPersister entityPersister = event.getPersister(); + final EntityPersister entityPersister = event.getPersister(); for ( int i = 0; i < entityPersister.getPropertyNames().length; ++i ) { if ( !entityPersister.getPropertyUpdateability()[i] ) { // Assuming that PostUpdateEvent#getOldState() returns database state of the record before modification. diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPreCollectionRemoveEventListenerImpl.java b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPreCollectionRemoveEventListenerImpl.java index aa4204f99a..61a3c1a5ca 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPreCollectionRemoveEventListenerImpl.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPreCollectionRemoveEventListenerImpl.java @@ -31,6 +31,8 @@ import org.hibernate.event.spi.PreCollectionRemoveEvent; import org.hibernate.event.spi.PreCollectionRemoveEventListener; /** + * Envers-specific collection removal event listener + * * @author Adam Warski (adam at warski dot org) * @author HernпїЅn Chanfreau * @author Steve Ebersole @@ -46,14 +48,14 @@ public class EnversPreCollectionRemoveEventListenerImpl @Override public void onPreRemoveCollection(PreCollectionRemoveEvent event) { - CollectionEntry collectionEntry = getCollectionEntry( event ); - if ( collectionEntry != null && !collectionEntry.getLoadedPersister().isInverse() ) { + final CollectionEntry collectionEntry = getCollectionEntry( event ); + if ( collectionEntry != null && !collectionEntry.getLoadedPersister().isInverse() ) { Serializable oldColl = collectionEntry.getSnapshot(); if ( !event.getCollection().wasInitialized() && shouldGenerateRevision( event ) ) { // In case of uninitialized collection we need a fresh snapshot to properly calculate audit data. oldColl = initializeCollection( event ); } - onCollectionAction( event, null, oldColl, collectionEntry ); - } + onCollectionAction( event, null, oldColl, collectionEntry ); + } } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPreCollectionUpdateEventListenerImpl.java b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPreCollectionUpdateEventListenerImpl.java index a088c2c891..b416349ce6 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPreCollectionUpdateEventListenerImpl.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/event/spi/EnversPreCollectionUpdateEventListenerImpl.java @@ -29,6 +29,8 @@ import org.hibernate.event.spi.PreCollectionUpdateEvent; import org.hibernate.event.spi.PreCollectionUpdateEventListener; /** + * Envers-specific collection update event listener + * * @author Adam Warski (adam at warski dot org) * @author HernпїЅn Chanfreau * @author Steve Ebersole @@ -43,9 +45,9 @@ public class EnversPreCollectionUpdateEventListenerImpl @Override public void onPreUpdateCollection(PreCollectionUpdateEvent event) { - CollectionEntry collectionEntry = getCollectionEntry( event ); - if ( ! collectionEntry.getLoadedPersister().isInverse() ) { - onCollectionAction( event, event.getCollection(), collectionEntry.getSnapshot(), collectionEntry ); - } + final CollectionEntry collectionEntry = getCollectionEntry( event ); + if ( !collectionEntry.getLoadedPersister().isInverse() ) { + onCollectionAction( event, event.getCollection(), collectionEntry.getSnapshot(), collectionEntry ); + } } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/exception/AuditException.java b/hibernate-envers/src/main/java/org/hibernate/envers/exception/AuditException.java index a92d3c2b28..d0407c3825 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/exception/AuditException.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/exception/AuditException.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.exception; + import org.hibernate.HibernateException; /** @@ -31,14 +32,14 @@ public class AuditException extends HibernateException { private static final long serialVersionUID = 4306480965630972168L; public AuditException(String message) { - super(message); - } + super( message ); + } - public AuditException(String message, Throwable cause) { - super(message, cause); - } + public AuditException(String message, Throwable cause) { + super( message, cause ); + } - public AuditException(Throwable cause) { - super(cause); - } + public AuditException(Throwable cause) { + super( cause ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/exception/NotAuditedException.java b/hibernate-envers/src/main/java/org/hibernate/envers/exception/NotAuditedException.java index afafd43952..d086ba0acf 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/exception/NotAuditedException.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/exception/NotAuditedException.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -29,15 +29,15 @@ package org.hibernate.envers.exception; */ public class NotAuditedException extends AuditException { private static final long serialVersionUID = 4809674577449455510L; - - private final String entityName; + + private final String entityName; public NotAuditedException(String entityName, String message) { - super(message); - this.entityName = entityName; - } + super( message ); + this.entityName = entityName; + } - public String getEntityName() { - return entityName; - } + public String getEntityName() { + return entityName; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/exception/RevisionDoesNotExistException.java b/hibernate-envers/src/main/java/org/hibernate/envers/exception/RevisionDoesNotExistException.java index eda609bf8d..277e547ca4 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/exception/RevisionDoesNotExistException.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/exception/RevisionDoesNotExistException.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.exception; + import java.util.Date; /** @@ -29,25 +30,27 @@ import java.util.Date; */ public class RevisionDoesNotExistException extends AuditException { private static final long serialVersionUID = -6417768274074962282L; - - private Number revision; - private Date date; + + private final Number revision; + private final Date date; public RevisionDoesNotExistException(Number revision) { - super("Revision " + revision + " does not exist."); - this.revision = revision; - } + super( "Revision " + revision + " does not exist." ); + this.revision = revision; + this.date = null; + } - public RevisionDoesNotExistException(Date date) { - super("There is no revision before or at " + date + "."); - this.date = date; - } + public RevisionDoesNotExistException(Date date) { + super( "There is no revision before or at " + date + "." ); + this.date = date; + this.revision = null; + } - public Number getRevision() { - return revision; - } + public Number getRevision() { + return revision; + } - public Date getDate() { - return date; - } + public Date getDate() { + return date; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/EnversMessageLogger.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/EnversMessageLogger.java index b8208f3994..93e04e3851 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/EnversMessageLogger.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/EnversMessageLogger.java @@ -1,7 +1,7 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2007-2011, Red Hat Inc. or third-party contributors as + * Copyright (c) 2013, 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. @@ -37,10 +37,13 @@ import static org.jboss.logging.Logger.Level.WARN; *

      * New messages must be added after the last message defined to ensure message codes are unique. */ -@MessageLogger( projectCode = "HHH" ) +@MessageLogger(projectCode = "HHH") public interface EnversMessageLogger extends CoreMessageLogger { - @LogMessage( level = WARN ) - @Message( value = "ValidTimeAuditStrategy is deprecated, please use ValidityAuditStrategy instead", id = 25001 ) - void validTimeAuditStrategyDeprecated(); + /** + * Message indicating that user attempted to use the deprecated ValidTimeAuditStrategy + */ + @LogMessage(level = WARN) + @Message(value = "ValidTimeAuditStrategy is deprecated, please use ValidityAuditStrategy instead", id = 25001) + void validTimeAuditStrategyDeprecated(); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/EntitiesConfigurations.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/EntitiesConfigurations.java index 0221e5229c..3c49bae34a 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/EntitiesConfigurations.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/EntitiesConfigurations.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities; + import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -31,129 +32,136 @@ import java.util.Set; /** * Configuration of the user entities: property mapping of the entities, relations, inheritance. + * * @author Adam Warski (adam at warski dot org) * @author Hernán Chanfreau * @author Michal Skowronek (mskowr at o2 dot pl) */ public class EntitiesConfigurations { - private Map entitiesConfigurations; - private Map notAuditedEntitiesConfigurations; + private Map entitiesConfigurations; + private Map notAuditedEntitiesConfigurations; - // Map versions entity name -> entity name - private Map entityNamesForVersionsEntityNames = new HashMap(); + // Map versions entity name -> entity name + private Map entityNamesForVersionsEntityNames = new HashMap(); - public EntitiesConfigurations(Map entitiesConfigurations, - Map notAuditedEntitiesConfigurations) { - this.entitiesConfigurations = entitiesConfigurations; - this.notAuditedEntitiesConfigurations = notAuditedEntitiesConfigurations; + public EntitiesConfigurations( + Map entitiesConfigurations, + Map notAuditedEntitiesConfigurations) { + this.entitiesConfigurations = entitiesConfigurations; + this.notAuditedEntitiesConfigurations = notAuditedEntitiesConfigurations; - generateBidirectionRelationInfo(); - generateVersionsEntityToEntityNames(); - } + generateBidirectionRelationInfo(); + generateVersionsEntityToEntityNames(); + } - private void generateVersionsEntityToEntityNames() { - entityNamesForVersionsEntityNames = new HashMap(); + private void generateVersionsEntityToEntityNames() { + entityNamesForVersionsEntityNames = new HashMap(); - for (String entityName : entitiesConfigurations.keySet()) { - entityNamesForVersionsEntityNames.put(entitiesConfigurations.get(entityName).getVersionsEntityName(), - entityName); - } - } + for ( String entityName : entitiesConfigurations.keySet() ) { + entityNamesForVersionsEntityNames.put( + entitiesConfigurations.get( entityName ).getVersionsEntityName(), + entityName + ); + } + } - private void generateBidirectionRelationInfo() { - // Checking each relation if it is bidirectional. If so, storing that information. - for (String entityName : entitiesConfigurations.keySet()) { - EntityConfiguration entCfg = entitiesConfigurations.get(entityName); - // Iterating over all relations from that entity - for (RelationDescription relDesc : entCfg.getRelationsIterator()) { - // If this is an "owned" relation, checking the related entity, if it has a relation that has - // a mapped-by attribute to the currently checked. If so, this is a bidirectional relation. - if (relDesc.getRelationType() == RelationType.TO_ONE || - relDesc.getRelationType() == RelationType.TO_MANY_MIDDLE) { - EntityConfiguration entityConfiguration = entitiesConfigurations.get(relDesc.getToEntityName()); - if (entityConfiguration != null) { - for (RelationDescription other : entityConfiguration.getRelationsIterator()) { - if (relDesc.getFromPropertyName().equals(other.getMappedByPropertyName()) && - (entityName.equals(other.getToEntityName()))) { - relDesc.setBidirectional(true); - other.setBidirectional(true); + private void generateBidirectionRelationInfo() { + // Checking each relation if it is bidirectional. If so, storing that information. + for ( String entityName : entitiesConfigurations.keySet() ) { + final EntityConfiguration entCfg = entitiesConfigurations.get( entityName ); + // Iterating over all relations from that entity + for ( RelationDescription relDesc : entCfg.getRelationsIterator() ) { + // If this is an "owned" relation, checking the related entity, if it has a relation that has + // a mapped-by attribute to the currently checked. If so, this is a bidirectional relation. + if ( relDesc.getRelationType() == RelationType.TO_ONE || + relDesc.getRelationType() == RelationType.TO_MANY_MIDDLE ) { + final EntityConfiguration entityConfiguration = entitiesConfigurations.get( relDesc.getToEntityName() ); + if ( entityConfiguration != null ) { + for ( RelationDescription other : entityConfiguration.getRelationsIterator() ) { + if ( relDesc.getFromPropertyName().equals( other.getMappedByPropertyName() ) && + (entityName.equals( other.getToEntityName() )) ) { + relDesc.setBidirectional( true ); + other.setBidirectional( true ); } } } - } - } - } - } + } + } + } + } - public EntityConfiguration get(String entityName) { - return entitiesConfigurations.get(entityName); - } + public EntityConfiguration get(String entityName) { + return entitiesConfigurations.get( entityName ); + } - public EntityConfiguration getNotVersionEntityConfiguration(String entityName) { - return notAuditedEntitiesConfigurations.get(entityName); - } + public EntityConfiguration getNotVersionEntityConfiguration(String entityName) { + return notAuditedEntitiesConfigurations.get( entityName ); + } - public String getEntityNameForVersionsEntityName(String versionsEntityName) { - return entityNamesForVersionsEntityNames.get(versionsEntityName); - } + public String getEntityNameForVersionsEntityName(String versionsEntityName) { + return entityNamesForVersionsEntityNames.get( versionsEntityName ); + } - public boolean isVersioned(String entityName) { - return get(entityName) != null; - } + public boolean isVersioned(String entityName) { + return get( entityName ) != null; + } - public boolean hasAuditedEntities() { - return entitiesConfigurations.size() != 0; - } + public boolean hasAuditedEntities() { + return entitiesConfigurations.size() != 0; + } - public RelationDescription getRelationDescription(String entityName, String propertyName) { - EntityConfiguration entCfg = entitiesConfigurations.get(entityName); - RelationDescription relDesc = entCfg.getRelationDescription(propertyName); - if (relDesc != null) { - return relDesc; - } else if (entCfg.getParentEntityName() != null) { - // The field may be declared in a superclass ... - return getRelationDescription(entCfg.getParentEntityName(), propertyName); - } else { - return null; - } - } + public RelationDescription getRelationDescription(String entityName, String propertyName) { + final EntityConfiguration entCfg = entitiesConfigurations.get( entityName ); + final RelationDescription relDesc = entCfg.getRelationDescription( propertyName ); + if ( relDesc != null ) { + return relDesc; + } + else if ( entCfg.getParentEntityName() != null ) { + // The field may be declared in a superclass ... + return getRelationDescription( entCfg.getParentEntityName(), propertyName ); + } + else { + return null; + } + } private Collection getRelationDescriptions(String entityName) { - EntityConfiguration entCfg = entitiesConfigurations.get(entityName); + final EntityConfiguration entCfg = entitiesConfigurations.get( entityName ); Collection descriptions = new ArrayList(); - if (entCfg.getParentEntityName() != null) { + if ( entCfg.getParentEntityName() != null ) { // collect descriptions from super classes - descriptions.addAll(getRelationDescriptions(entCfg.getParentEntityName())); + descriptions.addAll( getRelationDescriptions( entCfg.getParentEntityName() ) ); } - for (RelationDescription relationDescription : entCfg.getRelationsIterator()) { - descriptions.add(relationDescription); + for ( RelationDescription relationDescription : entCfg.getRelationsIterator() ) { + descriptions.add( relationDescription ); } return descriptions; } private void addWithParentEntityNames(String entityName, Set entityNames) { - entityNames.add(entityName); - EntityConfiguration entCfg = entitiesConfigurations.get(entityName); - if (entCfg.getParentEntityName() != null) { + entityNames.add( entityName ); + final EntityConfiguration entCfg = entitiesConfigurations.get( entityName ); + if ( entCfg.getParentEntityName() != null ) { // collect descriptions from super classes - addWithParentEntityNames(entCfg.getParentEntityName(), entityNames); + addWithParentEntityNames( entCfg.getParentEntityName(), entityNames ); } } private Set getEntityAndParentsNames(String entityName) { - Set names = new HashSet(); - addWithParentEntityNames(entityName, names); + final Set names = new HashSet(); + addWithParentEntityNames( entityName, names ); return names; } public Set getToPropertyNames(String fromEntityName, String fromPropertyName, String toEntityName) { - Set entityAndParentsNames = getEntityAndParentsNames(fromEntityName); - Set toPropertyNames = new HashSet(); - for (RelationDescription relationDescription : getRelationDescriptions(toEntityName)) { - String relToEntityName = relationDescription.getToEntityName(); - String mappedByPropertyName = relationDescription.getMappedByPropertyName(); - if (entityAndParentsNames.contains(relToEntityName) && mappedByPropertyName != null && mappedByPropertyName.equals(fromPropertyName)) { - toPropertyNames.add(relationDescription.getFromPropertyName()); + final Set entityAndParentsNames = getEntityAndParentsNames( fromEntityName ); + final Set toPropertyNames = new HashSet(); + for ( RelationDescription relationDescription : getRelationDescriptions( toEntityName ) ) { + final String relToEntityName = relationDescription.getToEntityName(); + final String mappedByPropertyName = relationDescription.getMappedByPropertyName(); + if ( entityAndParentsNames.contains( relToEntityName ) && mappedByPropertyName != null && mappedByPropertyName + .equals( fromPropertyName ) ) { + toPropertyNames.add( relationDescription.getFromPropertyName() ); } } return toPropertyNames; diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/EntityConfiguration.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/EntityConfiguration.java index ba5a59e81d..8ee7d237e3 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/EntityConfiguration.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/EntityConfiguration.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities; + import java.util.HashMap; import java.util.Map; @@ -34,93 +35,160 @@ import org.hibernate.envers.internal.entities.mapper.id.IdMapper; * @author HernпїЅn Chanfreau */ public class EntityConfiguration { - private String versionsEntityName; - /** Holds the className for instantiation the configured entity */ - private String entityClassName; + private String versionsEntityName; + /** + * Holds the className for instantiation the configured entity + */ + private String entityClassName; private IdMappingData idMappingData; - private ExtendedPropertyMapper propertyMapper; - // Maps from property name - private Map relations; - private String parentEntityName; + private ExtendedPropertyMapper propertyMapper; + // Maps from property name + private Map relations; + private String parentEntityName; - public EntityConfiguration(String versionsEntityName, String entityClassName, IdMappingData idMappingData, - ExtendedPropertyMapper propertyMapper, String parentEntityName) { - this.versionsEntityName = versionsEntityName; - this.entityClassName = entityClassName; - this.idMappingData = idMappingData; - this.propertyMapper = propertyMapper; - this.parentEntityName = parentEntityName; + public EntityConfiguration( + String versionsEntityName, String entityClassName, IdMappingData idMappingData, + ExtendedPropertyMapper propertyMapper, String parentEntityName) { + this.versionsEntityName = versionsEntityName; + this.entityClassName = entityClassName; + this.idMappingData = idMappingData; + this.propertyMapper = propertyMapper; + this.parentEntityName = parentEntityName; - this.relations = new HashMap(); - } + this.relations = new HashMap(); + } - public void addToOneRelation(String fromPropertyName, String toEntityName, IdMapper idMapper, boolean insertable) { - relations.put(fromPropertyName, new RelationDescription(fromPropertyName, RelationType.TO_ONE, - toEntityName, null, idMapper, null, null, insertable)); - } + public void addToOneRelation(String fromPropertyName, String toEntityName, IdMapper idMapper, boolean insertable) { + relations.put( + fromPropertyName, + new RelationDescription( + fromPropertyName, + RelationType.TO_ONE, + toEntityName, + null, + idMapper, + null, + null, + insertable + ) + ); + } - public void addToOneNotOwningRelation(String fromPropertyName, String mappedByPropertyName, String toEntityName, - IdMapper idMapper) { - relations.put(fromPropertyName, new RelationDescription(fromPropertyName, RelationType.TO_ONE_NOT_OWNING, - toEntityName, mappedByPropertyName, idMapper, null, null, true)); - } + public void addToOneNotOwningRelation( + String fromPropertyName, + String mappedByPropertyName, + String toEntityName, + IdMapper idMapper) { + relations.put( + fromPropertyName, + new RelationDescription( + fromPropertyName, + RelationType.TO_ONE_NOT_OWNING, + toEntityName, + mappedByPropertyName, + idMapper, + null, + null, + true + ) + ); + } - public void addToManyNotOwningRelation(String fromPropertyName, String mappedByPropertyName, String toEntityName, - IdMapper idMapper, PropertyMapper fakeBidirectionalRelationMapper, - PropertyMapper fakeBidirectionalRelationIndexMapper) { - relations.put(fromPropertyName, new RelationDescription(fromPropertyName, RelationType.TO_MANY_NOT_OWNING, - toEntityName, mappedByPropertyName, idMapper, fakeBidirectionalRelationMapper, - fakeBidirectionalRelationIndexMapper, true)); - } + public void addToManyNotOwningRelation( + String fromPropertyName, + String mappedByPropertyName, + String toEntityName, + IdMapper idMapper, + PropertyMapper fakeBidirectionalRelationMapper, + PropertyMapper fakeBidirectionalRelationIndexMapper) { + relations.put( + fromPropertyName, + new RelationDescription( + fromPropertyName, + RelationType.TO_MANY_NOT_OWNING, + toEntityName, + mappedByPropertyName, + idMapper, + fakeBidirectionalRelationMapper, + fakeBidirectionalRelationIndexMapper, + true + ) + ); + } - public void addToManyMiddleRelation(String fromPropertyName, String toEntityName) { - relations.put(fromPropertyName, new RelationDescription(fromPropertyName, RelationType.TO_MANY_MIDDLE, - toEntityName, null, null, null, null, true)); - } + public void addToManyMiddleRelation(String fromPropertyName, String toEntityName) { + relations.put( + fromPropertyName, + new RelationDescription( + fromPropertyName, + RelationType.TO_MANY_MIDDLE, + toEntityName, + null, + null, + null, + null, + true + ) + ); + } - public void addToManyMiddleNotOwningRelation(String fromPropertyName, String mappedByPropertyName, String toEntityName) { - relations.put(fromPropertyName, new RelationDescription(fromPropertyName, RelationType.TO_MANY_MIDDLE_NOT_OWNING, - toEntityName, mappedByPropertyName, null, null, null, true)); - } + public void addToManyMiddleNotOwningRelation( + String fromPropertyName, + String mappedByPropertyName, + String toEntityName) { + relations.put( + fromPropertyName, + new RelationDescription( + fromPropertyName, + RelationType.TO_MANY_MIDDLE_NOT_OWNING, + toEntityName, + mappedByPropertyName, + null, + null, + null, + true + ) + ); + } - public boolean isRelation(String propertyName) { - return relations.get(propertyName) != null; - } - - public RelationDescription getRelationDescription(String propertyName) { - return relations.get(propertyName); - } + public boolean isRelation(String propertyName) { + return relations.get( propertyName ) != null; + } - public IdMappingData getIdMappingData() { - return idMappingData; - } + public RelationDescription getRelationDescription(String propertyName) { + return relations.get( propertyName ); + } - public IdMapper getIdMapper() { - return idMappingData.getIdMapper(); - } + public IdMappingData getIdMappingData() { + return idMappingData; + } - public ExtendedPropertyMapper getPropertyMapper() { - return propertyMapper; - } + public IdMapper getIdMapper() { + return idMappingData.getIdMapper(); + } - public String getParentEntityName() { - return parentEntityName; - } + public ExtendedPropertyMapper getPropertyMapper() { + return propertyMapper; + } - // For use by EntitiesConfigurations + public String getParentEntityName() { + return parentEntityName; + } - String getVersionsEntityName() { - return versionsEntityName; - } + // For use by EntitiesConfigurations - Iterable getRelationsIterator() { - return relations.values(); - } - - /** - * @return the className for the configured entity - */ - public String getEntityClassName() { + String getVersionsEntityName() { + return versionsEntityName; + } + + Iterable getRelationsIterator() { + return relations.values(); + } + + /** + * @return the className for the configured entity + */ + public String getEntityClassName() { return entityClassName; } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/EntityInstantiator.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/EntityInstantiator.java index cf9cf211cb..acac9babe8 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/EntityInstantiator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/EntityInstantiator.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -44,109 +44,136 @@ import org.hibernate.proxy.LazyInitializer; * @author Hernán Chanfreau */ public class EntityInstantiator { - private final AuditConfiguration verCfg; - private final AuditReaderImplementor versionsReader; + private final AuditConfiguration verCfg; + private final AuditReaderImplementor versionsReader; - public EntityInstantiator(AuditConfiguration verCfg, AuditReaderImplementor versionsReader) { - this.verCfg = verCfg; - this.versionsReader = versionsReader; - } + public EntityInstantiator(AuditConfiguration verCfg, AuditReaderImplementor versionsReader) { + this.verCfg = verCfg; + this.versionsReader = versionsReader; + } - /** - * Creates an entity instance based on an entry from the versions table. - * @param entityName Name of the entity, which instances should be read - * @param versionsEntity An entry in the versions table, from which data should be mapped. - * @param revision Revision at which this entity was read. - * @return An entity instance, with versioned properties set as in the versionsEntity map, and proxies - * created for collections. - */ - public Object createInstanceFromVersionsEntity(String entityName, Map versionsEntity, Number revision) { - if (versionsEntity == null) { - return null; - } + /** + * Creates an entity instance based on an entry from the versions table. + * + * @param entityName Name of the entity, which instances should be read + * @param versionsEntity An entry in the versions table, from which data should be mapped. + * @param revision Revision at which this entity was read. + * + * @return An entity instance, with versioned properties set as in the versionsEntity map, and proxies + * created for collections. + */ + public Object createInstanceFromVersionsEntity(String entityName, Map versionsEntity, Number revision) { + if ( versionsEntity == null ) { + return null; + } - // The $type$ property holds the name of the (versions) entity - String type = verCfg.getEntCfg().getEntityNameForVersionsEntityName((String) versionsEntity.get("$type$")); + // The $type$ property holds the name of the (versions) entity + final String type = verCfg.getEntCfg().getEntityNameForVersionsEntityName( (String) versionsEntity.get( "$type$" ) ); - if (type != null) { - entityName = type; - } + if ( type != null ) { + entityName = type; + } - // First mapping the primary key - IdMapper idMapper = verCfg.getEntCfg().get(entityName).getIdMapper(); - Map originalId = (Map) versionsEntity.get(verCfg.getAuditEntCfg().getOriginalIdPropName()); + // First mapping the primary key + final IdMapper idMapper = verCfg.getEntCfg().get( entityName ).getIdMapper(); + final Map originalId = (Map) versionsEntity.get( verCfg.getAuditEntCfg().getOriginalIdPropName() ); - // Fixes HHH-4751 issue (@IdClass with @ManyToOne relation mapping inside) - // Note that identifiers are always audited - // Replace identifier proxies if do not point to audit tables - replaceNonAuditIdProxies(versionsEntity, revision); + // Fixes HHH-4751 issue (@IdClass with @ManyToOne relation mapping inside) + // Note that identifiers are always audited + // Replace identifier proxies if do not point to audit tables + replaceNonAuditIdProxies( versionsEntity, revision ); - Object primaryKey = idMapper.mapToIdFromMap(originalId); + final Object primaryKey = idMapper.mapToIdFromMap( originalId ); - // Checking if the entity is in cache - if (versionsReader.getFirstLevelCache().contains(entityName, revision, primaryKey)) { - return versionsReader.getFirstLevelCache().get(entityName, revision, primaryKey); - } + // Checking if the entity is in cache + if ( versionsReader.getFirstLevelCache().contains( entityName, revision, primaryKey ) ) { + return versionsReader.getFirstLevelCache().get( entityName, revision, primaryKey ); + } - // If it is not in the cache, creating a new entity instance - Object ret; - try { - EntityConfiguration entCfg = verCfg.getEntCfg().get(entityName); - if(entCfg == null) { - // a relation marked as RelationTargetAuditMode.NOT_AUDITED - entCfg = verCfg.getEntCfg().getNotVersionEntityConfiguration(entityName); - } + // If it is not in the cache, creating a new entity instance + Object ret; + try { + EntityConfiguration entCfg = verCfg.getEntCfg().get( entityName ); + if ( entCfg == null ) { + // a relation marked as RelationTargetAuditMode.NOT_AUDITED + entCfg = verCfg.getEntCfg().getNotVersionEntityConfiguration( entityName ); + } - Class cls = ReflectionTools.loadClass( entCfg.getEntityClassName(), verCfg.getClassLoaderService() ); - ret = ReflectHelper.getDefaultConstructor(cls).newInstance(); - } catch (Exception e) { - throw new AuditException(e); - } + final Class cls = ReflectionTools.loadClass( entCfg.getEntityClassName(), verCfg.getClassLoaderService() ); + ret = ReflectHelper.getDefaultConstructor( cls ).newInstance(); + } + catch (Exception e) { + throw new AuditException( e ); + } - // Putting the newly created entity instance into the first level cache, in case a one-to-one bidirectional - // relation is present (which is eagerly loaded). - versionsReader.getFirstLevelCache().put(entityName, revision, primaryKey, ret); + // Putting the newly created entity instance into the first level cache, in case a one-to-one bidirectional + // relation is present (which is eagerly loaded). + versionsReader.getFirstLevelCache().put( entityName, revision, primaryKey, ret ); - verCfg.getEntCfg().get(entityName).getPropertyMapper().mapToEntityFromMap(verCfg, ret, versionsEntity, primaryKey, - versionsReader, revision); - idMapper.mapToEntityFromMap(ret, originalId); + verCfg.getEntCfg().get( entityName ).getPropertyMapper().mapToEntityFromMap( + verCfg, + ret, + versionsEntity, + primaryKey, + versionsReader, + revision + ); + idMapper.mapToEntityFromMap( ret, originalId ); - // Put entity on entityName cache after mapping it from the map representation - versionsReader.getFirstLevelCache().putOnEntityNameCache(primaryKey, revision, ret, entityName); - - return ret; - } + // Put entity on entityName cache after mapping it from the map representation + versionsReader.getFirstLevelCache().putOnEntityNameCache( primaryKey, revision, ret, entityName ); - @SuppressWarnings({"unchecked"}) - private void replaceNonAuditIdProxies(Map versionsEntity, Number revision) { - final Map originalId = (Map) versionsEntity.get( verCfg.getAuditEntCfg().getOriginalIdPropName() ); - for (Object key : originalId.keySet()) { - Object value = originalId.get(key); - if (value instanceof HibernateProxy) { - HibernateProxy hibernateProxy = (HibernateProxy) value; - LazyInitializer initializer = hibernateProxy.getHibernateLazyInitializer(); - final String entityName = initializer.getEntityName(); - final Serializable entityId = initializer.getIdentifier(); - if (verCfg.getEntCfg().isVersioned(entityName)) { - final String entityClassName = verCfg.getEntCfg().get(entityName).getEntityClassName(); - final Class entityClass = ReflectionTools.loadClass( entityClassName, verCfg.getClassLoaderService() ); - final ToOneDelegateSessionImplementor delegate = new ToOneDelegateSessionImplementor( - versionsReader, entityClass, entityId, revision, - RevisionType.DEL.equals( versionsEntity.get( verCfg.getAuditEntCfg().getRevisionTypePropName() ) ), - verCfg); - originalId.put(key, - versionsReader.getSessionImplementor().getFactory().getEntityPersister(entityName).createProxy(entityId, delegate)); - } - } - } - } + return ret; + } - @SuppressWarnings({"unchecked"}) - public void addInstancesFromVersionsEntities(String entityName, Collection addTo, List versionsEntities, Number revision) { - for (Map versionsEntity : versionsEntities) { - addTo.add(createInstanceFromVersionsEntity(entityName, versionsEntity, revision)); - } - } + @SuppressWarnings({"unchecked"}) + private void replaceNonAuditIdProxies(Map versionsEntity, Number revision) { + final Map originalId = (Map) versionsEntity.get( verCfg.getAuditEntCfg().getOriginalIdPropName() ); + for ( Object key : originalId.keySet() ) { + final Object value = originalId.get( key ); + if ( value instanceof HibernateProxy ) { + final HibernateProxy hibernateProxy = (HibernateProxy) value; + final LazyInitializer initializer = hibernateProxy.getHibernateLazyInitializer(); + final String entityName = initializer.getEntityName(); + final Serializable entityId = initializer.getIdentifier(); + if ( verCfg.getEntCfg().isVersioned( entityName ) ) { + final String entityClassName = verCfg.getEntCfg().get( entityName ).getEntityClassName(); + final Class entityClass = ReflectionTools.loadClass( + entityClassName, + verCfg.getClassLoaderService() + ); + final ToOneDelegateSessionImplementor delegate = new ToOneDelegateSessionImplementor( + versionsReader, entityClass, entityId, revision, + RevisionType.DEL.equals( + versionsEntity.get( + verCfg.getAuditEntCfg() + .getRevisionTypePropName() + ) + ), + verCfg + ); + originalId.put( + key, + versionsReader.getSessionImplementor() + .getFactory() + .getEntityPersister( entityName ) + .createProxy( entityId, delegate ) + ); + } + } + } + } + + @SuppressWarnings({"unchecked"}) + public void addInstancesFromVersionsEntities( + String entityName, + Collection addTo, + List versionsEntities, + Number revision) { + for ( Map versionsEntity : versionsEntities ) { + addTo.add( createInstanceFromVersionsEntity( entityName, versionsEntity, revision ) ); + } + } public AuditConfiguration getAuditConfiguration() { return verCfg; diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/IdMappingData.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/IdMappingData.java index e554f28eeb..681a8c725d 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/IdMappingData.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/IdMappingData.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities; + import org.dom4j.Element; import org.hibernate.envers.internal.entities.mapper.id.IdMapper; @@ -30,27 +31,27 @@ import org.hibernate.envers.internal.entities.mapper.id.IdMapper; * @author Adam Warski (adam at warski dot org) */ public class IdMappingData { - private final IdMapper idMapper; - // Mapping which will be used to generate the entity - private final Element xmlMapping; - // Mapping which will be used to generate references to the entity in related entities - private final Element xmlRelationMapping; + private final IdMapper idMapper; + // Mapping which will be used to generate the entity + private final Element xmlMapping; + // Mapping which will be used to generate references to the entity in related entities + private final Element xmlRelationMapping; - public IdMappingData(IdMapper idMapper, Element xmlMapping, Element xmlRelationMapping) { - this.idMapper = idMapper; - this.xmlMapping = xmlMapping; - this.xmlRelationMapping = xmlRelationMapping; - } + public IdMappingData(IdMapper idMapper, Element xmlMapping, Element xmlRelationMapping) { + this.idMapper = idMapper; + this.xmlMapping = xmlMapping; + this.xmlRelationMapping = xmlRelationMapping; + } - public IdMapper getIdMapper() { - return idMapper; - } + public IdMapper getIdMapper() { + return idMapper; + } - public Element getXmlMapping() { - return xmlMapping; - } + public Element getXmlMapping() { + return xmlMapping; + } - public Element getXmlRelationMapping() { - return xmlRelationMapping; - } + public Element getXmlRelationMapping() { + return xmlRelationMapping; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/PropertyData.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/PropertyData.java index 0494d2db7b..52d76a89aa 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/PropertyData.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/PropertyData.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,76 +22,86 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities; + import org.hibernate.envers.ModificationStore; +import org.hibernate.internal.util.compare.EqualsHelper; /** * Holds information on a property that is audited. + * * @author Adam Warski (adam at warski dot org) */ public class PropertyData { - private final String name; + private final String name; /** * Name of the property in the bean. */ private final String beanName; - private final String accessType; - private final ModificationStore store; + private final String accessType; + private final ModificationStore store; private boolean usingModifiedFlag; private String modifiedFlagName; - /** - * Copies the given property data, except the name. - * @param newName New name. - * @param propertyData Property data to copy the rest of properties from. - */ - public PropertyData(String newName, PropertyData propertyData) { - this.name = newName; + /** + * Copies the given property data, except the name. + * + * @param newName New name. + * @param propertyData Property data to copy the rest of properties from. + */ + public PropertyData(String newName, PropertyData propertyData) { + this.name = newName; this.beanName = propertyData.beanName; - this.accessType = propertyData.accessType; - this.store = propertyData.store; - } - - /** - * @param name Name of the property. - * @param beanName Name of the property in the bean. - * @param accessType Accessor type for this property. - * @param store How this property should be stored. - */ - public PropertyData(String name, String beanName, String accessType, ModificationStore store) { - this.name = name; - this.beanName = beanName; - this.accessType = accessType; - this.store = store; - } + this.accessType = propertyData.accessType; + this.store = propertyData.store; + } /** - * @param name Name of the property. + * @param name Name of the property. * @param beanName Name of the property in the bean. - * @param accessType Accessor type for this property. - * @param store How this property should be stored. - * @param usingModifiedFlag Defines if field changes should be tracked - */ - public PropertyData(String name, String beanName, String accessType, ModificationStore store, boolean usingModifiedFlag, String modifiedFlagName) { - this(name, beanName, accessType, store); + * @param accessType Accessor type for this property. + * @param store How this property should be stored. + */ + public PropertyData(String name, String beanName, String accessType, ModificationStore store) { + this.name = name; + this.beanName = beanName; + this.accessType = accessType; + this.store = store; + } + + /** + * @param name Name of the property. + * @param beanName Name of the property in the bean. + * @param accessType Accessor type for this property. + * @param store How this property should be stored. + * @param usingModifiedFlag Defines if field changes should be tracked + */ + public PropertyData( + String name, + String beanName, + String accessType, + ModificationStore store, + boolean usingModifiedFlag, + String modifiedFlagName) { + this( name, beanName, accessType, store ); this.usingModifiedFlag = usingModifiedFlag; this.modifiedFlagName = modifiedFlagName; } - public String getName() { - return name; - } + public String getName() { + return name; + } public String getBeanName() { return beanName; } public String getAccessType() { - return accessType; - } + return accessType; + } - public ModificationStore getStore() { - return store; - } + public ModificationStore getStore() { + return store; + } public boolean isUsingModifiedFlag() { return usingModifiedFlag; @@ -103,18 +113,19 @@ public class PropertyData { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } - PropertyData that = (PropertyData) o; - - if (accessType != null ? !accessType.equals(that.accessType) : that.accessType != null) return false; - if (beanName != null ? !beanName.equals(that.beanName) : that.beanName != null) return false; - if (name != null ? !name.equals(that.name) : that.name != null) return false; - if (store != that.store) return false; - if (usingModifiedFlag != that.usingModifiedFlag) return false; - - return true; + final PropertyData that = (PropertyData) o; + return usingModifiedFlag == that.usingModifiedFlag + && store == that.store + && EqualsHelper.equals( accessType, that.accessType ) + && EqualsHelper.equals( beanName, that.beanName ) + && EqualsHelper.equals( name, that.name ); } @Override diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/RelationDescription.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/RelationDescription.java index b129500944..a4cc200a68 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/RelationDescription.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/RelationDescription.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,76 +22,78 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities; + import org.hibernate.envers.internal.entities.mapper.PropertyMapper; import org.hibernate.envers.internal.entities.mapper.id.IdMapper; /** * @author Adam Warski (adam at warski dot org) -*/ + */ public class RelationDescription { - private final String fromPropertyName; - private final RelationType relationType; - private final String toEntityName; - private final String mappedByPropertyName; - private final IdMapper idMapper; - private final PropertyMapper fakeBidirectionalRelationMapper; - private final PropertyMapper fakeBidirectionalRelationIndexMapper; - private final boolean insertable; - private boolean bidirectional; + private final String fromPropertyName; + private final RelationType relationType; + private final String toEntityName; + private final String mappedByPropertyName; + private final IdMapper idMapper; + private final PropertyMapper fakeBidirectionalRelationMapper; + private final PropertyMapper fakeBidirectionalRelationIndexMapper; + private final boolean insertable; + private boolean bidirectional; - public RelationDescription(String fromPropertyName, RelationType relationType, String toEntityName, - String mappedByPropertyName, IdMapper idMapper, - PropertyMapper fakeBidirectionalRelationMapper, - PropertyMapper fakeBidirectionalRelationIndexMapper, boolean insertable) { - this.fromPropertyName = fromPropertyName; - this.relationType = relationType; - this.toEntityName = toEntityName; - this.mappedByPropertyName = mappedByPropertyName; - this.idMapper = idMapper; - this.fakeBidirectionalRelationMapper = fakeBidirectionalRelationMapper; - this.fakeBidirectionalRelationIndexMapper = fakeBidirectionalRelationIndexMapper; - this.insertable = insertable; + public RelationDescription( + String fromPropertyName, RelationType relationType, String toEntityName, + String mappedByPropertyName, IdMapper idMapper, + PropertyMapper fakeBidirectionalRelationMapper, + PropertyMapper fakeBidirectionalRelationIndexMapper, boolean insertable) { + this.fromPropertyName = fromPropertyName; + this.relationType = relationType; + this.toEntityName = toEntityName; + this.mappedByPropertyName = mappedByPropertyName; + this.idMapper = idMapper; + this.fakeBidirectionalRelationMapper = fakeBidirectionalRelationMapper; + this.fakeBidirectionalRelationIndexMapper = fakeBidirectionalRelationIndexMapper; + this.insertable = insertable; - this.bidirectional = false; - } + this.bidirectional = false; + } - public String getFromPropertyName() { - return fromPropertyName; - } + public String getFromPropertyName() { + return fromPropertyName; + } - public RelationType getRelationType() { - return relationType; - } + public RelationType getRelationType() { + return relationType; + } - public String getToEntityName() { - return toEntityName; - } + public String getToEntityName() { + return toEntityName; + } - public String getMappedByPropertyName() { - return mappedByPropertyName; - } + public String getMappedByPropertyName() { + return mappedByPropertyName; + } - public IdMapper getIdMapper() { - return idMapper; - } + public IdMapper getIdMapper() { + return idMapper; + } - public PropertyMapper getFakeBidirectionalRelationMapper() { - return fakeBidirectionalRelationMapper; - } + public PropertyMapper getFakeBidirectionalRelationMapper() { + return fakeBidirectionalRelationMapper; + } - public PropertyMapper getFakeBidirectionalRelationIndexMapper() { - return fakeBidirectionalRelationIndexMapper; - } + public PropertyMapper getFakeBidirectionalRelationIndexMapper() { + return fakeBidirectionalRelationIndexMapper; + } - public boolean isInsertable() { - return insertable; - } + public boolean isInsertable() { + return insertable; + } - public boolean isBidirectional() { - return bidirectional; - } + public boolean isBidirectional() { + return bidirectional; + } - void setBidirectional(boolean bidirectional) { - this.bidirectional = bidirectional; - } + void setBidirectional(boolean bidirectional) { + this.bidirectional = bidirectional; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/RelationType.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/RelationType.java index 449b4ecfd9..fa53383dc9 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/RelationType.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/RelationType.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -26,30 +26,31 @@ package org.hibernate.envers.internal.entities; /** * Type of a relation between two entities. + * * @author Adam Warski (adam at warski dot org) -*/ + */ public enum RelationType { - /** - * A single-reference-valued relation. The entity owns the relation. - */ - TO_ONE, - /** - * A single-reference-valued relation. The entity doesn't own the relation. It is directly mapped in the related - * entity. - */ - TO_ONE_NOT_OWNING, - /** - * A collection-of-references-valued relation. The entity doesn't own the relation. It is directly mapped in the - * related entity. - */ - TO_MANY_NOT_OWNING, - /** - * A collection-of-references-valued relation. The entity owns the relation. It is mapped using a middle table. - */ - TO_MANY_MIDDLE, - /** - * A collection-of-references-valued relation. The entity doesn't own the relation. It is mapped using a middle - * table. - */ - TO_MANY_MIDDLE_NOT_OWNING + /** + * A single-reference-valued relation. The entity owns the relation. + */ + TO_ONE, + /** + * A single-reference-valued relation. The entity doesn't own the relation. It is directly mapped in the related + * entity. + */ + TO_ONE_NOT_OWNING, + /** + * A collection-of-references-valued relation. The entity doesn't own the relation. It is directly mapped in the + * related entity. + */ + TO_MANY_NOT_OWNING, + /** + * A collection-of-references-valued relation. The entity owns the relation. It is mapped using a middle table. + */ + TO_MANY_MIDDLE, + /** + * A collection-of-references-valued relation. The entity doesn't own the relation. It is mapped using a middle + * table. + */ + TO_MANY_MIDDLE_NOT_OWNING } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/RevisionTypeType.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/RevisionTypeType.java index 0580c804c2..9557a8a70f 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/RevisionTypeType.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/RevisionTypeType.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -32,78 +32,84 @@ import java.sql.Types; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.envers.RevisionType; +import org.hibernate.internal.util.compare.EqualsHelper; import org.hibernate.type.IntegerType; import org.hibernate.usertype.UserType; /** * A hibernate type for the {@link RevisionType} enum. + * * @author Adam Warski (adam at warski dot org) */ public class RevisionTypeType implements UserType, Serializable { - private static final long serialVersionUID = -1053201518229282688L; - - private static final int[] SQL_TYPES = { Types.TINYINT }; + private static final long serialVersionUID = -1053201518229282688L; - public int[] sqlTypes() { - return SQL_TYPES; - } + private static final int[] SQL_TYPES = {Types.TINYINT}; - public Class returnedClass() { - return RevisionType.class; - } + @Override + public int[] sqlTypes() { + return SQL_TYPES; + } - public RevisionType nullSafeGet(ResultSet resultSet, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException { - Integer representationInt = IntegerType.INSTANCE.nullSafeGet( resultSet, names[0], session ); + @Override + public Class returnedClass() { + return RevisionType.class; + } + + @Override + public RevisionType nullSafeGet(ResultSet resultSet, String[] names, SessionImplementor session, Object owner) + throws HibernateException, SQLException { + final Integer representationInt = IntegerType.INSTANCE.nullSafeGet( resultSet, names[0], session ); return representationInt == null ? null : RevisionType.fromRepresentation( representationInt.byteValue() ); - } + } - public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index, SessionImplementor session) throws HibernateException, SQLException { + @Override + public void nullSafeSet(PreparedStatement preparedStatement, Object value, int index, SessionImplementor session) + throws HibernateException, SQLException { IntegerType.INSTANCE.nullSafeSet( preparedStatement, - ( value == null ? null : ((RevisionType) value).getRepresentation().intValue() ), + (value == null ? null : ((RevisionType) value).getRepresentation().intValue()), index, session ); - } + } - public Object deepCopy(Object value) throws HibernateException{ - return value; - } + @Override + public Object deepCopy(Object value) throws HibernateException { + return value; + } - public boolean isMutable() { - return false; - } + @Override + public boolean isMutable() { + return false; + } - public Object assemble(Serializable cached, Object owner) throws HibernateException { - return cached; - } + @Override + public Object assemble(Serializable cached, Object owner) throws HibernateException { + return cached; + } - public Serializable disassemble(Object value) throws HibernateException { - return (Serializable)value; - } + @Override + public Serializable disassemble(Object value) throws HibernateException { + return (Serializable) value; + } - public Object replace(Object original, Object target, Object owner) throws HibernateException { - return original; - } + @Override + public Object replace(Object original, Object target, Object owner) throws HibernateException { + return original; + } - public int hashCode(Object x) throws HibernateException { - return x.hashCode(); - } + @Override + public int hashCode(Object x) throws HibernateException { + return x.hashCode(); + } - public boolean equals(Object x, Object y) throws HibernateException { - //noinspection ObjectEquality - if (x == y) { - return true; - } - - if (null == x || null == y) { - return false; - } - - return x.equals(y); - } + @Override + public boolean equals(Object x, Object y) throws HibernateException { + return EqualsHelper.equals( x, y ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/TypeContributorImpl.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/TypeContributorImpl.java index 0a49200a26..e2366a0b80 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/TypeContributorImpl.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/TypeContributorImpl.java @@ -1,22 +1,25 @@ -/* +/* * Hibernate, Relational Persistence for Idiomatic Java - * - * JBoss, Home of Professional Open Source - * Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors - * as indicated by the @authors tag. All rights reserved. - * See the copyright.txt in the distribution for a - * full listing of individual contributors. * - * 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, v. 2.1. - * This program is distributed in the hope that it will be useful, but WITHOUT A - * 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, - * v.2.1 along with this distribution; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, - * MA 02110-1301, USA. + * Copyright (c) 2013, 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.envers.internal.entities; @@ -25,14 +28,17 @@ import org.hibernate.metamodel.spi.TypeContributor; import org.hibernate.service.ServiceRegistry; /** + * Envers specific TypeContributor + * * @author Brett Meyer */ public class TypeContributorImpl implements TypeContributor { - @Override public void contribute(TypeContributions typeContributions, ServiceRegistry serviceRegistry) { - typeContributions.contributeType( new RevisionTypeType(), - new String[] { RevisionTypeType.class.getName() } ); + typeContributions.contributeType( + new RevisionTypeType(), + new String[] { RevisionTypeType.class.getName() } + ); } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/ComponentPropertyMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/ComponentPropertyMapper.java index 52d0323998..3cdb1c2d89 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/ComponentPropertyMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/ComponentPropertyMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -43,98 +43,127 @@ import org.hibernate.property.Setter; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class ComponentPropertyMapper implements PropertyMapper, CompositeMapperBuilder { - private final PropertyData propertyData; - private final MultiPropertyMapper delegate; + private final PropertyData propertyData; + private final MultiPropertyMapper delegate; private final Class componentClass; - public ComponentPropertyMapper(PropertyData propertyData, Class componentClass) { - this.propertyData = propertyData; - this.delegate = new MultiPropertyMapper(); + public ComponentPropertyMapper(PropertyData propertyData, Class componentClass) { + this.propertyData = propertyData; + this.delegate = new MultiPropertyMapper(); this.componentClass = componentClass; - } - - public void add(PropertyData propertyData) { - delegate.add(propertyData); - } - - public CompositeMapperBuilder addComponent(PropertyData propertyData, Class componentClass) { - return delegate.addComponent(propertyData, componentClass); - } - - public void addComposite(PropertyData propertyData, PropertyMapper propertyMapper) { - delegate.addComposite(propertyData, propertyMapper); - } - - public boolean mapToMapFromEntity(SessionImplementor session, Map data, Object newObj, Object oldObj) { - return delegate.mapToMapFromEntity(session, data, newObj, oldObj); - } + } @Override - public void mapModifiedFlagsToMapFromEntity(SessionImplementor session, Map data, Object newObj, Object oldObj) { - if (propertyData.isUsingModifiedFlag()) { - data.put(propertyData.getModifiedFlagPropertyName(), - delegate.mapToMapFromEntity(session, new HashMap(), newObj, oldObj)); + public void add(PropertyData propertyData) { + delegate.add( propertyData ); + } + + @Override + public CompositeMapperBuilder addComponent(PropertyData propertyData, Class componentClass) { + return delegate.addComponent( propertyData, componentClass ); + } + + @Override + public void addComposite(PropertyData propertyData, PropertyMapper propertyMapper) { + delegate.addComposite( propertyData, propertyMapper ); + } + + @Override + public boolean mapToMapFromEntity( + SessionImplementor session, + Map data, + Object newObj, + Object oldObj) { + return delegate.mapToMapFromEntity( session, data, newObj, oldObj ); + } + + @Override + public void mapModifiedFlagsToMapFromEntity( + SessionImplementor session, + Map data, + Object newObj, + Object oldObj) { + if ( propertyData.isUsingModifiedFlag() ) { + data.put( + propertyData.getModifiedFlagPropertyName(), + delegate.mapToMapFromEntity( session, new HashMap(), newObj, oldObj ) + ); } } @Override public void mapModifiedFlagsToMapForCollectionChange(String collectionPropertyName, Map data) { - if (propertyData.isUsingModifiedFlag()) { + if ( propertyData.isUsingModifiedFlag() ) { boolean hasModifiedCollection = false; - for (PropertyData propData : delegate.getProperties().keySet()) { - if (collectionPropertyName.equals(propData.getName())) { + for ( PropertyData propData : delegate.getProperties().keySet() ) { + if ( collectionPropertyName.equals( propData.getName() ) ) { hasModifiedCollection = true; break; } } - data.put(propertyData.getModifiedFlagPropertyName(), hasModifiedCollection); + data.put( propertyData.getModifiedFlagPropertyName(), hasModifiedCollection ); } } - public void mapToEntityFromMap(AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, AuditReaderImplementor versionsReader, Number revision) { - if (data == null || obj == null) { - return; - } + @Override + public void mapToEntityFromMap( + AuditConfiguration verCfg, + Object obj, + Map data, + Object primaryKey, + AuditReaderImplementor versionsReader, + Number revision) { + if ( data == null || obj == null ) { + return; + } - if (propertyData.getBeanName() == null) { - // If properties are not encapsulated in a component but placed directly in a class - // (e.g. by applying tag). - delegate.mapToEntityFromMap(verCfg, obj, data, primaryKey, versionsReader, revision); - return; - } + if ( propertyData.getBeanName() == null ) { + // If properties are not encapsulated in a component but placed directly in a class + // (e.g. by applying tag). + delegate.mapToEntityFromMap( verCfg, obj, data, primaryKey, versionsReader, revision ); + return; + } - Setter setter = ReflectionTools.getSetter(obj.getClass(), propertyData); + final Setter setter = ReflectionTools.getSetter( obj.getClass(), propertyData ); // If all properties are null and single, then the component has to be null also. boolean allNullAndSingle = true; - for (Map.Entry property : delegate.getProperties().entrySet()) { - if (data.get(property.getKey().getName()) != null || !(property.getValue() instanceof SinglePropertyMapper)) { + for ( Map.Entry property : delegate.getProperties().entrySet() ) { + if ( data.get( + property.getKey() + .getName() + ) != null || !(property.getValue() instanceof SinglePropertyMapper) ) { allNullAndSingle = false; break; } } - if (allNullAndSingle) { + if ( allNullAndSingle ) { // single property, but default value need not be null, so we'll set it to null anyway - setter.set(obj, null, null); - } else { + setter.set( obj, null, null ); + } + else { // set the component try { - Object subObj = ReflectHelper.getDefaultConstructor(componentClass).newInstance(); - setter.set(obj, subObj, null); - delegate.mapToEntityFromMap(verCfg, subObj, data, primaryKey, versionsReader, revision); - } catch (Exception e) { - throw new AuditException(e); + final Object subObj = ReflectHelper.getDefaultConstructor( componentClass ).newInstance(); + setter.set( obj, subObj, null ); + delegate.mapToEntityFromMap( verCfg, subObj, data, primaryKey, versionsReader, revision ); + } + catch (Exception e) { + throw new AuditException( e ); } } - } + } - public List mapCollectionChanges(SessionImplementor session, String referencingPropertyName, - PersistentCollection newColl, - Serializable oldColl, Serializable id) { - return delegate.mapCollectionChanges(session, referencingPropertyName, newColl, oldColl, id); - } + @Override + public List mapCollectionChanges( + SessionImplementor session, String referencingPropertyName, + PersistentCollection newColl, + Serializable oldColl, Serializable id) { + return delegate.mapCollectionChanges( session, referencingPropertyName, newColl, oldColl, id ); + } + @Override public Map getProperties() { return delegate.getProperties(); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/CompositeMapperBuilder.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/CompositeMapperBuilder.java index c863249ea0..aa3c5fb8bb 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/CompositeMapperBuilder.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/CompositeMapperBuilder.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -30,8 +30,10 @@ import org.hibernate.envers.internal.entities.PropertyData; /** * @author Adam Warski (adam at warski dot org) */ -public interface CompositeMapperBuilder extends SimpleMapperBuilder { - public CompositeMapperBuilder addComponent(PropertyData propertyData, Class componentClass); - public void addComposite(PropertyData propertyData, PropertyMapper propertyMapper); +public interface CompositeMapperBuilder extends SimpleMapperBuilder { + public CompositeMapperBuilder addComponent(PropertyData propertyData, Class componentClass); + + public void addComposite(PropertyData propertyData, PropertyMapper propertyMapper); + public Map getProperties(); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/ExtendedPropertyMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/ExtendedPropertyMapper.java index a804087836..6c3bec77cc 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/ExtendedPropertyMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/ExtendedPropertyMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper; + import java.util.Map; import org.hibernate.engine.spi.SessionImplementor; @@ -30,5 +31,10 @@ import org.hibernate.engine.spi.SessionImplementor; * @author Adam Warski (adam at warski dot org) */ public interface ExtendedPropertyMapper extends PropertyMapper, CompositeMapperBuilder { - public boolean map(SessionImplementor session, Map data, String[] propertyNames, Object[] newState, Object[] oldState); + public boolean map( + SessionImplementor session, + Map data, + String[] propertyNames, + Object[] newState, + Object[] oldState); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/MultiPropertyMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/MultiPropertyMapper.java index cff9d7aff1..fe99f02166 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/MultiPropertyMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/MultiPropertyMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -43,148 +43,183 @@ import org.hibernate.property.Getter; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class MultiPropertyMapper implements ExtendedPropertyMapper { - protected final Map properties; - private final Map propertyDatas; + protected final Map properties; + private final Map propertyDatas; - public MultiPropertyMapper() { - properties = Tools.newHashMap(); - propertyDatas = Tools.newHashMap(); - } - - public void add(PropertyData propertyData) { - SinglePropertyMapper single = new SinglePropertyMapper(); - single.add(propertyData); - properties.put(propertyData, single); - propertyDatas.put(propertyData.getName(), propertyData); - } - - public CompositeMapperBuilder addComponent(PropertyData propertyData, Class componentClass) { - if (properties.get(propertyData) != null) { - // This is needed for second pass to work properly in the components mapper - return (CompositeMapperBuilder) properties.get(propertyData); - } - - ComponentPropertyMapper componentMapperBuilder = new ComponentPropertyMapper(propertyData, componentClass); - addComposite(propertyData, componentMapperBuilder); - - return componentMapperBuilder; - } - - public void addComposite(PropertyData propertyData, PropertyMapper propertyMapper) { - properties.put(propertyData, propertyMapper); - propertyDatas.put(propertyData.getName(), propertyData); - } - - private Object getAtIndexOrNull(Object[] array, int index) { return array == null ? null : array[index]; } - - public boolean map(SessionImplementor session, Map data, String[] propertyNames, Object[] newState, Object[] oldState) { - boolean ret = false; - for (int i=0; i data, Object newObj, Object oldObj) { - boolean ret = false; - for (PropertyData propertyData : properties.keySet()) { - Getter getter; - if (newObj != null) { - getter = ReflectionTools.getGetter(newObj.getClass(), propertyData); - } else if (oldObj != null) { - getter = ReflectionTools.getGetter(oldObj.getClass(), propertyData); - } else { - return false; - } - - ret |= properties.get(propertyData).mapToMapFromEntity(session, data, - newObj == null ? null : getter.get(newObj), - oldObj == null ? null : getter.get(oldObj)); - } - - return ret; - } - - @Override - public void mapModifiedFlagsToMapFromEntity(SessionImplementor session, Map data, Object newObj, Object oldObj) { - for (PropertyData propertyData : properties.keySet()) { - Getter getter; - if (newObj != null) { - getter = ReflectionTools.getGetter(newObj.getClass(), propertyData); - } else if (oldObj != null) { - getter = ReflectionTools.getGetter(oldObj.getClass(), propertyData); - } else { - return; - } - - properties.get(propertyData).mapModifiedFlagsToMapFromEntity(session, data, - newObj == null ? null : getter.get(newObj), - oldObj == null ? null : getter.get(oldObj)); - } + public MultiPropertyMapper() { + properties = Tools.newHashMap(); + propertyDatas = Tools.newHashMap(); } - public void mapToEntityFromMap(AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, - AuditReaderImplementor versionsReader, Number revision) { - for (PropertyMapper mapper : properties.values()) { - mapper.mapToEntityFromMap(verCfg, obj, data, primaryKey, versionsReader, revision); - } - } + @Override + public void add(PropertyData propertyData) { + final SinglePropertyMapper single = new SinglePropertyMapper(); + single.add( propertyData ); + properties.put( propertyData, single ); + propertyDatas.put( propertyData.getName(), propertyData ); + } - private Pair getMapperAndDelegatePropName(String referencingPropertyName){ + @Override + public CompositeMapperBuilder addComponent(PropertyData propertyData, Class componentClass) { + if ( properties.get( propertyData ) != null ) { + // This is needed for second pass to work properly in the components mapper + return (CompositeMapperBuilder) properties.get( propertyData ); + } + + final ComponentPropertyMapper componentMapperBuilder = new ComponentPropertyMapper( propertyData, componentClass ); + addComposite( propertyData, componentMapperBuilder ); + + return componentMapperBuilder; + } + + @Override + public void addComposite(PropertyData propertyData, PropertyMapper propertyMapper) { + properties.put( propertyData, propertyMapper ); + propertyDatas.put( propertyData.getName(), propertyData ); + } + + private Object getAtIndexOrNull(Object[] array, int index) { + return array == null ? null : array[index]; + } + + @Override + public boolean map( + SessionImplementor session, + Map data, + String[] propertyNames, + Object[] newState, + Object[] oldState) { + boolean ret = false; + for ( int i = 0; i < propertyNames.length; i++ ) { + final String propertyName = propertyNames[i]; + + if ( propertyDatas.containsKey( propertyName ) ) { + final PropertyMapper propertyMapper = properties.get( propertyDatas.get( propertyName ) ); + final Object newObj = getAtIndexOrNull( newState, i ); + final Object oldObj = getAtIndexOrNull( oldState, i ); + ret |= propertyMapper.mapToMapFromEntity( session, data, newObj, oldObj ); + propertyMapper.mapModifiedFlagsToMapFromEntity( session, data, newObj, oldObj ); + } + } + + return ret; + } + + @Override + public boolean mapToMapFromEntity( + SessionImplementor session, + Map data, + Object newObj, + Object oldObj) { + boolean ret = false; + for ( PropertyData propertyData : properties.keySet() ) { + Getter getter; + if ( newObj != null ) { + getter = ReflectionTools.getGetter( newObj.getClass(), propertyData ); + } + else if ( oldObj != null ) { + getter = ReflectionTools.getGetter( oldObj.getClass(), propertyData ); + } + else { + return false; + } + + ret |= properties.get( propertyData ).mapToMapFromEntity( + session, data, + newObj == null ? null : getter.get( newObj ), + oldObj == null ? null : getter.get( oldObj ) + ); + } + + return ret; + } + + @Override + public void mapModifiedFlagsToMapFromEntity( + SessionImplementor session, + Map data, + Object newObj, + Object oldObj) { + for ( PropertyData propertyData : properties.keySet() ) { + Getter getter; + if ( newObj != null ) { + getter = ReflectionTools.getGetter( newObj.getClass(), propertyData ); + } + else if ( oldObj != null ) { + getter = ReflectionTools.getGetter( oldObj.getClass(), propertyData ); + } + else { + return; + } + + properties.get( propertyData ).mapModifiedFlagsToMapFromEntity( + session, data, + newObj == null ? null : getter.get( newObj ), + oldObj == null ? null : getter.get( oldObj ) + ); + } + } + + @Override + public void mapToEntityFromMap( + AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, + AuditReaderImplementor versionsReader, Number revision) { + for ( PropertyMapper mapper : properties.values() ) { + mapper.mapToEntityFromMap( verCfg, obj, data, primaryKey, versionsReader, revision ); + } + } + + private Pair getMapperAndDelegatePropName(String referencingPropertyName) { // Name of the property, to which we will delegate the mapping. String delegatePropertyName; // Checking if the property name doesn't reference a collection in a component - then the name will containa a . - int dotIndex = referencingPropertyName.indexOf('.'); - if (dotIndex != -1) { + final int dotIndex = referencingPropertyName.indexOf( '.' ); + if ( dotIndex != -1 ) { // Computing the name of the component - String componentName = referencingPropertyName.substring(0, dotIndex); + final String componentName = referencingPropertyName.substring( 0, dotIndex ); // And the name of the property in the component - String propertyInComponentName = MappingTools.createComponentPrefix(componentName) - + referencingPropertyName.substring(dotIndex+1); + final String propertyInComponentName = MappingTools.createComponentPrefix( componentName ) + + referencingPropertyName.substring( dotIndex + 1 ); // We need to get the mapper for the component. referencingPropertyName = componentName; // As this is a component, we delegate to the property in the component. delegatePropertyName = propertyInComponentName; - } else { + } + else { // If this is not a component, we delegate to the same property. delegatePropertyName = referencingPropertyName; } - return Pair.make(properties.get(propertyDatas.get(referencingPropertyName)), delegatePropertyName); + return Pair.make( properties.get( propertyDatas.get( referencingPropertyName ) ), delegatePropertyName ); } @Override public void mapModifiedFlagsToMapForCollectionChange(String collectionPropertyName, Map data) { - Pair pair = getMapperAndDelegatePropName(collectionPropertyName); - PropertyMapper mapper = pair.getFirst(); - if (mapper != null) { - mapper.mapModifiedFlagsToMapForCollectionChange(pair.getSecond(), data); + final Pair pair = getMapperAndDelegatePropName( collectionPropertyName ); + final PropertyMapper mapper = pair.getFirst(); + if ( mapper != null ) { + mapper.mapModifiedFlagsToMapForCollectionChange( pair.getSecond(), data ); } } - public List mapCollectionChanges(SessionImplementor session, - String referencingPropertyName, - PersistentCollection newColl, - Serializable oldColl, Serializable id) { - Pair pair = getMapperAndDelegatePropName(referencingPropertyName); - PropertyMapper mapper = pair.getFirst(); - if (mapper != null) { - return mapper.mapCollectionChanges(session, pair.getSecond(), newColl, oldColl, id); - } else { + @Override + public List mapCollectionChanges( + SessionImplementor session, + String referencingPropertyName, + PersistentCollection newColl, + Serializable oldColl, Serializable id) { + final Pair pair = getMapperAndDelegatePropName( referencingPropertyName ); + final PropertyMapper mapper = pair.getFirst(); + if ( mapper != null ) { + return mapper.mapCollectionChanges( session, pair.getSecond(), newColl, oldColl, id ); + } + else { return null; } } + @Override public Map getProperties() { return properties; } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/PersistentCollectionChangeData.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/PersistentCollectionChangeData.java index cce22395ee..ce75a7c83a 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/PersistentCollectionChangeData.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/PersistentCollectionChangeData.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper; + import java.util.Map; import org.hibernate.envers.tools.Pair; @@ -29,58 +30,58 @@ import org.hibernate.envers.tools.Pair; /** * Data describing the change of a single object in a persistent collection (when the object was added, removed or * modified in the collection). + * * @author Adam Warski (adam at warski dot org) */ public class PersistentCollectionChangeData { - private final String entityName; - private final Map data; - private final Object changedElement; + private final String entityName; + private final Map data; + private final Object changedElement; - public PersistentCollectionChangeData(String entityName, Map data, Object changedElement) { - this.entityName = entityName; - this.data = data; - this.changedElement = changedElement; - } + public PersistentCollectionChangeData(String entityName, Map data, Object changedElement) { + this.entityName = entityName; + this.data = data; + this.changedElement = changedElement; + } - /** - * - * @return Name of the (middle) entity that holds the collection data. - */ - public String getEntityName() { - return entityName; - } + /** + * @return Name of the (middle) entity that holds the collection data. + */ + public String getEntityName() { + return entityName; + } - public Map getData() { - return data; - } + public Map getData() { + return data; + } - /** - * @return The affected element, which was changed (added, removed, modified) in the collection. - */ - public Object getChangedElement() { - if (changedElement instanceof Pair) { - return ((Pair) changedElement).getSecond(); - } + /** + * @return The affected element, which was changed (added, removed, modified) in the collection. + */ + public Object getChangedElement() { + if ( changedElement instanceof Pair ) { + return ((Pair) changedElement).getSecond(); + } - if (changedElement instanceof Map.Entry) { - return ((Map.Entry) changedElement).getValue(); - } + if ( changedElement instanceof Map.Entry ) { + return ((Map.Entry) changedElement).getValue(); + } - return changedElement; - } + return changedElement; + } - /** - * @return Index of the affected element, or {@code null} if the collection isn't indexed. - */ - public Object getChangedElementIndex() { - if (changedElement instanceof Pair) { - return ((Pair) changedElement).getFirst(); - } + /** + * @return Index of the affected element, or {@code null} if the collection isn't indexed. + */ + public Object getChangedElementIndex() { + if ( changedElement instanceof Pair ) { + return ((Pair) changedElement).getFirst(); + } - if (changedElement instanceof Map.Entry) { - return ((Map.Entry) changedElement).getKey(); - } + if ( changedElement instanceof Map.Entry ) { + return ((Map.Entry) changedElement).getKey(); + } - return null; - } + return null; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/PropertyMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/PropertyMapper.java index f8e23b044e..43d6acaa14 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/PropertyMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/PropertyMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper; + import java.io.Serializable; import java.util.List; import java.util.Map; @@ -36,41 +37,53 @@ import org.hibernate.envers.internal.reader.AuditReaderImplementor; * @author Michal Skowronek (mskowr at o2 dot pl) */ public interface PropertyMapper { - /** - * Maps properties to the given map, basing on differences between properties of new and old objects. - * @param session The current session. + /** + * Maps properties to the given map, basing on differences between properties of new and old objects. + * + * @param session The current session. * @param data Data to map to. * @param newObj New state of the entity. * @param oldObj Old state of the entity. + * * @return True if there are any differences between the states represented by newObj and oldObj. - */ - boolean mapToMapFromEntity(SessionImplementor session, Map data, Object newObj, Object oldObj); + */ + boolean mapToMapFromEntity(SessionImplementor session, Map data, Object newObj, Object oldObj); - /** - * Maps properties from the given map to the given object. - * @param verCfg Versions configuration. - * @param obj Object to map to. - * @param data Data to map from. - * @param primaryKey Primary key of the object to which we map (for relations) - * @param versionsReader VersionsReader for reading relations - * @param revision Revision at which the object is read, for reading relations - */ - void mapToEntityFromMap(AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, - AuditReaderImplementor versionsReader, Number revision); + /** + * Maps properties from the given map to the given object. + * + * @param verCfg Versions configuration. + * @param obj Object to map to. + * @param data Data to map from. + * @param primaryKey Primary key of the object to which we map (for relations) + * @param versionsReader VersionsReader for reading relations + * @param revision Revision at which the object is read, for reading relations + */ + void mapToEntityFromMap( + AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, + AuditReaderImplementor versionsReader, Number revision); - /** - * Maps collection changes. + /** + * Maps collection changes. + * * @param session The current session. - * @param referencingPropertyName Name of the field, which holds the collection in the entity. - * @param newColl New collection, after updates. - * @param oldColl Old collection, before updates. - * @param id Id of the object owning the collection. - * @return List of changes that need to be performed on the persistent store. - */ - List mapCollectionChanges(SessionImplementor session, String referencingPropertyName, - PersistentCollection newColl, - Serializable oldColl, Serializable id); + * @param referencingPropertyName Name of the field, which holds the collection in the entity. + * @param newColl New collection, after updates. + * @param oldColl Old collection, before updates. + * @param id Id of the object owning the collection. + * + * @return List of changes that need to be performed on the persistent store. + */ + List mapCollectionChanges( + SessionImplementor session, String referencingPropertyName, + PersistentCollection newColl, + Serializable oldColl, Serializable id); + + void mapModifiedFlagsToMapFromEntity( + SessionImplementor session, + Map data, + Object newObj, + Object oldObj); - void mapModifiedFlagsToMapFromEntity(SessionImplementor session, Map data, Object newObj, Object oldObj); void mapModifiedFlagsToMapForCollectionChange(String collectionPropertyName, Map data); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/SimpleMapperBuilder.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/SimpleMapperBuilder.java index 6843e62c63..4e545f845b 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/SimpleMapperBuilder.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/SimpleMapperBuilder.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,11 +22,12 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper; + import org.hibernate.envers.internal.entities.PropertyData; /** * @author Adam Warski (adam at warski dot org) */ -public interface SimpleMapperBuilder { - public void add(PropertyData propertyData); +public interface SimpleMapperBuilder { + public void add(PropertyData propertyData); } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/SinglePropertyMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/SinglePropertyMapper.java index 329955604e..f45f026640 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/SinglePropertyMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/SinglePropertyMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -43,40 +43,53 @@ import org.hibernate.property.Setter; /** * TODO: diff + * * @author Adam Warski (adam at warski dot org) * @author Michal Skowronek (mskowr at o2 dot pl) */ public class SinglePropertyMapper implements PropertyMapper, SimpleMapperBuilder { - private PropertyData propertyData; + private PropertyData propertyData; - public SinglePropertyMapper(PropertyData propertyData) { - this.propertyData = propertyData; - } + public SinglePropertyMapper(PropertyData propertyData) { + this.propertyData = propertyData; + } - public SinglePropertyMapper() { } - - public void add(PropertyData propertyData) { - if (this.propertyData != null) { - throw new AuditException("Only one property can be added!"); - } - - this.propertyData = propertyData; - } - - public boolean mapToMapFromEntity(SessionImplementor session, Map data, Object newObj, Object oldObj) { - data.put(propertyData.getName(), newObj); - boolean dbLogicallyDifferent = true; - if ((session.getFactory().getDialect() instanceof Oracle8iDialect) && (newObj instanceof String || oldObj instanceof String)) { - // Don't generate new revision when database replaces empty string with NULL during INSERT or UPDATE statements. - dbLogicallyDifferent = !(StringTools.isEmpty(newObj) && StringTools.isEmpty(oldObj)); - } - return dbLogicallyDifferent && !Tools.objectsEqual(newObj, oldObj); - } + public SinglePropertyMapper() { + } @Override - public void mapModifiedFlagsToMapFromEntity(SessionImplementor session, Map data, Object newObj, Object oldObj) { - if (propertyData.isUsingModifiedFlag()) { - data.put(propertyData.getModifiedFlagPropertyName(), !Tools.objectsEqual(newObj, oldObj)); + public void add(PropertyData propertyData) { + if ( this.propertyData != null ) { + throw new AuditException( "Only one property can be added!" ); + } + + this.propertyData = propertyData; + } + + @Override + public boolean mapToMapFromEntity( + SessionImplementor session, + Map data, + Object newObj, + Object oldObj) { + data.put( propertyData.getName(), newObj ); + boolean dbLogicallyDifferent = true; + if ( (session.getFactory() + .getDialect() instanceof Oracle8iDialect) && (newObj instanceof String || oldObj instanceof String) ) { + // Don't generate new revision when database replaces empty string with NULL during INSERT or UPDATE statements. + dbLogicallyDifferent = !(StringTools.isEmpty( newObj ) && StringTools.isEmpty( oldObj )); + } + return dbLogicallyDifferent && !Tools.objectsEqual( newObj, oldObj ); + } + + @Override + public void mapModifiedFlagsToMapFromEntity( + SessionImplementor session, + Map data, + Object newObj, + Object oldObj) { + if ( propertyData.isUsingModifiedFlag() ) { + data.put( propertyData.getModifiedFlagPropertyName(), !Tools.objectsEqual( newObj, oldObj ) ); } } @@ -84,43 +97,50 @@ public class SinglePropertyMapper implements PropertyMapper, SimpleMapperBuilder public void mapModifiedFlagsToMapForCollectionChange(String collectionPropertyName, Map data) { } - public void mapToEntityFromMap(AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, - AuditReaderImplementor versionsReader, Number revision) { - if (data == null || obj == null) { - return; - } - - Setter setter = ReflectionTools.getSetter(obj.getClass(), propertyData); - Object value = data.get(propertyData.getName()); - // We only set a null value if the field is not primite. Otherwise, we leave it intact. - if (value != null || !isPrimitive(setter, propertyData, obj.getClass())) { - setter.set(obj, value, null); + @Override + public void mapToEntityFromMap( + AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, + AuditReaderImplementor versionsReader, Number revision) { + if ( data == null || obj == null ) { + return; } - } + + final Setter setter = ReflectionTools.getSetter( obj.getClass(), propertyData ); + final Object value = data.get( propertyData.getName() ); + // We only set a null value if the field is not primite. Otherwise, we leave it intact. + if ( value != null || !isPrimitive( setter, propertyData, obj.getClass() ) ) { + setter.set( obj, value, null ); + } + } private boolean isPrimitive(Setter setter, PropertyData propertyData, Class cls) { - if (cls == null) { - throw new HibernateException("No field found for property: " + propertyData.getName()); + if ( cls == null ) { + throw new HibernateException( "No field found for property: " + propertyData.getName() ); } - if (setter instanceof DirectPropertyAccessor.DirectSetter) { + if ( setter instanceof DirectPropertyAccessor.DirectSetter ) { // In a direct setter, getMethod() returns null // Trying to look up the field try { - return cls.getDeclaredField(propertyData.getBeanName()).getType().isPrimitive(); - } catch (NoSuchFieldException e) { - return isPrimitive(setter, propertyData, cls.getSuperclass()); + return cls.getDeclaredField( propertyData.getBeanName() ).getType().isPrimitive(); } - } else { + catch (NoSuchFieldException e) { + return isPrimitive( setter, propertyData, cls.getSuperclass() ); + } + } + else { return setter.getMethod().getParameterTypes()[0].isPrimitive(); } } - public List mapCollectionChanges(SessionImplementor sessionImplementor, - String referencingPropertyName, - PersistentCollection newColl, - Serializable oldColl, Serializable id) { - return null; - } + @Override + public List mapCollectionChanges( + SessionImplementor sessionImplementor, + String referencingPropertyName, + PersistentCollection newColl, + Serializable oldColl, + Serializable id) { + return null; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/SubclassPropertyMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/SubclassPropertyMapper.java index f673d6e5a9..3696a30dd6 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/SubclassPropertyMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/SubclassPropertyMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper; + import java.io.Serializable; import java.util.HashMap; import java.util.List; @@ -36,84 +37,124 @@ import org.hibernate.envers.internal.reader.AuditReaderImplementor; /** * A mapper which maps from a parent mapper and a "main" one, but adds only to the "main". The "main" mapper * should be the mapper of the subclass. + * * @author Adam Warski (adam at warski dot org) * @author Michal Skowronek (mskowr at o2 dot pl) */ public class SubclassPropertyMapper implements ExtendedPropertyMapper { - private ExtendedPropertyMapper main; - private ExtendedPropertyMapper parentMapper; + private ExtendedPropertyMapper main; + private ExtendedPropertyMapper parentMapper; - public SubclassPropertyMapper(ExtendedPropertyMapper main, ExtendedPropertyMapper parentMapper) { - this.main = main; - this.parentMapper = parentMapper; - } - - public boolean map(SessionImplementor session, Map data, String[] propertyNames, Object[] newState, Object[] oldState) { - boolean parentDiffs = parentMapper.map(session, data, propertyNames, newState, oldState); - boolean mainDiffs = main.map(session, data, propertyNames, newState, oldState); - - return parentDiffs || mainDiffs; - } - - public boolean mapToMapFromEntity(SessionImplementor session, Map data, Object newObj, Object oldObj) { - boolean parentDiffs = parentMapper.mapToMapFromEntity(session, data, newObj, oldObj); - boolean mainDiffs = main.mapToMapFromEntity(session, data, newObj, oldObj); - - return parentDiffs || mainDiffs; - } + public SubclassPropertyMapper(ExtendedPropertyMapper main, ExtendedPropertyMapper parentMapper) { + this.main = main; + this.parentMapper = parentMapper; + } @Override - public void mapModifiedFlagsToMapFromEntity(SessionImplementor session, Map data, Object newObj, Object oldObj) { - parentMapper.mapModifiedFlagsToMapFromEntity(session, data, newObj, oldObj); - main.mapModifiedFlagsToMapFromEntity(session, data, newObj, oldObj); + public boolean map( + SessionImplementor session, + Map data, + String[] propertyNames, + Object[] newState, + Object[] oldState) { + final boolean parentDiffs = parentMapper.map( session, data, propertyNames, newState, oldState ); + final boolean mainDiffs = main.map( session, data, propertyNames, newState, oldState ); + + return parentDiffs || mainDiffs; + } + + @Override + public boolean mapToMapFromEntity( + SessionImplementor session, + Map data, + Object newObj, + Object oldObj) { + final boolean parentDiffs = parentMapper.mapToMapFromEntity( session, data, newObj, oldObj ); + final boolean mainDiffs = main.mapToMapFromEntity( session, data, newObj, oldObj ); + + return parentDiffs || mainDiffs; + } + + @Override + public void mapModifiedFlagsToMapFromEntity( + SessionImplementor session, + Map data, + Object newObj, + Object oldObj) { + parentMapper.mapModifiedFlagsToMapFromEntity( session, data, newObj, oldObj ); + main.mapModifiedFlagsToMapFromEntity( session, data, newObj, oldObj ); } @Override public void mapModifiedFlagsToMapForCollectionChange(String collectionPropertyName, Map data) { - parentMapper.mapModifiedFlagsToMapForCollectionChange(collectionPropertyName, data); - main.mapModifiedFlagsToMapForCollectionChange(collectionPropertyName, data); + parentMapper.mapModifiedFlagsToMapForCollectionChange( collectionPropertyName, data ); + main.mapModifiedFlagsToMapForCollectionChange( collectionPropertyName, data ); } - public void mapToEntityFromMap(AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, AuditReaderImplementor versionsReader, Number revision) { - parentMapper.mapToEntityFromMap(verCfg, obj, data, primaryKey, versionsReader, revision); - main.mapToEntityFromMap(verCfg, obj, data, primaryKey, versionsReader, revision); - } + @Override + public void mapToEntityFromMap( + AuditConfiguration verCfg, + Object obj, + Map data, + Object primaryKey, + AuditReaderImplementor versionsReader, + Number revision) { + parentMapper.mapToEntityFromMap( verCfg, obj, data, primaryKey, versionsReader, revision ); + main.mapToEntityFromMap( verCfg, obj, data, primaryKey, versionsReader, revision ); + } - public List mapCollectionChanges(SessionImplementor session, String referencingPropertyName, - PersistentCollection newColl, - Serializable oldColl, Serializable id) { - List parentCollectionChanges = parentMapper.mapCollectionChanges( - session, referencingPropertyName, newColl, oldColl, id); + @Override + public List mapCollectionChanges( + SessionImplementor session, String referencingPropertyName, + PersistentCollection newColl, + Serializable oldColl, Serializable id) { + final List parentCollectionChanges = parentMapper.mapCollectionChanges( + session, + referencingPropertyName, + newColl, + oldColl, + id + ); - List mainCollectionChanges = main.mapCollectionChanges( - session, referencingPropertyName, newColl, oldColl, id); + final List mainCollectionChanges = main.mapCollectionChanges( + session, + referencingPropertyName, + newColl, + oldColl, + id + ); - if (parentCollectionChanges == null) { - return mainCollectionChanges; - } else { - if(mainCollectionChanges != null) { - parentCollectionChanges.addAll(mainCollectionChanges); - } + if ( parentCollectionChanges == null ) { + return mainCollectionChanges; + } + else { + if ( mainCollectionChanges != null ) { + parentCollectionChanges.addAll( mainCollectionChanges ); + } return parentCollectionChanges; - } - } + } + } - public CompositeMapperBuilder addComponent(PropertyData propertyData, Class componentClass) { - return main.addComponent(propertyData, componentClass); - } + @Override + public CompositeMapperBuilder addComponent(PropertyData propertyData, Class componentClass) { + return main.addComponent( propertyData, componentClass ); + } - public void addComposite(PropertyData propertyData, PropertyMapper propertyMapper) { - main.addComposite(propertyData, propertyMapper); - } + @Override + public void addComposite(PropertyData propertyData, PropertyMapper propertyMapper) { + main.addComposite( propertyData, propertyMapper ); + } - public void add(PropertyData propertyData) { - main.add(propertyData); - } + @Override + public void add(PropertyData propertyData) { + main.add( propertyData ); + } + @Override public Map getProperties() { final Map joinedProperties = new HashMap(); - joinedProperties.putAll(parentMapper.getProperties()); - joinedProperties.putAll(main.getProperties()); + joinedProperties.putAll( parentMapper.getProperties() ); + joinedProperties.putAll( main.getProperties() ); return joinedProperties; } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/AbstractCompositeIdMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/AbstractCompositeIdMapper.java index c60531148a..7909a8880c 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/AbstractCompositeIdMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/AbstractCompositeIdMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -35,36 +35,39 @@ import org.hibernate.internal.util.ReflectHelper; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public abstract class AbstractCompositeIdMapper extends AbstractIdMapper implements SimpleIdMapperBuilder { - protected Map ids; - protected Class compositeIdClass; + protected Map ids; + protected Class compositeIdClass; - protected AbstractCompositeIdMapper(Class compositeIdClass) { - ids = Tools.newLinkedHashMap(); - this.compositeIdClass = compositeIdClass; - } + protected AbstractCompositeIdMapper(Class compositeIdClass) { + ids = Tools.newLinkedHashMap(); + this.compositeIdClass = compositeIdClass; + } - public void add(PropertyData propertyData) { - ids.put(propertyData, new SingleIdMapper(propertyData)); - } + @Override + public void add(PropertyData propertyData) { + ids.put( propertyData, new SingleIdMapper( propertyData ) ); + } - public Object mapToIdFromMap(Map data) { - if (data == null) { - return null; - } + @Override + public Object mapToIdFromMap(Map data) { + if ( data == null ) { + return null; + } - Object ret; - try { - ret = ReflectHelper.getDefaultConstructor(compositeIdClass).newInstance(); - } catch (Exception e) { - throw new AuditException(e); - } + final Object ret; + try { + ret = ReflectHelper.getDefaultConstructor( compositeIdClass ).newInstance(); + } + catch (Exception e) { + throw new AuditException( e ); + } - for (SingleIdMapper mapper : ids.values()) { - if (!mapper.mapToEntityFromMap(ret, data)) { - return null; - } - } + for ( SingleIdMapper mapper : ids.values() ) { + if ( !mapper.mapToEntityFromMap( ret, data ) ) { + return null; + } + } - return ret; - } + return ret; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/AbstractIdMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/AbstractIdMapper.java index 111c7b6c54..28eb8dfa3c 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/AbstractIdMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/AbstractIdMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.id; + import java.util.Iterator; import java.util.List; @@ -31,69 +32,96 @@ import org.hibernate.envers.internal.tools.query.Parameters; * @author Adam Warski (adam at warski dot org) */ public abstract class AbstractIdMapper implements IdMapper { - private Parameters getParametersToUse(Parameters parameters, List paramDatas) { - if (paramDatas.size() > 1) { - return parameters.addSubParameters("and"); - } else { - return parameters; - } - } + private Parameters getParametersToUse(Parameters parameters, List paramDatas) { + if ( paramDatas.size() > 1 ) { + return parameters.addSubParameters( "and" ); + } + else { + return parameters; + } + } - public void addIdsEqualToQuery(Parameters parameters, String prefix1, String prefix2) { - List paramDatas = mapToQueryParametersFromId(null); + @Override + public void addIdsEqualToQuery(Parameters parameters, String prefix1, String prefix2) { + final List paramDatas = mapToQueryParametersFromId( null ); - Parameters parametersToUse = getParametersToUse(parameters, paramDatas); + final Parameters parametersToUse = getParametersToUse( parameters, paramDatas ); - for (QueryParameterData paramData : paramDatas) { - parametersToUse.addWhere(paramData.getProperty(prefix1), false, "=", paramData.getProperty(prefix2), false); - } - } + for ( QueryParameterData paramData : paramDatas ) { + parametersToUse.addWhere( + paramData.getProperty( prefix1 ), + false, + "=", + paramData.getProperty( prefix2 ), + false + ); + } + } - public void addIdsEqualToQuery(Parameters parameters, String prefix1, IdMapper mapper2, String prefix2) { - List paramDatas1 = mapToQueryParametersFromId(null); - List paramDatas2 = mapper2.mapToQueryParametersFromId(null); + @Override + public void addIdsEqualToQuery(Parameters parameters, String prefix1, IdMapper mapper2, String prefix2) { + final List paramDatas1 = mapToQueryParametersFromId( null ); + final List paramDatas2 = mapper2.mapToQueryParametersFromId( null ); - Parameters parametersToUse = getParametersToUse(parameters, paramDatas1); + final Parameters parametersToUse = getParametersToUse( parameters, paramDatas1 ); - Iterator paramDataIter1 = paramDatas1.iterator(); - Iterator paramDataIter2 = paramDatas2.iterator(); - while (paramDataIter1.hasNext()) { - QueryParameterData paramData1 = paramDataIter1.next(); - QueryParameterData paramData2 = paramDataIter2.next(); + final Iterator paramDataIter1 = paramDatas1.iterator(); + final Iterator paramDataIter2 = paramDatas2.iterator(); + while ( paramDataIter1.hasNext() ) { + final QueryParameterData paramData1 = paramDataIter1.next(); + final QueryParameterData paramData2 = paramDataIter2.next(); - parametersToUse.addWhere(paramData1.getProperty(prefix1), false, "=", paramData2.getProperty(prefix2), false); - } - } + parametersToUse.addWhere( + paramData1.getProperty( prefix1 ), + false, + "=", + paramData2.getProperty( prefix2 ), + false + ); + } + } - public void addIdEqualsToQuery(Parameters parameters, Object id, String prefix, boolean equals) { - List paramDatas = mapToQueryParametersFromId(id); + @Override + public void addIdEqualsToQuery(Parameters parameters, Object id, String prefix, boolean equals) { + final List paramDatas = mapToQueryParametersFromId( id ); - Parameters parametersToUse = getParametersToUse(parameters, paramDatas); + final Parameters parametersToUse = getParametersToUse( parameters, paramDatas ); - for (QueryParameterData paramData : paramDatas) { - if (paramData.getValue() == null) { - handleNullValue(parametersToUse, paramData.getProperty(prefix), equals); - } else { - parametersToUse.addWhereWithParam(paramData.getProperty(prefix), equals ? "=" : "<>", paramData.getValue()); - } - } - } + for ( QueryParameterData paramData : paramDatas ) { + if ( paramData.getValue() == null ) { + handleNullValue( parametersToUse, paramData.getProperty( prefix ), equals ); + } + else { + parametersToUse.addWhereWithParam( + paramData.getProperty( prefix ), + equals ? "=" : "<>", + paramData.getValue() + ); + } + } + } - public void addNamedIdEqualsToQuery(Parameters parameters, String prefix, boolean equals) { - List paramDatas = mapToQueryParametersFromId(null); + @Override + public void addNamedIdEqualsToQuery(Parameters parameters, String prefix, boolean equals) { + final List paramDatas = mapToQueryParametersFromId( null ); - Parameters parametersToUse = getParametersToUse(parameters, paramDatas); + final Parameters parametersToUse = getParametersToUse( parameters, paramDatas ); - for (QueryParameterData paramData : paramDatas) { - parametersToUse.addWhereWithNamedParam(paramData.getProperty(prefix), equals ? "=" : "<>", paramData.getQueryParameterName()); - } - } + for ( QueryParameterData paramData : paramDatas ) { + parametersToUse.addWhereWithNamedParam( + paramData.getProperty( prefix ), + equals ? "=" : "<>", + paramData.getQueryParameterName() + ); + } + } - private void handleNullValue(Parameters parameters, String propertyName, boolean equals) { - if (equals) { - parameters.addNullRestriction(propertyName, equals); - } else { - parameters.addNotNullRestriction(propertyName, equals); - } - } + private void handleNullValue(Parameters parameters, String propertyName, boolean equals) { + if ( equals ) { + parameters.addNullRestriction( propertyName, equals ); + } + else { + parameters.addNotNullRestriction( propertyName, equals ); + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/EmbeddedIdMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/EmbeddedIdMapper.java index 4cdc539f91..f965d39f9d 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/EmbeddedIdMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/EmbeddedIdMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -39,85 +39,92 @@ import org.hibernate.property.Setter; * @author Adam Warski (adam at warski dot org) */ public class EmbeddedIdMapper extends AbstractCompositeIdMapper implements SimpleIdMapperBuilder { - private PropertyData idPropertyData; + private PropertyData idPropertyData; - public EmbeddedIdMapper(PropertyData idPropertyData, Class compositeIdClass) { - super(compositeIdClass); + public EmbeddedIdMapper(PropertyData idPropertyData, Class compositeIdClass) { + super( compositeIdClass ); - this.idPropertyData = idPropertyData; - } + this.idPropertyData = idPropertyData; + } - public void mapToMapFromId(Map data, Object obj) { - for (IdMapper idMapper : ids.values()) { - idMapper.mapToMapFromEntity(data, obj); - } - } + @Override + public void mapToMapFromId(Map data, Object obj) { + for ( IdMapper idMapper : ids.values() ) { + idMapper.mapToMapFromEntity( data, obj ); + } + } - public void mapToMapFromEntity(Map data, Object obj) { - if (obj == null) { - return; - } + @Override + public void mapToMapFromEntity(Map data, Object obj) { + if ( obj == null ) { + return; + } - Getter getter = ReflectionTools.getGetter(obj.getClass(), idPropertyData); - mapToMapFromId(data, getter.get(obj)); - } + final Getter getter = ReflectionTools.getGetter( obj.getClass(), idPropertyData ); + mapToMapFromId( data, getter.get( obj ) ); + } - public boolean mapToEntityFromMap(Object obj, Map data) { - if (data == null || obj == null) { - return false; - } + @Override + public boolean mapToEntityFromMap(Object obj, Map data) { + if ( data == null || obj == null ) { + return false; + } - Getter getter = ReflectionTools.getGetter(obj.getClass(), idPropertyData); - Setter setter = ReflectionTools.getSetter(obj.getClass(), idPropertyData); + final Getter getter = ReflectionTools.getGetter( obj.getClass(), idPropertyData ); + final Setter setter = ReflectionTools.getSetter( obj.getClass(), idPropertyData ); - try { - Object subObj = ReflectHelper.getDefaultConstructor( getter.getReturnType() ).newInstance(); + try { + final Object subObj = ReflectHelper.getDefaultConstructor( getter.getReturnType() ).newInstance(); - boolean ret = true; - for (IdMapper idMapper : ids.values()) { - ret &= idMapper.mapToEntityFromMap(subObj, data); - } + boolean ret = true; + for ( IdMapper idMapper : ids.values() ) { + ret &= idMapper.mapToEntityFromMap( subObj, data ); + } - if (ret) { - setter.set(obj, subObj, null); - } + if ( ret ) { + setter.set( obj, subObj, null ); + } - return ret; - } catch (Exception e) { - throw new AuditException(e); - } - } + return ret; + } + catch (Exception e) { + throw new AuditException( e ); + } + } - public IdMapper prefixMappedProperties(String prefix) { - EmbeddedIdMapper ret = new EmbeddedIdMapper(idPropertyData, compositeIdClass); + @Override + public IdMapper prefixMappedProperties(String prefix) { + final EmbeddedIdMapper ret = new EmbeddedIdMapper( idPropertyData, compositeIdClass ); - for (PropertyData propertyData : ids.keySet()) { - String propertyName = propertyData.getName(); - ret.ids.put(propertyData, new SingleIdMapper(new PropertyData(prefix + propertyName, propertyData))); - } + for ( PropertyData propertyData : ids.keySet() ) { + final String propertyName = propertyData.getName(); + ret.ids.put( propertyData, new SingleIdMapper( new PropertyData( prefix + propertyName, propertyData ) ) ); + } - return ret; - } + return ret; + } - public Object mapToIdFromEntity(Object data) { - if (data == null) { - return null; - } + @Override + public Object mapToIdFromEntity(Object data) { + if ( data == null ) { + return null; + } - Getter getter = ReflectionTools.getGetter(data.getClass(), idPropertyData); - return getter.get(data); - } + final Getter getter = ReflectionTools.getGetter( data.getClass(), idPropertyData ); + return getter.get( data ); + } - public List mapToQueryParametersFromId(Object obj) { - Map data = new LinkedHashMap(); - mapToMapFromId(data, obj); + @Override + public List mapToQueryParametersFromId(Object obj) { + final Map data = new LinkedHashMap(); + mapToMapFromId( data, obj ); - List ret = new ArrayList(); + final List ret = new ArrayList(); - for (Map.Entry propertyData : data.entrySet()) { - ret.add(new QueryParameterData(propertyData.getKey(), propertyData.getValue())); - } + for ( Map.Entry propertyData : data.entrySet() ) { + ret.add( new QueryParameterData( propertyData.getKey(), propertyData.getValue() ) ); + } - return ret; - } + return ret; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/IdMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/IdMapper.java index c490b1ea1f..b292ad0fd8 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/IdMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/IdMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.id; + import java.util.List; import java.util.Map; @@ -31,73 +32,81 @@ import org.hibernate.envers.internal.tools.query.Parameters; * @author Adam Warski (adam at warski dot org) */ public interface IdMapper { - void mapToMapFromId(Map data, Object obj); + void mapToMapFromId(Map data, Object obj); - void mapToMapFromEntity(Map data, Object obj); + void mapToMapFromEntity(Map data, Object obj); - /** - * @param obj Object to map to. - * @param data Data to map. - * @return True if data was mapped; false otherwise (when the id is {@code null}). - */ - boolean mapToEntityFromMap(Object obj, Map data); + /** + * @param obj Object to map to. + * @param data Data to map. + * + * @return True if data was mapped; false otherwise (when the id is {@code null}). + */ + boolean mapToEntityFromMap(Object obj, Map data); - Object mapToIdFromEntity(Object data); + Object mapToIdFromEntity(Object data); - Object mapToIdFromMap(Map data); + Object mapToIdFromMap(Map data); - /** - * Creates a mapper with all mapped properties prefixed. A mapped property is a property which - * is directly mapped to values (not composite). - * @param prefix Prefix to add to mapped properties - * @return A copy of the current property mapper, with mapped properties prefixed. - */ - IdMapper prefixMappedProperties(String prefix); + /** + * Creates a mapper with all mapped properties prefixed. A mapped property is a property which + * is directly mapped to values (not composite). + * + * @param prefix Prefix to add to mapped properties + * + * @return A copy of the current property mapper, with mapped properties prefixed. + */ + IdMapper prefixMappedProperties(String prefix); - /** - * @param obj Id from which to map. - * @return A set parameter data, needed to build a query basing on the given id. - */ - List mapToQueryParametersFromId(Object obj); + /** + * @param obj Id from which to map. + * + * @return A set parameter data, needed to build a query basing on the given id. + */ + List mapToQueryParametersFromId(Object obj); - /** - * Adds query statements, which contains restrictions, which express the property that the id of the entity - * with alias prefix1, is equal to the id of the entity with alias prefix2 (the entity is the same). - * @param parameters Parameters, to which to add the statements. - * @param prefix1 First alias of the entity + prefix to add to the properties. - * @param prefix2 Second alias of the entity + prefix to add to the properties. - */ - void addIdsEqualToQuery(Parameters parameters, String prefix1, String prefix2); + /** + * Adds query statements, which contains restrictions, which express the property that the id of the entity + * with alias prefix1, is equal to the id of the entity with alias prefix2 (the entity is the same). + * + * @param parameters Parameters, to which to add the statements. + * @param prefix1 First alias of the entity + prefix to add to the properties. + * @param prefix2 Second alias of the entity + prefix to add to the properties. + */ + void addIdsEqualToQuery(Parameters parameters, String prefix1, String prefix2); - /** - * Adds query statements, which contains restrictions, which express the property that the id of the entity - * with alias prefix1, is equal to the id of the entity with alias prefix2 mapped by the second mapper - * (the second mapper must be for the same entity, but it can have, for example, prefixed properties). - * @param parameters Parameters, to which to add the statements. - * @param prefix1 First alias of the entity + prefix to add to the properties. - * @param mapper2 Second mapper for the same entity, which will be used to get properties for the right side - * of the equation. - * @param prefix2 Second alias of the entity + prefix to add to the properties. - */ - void addIdsEqualToQuery(Parameters parameters, String prefix1, IdMapper mapper2, String prefix2); + /** + * Adds query statements, which contains restrictions, which express the property that the id of the entity + * with alias prefix1, is equal to the id of the entity with alias prefix2 mapped by the second mapper + * (the second mapper must be for the same entity, but it can have, for example, prefixed properties). + * + * @param parameters Parameters, to which to add the statements. + * @param prefix1 First alias of the entity + prefix to add to the properties. + * @param mapper2 Second mapper for the same entity, which will be used to get properties for the right side + * of the equation. + * @param prefix2 Second alias of the entity + prefix to add to the properties. + */ + void addIdsEqualToQuery(Parameters parameters, String prefix1, IdMapper mapper2, String prefix2); - /** - * Adds query statements, which contains restrictions, which express the property that the id of the entity - * with alias prefix, is equal to the given object. - * @param parameters Parameters, to which to add the statements. - * @param id Value of id. - * @param prefix Prefix to add to the properties (may be null). - * @param equals Should this query express the "=" relation or the "<>" relation. - */ - void addIdEqualsToQuery(Parameters parameters, Object id, String prefix, boolean equals); + /** + * Adds query statements, which contains restrictions, which express the property that the id of the entity + * with alias prefix, is equal to the given object. + * + * @param parameters Parameters, to which to add the statements. + * @param id Value of id. + * @param prefix Prefix to add to the properties (may be null). + * @param equals Should this query express the "=" relation or the "<>" relation. + */ + void addIdEqualsToQuery(Parameters parameters, Object id, String prefix, boolean equals); - /** - * Adds query statements, which contains named parameters, which express the property that the id of the entity - * with alias prefix, is equal to the given object. It is the responsibility of the using method to read - * parameter values from the id and specify them on the final query object. - * @param parameters Parameters, to which to add the statements. - * @param prefix Prefix to add to the properties (may be null). - * @param equals Should this query express the "=" relation or the "<>" relation. - */ - void addNamedIdEqualsToQuery(Parameters parameters, String prefix, boolean equals); + /** + * Adds query statements, which contains named parameters, which express the property that the id of the entity + * with alias prefix, is equal to the given object. It is the responsibility of the using method to read + * parameter values from the id and specify them on the final query object. + * + * @param parameters Parameters, to which to add the statements. + * @param prefix Prefix to add to the properties (may be null). + * @param equals Should this query express the "=" relation or the "<>" relation. + */ + void addNamedIdEqualsToQuery(Parameters parameters, String prefix, boolean equals); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/MultipleIdMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/MultipleIdMapper.java index 25f5e4a1a5..aadf588ac3 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/MultipleIdMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/MultipleIdMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -36,69 +36,76 @@ import org.hibernate.internal.util.ReflectHelper; * @author Adam Warski (adam at warski dot org) */ public class MultipleIdMapper extends AbstractCompositeIdMapper implements SimpleIdMapperBuilder { - public MultipleIdMapper(Class compositeIdClass) { - super(compositeIdClass); - } + public MultipleIdMapper(Class compositeIdClass) { + super( compositeIdClass ); + } - public void mapToMapFromId(Map data, Object obj) { - for (IdMapper idMapper : ids.values()) { - idMapper.mapToMapFromEntity(data, obj); - } - } + @Override + public void mapToMapFromId(Map data, Object obj) { + for ( IdMapper idMapper : ids.values() ) { + idMapper.mapToMapFromEntity( data, obj ); + } + } - public void mapToMapFromEntity(Map data, Object obj) { - mapToMapFromId(data, obj); - } + @Override + public void mapToMapFromEntity(Map data, Object obj) { + mapToMapFromId( data, obj ); + } - public boolean mapToEntityFromMap(Object obj, Map data) { - boolean ret = true; - for (IdMapper idMapper : ids.values()) { - ret &= idMapper.mapToEntityFromMap(obj, data); - } + @Override + public boolean mapToEntityFromMap(Object obj, Map data) { + boolean ret = true; + for ( IdMapper idMapper : ids.values() ) { + ret &= idMapper.mapToEntityFromMap( obj, data ); + } - return ret; - } + return ret; + } - public IdMapper prefixMappedProperties(String prefix) { - MultipleIdMapper ret = new MultipleIdMapper(compositeIdClass); + @Override + public IdMapper prefixMappedProperties(String prefix) { + final MultipleIdMapper ret = new MultipleIdMapper( compositeIdClass ); - for (PropertyData propertyData : ids.keySet()) { - String propertyName = propertyData.getName(); - ret.ids.put(propertyData, new SingleIdMapper(new PropertyData(prefix + propertyName, propertyData))); - } + for ( PropertyData propertyData : ids.keySet() ) { + final String propertyName = propertyData.getName(); + ret.ids.put( propertyData, new SingleIdMapper( new PropertyData( prefix + propertyName, propertyData ) ) ); + } - return ret; - } + return ret; + } - public Object mapToIdFromEntity(Object data) { - if (data == null) { - return null; - } + @Override + public Object mapToIdFromEntity(Object data) { + if ( data == null ) { + return null; + } - Object ret; - try { - ret = ReflectHelper.getDefaultConstructor(compositeIdClass).newInstance(); - } catch (Exception e) { - throw new AuditException(e); - } + final Object ret; + try { + ret = ReflectHelper.getDefaultConstructor( compositeIdClass ).newInstance(); + } + catch (Exception e) { + throw new AuditException( e ); + } - for (SingleIdMapper mapper : ids.values()) { - mapper.mapToEntityFromEntity(ret, data); - } + for ( SingleIdMapper mapper : ids.values() ) { + mapper.mapToEntityFromEntity( ret, data ); + } - return ret; - } + return ret; + } - public List mapToQueryParametersFromId(Object obj) { - Map data = new LinkedHashMap(); - mapToMapFromId(data, obj); + @Override + public List mapToQueryParametersFromId(Object obj) { + final Map data = new LinkedHashMap(); + mapToMapFromId( data, obj ); - List ret = new ArrayList(); + final List ret = new ArrayList(); - for (Map.Entry propertyData : data.entrySet()) { - ret.add(new QueryParameterData(propertyData.getKey(), propertyData.getValue())); - } + for ( Map.Entry propertyData : data.entrySet() ) { + ret.add( new QueryParameterData( propertyData.getKey(), propertyData.getValue() ) ); + } - return ret; - } + return ret; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/QueryParameterData.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/QueryParameterData.java index 75201a220d..a87c2d6dae 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/QueryParameterData.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/QueryParameterData.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,53 +22,58 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.id; + import org.hibernate.Query; +import org.hibernate.internal.util.compare.EqualsHelper; /** * @author Adam Warski (adam at warski dot org) */ public class QueryParameterData { - private String flatEntityPropertyName; - private Object value; + private String flatEntityPropertyName; + private Object value; - public QueryParameterData(String flatEntityPropertyName, Object value) { - this.flatEntityPropertyName = flatEntityPropertyName; - this.value = value; - } + public QueryParameterData(String flatEntityPropertyName, Object value) { + this.flatEntityPropertyName = flatEntityPropertyName; + this.value = value; + } - public String getProperty(String prefix) { - if (prefix != null) { - return prefix + "." + flatEntityPropertyName; - } else { - return flatEntityPropertyName; - } - } + public String getProperty(String prefix) { + if ( prefix != null ) { + return prefix + "." + flatEntityPropertyName; + } + else { + return flatEntityPropertyName; + } + } - public Object getValue() { - return value; - } + public Object getValue() { + return value; + } - public void setParameterValue(Query query) { - query.setParameter(flatEntityPropertyName, value); - } + public void setParameterValue(Query query) { + query.setParameter( flatEntityPropertyName, value ); + } - public String getQueryParameterName() { - return flatEntityPropertyName; - } + public String getQueryParameterName() { + return flatEntityPropertyName; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof QueryParameterData)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof QueryParameterData) ) { + return false; + } - QueryParameterData that = (QueryParameterData) o; + final QueryParameterData that = (QueryParameterData) o; + return EqualsHelper.equals( flatEntityPropertyName, that.flatEntityPropertyName ); + } - if (flatEntityPropertyName != null ? !flatEntityPropertyName.equals(that.flatEntityPropertyName) : that.flatEntityPropertyName != null) - return false; - - return true; - } - - public int hashCode() { - return (flatEntityPropertyName != null ? flatEntityPropertyName.hashCode() : 0); - } + @Override + public int hashCode() { + return (flatEntityPropertyName != null ? flatEntityPropertyName.hashCode() : 0); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/SimpleIdMapperBuilder.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/SimpleIdMapperBuilder.java index 12039e4de2..65bfc8d643 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/SimpleIdMapperBuilder.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/SimpleIdMapperBuilder.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.id; + import org.hibernate.envers.internal.entities.mapper.SimpleMapperBuilder; /** diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/SingleIdMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/SingleIdMapper.java index 0f14c16c4f..376c36f937 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/SingleIdMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/id/SingleIdMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -38,100 +38,111 @@ import org.hibernate.proxy.HibernateProxy; * @author Adam Warski (adam at warski dot org) */ public class SingleIdMapper extends AbstractIdMapper implements SimpleIdMapperBuilder { - private PropertyData propertyData; + private PropertyData propertyData; - public SingleIdMapper() { - } + public SingleIdMapper() { + } - public SingleIdMapper(PropertyData propertyData) { - this.propertyData = propertyData; - } + public SingleIdMapper(PropertyData propertyData) { + this.propertyData = propertyData; + } - public void add(PropertyData propertyData) { - if (this.propertyData != null) { - throw new AuditException("Only one property can be added!"); - } + @Override + public void add(PropertyData propertyData) { + if ( this.propertyData != null ) { + throw new AuditException( "Only one property can be added!" ); + } - this.propertyData = propertyData; - } + this.propertyData = propertyData; + } - public boolean mapToEntityFromMap(Object obj, Map data) { - if (data == null || obj == null) { - return false; - } + @Override + public boolean mapToEntityFromMap(Object obj, Map data) { + if ( data == null || obj == null ) { + return false; + } - Object value = data.get(propertyData.getName()); - if (value == null) { - return false; - } + final Object value = data.get( propertyData.getName() ); + if ( value == null ) { + return false; + } - Setter setter = ReflectionTools.getSetter(obj.getClass(), propertyData); - setter.set(obj, value, null); + final Setter setter = ReflectionTools.getSetter( obj.getClass(), propertyData ); + setter.set( obj, value, null ); - return true; - } + return true; + } - public Object mapToIdFromMap(Map data) { - if (data == null) { - return null; - } + @Override + public Object mapToIdFromMap(Map data) { + if ( data == null ) { + return null; + } - return data.get(propertyData.getName()); - } + return data.get( propertyData.getName() ); + } - public Object mapToIdFromEntity(Object data) { - if (data == null) { - return null; - } + @Override + public Object mapToIdFromEntity(Object data) { + if ( data == null ) { + return null; + } - if(data instanceof HibernateProxy) { - HibernateProxy hibernateProxy = (HibernateProxy) data; - return hibernateProxy.getHibernateLazyInitializer().getIdentifier(); - } else { - Getter getter = ReflectionTools.getGetter(data.getClass(), propertyData); - return getter.get(data); - } - } + if ( data instanceof HibernateProxy ) { + final HibernateProxy hibernateProxy = (HibernateProxy) data; + return hibernateProxy.getHibernateLazyInitializer().getIdentifier(); + } + else { + final Getter getter = ReflectionTools.getGetter( data.getClass(), propertyData ); + return getter.get( data ); + } + } - public void mapToMapFromId(Map data, Object obj) { - if (data != null) { - data.put(propertyData.getName(), obj); - } - } + @Override + public void mapToMapFromId(Map data, Object obj) { + if ( data != null ) { + data.put( propertyData.getName(), obj ); + } + } - public void mapToMapFromEntity(Map data, Object obj) { - if (obj == null) { - data.put(propertyData.getName(), null); - } else { - if(obj instanceof HibernateProxy) { - HibernateProxy hibernateProxy = (HibernateProxy)obj; - data.put(propertyData.getName(), hibernateProxy.getHibernateLazyInitializer().getIdentifier()); - } else { - Getter getter = ReflectionTools.getGetter(obj.getClass(), propertyData); - data.put(propertyData.getName(), getter.get(obj)); - } - } - } + @Override + public void mapToMapFromEntity(Map data, Object obj) { + if ( obj == null ) { + data.put( propertyData.getName(), null ); + } + else { + if ( obj instanceof HibernateProxy ) { + final HibernateProxy hibernateProxy = (HibernateProxy) obj; + data.put( propertyData.getName(), hibernateProxy.getHibernateLazyInitializer().getIdentifier() ); + } + else { + final Getter getter = ReflectionTools.getGetter( obj.getClass(), propertyData ); + data.put( propertyData.getName(), getter.get( obj ) ); + } + } + } - public void mapToEntityFromEntity(Object objTo, Object objFrom) { - if (objTo == null || objFrom == null) { - return; - } + public void mapToEntityFromEntity(Object objTo, Object objFrom) { + if ( objTo == null || objFrom == null ) { + return; + } - Getter getter = ReflectionTools.getGetter(objFrom.getClass(), propertyData); - Setter setter = ReflectionTools.getSetter(objTo.getClass(), propertyData); - setter.set(objTo, getter.get(objFrom), null); - } + final Getter getter = ReflectionTools.getGetter( objFrom.getClass(), propertyData ); + final Setter setter = ReflectionTools.getSetter( objTo.getClass(), propertyData ); + setter.set( objTo, getter.get( objFrom ), null ); + } - public IdMapper prefixMappedProperties(String prefix) { - return new SingleIdMapper(new PropertyData(prefix + propertyData.getName(), propertyData)); - } + @Override + public IdMapper prefixMappedProperties(String prefix) { + return new SingleIdMapper( new PropertyData( prefix + propertyData.getName(), propertyData ) ); + } - public List mapToQueryParametersFromId(Object obj) { - List ret = new ArrayList(); + @Override + public List mapToQueryParametersFromId(Object obj) { + final List ret = new ArrayList(); - ret.add(new QueryParameterData(propertyData.getName(), obj)); + ret.add( new QueryParameterData( propertyData.getName(), obj ) ); - return ret; - } + return ret; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/AbstractCollectionMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/AbstractCollectionMapper.java index a06cc6270a..dbf7443853 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/AbstractCollectionMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/AbstractCollectionMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -53,43 +53,53 @@ import org.hibernate.property.Setter; * @author Michal Skowronek (mskowr at o2 dot pl) */ public abstract class AbstractCollectionMapper implements PropertyMapper { - protected final CommonCollectionMapperData commonCollectionMapperData; - protected final Class collectionClass; - protected final boolean ordinalInId; + protected final CommonCollectionMapperData commonCollectionMapperData; + protected final Class collectionClass; + protected final boolean ordinalInId; protected final boolean revisionTypeInId; - private final Constructor proxyConstructor; + private final Constructor proxyConstructor; - protected AbstractCollectionMapper(CommonCollectionMapperData commonCollectionMapperData, + protected AbstractCollectionMapper( + CommonCollectionMapperData commonCollectionMapperData, Class collectionClass, Class proxyClass, boolean ordinalInId, boolean revisionTypeInId) { - this.commonCollectionMapperData = commonCollectionMapperData; - this.collectionClass = collectionClass; + this.commonCollectionMapperData = commonCollectionMapperData; + this.collectionClass = collectionClass; this.ordinalInId = ordinalInId; this.revisionTypeInId = revisionTypeInId; - try { - proxyConstructor = proxyClass.getConstructor(Initializor.class); - } catch (NoSuchMethodException e) { - throw new AuditException(e); - } - } + try { + proxyConstructor = proxyClass.getConstructor( Initializor.class ); + } + catch (NoSuchMethodException e) { + throw new AuditException( e ); + } + } - protected abstract Collection getNewCollectionContent(PersistentCollection newCollection); - protected abstract Collection getOldCollectionContent(Serializable oldCollection); + protected abstract Collection getNewCollectionContent(PersistentCollection newCollection); - /** - * Maps the changed collection element to the given map. + protected abstract Collection getOldCollectionContent(Serializable oldCollection); + + /** + * Maps the changed collection element to the given map. + * * @param idData Map to which composite-id data should be added. - * @param data Where to map the data. - * @param changed The changed collection element to map. - */ - protected abstract void mapToMapFromObject(SessionImplementor session, Map idData, Map data, Object changed); + * @param data Where to map the data. + * @param changed The changed collection element to map. + */ + protected abstract void mapToMapFromObject( + SessionImplementor session, + Map idData, + Map data, + Object changed); /** * Creates map for storing identifier data. Ordinal parameter guarantees uniqueness of primary key. * Composite primary key cannot contain embeddable properties since they might be nullable. + * * @param ordinal Iteration ordinal. + * * @return Map for holding identifier data. */ protected Map createIdMap(int ordinal) { @@ -100,79 +110,113 @@ public abstract class AbstractCollectionMapper implements PropertyMapper { return idMap; } - private void addCollectionChanges(SessionImplementor session, List collectionChanges, - Set changed, RevisionType revisionType, Serializable id) { + private void addCollectionChanges( + SessionImplementor session, List collectionChanges, + Set changed, RevisionType revisionType, Serializable id) { int ordinal = 0; - for (Object changedObj : changed) { - Map entityData = new HashMap(); - Map originalId = createIdMap( ordinal++ ); - entityData.put(commonCollectionMapperData.getVerEntCfg().getOriginalIdPropName(), originalId); + for ( Object changedObj : changed ) { + final Map entityData = new HashMap(); + final Map originalId = createIdMap( ordinal++ ); + entityData.put( commonCollectionMapperData.getVerEntCfg().getOriginalIdPropName(), originalId ); - collectionChanges.add(new PersistentCollectionChangeData( - commonCollectionMapperData.getVersionsMiddleEntityName(), entityData, changedObj)); - // Mapping the collection owner's id. - commonCollectionMapperData.getReferencingIdData().getPrefixedMapper().mapToMapFromId(originalId, id); + collectionChanges.add( + new PersistentCollectionChangeData( + commonCollectionMapperData.getVersionsMiddleEntityName(), entityData, changedObj + ) + ); + // Mapping the collection owner's id. + commonCollectionMapperData.getReferencingIdData().getPrefixedMapper().mapToMapFromId( originalId, id ); - // Mapping collection element and index (if present). - mapToMapFromObject(session, originalId, entityData, changedObj); + // Mapping collection element and index (if present). + mapToMapFromObject( session, originalId, entityData, changedObj ); - (revisionTypeInId ? originalId : entityData).put(commonCollectionMapperData.getVerEntCfg().getRevisionTypePropName(), revisionType); - } - } - - @SuppressWarnings({"unchecked"}) - public List mapCollectionChanges(SessionImplementor session, - String referencingPropertyName, - PersistentCollection newColl, - Serializable oldColl, Serializable id) { - if (!commonCollectionMapperData.getCollectionReferencingPropertyData().getName().equals(referencingPropertyName)) { - return null; - } - - List collectionChanges = new ArrayList(); - - // Comparing new and old collection content. - Collection newCollection = getNewCollectionContent(newColl); - Collection oldCollection = getOldCollectionContent(oldColl); - - Set added = new HashSet(); - if (newColl != null) { added.addAll(newCollection); } - // Re-hashing the old collection as the hash codes of the elements there may have changed, and the - // removeAll in AbstractSet has an implementation that is hashcode-change sensitive (as opposed to addAll). - if (oldColl != null) { added.removeAll(new HashSet(oldCollection)); } - - addCollectionChanges(session, collectionChanges, added, RevisionType.ADD, id); - - Set deleted = new HashSet(); - if (oldColl != null) { deleted.addAll(oldCollection); } - // The same as above - re-hashing new collection. - if (newColl != null) { deleted.removeAll(new HashSet(newCollection)); } - - addCollectionChanges(session, collectionChanges, deleted, RevisionType.DEL, id); - - return collectionChanges; - } - - public boolean mapToMapFromEntity(SessionImplementor session, Map data, Object newObj, Object oldObj) { - // Changes are mapped in the "mapCollectionChanges" method. - return false; - } + (revisionTypeInId ? originalId : entityData).put( + commonCollectionMapperData.getVerEntCfg() + .getRevisionTypePropName(), revisionType + ); + } + } @Override - public void mapModifiedFlagsToMapFromEntity(SessionImplementor session, Map data, Object newObj, Object oldObj) { - PropertyData propertyData = commonCollectionMapperData.getCollectionReferencingPropertyData(); - if (propertyData.isUsingModifiedFlag()) { - if (isNotPersistentCollection(newObj) || isNotPersistentCollection(oldObj)) { + @SuppressWarnings({"unchecked"}) + public List mapCollectionChanges( + SessionImplementor session, + String referencingPropertyName, + PersistentCollection newColl, + Serializable oldColl, Serializable id) { + if ( !commonCollectionMapperData.getCollectionReferencingPropertyData().getName().equals( + referencingPropertyName + ) ) { + return null; + } + + final List collectionChanges = new ArrayList(); + + // Comparing new and old collection content. + final Collection newCollection = getNewCollectionContent( newColl ); + final Collection oldCollection = getOldCollectionContent( oldColl ); + + final Set added = new HashSet(); + if ( newColl != null ) { + added.addAll( newCollection ); + } + // Re-hashing the old collection as the hash codes of the elements there may have changed, and the + // removeAll in AbstractSet has an implementation that is hashcode-change sensitive (as opposed to addAll). + if ( oldColl != null ) { + added.removeAll( new HashSet( oldCollection ) ); + } + + addCollectionChanges( session, collectionChanges, added, RevisionType.ADD, id ); + + final Set deleted = new HashSet(); + if ( oldColl != null ) { + deleted.addAll( oldCollection ); + } + // The same as above - re-hashing new collection. + if ( newColl != null ) { + deleted.removeAll( new HashSet( newCollection ) ); + } + + addCollectionChanges( session, collectionChanges, deleted, RevisionType.DEL, id ); + + return collectionChanges; + } + + @Override + public boolean mapToMapFromEntity( + SessionImplementor session, + Map data, + Object newObj, + Object oldObj) { + // Changes are mapped in the "mapCollectionChanges" method. + return false; + } + + @Override + public void mapModifiedFlagsToMapFromEntity( + SessionImplementor session, + Map data, + Object newObj, + Object oldObj) { + final PropertyData propertyData = commonCollectionMapperData.getCollectionReferencingPropertyData(); + if ( propertyData.isUsingModifiedFlag() ) { + if ( isNotPersistentCollection( newObj ) || isNotPersistentCollection( oldObj ) ) { // Compare POJOs. - data.put(propertyData.getModifiedFlagPropertyName(), !Tools.objectsEqual(newObj, oldObj)); - } else if (isFromNullToEmptyOrFromEmptyToNull((PersistentCollection) newObj, (Serializable) oldObj)) { - data.put(propertyData.getModifiedFlagPropertyName(), true); - } else { - List changes = mapCollectionChanges(session, - commonCollectionMapperData.getCollectionReferencingPropertyData().getName(), - (PersistentCollection) newObj, (Serializable) oldObj, null); - data.put(propertyData.getModifiedFlagPropertyName(), !changes.isEmpty()); + data.put( propertyData.getModifiedFlagPropertyName(), !Tools.objectsEqual( newObj, oldObj ) ); + } + else if ( isFromNullToEmptyOrFromEmptyToNull( (PersistentCollection) newObj, (Serializable) oldObj ) ) { + data.put( propertyData.getModifiedFlagPropertyName(), true ); + } + else { + final List changes = mapCollectionChanges( + session, + commonCollectionMapperData.getCollectionReferencingPropertyData().getName(), + (PersistentCollection) newObj, + (Serializable) oldObj, + null + ); + data.put( propertyData.getModifiedFlagPropertyName(), !changes.isEmpty() ); } } } @@ -183,8 +227,8 @@ public abstract class AbstractCollectionMapper implements PropertyMapper { private boolean isFromNullToEmptyOrFromEmptyToNull(PersistentCollection newColl, Serializable oldColl) { // Comparing new and old collection content. - Collection newCollection = getNewCollectionContent(newColl); - Collection oldCollection = getOldCollectionContent(oldColl); + final Collection newCollection = getNewCollectionContent( newColl ); + final Collection oldCollection = getOldCollectionContent( oldColl ); return oldCollection == null && newCollection != null && newCollection.isEmpty() || newCollection == null && oldCollection != null && oldCollection.isEmpty(); @@ -192,36 +236,53 @@ public abstract class AbstractCollectionMapper implements PropertyMapper { @Override public void mapModifiedFlagsToMapForCollectionChange(String collectionPropertyName, Map data) { - PropertyData propertyData = commonCollectionMapperData.getCollectionReferencingPropertyData(); - if (propertyData.isUsingModifiedFlag()) { - data.put(propertyData.getModifiedFlagPropertyName(), propertyData.getName().equals(collectionPropertyName)); + final PropertyData propertyData = commonCollectionMapperData.getCollectionReferencingPropertyData(); + if ( propertyData.isUsingModifiedFlag() ) { + data.put( + propertyData.getModifiedFlagPropertyName(), + propertyData.getName().equals( collectionPropertyName ) + ); } } - protected abstract Initializor getInitializor(AuditConfiguration verCfg, - AuditReaderImplementor versionsReader, Object primaryKey, - Number revision, boolean removed); + protected abstract Initializor getInitializor( + AuditConfiguration verCfg, + AuditReaderImplementor versionsReader, Object primaryKey, + Number revision, boolean removed); - public void mapToEntityFromMap(AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, - AuditReaderImplementor versionsReader, Number revision) { - Setter setter = ReflectionTools.getSetter(obj.getClass(), commonCollectionMapperData.getCollectionReferencingPropertyData()); - try { + @Override + public void mapToEntityFromMap( + AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, + AuditReaderImplementor versionsReader, Number revision) { + final Setter setter = ReflectionTools.getSetter( + obj.getClass(), + commonCollectionMapperData.getCollectionReferencingPropertyData() + ); + try { setter.set( obj, proxyConstructor.newInstance( getInitializor( verCfg, versionsReader, primaryKey, revision, - RevisionType.DEL.equals( data.get( verCfg.getAuditEntCfg().getRevisionTypePropName() ) ) + RevisionType.DEL.equals( + data.get( + verCfg.getAuditEntCfg() + .getRevisionTypePropName() + ) + ) ) ), null ); - } catch (InstantiationException e) { - throw new AuditException(e); - } catch (IllegalAccessException e) { - throw new AuditException(e); - } catch (InvocationTargetException e) { - throw new AuditException(e); - } - } + } + catch (InstantiationException e) { + throw new AuditException( e ); + } + catch (IllegalAccessException e) { + throw new AuditException( e ); + } + catch (InvocationTargetException e) { + throw new AuditException( e ); + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/AbstractOneToOneMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/AbstractOneToOneMapper.java index 31fe58fc19..48a72ba7c7 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/AbstractOneToOneMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/AbstractOneToOneMapper.java @@ -1,8 +1,31 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.internal.entities.mapper.relation; +import javax.persistence.NoResultException; import java.io.Serializable; import java.util.Map; -import javax.persistence.NoResultException; import org.hibernate.NonUniqueResultException; import org.hibernate.engine.spi.SessionImplementor; @@ -13,54 +36,69 @@ import org.hibernate.envers.internal.reader.AuditReaderImplementor; /** * Template class for property mappers that manage one-to-one relation. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public abstract class AbstractOneToOneMapper extends AbstractToOneMapper { - private final String entityName; - private final String referencedEntityName; + private final String entityName; + private final String referencedEntityName; - protected AbstractOneToOneMapper(String entityName, String referencedEntityName, PropertyData propertyData) { - super(propertyData); - this.entityName = entityName; - this.referencedEntityName = referencedEntityName; - } + protected AbstractOneToOneMapper(String entityName, String referencedEntityName, PropertyData propertyData) { + super( propertyData ); + this.entityName = entityName; + this.referencedEntityName = referencedEntityName; + } - @Override - public void nullSafeMapToEntityFromMap(AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, - AuditReaderImplementor versionsReader, Number revision) { - EntityInfo referencedEntity = getEntityInfo(verCfg, referencedEntityName); + @Override + public void nullSafeMapToEntityFromMap( + AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, + AuditReaderImplementor versionsReader, Number revision) { + final EntityInfo referencedEntity = getEntityInfo( verCfg, referencedEntityName ); - Object value = null; - try { - value = queryForReferencedEntity(versionsReader, referencedEntity, (Serializable) primaryKey, revision); - } catch (NoResultException e) { - value = null; - } catch (NonUniqueResultException e) { - throw new AuditException("Many versions results for one-to-one relationship " + entityName + - "." + getPropertyData().getBeanName() + ".", e); - } + Object value; + try { + value = queryForReferencedEntity( versionsReader, referencedEntity, (Serializable) primaryKey, revision ); + } + catch (NoResultException e) { + value = null; + } + catch (NonUniqueResultException e) { + throw new AuditException( + "Many versions results for one-to-one relationship " + entityName + + "." + getPropertyData().getBeanName() + ".", e + ); + } - setPropertyValue(obj, value); - } + setPropertyValue( obj, value ); + } - /** - * @param versionsReader Audit reader. - * @param referencedEntity Referenced entity descriptor. - * @param primaryKey Referenced entity identifier. - * @param revision Revision number. - * @return Referenced object or proxy of one-to-one relation. - */ - protected abstract Object queryForReferencedEntity(AuditReaderImplementor versionsReader, EntityInfo referencedEntity, - Serializable primaryKey, Number revision); + /** + * @param versionsReader Audit reader. + * @param referencedEntity Referenced entity descriptor. + * @param primaryKey Referenced entity identifier. + * @param revision Revision number. + * + * @return Referenced object or proxy of one-to-one relation. + */ + protected abstract Object queryForReferencedEntity( + AuditReaderImplementor versionsReader, EntityInfo referencedEntity, + Serializable primaryKey, Number revision); - @Override - public void mapModifiedFlagsToMapFromEntity(SessionImplementor session, Map data, Object newObj, Object oldObj) { - } + @Override + public void mapModifiedFlagsToMapFromEntity( + SessionImplementor session, + Map data, + Object newObj, + Object oldObj) { + } - @Override - public void mapModifiedFlagsToMapForCollectionChange(String collectionPropertyName, Map data) { - if (getPropertyData().isUsingModifiedFlag()) { - data.put(getPropertyData().getModifiedFlagPropertyName(), collectionPropertyName.equals(getPropertyData().getName())); - } - } + @Override + public void mapModifiedFlagsToMapForCollectionChange(String collectionPropertyName, Map data) { + if ( getPropertyData().isUsingModifiedFlag() ) { + data.put( + getPropertyData().getModifiedFlagPropertyName(), + collectionPropertyName.equals( getPropertyData().getName() ) + ); + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/AbstractToOneMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/AbstractToOneMapper.java index 80fcec3bbf..ef292e3280 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/AbstractToOneMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/AbstractToOneMapper.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.internal.entities.mapper.relation; import java.io.Serializable; @@ -17,87 +40,109 @@ import org.hibernate.property.Setter; /** * Base class for property mappers that manage to-one relation. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public abstract class AbstractToOneMapper implements PropertyMapper { - private final PropertyData propertyData; + private final PropertyData propertyData; - protected AbstractToOneMapper(PropertyData propertyData) { - this.propertyData = propertyData; - } + protected AbstractToOneMapper(PropertyData propertyData) { + this.propertyData = propertyData; + } - @Override - public boolean mapToMapFromEntity(SessionImplementor session, Map data, Object newObj, Object oldObj) { - return false; - } + @Override + public boolean mapToMapFromEntity( + SessionImplementor session, + Map data, + Object newObj, + Object oldObj) { + return false; + } - @Override - public void mapToEntityFromMap(AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, - AuditReaderImplementor versionsReader, Number revision) { - if (obj != null) { - nullSafeMapToEntityFromMap(verCfg, obj, data, primaryKey, versionsReader, revision); - } - } + @Override + public void mapToEntityFromMap( + AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, + AuditReaderImplementor versionsReader, Number revision) { + if ( obj != null ) { + nullSafeMapToEntityFromMap( verCfg, obj, data, primaryKey, versionsReader, revision ); + } + } - @Override - public List mapCollectionChanges(SessionImplementor session, String referencingPropertyName, - PersistentCollection newColl, Serializable oldColl, - Serializable id) { - return null; - } + @Override + public List mapCollectionChanges( + SessionImplementor session, String referencingPropertyName, + PersistentCollection newColl, Serializable oldColl, + Serializable id) { + return null; + } - /** - * @param verCfg Audit configuration. - * @param entityName Entity name. - * @return Entity class, name and information whether it is audited or not. - */ - protected EntityInfo getEntityInfo(AuditConfiguration verCfg, String entityName) { - EntityConfiguration entCfg = verCfg.getEntCfg().get(entityName); - boolean isRelationAudited = true; - if (entCfg == null) { - // a relation marked as RelationTargetAuditMode.NOT_AUDITED - entCfg = verCfg.getEntCfg().getNotVersionEntityConfiguration(entityName); - isRelationAudited = false; - } - Class entityClass = ReflectionTools.loadClass( entCfg.getEntityClassName(), verCfg.getClassLoaderService() ); - return new EntityInfo(entityClass, entityName, isRelationAudited); - } + /** + * @param verCfg Audit configuration. + * @param entityName Entity name. + * + * @return Entity class, name and information whether it is audited or not. + */ + protected EntityInfo getEntityInfo(AuditConfiguration verCfg, String entityName) { + EntityConfiguration entCfg = verCfg.getEntCfg().get( entityName ); + boolean isRelationAudited = true; + if ( entCfg == null ) { + // a relation marked as RelationTargetAuditMode.NOT_AUDITED + entCfg = verCfg.getEntCfg().getNotVersionEntityConfiguration( entityName ); + isRelationAudited = false; + } + final Class entityClass = ReflectionTools.loadClass( entCfg.getEntityClassName(), verCfg.getClassLoaderService() ); + return new EntityInfo( entityClass, entityName, isRelationAudited ); + } - protected void setPropertyValue(Object targetObject, Object value) { - Setter setter = ReflectionTools.getSetter(targetObject.getClass(), propertyData); - setter.set(targetObject, value, null); - } + protected void setPropertyValue(Object targetObject, Object value) { + final Setter setter = ReflectionTools.getSetter( targetObject.getClass(), propertyData ); + setter.set( targetObject, value, null ); + } - /** - * @return Bean property that represents the relation. - */ - protected PropertyData getPropertyData() { - return propertyData; - } + /** + * @return Bean property that represents the relation. + */ + protected PropertyData getPropertyData() { + return propertyData; + } - /** - * Parameter {@code obj} is never {@code null}. - * @see PropertyMapper#mapToEntityFromMap(AuditConfiguration, Object, Map, Object, AuditReaderImplementor, Number) - */ - public abstract void nullSafeMapToEntityFromMap(AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, - AuditReaderImplementor versionsReader, Number revision); + /** + * Parameter {@code obj} is never {@code null}. + * + * @see PropertyMapper#mapToEntityFromMap(AuditConfiguration, Object, Map, Object, AuditReaderImplementor, Number) + */ + public abstract void nullSafeMapToEntityFromMap( + AuditConfiguration verCfg, + Object obj, + Map data, + Object primaryKey, + AuditReaderImplementor versionsReader, + Number revision); - /** - * Simple descriptor of an entity. - */ - protected class EntityInfo { - private final Class entityClass; - private final String entityName; - private final boolean audited; + /** + * Simple descriptor of an entity. + */ + protected class EntityInfo { + private final Class entityClass; + private final String entityName; + private final boolean audited; - public EntityInfo(Class entityClass, String entityName, boolean audited) { - this.entityClass = entityClass; - this.entityName = entityName; - this.audited = audited; - } + public EntityInfo(Class entityClass, String entityName, boolean audited) { + this.entityClass = entityClass; + this.entityName = entityName; + this.audited = audited; + } - public Class getEntityClass() { return entityClass; } - public String getEntityName() { return entityName; } - public boolean isAudited() { return audited; } - } + public Class getEntityClass() { + return entityClass; + } + + public String getEntityName() { + return entityName; + } + + public boolean isAudited() { + return audited; + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/BasicCollectionMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/BasicCollectionMapper.java index ca327fe78d..2b11620037 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/BasicCollectionMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/BasicCollectionMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -39,36 +39,50 @@ import org.hibernate.envers.internal.reader.AuditReaderImplementor; * @author Adam Warski (adam at warski dot org) */ public class BasicCollectionMapper extends AbstractCollectionMapper implements PropertyMapper { - protected final MiddleComponentData elementComponentData; + protected final MiddleComponentData elementComponentData; - public BasicCollectionMapper(CommonCollectionMapperData commonCollectionMapperData, + public BasicCollectionMapper( + CommonCollectionMapperData commonCollectionMapperData, Class collectionClass, Class proxyClass, MiddleComponentData elementComponentData, boolean ordinalInId, boolean revisionTypeInId) { super( commonCollectionMapperData, collectionClass, proxyClass, ordinalInId, revisionTypeInId ); - this.elementComponentData = elementComponentData; - } + this.elementComponentData = elementComponentData; + } - protected Initializor getInitializor(AuditConfiguration verCfg, AuditReaderImplementor versionsReader, - Object primaryKey, Number revision, boolean removed) { - return new BasicCollectionInitializor(verCfg, versionsReader, commonCollectionMapperData.getQueryGenerator(), - primaryKey, revision, removed, collectionClass, elementComponentData); - } + @Override + protected Initializor getInitializor( + AuditConfiguration verCfg, AuditReaderImplementor versionsReader, + Object primaryKey, Number revision, boolean removed) { + return new BasicCollectionInitializor( + verCfg, versionsReader, commonCollectionMapperData.getQueryGenerator(), + primaryKey, revision, removed, collectionClass, elementComponentData + ); + } - protected Collection getNewCollectionContent(PersistentCollection newCollection) { - return (Collection) newCollection; - } + @Override + protected Collection getNewCollectionContent(PersistentCollection newCollection) { + return (Collection) newCollection; + } - protected Collection getOldCollectionContent(Serializable oldCollection) { - if (oldCollection == null) { - return null; - } else if (oldCollection instanceof Map) { - return ((Map) oldCollection).keySet(); - } else { - return (Collection) oldCollection; - } - } + @Override + protected Collection getOldCollectionContent(Serializable oldCollection) { + if ( oldCollection == null ) { + return null; + } + else if ( oldCollection instanceof Map ) { + return ((Map) oldCollection).keySet(); + } + else { + return (Collection) oldCollection; + } + } - protected void mapToMapFromObject(SessionImplementor session, Map idData, Map data, Object changed) { - elementComponentData.getComponentMapper().mapToMapFromObject(session, idData, data, changed); - } + @Override + protected void mapToMapFromObject( + SessionImplementor session, + Map idData, + Map data, + Object changed) { + elementComponentData.getComponentMapper().mapToMapFromObject( session, idData, data, changed ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/CommonCollectionMapperData.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/CommonCollectionMapperData.java index dc22be02d1..97edad9b6d 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/CommonCollectionMapperData.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/CommonCollectionMapperData.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,48 +22,51 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation; + import org.hibernate.envers.configuration.internal.AuditEntitiesConfiguration; import org.hibernate.envers.internal.entities.PropertyData; import org.hibernate.envers.internal.entities.mapper.relation.query.RelationQueryGenerator; /** - * Data that is used by all collection mappers, regardless of the type. + * Data that is used by all collection mappers, regardless of the type. + * * @author Adam Warski (adam at warski dot org) */ public final class CommonCollectionMapperData { - private final AuditEntitiesConfiguration verEntCfg; - private final String versionsMiddleEntityName; - private final PropertyData collectionReferencingPropertyData; - private final MiddleIdData referencingIdData; - private final RelationQueryGenerator queryGenerator; + private final AuditEntitiesConfiguration verEntCfg; + private final String versionsMiddleEntityName; + private final PropertyData collectionReferencingPropertyData; + private final MiddleIdData referencingIdData; + private final RelationQueryGenerator queryGenerator; - public CommonCollectionMapperData(AuditEntitiesConfiguration verEntCfg, String versionsMiddleEntityName, - PropertyData collectionReferencingPropertyData, MiddleIdData referencingIdData, - RelationQueryGenerator queryGenerator) { - this.verEntCfg = verEntCfg; - this.versionsMiddleEntityName = versionsMiddleEntityName; - this.collectionReferencingPropertyData = collectionReferencingPropertyData; - this.referencingIdData = referencingIdData; - this.queryGenerator = queryGenerator; - } + public CommonCollectionMapperData( + AuditEntitiesConfiguration verEntCfg, String versionsMiddleEntityName, + PropertyData collectionReferencingPropertyData, MiddleIdData referencingIdData, + RelationQueryGenerator queryGenerator) { + this.verEntCfg = verEntCfg; + this.versionsMiddleEntityName = versionsMiddleEntityName; + this.collectionReferencingPropertyData = collectionReferencingPropertyData; + this.referencingIdData = referencingIdData; + this.queryGenerator = queryGenerator; + } - public AuditEntitiesConfiguration getVerEntCfg() { - return verEntCfg; - } + public AuditEntitiesConfiguration getVerEntCfg() { + return verEntCfg; + } - public String getVersionsMiddleEntityName() { - return versionsMiddleEntityName; - } + public String getVersionsMiddleEntityName() { + return versionsMiddleEntityName; + } - public PropertyData getCollectionReferencingPropertyData() { - return collectionReferencingPropertyData; - } + public PropertyData getCollectionReferencingPropertyData() { + return collectionReferencingPropertyData; + } - public MiddleIdData getReferencingIdData() { - return referencingIdData; - } + public MiddleIdData getReferencingIdData() { + return referencingIdData; + } - public RelationQueryGenerator getQueryGenerator() { - return queryGenerator; - } + public RelationQueryGenerator getQueryGenerator() { + return queryGenerator; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/ListCollectionMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/ListCollectionMapper.java index 3b58a11706..6d1ca6ea2c 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/ListCollectionMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/ListCollectionMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -43,45 +43,64 @@ import org.hibernate.envers.tools.Pair; * @author Adam Warski (adam at warski dot org) */ public final class ListCollectionMapper extends AbstractCollectionMapper implements PropertyMapper { - private final MiddleComponentData elementComponentData; - private final MiddleComponentData indexComponentData; + private final MiddleComponentData elementComponentData; + private final MiddleComponentData indexComponentData; - public ListCollectionMapper(CommonCollectionMapperData commonCollectionMapperData, - MiddleComponentData elementComponentData, MiddleComponentData indexComponentData, - boolean revisionTypeInId) { + public ListCollectionMapper( + CommonCollectionMapperData commonCollectionMapperData, + MiddleComponentData elementComponentData, MiddleComponentData indexComponentData, + boolean revisionTypeInId) { super( commonCollectionMapperData, List.class, ListProxy.class, false, revisionTypeInId ); - this.elementComponentData = elementComponentData; - this.indexComponentData = indexComponentData; - } + this.elementComponentData = elementComponentData; + this.indexComponentData = indexComponentData; + } - protected Initializor getInitializor(AuditConfiguration verCfg, AuditReaderImplementor versionsReader, - Object primaryKey, Number revision, boolean removed) { - return new ListCollectionInitializor(verCfg, versionsReader, commonCollectionMapperData.getQueryGenerator(), - primaryKey, revision, removed, elementComponentData, indexComponentData); - } + @Override + protected Initializor getInitializor( + AuditConfiguration verCfg, AuditReaderImplementor versionsReader, + Object primaryKey, Number revision, boolean removed) { + return new ListCollectionInitializor( + verCfg, versionsReader, commonCollectionMapperData.getQueryGenerator(), + primaryKey, revision, removed, elementComponentData, indexComponentData + ); + } - @SuppressWarnings({"unchecked"}) - protected Collection getNewCollectionContent(PersistentCollection newCollection) { - if (newCollection == null) { - return null; - } else { - return Tools.listToIndexElementPairList((List) newCollection); - } - } + @Override + @SuppressWarnings({"unchecked"}) + protected Collection getNewCollectionContent(PersistentCollection newCollection) { + if ( newCollection == null ) { + return null; + } + else { + return Tools.listToIndexElementPairList( (List) newCollection ); + } + } - @SuppressWarnings({"unchecked"}) - protected Collection getOldCollectionContent(Serializable oldCollection) { - if (oldCollection == null) { - return null; - } else { - return Tools.listToIndexElementPairList((List) oldCollection); - } - } + @Override + @SuppressWarnings({"unchecked"}) + protected Collection getOldCollectionContent(Serializable oldCollection) { + if ( oldCollection == null ) { + return null; + } + else { + return Tools.listToIndexElementPairList( (List) oldCollection ); + } + } - @SuppressWarnings({"unchecked"}) - protected void mapToMapFromObject(SessionImplementor session, Map idData, Map data, Object changed) { - Pair indexValuePair = (Pair) changed; - elementComponentData.getComponentMapper().mapToMapFromObject(session, idData, data, indexValuePair.getSecond()); - indexComponentData.getComponentMapper().mapToMapFromObject(session, idData, data, indexValuePair.getFirst()); - } + @Override + @SuppressWarnings({"unchecked"}) + protected void mapToMapFromObject( + SessionImplementor session, + Map idData, + Map data, + Object changed) { + final Pair indexValuePair = (Pair) changed; + elementComponentData.getComponentMapper().mapToMapFromObject( + session, + idData, + data, + indexValuePair.getSecond() + ); + indexComponentData.getComponentMapper().mapToMapFromObject( session, idData, data, indexValuePair.getFirst() ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/MapCollectionMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/MapCollectionMapper.java index 5310ced432..fbc3671bcd 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/MapCollectionMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/MapCollectionMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -39,42 +39,66 @@ import org.hibernate.envers.internal.reader.AuditReaderImplementor; * @author Adam Warski (adam at warski dot org) */ public class MapCollectionMapper extends AbstractCollectionMapper implements PropertyMapper { - protected final MiddleComponentData elementComponentData; - protected final MiddleComponentData indexComponentData; + protected final MiddleComponentData elementComponentData; + protected final MiddleComponentData indexComponentData; - public MapCollectionMapper(CommonCollectionMapperData commonCollectionMapperData, - Class collectionClass, Class proxyClass, - MiddleComponentData elementComponentData, MiddleComponentData indexComponentData, - boolean revisionTypeInId) { + public MapCollectionMapper( + CommonCollectionMapperData commonCollectionMapperData, + Class collectionClass, Class proxyClass, + MiddleComponentData elementComponentData, MiddleComponentData indexComponentData, + boolean revisionTypeInId) { super( commonCollectionMapperData, collectionClass, proxyClass, false, revisionTypeInId ); - this.elementComponentData = elementComponentData; - this.indexComponentData = indexComponentData; - } + this.elementComponentData = elementComponentData; + this.indexComponentData = indexComponentData; + } - protected Initializor getInitializor(AuditConfiguration verCfg, AuditReaderImplementor versionsReader, - Object primaryKey, Number revision, boolean removed) { - return new MapCollectionInitializor(verCfg, versionsReader, commonCollectionMapperData.getQueryGenerator(), - primaryKey, revision, removed, collectionClass, elementComponentData, indexComponentData); - } + @Override + protected Initializor getInitializor( + AuditConfiguration verCfg, AuditReaderImplementor versionsReader, + Object primaryKey, Number revision, boolean removed) { + return new MapCollectionInitializor( + verCfg, versionsReader, commonCollectionMapperData.getQueryGenerator(), + primaryKey, revision, removed, collectionClass, elementComponentData, indexComponentData + ); + } - protected Collection getNewCollectionContent(PersistentCollection newCollection) { - if (newCollection == null) { - return null; - } else { - return ((Map) newCollection).entrySet(); - } - } + @Override + protected Collection getNewCollectionContent(PersistentCollection newCollection) { + if ( newCollection == null ) { + return null; + } + else { + return ((Map) newCollection).entrySet(); + } + } - protected Collection getOldCollectionContent(Serializable oldCollection) { - if (oldCollection == null) { - return null; - } else { - return ((Map) oldCollection).entrySet(); - } - } + @Override + protected Collection getOldCollectionContent(Serializable oldCollection) { + if ( oldCollection == null ) { + return null; + } + else { + return ((Map) oldCollection).entrySet(); + } + } - protected void mapToMapFromObject(SessionImplementor session, Map idData, Map data, Object changed) { - elementComponentData.getComponentMapper().mapToMapFromObject(session, idData, data, ((Map.Entry) changed).getValue()); - indexComponentData.getComponentMapper().mapToMapFromObject(session, idData, data, ((Map.Entry) changed).getKey()); - } + @Override + protected void mapToMapFromObject( + SessionImplementor session, + Map idData, + Map data, + Object changed) { + elementComponentData.getComponentMapper().mapToMapFromObject( + session, + idData, + data, + ((Map.Entry) changed).getValue() + ); + indexComponentData.getComponentMapper().mapToMapFromObject( + session, + idData, + data, + ((Map.Entry) changed).getKey() + ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/MiddleComponentData.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/MiddleComponentData.java index 7ac2ff25b1..ca2e7bef07 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/MiddleComponentData.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/MiddleComponentData.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation; + import org.hibernate.envers.internal.entities.mapper.relation.component.MiddleComponentMapper; /** @@ -29,22 +30,23 @@ import org.hibernate.envers.internal.entities.mapper.relation.component.MiddleCo * - component mapper used to map the component to and from versions entities * - an index, which specifies in which element of the array returned by the query for reading the collection the data * of the component is + * * @author Adam Warski (adam at warski dot org) */ public final class MiddleComponentData { - private final MiddleComponentMapper componentMapper; - private final int componentIndex; + private final MiddleComponentMapper componentMapper; + private final int componentIndex; - public MiddleComponentData(MiddleComponentMapper componentMapper, int componentIndex) { - this.componentMapper = componentMapper; - this.componentIndex = componentIndex; - } + public MiddleComponentData(MiddleComponentMapper componentMapper, int componentIndex) { + this.componentMapper = componentMapper; + this.componentIndex = componentIndex; + } - public MiddleComponentMapper getComponentMapper() { - return componentMapper; - } + public MiddleComponentMapper getComponentMapper() { + return componentMapper; + } - public int getComponentIndex() { - return componentIndex; - } + public int getComponentIndex() { + return componentIndex; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/MiddleIdData.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/MiddleIdData.java index 8d688e541e..a5b1ca45ff 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/MiddleIdData.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/MiddleIdData.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation; + import org.hibernate.envers.configuration.internal.AuditEntitiesConfiguration; import org.hibernate.envers.internal.entities.IdMappingData; import org.hibernate.envers.internal.entities.mapper.id.IdMapper; @@ -29,54 +30,56 @@ import org.hibernate.envers.internal.entities.mapper.id.IdMapper; /** * A class holding information about ids, which form a virtual "relation" from a middle-table. Middle-tables are used * when mapping collections. + * * @author Adam Warski (adam at warski dot org) */ public final class MiddleIdData { - private final IdMapper originalMapper; - private final IdMapper prefixedMapper; - private final String entityName; - private final String auditEntityName; + private final IdMapper originalMapper; + private final IdMapper prefixedMapper; + private final String entityName; + private final String auditEntityName; - public MiddleIdData(AuditEntitiesConfiguration verEntCfg, IdMappingData mappingData, String prefix, - String entityName, boolean audited) { - this.originalMapper = mappingData.getIdMapper(); - this.prefixedMapper = mappingData.getIdMapper().prefixMappedProperties(prefix); - this.entityName = entityName; - this.auditEntityName = audited ? verEntCfg.getAuditEntityName(entityName) : null; - } + public MiddleIdData( + AuditEntitiesConfiguration verEntCfg, IdMappingData mappingData, String prefix, + String entityName, boolean audited) { + this.originalMapper = mappingData.getIdMapper(); + this.prefixedMapper = mappingData.getIdMapper().prefixMappedProperties( prefix ); + this.entityName = entityName; + this.auditEntityName = audited ? verEntCfg.getAuditEntityName( entityName ) : null; + } - /** - * @return Original id mapper of the related entity. - */ - public IdMapper getOriginalMapper() { - return originalMapper; - } + /** + * @return Original id mapper of the related entity. + */ + public IdMapper getOriginalMapper() { + return originalMapper; + } - /** - * @return prefixed id mapper (with the names for the id fields that are used in the middle table) of the related entity. - */ - public IdMapper getPrefixedMapper() { - return prefixedMapper; - } + /** + * @return prefixed id mapper (with the names for the id fields that are used in the middle table) of the related entity. + */ + public IdMapper getPrefixedMapper() { + return prefixedMapper; + } - /** - * @return Name of the related entity (regular, not audited). - */ - public String getEntityName() { - return entityName; - } + /** + * @return Name of the related entity (regular, not audited). + */ + public String getEntityName() { + return entityName; + } - /** - * @return Audit name of the related entity. - */ - public String getAuditEntityName() { - return auditEntityName; - } + /** + * @return Audit name of the related entity. + */ + public String getAuditEntityName() { + return auditEntityName; + } - /** - * @return Is the entity, to which this middle id data correspond, audited. - */ - public boolean isAudited() { - return auditEntityName != null; - } + /** + * @return Is the entity, to which this middle id data correspond, audited. + */ + public boolean isAudited() { + return auditEntityName != null; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/OneToOneNotOwningMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/OneToOneNotOwningMapper.java index c56754876b..9b3b66b3b9 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/OneToOneNotOwningMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/OneToOneNotOwningMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -23,8 +23,8 @@ */ package org.hibernate.envers.internal.entities.mapper.relation; -import java.io.Serializable; import javax.persistence.OneToOne; +import java.io.Serializable; import org.hibernate.envers.internal.entities.PropertyData; import org.hibernate.envers.internal.reader.AuditReaderImplementor; @@ -32,26 +32,31 @@ import org.hibernate.envers.query.AuditEntity; /** * Property mapper for not owning side of {@link OneToOne} relation. + * * @author Adam Warski (adam at warski dot org) * @author HernпїЅn Chanfreau - * @author Michal Skowronek (mskowr at o2 dot pl) + * @author Michal Skowronek (mskowr at o2 dot pl) * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class OneToOneNotOwningMapper extends AbstractOneToOneMapper { - private final String owningReferencePropertyName; + private final String owningReferencePropertyName; - public OneToOneNotOwningMapper(String notOwningEntityName, String owningEntityName, String owningReferencePropertyName, - PropertyData propertyData) { - super(notOwningEntityName, owningEntityName, propertyData); - this.owningReferencePropertyName = owningReferencePropertyName; - } + public OneToOneNotOwningMapper( + String notOwningEntityName, String owningEntityName, String owningReferencePropertyName, + PropertyData propertyData) { + super( notOwningEntityName, owningEntityName, propertyData ); + this.owningReferencePropertyName = owningReferencePropertyName; + } - @Override - protected Object queryForReferencedEntity(AuditReaderImplementor versionsReader, EntityInfo referencedEntity, - Serializable primaryKey, Number revision) { - return versionsReader.createQuery().forEntitiesAtRevision(referencedEntity.getEntityClass(), - referencedEntity.getEntityName(), revision) - .add(AuditEntity.relatedId(owningReferencePropertyName).eq(primaryKey)) - .getSingleResult(); - } + @Override + protected Object queryForReferencedEntity( + AuditReaderImplementor versionsReader, EntityInfo referencedEntity, + Serializable primaryKey, Number revision) { + return versionsReader.createQuery().forEntitiesAtRevision( + referencedEntity.getEntityClass(), + referencedEntity.getEntityName(), revision + ) + .add( AuditEntity.relatedId( owningReferencePropertyName ).eq( primaryKey ) ) + .getSingleResult(); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/OneToOnePrimaryKeyJoinColumnMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/OneToOnePrimaryKeyJoinColumnMapper.java index 6ef8ff4d71..7503bc0284 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/OneToOnePrimaryKeyJoinColumnMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/OneToOnePrimaryKeyJoinColumnMapper.java @@ -1,54 +1,88 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.internal.entities.mapper.relation; import java.io.Serializable; -import javax.persistence.OneToOne; -import javax.persistence.PrimaryKeyJoinColumn; -import org.hibernate.envers.Audited; import org.hibernate.envers.internal.entities.PropertyData; import org.hibernate.envers.internal.reader.AuditReaderImplementor; import org.hibernate.envers.query.AuditEntity; import org.hibernate.persister.entity.EntityPersister; /** - * Property mapper for {@link OneToOne} with {@link PrimaryKeyJoinColumn} relation. + * Property mapper for {@link javax.persistence.OneToOne} with {@link javax.persistence.PrimaryKeyJoinColumn} relation. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class OneToOnePrimaryKeyJoinColumnMapper extends AbstractOneToOneMapper { - public OneToOnePrimaryKeyJoinColumnMapper(String entityName, String referencedEntityName, PropertyData propertyData) { - super(entityName, referencedEntityName, propertyData); - } + public OneToOnePrimaryKeyJoinColumnMapper( + String entityName, + String referencedEntityName, + PropertyData propertyData) { + super( entityName, referencedEntityName, propertyData ); + } - @Override - protected Object queryForReferencedEntity(AuditReaderImplementor versionsReader, EntityInfo referencedEntity, - Serializable primaryKey, Number revision) { - if (referencedEntity.isAudited()) { - // Audited relation. - return versionsReader.createQuery().forEntitiesAtRevision(referencedEntity.getEntityClass(), - referencedEntity.getEntityName(), revision) - .add(AuditEntity.id().eq(primaryKey)) - .getSingleResult(); - } else { - // Not audited relation. - return createNotAuditedEntityReference(versionsReader, referencedEntity.getEntityClass(), - referencedEntity.getEntityName(), primaryKey); - } - } + @Override + protected Object queryForReferencedEntity( + AuditReaderImplementor versionsReader, EntityInfo referencedEntity, + Serializable primaryKey, Number revision) { + if ( referencedEntity.isAudited() ) { + // Audited relation. + return versionsReader.createQuery().forEntitiesAtRevision( + referencedEntity.getEntityClass(), + referencedEntity.getEntityName(), revision + ) + .add( AuditEntity.id().eq( primaryKey ) ) + .getSingleResult(); + } + else { + // Not audited relation. + return createNotAuditedEntityReference( + versionsReader, referencedEntity.getEntityClass(), + referencedEntity.getEntityName(), primaryKey + ); + } + } - /** - * Create Hibernate proxy or retrieve the complete object of referenced, not audited entity. According to - * {@link Audited#targetAuditMode()}} documentation, reference shall point to current (non-historical) version - * of an entity. - */ - private Object createNotAuditedEntityReference(AuditReaderImplementor versionsReader, Class entityClass, - String entityName, Serializable primaryKey) { - EntityPersister entityPersister = versionsReader.getSessionImplementor().getFactory().getEntityPersister(entityName); - if (entityPersister.hasProxy()) { - // If possible create a proxy. Returning complete object may affect performance. - return versionsReader.getSession().load(entityClass, primaryKey); - } else { - // If proxy is not allowed (e.g. @Proxy(lazy=false)) construct the original object. - return versionsReader.getSession().get(entityClass, primaryKey); - } - } + /** + * Create Hibernate proxy or retrieve the complete object of referenced, not audited entity. According to + * {@link org.hibernate.envers.Audited#targetAuditMode()}} documentation, reference shall point to current + * (non-historical) version of an entity. + */ + private Object createNotAuditedEntityReference( + AuditReaderImplementor versionsReader, Class entityClass, + String entityName, Serializable primaryKey) { + final EntityPersister entityPersister = versionsReader.getSessionImplementor().getFactory().getEntityPersister( + entityName + ); + if ( entityPersister.hasProxy() ) { + // If possible create a proxy. Returning complete object may affect performance. + return versionsReader.getSession().load( entityClass, primaryKey ); + } + else { + // If proxy is not allowed (e.g. @Proxy(lazy=false)) construct the original object. + return versionsReader.getSession().get( entityClass, primaryKey ); + } + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/SortedMapCollectionMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/SortedMapCollectionMapper.java index 8f96fa3a0d..a9ec7f442a 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/SortedMapCollectionMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/SortedMapCollectionMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -37,18 +37,30 @@ import org.hibernate.envers.internal.reader.AuditReaderImplementor; public final class SortedMapCollectionMapper extends MapCollectionMapper { private final Comparator comparator; - public SortedMapCollectionMapper(CommonCollectionMapperData commonCollectionMapperData, - Class collectionClass, Class proxyClass, - MiddleComponentData elementComponentData, MiddleComponentData indexComponentData, Comparator comparator, - boolean revisionTypeInId) { - super(commonCollectionMapperData, collectionClass, proxyClass, elementComponentData, indexComponentData, revisionTypeInId); + public SortedMapCollectionMapper( + CommonCollectionMapperData commonCollectionMapperData, + Class collectionClass, Class proxyClass, + MiddleComponentData elementComponentData, MiddleComponentData indexComponentData, Comparator comparator, + boolean revisionTypeInId) { + super( + commonCollectionMapperData, + collectionClass, + proxyClass, + elementComponentData, + indexComponentData, + revisionTypeInId + ); this.comparator = comparator; } - protected Initializor getInitializor(AuditConfiguration verCfg, AuditReaderImplementor versionsReader, - Object primaryKey, Number revision, boolean removed) { - return new SortedMapCollectionInitializor(verCfg, versionsReader, commonCollectionMapperData.getQueryGenerator(), - primaryKey, revision, removed, collectionClass, elementComponentData, indexComponentData, comparator); + @Override + protected Initializor getInitializor( + AuditConfiguration verCfg, AuditReaderImplementor versionsReader, + Object primaryKey, Number revision, boolean removed) { + return new SortedMapCollectionInitializor( + verCfg, versionsReader, commonCollectionMapperData.getQueryGenerator(), + primaryKey, revision, removed, collectionClass, elementComponentData, indexComponentData, comparator + ); } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/SortedSetCollectionMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/SortedSetCollectionMapper.java index aad21b113a..fd275143e2 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/SortedSetCollectionMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/SortedSetCollectionMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -37,17 +37,29 @@ import org.hibernate.envers.internal.reader.AuditReaderImplementor; public final class SortedSetCollectionMapper extends BasicCollectionMapper { private final Comparator comparator; - public SortedSetCollectionMapper(CommonCollectionMapperData commonCollectionMapperData, + public SortedSetCollectionMapper( + CommonCollectionMapperData commonCollectionMapperData, Class collectionClass, Class proxyClass, MiddleComponentData elementComponentData, Comparator comparator, boolean ordinalInId, boolean revisionTypeInId) { - super( commonCollectionMapperData, collectionClass, proxyClass, elementComponentData, ordinalInId, revisionTypeInId ); + super( + commonCollectionMapperData, + collectionClass, + proxyClass, + elementComponentData, + ordinalInId, + revisionTypeInId + ); this.comparator = comparator; } - protected Initializor getInitializor(AuditConfiguration verCfg, AuditReaderImplementor versionsReader, - Object primaryKey, Number revision, boolean removed) { - return new SortedSetCollectionInitializor(verCfg, versionsReader, commonCollectionMapperData.getQueryGenerator(), - primaryKey, revision, removed, collectionClass, elementComponentData, comparator); + @Override + protected Initializor getInitializor( + AuditConfiguration verCfg, AuditReaderImplementor versionsReader, + Object primaryKey, Number revision, boolean removed) { + return new SortedSetCollectionInitializor( + verCfg, versionsReader, commonCollectionMapperData.getQueryGenerator(), + primaryKey, revision, removed, collectionClass, elementComponentData, comparator + ); } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/ToOneEntityLoader.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/ToOneEntityLoader.java index 3d9aeaa016..af8897846e 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/ToOneEntityLoader.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/ToOneEntityLoader.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.internal.entities.mapper.relation; import java.io.Serializable; @@ -14,13 +37,19 @@ public class ToOneEntityLoader { /** * Immediately loads historical entity or its current state when excluded from audit process. */ - public static Object loadImmediate(AuditReaderImplementor versionsReader, Class entityClass, String entityName, - Object entityId, Number revision, boolean removed, AuditConfiguration verCfg) { + public static Object loadImmediate( + AuditReaderImplementor versionsReader, + Class entityClass, + String entityName, + Object entityId, + Number revision, + boolean removed, + AuditConfiguration verCfg) { if ( verCfg.getEntCfg().getNotVersionEntityConfiguration( entityName ) == null ) { // Audited relation, look up entity with Envers. // When user traverses removed entities graph, do not restrict revision type of referencing objects // to ADD or MOD (DEL possible). See HHH-5845. - return versionsReader.find( entityClass, entityName, entityId, revision, removed); + return versionsReader.find( entityClass, entityName, entityId, revision, removed ); } else { // Not audited relation, look up entity with Hibernate. @@ -31,9 +60,17 @@ public class ToOneEntityLoader { /** * Creates proxy of referenced *-to-one entity. */ - public static Object createProxy(AuditReaderImplementor versionsReader, Class entityClass, String entityName, - Object entityId, Number revision, boolean removed, AuditConfiguration verCfg) { - EntityPersister persister = versionsReader.getSessionImplementor().getFactory().getEntityPersister( entityName ); + public static Object createProxy( + AuditReaderImplementor versionsReader, + Class entityClass, + String entityName, + Object entityId, + Number revision, + boolean removed, + AuditConfiguration verCfg) { + final EntityPersister persister = versionsReader.getSessionImplementor() + .getFactory() + .getEntityPersister( entityName ); return persister.createProxy( (Serializable) entityId, new ToOneDelegateSessionImplementor( versionsReader, entityClass, entityId, revision, removed, verCfg ) @@ -44,9 +81,17 @@ public class ToOneEntityLoader { * Creates Hibernate proxy or retrieves the complete object of an entity if proxy is not * allowed (e.g. @Proxy(lazy=false), final class). */ - public static Object createProxyOrLoadImmediate(AuditReaderImplementor versionsReader, Class entityClass, String entityName, - Object entityId, Number revision, boolean removed, AuditConfiguration verCfg) { - EntityPersister persister = versionsReader.getSessionImplementor().getFactory().getEntityPersister( entityName ); + public static Object createProxyOrLoadImmediate( + AuditReaderImplementor versionsReader, + Class entityClass, + String entityName, + Object entityId, + Number revision, + boolean removed, + AuditConfiguration verCfg) { + final EntityPersister persister = versionsReader.getSessionImplementor() + .getFactory() + .getEntityPersister( entityName ); if ( persister.hasProxy() ) { return createProxy( versionsReader, entityClass, entityName, entityId, revision, removed, verCfg ); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/ToOneIdMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/ToOneIdMapper.java index 3382b0136d..f41bfd7a07 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/ToOneIdMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/ToOneIdMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -41,71 +41,100 @@ import org.hibernate.envers.internal.tools.query.Parameters; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class ToOneIdMapper extends AbstractToOneMapper { - private final IdMapper delegate; - private final String referencedEntityName; - private final boolean nonInsertableFake; + private final IdMapper delegate; + private final String referencedEntityName; + private final boolean nonInsertableFake; - public ToOneIdMapper(IdMapper delegate, PropertyData propertyData, String referencedEntityName, boolean nonInsertableFake) { - super(propertyData); - this.delegate = delegate; - this.referencedEntityName = referencedEntityName; - this.nonInsertableFake = nonInsertableFake; - } + public ToOneIdMapper( + IdMapper delegate, + PropertyData propertyData, + String referencedEntityName, + boolean nonInsertableFake) { + super( propertyData ); + this.delegate = delegate; + this.referencedEntityName = referencedEntityName; + this.nonInsertableFake = nonInsertableFake; + } - public boolean mapToMapFromEntity(SessionImplementor session, Map data, Object newObj, Object oldObj) { - HashMap newData = new HashMap(); + @Override + public boolean mapToMapFromEntity( + SessionImplementor session, + Map data, + Object newObj, + Object oldObj) { + final HashMap newData = new HashMap(); - // If this property is originally non-insertable, but made insertable because it is in a many-to-one "fake" - // bi-directional relation, we always store the "old", unchaged data, to prevent storing changes made - // to this field. It is the responsibility of the collection to properly update it if it really changed. - delegate.mapToMapFromEntity(newData, nonInsertableFake ? oldObj : newObj); + // If this property is originally non-insertable, but made insertable because it is in a many-to-one "fake" + // bi-directional relation, we always store the "old", unchaged data, to prevent storing changes made + // to this field. It is the responsibility of the collection to properly update it if it really changed. + delegate.mapToMapFromEntity( newData, nonInsertableFake ? oldObj : newObj ); - for (Map.Entry entry : newData.entrySet()) { - data.put(entry.getKey(), entry.getValue()); + for ( Map.Entry entry : newData.entrySet() ) { + data.put( entry.getKey(), entry.getValue() ); } - return checkModified(session, newObj, oldObj); - } + return checkModified( session, newObj, oldObj ); + } - @Override - public void mapModifiedFlagsToMapFromEntity(SessionImplementor session, Map data, Object newObj, Object oldObj) { - if (getPropertyData().isUsingModifiedFlag()) { - data.put(getPropertyData().getModifiedFlagPropertyName(), checkModified(session, newObj, oldObj)); - } - } + @Override + public void mapModifiedFlagsToMapFromEntity( + SessionImplementor session, + Map data, + Object newObj, + Object oldObj) { + if ( getPropertyData().isUsingModifiedFlag() ) { + data.put( getPropertyData().getModifiedFlagPropertyName(), checkModified( session, newObj, oldObj ) ); + } + } - @Override - public void mapModifiedFlagsToMapForCollectionChange(String collectionPropertyName, Map data) { - if (getPropertyData().isUsingModifiedFlag()) { - data.put(getPropertyData().getModifiedFlagPropertyName(), collectionPropertyName.equals(getPropertyData().getName())); - } - } + @Override + public void mapModifiedFlagsToMapForCollectionChange(String collectionPropertyName, Map data) { + if ( getPropertyData().isUsingModifiedFlag() ) { + data.put( + getPropertyData().getModifiedFlagPropertyName(), + collectionPropertyName.equals( getPropertyData().getName() ) + ); + } + } - protected boolean checkModified(SessionImplementor session, Object newObj, Object oldObj) { - //noinspection SimplifiableConditionalExpression - return nonInsertableFake ? false : !EntityTools.entitiesEqual(session, referencedEntityName, newObj, oldObj); - } + protected boolean checkModified(SessionImplementor session, Object newObj, Object oldObj) { + //noinspection SimplifiableConditionalExpression + return nonInsertableFake ? false : !EntityTools.entitiesEqual( session, referencedEntityName, newObj, oldObj ); + } - public void nullSafeMapToEntityFromMap(AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, - AuditReaderImplementor versionsReader, Number revision) { - Object entityId = delegate.mapToIdFromMap(data); - Object value = null; - if (entityId != null) { - if (versionsReader.getFirstLevelCache().contains(referencedEntityName, revision, entityId)) { - value = versionsReader.getFirstLevelCache().get(referencedEntityName, revision, entityId); - } else { - EntityInfo referencedEntity = getEntityInfo(verCfg, referencedEntityName); - value = ToOneEntityLoader.createProxyOrLoadImmediate( - versionsReader, referencedEntity.getEntityClass(), referencedEntityName, - entityId, revision, RevisionType.DEL.equals( data.get( verCfg.getAuditEntCfg().getRevisionTypePropName() ) ), verCfg - ); - } - } + @Override + public void nullSafeMapToEntityFromMap( + AuditConfiguration verCfg, Object obj, Map data, Object primaryKey, + AuditReaderImplementor versionsReader, Number revision) { + final Object entityId = delegate.mapToIdFromMap( data ); + Object value = null; + if ( entityId != null ) { + if ( versionsReader.getFirstLevelCache().contains( referencedEntityName, revision, entityId ) ) { + value = versionsReader.getFirstLevelCache().get( referencedEntityName, revision, entityId ); + } + else { + final EntityInfo referencedEntity = getEntityInfo( verCfg, referencedEntityName ); + value = ToOneEntityLoader.createProxyOrLoadImmediate( + versionsReader, referencedEntity.getEntityClass(), referencedEntityName, + entityId, revision, RevisionType.DEL.equals( + data.get( + verCfg.getAuditEntCfg() + .getRevisionTypePropName() + ) + ), verCfg + ); + } + } - setPropertyValue(obj, value); - } + setPropertyValue( obj, value ); + } - public void addMiddleEqualToQuery(Parameters parameters, String idPrefix1, String prefix1, String idPrefix2, String prefix2) { + public void addMiddleEqualToQuery( + Parameters parameters, + String idPrefix1, + String prefix1, + String idPrefix2, + String prefix2) { delegate.addIdsEqualToQuery( parameters, prefix1, delegate, prefix2 ); } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleComponentMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleComponentMapper.java index f9213ab8ac..77615a6d31 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleComponentMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleComponentMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -33,36 +33,50 @@ import org.hibernate.envers.internal.tools.query.Parameters; * @author Adam Warski (adam at warski dot org) */ public interface MiddleComponentMapper { - /** - * Maps from full object data, contained in the given map (or object representation of the map, if - * available), to an object. - * @param entityInstantiator An entity instatiator bound with an open versions reader. - * @param data Full object data. - * @param dataObject An optional object representation of the data. - * @param revision Revision at which the data is read. - * @return An object with data corresponding to the one found in the given map. - */ - Object mapToObjectFromFullMap(EntityInstantiator entityInstantiator, Map data, - Object dataObject, Number revision); + /** + * Maps from full object data, contained in the given map (or object representation of the map, if + * available), to an object. + * + * @param entityInstantiator An entity instatiator bound with an open versions reader. + * @param data Full object data. + * @param dataObject An optional object representation of the data. + * @param revision Revision at which the data is read. + * + * @return An object with data corresponding to the one found in the given map. + */ + Object mapToObjectFromFullMap( + EntityInstantiator entityInstantiator, Map data, + Object dataObject, Number revision); - /** - * Maps from an object to the object's map representation (for an entity - only its id). + /** + * Maps from an object to the object's map representation (for an entity - only its id). + * * @param session The current session. * @param idData Map to which composite-id data should be added. - * @param data Map to which data should be added. - * @param obj Object to map from. - */ - void mapToMapFromObject(SessionImplementor session, Map idData, Map data, Object obj); + * @param data Map to which data should be added. + * @param obj Object to map from. + */ + void mapToMapFromObject( + SessionImplementor session, + Map idData, + Map data, + Object obj); - /** - * Adds query statements, which contains restrictions, which express the property that part of the middle - * entity with alias prefix1, is equal to part of the middle entity with alias prefix2 (the entity is the same). - * The part is the component's representation in the middle entity. - * @param parameters Parameters, to which to add the statements. + /** + * Adds query statements, which contains restrictions, which express the property that part of the middle + * entity with alias prefix1, is equal to part of the middle entity with alias prefix2 (the entity is the same). + * The part is the component's representation in the middle entity. + * + * @param parameters Parameters, to which to add the statements. * @param idPrefix1 First alias of the entity + prefix + id to add to the properties. - * @param prefix1 First alias of the entity + prefix to add to the properties. + * @param prefix1 First alias of the entity + prefix to add to the properties. * @param idPrefix2 Second alias of the entity + prefix + id to add to the properties. - * @param prefix2 Second alias of the entity + prefix to add to the properties. - */ - void addMiddleEqualToQuery(Parameters parameters, String idPrefix1, String prefix1, String idPrefix2, String prefix2); + * @param prefix2 Second alias of the entity + prefix to add to the properties. + */ + void addMiddleEqualToQuery( + Parameters parameters, + String idPrefix1, + String prefix1, + String idPrefix2, + String prefix2); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleDummyComponentMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleDummyComponentMapper.java index b4da4f3c37..257c50d115 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleDummyComponentMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleDummyComponentMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation.component; + import java.util.Map; import org.hibernate.engine.spi.SessionImplementor; @@ -32,14 +33,26 @@ import org.hibernate.envers.internal.tools.query.Parameters; * @author Adam Warski (adam at warski dot org) */ public final class MiddleDummyComponentMapper implements MiddleComponentMapper { - public Object mapToObjectFromFullMap(EntityInstantiator entityInstantiator, Map data, - Object dataObject, Number revision) { - return null; - } + public Object mapToObjectFromFullMap( + EntityInstantiator entityInstantiator, Map data, + Object dataObject, Number revision) { + return null; + } - public void mapToMapFromObject(SessionImplementor session, Map idData, Map data, Object obj) { - } + @Override + public void mapToMapFromObject( + SessionImplementor session, + Map idData, + Map data, + Object obj) { + } - public void addMiddleEqualToQuery(Parameters parameters, String idPrefix1, String prefix1, String idPrefix2, String prefix2) { - } + @Override + public void addMiddleEqualToQuery( + Parameters parameters, + String idPrefix1, + String prefix1, + String idPrefix2, + String prefix2) { + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleEmbeddableComponentMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleEmbeddableComponentMapper.java index f599d81e8c..8a36315829 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleEmbeddableComponentMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleEmbeddableComponentMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -49,39 +49,73 @@ public class MiddleEmbeddableComponentMapper implements MiddleComponentMapper, C } @Override - public Object mapToObjectFromFullMap(EntityInstantiator entityInstantiator, Map data, Object dataObject, Number revision) { + public Object mapToObjectFromFullMap( + EntityInstantiator entityInstantiator, + Map data, + Object dataObject, + Number revision) { try { - final Object componentInstance = dataObject != null ? dataObject : ReflectHelper.getDefaultConstructor( componentClass ).newInstance(); + final Object componentInstance = dataObject != null ? dataObject : ReflectHelper.getDefaultConstructor( + componentClass + ).newInstance(); delegate.mapToEntityFromMap( entityInstantiator.getAuditConfiguration(), componentInstance, data, null, entityInstantiator.getAuditReaderImplementor(), revision ); return componentInstance; } - catch ( Exception e ) { + catch (Exception e) { throw new AuditException( e ); } } @Override - public void mapToMapFromObject(SessionImplementor session, Map idData, Map data, Object obj) { + public void mapToMapFromObject( + SessionImplementor session, + Map idData, + Map data, + Object obj) { delegate.mapToMapFromEntity( session, data, obj, obj ); } @Override - public void addMiddleEqualToQuery(Parameters parameters, String idPrefix1, String prefix1, String idPrefix2, String prefix2) { + public void addMiddleEqualToQuery( + Parameters parameters, + String idPrefix1, + String prefix1, + String idPrefix2, + String prefix2) { addMiddleEqualToQuery( delegate, parameters, idPrefix1, prefix1, idPrefix2, prefix2 ); } - protected void addMiddleEqualToQuery(CompositeMapperBuilder compositeMapper, Parameters parameters, String idPrefix1, String prefix1, String idPrefix2, String prefix2) { + protected void addMiddleEqualToQuery( + CompositeMapperBuilder compositeMapper, + Parameters parameters, + String idPrefix1, + String prefix1, + String idPrefix2, + String prefix2) { for ( final Map.Entry entry : compositeMapper.getProperties().entrySet() ) { final String propertyName = entry.getKey().getName(); final PropertyMapper nestedMapper = entry.getValue(); if ( nestedMapper instanceof CompositeMapperBuilder ) { - addMiddleEqualToQuery( (CompositeMapperBuilder) nestedMapper, parameters, idPrefix1, prefix1, idPrefix2, prefix2 ); + addMiddleEqualToQuery( + (CompositeMapperBuilder) nestedMapper, + parameters, + idPrefix1, + prefix1, + idPrefix2, + prefix2 + ); } else if ( nestedMapper instanceof ToOneIdMapper ) { - ( (ToOneIdMapper) nestedMapper ).addMiddleEqualToQuery( parameters, idPrefix1, prefix1, idPrefix2, prefix2 ); + ((ToOneIdMapper) nestedMapper).addMiddleEqualToQuery( + parameters, + idPrefix1, + prefix1, + idPrefix2, + prefix2 + ); } else { parameters.addWhere( prefix1 + '.' + propertyName, false, "=", prefix2 + '.' + propertyName, false ); diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleMapKeyIdComponentMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleMapKeyIdComponentMapper.java index cc9c899e75..5298441418 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleMapKeyIdComponentMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleMapKeyIdComponentMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation.component; + import java.util.Map; import org.hibernate.engine.spi.SessionImplementor; @@ -34,27 +35,41 @@ import org.hibernate.envers.internal.tools.query.Parameters; * A component mapper for the @MapKey mapping: the value of the map's key is the id of the entity. This * doesn't have an effect on the data stored in the versions tables, so mapToMapFromObject is * empty. + * * @author Adam Warski (adam at warski dot org) */ public final class MiddleMapKeyIdComponentMapper implements MiddleComponentMapper { - private final AuditEntitiesConfiguration verEntCfg; - private final IdMapper relatedIdMapper; + private final AuditEntitiesConfiguration verEntCfg; + private final IdMapper relatedIdMapper; - public MiddleMapKeyIdComponentMapper(AuditEntitiesConfiguration verEntCfg, IdMapper relatedIdMapper) { - this.verEntCfg = verEntCfg; - this.relatedIdMapper = relatedIdMapper; - } + public MiddleMapKeyIdComponentMapper(AuditEntitiesConfiguration verEntCfg, IdMapper relatedIdMapper) { + this.verEntCfg = verEntCfg; + this.relatedIdMapper = relatedIdMapper; + } - public Object mapToObjectFromFullMap(EntityInstantiator entityInstantiator, Map data, - Object dataObject, Number revision) { - return relatedIdMapper.mapToIdFromMap((Map) data.get(verEntCfg.getOriginalIdPropName())); - } + @Override + public Object mapToObjectFromFullMap( + EntityInstantiator entityInstantiator, Map data, + Object dataObject, Number revision) { + return relatedIdMapper.mapToIdFromMap( (Map) data.get( verEntCfg.getOriginalIdPropName() ) ); + } - public void mapToMapFromObject(SessionImplementor session, Map idData, Map data, Object obj) { - // Doing nothing. - } + @Override + public void mapToMapFromObject( + SessionImplementor session, + Map idData, + Map data, + Object obj) { + // Doing nothing. + } - public void addMiddleEqualToQuery(Parameters parameters, String idPrefix1, String prefix1, String idPrefix2, String prefix2) { - // Doing nothing. - } + @Override + public void addMiddleEqualToQuery( + Parameters parameters, + String idPrefix1, + String prefix1, + String idPrefix2, + String prefix2) { + // Doing nothing. + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleMapKeyPropertyComponentMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleMapKeyPropertyComponentMapper.java index 943c22cab4..1a68b800a1 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleMapKeyPropertyComponentMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleMapKeyPropertyComponentMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -34,28 +34,42 @@ import org.hibernate.envers.internal.tools.query.Parameters; * A component mapper for the @MapKey mapping with the name parameter specified: the value of the map's key * is a property of the entity. This doesn't have an effect on the data stored in the versions tables, * so mapToMapFromObject is empty. + * * @author Adam Warski (adam at warski dot org) */ public class MiddleMapKeyPropertyComponentMapper implements MiddleComponentMapper { - private final String propertyName; - private final String accessType; + private final String propertyName; + private final String accessType; - public MiddleMapKeyPropertyComponentMapper(String propertyName, String accessType) { - this.propertyName = propertyName; - this.accessType = accessType; - } + public MiddleMapKeyPropertyComponentMapper(String propertyName, String accessType) { + this.propertyName = propertyName; + this.accessType = accessType; + } - public Object mapToObjectFromFullMap(EntityInstantiator entityInstantiator, Map data, - Object dataObject, Number revision) { - // dataObject is not null, as this mapper can only be used in an index. - return ReflectionTools.getGetter(dataObject.getClass(), propertyName, accessType).get(dataObject); - } + @Override + public Object mapToObjectFromFullMap( + EntityInstantiator entityInstantiator, Map data, + Object dataObject, Number revision) { + // dataObject is not null, as this mapper can only be used in an index. + return ReflectionTools.getGetter( dataObject.getClass(), propertyName, accessType ).get( dataObject ); + } - public void mapToMapFromObject(SessionImplementor session, Map idData, Map data, Object obj) { - // Doing nothing. - } + @Override + public void mapToMapFromObject( + SessionImplementor session, + Map idData, + Map data, + Object obj) { + // Doing nothing. + } - public void addMiddleEqualToQuery(Parameters parameters, String idPrefix1, String prefix1, String idPrefix2, String prefix2) { - // Doing nothing. - } + @Override + public void addMiddleEqualToQuery( + Parameters parameters, + String idPrefix1, + String prefix1, + String idPrefix2, + String prefix2) { + // Doing nothing. + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleRelatedComponentMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleRelatedComponentMapper.java index de340038d0..9150b4cf1a 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleRelatedComponentMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleRelatedComponentMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation.component; + import java.util.Map; import org.hibernate.engine.spi.SessionImplementor; @@ -33,22 +34,35 @@ import org.hibernate.envers.internal.tools.query.Parameters; * @author Adam Warski (adam at warski dot org) */ public final class MiddleRelatedComponentMapper implements MiddleComponentMapper { - private final MiddleIdData relatedIdData; + private final MiddleIdData relatedIdData; - public MiddleRelatedComponentMapper(MiddleIdData relatedIdData) { - this.relatedIdData = relatedIdData; - } + public MiddleRelatedComponentMapper(MiddleIdData relatedIdData) { + this.relatedIdData = relatedIdData; + } - public Object mapToObjectFromFullMap(EntityInstantiator entityInstantiator, Map data, - Object dataObject, Number revision) { - return entityInstantiator.createInstanceFromVersionsEntity(relatedIdData.getEntityName(), data, revision); - } + @Override + public Object mapToObjectFromFullMap( + EntityInstantiator entityInstantiator, Map data, + Object dataObject, Number revision) { + return entityInstantiator.createInstanceFromVersionsEntity( relatedIdData.getEntityName(), data, revision ); + } - public void mapToMapFromObject(SessionImplementor session, Map idData, Map data, Object obj) { - relatedIdData.getPrefixedMapper().mapToMapFromEntity(idData, obj); - } + @Override + public void mapToMapFromObject( + SessionImplementor session, + Map idData, + Map data, + Object obj) { + relatedIdData.getPrefixedMapper().mapToMapFromEntity( idData, obj ); + } - public void addMiddleEqualToQuery(Parameters parameters, String idPrefix1, String prefix1, String idPrefix2, String prefix2) { - relatedIdData.getPrefixedMapper().addIdsEqualToQuery(parameters, idPrefix1, idPrefix2); - } + @Override + public void addMiddleEqualToQuery( + Parameters parameters, + String idPrefix1, + String prefix1, + String idPrefix2, + String prefix2) { + relatedIdData.getPrefixedMapper().addIdsEqualToQuery( parameters, idPrefix1, idPrefix2 ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleSimpleComponentMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleSimpleComponentMapper.java index 4ccf1de192..25b5a2ea9a 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleSimpleComponentMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleSimpleComponentMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation.component; + import java.util.Map; import org.hibernate.engine.spi.SessionImplementor; @@ -33,25 +34,38 @@ import org.hibernate.envers.internal.tools.query.Parameters; * @author Adam Warski (adam at warski dot org) */ public final class MiddleSimpleComponentMapper implements MiddleComponentMapper { - private final String propertyName; - private final AuditEntitiesConfiguration verEntCfg; + private final String propertyName; + private final AuditEntitiesConfiguration verEntCfg; - public MiddleSimpleComponentMapper(AuditEntitiesConfiguration verEntCfg, String propertyName) { - this.propertyName = propertyName; - this.verEntCfg = verEntCfg; - } + public MiddleSimpleComponentMapper(AuditEntitiesConfiguration verEntCfg, String propertyName) { + this.propertyName = propertyName; + this.verEntCfg = verEntCfg; + } - @SuppressWarnings({"unchecked"}) - public Object mapToObjectFromFullMap(EntityInstantiator entityInstantiator, Map data, - Object dataObject, Number revision) { - return ((Map) data.get(verEntCfg.getOriginalIdPropName())).get(propertyName); - } + @Override + @SuppressWarnings({"unchecked"}) + public Object mapToObjectFromFullMap( + EntityInstantiator entityInstantiator, Map data, + Object dataObject, Number revision) { + return ((Map) data.get( verEntCfg.getOriginalIdPropName() )).get( propertyName ); + } - public void mapToMapFromObject(SessionImplementor session, Map idData, Map data, Object obj) { - idData.put(propertyName, obj); - } + @Override + public void mapToMapFromObject( + SessionImplementor session, + Map idData, + Map data, + Object obj) { + idData.put( propertyName, obj ); + } - public void addMiddleEqualToQuery(Parameters parameters, String idPrefix1, String prefix1, String idPrefix2, String prefix2) { - parameters.addWhere(idPrefix1 + "." + propertyName, false, "=", idPrefix2 + "." + propertyName, false); - } + @Override + public void addMiddleEqualToQuery( + Parameters parameters, + String idPrefix1, + String prefix1, + String idPrefix2, + String prefix2) { + parameters.addWhere( idPrefix1 + "." + propertyName, false, "=", idPrefix2 + "." + propertyName, false ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleStraightComponentMapper.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleStraightComponentMapper.java index 2457155d6d..02275fea4b 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleStraightComponentMapper.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/component/MiddleStraightComponentMapper.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation.component; + import java.util.Map; import org.hibernate.engine.spi.SessionImplementor; @@ -30,27 +31,41 @@ import org.hibernate.envers.internal.tools.query.Parameters; /** * A mapper for reading and writing a property straight to/from maps. This mapper cannot be used with middle tables, - * but only with "fake" bidirectional indexed relations. + * but only with "fake" bidirectional indexed relations. + * * @author Adam Warski (adam at warski dot org) */ public final class MiddleStraightComponentMapper implements MiddleComponentMapper { - private final String propertyName; + private final String propertyName; - public MiddleStraightComponentMapper(String propertyName) { - this.propertyName = propertyName; - } - - @SuppressWarnings({"unchecked"}) - public Object mapToObjectFromFullMap(EntityInstantiator entityInstantiator, Map data, - Object dataObject, Number revision) { - return data.get(propertyName); - } - - public void mapToMapFromObject(SessionImplementor session, Map idData, Map data, Object obj) { - idData.put(propertyName, obj); + public MiddleStraightComponentMapper(String propertyName) { + this.propertyName = propertyName; } - public void addMiddleEqualToQuery(Parameters parameters, String idPrefix1, String prefix1, String idPrefix2, String prefix2) { - throw new UnsupportedOperationException("Cannot use this mapper with a middle table!"); - } + @Override + @SuppressWarnings({"unchecked"}) + public Object mapToObjectFromFullMap( + EntityInstantiator entityInstantiator, Map data, + Object dataObject, Number revision) { + return data.get( propertyName ); + } + + @Override + public void mapToMapFromObject( + SessionImplementor session, + Map idData, + Map data, + Object obj) { + idData.put( propertyName, obj ); + } + + @Override + public void addMiddleEqualToQuery( + Parameters parameters, + String idPrefix1, + String prefix1, + String idPrefix2, + String prefix2) { + throw new UnsupportedOperationException( "Cannot use this mapper with a middle table!" ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/AbstractDelegateSessionImplementor.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/AbstractDelegateSessionImplementor.java index cd4823b78c..57bcd04a86 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/AbstractDelegateSessionImplementor.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/AbstractDelegateSessionImplementor.java @@ -1,7 +1,7 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as + * Copyright (c) 2013, 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. @@ -56,22 +56,22 @@ import org.hibernate.type.Type; /** * @author Adam Warski (adam at warski dot org) */ -@SuppressWarnings( {"deprecation"}) +@SuppressWarnings({"deprecation"}) public abstract class AbstractDelegateSessionImplementor implements SessionImplementor { - protected SessionImplementor delegate; + protected SessionImplementor delegate; - public AbstractDelegateSessionImplementor(SessionImplementor delegate) { - this.delegate = delegate; - } + public AbstractDelegateSessionImplementor(SessionImplementor delegate) { + this.delegate = delegate; + } - public abstract Object doImmediateLoad(String entityName); + public abstract Object doImmediateLoad(String entityName); @Override - public Object immediateLoad(String entityName, Serializable id) throws HibernateException { - return doImmediateLoad(entityName); - } + public Object immediateLoad(String entityName, Serializable id) throws HibernateException { + return doImmediateLoad( entityName ); + } - // Delegate methods + // Delegate methods @Override @@ -106,13 +106,13 @@ public abstract class AbstractDelegateSessionImplementor implements SessionImple @Override public Interceptor getInterceptor() { - return delegate.getInterceptor(); - } + return delegate.getInterceptor(); + } @Override - public void setAutoClear(boolean enabled) { - delegate.setAutoClear(enabled); - } + public void setAutoClear(boolean enabled) { + delegate.setAutoClear( enabled ); + } @Override public void disableTransactionAutoJoin() { @@ -121,148 +121,154 @@ public abstract class AbstractDelegateSessionImplementor implements SessionImple @Override public boolean isTransactionInProgress() { - return delegate.isTransactionInProgress(); - } + return delegate.isTransactionInProgress(); + } @Override - public void initializeCollection(PersistentCollection collection, boolean writing) throws HibernateException { - delegate.initializeCollection(collection, writing); - } + public void initializeCollection(PersistentCollection collection, boolean writing) throws HibernateException { + delegate.initializeCollection( collection, writing ); + } @Override - public Object internalLoad(String entityName, Serializable id, boolean eager, boolean nullable) throws HibernateException { - return delegate.internalLoad(entityName, id, eager, nullable); - } + public Object internalLoad(String entityName, Serializable id, boolean eager, boolean nullable) + throws HibernateException { + return delegate.internalLoad( entityName, id, eager, nullable ); + } @Override - public long getTimestamp() { - return delegate.getTimestamp(); - } + public long getTimestamp() { + return delegate.getTimestamp(); + } @Override - public SessionFactoryImplementor getFactory() { - return delegate.getFactory(); - } + public SessionFactoryImplementor getFactory() { + return delegate.getFactory(); + } @Override - public List list(String query, QueryParameters queryParameters) throws HibernateException { - return delegate.list(query, queryParameters); - } + public List list(String query, QueryParameters queryParameters) throws HibernateException { + return delegate.list( query, queryParameters ); + } @Override - public Iterator iterate(String query, QueryParameters queryParameters) throws HibernateException { - return delegate.iterate(query, queryParameters); - } + public Iterator iterate(String query, QueryParameters queryParameters) throws HibernateException { + return delegate.iterate( query, queryParameters ); + } @Override - public ScrollableResults scroll(String query, QueryParameters queryParameters) throws HibernateException { - return delegate.scroll(query, queryParameters); - } + public ScrollableResults scroll(String query, QueryParameters queryParameters) throws HibernateException { + return delegate.scroll( query, queryParameters ); + } @Override - public ScrollableResults scroll(Criteria criteria, ScrollMode scrollMode) { - return delegate.scroll(criteria, scrollMode); - } + public ScrollableResults scroll(Criteria criteria, ScrollMode scrollMode) { + return delegate.scroll( criteria, scrollMode ); + } @Override - public List list(Criteria criteria) { - return delegate.list(criteria); - } + public List list(Criteria criteria) { + return delegate.list( criteria ); + } @Override - public List listFilter(Object collection, String filter, QueryParameters queryParameters) throws HibernateException { - return delegate.listFilter(collection, filter, queryParameters); - } + public List listFilter(Object collection, String filter, QueryParameters queryParameters) + throws HibernateException { + return delegate.listFilter( collection, filter, queryParameters ); + } @Override - public Iterator iterateFilter(Object collection, String filter, QueryParameters queryParameters) throws HibernateException { - return delegate.iterateFilter(collection, filter, queryParameters); - } + public Iterator iterateFilter(Object collection, String filter, QueryParameters queryParameters) + throws HibernateException { + return delegate.iterateFilter( collection, filter, queryParameters ); + } @Override - public EntityPersister getEntityPersister(String entityName, Object object) throws HibernateException { - return delegate.getEntityPersister(entityName, object); - } + public EntityPersister getEntityPersister(String entityName, Object object) throws HibernateException { + return delegate.getEntityPersister( entityName, object ); + } @Override - public Object getEntityUsingInterceptor(EntityKey key) throws HibernateException { - return delegate.getEntityUsingInterceptor(key); - } + public Object getEntityUsingInterceptor(EntityKey key) throws HibernateException { + return delegate.getEntityUsingInterceptor( key ); + } @Override - public Serializable getContextEntityIdentifier(Object object) { - return delegate.getContextEntityIdentifier(object); - } + public Serializable getContextEntityIdentifier(Object object) { + return delegate.getContextEntityIdentifier( object ); + } @Override - public String bestGuessEntityName(Object object) { - return delegate.bestGuessEntityName(object); - } + public String bestGuessEntityName(Object object) { + return delegate.bestGuessEntityName( object ); + } @Override - public String guessEntityName(Object entity) throws HibernateException { - return delegate.guessEntityName(entity); - } + public String guessEntityName(Object entity) throws HibernateException { + return delegate.guessEntityName( entity ); + } @Override - public Object instantiate(String entityName, Serializable id) throws HibernateException { - return delegate.instantiate(entityName, id); - } + public Object instantiate(String entityName, Serializable id) throws HibernateException { + return delegate.instantiate( entityName, id ); + } @Override - public List listCustomQuery(CustomQuery customQuery, QueryParameters queryParameters) throws HibernateException { - return delegate.listCustomQuery(customQuery, queryParameters); - } + public List listCustomQuery(CustomQuery customQuery, QueryParameters queryParameters) throws HibernateException { + return delegate.listCustomQuery( customQuery, queryParameters ); + } @Override - public ScrollableResults scrollCustomQuery(CustomQuery customQuery, QueryParameters queryParameters) throws HibernateException { - return delegate.scrollCustomQuery(customQuery, queryParameters); - } + public ScrollableResults scrollCustomQuery(CustomQuery customQuery, QueryParameters queryParameters) + throws HibernateException { + return delegate.scrollCustomQuery( customQuery, queryParameters ); + } @Override - public List list(NativeSQLQuerySpecification spec, QueryParameters queryParameters) throws HibernateException { - return delegate.list(spec, queryParameters); - } + public List list(NativeSQLQuerySpecification spec, QueryParameters queryParameters) throws HibernateException { + return delegate.list( spec, queryParameters ); + } @Override - public ScrollableResults scroll(NativeSQLQuerySpecification spec, QueryParameters queryParameters) throws HibernateException { - return delegate.scroll(spec, queryParameters); - } + public ScrollableResults scroll(NativeSQLQuerySpecification spec, QueryParameters queryParameters) + throws HibernateException { + return delegate.scroll( spec, queryParameters ); + } @Override - public Object getFilterParameterValue(String filterParameterName) { - return delegate.getFilterParameterValue(filterParameterName); - } + public Object getFilterParameterValue(String filterParameterName) { + return delegate.getFilterParameterValue( filterParameterName ); + } @Override - public Type getFilterParameterType(String filterParameterName) { - return delegate.getFilterParameterType(filterParameterName); - } + public Type getFilterParameterType(String filterParameterName) { + return delegate.getFilterParameterType( filterParameterName ); + } @Override - public Map getEnabledFilters() { - return delegate.getEnabledFilters(); - } + public Map getEnabledFilters() { + return delegate.getEnabledFilters(); + } @Override - public int getDontFlushFromFind() { - return delegate.getDontFlushFromFind(); - } + public int getDontFlushFromFind() { + return delegate.getDontFlushFromFind(); + } @Override - public PersistenceContext getPersistenceContext() { - return delegate.getPersistenceContext(); - } + public PersistenceContext getPersistenceContext() { + return delegate.getPersistenceContext(); + } @Override - public int executeUpdate(String query, QueryParameters queryParameters) throws HibernateException { - return delegate.executeUpdate(query, queryParameters); - } + public int executeUpdate(String query, QueryParameters queryParameters) throws HibernateException { + return delegate.executeUpdate( query, queryParameters ); + } @Override - public int executeNativeUpdate(NativeSQLQuerySpecification specification, QueryParameters queryParameters) throws HibernateException { - return delegate.executeNativeUpdate(specification, queryParameters); - } + public int executeNativeUpdate(NativeSQLQuerySpecification specification, QueryParameters queryParameters) + throws HibernateException { + return delegate.executeNativeUpdate( specification, queryParameters ); + } @Override public NonFlushedChanges getNonFlushedChanges() throws HibernateException { @@ -275,74 +281,74 @@ public abstract class AbstractDelegateSessionImplementor implements SessionImple } @Override - public CacheMode getCacheMode() { - return delegate.getCacheMode(); - } + public CacheMode getCacheMode() { + return delegate.getCacheMode(); + } @Override - public void setCacheMode(CacheMode cm) { - delegate.setCacheMode(cm); - } + public void setCacheMode(CacheMode cm) { + delegate.setCacheMode( cm ); + } @Override - public boolean isOpen() { - return delegate.isOpen(); - } + public boolean isOpen() { + return delegate.isOpen(); + } @Override - public boolean isConnected() { - return delegate.isConnected(); - } + public boolean isConnected() { + return delegate.isConnected(); + } @Override - public FlushMode getFlushMode() { - return delegate.getFlushMode(); - } + public FlushMode getFlushMode() { + return delegate.getFlushMode(); + } @Override - public void setFlushMode(FlushMode fm) { - delegate.setFlushMode(fm); - } + public void setFlushMode(FlushMode fm) { + delegate.setFlushMode( fm ); + } @Override - public Connection connection() { - return delegate.connection(); - } + public Connection connection() { + return delegate.connection(); + } @Override - public void flush() { - delegate.flush(); - } + public void flush() { + delegate.flush(); + } @Override - public Query getNamedQuery(String name) { - return delegate.getNamedQuery(name); - } + public Query getNamedQuery(String name) { + return delegate.getNamedQuery( name ); + } @Override - public Query getNamedSQLQuery(String name) { - return delegate.getNamedSQLQuery(name); - } + public Query getNamedSQLQuery(String name) { + return delegate.getNamedSQLQuery( name ); + } @Override - public boolean isEventSource() { - return delegate.isEventSource(); - } + public boolean isEventSource() { + return delegate.isEventSource(); + } @Override - public void afterScrollOperation() { - delegate.afterScrollOperation(); - } + public void afterScrollOperation() { + delegate.afterScrollOperation(); + } @Override - public void setFetchProfile(String name) { - delegate.setFetchProfile(name); - } + public void setFetchProfile(String name) { + delegate.setFetchProfile( name ); + } @Override - public String getFetchProfile() { - return delegate.getFetchProfile(); - } + public String getFetchProfile() { + return delegate.getFetchProfile(); + } @Override public TransactionCoordinator getTransactionCoordinator() { @@ -351,6 +357,6 @@ public abstract class AbstractDelegateSessionImplementor implements SessionImple @Override public boolean isClosed() { - return delegate.isClosed(); - } + return delegate.isClosed(); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/ToOneDelegateSessionImplementor.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/ToOneDelegateSessionImplementor.java index 13394d437f..23f1855490 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/ToOneDelegateSessionImplementor.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/ToOneDelegateSessionImplementor.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -35,27 +35,37 @@ import org.hibernate.envers.internal.reader.AuditReaderImplementor; */ public class ToOneDelegateSessionImplementor extends AbstractDelegateSessionImplementor { private static final long serialVersionUID = 4770438372940785488L; - - private final AuditReaderImplementor versionsReader; - private final Class entityClass; - private final Object entityId; - private final Number revision; - private final boolean removed; - private final AuditConfiguration verCfg; - public ToOneDelegateSessionImplementor(AuditReaderImplementor versionsReader, - Class entityClass, Object entityId, Number revision, boolean removed, - AuditConfiguration verCfg) { - super(versionsReader.getSessionImplementor()); - this.versionsReader = versionsReader; - this.entityClass = entityClass; - this.entityId = entityId; - this.revision = revision; - this.removed = removed; - this.verCfg = verCfg; - } + private final AuditReaderImplementor versionsReader; + private final Class entityClass; + private final Object entityId; + private final Number revision; + private final boolean removed; + private final AuditConfiguration verCfg; - public Object doImmediateLoad(String entityName) throws HibernateException { - return ToOneEntityLoader.loadImmediate( versionsReader, entityClass, entityName, entityId, revision, removed, verCfg ); - } + public ToOneDelegateSessionImplementor( + AuditReaderImplementor versionsReader, + Class entityClass, Object entityId, Number revision, boolean removed, + AuditConfiguration verCfg) { + super( versionsReader.getSessionImplementor() ); + this.versionsReader = versionsReader; + this.entityClass = entityClass; + this.entityId = entityId; + this.revision = revision; + this.removed = removed; + this.verCfg = verCfg; + } + + @Override + public Object doImmediateLoad(String entityName) throws HibernateException { + return ToOneEntityLoader.loadImmediate( + versionsReader, + entityClass, + entityName, + entityId, + revision, + removed, + verCfg + ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/AbstractCollectionInitializor.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/AbstractCollectionInitializor.java index c2d43ff8eb..55f91f2542 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/AbstractCollectionInitializor.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/AbstractCollectionInitializor.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor; + import java.util.List; import org.hibernate.envers.configuration.spi.AuditConfiguration; @@ -31,42 +32,45 @@ import org.hibernate.envers.internal.reader.AuditReaderImplementor; /** * Initializes a persistent collection. + * * @author Adam Warski (adam at warski dot org) */ public abstract class AbstractCollectionInitializor implements Initializor { - private final AuditReaderImplementor versionsReader; - private final RelationQueryGenerator queryGenerator; - private final Object primaryKey; - protected final Number revision; + private final AuditReaderImplementor versionsReader; + private final RelationQueryGenerator queryGenerator; + private final Object primaryKey; + protected final Number revision; protected final boolean removed; - protected final EntityInstantiator entityInstantiator; + protected final EntityInstantiator entityInstantiator; - public AbstractCollectionInitializor(AuditConfiguration verCfg, - AuditReaderImplementor versionsReader, - RelationQueryGenerator queryGenerator, - Object primaryKey, Number revision, boolean removed) { - this.versionsReader = versionsReader; - this.queryGenerator = queryGenerator; - this.primaryKey = primaryKey; - this.revision = revision; + public AbstractCollectionInitializor( + AuditConfiguration verCfg, + AuditReaderImplementor versionsReader, + RelationQueryGenerator queryGenerator, + Object primaryKey, Number revision, boolean removed) { + this.versionsReader = versionsReader; + this.queryGenerator = queryGenerator; + this.primaryKey = primaryKey; + this.revision = revision; this.removed = removed; - entityInstantiator = new EntityInstantiator(verCfg, versionsReader); - } + entityInstantiator = new EntityInstantiator( verCfg, versionsReader ); + } - protected abstract T initializeCollection(int size); + protected abstract T initializeCollection(int size); - protected abstract void addToCollection(T collection, Object collectionRow); + protected abstract void addToCollection(T collection, Object collectionRow); - public T initialize() { - List collectionContent = queryGenerator.getQuery(versionsReader, primaryKey, revision, removed).list(); + @Override + public T initialize() { + final List collectionContent = queryGenerator.getQuery( versionsReader, primaryKey, revision, removed ).list(); - T collection = initializeCollection(collectionContent.size()); + final T collection = initializeCollection( collectionContent.size() ); - for (Object collectionRow : collectionContent) { - addToCollection(collection, collectionRow); - } + for ( Object collectionRow : collectionContent ) { + addToCollection( collection, collectionRow ); + } - return collection; - } + return collection; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/ArrayCollectionInitializor.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/ArrayCollectionInitializor.java index d6116fdde5..37d1b8ccdb 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/ArrayCollectionInitializor.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/ArrayCollectionInitializor.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor; + import java.util.List; import java.util.Map; @@ -32,39 +33,47 @@ import org.hibernate.envers.internal.reader.AuditReaderImplementor; /** * Initializes a map. + * * @author Adam Warski (adam at warski dot org) */ public class ArrayCollectionInitializor extends AbstractCollectionInitializor { - private final MiddleComponentData elementComponentData; - private final MiddleComponentData indexComponentData; + private final MiddleComponentData elementComponentData; + private final MiddleComponentData indexComponentData; - public ArrayCollectionInitializor(AuditConfiguration verCfg, - AuditReaderImplementor versionsReader, - RelationQueryGenerator queryGenerator, - Object primaryKey, Number revision, boolean removed, - MiddleComponentData elementComponentData, - MiddleComponentData indexComponentData) { - super(verCfg, versionsReader, queryGenerator, primaryKey, revision, removed); + public ArrayCollectionInitializor( + AuditConfiguration verCfg, + AuditReaderImplementor versionsReader, + RelationQueryGenerator queryGenerator, + Object primaryKey, Number revision, boolean removed, + MiddleComponentData elementComponentData, + MiddleComponentData indexComponentData) { + super( verCfg, versionsReader, queryGenerator, primaryKey, revision, removed ); - this.elementComponentData = elementComponentData; - this.indexComponentData = indexComponentData; - } + this.elementComponentData = elementComponentData; + this.indexComponentData = indexComponentData; + } - protected Object[] initializeCollection(int size) { - return new Object[size]; - } + @Override + protected Object[] initializeCollection(int size) { + return new Object[size]; + } - @SuppressWarnings({"unchecked"}) - protected void addToCollection(Object[] collection, Object collectionRow) { - Object elementData = ((List) collectionRow).get(elementComponentData.getComponentIndex()); - Object element = elementComponentData.getComponentMapper().mapToObjectFromFullMap(entityInstantiator, - (Map) elementData, null, revision); + @Override + @SuppressWarnings({"unchecked"}) + protected void addToCollection(Object[] collection, Object collectionRow) { + final Object elementData = ((List) collectionRow).get( elementComponentData.getComponentIndex() ); + final Object element = elementComponentData.getComponentMapper().mapToObjectFromFullMap( + entityInstantiator, + (Map) elementData, null, revision + ); - Object indexData = ((List) collectionRow).get(indexComponentData.getComponentIndex()); - Object indexObj = indexComponentData.getComponentMapper().mapToObjectFromFullMap(entityInstantiator, - (Map) indexData, element, revision); - int index = ((Number) indexObj).intValue(); + final Object indexData = ((List) collectionRow).get( indexComponentData.getComponentIndex() ); + final Object indexObj = indexComponentData.getComponentMapper().mapToObjectFromFullMap( + entityInstantiator, + (Map) indexData, element, revision + ); + final int index = ((Number) indexObj).intValue(); - collection[index] = element; - } + collection[index] = element; + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/BasicCollectionInitializor.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/BasicCollectionInitializor.java index f3c00bfba6..754b918099 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/BasicCollectionInitializor.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/BasicCollectionInitializor.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -37,54 +37,65 @@ import org.hibernate.internal.util.ReflectHelper; /** * Initializes a non-indexed java collection (set or list, eventually sorted). + * * @author Adam Warski (adam at warski dot org) */ public class BasicCollectionInitializor extends AbstractCollectionInitializor { - protected final Class collectionClass; - private final MiddleComponentData elementComponentData; + protected final Class collectionClass; + private final MiddleComponentData elementComponentData; - public BasicCollectionInitializor(AuditConfiguration verCfg, - AuditReaderImplementor versionsReader, - RelationQueryGenerator queryGenerator, - Object primaryKey, Number revision, boolean removed, - Class collectionClass, - MiddleComponentData elementComponentData) { - super(verCfg, versionsReader, queryGenerator, primaryKey, revision, removed); + public BasicCollectionInitializor( + AuditConfiguration verCfg, + AuditReaderImplementor versionsReader, + RelationQueryGenerator queryGenerator, + Object primaryKey, Number revision, boolean removed, + Class collectionClass, + MiddleComponentData elementComponentData) { + super( verCfg, versionsReader, queryGenerator, primaryKey, revision, removed ); - this.collectionClass = collectionClass; - this.elementComponentData = elementComponentData; - } - - protected T initializeCollection(int size) { - try { - return (T) ReflectHelper.getDefaultConstructor(collectionClass).newInstance(); - } catch (InstantiationException e) { - throw new AuditException(e); - } catch (IllegalAccessException e) { - throw new AuditException(e); - } catch (InvocationTargetException e) { - throw new AuditException(e); - } - } - - @SuppressWarnings({"unchecked"}) - protected void addToCollection(T collection, Object collectionRow) { - // collectionRow will be the actual object if retrieved from audit relation or middle table - // otherwise it will be a List - Object elementData = collectionRow; - if (collectionRow instanceof java.util.List) { - elementData = ((List) collectionRow).get(elementComponentData.getComponentIndex()); + this.collectionClass = collectionClass; + this.elementComponentData = elementComponentData; } - // If the target entity is not audited, the elements may be the entities already, so we have to check - // if they are maps or not. - Object element; - if (elementData instanceof Map) { - element = elementComponentData.getComponentMapper().mapToObjectFromFullMap(entityInstantiator, - (Map) elementData, null, revision); - } else { - element = elementData; - } - collection.add(element); - } + @Override + @SuppressWarnings("unchecked") + protected T initializeCollection(int size) { + try { + return (T) ReflectHelper.getDefaultConstructor( collectionClass ).newInstance(); + } + catch (InstantiationException e) { + throw new AuditException( e ); + } + catch (IllegalAccessException e) { + throw new AuditException( e ); + } + catch (InvocationTargetException e) { + throw new AuditException( e ); + } + } + + @Override + @SuppressWarnings({"unchecked"}) + protected void addToCollection(T collection, Object collectionRow) { + // collectionRow will be the actual object if retrieved from audit relation or middle table + // otherwise it will be a List + Object elementData = collectionRow; + if ( collectionRow instanceof java.util.List ) { + elementData = ((List) collectionRow).get( elementComponentData.getComponentIndex() ); + } + + // If the target entity is not audited, the elements may be the entities already, so we have to check + // if they are maps or not. + Object element; + if ( elementData instanceof Map ) { + element = elementComponentData.getComponentMapper().mapToObjectFromFullMap( + entityInstantiator, + (Map) elementData, null, revision + ); + } + else { + element = elementData; + } + collection.add( element ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/Initializor.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/Initializor.java index a283eb1d57..55116651fe 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/Initializor.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/Initializor.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -28,5 +28,5 @@ package org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor; * @author Adam Warski (adam at warski dot org) */ public interface Initializor { - T initialize(); + T initialize(); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/ListCollectionInitializor.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/ListCollectionInitializor.java index 44eef60d8f..851254631d 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/ListCollectionInitializor.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/ListCollectionInitializor.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor; + import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -33,52 +34,62 @@ import org.hibernate.envers.internal.reader.AuditReaderImplementor; /** * Initializes a map. + * * @author Adam Warski (adam at warski dot org) */ public class ListCollectionInitializor extends AbstractCollectionInitializor { - private final MiddleComponentData elementComponentData; - private final MiddleComponentData indexComponentData; + private final MiddleComponentData elementComponentData; + private final MiddleComponentData indexComponentData; - public ListCollectionInitializor(AuditConfiguration verCfg, - AuditReaderImplementor versionsReader, - RelationQueryGenerator queryGenerator, - Object primaryKey, Number revision, boolean removed, - MiddleComponentData elementComponentData, - MiddleComponentData indexComponentData) { - super(verCfg, versionsReader, queryGenerator, primaryKey, revision, removed); + public ListCollectionInitializor( + AuditConfiguration verCfg, + AuditReaderImplementor versionsReader, + RelationQueryGenerator queryGenerator, + Object primaryKey, Number revision, boolean removed, + MiddleComponentData elementComponentData, + MiddleComponentData indexComponentData) { + super( verCfg, versionsReader, queryGenerator, primaryKey, revision, removed ); - this.elementComponentData = elementComponentData; - this.indexComponentData = indexComponentData; - } - - @SuppressWarnings({"unchecked"}) - protected List initializeCollection(int size) { - // Creating a list of the given capacity with all elements null initially. This ensures that we can then - // fill the elements safely using the List.set method. - List list = new ArrayList(size); - for (int i=0; i) elementData, null, revision) - : elementData ; - Object indexObj = indexComponentData.getComponentMapper().mapToObjectFromFullMap(entityInstantiator, - (Map) indexData, element, revision); - int index = ((Number) indexObj).intValue(); + @Override + @SuppressWarnings({"unchecked"}) + protected List initializeCollection(int size) { + // Creating a list of the given capacity with all elements null initially. This ensures that we can then + // fill the elements safely using the List.set method. + final List list = new ArrayList( size ); + for ( int i = 0; i < size; i++ ) { + list.add( null ); + } + return list; + } - collection.set(index, element); - } + @Override + @SuppressWarnings({"unchecked"}) + protected void addToCollection(List collection, Object collectionRow) { + // collectionRow will be the actual object if retrieved from audit relation or middle table + // otherwise it will be a List + Object elementData = collectionRow; + Object indexData = collectionRow; + if ( collectionRow instanceof java.util.List ) { + elementData = ((List) collectionRow).get( elementComponentData.getComponentIndex() ); + indexData = ((List) collectionRow).get( indexComponentData.getComponentIndex() ); + } + final Object element = elementData instanceof Map + ? elementComponentData.getComponentMapper().mapToObjectFromFullMap( + entityInstantiator, + (Map) elementData, null, revision + ) + : elementData; + + final Object indexObj = indexComponentData.getComponentMapper().mapToObjectFromFullMap( + entityInstantiator, + (Map) indexData, element, revision + ); + final int index = ((Number) indexObj).intValue(); + + collection.set( index, element ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/MapCollectionInitializor.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/MapCollectionInitializor.java index 7994fad18f..f6d1c34104 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/MapCollectionInitializor.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/MapCollectionInitializor.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -36,55 +36,67 @@ import org.hibernate.internal.util.ReflectHelper; /** * Initializes a map. + * * @author Adam Warski (adam at warski dot org) */ public class MapCollectionInitializor extends AbstractCollectionInitializor { - protected final Class collectionClass; - private final MiddleComponentData elementComponentData; - private final MiddleComponentData indexComponentData; + protected final Class collectionClass; + private final MiddleComponentData elementComponentData; + private final MiddleComponentData indexComponentData; - public MapCollectionInitializor(AuditConfiguration verCfg, - AuditReaderImplementor versionsReader, - RelationQueryGenerator queryGenerator, - Object primaryKey, Number revision, boolean removed, - Class collectionClass, - MiddleComponentData elementComponentData, - MiddleComponentData indexComponentData) { - super(verCfg, versionsReader, queryGenerator, primaryKey, revision, removed); + public MapCollectionInitializor( + AuditConfiguration verCfg, + AuditReaderImplementor versionsReader, + RelationQueryGenerator queryGenerator, + Object primaryKey, Number revision, boolean removed, + Class collectionClass, + MiddleComponentData elementComponentData, + MiddleComponentData indexComponentData) { + super( verCfg, versionsReader, queryGenerator, primaryKey, revision, removed ); - this.collectionClass = collectionClass; - this.elementComponentData = elementComponentData; - this.indexComponentData = indexComponentData; - } - - protected T initializeCollection(int size) { - try { - return (T) ReflectHelper.getDefaultConstructor(collectionClass).newInstance(); - } catch (InstantiationException e) { - throw new AuditException(e); - } catch (IllegalAccessException e) { - throw new AuditException(e); - } catch (InvocationTargetException e) { - throw new AuditException(e); - } - } - - @SuppressWarnings({"unchecked"}) - protected void addToCollection(T collection, Object collectionRow) { - // collectionRow will be the actual object if retrieved from audit relation or middle table - // otherwise it will be a List - Object elementData = collectionRow; - Object indexData = collectionRow; - if (collectionRow instanceof java.util.List) { - elementData = ((List) collectionRow).get(elementComponentData.getComponentIndex()); - indexData = ((List) collectionRow).get(indexComponentData.getComponentIndex()); + this.collectionClass = collectionClass; + this.elementComponentData = elementComponentData; + this.indexComponentData = indexComponentData; } - Object element = elementComponentData.getComponentMapper().mapToObjectFromFullMap(entityInstantiator, - (Map) elementData, null, revision); - Object index = indexComponentData.getComponentMapper().mapToObjectFromFullMap(entityInstantiator, - (Map) indexData, element, revision); + @Override + @SuppressWarnings("unchecked") + protected T initializeCollection(int size) { + try { + return (T) ReflectHelper.getDefaultConstructor( collectionClass ).newInstance(); + } + catch (InstantiationException e) { + throw new AuditException( e ); + } + catch (IllegalAccessException e) { + throw new AuditException( e ); + } + catch (InvocationTargetException e) { + throw new AuditException( e ); + } + } - collection.put(index, element); - } + @Override + @SuppressWarnings({"unchecked"}) + protected void addToCollection(T collection, Object collectionRow) { + // collectionRow will be the actual object if retrieved from audit relation or middle table + // otherwise it will be a List + Object elementData = collectionRow; + Object indexData = collectionRow; + if ( collectionRow instanceof java.util.List ) { + elementData = ((List) collectionRow).get( elementComponentData.getComponentIndex() ); + indexData = ((List) collectionRow).get( indexComponentData.getComponentIndex() ); + } + final Object element = elementComponentData.getComponentMapper().mapToObjectFromFullMap( + entityInstantiator, + (Map) elementData, null, revision + ); + + final Object index = indexComponentData.getComponentMapper().mapToObjectFromFullMap( + entityInstantiator, + (Map) indexData, element, revision + ); + + collection.put( index, element ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/SortedMapCollectionInitializor.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/SortedMapCollectionInitializor.java index d7107e6482..562d4f3546 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/SortedMapCollectionInitializor.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/SortedMapCollectionInitializor.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -41,31 +41,47 @@ import org.hibernate.envers.internal.reader.AuditReaderImplementor; public class SortedMapCollectionInitializor extends MapCollectionInitializor { private final Comparator comparator; - public SortedMapCollectionInitializor(AuditConfiguration verCfg, - AuditReaderImplementor versionsReader, - RelationQueryGenerator queryGenerator, - Object primaryKey, Number revision, boolean removed, - Class collectionClass, - MiddleComponentData elementComponentData, - MiddleComponentData indexComponentData, Comparator comparator) { - super(verCfg, versionsReader, queryGenerator, primaryKey, revision, removed, collectionClass, elementComponentData, indexComponentData); + public SortedMapCollectionInitializor( + AuditConfiguration verCfg, + AuditReaderImplementor versionsReader, + RelationQueryGenerator queryGenerator, + Object primaryKey, Number revision, boolean removed, + Class collectionClass, + MiddleComponentData elementComponentData, + MiddleComponentData indexComponentData, Comparator comparator) { + super( + verCfg, + versionsReader, + queryGenerator, + primaryKey, + revision, + removed, + collectionClass, + elementComponentData, + indexComponentData + ); this.comparator = comparator; } + @Override protected SortedMap initializeCollection(int size) { - if (comparator == null) { - return super.initializeCollection(size); + if ( comparator == null ) { + return super.initializeCollection( size ); } try { - return collectionClass.getConstructor(Comparator.class).newInstance(comparator); - } catch (InstantiationException e) { - throw new AuditException(e); - } catch (IllegalAccessException e) { - throw new AuditException(e); - } catch (NoSuchMethodException e) { - throw new AuditException(e); - } catch (InvocationTargetException e) { - throw new AuditException(e); + return collectionClass.getConstructor( Comparator.class ).newInstance( comparator ); + } + catch (InstantiationException e) { + throw new AuditException( e ); + } + catch (IllegalAccessException e) { + throw new AuditException( e ); + } + catch (NoSuchMethodException e) { + throw new AuditException( e ); + } + catch (InvocationTargetException e) { + throw new AuditException( e ); } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/SortedSetCollectionInitializor.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/SortedSetCollectionInitializor.java index 3958de056e..f171e5f68b 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/SortedSetCollectionInitializor.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/SortedSetCollectionInitializor.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -41,29 +41,43 @@ import org.hibernate.envers.internal.reader.AuditReaderImplementor; public class SortedSetCollectionInitializor extends BasicCollectionInitializor { private final Comparator comparator; - public SortedSetCollectionInitializor(AuditConfiguration verCfg, AuditReaderImplementor versionsReader, - RelationQueryGenerator queryGenerator, Object primaryKey, Number revision, boolean removed, - Class collectionClass, MiddleComponentData elementComponentData, - Comparator comparator) { - super(verCfg, versionsReader, queryGenerator, primaryKey, revision, removed, collectionClass, elementComponentData); + public SortedSetCollectionInitializor( + AuditConfiguration verCfg, AuditReaderImplementor versionsReader, + RelationQueryGenerator queryGenerator, Object primaryKey, Number revision, boolean removed, + Class collectionClass, MiddleComponentData elementComponentData, + Comparator comparator) { + super( + verCfg, + versionsReader, + queryGenerator, + primaryKey, + revision, + removed, + collectionClass, + elementComponentData + ); this.comparator = comparator; } @Override protected SortedSet initializeCollection(int size) { - if (comparator == null) { - return super.initializeCollection(size); + if ( comparator == null ) { + return super.initializeCollection( size ); } try { - return collectionClass.getConstructor(Comparator.class).newInstance(comparator); - } catch (InstantiationException e) { - throw new AuditException(e); - } catch (IllegalAccessException e) { - throw new AuditException(e); - } catch (NoSuchMethodException e) { - throw new AuditException(e); - } catch (InvocationTargetException e) { - throw new AuditException(e); + return collectionClass.getConstructor( Comparator.class ).newInstance( comparator ); + } + catch (InstantiationException e) { + throw new AuditException( e ); + } + catch (IllegalAccessException e) { + throw new AuditException( e ); + } + catch (NoSuchMethodException e) { + throw new AuditException( e ); + } + catch (InvocationTargetException e) { + throw new AuditException( e ); } } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/CollectionProxy.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/CollectionProxy.java index d44180cbe0..74cc36fd50 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/CollectionProxy.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/CollectionProxy.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation.lazy.proxy; + import java.io.Serializable; import java.util.Collection; import java.util.Iterator; @@ -35,102 +36,115 @@ public abstract class CollectionProxy> implements Col private static final long serialVersionUID = 8698249863871832402L; private transient org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor.Initializor initializor; - protected T delegate; + protected T delegate; - protected CollectionProxy() { - } + protected CollectionProxy() { + } - public CollectionProxy(Initializor initializor) { - this.initializor = initializor; - } + public CollectionProxy(Initializor initializor) { + this.initializor = initializor; + } - protected void checkInit() { - if (delegate == null) { - delegate = initializor.initialize(); - } - } + protected void checkInit() { + if ( delegate == null ) { + delegate = initializor.initialize(); + } + } - public int size() { - checkInit(); - return delegate.size(); - } + @Override + public int size() { + checkInit(); + return delegate.size(); + } - public boolean isEmpty() { - checkInit(); - return delegate.isEmpty(); - } + @Override + public boolean isEmpty() { + checkInit(); + return delegate.isEmpty(); + } - public boolean contains(Object o) { - checkInit(); - return delegate.contains(o); - } + @Override + public boolean contains(Object o) { + checkInit(); + return delegate.contains( o ); + } - public Iterator iterator() { - checkInit(); - return delegate.iterator(); - } + @Override + public Iterator iterator() { + checkInit(); + return delegate.iterator(); + } - public Object[] toArray() { - checkInit(); - return delegate.toArray(); - } + @Override + public Object[] toArray() { + checkInit(); + return delegate.toArray(); + } - public V[] toArray(V[] a) { - checkInit(); - return delegate.toArray(a); - } + @Override + public V[] toArray(V[] a) { + checkInit(); + return delegate.toArray( a ); + } - public boolean add(U o) { - checkInit(); - return delegate.add(o); - } + @Override + public boolean add(U o) { + checkInit(); + return delegate.add( o ); + } - public boolean remove(Object o) { - checkInit(); - return delegate.remove(o); - } + @Override + public boolean remove(Object o) { + checkInit(); + return delegate.remove( o ); + } - public boolean containsAll(Collection c) { - checkInit(); - return delegate.containsAll(c); - } + @Override + public boolean containsAll(Collection c) { + checkInit(); + return delegate.containsAll( c ); + } - public boolean addAll(Collection c) { - checkInit(); - return delegate.addAll(c); - } + @Override + public boolean addAll(Collection c) { + checkInit(); + return delegate.addAll( c ); + } - public boolean removeAll(Collection c) { - checkInit(); - return delegate.removeAll(c); - } + @Override + public boolean removeAll(Collection c) { + checkInit(); + return delegate.removeAll( c ); + } - public boolean retainAll(Collection c) { - checkInit(); - return delegate.retainAll(c); - } + @Override + public boolean retainAll(Collection c) { + checkInit(); + return delegate.retainAll( c ); + } - public void clear() { - checkInit(); - delegate.clear(); - } + @Override + public void clear() { + checkInit(); + delegate.clear(); + } - @Override - public String toString() { - checkInit(); - return delegate.toString(); - } + @Override + public String toString() { + checkInit(); + return delegate.toString(); + } - @SuppressWarnings({"EqualsWhichDoesntCheckParameterClass"}) - @Override - public boolean equals(Object obj) { - checkInit(); - return delegate.equals(obj); - } + @SuppressWarnings({"EqualsWhichDoesntCheckParameterClass"}) + @Override + public boolean equals(Object obj) { + checkInit(); + return delegate.equals( obj ); + } - @Override - public int hashCode() { - checkInit(); - return delegate.hashCode(); - } + @Override + public int hashCode() { + checkInit(); + return delegate.hashCode(); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/ListProxy.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/ListProxy.java index 348f778711..55ccf5de52 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/ListProxy.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/ListProxy.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation.lazy.proxy; + import java.util.Collection; import java.util.List; import java.util.ListIterator; @@ -30,62 +31,72 @@ import java.util.ListIterator; * @author Adam Warski (adam at warski dot org) */ public class ListProxy extends CollectionProxy> implements List { - private static final long serialVersionUID = -5479232938279790987L; + private static final long serialVersionUID = -5479232938279790987L; - public ListProxy() { - } + public ListProxy() { + } - public ListProxy(org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor.Initializor> initializor) { - super(initializor); - } + public ListProxy(org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor.Initializor> initializor) { + super( initializor ); + } - public boolean addAll(int index, Collection c) { - checkInit(); - return delegate.addAll(index, c); - } + @Override + public boolean addAll(int index, Collection c) { + checkInit(); + return delegate.addAll( index, c ); + } - public U get(int index) { - checkInit(); - return delegate.get(index); - } + @Override + public U get(int index) { + checkInit(); + return delegate.get( index ); + } - public U set(int index, U element) { - checkInit(); - return delegate.set(index, element); - } + @Override + public U set(int index, U element) { + checkInit(); + return delegate.set( index, element ); + } - public void add(int index, U element) { - checkInit(); - delegate.add(index, element); - } + @Override + public void add(int index, U element) { + checkInit(); + delegate.add( index, element ); + } - public U remove(int index) { - checkInit(); - return delegate.remove(index); - } + @Override + public U remove(int index) { + checkInit(); + return delegate.remove( index ); + } - public int indexOf(Object o) { - checkInit(); - return delegate.indexOf(o); - } + @Override + public int indexOf(Object o) { + checkInit(); + return delegate.indexOf( o ); + } - public int lastIndexOf(Object o) { - checkInit(); - return delegate.lastIndexOf(o); - } + @Override + public int lastIndexOf(Object o) { + checkInit(); + return delegate.lastIndexOf( o ); + } - public ListIterator listIterator() { - checkInit(); - return delegate.listIterator(); - } + @Override + public ListIterator listIterator() { + checkInit(); + return delegate.listIterator(); + } - public ListIterator listIterator(int index) { - checkInit(); - return delegate.listIterator(index); - } + @Override + public ListIterator listIterator(int index) { + checkInit(); + return delegate.listIterator( index ); + } - public List subList(int fromIndex, int toIndex) { - checkInit(); - return delegate.subList(fromIndex, toIndex); - } + @Override + public List subList(int fromIndex, int toIndex) { + checkInit(); + return delegate.subList( fromIndex, toIndex ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/MapProxy.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/MapProxy.java index bbc4e97386..f1096ef82e 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/MapProxy.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/MapProxy.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation.lazy.proxy; + import java.io.Serializable; import java.util.Collection; import java.util.Map; @@ -33,100 +34,112 @@ import org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor.I * @author Adam Warski (adam at warski dot org) */ public class MapProxy implements Map, Serializable { - private static final long serialVersionUID = 8418037541773074646L; + private static final long serialVersionUID = 8418037541773074646L; - private transient Initializor> initializor; - protected Map delegate; + private transient Initializor> initializor; + protected Map delegate; - public MapProxy() { - } + public MapProxy() { + } - public MapProxy(org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor.Initializor> initializor) { - this.initializor = initializor; - } + public MapProxy(org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor.Initializor> initializor) { + this.initializor = initializor; + } - private void checkInit() { - if (delegate == null) { - delegate = initializor.initialize(); - } - } + private void checkInit() { + if ( delegate == null ) { + delegate = initializor.initialize(); + } + } - public int size() { - checkInit(); - return delegate.size(); - } + @Override + public int size() { + checkInit(); + return delegate.size(); + } - public boolean isEmpty() { - checkInit(); - return delegate.isEmpty(); - } + @Override + public boolean isEmpty() { + checkInit(); + return delegate.isEmpty(); + } - public boolean containsKey(Object o) { - checkInit(); - return delegate.containsKey(o); - } + @Override + public boolean containsKey(Object o) { + checkInit(); + return delegate.containsKey( o ); + } - public boolean containsValue(Object o) { - checkInit(); - return delegate.containsValue(o); - } + @Override + public boolean containsValue(Object o) { + checkInit(); + return delegate.containsValue( o ); + } - public V get(Object o) { - checkInit(); - return delegate.get(o); - } + @Override + public V get(Object o) { + checkInit(); + return delegate.get( o ); + } - public V put(K k, V v) { - checkInit(); - return delegate.put(k, v); - } + @Override + public V put(K k, V v) { + checkInit(); + return delegate.put( k, v ); + } - public V remove(Object o) { - checkInit(); - return delegate.remove(o); - } + @Override + public V remove(Object o) { + checkInit(); + return delegate.remove( o ); + } - public void putAll(Map map) { - checkInit(); - delegate.putAll(map); - } + @Override + public void putAll(Map map) { + checkInit(); + delegate.putAll( map ); + } - public void clear() { - checkInit(); - delegate.clear(); - } + @Override + public void clear() { + checkInit(); + delegate.clear(); + } - public Set keySet() { - checkInit(); - return delegate.keySet(); - } + @Override + public Set keySet() { + checkInit(); + return delegate.keySet(); + } - public Collection values() { - checkInit(); - return delegate.values(); - } + @Override + public Collection values() { + checkInit(); + return delegate.values(); + } - public Set> entrySet() { - checkInit(); - return delegate.entrySet(); - } + @Override + public Set> entrySet() { + checkInit(); + return delegate.entrySet(); + } - @Override - public String toString() { - checkInit(); - return delegate.toString(); - } + @Override + public String toString() { + checkInit(); + return delegate.toString(); + } - @SuppressWarnings({"EqualsWhichDoesntCheckParameterClass"}) - @Override - public boolean equals(Object obj) { - checkInit(); - return delegate.equals(obj); - } + @Override + @SuppressWarnings({"EqualsWhichDoesntCheckParameterClass"}) + public boolean equals(Object obj) { + checkInit(); + return delegate.equals( obj ); + } - @Override - public int hashCode() { - checkInit(); - return delegate.hashCode(); - } + @Override + public int hashCode() { + checkInit(); + return delegate.hashCode(); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/SetProxy.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/SetProxy.java index e57473b887..ae7648a10c 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/SetProxy.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/SetProxy.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,18 +22,19 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation.lazy.proxy; + import java.util.Set; /** * @author Adam Warski (adam at warski dot org) */ public class SetProxy extends CollectionProxy> implements Set { - private static final long serialVersionUID = 131464133074137701L; + private static final long serialVersionUID = 131464133074137701L; - public SetProxy() { - } + public SetProxy() { + } - public SetProxy(org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor.Initializor> initializor) { - super(initializor); - } + public SetProxy(org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor.Initializor> initializor) { + super( initializor ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/SortedMapProxy.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/SortedMapProxy.java index 51a199125f..25e8c19f84 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/SortedMapProxy.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/SortedMapProxy.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation.lazy.proxy; + import java.io.Serializable; import java.util.Collection; import java.util.Comparator; @@ -35,122 +36,142 @@ import org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor.I * @author Adam Warski (adam at warski dot org) */ public class SortedMapProxy implements SortedMap, Serializable { - private static final long serialVersionUID = 2645817952901452375L; + private static final long serialVersionUID = 2645817952901452375L; - private transient Initializor> initializor; - protected SortedMap delegate; + private transient Initializor> initializor; + protected SortedMap delegate; - public SortedMapProxy() { - } + public SortedMapProxy() { + } - public SortedMapProxy(org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor.Initializor> initializor) { - this.initializor = initializor; - } + public SortedMapProxy(org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor.Initializor> initializor) { + this.initializor = initializor; + } - private void checkInit() { - if (delegate == null) { - delegate = initializor.initialize(); - } - } + private void checkInit() { + if ( delegate == null ) { + delegate = initializor.initialize(); + } + } - public int size() { - checkInit(); - return delegate.size(); - } + @Override + public int size() { + checkInit(); + return delegate.size(); + } - public boolean isEmpty() { - checkInit(); - return delegate.isEmpty(); - } + @Override + public boolean isEmpty() { + checkInit(); + return delegate.isEmpty(); + } - public boolean containsKey(Object o) { - checkInit(); - return delegate.containsKey(o); - } + @Override + public boolean containsKey(Object o) { + checkInit(); + return delegate.containsKey( o ); + } - public boolean containsValue(Object o) { - checkInit(); - return delegate.containsValue(o); - } + @Override + public boolean containsValue(Object o) { + checkInit(); + return delegate.containsValue( o ); + } - public V get(Object o) { - checkInit(); - return delegate.get(o); - } + @Override + public V get(Object o) { + checkInit(); + return delegate.get( o ); + } - public V put(K k, V v) { - checkInit(); - return delegate.put(k, v); - } + @Override + public V put(K k, V v) { + checkInit(); + return delegate.put( k, v ); + } - public V remove(Object o) { - checkInit(); - return delegate.remove(o); - } + @Override + public V remove(Object o) { + checkInit(); + return delegate.remove( o ); + } - public void putAll(Map map) { - checkInit(); - delegate.putAll(map); - } + @Override + public void putAll(Map map) { + checkInit(); + delegate.putAll( map ); + } - public void clear() { - checkInit(); - delegate.clear(); - } + @Override + public void clear() { + checkInit(); + delegate.clear(); + } - public Set keySet() { - checkInit(); - return delegate.keySet(); - } + @Override + public Set keySet() { + checkInit(); + return delegate.keySet(); + } - public Collection values() { - checkInit(); - return delegate.values(); - } + @Override + public Collection values() { + checkInit(); + return delegate.values(); + } - public Set> entrySet() { - checkInit(); - return delegate.entrySet(); - } + @Override + public Set> entrySet() { + checkInit(); + return delegate.entrySet(); + } - public Comparator comparator() { - checkInit(); - return delegate.comparator(); - } + @Override + public Comparator comparator() { + checkInit(); + return delegate.comparator(); + } - public SortedMap subMap(K k, K k1) { - checkInit(); - return delegate.subMap(k, k1); - } + @Override + public SortedMap subMap(K k, K k1) { + checkInit(); + return delegate.subMap( k, k1 ); + } - public SortedMap headMap(K k) { - checkInit(); - return delegate.headMap(k); - } + @Override + public SortedMap headMap(K k) { + checkInit(); + return delegate.headMap( k ); + } - public SortedMap tailMap(K k) { - checkInit(); - return delegate.tailMap(k); - } + @Override + public SortedMap tailMap(K k) { + checkInit(); + return delegate.tailMap( k ); + } - public K firstKey() { - checkInit(); - return delegate.firstKey(); - } + @Override + public K firstKey() { + checkInit(); + return delegate.firstKey(); + } - public K lastKey() { - checkInit(); - return delegate.lastKey(); - } + @Override + public K lastKey() { + checkInit(); + return delegate.lastKey(); + } - @SuppressWarnings({"EqualsWhichDoesntCheckParameterClass"}) - public boolean equals(Object o) { - checkInit(); - return delegate.equals(o); - } + @Override + @SuppressWarnings({"EqualsWhichDoesntCheckParameterClass"}) + public boolean equals(Object o) { + checkInit(); + return delegate.equals( o ); + } - public int hashCode() { - checkInit(); - return delegate.hashCode(); - } + @Override + public int hashCode() { + checkInit(); + return delegate.hashCode(); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/SortedSetProxy.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/SortedSetProxy.java index 962a754094..3b189e2de6 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/SortedSetProxy.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/proxy/SortedSetProxy.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation.lazy.proxy; + import java.util.Comparator; import java.util.SortedSet; @@ -29,42 +30,48 @@ import java.util.SortedSet; * @author Adam Warski (adam at warski dot org) */ public class SortedSetProxy extends CollectionProxy> implements SortedSet { - private static final long serialVersionUID = 2092884107178125905L; + private static final long serialVersionUID = 2092884107178125905L; - public SortedSetProxy() { - } + public SortedSetProxy() { + } - public SortedSetProxy(org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor.Initializor> initializor) { - super(initializor); - } + public SortedSetProxy(org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor.Initializor> initializor) { + super( initializor ); + } - public Comparator comparator() { - checkInit(); - return delegate.comparator(); - } + @Override + public Comparator comparator() { + checkInit(); + return delegate.comparator(); + } - public SortedSet subSet(U u, U u1) { - checkInit(); - return delegate.subSet(u, u1); - } + @Override + public SortedSet subSet(U u, U u1) { + checkInit(); + return delegate.subSet( u, u1 ); + } - public SortedSet headSet(U u) { - checkInit(); - return delegate.headSet(u); - } + @Override + public SortedSet headSet(U u) { + checkInit(); + return delegate.headSet( u ); + } - public SortedSet tailSet(U u) { - checkInit(); - return delegate.tailSet(u); - } + @Override + public SortedSet tailSet(U u) { + checkInit(); + return delegate.tailSet( u ); + } - public U first() { - checkInit(); - return delegate.first(); - } + @Override + public U first() { + checkInit(); + return delegate.first(); + } - public U last() { - checkInit(); - return delegate.last(); - } + @Override + public U last() { + checkInit(); + return delegate.last(); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/AbstractRelationQueryGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/AbstractRelationQueryGenerator.java index 7c73f61b52..e30e4626f7 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/AbstractRelationQueryGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/AbstractRelationQueryGenerator.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -47,8 +47,9 @@ public abstract class AbstractRelationQueryGenerator implements RelationQueryGen protected final MiddleIdData referencingIdData; protected final boolean revisionTypeInId; - protected AbstractRelationQueryGenerator(AuditEntitiesConfiguration verEntCfg, MiddleIdData referencingIdData, - boolean revisionTypeInId) { + protected AbstractRelationQueryGenerator( + AuditEntitiesConfiguration verEntCfg, MiddleIdData referencingIdData, + boolean revisionTypeInId) { this.verEntCfg = verEntCfg; this.referencingIdData = referencingIdData; this.revisionTypeInId = revisionTypeInId; @@ -61,16 +62,19 @@ public abstract class AbstractRelationQueryGenerator implements RelationQueryGen /** * @return Query executed to retrieve state of audited entity valid at previous revision - * or removed during exactly specified revision number. Used only when traversing deleted - * entities graph. + * or removed during exactly specified revision number. Used only when traversing deleted + * entities graph. */ protected abstract String getQueryRemovedString(); + @Override public Query getQuery(AuditReaderImplementor versionsReader, Object primaryKey, Number revision, boolean removed) { - Query query = versionsReader.getSession().createQuery( removed ? getQueryRemovedString() : getQueryString() ); + final Query query = versionsReader.getSession().createQuery( removed ? getQueryRemovedString() : getQueryString() ); query.setParameter( DEL_REVISION_TYPE_PARAMETER, RevisionType.DEL ); query.setParameter( REVISION_PARAMETER, revision ); - for ( QueryParameterData paramData : referencingIdData.getPrefixedMapper().mapToQueryParametersFromId( primaryKey ) ) { + for ( QueryParameterData paramData : referencingIdData.getPrefixedMapper().mapToQueryParametersFromId( + primaryKey + ) ) { paramData.setParameterValue( query ); } return query; diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/OneAuditEntityQueryGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/OneAuditEntityQueryGenerator.java index 7fdab24325..87c54f2b5c 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/OneAuditEntityQueryGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/OneAuditEntityQueryGenerator.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -45,9 +45,10 @@ public final class OneAuditEntityQueryGenerator extends AbstractRelationQueryGen private final String queryString; private final String queryRemovedString; - public OneAuditEntityQueryGenerator(GlobalConfiguration globalCfg, AuditEntitiesConfiguration verEntCfg, - AuditStrategy auditStrategy, MiddleIdData referencingIdData, - String referencedEntityName, MiddleIdData referencedIdData, boolean revisionTypeInId) { + public OneAuditEntityQueryGenerator( + GlobalConfiguration globalCfg, AuditEntitiesConfiguration verEntCfg, + AuditStrategy auditStrategy, MiddleIdData referencingIdData, + String referencedEntityName, MiddleIdData referencedIdData, boolean revisionTypeInId) { super( verEntCfg, referencingIdData, revisionTypeInId ); /* @@ -96,9 +97,10 @@ public final class OneAuditEntityQueryGenerator extends AbstractRelationQueryGen /** * Creates query restrictions used to retrieve only actual data. */ - private void createValidDataRestrictions(GlobalConfiguration globalCfg, AuditStrategy auditStrategy, - MiddleIdData referencedIdData, QueryBuilder qb, Parameters rootParameters, - boolean inclusive) { + private void createValidDataRestrictions( + GlobalConfiguration globalCfg, AuditStrategy auditStrategy, + MiddleIdData referencedIdData, QueryBuilder qb, Parameters rootParameters, + boolean inclusive) { final String revisionPropertyPath = verEntCfg.getRevisionNumberPath(); // (selecting e entities at revision :revision) // --> based on auditStrategy (see above) @@ -115,11 +117,14 @@ public final class OneAuditEntityQueryGenerator extends AbstractRelationQueryGen /** * Create query restrictions used to retrieve actual data and deletions that took place at exactly given revision. */ - private void createValidAndRemovedDataRestrictions(GlobalConfiguration globalCfg, AuditStrategy auditStrategy, - MiddleIdData referencedIdData, QueryBuilder remQb) { + private void createValidAndRemovedDataRestrictions( + GlobalConfiguration globalCfg, AuditStrategy auditStrategy, + MiddleIdData referencedIdData, QueryBuilder remQb) { final Parameters disjoint = remQb.getRootParameters().addSubParameters( "or" ); - final Parameters valid = disjoint.addSubParameters( "and" ); // Restrictions to match all valid rows. - final Parameters removed = disjoint.addSubParameters( "and" ); // Restrictions to match all rows deleted at exactly given revision. + // Restrictions to match all valid rows. + final Parameters valid = disjoint.addSubParameters( "and" ); + // Restrictions to match all rows deleted at exactly given revision. + final Parameters removed = disjoint.addSubParameters( "and" ); // Excluding current revision, because we need to match data valid at the previous one. createValidDataRestrictions( globalCfg, auditStrategy, referencedIdData, remQb, valid, false ); // e.revision = :revision diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/OneEntityQueryGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/OneEntityQueryGenerator.java index 66575b2bf2..63402f0511 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/OneEntityQueryGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/OneEntityQueryGenerator.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -44,9 +44,10 @@ public final class OneEntityQueryGenerator extends AbstractRelationQueryGenerato private final String queryString; private final String queryRemovedString; - public OneEntityQueryGenerator(AuditEntitiesConfiguration verEntCfg, AuditStrategy auditStrategy, - String versionsMiddleEntityName, MiddleIdData referencingIdData, - boolean revisionTypeInId, MiddleComponentData... componentData) { + public OneEntityQueryGenerator( + AuditEntitiesConfiguration verEntCfg, AuditStrategy auditStrategy, + String versionsMiddleEntityName, MiddleIdData referencingIdData, + boolean revisionTypeInId, MiddleComponentData... componentData) { super( verEntCfg, referencingIdData, revisionTypeInId ); /* @@ -89,16 +90,21 @@ public final class OneEntityQueryGenerator extends AbstractRelationQueryGenerato qb.addProjection( null, MIDDLE_ENTITY_ALIAS, false, false ); // WHERE // ee.originalId.id_ref_ing = :id_ref_ing - referencingIdData.getPrefixedMapper().addNamedIdEqualsToQuery( qb.getRootParameters(), verEntCfg.getOriginalIdPropName(), true ); + referencingIdData.getPrefixedMapper().addNamedIdEqualsToQuery( + qb.getRootParameters(), + verEntCfg.getOriginalIdPropName(), + true + ); return qb; } /** * Creates query restrictions used to retrieve only actual data. */ - private void createValidDataRestrictions(AuditStrategy auditStrategy, String versionsMiddleEntityName, - QueryBuilder qb, Parameters rootParameters, boolean inclusive, - MiddleComponentData... componentData) { + private void createValidDataRestrictions( + AuditStrategy auditStrategy, String versionsMiddleEntityName, + QueryBuilder qb, Parameters rootParameters, boolean inclusive, + MiddleComponentData... componentData) { final String revisionPropertyPath = verEntCfg.getRevisionNumberPath(); final String originalIdPropertyName = verEntCfg.getOriginalIdPropName(); final String eeOriginalIdPropertyPath = MIDDLE_ENTITY_ALIAS + "." + originalIdPropertyName; @@ -116,11 +122,14 @@ public final class OneEntityQueryGenerator extends AbstractRelationQueryGenerato /** * Create query restrictions used to retrieve actual data and deletions that took place at exactly given revision. */ - private void createValidAndRemovedDataRestrictions(AuditStrategy auditStrategy, String versionsMiddleEntityName, - QueryBuilder remQb, MiddleComponentData... componentData) { + private void createValidAndRemovedDataRestrictions( + AuditStrategy auditStrategy, String versionsMiddleEntityName, + QueryBuilder remQb, MiddleComponentData... componentData) { final Parameters disjoint = remQb.getRootParameters().addSubParameters( "or" ); - final Parameters valid = disjoint.addSubParameters( "and" ); // Restrictions to match all valid rows. - final Parameters removed = disjoint.addSubParameters( "and" ); // Restrictions to match all rows deleted at exactly given revision. + // Restrictions to match all valid rows. + final Parameters valid = disjoint.addSubParameters( "and" ); + // Restrictions to match all rows deleted at exactly given revision. + final Parameters removed = disjoint.addSubParameters( "and" ); // Excluding current revision, because we need to match data valid at the previous one. createValidDataRestrictions( auditStrategy, versionsMiddleEntityName, remQb, valid, false, componentData ); // ee.revision = :revision diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/QueryConstants.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/QueryConstants.java index bb01740dd4..086bfc2e1f 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/QueryConstants.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/QueryConstants.java @@ -1,20 +1,43 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.internal.entities.mapper.relation.query; /** * Constants used in JPQL queries. - * + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class QueryConstants { - public static final String REFERENCED_ENTITY_ALIAS = "e__"; - public static final String REFERENCED_ENTITY_ALIAS_DEF_AUD_STR = "e2__"; + public static final String REFERENCED_ENTITY_ALIAS = "e__"; + public static final String REFERENCED_ENTITY_ALIAS_DEF_AUD_STR = "e2__"; - public static final String INDEX_ENTITY_ALIAS = "f__"; - public static final String INDEX_ENTITY_ALIAS_DEF_AUD_STR = "f2__"; + public static final String INDEX_ENTITY_ALIAS = "f__"; + public static final String INDEX_ENTITY_ALIAS_DEF_AUD_STR = "f2__"; - public static final String MIDDLE_ENTITY_ALIAS = "ee__"; - public static final String MIDDLE_ENTITY_ALIAS_DEF_AUD_STR = "ee2__"; + public static final String MIDDLE_ENTITY_ALIAS = "ee__"; + public static final String MIDDLE_ENTITY_ALIAS_DEF_AUD_STR = "ee2__"; - public static final String REVISION_PARAMETER = "revision"; - public static final String DEL_REVISION_TYPE_PARAMETER = "delrevisiontype"; + public static final String REVISION_PARAMETER = "revision"; + public static final String DEL_REVISION_TYPE_PARAMETER = "delrevisiontype"; } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/RelationQueryGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/RelationQueryGenerator.java index c65e8c90f1..191595c8be 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/RelationQueryGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/RelationQueryGenerator.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,17 +22,19 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.entities.mapper.relation.query; + import org.hibernate.Query; import org.hibernate.envers.internal.reader.AuditReaderImplementor; /** * TODO: cleanup implementations and extract common code - * + *

      * Implementations of this interface provide a method to generate queries on a relation table (a table used * for mapping relations). The query can select, apart from selecting the content of the relation table, also data of * other "related" entities. + * * @author Adam Warski (adam at warski dot org) */ public interface RelationQueryGenerator { - Query getQuery(AuditReaderImplementor versionsReader, Object primaryKey, Number revision, boolean removed); + Query getQuery(AuditReaderImplementor versionsReader, Object primaryKey, Number revision, boolean removed); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/ThreeEntityQueryGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/ThreeEntityQueryGenerator.java index c548031531..5d374b8f54 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/ThreeEntityQueryGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/ThreeEntityQueryGenerator.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -49,11 +49,12 @@ public final class ThreeEntityQueryGenerator extends AbstractRelationQueryGenera private final String queryString; private final String queryRemovedString; - public ThreeEntityQueryGenerator(GlobalConfiguration globalCfg, AuditEntitiesConfiguration verEntCfg, - AuditStrategy auditStrategy, String versionsMiddleEntityName, - MiddleIdData referencingIdData, MiddleIdData referencedIdData, - MiddleIdData indexIdData, boolean revisionTypeInId, - MiddleComponentData... componentData) { + public ThreeEntityQueryGenerator( + GlobalConfiguration globalCfg, AuditEntitiesConfiguration verEntCfg, + AuditStrategy auditStrategy, String versionsMiddleEntityName, + MiddleIdData referencingIdData, MiddleIdData referencedIdData, + MiddleIdData indexIdData, boolean revisionTypeInId, + MiddleComponentData... componentData) { super( verEntCfg, referencingIdData, revisionTypeInId ); /* @@ -102,7 +103,12 @@ public final class ThreeEntityQueryGenerator extends AbstractRelationQueryGenera * e.revision_type != DEL AND * f.revision_type != DEL */ - final QueryBuilder commonPart = commonQueryPart( referencedIdData, indexIdData, versionsMiddleEntityName, verEntCfg.getOriginalIdPropName() ); + final QueryBuilder commonPart = commonQueryPart( + referencedIdData, + indexIdData, + versionsMiddleEntityName, + verEntCfg.getOriginalIdPropName() + ); final QueryBuilder validQuery = commonPart.deepCopy(); final QueryBuilder removedQuery = commonPart.deepCopy(); createValidDataRestrictions( @@ -120,8 +126,9 @@ public final class ThreeEntityQueryGenerator extends AbstractRelationQueryGenera /** * Compute common part for both queries. */ - private QueryBuilder commonQueryPart(MiddleIdData referencedIdData, MiddleIdData indexIdData, - String versionsMiddleEntityName, String originalIdPropertyName) { + private QueryBuilder commonQueryPart( + MiddleIdData referencedIdData, MiddleIdData indexIdData, + String versionsMiddleEntityName, String originalIdPropertyName) { final String eeOriginalIdPropertyPath = MIDDLE_ENTITY_ALIAS + "." + originalIdPropertyName; // SELECT new list(ee) FROM middleEntity ee final QueryBuilder qb = new QueryBuilder( versionsMiddleEntityName, MIDDLE_ENTITY_ALIAS ); @@ -151,9 +158,10 @@ public final class ThreeEntityQueryGenerator extends AbstractRelationQueryGenera /** * Creates query restrictions used to retrieve only actual data. */ - private void createValidDataRestrictions(GlobalConfiguration globalCfg, AuditStrategy auditStrategy, - MiddleIdData referencedIdData, String versionsMiddleEntityName, QueryBuilder qb, - Parameters rootParameters, boolean inclusive, MiddleComponentData... componentData) { + private void createValidDataRestrictions( + GlobalConfiguration globalCfg, AuditStrategy auditStrategy, + MiddleIdData referencedIdData, String versionsMiddleEntityName, QueryBuilder qb, + Parameters rootParameters, boolean inclusive, MiddleComponentData... componentData) { final String revisionPropertyPath = verEntCfg.getRevisionNumberPath(); final String originalIdPropertyName = verEntCfg.getOriginalIdPropName(); final String eeOriginalIdPropertyPath = MIDDLE_ENTITY_ALIAS + "." + originalIdPropertyName; @@ -161,16 +169,34 @@ public final class ThreeEntityQueryGenerator extends AbstractRelationQueryGenera // (selecting e entities at revision :revision) // --> based on auditStrategy (see above) auditStrategy.addEntityAtRevisionRestriction( - globalCfg, qb, rootParameters, REFERENCED_ENTITY_ALIAS + "." + revisionPropertyPath, - REFERENCED_ENTITY_ALIAS + "." + verEntCfg.getRevisionEndFieldName(), false, referencedIdData, revisionPropertyPath, - originalIdPropertyName, REFERENCED_ENTITY_ALIAS, REFERENCED_ENTITY_ALIAS_DEF_AUD_STR, inclusive + globalCfg, + qb, + rootParameters, + REFERENCED_ENTITY_ALIAS + "." + revisionPropertyPath, + REFERENCED_ENTITY_ALIAS + "." + verEntCfg.getRevisionEndFieldName(), + false, + referencedIdData, + revisionPropertyPath, + originalIdPropertyName, + REFERENCED_ENTITY_ALIAS, + REFERENCED_ENTITY_ALIAS_DEF_AUD_STR, + inclusive ); // (selecting f entities at revision :revision) // --> based on auditStrategy (see above) auditStrategy.addEntityAtRevisionRestriction( - globalCfg, qb, rootParameters, REFERENCED_ENTITY_ALIAS + "." + revisionPropertyPath, - REFERENCED_ENTITY_ALIAS + "." + verEntCfg.getRevisionEndFieldName(), false, referencedIdData, revisionPropertyPath, - originalIdPropertyName, INDEX_ENTITY_ALIAS, INDEX_ENTITY_ALIAS_DEF_AUD_STR, inclusive + globalCfg, + qb, + rootParameters, + REFERENCED_ENTITY_ALIAS + "." + revisionPropertyPath, + REFERENCED_ENTITY_ALIAS + "." + verEntCfg.getRevisionEndFieldName(), + false, + referencedIdData, + revisionPropertyPath, + originalIdPropertyName, + INDEX_ENTITY_ALIAS, + INDEX_ENTITY_ALIAS_DEF_AUD_STR, + inclusive ); // (with ee association at revision :revision) // --> based on auditStrategy (see above) @@ -182,20 +208,33 @@ public final class ThreeEntityQueryGenerator extends AbstractRelationQueryGenera // ee.revision_type != DEL rootParameters.addWhereWithNamedParam( revisionTypePropName, "!=", DEL_REVISION_TYPE_PARAMETER ); // e.revision_type != DEL - rootParameters.addWhereWithNamedParam( REFERENCED_ENTITY_ALIAS + "." + revisionTypePropName, false, "!=", DEL_REVISION_TYPE_PARAMETER ); + rootParameters.addWhereWithNamedParam( + REFERENCED_ENTITY_ALIAS + "." + revisionTypePropName, + false, + "!=", + DEL_REVISION_TYPE_PARAMETER + ); // f.revision_type != DEL - rootParameters.addWhereWithNamedParam( INDEX_ENTITY_ALIAS + "." + revisionTypePropName, false, "!=", DEL_REVISION_TYPE_PARAMETER ); + rootParameters.addWhereWithNamedParam( + INDEX_ENTITY_ALIAS + "." + revisionTypePropName, + false, + "!=", + DEL_REVISION_TYPE_PARAMETER + ); } /** * Create query restrictions used to retrieve actual data and deletions that took place at exactly given revision. */ - private void createValidAndRemovedDataRestrictions(GlobalConfiguration globalCfg, AuditStrategy auditStrategy, - MiddleIdData referencedIdData, String versionsMiddleEntityName, - QueryBuilder remQb, MiddleComponentData... componentData) { + private void createValidAndRemovedDataRestrictions( + GlobalConfiguration globalCfg, AuditStrategy auditStrategy, + MiddleIdData referencedIdData, String versionsMiddleEntityName, + QueryBuilder remQb, MiddleComponentData... componentData) { final Parameters disjoint = remQb.getRootParameters().addSubParameters( "or" ); - final Parameters valid = disjoint.addSubParameters( "and" ); // Restrictions to match all valid rows. - final Parameters removed = disjoint.addSubParameters( "and" ); // Restrictions to match all rows deleted at exactly given revision. + // Restrictions to match all valid rows. + final Parameters valid = disjoint.addSubParameters( "and" ); + // Restrictions to match all rows deleted at exactly given revision. + final Parameters removed = disjoint.addSubParameters( "and" ); final String revisionPropertyPath = verEntCfg.getRevisionNumberPath(); final String revisionTypePropName = getRevisionTypePath(); // Excluding current revision, because we need to match data valid at the previous one. @@ -205,15 +244,35 @@ public final class ThreeEntityQueryGenerator extends AbstractRelationQueryGenera // ee.revision = :revision removed.addWhereWithNamedParam( revisionPropertyPath, "=", REVISION_PARAMETER ); // e.revision = :revision - removed.addWhereWithNamedParam( REFERENCED_ENTITY_ALIAS + "." + revisionPropertyPath, false, "=", REVISION_PARAMETER ); + removed.addWhereWithNamedParam( + REFERENCED_ENTITY_ALIAS + "." + revisionPropertyPath, + false, + "=", + REVISION_PARAMETER + ); // f.revision = :revision - removed.addWhereWithNamedParam( INDEX_ENTITY_ALIAS + "." + revisionPropertyPath, false, "=", REVISION_PARAMETER ); + removed.addWhereWithNamedParam( + INDEX_ENTITY_ALIAS + "." + revisionPropertyPath, + false, + "=", + REVISION_PARAMETER + ); // ee.revision_type = DEL removed.addWhereWithNamedParam( revisionTypePropName, "=", DEL_REVISION_TYPE_PARAMETER ); // e.revision_type = DEL - removed.addWhereWithNamedParam( REFERENCED_ENTITY_ALIAS + "." + revisionTypePropName, false, "=", DEL_REVISION_TYPE_PARAMETER ); + removed.addWhereWithNamedParam( + REFERENCED_ENTITY_ALIAS + "." + revisionTypePropName, + false, + "=", + DEL_REVISION_TYPE_PARAMETER + ); // f.revision_type = DEL - removed.addWhereWithNamedParam( INDEX_ENTITY_ALIAS + "." + revisionTypePropName, false, "=", DEL_REVISION_TYPE_PARAMETER ); + removed.addWhereWithNamedParam( + INDEX_ENTITY_ALIAS + "." + revisionTypePropName, + false, + "=", + DEL_REVISION_TYPE_PARAMETER + ); } @Override diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/TwoEntityOneAuditedQueryGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/TwoEntityOneAuditedQueryGenerator.java index 23c26e92c5..065239c0cd 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/TwoEntityOneAuditedQueryGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/TwoEntityOneAuditedQueryGenerator.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -45,10 +45,11 @@ public final class TwoEntityOneAuditedQueryGenerator extends AbstractRelationQue private final String queryString; private final String queryRemovedString; - public TwoEntityOneAuditedQueryGenerator(AuditEntitiesConfiguration verEntCfg, AuditStrategy auditStrategy, - String versionsMiddleEntityName, MiddleIdData referencingIdData, - MiddleIdData referencedIdData, boolean revisionTypeInId, - MiddleComponentData... componentData) { + public TwoEntityOneAuditedQueryGenerator( + AuditEntitiesConfiguration verEntCfg, AuditStrategy auditStrategy, + String versionsMiddleEntityName, MiddleIdData referencingIdData, + MiddleIdData referencedIdData, boolean revisionTypeInId, + MiddleComponentData... componentData) { super( verEntCfg, referencingIdData, revisionTypeInId ); /* @@ -73,7 +74,11 @@ public final class TwoEntityOneAuditedQueryGenerator extends AbstractRelationQue * (only non-deleted entities and associations) * ee.revision_type != DEL */ - final QueryBuilder commonPart = commonQueryPart( referencedIdData, versionsMiddleEntityName, verEntCfg.getOriginalIdPropName() ); + final QueryBuilder commonPart = commonQueryPart( + referencedIdData, + versionsMiddleEntityName, + verEntCfg.getOriginalIdPropName() + ); final QueryBuilder validQuery = commonPart.deepCopy(); final QueryBuilder removedQuery = commonPart.deepCopy(); createValidDataRestrictions( @@ -88,8 +93,9 @@ public final class TwoEntityOneAuditedQueryGenerator extends AbstractRelationQue /** * Compute common part for both queries. */ - private QueryBuilder commonQueryPart(MiddleIdData referencedIdData, String versionsMiddleEntityName, - String originalIdPropertyName) { + private QueryBuilder commonQueryPart( + MiddleIdData referencedIdData, String versionsMiddleEntityName, + String originalIdPropertyName) { final String eeOriginalIdPropertyPath = MIDDLE_ENTITY_ALIAS + "." + originalIdPropertyName; // SELECT new list(ee) FROM middleEntity ee final QueryBuilder qb = new QueryBuilder( versionsMiddleEntityName, MIDDLE_ENTITY_ALIAS ); @@ -109,8 +115,9 @@ public final class TwoEntityOneAuditedQueryGenerator extends AbstractRelationQue /** * Creates query restrictions used to retrieve only actual data. */ - private void createValidDataRestrictions(AuditStrategy auditStrategy, String versionsMiddleEntityName, QueryBuilder qb, - Parameters rootParameters, MiddleComponentData... componentData) { + private void createValidDataRestrictions( + AuditStrategy auditStrategy, String versionsMiddleEntityName, QueryBuilder qb, + Parameters rootParameters, MiddleComponentData... componentData) { final String revisionPropertyPath = verEntCfg.getRevisionNumberPath(); final String originalIdPropertyName = verEntCfg.getOriginalIdPropName(); final String eeOriginalIdPropertyPath = MIDDLE_ENTITY_ALIAS + "." + originalIdPropertyName; @@ -128,11 +135,14 @@ public final class TwoEntityOneAuditedQueryGenerator extends AbstractRelationQue /** * Create query restrictions used to retrieve actual data and deletions that took place at exactly given revision. */ - private void createValidAndRemovedDataRestrictions(AuditStrategy auditStrategy, String versionsMiddleEntityName, - QueryBuilder remQb, MiddleComponentData... componentData) { + private void createValidAndRemovedDataRestrictions( + AuditStrategy auditStrategy, String versionsMiddleEntityName, + QueryBuilder remQb, MiddleComponentData... componentData) { final Parameters disjoint = remQb.getRootParameters().addSubParameters( "or" ); - final Parameters valid = disjoint.addSubParameters( "and" ); // Restrictions to match all valid rows. - final Parameters removed = disjoint.addSubParameters( "and" ); // Restrictions to match all rows deleted at exactly given revision. + // Restrictions to match all valid rows. + final Parameters valid = disjoint.addSubParameters( "and" ); + // Restrictions to match all rows deleted at exactly given revision. + final Parameters removed = disjoint.addSubParameters( "and" ); createValidDataRestrictions( auditStrategy, versionsMiddleEntityName, remQb, valid, componentData ); // ee.revision = :revision removed.addWhereWithNamedParam( verEntCfg.getRevisionNumberPath(), "=", REVISION_PARAMETER ); diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/TwoEntityQueryGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/TwoEntityQueryGenerator.java index 2fc6cbec2b..21ea05cb48 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/TwoEntityQueryGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/query/TwoEntityQueryGenerator.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -47,10 +47,11 @@ public final class TwoEntityQueryGenerator extends AbstractRelationQueryGenerato private final String queryString; private final String queryRemovedString; - public TwoEntityQueryGenerator(GlobalConfiguration globalCfg, AuditEntitiesConfiguration verEntCfg, - AuditStrategy auditStrategy, String versionsMiddleEntityName, - MiddleIdData referencingIdData, MiddleIdData referencedIdData, - boolean revisionTypeInId, MiddleComponentData... componentData) { + public TwoEntityQueryGenerator( + GlobalConfiguration globalCfg, AuditEntitiesConfiguration verEntCfg, + AuditStrategy auditStrategy, String versionsMiddleEntityName, + MiddleIdData referencingIdData, MiddleIdData referencedIdData, + boolean revisionTypeInId, MiddleComponentData... componentData) { super( verEntCfg, referencingIdData, revisionTypeInId ); /* @@ -84,7 +85,11 @@ public final class TwoEntityQueryGenerator extends AbstractRelationQueryGenerato * ee.revision_type != DEL AND * e.revision_type != DEL */ - final QueryBuilder commonPart = commonQueryPart( referencedIdData, versionsMiddleEntityName, verEntCfg.getOriginalIdPropName() ); + final QueryBuilder commonPart = commonQueryPart( + referencedIdData, + versionsMiddleEntityName, + verEntCfg.getOriginalIdPropName() + ); final QueryBuilder validQuery = commonPart.deepCopy(); final QueryBuilder removedQuery = commonPart.deepCopy(); createValidDataRestrictions( @@ -102,8 +107,9 @@ public final class TwoEntityQueryGenerator extends AbstractRelationQueryGenerato /** * Compute common part for both queries. */ - private QueryBuilder commonQueryPart(MiddleIdData referencedIdData, String versionsMiddleEntityName, - String originalIdPropertyName) { + private QueryBuilder commonQueryPart( + MiddleIdData referencedIdData, String versionsMiddleEntityName, + String originalIdPropertyName) { final String eeOriginalIdPropertyPath = MIDDLE_ENTITY_ALIAS + "." + originalIdPropertyName; // SELECT new list(ee) FROM middleEntity ee QueryBuilder qb = new QueryBuilder( versionsMiddleEntityName, MIDDLE_ENTITY_ALIAS ); @@ -124,9 +130,10 @@ public final class TwoEntityQueryGenerator extends AbstractRelationQueryGenerato /** * Creates query restrictions used to retrieve only actual data. */ - private void createValidDataRestrictions(GlobalConfiguration globalCfg, AuditStrategy auditStrategy, MiddleIdData referencedIdData, - String versionsMiddleEntityName, QueryBuilder qb, Parameters rootParameters, - boolean inclusive, MiddleComponentData... componentData) { + private void createValidDataRestrictions( + GlobalConfiguration globalCfg, AuditStrategy auditStrategy, MiddleIdData referencedIdData, + String versionsMiddleEntityName, QueryBuilder qb, Parameters rootParameters, + boolean inclusive, MiddleComponentData... componentData) { final String revisionPropertyPath = verEntCfg.getRevisionNumberPath(); final String originalIdPropertyName = verEntCfg.getOriginalIdPropName(); final String eeOriginalIdPropertyPath = MIDDLE_ENTITY_ALIAS + "." + originalIdPropertyName; @@ -134,13 +141,23 @@ public final class TwoEntityQueryGenerator extends AbstractRelationQueryGenerato // (selecting e entities at revision :revision) // --> based on auditStrategy (see above) auditStrategy.addEntityAtRevisionRestriction( - globalCfg, qb, rootParameters, REFERENCED_ENTITY_ALIAS + "." + revisionPropertyPath, - REFERENCED_ENTITY_ALIAS + "." + verEntCfg.getRevisionEndFieldName(), false, referencedIdData, revisionPropertyPath, - originalIdPropertyName, REFERENCED_ENTITY_ALIAS, REFERENCED_ENTITY_ALIAS_DEF_AUD_STR, inclusive + globalCfg, + qb, + rootParameters, + REFERENCED_ENTITY_ALIAS + "." + revisionPropertyPath, + REFERENCED_ENTITY_ALIAS + "." + verEntCfg.getRevisionEndFieldName(), + false, + referencedIdData, + revisionPropertyPath, + originalIdPropertyName, + REFERENCED_ENTITY_ALIAS, + REFERENCED_ENTITY_ALIAS_DEF_AUD_STR, + inclusive ); // (with ee association at revision :revision) // --> based on auditStrategy (see above) - auditStrategy.addAssociationAtRevisionRestriction( qb, rootParameters, revisionPropertyPath, + auditStrategy.addAssociationAtRevisionRestriction( + qb, rootParameters, revisionPropertyPath, verEntCfg.getRevisionEndFieldName(), true, referencingIdData, versionsMiddleEntityName, eeOriginalIdPropertyPath, revisionPropertyPath, originalIdPropertyName, MIDDLE_ENTITY_ALIAS, inclusive, componentData @@ -148,30 +165,57 @@ public final class TwoEntityQueryGenerator extends AbstractRelationQueryGenerato // ee.revision_type != DEL rootParameters.addWhereWithNamedParam( revisionTypePropName, "!=", DEL_REVISION_TYPE_PARAMETER ); // e.revision_type != DEL - rootParameters.addWhereWithNamedParam( REFERENCED_ENTITY_ALIAS + "." + revisionTypePropName, false, "!=", DEL_REVISION_TYPE_PARAMETER ); + rootParameters.addWhereWithNamedParam( + REFERENCED_ENTITY_ALIAS + "." + revisionTypePropName, + false, + "!=", + DEL_REVISION_TYPE_PARAMETER + ); } /** * Create query restrictions used to retrieve actual data and deletions that took place at exactly given revision. */ - private void createValidAndRemovedDataRestrictions(GlobalConfiguration globalCfg, AuditStrategy auditStrategy, - MiddleIdData referencedIdData, String versionsMiddleEntityName, - QueryBuilder remQb, MiddleComponentData... componentData) { + private void createValidAndRemovedDataRestrictions( + GlobalConfiguration globalCfg, AuditStrategy auditStrategy, + MiddleIdData referencedIdData, String versionsMiddleEntityName, + QueryBuilder remQb, MiddleComponentData... componentData) { final Parameters disjoint = remQb.getRootParameters().addSubParameters( "or" ); - final Parameters valid = disjoint.addSubParameters( "and" ); // Restrictions to match all valid rows. - final Parameters removed = disjoint.addSubParameters( "and" ); // Restrictions to match all rows deleted at exactly given revision. + // Restrictions to match all valid rows. + final Parameters valid = disjoint.addSubParameters( "and" ); + // Restrictions to match all rows deleted at exactly given revision. + final Parameters removed = disjoint.addSubParameters( "and" ); final String revisionPropertyPath = verEntCfg.getRevisionNumberPath(); final String revisionTypePropName = getRevisionTypePath(); // Excluding current revision, because we need to match data valid at the previous one. - createValidDataRestrictions( globalCfg, auditStrategy, referencedIdData, versionsMiddleEntityName, remQb, valid, false, componentData ); + createValidDataRestrictions( + globalCfg, + auditStrategy, + referencedIdData, + versionsMiddleEntityName, + remQb, + valid, + false, + componentData + ); // ee.revision = :revision removed.addWhereWithNamedParam( revisionPropertyPath, "=", REVISION_PARAMETER ); // e.revision = :revision - removed.addWhereWithNamedParam( REFERENCED_ENTITY_ALIAS + "." + revisionPropertyPath, false, "=", REVISION_PARAMETER ); + removed.addWhereWithNamedParam( + REFERENCED_ENTITY_ALIAS + "." + revisionPropertyPath, + false, + "=", + REVISION_PARAMETER + ); // ee.revision_type = DEL removed.addWhereWithNamedParam( revisionTypePropName, "=", DEL_REVISION_TYPE_PARAMETER ); // e.revision_type = DEL - removed.addWhereWithNamedParam( REFERENCED_ENTITY_ALIAS + "." + revisionTypePropName, false, "=", DEL_REVISION_TYPE_PARAMETER ); + removed.addWhereWithNamedParam( + REFERENCED_ENTITY_ALIAS + "." + revisionTypePropName, + false, + "=", + DEL_REVISION_TYPE_PARAMETER + ); } @Override diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/AuditReaderImpl.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/AuditReaderImpl.java index 7a64945109..5ae1cc4e4f 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/AuditReaderImpl.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/AuditReaderImpl.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -23,13 +23,13 @@ */ package org.hibernate.envers.internal.reader; +import javax.persistence.NoResultException; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import javax.persistence.NoResultException; import org.hibernate.Criteria; import org.hibernate.HibernateException; @@ -57,260 +57,292 @@ import static org.hibernate.envers.internal.tools.EntityTools.getTargetClassIfPr * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class AuditReaderImpl implements AuditReaderImplementor { - private final AuditConfiguration verCfg; - private final SessionImplementor sessionImplementor; - private final Session session; - private final FirstLevelCache firstLevelCache; - private final CrossTypeRevisionChangesReader crossTypeRevisionChangesReader; + private final AuditConfiguration verCfg; + private final SessionImplementor sessionImplementor; + private final Session session; + private final FirstLevelCache firstLevelCache; + private final CrossTypeRevisionChangesReader crossTypeRevisionChangesReader; - public AuditReaderImpl(AuditConfiguration verCfg, Session session, - SessionImplementor sessionImplementor) { - this.verCfg = verCfg; - this.sessionImplementor = sessionImplementor; - this.session = session; + public AuditReaderImpl( + AuditConfiguration verCfg, Session session, + SessionImplementor sessionImplementor) { + this.verCfg = verCfg; + this.sessionImplementor = sessionImplementor; + this.session = session; - firstLevelCache = new FirstLevelCache(); - crossTypeRevisionChangesReader = new CrossTypeRevisionChangesReaderImpl(this, verCfg); - } + firstLevelCache = new FirstLevelCache(); + crossTypeRevisionChangesReader = new CrossTypeRevisionChangesReaderImpl( this, verCfg ); + } - private void checkSession() { - if (!session.isOpen()) { - throw new IllegalStateException("The associated entity manager is closed!"); - } - } - - public SessionImplementor getSessionImplementor() { - return sessionImplementor; - } - - public Session getSession() { - return session; - } - - public FirstLevelCache getFirstLevelCache() { - return firstLevelCache; - } - - public T find(Class cls, Object primaryKey, Number revision) throws - IllegalArgumentException, NotAuditedException, IllegalStateException { - cls = getTargetClassIfProxied(cls); - return this.find(cls, cls.getName(), primaryKey, revision); - } - - public T find(Class cls, String entityName, Object primaryKey, Number revision) - throws IllegalArgumentException, NotAuditedException, IllegalStateException { - return this.find(cls, entityName, primaryKey, revision, false); - } - - @SuppressWarnings({"unchecked"}) - public T find(Class cls, String entityName, Object primaryKey, Number revision, - boolean includeDeletions) throws - IllegalArgumentException, NotAuditedException, IllegalStateException { - cls = getTargetClassIfProxied(cls); - checkNotNull(cls, "Entity class"); - checkNotNull(entityName, "Entity name"); - checkNotNull(primaryKey, "Primary key"); - checkNotNull(revision, "Entity revision"); - checkPositive(revision, "Entity revision"); - checkSession(); - - if (!verCfg.getEntCfg().isVersioned(entityName)) { - throw new NotAuditedException(entityName, entityName + " is not versioned!"); - } - - if (firstLevelCache.contains(entityName, revision, primaryKey)) { - return (T) firstLevelCache.get(entityName, revision, primaryKey); - } - - Object result; - try { - // The result is put into the cache by the entity instantiator called from the query - result = createQuery().forEntitiesAtRevision(cls, entityName, revision, includeDeletions) - .add(AuditEntity.id().eq(primaryKey)).getSingleResult(); - } catch (NoResultException e) { - result = null; - } catch (NonUniqueResultException e) { - throw new AuditException(e); - } - - return (T) result; - } - - public List getRevisions(Class cls, Object primaryKey) - throws IllegalArgumentException, NotAuditedException, IllegalStateException { - cls = getTargetClassIfProxied(cls); - return this.getRevisions(cls, cls.getName(), primaryKey); - } - - @SuppressWarnings({"unchecked"}) - public List getRevisions(Class cls, String entityName, Object primaryKey) - throws IllegalArgumentException, NotAuditedException, IllegalStateException { - // todo: if a class is not versioned from the beginning, there's a missing ADD rev - what then? - cls = getTargetClassIfProxied(cls); - checkNotNull(cls, "Entity class"); - checkNotNull(entityName, "Entity name"); - checkNotNull(primaryKey, "Primary key"); - checkSession(); - - if (!verCfg.getEntCfg().isVersioned(entityName)) { - throw new NotAuditedException(entityName, entityName + " is not versioned!"); - } - - return createQuery().forRevisionsOfEntity(cls, entityName, false, true) - .addProjection(AuditEntity.revisionNumber()) - .addOrder(AuditEntity.revisionNumber().asc()) - .add(AuditEntity.id().eq(primaryKey)) - .getResultList(); - } - - public Date getRevisionDate(Number revision) throws IllegalArgumentException, RevisionDoesNotExistException, - IllegalStateException{ - checkNotNull(revision, "Entity revision"); - checkPositive(revision, "Entity revision"); - checkSession(); - - Criteria query = verCfg.getRevisionInfoQueryCreator().getRevisionDateQuery(session, revision); - - try { - Object timestampObject = query.uniqueResult(); - if (timestampObject == null) { - throw new RevisionDoesNotExistException(revision); - } - - // The timestamp object is either a date or a long - return timestampObject instanceof Date ? (Date) timestampObject : new Date((Long) timestampObject); - } catch (NonUniqueResultException e) { - throw new AuditException(e); - } - } - - public Number getRevisionNumberForDate(Date date) { - checkNotNull(date, "Date of revision"); - checkSession(); - - Criteria query = verCfg.getRevisionInfoQueryCreator().getRevisionNumberForDateQuery(session, date); - - try { - Number res = (Number) query.uniqueResult(); - if (res == null) { - throw new RevisionDoesNotExistException(date); - } - - return res; - } catch (NonUniqueResultException e) { - throw new AuditException(e); - } - } - - @SuppressWarnings({"unchecked"}) - public T findRevision(Class revisionEntityClass, Number revision) throws IllegalArgumentException, - RevisionDoesNotExistException, IllegalStateException { - revisionEntityClass = getTargetClassIfProxied(revisionEntityClass); - checkNotNull(revision, "Entity revision"); - checkPositive(revision, "Entity revision"); - checkSession(); - - Set revisions = new HashSet(1); - revisions.add(revision); - Criteria query = verCfg.getRevisionInfoQueryCreator().getRevisionsQuery(session, revisions); - - try { - T revisionData = (T) query.uniqueResult(); - - if (revisionData == null) { - throw new RevisionDoesNotExistException(revision); - } - - return revisionData; - } catch (NonUniqueResultException e) { - throw new AuditException(e); - } - } - - @SuppressWarnings({"unchecked"}) - public Map findRevisions(Class revisionEntityClass, Set revisions) throws IllegalArgumentException, - IllegalStateException { - revisionEntityClass = getTargetClassIfProxied(revisionEntityClass); - Map result = new HashMap(revisions.size()); - - for (Number revision : revisions) { - checkNotNull(revision, "Entity revision"); - checkPositive(revision, "Entity revision"); + private void checkSession() { + if ( !session.isOpen() ) { + throw new IllegalStateException( "The associated entity manager is closed!" ); } - checkSession(); + } - Criteria query = verCfg.getRevisionInfoQueryCreator().getRevisionsQuery(session, revisions); + @Override + public SessionImplementor getSessionImplementor() { + return sessionImplementor; + } - try { - List revisionList = query.list(); - for (T revision : revisionList) { - Number revNo = verCfg.getRevisionInfoNumberReader().getRevisionNumber(revision); - result.put(revNo, revision); + @Override + public Session getSession() { + return session; + } + + @Override + public FirstLevelCache getFirstLevelCache() { + return firstLevelCache; + } + + @Override + public T find(Class cls, Object primaryKey, Number revision) throws + IllegalArgumentException, NotAuditedException, IllegalStateException { + cls = getTargetClassIfProxied( cls ); + return this.find( cls, cls.getName(), primaryKey, revision ); + } + + @Override + public T find(Class cls, String entityName, Object primaryKey, Number revision) + throws IllegalArgumentException, NotAuditedException, IllegalStateException { + return this.find( cls, entityName, primaryKey, revision, false ); + } + + @Override + @SuppressWarnings({"unchecked"}) + public T find( + Class cls, + String entityName, + Object primaryKey, + Number revision, + boolean includeDeletions) throws IllegalArgumentException, NotAuditedException, IllegalStateException { + cls = getTargetClassIfProxied( cls ); + checkNotNull( cls, "Entity class" ); + checkNotNull( entityName, "Entity name" ); + checkNotNull( primaryKey, "Primary key" ); + checkNotNull( revision, "Entity revision" ); + checkPositive( revision, "Entity revision" ); + checkSession(); + + if ( !verCfg.getEntCfg().isVersioned( entityName ) ) { + throw new NotAuditedException( entityName, entityName + " is not versioned!" ); + } + + if ( firstLevelCache.contains( entityName, revision, primaryKey ) ) { + return (T) firstLevelCache.get( entityName, revision, primaryKey ); + } + + Object result; + try { + // The result is put into the cache by the entity instantiator called from the query + result = createQuery().forEntitiesAtRevision( cls, entityName, revision, includeDeletions ) + .add( AuditEntity.id().eq( primaryKey ) ).getSingleResult(); + } + catch (NoResultException e) { + result = null; + } + catch (NonUniqueResultException e) { + throw new AuditException( e ); + } + + return (T) result; + } + + @Override + public List getRevisions(Class cls, Object primaryKey) + throws IllegalArgumentException, NotAuditedException, IllegalStateException { + cls = getTargetClassIfProxied( cls ); + return this.getRevisions( cls, cls.getName(), primaryKey ); + } + + @Override + @SuppressWarnings({"unchecked"}) + public List getRevisions(Class cls, String entityName, Object primaryKey) + throws IllegalArgumentException, NotAuditedException, IllegalStateException { + // todo: if a class is not versioned from the beginning, there's a missing ADD rev - what then? + cls = getTargetClassIfProxied( cls ); + checkNotNull( cls, "Entity class" ); + checkNotNull( entityName, "Entity name" ); + checkNotNull( primaryKey, "Primary key" ); + checkSession(); + + if ( !verCfg.getEntCfg().isVersioned( entityName ) ) { + throw new NotAuditedException( entityName, entityName + " is not versioned!" ); + } + + return createQuery().forRevisionsOfEntity( cls, entityName, false, true ) + .addProjection( AuditEntity.revisionNumber() ) + .addOrder( AuditEntity.revisionNumber().asc() ) + .add( AuditEntity.id().eq( primaryKey ) ) + .getResultList(); + } + + @Override + public Date getRevisionDate(Number revision) + throws IllegalArgumentException, RevisionDoesNotExistException, IllegalStateException { + checkNotNull( revision, "Entity revision" ); + checkPositive( revision, "Entity revision" ); + checkSession(); + + final Criteria query = verCfg.getRevisionInfoQueryCreator().getRevisionDateQuery( session, revision ); + + try { + final Object timestampObject = query.uniqueResult(); + if ( timestampObject == null ) { + throw new RevisionDoesNotExistException( revision ); } - return result; - } catch (HibernateException e) { - throw new AuditException(e); - } - } + // The timestamp object is either a date or a long + return timestampObject instanceof Date ? (Date) timestampObject : new Date( (Long) timestampObject ); + } + catch (NonUniqueResultException e) { + throw new AuditException( e ); + } + } - public CrossTypeRevisionChangesReader getCrossTypeRevisionChangesReader() throws AuditException { - if (!verCfg.getGlobalCfg().isTrackEntitiesChangedInRevision()) { - throw new AuditException("This API is designed for Envers default mechanism of tracking entities modified in a given revision." - + " Extend DefaultTrackingModifiedEntitiesRevisionEntity, utilize @ModifiedEntityNames annotation or set " - + "'org.hibernate.envers.track_entities_changed_in_revision' parameter to true."); - } - return crossTypeRevisionChangesReader; - } + @Override + public Number getRevisionNumberForDate(Date date) { + checkNotNull( date, "Date of revision" ); + checkSession(); + final Criteria query = verCfg.getRevisionInfoQueryCreator().getRevisionNumberForDateQuery( session, date ); + + try { + final Number res = (Number) query.uniqueResult(); + if ( res == null ) { + throw new RevisionDoesNotExistException( date ); + } + + return res; + } + catch (NonUniqueResultException e) { + throw new AuditException( e ); + } + } + + @Override + @SuppressWarnings({"unchecked"}) + public T findRevision(Class revisionEntityClass, Number revision) + throws IllegalArgumentException, RevisionDoesNotExistException, IllegalStateException { + revisionEntityClass = getTargetClassIfProxied( revisionEntityClass ); + checkNotNull( revision, "Entity revision" ); + checkPositive( revision, "Entity revision" ); + checkSession(); + + final Set revisions = new HashSet( 1 ); + revisions.add( revision ); + final Criteria query = verCfg.getRevisionInfoQueryCreator().getRevisionsQuery( session, revisions ); + + try { + final T revisionData = (T) query.uniqueResult(); + + if ( revisionData == null ) { + throw new RevisionDoesNotExistException( revision ); + } + + return revisionData; + } + catch (NonUniqueResultException e) { + throw new AuditException( e ); + } + } + + @Override + @SuppressWarnings({"unchecked"}) + public Map findRevisions(Class revisionEntityClass, Set revisions) + throws IllegalArgumentException, + IllegalStateException { + revisionEntityClass = getTargetClassIfProxied( revisionEntityClass ); + final Map result = new HashMap( revisions.size() ); + + for ( Number revision : revisions ) { + checkNotNull( revision, "Entity revision" ); + checkPositive( revision, "Entity revision" ); + } + checkSession(); + + final Criteria query = verCfg.getRevisionInfoQueryCreator().getRevisionsQuery( session, revisions ); + + try { + final List revisionList = query.list(); + for ( T revision : revisionList ) { + final Number revNo = verCfg.getRevisionInfoNumberReader().getRevisionNumber( revision ); + result.put( revNo, revision ); + } + + return result; + } + catch (HibernateException e) { + throw new AuditException( e ); + } + } + + @Override + public CrossTypeRevisionChangesReader getCrossTypeRevisionChangesReader() throws AuditException { + if ( !verCfg.getGlobalCfg().isTrackEntitiesChangedInRevision() ) { + throw new AuditException( + "This API is designed for Envers default mechanism of tracking entities modified in a given revision." + + " Extend DefaultTrackingModifiedEntitiesRevisionEntity, utilize @ModifiedEntityNames annotation or set " + + "'org.hibernate.envers.track_entities_changed_in_revision' parameter to true." + ); + } + return crossTypeRevisionChangesReader; + } + + @Override @SuppressWarnings({"unchecked"}) public T getCurrentRevision(Class revisionEntityClass, boolean persist) { - revisionEntityClass = getTargetClassIfProxied(revisionEntityClass); - if (!(session instanceof EventSource)) { - throw new IllegalArgumentException("The provided session is not an EventSource!"); + revisionEntityClass = getTargetClassIfProxied( revisionEntityClass ); + if ( !(session instanceof EventSource) ) { + throw new IllegalArgumentException( "The provided session is not an EventSource!" ); } // Obtaining the current audit sync - AuditProcess auditProcess = verCfg.getSyncManager().get((EventSource) session); + final AuditProcess auditProcess = verCfg.getSyncManager().get( (EventSource) session ); // And getting the current revision data - return (T) auditProcess.getCurrentRevisionData(session, persist); + return (T) auditProcess.getCurrentRevisionData( session, persist ); } + @Override public AuditQueryCreator createQuery() { - return new AuditQueryCreator(verCfg, this); - } - - public boolean isEntityClassAudited(Class entityClass) { - entityClass = getTargetClassIfProxied(entityClass); - return this.isEntityNameAudited(entityClass.getName()); - } + return new AuditQueryCreator( verCfg, this ); + } + + @Override + public boolean isEntityClassAudited(Class entityClass) { + entityClass = getTargetClassIfProxied( entityClass ); + return this.isEntityNameAudited( entityClass.getName() ); + } + @Override public boolean isEntityNameAudited(String entityName) { - checkNotNull(entityName, "Entity name"); - checkSession(); - return (verCfg.getEntCfg().isVersioned(entityName)); - } + checkNotNull( entityName, "Entity name" ); + checkSession(); + return (verCfg.getEntCfg().isVersioned( entityName )); + } - - public String getEntityName(Object primaryKey, Number revision ,Object entity) throws HibernateException{ - checkNotNull(primaryKey, "Primary key"); - checkNotNull(revision, "Entity revision"); - checkPositive(revision, "Entity revision"); - checkNotNull(entity, "Entity"); - checkSession(); + @Override + public String getEntityName(Object primaryKey, Number revision, Object entity) throws HibernateException { + checkNotNull( primaryKey, "Primary key" ); + checkNotNull( revision, "Entity revision" ); + checkPositive( revision, "Entity revision" ); + checkNotNull( entity, "Entity" ); + checkSession(); // Unwrap if necessary - if(entity instanceof HibernateProxy) { - entity = ((HibernateProxy)entity).getHibernateLazyInitializer().getImplementation(); + if ( entity instanceof HibernateProxy ) { + entity = ((HibernateProxy) entity).getHibernateLazyInitializer().getImplementation(); } - if(firstLevelCache.containsEntityName(primaryKey, revision, entity)) { + if ( firstLevelCache.containsEntityName( primaryKey, revision, entity ) ) { // it's on envers FLC! - return firstLevelCache.getFromEntityNameCache(primaryKey, revision, entity); - } else { + return firstLevelCache.getFromEntityNameCache( primaryKey, revision, entity ); + } + else { throw new HibernateException( - "Envers can't resolve entityName for historic entity. The id, revision and entity is not on envers first level cache."); - } -} + "Envers can't resolve entityName for historic entity. The id, revision and entity is not on envers first level cache." + ); + } + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/AuditReaderImplementor.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/AuditReaderImplementor.java index bacd9dd813..ce98112daf 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/AuditReaderImplementor.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/AuditReaderImplementor.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,16 +22,20 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.reader; + import org.hibernate.Session; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.envers.AuditReader; /** * An interface exposed by a VersionsReader to library-facing classes. + * * @author Adam Warski (adam at warski dot org) */ public interface AuditReaderImplementor extends AuditReader { - SessionImplementor getSessionImplementor(); - Session getSession(); - FirstLevelCache getFirstLevelCache(); + SessionImplementor getSessionImplementor(); + + Session getSession(); + + FirstLevelCache getFirstLevelCache(); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/CrossTypeRevisionChangesReaderImpl.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/CrossTypeRevisionChangesReaderImpl.java index 1f4cbbc0ab..6b4ab9619b 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/CrossTypeRevisionChangesReaderImpl.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/CrossTypeRevisionChangesReaderImpl.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.internal.reader; import java.util.ArrayList; @@ -25,86 +48,115 @@ import static org.hibernate.envers.internal.tools.ArgumentsTools.checkPositive; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class CrossTypeRevisionChangesReaderImpl implements CrossTypeRevisionChangesReader { - private final AuditReaderImplementor auditReaderImplementor; - private final AuditConfiguration verCfg; + private final AuditReaderImplementor auditReaderImplementor; + private final AuditConfiguration verCfg; - public CrossTypeRevisionChangesReaderImpl(AuditReaderImplementor auditReaderImplementor, AuditConfiguration verCfg) { - this.auditReaderImplementor = auditReaderImplementor; - this.verCfg = verCfg; - } + public CrossTypeRevisionChangesReaderImpl( + AuditReaderImplementor auditReaderImplementor, + AuditConfiguration verCfg) { + this.auditReaderImplementor = auditReaderImplementor; + this.verCfg = verCfg; + } - @SuppressWarnings({"unchecked"}) - public List findEntities(Number revision) throws IllegalStateException, IllegalArgumentException { - Set> entityTypes = findEntityTypes(revision); - List result = new ArrayList(); - for (Pair type : entityTypes) { - result.addAll(auditReaderImplementor.createQuery().forEntitiesModifiedAtRevision(type.getSecond(), type.getFirst(), revision) - .getResultList()); - } - return result; - } + @Override + @SuppressWarnings({"unchecked"}) + public List findEntities(Number revision) throws IllegalStateException, IllegalArgumentException { + final Set> entityTypes = findEntityTypes( revision ); + final List result = new ArrayList(); + for ( Pair type : entityTypes ) { + result.addAll( + auditReaderImplementor.createQuery().forEntitiesModifiedAtRevision( + type.getSecond(), + type.getFirst(), + revision + ) + .getResultList() + ); + } + return result; + } - @SuppressWarnings({"unchecked"}) - public List findEntities(Number revision, RevisionType revisionType) throws IllegalStateException, - IllegalArgumentException { - Set> entityTypes = findEntityTypes(revision); - List result = new ArrayList(); - for (Pair type : entityTypes) { - result.addAll(auditReaderImplementor.createQuery().forEntitiesModifiedAtRevision(type.getSecond(), type.getFirst(), revision) - .add(new RevisionTypeAuditExpression(revisionType, "=")).getResultList()); - } - return result; - } + @Override + @SuppressWarnings({"unchecked"}) + public List findEntities(Number revision, RevisionType revisionType) + throws IllegalStateException, IllegalArgumentException { + final Set> entityTypes = findEntityTypes( revision ); + final List result = new ArrayList(); + for ( Pair type : entityTypes ) { + result.addAll( + auditReaderImplementor.createQuery().forEntitiesModifiedAtRevision( + type.getSecond(), + type.getFirst(), + revision + ) + .add( new RevisionTypeAuditExpression( revisionType, "=" ) ).getResultList() + ); + } + return result; + } - @SuppressWarnings({"unchecked"}) - public Map> findEntitiesGroupByRevisionType(Number revision) throws IllegalStateException, - IllegalArgumentException { - Set> entityTypes = findEntityTypes(revision); - Map> result = new HashMap>(); - for (RevisionType revisionType : RevisionType.values()) { - result.put(revisionType, new ArrayList()); - for (Pair type : entityTypes) { - List list = auditReaderImplementor.createQuery().forEntitiesModifiedAtRevision(type.getSecond(), type.getFirst(), revision) - .add(new RevisionTypeAuditExpression(revisionType, "=")).getResultList(); - result.get(revisionType).addAll(list); - } - } - return result; - } + @Override + @SuppressWarnings({"unchecked"}) + public Map> findEntitiesGroupByRevisionType(Number revision) + throws IllegalStateException, IllegalArgumentException { + final Set> entityTypes = findEntityTypes( revision ); + final Map> result = new HashMap>(); + for ( RevisionType revisionType : RevisionType.values() ) { + result.put( revisionType, new ArrayList() ); + for ( Pair type : entityTypes ) { + final List list = auditReaderImplementor.createQuery() + .forEntitiesModifiedAtRevision( type.getSecond(), type.getFirst(), revision ) + .add( new RevisionTypeAuditExpression( revisionType, "=" ) ) + .getResultList(); + result.get( revisionType ).addAll( list ); + } + } + return result; + } - @SuppressWarnings({"unchecked"}) - public Set> findEntityTypes(Number revision) throws IllegalStateException, IllegalArgumentException { - checkNotNull(revision, "Entity revision"); - checkPositive(revision, "Entity revision"); - checkSession(); + @Override + @SuppressWarnings({"unchecked"}) + public Set> findEntityTypes(Number revision) + throws IllegalStateException, IllegalArgumentException { + checkNotNull( revision, "Entity revision" ); + checkPositive( revision, "Entity revision" ); + checkSession(); - Session session = auditReaderImplementor.getSession(); - SessionImplementor sessionImplementor = auditReaderImplementor.getSessionImplementor(); + final Session session = auditReaderImplementor.getSession(); + final SessionImplementor sessionImplementor = auditReaderImplementor.getSessionImplementor(); - Set revisions = new HashSet(1); - revisions.add(revision); - Criteria query = verCfg.getRevisionInfoQueryCreator().getRevisionsQuery(session, revisions); - Object revisionInfo = query.uniqueResult(); + final Set revisions = new HashSet( 1 ); + revisions.add( revision ); + final Criteria query = verCfg.getRevisionInfoQueryCreator().getRevisionsQuery( session, revisions ); + final Object revisionInfo = query.uniqueResult(); - if (revisionInfo != null) { - // If revision exists. - Set entityNames = verCfg.getModifiedEntityNamesReader().getModifiedEntityNames(revisionInfo); - if (entityNames != null) { - // Generate result that contains entity names and corresponding Java classes. - Set> result = new HashSet>(); - for (String entityName : entityNames) { - result.add(Pair.make(entityName, EntityTools.getEntityClass(sessionImplementor, session, entityName))); - } - return result; - } - } + if ( revisionInfo != null ) { + // If revision exists. + final Set entityNames = verCfg.getModifiedEntityNamesReader().getModifiedEntityNames( revisionInfo ); + if ( entityNames != null ) { + // Generate result that contains entity names and corresponding Java classes. + final Set> result = new HashSet>(); + for ( String entityName : entityNames ) { + result.add( + Pair.make( + entityName, EntityTools.getEntityClass( + sessionImplementor, + session, + entityName + ) + ) + ); + } + return result; + } + } - return Collections.EMPTY_SET; - } + return Collections.EMPTY_SET; + } - private void checkSession() { - if (!auditReaderImplementor.getSession().isOpen()) { - throw new IllegalStateException("The associated entity manager is closed!"); - } - } + private void checkSession() { + if ( !auditReaderImplementor.getSession().isOpen() ) { + throw new IllegalStateException( "The associated entity manager is closed!" ); + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/FirstLevelCache.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/FirstLevelCache.java index db9a4a4ab6..1ad3511956 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/FirstLevelCache.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/reader/FirstLevelCache.java @@ -1,7 +1,7 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008-2011, Red Hat Inc. or third-party contributors as + * Copyright (c) 2013, 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. @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.reader; + import java.util.Map; import org.jboss.logging.Logger; @@ -35,82 +36,101 @@ import static org.hibernate.envers.internal.tools.Triple.make; /** * First level cache for versioned entities, versions reader-scoped. Each entity is uniquely identified by a * revision number and entity id. + * * @author Adam Warski (adam at warski dot org) * @author Hernán Chanfreau */ public class FirstLevelCache { + private static final EnversMessageLogger LOG = Logger.getMessageLogger( + EnversMessageLogger.class, + FirstLevelCache.class.getName() + ); - public static final EnversMessageLogger LOG = Logger.getMessageLogger(EnversMessageLogger.class, FirstLevelCache.class.getName()); + /** + * cache for resolve an object for a given id, revision and entityName. + */ + private final Map, Object> cache; - /** - * cache for resolve an object for a given id, revision and entityName. - */ - private final Map, Object> cache; + /** + * used to resolve the entityName for a given id, revision and entity. + */ + private final Map, String> entityNameCache; - /** - * used to resolve the entityName for a given id, revision and entity. - */ - private final Map, String> entityNameCache; + public FirstLevelCache() { + cache = newHashMap(); + entityNameCache = newHashMap(); + } - public FirstLevelCache() { - cache = newHashMap(); - entityNameCache = newHashMap(); - } + public Object get(String entityName, Number revision, Object id) { + LOG.debugf( + "Resolving object from First Level Cache: EntityName:%s - primaryKey:%s - revision:%s", + entityName, + id, + revision + ); + return cache.get( make( entityName, revision, id ) ); + } - public Object get(String entityName, Number revision, Object id) { - LOG.debugf("Resolving object from First Level Cache: EntityName:%s - primaryKey:%s - revision:%s", entityName, id, revision); - return cache.get(make(entityName, revision, id)); - } + public void put(String entityName, Number revision, Object id, Object entity) { + LOG.debugf( + "Caching entity on First Level Cache: - primaryKey:%s - revision:%s - entityName:%s", + id, + revision, + entityName + ); + cache.put( make( entityName, revision, id ), entity ); + } - public void put(String entityName, Number revision, Object id, Object entity) { - LOG.debugf("Caching entity on First Level Cache: - primaryKey:%s - revision:%s - entityName:%s", id, revision, entityName); - cache.put(make(entityName, revision, id), entity); - } + public boolean contains(String entityName, Number revision, Object id) { + return cache.containsKey( make( entityName, revision, id ) ); + } - public boolean contains(String entityName, Number revision, Object id) { - return cache.containsKey(make(entityName, revision, id)); - } - - /** - * Adds the entityName into the cache. The key is a triple make with primaryKey, revision and entity - * @param id primaryKey - * @param revision revision number - * @param entity object retrieved by envers - * @param entityName value of the cache - */ - public void putOnEntityNameCache(Object id, Number revision, Object entity, String entityName) { - LOG.debugf("Caching entityName on First Level Cache: - primaryKey:%s - revision:%s - entity:%s -> entityName:%s", - id, - revision, - entity.getClass().getName(), - entityName); - entityNameCache.put(make(id, revision, entity), entityName); - } - - /** - * Gets the entityName from the cache. The key is a triple make with primaryKey, revision and entity + /** + * Adds the entityName into the cache. The key is a triple make with primaryKey, revision and entity * - * @param id primaryKey - * @param revision revision number - * @param entity object retrieved by envers + * @param id primaryKey + * @param revision revision number + * @param entity object retrieved by envers + * @param entityName value of the cache + */ + public void putOnEntityNameCache(Object id, Number revision, Object entity, String entityName) { + LOG.debugf( + "Caching entityName on First Level Cache: - primaryKey:%s - revision:%s - entity:%s -> entityName:%s", + id, + revision, + entity.getClass().getName(), + entityName + ); + entityNameCache.put( make( id, revision, entity ), entityName ); + } + + /** + * Gets the entityName from the cache. The key is a triple make with primaryKey, revision and entity + * + * @param id primaryKey + * @param revision revision number + * @param entity object retrieved by envers * * @return The appropriate entity name - */ - public String getFromEntityNameCache(Object id, Number revision, Object entity) { - LOG.debugf("Trying to resolve entityName from First Level Cache: - primaryKey:%s - revision:%s - entity:%s", - id, - revision, - entity); - return entityNameCache.get(make(id, revision, entity)); - } + */ + public String getFromEntityNameCache(Object id, Number revision, Object entity) { + LOG.debugf( + "Trying to resolve entityName from First Level Cache: - primaryKey:%s - revision:%s - entity:%s", + id, + revision, + entity + ); + return entityNameCache.get( make( id, revision, entity ) ); + } /** * @param id primaryKey * @param revision revision number * @param entity object retrieved by envers + * * @return true if entityNameCache contains the triple */ - public boolean containsEntityName(Object id, Number revision, Object entity) { - return entityNameCache.containsKey(make(id, revision, entity)); - } + public boolean containsEntityName(Object id, Number revision, Object entity) { + return entityNameCache.containsKey( make( id, revision, entity ) ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/DefaultRevisionInfoGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/DefaultRevisionInfoGenerator.java index b3d480c71a..df36426cc6 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/DefaultRevisionInfoGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/DefaultRevisionInfoGenerator.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -43,70 +43,88 @@ import org.hibernate.property.Setter; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class DefaultRevisionInfoGenerator implements RevisionInfoGenerator { - private final String revisionInfoEntityName; - private final RevisionListener listener; - private final Setter revisionTimestampSetter; - private final boolean timestampAsDate; - private final Class revisionInfoClass; - private final SessionCacheCleaner sessionCacheCleaner; + private final String revisionInfoEntityName; + private final RevisionListener listener; + private final Setter revisionTimestampSetter; + private final boolean timestampAsDate; + private final Class revisionInfoClass; + private final SessionCacheCleaner sessionCacheCleaner; - public DefaultRevisionInfoGenerator(String revisionInfoEntityName, Class revisionInfoClass, - Class listenerClass, - PropertyData revisionInfoTimestampData, - boolean timestampAsDate) { - this.revisionInfoEntityName = revisionInfoEntityName; - this.revisionInfoClass = revisionInfoClass; - this.timestampAsDate = timestampAsDate; + public DefaultRevisionInfoGenerator( + String revisionInfoEntityName, Class revisionInfoClass, + Class listenerClass, + PropertyData revisionInfoTimestampData, + boolean timestampAsDate) { + this.revisionInfoEntityName = revisionInfoEntityName; + this.revisionInfoClass = revisionInfoClass; + this.timestampAsDate = timestampAsDate; - revisionTimestampSetter = ReflectionTools.getSetter(revisionInfoClass, revisionInfoTimestampData); + revisionTimestampSetter = ReflectionTools.getSetter( revisionInfoClass, revisionInfoTimestampData ); - if (!listenerClass.equals(RevisionListener.class)) { - // This is not the default value. - try { - listener = (RevisionListener) ReflectHelper.getDefaultConstructor(listenerClass).newInstance(); - } catch (InstantiationException e) { - throw new MappingException(e); - } catch (IllegalAccessException e) { - throw new MappingException(e); - } catch (InvocationTargetException e) { - throw new MappingException(e); - } - } else { - // Default listener - none - listener = null; - } + if ( !listenerClass.equals( RevisionListener.class ) ) { + // This is not the default value. + try { + listener = (RevisionListener) ReflectHelper.getDefaultConstructor( listenerClass ).newInstance(); + } + catch (InstantiationException e) { + throw new MappingException( e ); + } + catch (IllegalAccessException e) { + throw new MappingException( e ); + } + catch (InvocationTargetException e) { + throw new MappingException( e ); + } + } + else { + // Default listener - none + listener = null; + } - sessionCacheCleaner = new SessionCacheCleaner(); - } - - public void saveRevisionData(Session session, Object revisionData) { - session.save(revisionInfoEntityName, revisionData); - sessionCacheCleaner.scheduleAuditDataRemoval(session, revisionData); + sessionCacheCleaner = new SessionCacheCleaner(); } - public Object generate() { + @Override + public void saveRevisionData(Session session, Object revisionData) { + session.save( revisionInfoEntityName, revisionData ); + sessionCacheCleaner.scheduleAuditDataRemoval( session, revisionData ); + } + + @Override + public Object generate() { Object revisionInfo; - try { - revisionInfo = ReflectHelper.getDefaultConstructor(revisionInfoClass).newInstance(); - } catch (Exception e) { - throw new RuntimeException(e); - } + try { + revisionInfo = ReflectHelper.getDefaultConstructor( revisionInfoClass ).newInstance(); + } + catch (Exception e) { + throw new RuntimeException( e ); + } - long timestamp = System.currentTimeMillis(); - revisionTimestampSetter.set(revisionInfo, timestampAsDate ? new Date(timestamp) : timestamp, null); + final long timestamp = System.currentTimeMillis(); + revisionTimestampSetter.set( revisionInfo, timestampAsDate ? new Date( timestamp ) : timestamp, null ); - if (listener != null) { - listener.newRevision(revisionInfo); - } + if ( listener != null ) { + listener.newRevision( revisionInfo ); + } - return revisionInfo; - } + return revisionInfo; + } - public void entityChanged(Class entityClass, String entityName, Serializable entityId, RevisionType revisionType, - Object revisionInfo) { - if (listener instanceof EntityTrackingRevisionListener) { - ((EntityTrackingRevisionListener) listener).entityChanged(entityClass, entityName, entityId, revisionType, - revisionInfo); - } - } + @Override + public void entityChanged( + Class entityClass, + String entityName, + Serializable entityId, + RevisionType revisionType, + Object revisionInfo) { + if ( listener instanceof EntityTrackingRevisionListener ) { + ( (EntityTrackingRevisionListener) listener ).entityChanged( + entityClass, + entityName, + entityId, + revisionType, + revisionInfo + ); + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/DefaultTrackingModifiedEntitiesRevisionInfoGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/DefaultTrackingModifiedEntitiesRevisionInfoGenerator.java index f3da3f4d1a..328bc8f28d 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/DefaultTrackingModifiedEntitiesRevisionInfoGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/DefaultTrackingModifiedEntitiesRevisionInfoGenerator.java @@ -1,11 +1,32 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.internal.revisioninfo; import java.io.Serializable; import java.util.HashSet; import java.util.Set; -import org.hibernate.envers.DefaultTrackingModifiedEntitiesRevisionEntity; -import org.hibernate.envers.ModifiedEntityNames; import org.hibernate.envers.RevisionListener; import org.hibernate.envers.RevisionType; import org.hibernate.envers.internal.entities.PropertyData; @@ -15,33 +36,40 @@ import org.hibernate.property.Setter; /** * Automatically adds entity names, that have been changed during current revision, to revision entity. - * @see ModifiedEntityNames - * @see DefaultTrackingModifiedEntitiesRevisionEntity + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) + * + * @see org.hibernate.envers.ModifiedEntityNames + * @see org.hibernate.envers.DefaultTrackingModifiedEntitiesRevisionEntity */ public class DefaultTrackingModifiedEntitiesRevisionInfoGenerator extends DefaultRevisionInfoGenerator { - private final Setter modifiedEntityNamesSetter; - private final Getter modifiedEntityNamesGetter; + private final Setter modifiedEntityNamesSetter; + private final Getter modifiedEntityNamesGetter; - public DefaultTrackingModifiedEntitiesRevisionInfoGenerator(String revisionInfoEntityName, Class revisionInfoClass, - Class listenerClass, - PropertyData revisionInfoTimestampData, boolean timestampAsDate, - PropertyData modifiedEntityNamesData) { - super(revisionInfoEntityName, revisionInfoClass, listenerClass, revisionInfoTimestampData, timestampAsDate); - modifiedEntityNamesSetter = ReflectionTools.getSetter(revisionInfoClass, modifiedEntityNamesData); - modifiedEntityNamesGetter = ReflectionTools.getGetter(revisionInfoClass, modifiedEntityNamesData); - } + public DefaultTrackingModifiedEntitiesRevisionInfoGenerator( + String revisionInfoEntityName, Class revisionInfoClass, + Class listenerClass, + PropertyData revisionInfoTimestampData, boolean timestampAsDate, + PropertyData modifiedEntityNamesData) { + super( revisionInfoEntityName, revisionInfoClass, listenerClass, revisionInfoTimestampData, timestampAsDate ); + modifiedEntityNamesSetter = ReflectionTools.getSetter( revisionInfoClass, modifiedEntityNamesData ); + modifiedEntityNamesGetter = ReflectionTools.getGetter( revisionInfoClass, modifiedEntityNamesData ); + } - @Override - @SuppressWarnings({"unchecked"}) - public void entityChanged(Class entityClass, String entityName, Serializable entityId, RevisionType revisionType, - Object revisionEntity) { - super.entityChanged(entityClass, entityName, entityId, revisionType, revisionEntity); - Set modifiedEntityNames = (Set) modifiedEntityNamesGetter.get(revisionEntity); - if (modifiedEntityNames == null) { - modifiedEntityNames = new HashSet(); - modifiedEntityNamesSetter.set(revisionEntity, modifiedEntityNames, null); - } - modifiedEntityNames.add(entityName); - } + @Override + @SuppressWarnings({"unchecked"}) + public void entityChanged( + Class entityClass, + String entityName, + Serializable entityId, + RevisionType revisionType, + Object revisionEntity) { + super.entityChanged( entityClass, entityName, entityId, revisionType, revisionEntity ); + Set modifiedEntityNames = (Set) modifiedEntityNamesGetter.get( revisionEntity ); + if ( modifiedEntityNames == null ) { + modifiedEntityNames = new HashSet(); + modifiedEntityNamesSetter.set( revisionEntity, modifiedEntityNames, null ); + } + modifiedEntityNames.add( entityName ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/ModifiedEntityNamesReader.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/ModifiedEntityNamesReader.java index f29f6846d4..eeeaf41fdc 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/ModifiedEntityNamesReader.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/ModifiedEntityNamesReader.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.internal.revisioninfo; import java.util.Set; @@ -8,17 +31,18 @@ import org.hibernate.property.Getter; /** * Returns modified entity names from a persisted revision info entity. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class ModifiedEntityNamesReader { - private final Getter modifiedEntityNamesGetter; + private final Getter modifiedEntityNamesGetter; - public ModifiedEntityNamesReader(Class revisionInfoClass, PropertyData modifiedEntityNamesData) { - modifiedEntityNamesGetter = ReflectionTools.getGetter(revisionInfoClass, modifiedEntityNamesData); - } + public ModifiedEntityNamesReader(Class revisionInfoClass, PropertyData modifiedEntityNamesData) { + modifiedEntityNamesGetter = ReflectionTools.getGetter( revisionInfoClass, modifiedEntityNamesData ); + } - @SuppressWarnings({"unchecked"}) - public Set getModifiedEntityNames(Object revisionEntity) { - return (Set) modifiedEntityNamesGetter.get(revisionEntity); - } + @SuppressWarnings({"unchecked"}) + public Set getModifiedEntityNames(Object revisionEntity) { + return (Set) modifiedEntityNamesGetter.get( revisionEntity ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/RevisionInfoGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/RevisionInfoGenerator.java index cef1a14a3b..30fa321d36 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/RevisionInfoGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/RevisionInfoGenerator.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -34,11 +34,13 @@ import org.hibernate.envers.RevisionType; */ public interface RevisionInfoGenerator { void saveRevisionData(Session session, Object revisionData); - Object generate(); - /** - * @see EntityTrackingRevisionListener#entityChanged(Class, String, Serializable, RevisionType, Object) - */ - void entityChanged(Class entityClass, String entityName, Serializable entityId, RevisionType revisionType, - Object revisionEntity); + Object generate(); + + /** + * @see EntityTrackingRevisionListener#entityChanged(Class, String, Serializable, RevisionType, Object) + */ + void entityChanged( + Class entityClass, String entityName, Serializable entityId, RevisionType revisionType, + Object revisionEntity); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/RevisionInfoNumberReader.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/RevisionInfoNumberReader.java index 69f17ad8fb..a19d2667c7 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/RevisionInfoNumberReader.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/RevisionInfoNumberReader.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,21 +22,24 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.revisioninfo; + import org.hibernate.envers.internal.entities.PropertyData; import org.hibernate.envers.internal.tools.ReflectionTools; import org.hibernate.property.Getter; /** * Gets a revision number from a persisted revision info entity. + * * @author Adam Warski (adam at warski dot org) */ public class RevisionInfoNumberReader { - private final Getter revisionIdGetter; - public RevisionInfoNumberReader(Class revisionInfoClass, PropertyData revisionInfoIdData) { - revisionIdGetter = ReflectionTools.getGetter(revisionInfoClass, revisionInfoIdData); - } + private final Getter revisionIdGetter; - public Number getRevisionNumber(Object revision) { - return (Number) revisionIdGetter.get(revision); - } + public RevisionInfoNumberReader(Class revisionInfoClass, PropertyData revisionInfoIdData) { + revisionIdGetter = ReflectionTools.getGetter( revisionInfoClass, revisionInfoIdData ); + } + + public Number getRevisionNumber(Object revision) { + return (Number) revisionIdGetter.get( revision ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/RevisionInfoQueryCreator.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/RevisionInfoQueryCreator.java index 005d29db58..202d7f5eed 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/RevisionInfoQueryCreator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/revisioninfo/RevisionInfoQueryCreator.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -36,30 +36,35 @@ import org.hibernate.criterion.Restrictions; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class RevisionInfoQueryCreator { - private final String revisionInfoEntityName; - private final String revisionInfoIdName; - private final String revisionInfoTimestampName; - private final boolean timestampAsDate; + private final String revisionInfoEntityName; + private final String revisionInfoIdName; + private final String revisionInfoTimestampName; + private final boolean timestampAsDate; - public RevisionInfoQueryCreator(String revisionInfoEntityName, String revisionInfoIdName, - String revisionInfoTimestampName, boolean timestampAsDate) { - this.revisionInfoEntityName = revisionInfoEntityName; - this.revisionInfoIdName = revisionInfoIdName; - this.revisionInfoTimestampName = revisionInfoTimestampName; - this.timestampAsDate = timestampAsDate; - } + public RevisionInfoQueryCreator( + String revisionInfoEntityName, String revisionInfoIdName, + String revisionInfoTimestampName, boolean timestampAsDate) { + this.revisionInfoEntityName = revisionInfoEntityName; + this.revisionInfoIdName = revisionInfoIdName; + this.revisionInfoTimestampName = revisionInfoTimestampName; + this.timestampAsDate = timestampAsDate; + } - public Criteria getRevisionDateQuery(Session session, Number revision) { - return session.createCriteria(revisionInfoEntityName).setProjection(Projections.property(revisionInfoTimestampName)) - .add(Restrictions.eq(revisionInfoIdName, revision)); - } + public Criteria getRevisionDateQuery(Session session, Number revision) { + return session.createCriteria( revisionInfoEntityName ).setProjection( + Projections.property( + revisionInfoTimestampName + ) + ) + .add( Restrictions.eq( revisionInfoIdName, revision ) ); + } - public Criteria getRevisionNumberForDateQuery(Session session, Date date) { - return session.createCriteria(revisionInfoEntityName).setProjection(Projections.max(revisionInfoIdName)) - .add(Restrictions.le(revisionInfoTimestampName, timestampAsDate ? date : date.getTime())); - } + public Criteria getRevisionNumberForDateQuery(Session session, Date date) { + return session.createCriteria( revisionInfoEntityName ).setProjection( Projections.max( revisionInfoIdName ) ) + .add( Restrictions.le( revisionInfoTimestampName, timestampAsDate ? date : date.getTime() ) ); + } - public Criteria getRevisionsQuery(Session session, Set revisions) { - return session.createCriteria(revisionInfoEntityName).add(Restrictions.in(revisionInfoIdName, revisions)); - } + public Criteria getRevisionsQuery(Session session, Set revisions) { + return session.createCriteria( revisionInfoEntityName ).add( Restrictions.in( revisionInfoIdName, revisions ) ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/AuditProcess.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/AuditProcess.java index d8e79979b6..709eef5002 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/AuditProcess.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/AuditProcess.java @@ -1,7 +1,7 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2010, Red Hat Inc. or third-party contributors as + * Copyright (c) 2013, 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. @@ -41,121 +41,127 @@ import org.hibernate.envers.tools.Pair; * @author Adam Warski (adam at warski dot org) */ public class AuditProcess implements BeforeTransactionCompletionProcess { - private final RevisionInfoGenerator revisionInfoGenerator; - private final SessionImplementor session; + private final RevisionInfoGenerator revisionInfoGenerator; + private final SessionImplementor session; - private final LinkedList workUnits; - private final Queue undoQueue; - private final Map, AuditWorkUnit> usedIds; - private final EntityChangeNotifier entityChangeNotifier; + private final LinkedList workUnits; + private final Queue undoQueue; + private final Map, AuditWorkUnit> usedIds; + private final EntityChangeNotifier entityChangeNotifier; - private Object revisionData; + private Object revisionData; - public AuditProcess(RevisionInfoGenerator revisionInfoGenerator, SessionImplementor session) { - this.revisionInfoGenerator = revisionInfoGenerator; - this.session = session; + public AuditProcess(RevisionInfoGenerator revisionInfoGenerator, SessionImplementor session) { + this.revisionInfoGenerator = revisionInfoGenerator; + this.session = session; - workUnits = new LinkedList(); - undoQueue = new LinkedList(); - usedIds = new HashMap, AuditWorkUnit>(); - entityChangeNotifier = new EntityChangeNotifier(revisionInfoGenerator, session); - } + workUnits = new LinkedList(); + undoQueue = new LinkedList(); + usedIds = new HashMap, AuditWorkUnit>(); + entityChangeNotifier = new EntityChangeNotifier( revisionInfoGenerator, session ); + } - private void removeWorkUnit(AuditWorkUnit vwu) { - workUnits.remove(vwu); - if (vwu.isPerformed()) { - // If this work unit has already been performed, it must be deleted (undone) first. - undoQueue.offer(vwu); - } - } + private void removeWorkUnit(AuditWorkUnit vwu) { + workUnits.remove( vwu ); + if ( vwu.isPerformed() ) { + // If this work unit has already been performed, it must be deleted (undone) first. + undoQueue.offer( vwu ); + } + } - public void addWorkUnit(AuditWorkUnit vwu) { - if (vwu.containsWork()) { - Object entityId = vwu.getEntityId(); + public void addWorkUnit(AuditWorkUnit vwu) { + if ( vwu.containsWork() ) { + final Object entityId = vwu.getEntityId(); - if (entityId == null) { - // Just adding the work unit - it's not associated with any persistent entity. - workUnits.offer(vwu); - } else { - String entityName = vwu.getEntityName(); - Pair usedIdsKey = Pair.make(entityName, entityId); + if ( entityId == null ) { + // Just adding the work unit - it's not associated with any persistent entity. + workUnits.offer( vwu ); + } + else { + final String entityName = vwu.getEntityName(); + final Pair usedIdsKey = Pair.make( entityName, entityId ); - if (usedIds.containsKey(usedIdsKey)) { - AuditWorkUnit other = usedIds.get(usedIdsKey); + if ( usedIds.containsKey( usedIdsKey ) ) { + final AuditWorkUnit other = usedIds.get( usedIdsKey ); + final AuditWorkUnit result = vwu.dispatch( other ); - AuditWorkUnit result = vwu.dispatch(other); + if ( result != other ) { + removeWorkUnit( other ); - if (result != other) { - removeWorkUnit(other); + if ( result != null ) { + usedIds.put( usedIdsKey, result ); + workUnits.offer( result ); + } + // else: a null result means that no work unit should be kept + } + // else: the result is the same as the work unit already added. No need to do anything. + } + else { + usedIds.put( usedIdsKey, vwu ); + workUnits.offer( vwu ); + } + } + } + } - if (result != null) { - usedIds.put(usedIdsKey, result); - workUnits.offer(result); - } // else: a null result means that no work unit should be kept - } // else: the result is the same as the work unit already added. No need to do anything. - } else { - usedIds.put(usedIdsKey, vwu); - workUnits.offer(vwu); - } - } - } - } - - private void executeInSession(Session session) { + private void executeInSession(Session session) { // Making sure the revision data is persisted. - Object currentRevisionData = getCurrentRevisionData(session, true); + final Object currentRevisionData = getCurrentRevisionData( session, true ); - AuditWorkUnit vwu; + AuditWorkUnit vwu; - // First undoing any performed work units - while ((vwu = undoQueue.poll()) != null) { - vwu.undo(session); - } + // First undoing any performed work units + while ( (vwu = undoQueue.poll()) != null ) { + vwu.undo( session ); + } - while ((vwu = workUnits.poll()) != null) { - vwu.perform(session, revisionData); - entityChangeNotifier.entityChanged(session, currentRevisionData, vwu); - } - } + while ( (vwu = workUnits.poll()) != null ) { + vwu.perform( session, revisionData ); + entityChangeNotifier.entityChanged( session, currentRevisionData, vwu ); + } + } public Object getCurrentRevisionData(Session session, boolean persist) { // Generating the revision data if not yet generated - if (revisionData == null) { - revisionData = revisionInfoGenerator.generate(); - } + if ( revisionData == null ) { + revisionData = revisionInfoGenerator.generate(); + } // Saving the revision data, if not yet saved and persist is true - if (!session.contains(revisionData) && persist) { - revisionInfoGenerator.saveRevisionData(session, revisionData); + if ( !session.contains( revisionData ) && persist ) { + revisionInfoGenerator.saveRevisionData( session, revisionData ); } return revisionData; } - public void doBeforeTransactionCompletion(SessionImplementor session) { - if (workUnits.size() == 0 && undoQueue.size() == 0) { - return; - } + @Override + public void doBeforeTransactionCompletion(SessionImplementor session) { + if ( workUnits.size() == 0 && undoQueue.size() == 0 ) { + return; + } - // see: http://www.jboss.com/index.html?module=bb&op=viewtopic&p=4178431 - if (FlushMode.isManualFlushMode(session.getFlushMode())) { - Session temporarySession = null; - try { - temporarySession = ((Session) session).sessionWithOptions().transactionContext().autoClose(false) - .connectionReleaseMode(ConnectionReleaseMode.AFTER_TRANSACTION) - .openSession(); - executeInSession(temporarySession); - temporarySession.flush(); - } finally { - if (temporarySession != null) { - temporarySession.close(); - } - } - } else { - executeInSession((Session) session); + // see: http://www.jboss.com/index.html?module=bb&op=viewtopic&p=4178431 + if ( FlushMode.isManualFlushMode( session.getFlushMode() ) ) { + Session temporarySession = null; + try { + temporarySession = ((Session) session).sessionWithOptions().transactionContext().autoClose( false ) + .connectionReleaseMode( ConnectionReleaseMode.AFTER_TRANSACTION ) + .openSession(); + executeInSession( temporarySession ); + temporarySession.flush(); + } + finally { + if ( temporarySession != null ) { + temporarySession.close(); + } + } + } + else { + executeInSession( (Session) session ); - // Explicitly flushing the session, as the auto-flush may have already happened. - session.flush(); - } - } + // Explicitly flushing the session, as the auto-flush may have already happened. + session.flush(); + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/AuditProcessManager.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/AuditProcessManager.java index 7786d0970e..5e3b577495 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/AuditProcessManager.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/AuditProcessManager.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.synchronization; + import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -36,23 +37,23 @@ import org.hibernate.event.spi.EventSource; * @author Adam Warski (adam at warski dot org) */ public class AuditProcessManager { - private final Map auditProcesses; - private final RevisionInfoGenerator revisionInfoGenerator; + private final Map auditProcesses; + private final RevisionInfoGenerator revisionInfoGenerator; - public AuditProcessManager(RevisionInfoGenerator revisionInfoGenerator) { - auditProcesses = new ConcurrentHashMap(); + public AuditProcessManager(RevisionInfoGenerator revisionInfoGenerator) { + auditProcesses = new ConcurrentHashMap(); - this.revisionInfoGenerator = revisionInfoGenerator; - } + this.revisionInfoGenerator = revisionInfoGenerator; + } - public AuditProcess get(EventSource session) { - final Transaction transaction = session.getTransaction(); - - AuditProcess auditProcess = auditProcesses.get(transaction); - if (auditProcess == null) { - // No worries about registering a transaction twice - a transaction is single thread - auditProcess = new AuditProcess(revisionInfoGenerator, session); - auditProcesses.put(transaction, auditProcess); + public AuditProcess get(EventSource session) { + final Transaction transaction = session.getTransaction(); + + AuditProcess auditProcess = auditProcesses.get( transaction ); + if ( auditProcess == null ) { + // No worries about registering a transaction twice - a transaction is single thread + auditProcess = new AuditProcess( revisionInfoGenerator, session ); + auditProcesses.put( transaction, auditProcess ); session.getActionQueue().registerProcess( new BeforeTransactionCompletionProcess() { @@ -65,13 +66,15 @@ public class AuditProcessManager { } ); - session.getActionQueue().registerProcess(new AfterTransactionCompletionProcess() { - public void doAfterTransactionCompletion(boolean success, SessionImplementor session) { - auditProcesses.remove(transaction); - } - }); - } + session.getActionQueue().registerProcess( + new AfterTransactionCompletionProcess() { + public void doAfterTransactionCompletion(boolean success, SessionImplementor session) { + auditProcesses.remove( transaction ); + } + } + ); + } - return auditProcess; - } + return auditProcess; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/EntityChangeNotifier.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/EntityChangeNotifier.java index c9dc6cad76..a8744b8ac1 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/EntityChangeNotifier.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/EntityChangeNotifier.java @@ -1,10 +1,32 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.internal.synchronization; import java.io.Serializable; import org.hibernate.Session; import org.hibernate.engine.spi.SessionImplementor; -import org.hibernate.envers.RevisionType; import org.hibernate.envers.internal.revisioninfo.RevisionInfoGenerator; import org.hibernate.envers.internal.synchronization.work.AuditWorkUnit; import org.hibernate.envers.internal.synchronization.work.PersistentCollectionChangeWorkUnit; @@ -12,32 +34,40 @@ import org.hibernate.envers.internal.tools.EntityTools; /** * Notifies {@link RevisionInfoGenerator} about changes made in the current revision. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class EntityChangeNotifier { - private final RevisionInfoGenerator revisionInfoGenerator; - private final SessionImplementor sessionImplementor; + private final RevisionInfoGenerator revisionInfoGenerator; + private final SessionImplementor sessionImplementor; - public EntityChangeNotifier(RevisionInfoGenerator revisionInfoGenerator, SessionImplementor sessionImplementor) { - this.revisionInfoGenerator = revisionInfoGenerator; - this.sessionImplementor = sessionImplementor; - } + public EntityChangeNotifier(RevisionInfoGenerator revisionInfoGenerator, SessionImplementor sessionImplementor) { + this.revisionInfoGenerator = revisionInfoGenerator; + this.sessionImplementor = sessionImplementor; + } - /** - * Notifies {@link RevisionInfoGenerator} about changes made in the current revision. Provides information - * about modified entity class, entity name and its id, as well as {@link RevisionType} and revision log entity. - * @param session Active session. - * @param currentRevisionData Revision log entity. - * @param vwu Performed work unit. - */ - public void entityChanged(Session session, Object currentRevisionData, AuditWorkUnit vwu) { - Serializable entityId = vwu.getEntityId(); - if (entityId instanceof PersistentCollectionChangeWorkUnit.PersistentCollectionChangeWorkUnitId) { - // Notify about a change in collection owner entity. - entityId = ((PersistentCollectionChangeWorkUnit.PersistentCollectionChangeWorkUnitId) entityId).getOwnerId(); - } - Class entityClass = EntityTools.getEntityClass(sessionImplementor, session, vwu.getEntityName()); - revisionInfoGenerator.entityChanged(entityClass, vwu.getEntityName(), entityId, vwu.getRevisionType(), - currentRevisionData); - } + /** + * Notifies {@link RevisionInfoGenerator} about changes made in the current revision. Provides information + * about modified entity class, entity name and its id, as well as {@link org.hibernate.envers.RevisionType} + * and revision log entity. + * + * @param session Active session. + * @param currentRevisionData Revision log entity. + * @param vwu Performed work unit. + */ + public void entityChanged(Session session, Object currentRevisionData, AuditWorkUnit vwu) { + Serializable entityId = vwu.getEntityId(); + if ( entityId instanceof PersistentCollectionChangeWorkUnit.PersistentCollectionChangeWorkUnitId ) { + // Notify about a change in collection owner entity. + entityId = ((PersistentCollectionChangeWorkUnit.PersistentCollectionChangeWorkUnitId) entityId).getOwnerId(); + } + final Class entityClass = EntityTools.getEntityClass( sessionImplementor, session, vwu.getEntityName() ); + revisionInfoGenerator.entityChanged( + entityClass, + vwu.getEntityName(), + entityId, + vwu.getRevisionType(), + currentRevisionData + ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/SessionCacheCleaner.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/SessionCacheCleaner.java index 4c9c8c40fe..ed465a3707 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/SessionCacheCleaner.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/SessionCacheCleaner.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.internal.synchronization; import org.hibernate.Session; @@ -8,22 +31,26 @@ import org.hibernate.event.spi.EventSource; /** * Class responsible for evicting audit data entries that have been stored in the session level cache. * This operation increases Envers performance in case of massive entity updates without clearing persistence context. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class SessionCacheCleaner { - /** - * Schedules audit data removal from session level cache after transaction completion. The operation is performed - * regardless of commit success. - * @param session Active Hibernate session. - * @param data Audit data that shall be evicted (e.g. revision data or entity snapshot) - */ - public void scheduleAuditDataRemoval(final Session session, final Object data) { - ((EventSource) session).getActionQueue().registerProcess(new AfterTransactionCompletionProcess() { - public void doAfterTransactionCompletion(boolean success, SessionImplementor session) { - if (!session.isClosed()) { - ((Session) session).evict(data); - } - } - }); - } + /** + * Schedules audit data removal from session level cache after transaction completion. The operation is performed + * regardless of commit success. + * + * @param session Active Hibernate session. + * @param data Audit data that shall be evicted (e.g. revision data or entity snapshot) + */ + public void scheduleAuditDataRemoval(final Session session, final Object data) { + ((EventSource) session).getActionQueue().registerProcess( + new AfterTransactionCompletionProcess() { + public void doAfterTransactionCompletion(boolean success, SessionImplementor session) { + if ( !session.isClosed() ) { + ((Session) session).evict( data ); + } + } + } + ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/AbstractAuditWorkUnit.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/AbstractAuditWorkUnit.java index 29bd8ce032..4c58b34f46 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/AbstractAuditWorkUnit.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/AbstractAuditWorkUnit.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -41,67 +41,73 @@ import org.hibernate.envers.strategy.AuditStrategy; */ public abstract class AbstractAuditWorkUnit implements AuditWorkUnit { protected final SessionImplementor sessionImplementor; - protected final AuditConfiguration verCfg; - protected final Serializable id; - protected final String entityName; - protected final AuditStrategy auditStrategy; - protected final RevisionType revisionType; + protected final AuditConfiguration verCfg; + protected final Serializable id; + protected final String entityName; + protected final AuditStrategy auditStrategy; + protected final RevisionType revisionType; - private Object performedData; + private Object performedData; - protected AbstractAuditWorkUnit(SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg, - Serializable id, RevisionType revisionType) { + protected AbstractAuditWorkUnit( + SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg, + Serializable id, RevisionType revisionType) { this.sessionImplementor = sessionImplementor; - this.verCfg = verCfg; - this.id = id; - this.entityName = entityName; - this.revisionType = revisionType; - this.auditStrategy = verCfg.getAuditStrategy(); - } + this.verCfg = verCfg; + this.id = id; + this.entityName = entityName; + this.revisionType = revisionType; + this.auditStrategy = verCfg.getAuditStrategy(); + } - protected void fillDataWithId(Map data, Object revision) { - AuditEntitiesConfiguration entitiesCfg = verCfg.getAuditEntCfg(); + protected void fillDataWithId(Map data, Object revision) { + final AuditEntitiesConfiguration entitiesCfg = verCfg.getAuditEntCfg(); - Map originalId = new HashMap(); - originalId.put(entitiesCfg.getRevisionFieldName(), revision); + final Map originalId = new HashMap(); + originalId.put( entitiesCfg.getRevisionFieldName(), revision ); - verCfg.getEntCfg().get(getEntityName()).getIdMapper().mapToMapFromId(originalId, id); - data.put(entitiesCfg.getRevisionTypePropName(), revisionType); - data.put(entitiesCfg.getOriginalIdPropName(), originalId); - } + verCfg.getEntCfg().get( getEntityName() ).getIdMapper().mapToMapFromId( originalId, id ); + data.put( entitiesCfg.getRevisionTypePropName(), revisionType ); + data.put( entitiesCfg.getOriginalIdPropName(), originalId ); + } - public void perform(Session session, Object revisionData) { - Map data = generateData(revisionData); + @Override + public void perform(Session session, Object revisionData) { + final Map data = generateData( revisionData ); - auditStrategy.perform(session, getEntityName(), verCfg, id, data, revisionData); + auditStrategy.perform( session, getEntityName(), verCfg, id, data, revisionData ); - setPerformed(data); - } + setPerformed( data ); + } - public Serializable getEntityId() { - return id; - } + @Override + public Serializable getEntityId() { + return id; + } - public boolean isPerformed() { - return performedData != null; - } + @Override + public boolean isPerformed() { + return performedData != null; + } - public String getEntityName() { - return entityName; - } + @Override + public String getEntityName() { + return entityName; + } - protected void setPerformed(Object performedData) { - this.performedData = performedData; - } + protected void setPerformed(Object performedData) { + this.performedData = performedData; + } - public void undo(Session session) { - if (isPerformed()) { - session.delete(verCfg.getAuditEntCfg().getAuditEntityName(getEntityName()), performedData); - session.flush(); - } - } + public void undo(Session session) { + if ( isPerformed() ) { + session.delete( verCfg.getAuditEntCfg().getAuditEntityName( getEntityName() ), performedData ); + session.flush(); + } + } - public RevisionType getRevisionType() { - return revisionType; - } + @Override + public RevisionType getRevisionType() { + return revisionType; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/AddWorkUnit.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/AddWorkUnit.java index 2650661ae7..e36a021665 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/AddWorkUnit.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/AddWorkUnit.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -38,63 +38,77 @@ import org.hibernate.persister.entity.EntityPersister; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class AddWorkUnit extends AbstractAuditWorkUnit implements AuditWorkUnit { - private final Object[] state; - private final Map data; + private final Object[] state; + private final Map data; - public AddWorkUnit(SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg, - Serializable id, EntityPersister entityPersister, Object[] state) { - super(sessionImplementor, entityName, verCfg, id, RevisionType.ADD); + public AddWorkUnit( + SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg, + Serializable id, EntityPersister entityPersister, Object[] state) { + super( sessionImplementor, entityName, verCfg, id, RevisionType.ADD ); - this.data = new HashMap(); - this.state = state; - this.verCfg.getEntCfg().get(getEntityName()).getPropertyMapper().map(sessionImplementor, data, - entityPersister.getPropertyNames(), state, null); - } + this.data = new HashMap(); + this.state = state; + this.verCfg.getEntCfg().get( getEntityName() ).getPropertyMapper().map( + sessionImplementor, data, + entityPersister.getPropertyNames(), state, null + ); + } - public AddWorkUnit(SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg, - Serializable id, Map data) { - super(sessionImplementor, entityName, verCfg, id, RevisionType.ADD); + public AddWorkUnit( + SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg, + Serializable id, Map data) { + super( sessionImplementor, entityName, verCfg, id, RevisionType.ADD ); - this.data = data; - final String[] propertyNames = sessionImplementor.getFactory().getEntityPersister(getEntityName()).getPropertyNames(); - this.state = ArraysTools.mapToArray(data, propertyNames); - } + this.data = data; + final String[] propertyNames = sessionImplementor.getFactory() + .getEntityPersister( getEntityName() ) + .getPropertyNames(); + this.state = ArraysTools.mapToArray( data, propertyNames ); + } - public boolean containsWork() { - return true; - } + @Override + public boolean containsWork() { + return true; + } - public Map generateData(Object revisionData) { - fillDataWithId(data, revisionData); - return data; - } + @Override + public Map generateData(Object revisionData) { + fillDataWithId( data, revisionData ); + return data; + } - public Object[] getState() { - return state; - } + public Object[] getState() { + return state; + } - public AuditWorkUnit merge(AddWorkUnit second) { - return second; - } + @Override + public AuditWorkUnit merge(AddWorkUnit second) { + return second; + } - public AuditWorkUnit merge(ModWorkUnit second) { - return new AddWorkUnit(sessionImplementor, entityName, verCfg, id, second.getData()); - } + @Override + public AuditWorkUnit merge(ModWorkUnit second) { + return new AddWorkUnit( sessionImplementor, entityName, verCfg, id, second.getData() ); + } - public AuditWorkUnit merge(DelWorkUnit second) { - return null; - } + @Override + public AuditWorkUnit merge(DelWorkUnit second) { + return null; + } - public AuditWorkUnit merge(CollectionChangeWorkUnit second) { - second.mergeCollectionModifiedData(data); + @Override + public AuditWorkUnit merge(CollectionChangeWorkUnit second) { + second.mergeCollectionModifiedData( data ); return this; } - public AuditWorkUnit merge(FakeBidirectionalRelationWorkUnit second) { - return FakeBidirectionalRelationWorkUnit.merge(second, this, second.getNestedWorkUnit()); - } + @Override + public AuditWorkUnit merge(FakeBidirectionalRelationWorkUnit second) { + return FakeBidirectionalRelationWorkUnit.merge( second, this, second.getNestedWorkUnit() ); + } - public AuditWorkUnit dispatch(WorkUnitMergeVisitor first) { - return first.merge(this); - } + @Override + public AuditWorkUnit dispatch(WorkUnitMergeVisitor first) { + return first.merge( this ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/AuditWorkUnit.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/AuditWorkUnit.java index f247f21bee..1912b51353 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/AuditWorkUnit.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/AuditWorkUnit.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.synchronization.work; + import java.io.Serializable; import java.util.Map; @@ -30,34 +31,39 @@ import org.hibernate.envers.RevisionType; /** * TODO: refactor constructors into factory methods + * * @author Adam Warski (adam at warski dot org) */ public interface AuditWorkUnit extends WorkUnitMergeVisitor, WorkUnitMergeDispatcher { - Serializable getEntityId(); - String getEntityName(); - - boolean containsWork(); + Serializable getEntityId(); - boolean isPerformed(); + String getEntityName(); - /** - * Perform this work unit in the given session. - * @param session Session, in which the work unit should be performed. - * @param revisionData The current revision data, which will be used to populate the work unit with the correct - * revision relation. - */ - void perform(Session session, Object revisionData); - void undo(Session session); + boolean containsWork(); - /** - * @param revisionData The current revision data, which will be used to populate the work unit with the correct - * revision relation. - * @return Generates data that should be saved when performing this work unit. - */ - Map generateData(Object revisionData); + boolean isPerformed(); - /** - * @return Performed modification type. - */ - RevisionType getRevisionType(); + /** + * Perform this work unit in the given session. + * + * @param session Session, in which the work unit should be performed. + * @param revisionData The current revision data, which will be used to populate the work unit with the correct + * revision relation. + */ + void perform(Session session, Object revisionData); + + void undo(Session session); + + /** + * @param revisionData The current revision data, which will be used to populate the work unit with the correct + * revision relation. + * + * @return Generates data that should be saved when performing this work unit. + */ + Map generateData(Object revisionData); + + /** + * @return Performed modification type. + */ + RevisionType getRevisionType(); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/CollectionChangeWorkUnit.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/CollectionChangeWorkUnit.java index eb06f1f8c1..3bc9cb0aed 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/CollectionChangeWorkUnit.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/CollectionChangeWorkUnit.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -36,64 +36,74 @@ import org.hibernate.envers.configuration.spi.AuditConfiguration; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class CollectionChangeWorkUnit extends AbstractAuditWorkUnit implements AuditWorkUnit { - private Object entity; + private Object entity; private final String collectionPropertyName; private final Map data = new HashMap(); - public CollectionChangeWorkUnit(SessionImplementor session, String entityName, String collectionPropertyName, - AuditConfiguration verCfg, Serializable id, Object entity) { - super(session, entityName, verCfg, id, RevisionType.MOD); + public CollectionChangeWorkUnit( + SessionImplementor session, String entityName, String collectionPropertyName, + AuditConfiguration verCfg, Serializable id, Object entity) { + super( session, entityName, verCfg, id, RevisionType.MOD ); - this.entity = entity; + this.entity = entity; this.collectionPropertyName = collectionPropertyName; - } - - public boolean containsWork() { - return true; - } - - public Map generateData(Object revisionData) { - fillDataWithId(data, revisionData); - Map preGenerateData = new HashMap(data); - verCfg.getEntCfg().get(getEntityName()).getPropertyMapper() - .mapToMapFromEntity(sessionImplementor, data, entity, null); - verCfg.getEntCfg().get(getEntityName()).getPropertyMapper() - .mapModifiedFlagsToMapFromEntity(sessionImplementor, data, entity, entity); - verCfg.getEntCfg().get(getEntityName()).getPropertyMapper() - .mapModifiedFlagsToMapForCollectionChange(collectionPropertyName, data); - data.putAll(preGenerateData); - return data; - } - - public void mergeCollectionModifiedData(Map data) { - verCfg.getEntCfg().get(getEntityName()).getPropertyMapper() - .mapModifiedFlagsToMapForCollectionChange( - collectionPropertyName, data); } + @Override + public boolean containsWork() { + return true; + } + + @Override + public Map generateData(Object revisionData) { + fillDataWithId( data, revisionData ); + final Map preGenerateData = new HashMap( data ); + verCfg.getEntCfg().get( getEntityName() ).getPropertyMapper() + .mapToMapFromEntity( sessionImplementor, data, entity, null ); + verCfg.getEntCfg().get( getEntityName() ).getPropertyMapper() + .mapModifiedFlagsToMapFromEntity( sessionImplementor, data, entity, entity ); + verCfg.getEntCfg().get( getEntityName() ).getPropertyMapper() + .mapModifiedFlagsToMapForCollectionChange( collectionPropertyName, data ); + data.putAll( preGenerateData ); + return data; + } + + public void mergeCollectionModifiedData(Map data) { + verCfg.getEntCfg().get( getEntityName() ).getPropertyMapper().mapModifiedFlagsToMapForCollectionChange( + collectionPropertyName, + data + ); + } + + @Override public AuditWorkUnit merge(AddWorkUnit second) { - return second; - } + return second; + } - public AuditWorkUnit merge(ModWorkUnit second) { - mergeCollectionModifiedData(second.getData()); - return second; - } + @Override + public AuditWorkUnit merge(ModWorkUnit second) { + mergeCollectionModifiedData( second.getData() ); + return second; + } - public AuditWorkUnit merge(DelWorkUnit second) { - return second; - } + @Override + public AuditWorkUnit merge(DelWorkUnit second) { + return second; + } - public AuditWorkUnit merge(CollectionChangeWorkUnit second) { - second.mergeCollectionModifiedData(data); - return this; - } + @Override + public AuditWorkUnit merge(CollectionChangeWorkUnit second) { + second.mergeCollectionModifiedData( data ); + return this; + } - public AuditWorkUnit merge(FakeBidirectionalRelationWorkUnit second) { - return second; - } + @Override + public AuditWorkUnit merge(FakeBidirectionalRelationWorkUnit second) { + return second; + } - public AuditWorkUnit dispatch(WorkUnitMergeVisitor first) { - return first.merge(this); - } + @Override + public AuditWorkUnit dispatch(WorkUnitMergeVisitor first) { + return first.merge( this ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/DelWorkUnit.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/DelWorkUnit.java index 2f131f8375..04902e3477 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/DelWorkUnit.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/DelWorkUnit.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -38,62 +38,83 @@ import org.hibernate.persister.entity.EntityPersister; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class DelWorkUnit extends AbstractAuditWorkUnit implements AuditWorkUnit { - private final Object[] state; - private final EntityPersister entityPersister; - private final String[] propertyNames; + private final Object[] state; + private final EntityPersister entityPersister; + private final String[] propertyNames; - public DelWorkUnit(SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg, - Serializable id, EntityPersister entityPersister, Object[] state) { - super(sessionImplementor, entityName, verCfg, id, RevisionType.DEL); + public DelWorkUnit( + SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg, + Serializable id, EntityPersister entityPersister, Object[] state) { + super( sessionImplementor, entityName, verCfg, id, RevisionType.DEL ); - this.state = state; - this.entityPersister = entityPersister; - this.propertyNames = entityPersister.getPropertyNames(); - } + this.state = state; + this.entityPersister = entityPersister; + this.propertyNames = entityPersister.getPropertyNames(); + } - public boolean containsWork() { - return true; - } + @Override + public boolean containsWork() { + return true; + } - public Map generateData(Object revisionData) { - Map data = new HashMap(); - fillDataWithId(data, revisionData); + @Override + public Map generateData(Object revisionData) { + final Map data = new HashMap(); + fillDataWithId( data, revisionData ); - if (verCfg.getGlobalCfg().isStoreDataAtDelete()) { - verCfg.getEntCfg().get(getEntityName()).getPropertyMapper().map(sessionImplementor, data, - propertyNames, state, state); - } else { - verCfg.getEntCfg().get(getEntityName()).getPropertyMapper().map(sessionImplementor, data, - propertyNames, null, state); + if ( verCfg.getGlobalCfg().isStoreDataAtDelete() ) { + verCfg.getEntCfg().get( getEntityName() ).getPropertyMapper().map( + sessionImplementor, + data, + propertyNames, + state, + state + ); + } + else { + verCfg.getEntCfg().get( getEntityName() ).getPropertyMapper().map( + sessionImplementor, + data, + propertyNames, + null, + state + ); } - return data; - } + return data; + } - public AuditWorkUnit merge(AddWorkUnit second) { - if (ArraysTools.arraysEqual(second.getState(), state)) { - return null; // Return null if object's state has not changed. - } - return new ModWorkUnit(sessionImplementor, entityName, verCfg, id, entityPersister, second.getState(), state); - } + @Override + public AuditWorkUnit merge(AddWorkUnit second) { + if ( ArraysTools.arraysEqual( second.getState(), state ) ) { + // Return null if object's state has not changed. + return null; + } + return new ModWorkUnit( sessionImplementor, entityName, verCfg, id, entityPersister, second.getState(), state ); + } - public AuditWorkUnit merge(ModWorkUnit second) { - return null; - } + @Override + public AuditWorkUnit merge(ModWorkUnit second) { + return null; + } - public AuditWorkUnit merge(DelWorkUnit second) { - return this; - } + @Override + public AuditWorkUnit merge(DelWorkUnit second) { + return this; + } - public AuditWorkUnit merge(CollectionChangeWorkUnit second) { - return this; - } + @Override + public AuditWorkUnit merge(CollectionChangeWorkUnit second) { + return this; + } - public AuditWorkUnit merge(FakeBidirectionalRelationWorkUnit second) { - return this; - } + @Override + public AuditWorkUnit merge(FakeBidirectionalRelationWorkUnit second) { + return this; + } - public AuditWorkUnit dispatch(WorkUnitMergeVisitor first) { - return first.merge(this); - } + @Override + public AuditWorkUnit dispatch(WorkUnitMergeVisitor first) { + return first.merge( this ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/FakeBidirectionalRelationWorkUnit.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/FakeBidirectionalRelationWorkUnit.java index f5c5f58e3d..2a915c8bbf 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/FakeBidirectionalRelationWorkUnit.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/FakeBidirectionalRelationWorkUnit.java @@ -1,4 +1,28 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.internal.synchronization.work; + import java.io.Serializable; import java.util.HashMap; import java.util.HashSet; @@ -13,174 +37,211 @@ import org.hibernate.envers.internal.entities.RelationDescription; /** * A work unit that handles "fake" bidirectional one-to-many relations (mapped with {@code @OneToMany+@JoinColumn} and * {@code @ManyToOne+@Column(insertable=false, updatable=false)}. + * * @author Adam Warski (adam at warski dot org) */ public class FakeBidirectionalRelationWorkUnit extends AbstractAuditWorkUnit implements AuditWorkUnit { - private final Map fakeRelationChanges; + private final Map fakeRelationChanges; - /* - * The work unit responsible for generating the "raw" entity data to be saved. - */ - private final AuditWorkUnit nestedWorkUnit; + /* + * The work unit responsible for generating the "raw" entity data to be saved. + */ + private final AuditWorkUnit nestedWorkUnit; - public FakeBidirectionalRelationWorkUnit(SessionImplementor sessionImplementor, String entityName, - AuditConfiguration verCfg, Serializable id, - String referencingPropertyName, Object owningEntity, - RelationDescription rd, RevisionType revisionType, - Object index, - AuditWorkUnit nestedWorkUnit) { - super(sessionImplementor, entityName, verCfg, id, revisionType); - this.nestedWorkUnit = nestedWorkUnit; + public FakeBidirectionalRelationWorkUnit( + SessionImplementor sessionImplementor, String entityName, + AuditConfiguration verCfg, Serializable id, + String referencingPropertyName, Object owningEntity, + RelationDescription rd, RevisionType revisionType, + Object index, + AuditWorkUnit nestedWorkUnit) { + super( sessionImplementor, entityName, verCfg, id, revisionType ); + this.nestedWorkUnit = nestedWorkUnit; - // Adding the change for the relation. - fakeRelationChanges = new HashMap(); - fakeRelationChanges.put(referencingPropertyName, new FakeRelationChange(owningEntity, rd, revisionType, index)); - } + // Adding the change for the relation. + fakeRelationChanges = new HashMap(); + fakeRelationChanges.put( + referencingPropertyName, new FakeRelationChange( + owningEntity, + rd, + revisionType, + index + ) + ); + } - public FakeBidirectionalRelationWorkUnit(FakeBidirectionalRelationWorkUnit original, - Map fakeRelationChanges, - AuditWorkUnit nestedWorkUnit) { - super(original.sessionImplementor, original.entityName, original.verCfg, original.id, original.revisionType); + public FakeBidirectionalRelationWorkUnit( + FakeBidirectionalRelationWorkUnit original, + Map fakeRelationChanges, + AuditWorkUnit nestedWorkUnit) { + super( original.sessionImplementor, original.entityName, original.verCfg, original.id, original.revisionType ); - this.fakeRelationChanges = fakeRelationChanges; - this.nestedWorkUnit = nestedWorkUnit; - } + this.fakeRelationChanges = fakeRelationChanges; + this.nestedWorkUnit = nestedWorkUnit; + } - public FakeBidirectionalRelationWorkUnit(FakeBidirectionalRelationWorkUnit original, AuditWorkUnit nestedWorkUnit) { - super(original.sessionImplementor, original.entityName, original.verCfg, original.id, original.revisionType); + public FakeBidirectionalRelationWorkUnit(FakeBidirectionalRelationWorkUnit original, AuditWorkUnit nestedWorkUnit) { + super( original.sessionImplementor, original.entityName, original.verCfg, original.id, original.revisionType ); - this.nestedWorkUnit = nestedWorkUnit; + this.nestedWorkUnit = nestedWorkUnit; - fakeRelationChanges = new HashMap(original.getFakeRelationChanges()); - } + fakeRelationChanges = new HashMap( original.getFakeRelationChanges() ); + } - public AuditWorkUnit getNestedWorkUnit() { - return nestedWorkUnit; - } + public AuditWorkUnit getNestedWorkUnit() { + return nestedWorkUnit; + } - public Map getFakeRelationChanges() { - return fakeRelationChanges; - } + public Map getFakeRelationChanges() { + return fakeRelationChanges; + } - public boolean containsWork() { - return true; - } + @Override + public boolean containsWork() { + return true; + } - public Map generateData(Object revisionData) { - // Generating data with the nested work unit. This data contains all data except the fake relation. - // Making a defensive copy not to modify the data held by the nested work unit. - Map nestedData = new HashMap(nestedWorkUnit.generateData(revisionData)); + @Override + public Map generateData(Object revisionData) { + // Generating data with the nested work unit. This data contains all data except the fake relation. + // Making a defensive copy not to modify the data held by the nested work unit. + final Map nestedData = new HashMap( nestedWorkUnit.generateData( revisionData ) ); - // Now adding data for all fake relations. - for (FakeRelationChange fakeRelationChange : fakeRelationChanges.values()) { - fakeRelationChange.generateData(sessionImplementor, nestedData); - } + // Now adding data for all fake relations. + for ( FakeRelationChange fakeRelationChange : fakeRelationChanges.values() ) { + fakeRelationChange.generateData( sessionImplementor, nestedData ); + } - return nestedData; - } + return nestedData; + } - public AuditWorkUnit merge(AddWorkUnit second) { - return merge(this, nestedWorkUnit, second); - } + @Override + public AuditWorkUnit merge(AddWorkUnit second) { + return merge( this, nestedWorkUnit, second ); + } - public AuditWorkUnit merge(ModWorkUnit second) { - return merge(this, nestedWorkUnit, second); - } + @Override + public AuditWorkUnit merge(ModWorkUnit second) { + return merge( this, nestedWorkUnit, second ); + } - public AuditWorkUnit merge(DelWorkUnit second) { - return second; - } + @Override + public AuditWorkUnit merge(DelWorkUnit second) { + return second; + } - public AuditWorkUnit merge(CollectionChangeWorkUnit second) { - return this; - } + @Override + public AuditWorkUnit merge(CollectionChangeWorkUnit second) { + return this; + } - public AuditWorkUnit merge(FakeBidirectionalRelationWorkUnit second) { - // First merging the nested work units. - AuditWorkUnit mergedNested = second.getNestedWorkUnit().dispatch(nestedWorkUnit); + @Override + public AuditWorkUnit merge(FakeBidirectionalRelationWorkUnit second) { + // First merging the nested work units. + final AuditWorkUnit mergedNested = second.getNestedWorkUnit().dispatch( nestedWorkUnit ); - // Now merging the fake relation changes from both work units. - Map secondFakeRelationChanges = second.getFakeRelationChanges(); - Map mergedFakeRelationChanges = new HashMap(); - Set allPropertyNames = new HashSet(fakeRelationChanges.keySet()); - allPropertyNames.addAll(secondFakeRelationChanges.keySet()); + // Now merging the fake relation changes from both work units. + final Map secondFakeRelationChanges = second.getFakeRelationChanges(); + final Map mergedFakeRelationChanges = new HashMap(); + final Set allPropertyNames = new HashSet( fakeRelationChanges.keySet() ); + allPropertyNames.addAll( secondFakeRelationChanges.keySet() ); - for (String propertyName : allPropertyNames) { - mergedFakeRelationChanges.put(propertyName, - FakeRelationChange.merge( - fakeRelationChanges.get(propertyName), - secondFakeRelationChanges.get(propertyName))); - } + for ( String propertyName : allPropertyNames ) { + mergedFakeRelationChanges.put( + propertyName, + FakeRelationChange.merge( + fakeRelationChanges.get( propertyName ), + secondFakeRelationChanges.get( propertyName ) + ) + ); + } - return new FakeBidirectionalRelationWorkUnit(this, mergedFakeRelationChanges, mergedNested); - } + return new FakeBidirectionalRelationWorkUnit( this, mergedFakeRelationChanges, mergedNested ); + } - public AuditWorkUnit dispatch(WorkUnitMergeVisitor first) { - return first.merge(this); - } + @Override + public AuditWorkUnit dispatch(WorkUnitMergeVisitor first) { + return first.merge( this ); + } - public static AuditWorkUnit merge(FakeBidirectionalRelationWorkUnit frwu, AuditWorkUnit nestedFirst, - AuditWorkUnit nestedSecond) { - AuditWorkUnit nestedMerged = nestedSecond.dispatch(nestedFirst); + public static AuditWorkUnit merge( + FakeBidirectionalRelationWorkUnit frwu, + AuditWorkUnit nestedFirst, + AuditWorkUnit nestedSecond) { + final AuditWorkUnit nestedMerged = nestedSecond.dispatch( nestedFirst ); - // Creating a new fake relation work unit with the nested merged data - return new FakeBidirectionalRelationWorkUnit(frwu, nestedMerged); - } + // Creating a new fake relation work unit with the nested merged data + return new FakeBidirectionalRelationWorkUnit( frwu, nestedMerged ); + } - /** - * Describes a change to a single fake bidirectional relation. - */ - private static class FakeRelationChange { - private final Object owningEntity; - private final RelationDescription rd; - private final RevisionType revisionType; - private final Object index; + /** + * Describes a change to a single fake bidirectional relation. + */ + private static class FakeRelationChange { + private final Object owningEntity; + private final RelationDescription rd; + private final RevisionType revisionType; + private final Object index; - public FakeRelationChange(Object owningEntity, RelationDescription rd, RevisionType revisionType, - Object index) { - this.owningEntity = owningEntity; - this.rd = rd; - this.revisionType = revisionType; - this.index = index; - } + public FakeRelationChange( + Object owningEntity, RelationDescription rd, RevisionType revisionType, + Object index) { + this.owningEntity = owningEntity; + this.rd = rd; + this.revisionType = revisionType; + this.index = index; + } - public RevisionType getRevisionType() { - return revisionType; - } + public RevisionType getRevisionType() { + return revisionType; + } - public void generateData(SessionImplementor sessionImplementor, Map data) { - // If the revision type is "DEL", it means that the object is removed from the collection. Then the - // new owner will in fact be null. - rd.getFakeBidirectionalRelationMapper().mapToMapFromEntity(sessionImplementor, data, - revisionType == RevisionType.DEL ? null : owningEntity, null); - rd.getFakeBidirectionalRelationMapper().mapModifiedFlagsToMapFromEntity(sessionImplementor, data, - revisionType == RevisionType.DEL ? null : owningEntity, null); + public void generateData(SessionImplementor sessionImplementor, Map data) { + // If the revision type is "DEL", it means that the object is removed from the collection. Then the + // new owner will in fact be null. + rd.getFakeBidirectionalRelationMapper().mapToMapFromEntity( + sessionImplementor, data, + revisionType == RevisionType.DEL ? null : owningEntity, null + ); + rd.getFakeBidirectionalRelationMapper().mapModifiedFlagsToMapFromEntity( + sessionImplementor, data, + revisionType == RevisionType.DEL ? null : owningEntity, null + ); // Also mapping the index, if the collection is indexed. - if (rd.getFakeBidirectionalRelationIndexMapper() != null) { - rd.getFakeBidirectionalRelationIndexMapper().mapToMapFromEntity(sessionImplementor, data, - revisionType == RevisionType.DEL ? null : index, null); - rd.getFakeBidirectionalRelationIndexMapper().mapModifiedFlagsToMapFromEntity(sessionImplementor, data, - revisionType == RevisionType.DEL ? null : index, null); - } - } + if ( rd.getFakeBidirectionalRelationIndexMapper() != null ) { + rd.getFakeBidirectionalRelationIndexMapper().mapToMapFromEntity( + sessionImplementor, data, + revisionType == RevisionType.DEL ? null : index, null + ); + rd.getFakeBidirectionalRelationIndexMapper().mapModifiedFlagsToMapFromEntity( + sessionImplementor, data, + revisionType == RevisionType.DEL ? null : index, null + ); + } + } - public static FakeRelationChange merge(FakeRelationChange first, FakeRelationChange second) { - if (first == null) { return second; } - if (second == null) { return first; } + public static FakeRelationChange merge(FakeRelationChange first, FakeRelationChange second) { + if ( first == null ) { + return second; + } + if ( second == null ) { + return first; + } /* - * The merging rules are the following (revision types of the first and second changes): + * The merging rules are the following (revision types of the first and second changes): * - DEL, DEL - return any (the work units are the same) * - DEL, ADD - return ADD (points to new owner) * - ADD, DEL - return ADD (points to new owner) * - ADD, ADD - return second (points to newer owner) */ - if (first.getRevisionType() == RevisionType.DEL || second.getRevisionType() == RevisionType.ADD) { - return second; - } else { - return first; - } - } - } + if ( first.getRevisionType() == RevisionType.DEL || second.getRevisionType() == RevisionType.ADD ) { + return second; + } + else { + return first; + } + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/ModWorkUnit.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/ModWorkUnit.java index 77129d9c6a..c8c2f7731c 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/ModWorkUnit.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/ModWorkUnit.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -36,66 +36,77 @@ import org.hibernate.persister.entity.EntityPersister; * @author Adam Warski (adam at warski dot org) */ public class ModWorkUnit extends AbstractAuditWorkUnit implements AuditWorkUnit { - private final Map data; - private final boolean changes; + private final Map data; + private final boolean changes; - private final EntityPersister entityPersister; - private final Object[] oldState; - private final Object[] newState; + private final EntityPersister entityPersister; + private final Object[] oldState; + private final Object[] newState; - public ModWorkUnit(SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg, - Serializable id, EntityPersister entityPersister, Object[] newState, Object[] oldState) { - super(sessionImplementor, entityName, verCfg, id, RevisionType.MOD); + public ModWorkUnit( + SessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg, + Serializable id, EntityPersister entityPersister, Object[] newState, Object[] oldState) { + super( sessionImplementor, entityName, verCfg, id, RevisionType.MOD ); - this.entityPersister = entityPersister; - this.oldState = oldState; - this.newState = newState; - data = new HashMap(); - changes = verCfg.getEntCfg().get(getEntityName()).getPropertyMapper().map(sessionImplementor, data, - entityPersister.getPropertyNames(), newState, oldState); - } + this.entityPersister = entityPersister; + this.oldState = oldState; + this.newState = newState; + data = new HashMap(); + changes = verCfg.getEntCfg().get( getEntityName() ).getPropertyMapper().map( + sessionImplementor, data, + entityPersister.getPropertyNames(), newState, oldState + ); + } - public boolean containsWork() { - return changes; - } + public Map getData() { + return data; + } - public Map generateData(Object revisionData) { - fillDataWithId(data, revisionData); + @Override + public boolean containsWork() { + return changes; + } - return data; - } + @Override + public Map generateData(Object revisionData) { + fillDataWithId( data, revisionData ); - public Map getData() { - return data; - } + return data; + } - public AuditWorkUnit merge(AddWorkUnit second) { - return this; - } + @Override + public AuditWorkUnit merge(AddWorkUnit second) { + return this; + } - public AuditWorkUnit merge(ModWorkUnit second) { - // In case of multiple subsequent flushes within single transaction, modification flags need to be - // recalculated against initial and final state of the given entity. - return new ModWorkUnit( - second.sessionImplementor, second.getEntityName(), second.verCfg, second.id, - second.entityPersister, second.newState, this.oldState - ); - } + @Override + public AuditWorkUnit merge(ModWorkUnit second) { + // In case of multiple subsequent flushes within single transaction, modification flags need to be + // recalculated against initial and final state of the given entity. + return new ModWorkUnit( + second.sessionImplementor, second.getEntityName(), second.verCfg, second.id, + second.entityPersister, second.newState, this.oldState + ); + } - public AuditWorkUnit merge(DelWorkUnit second) { - return second; - } + @Override + public AuditWorkUnit merge(DelWorkUnit second) { + return second; + } - public AuditWorkUnit merge(CollectionChangeWorkUnit second) { - second.mergeCollectionModifiedData(data); - return this; - } + @Override + public AuditWorkUnit merge(CollectionChangeWorkUnit second) { + second.mergeCollectionModifiedData( data ); + return this; + } - public AuditWorkUnit merge(FakeBidirectionalRelationWorkUnit second) { - return FakeBidirectionalRelationWorkUnit.merge(second, this, second.getNestedWorkUnit()); - } + @Override + public AuditWorkUnit merge(FakeBidirectionalRelationWorkUnit second) { + return FakeBidirectionalRelationWorkUnit.merge( second, this, second.getNestedWorkUnit() ); + } - public AuditWorkUnit dispatch(WorkUnitMergeVisitor first) { - return first.merge(this); - } + @Override + public AuditWorkUnit dispatch(WorkUnitMergeVisitor first) { + return first.merge( this ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/PersistentCollectionChangeWorkUnit.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/PersistentCollectionChangeWorkUnit.java index 6f87f1d19b..73a9125c72 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/PersistentCollectionChangeWorkUnit.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/PersistentCollectionChangeWorkUnit.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -42,171 +42,212 @@ import org.hibernate.envers.internal.entities.mapper.PersistentCollectionChangeD * @author Adam Warski (adam at warski dot org) */ public class PersistentCollectionChangeWorkUnit extends AbstractAuditWorkUnit implements AuditWorkUnit { - private final List collectionChanges; - private final String referencingPropertyName; + private final List collectionChanges; + private final String referencingPropertyName; - public PersistentCollectionChangeWorkUnit(SessionImplementor sessionImplementor, String entityName, - AuditConfiguration auditCfg, PersistentCollection collection, - CollectionEntry collectionEntry, Serializable snapshot, Serializable id, - String referencingPropertyName) { - super(sessionImplementor, entityName, auditCfg, new PersistentCollectionChangeWorkUnitId(id, collectionEntry.getRole()), RevisionType.MOD); + public PersistentCollectionChangeWorkUnit( + SessionImplementor sessionImplementor, String entityName, + AuditConfiguration auditCfg, PersistentCollection collection, + CollectionEntry collectionEntry, Serializable snapshot, Serializable id, + String referencingPropertyName) { + super( + sessionImplementor, entityName, auditCfg, new PersistentCollectionChangeWorkUnitId( + id, + collectionEntry.getRole() + ), RevisionType.MOD + ); this.referencingPropertyName = referencingPropertyName; - collectionChanges = auditCfg.getEntCfg().get(getEntityName()).getPropertyMapper() - .mapCollectionChanges(sessionImplementor, referencingPropertyName, collection, snapshot, id); - } + collectionChanges = auditCfg.getEntCfg().get( getEntityName() ).getPropertyMapper() + .mapCollectionChanges( sessionImplementor, referencingPropertyName, collection, snapshot, id ); + } - public PersistentCollectionChangeWorkUnit(SessionImplementor sessionImplementor, String entityName, - AuditConfiguration verCfg, Serializable id, - List collectionChanges, - String referencingPropertyName) { - super(sessionImplementor, entityName, verCfg, id, RevisionType.MOD); + public PersistentCollectionChangeWorkUnit( + SessionImplementor sessionImplementor, String entityName, + AuditConfiguration verCfg, Serializable id, + List collectionChanges, + String referencingPropertyName) { + super( sessionImplementor, entityName, verCfg, id, RevisionType.MOD ); - this.collectionChanges = collectionChanges; - this.referencingPropertyName = referencingPropertyName; - } + this.collectionChanges = collectionChanges; + this.referencingPropertyName = referencingPropertyName; + } - public boolean containsWork() { - return collectionChanges != null && collectionChanges.size() != 0; - } + @Override + public boolean containsWork() { + return collectionChanges != null && collectionChanges.size() != 0; + } - public Map generateData(Object revisionData) { - throw new UnsupportedOperationException("Cannot generate data for a collection change work unit!"); - } + @Override + public Map generateData(Object revisionData) { + throw new UnsupportedOperationException( "Cannot generate data for a collection change work unit!" ); + } - @SuppressWarnings({"unchecked"}) - public void perform(Session session, Object revisionData) { - AuditEntitiesConfiguration entitiesCfg = verCfg.getAuditEntCfg(); + @Override + @SuppressWarnings({"unchecked"}) + public void perform(Session session, Object revisionData) { + final AuditEntitiesConfiguration entitiesCfg = verCfg.getAuditEntCfg(); - for (PersistentCollectionChangeData persistentCollectionChangeData : collectionChanges) { - // Setting the revision number - ((Map) persistentCollectionChangeData.getData().get(entitiesCfg.getOriginalIdPropName())) - .put(entitiesCfg.getRevisionFieldName(), revisionData); + for ( PersistentCollectionChangeData persistentCollectionChangeData : collectionChanges ) { + // Setting the revision number + ((Map) persistentCollectionChangeData.getData().get( entitiesCfg.getOriginalIdPropName() )) + .put( entitiesCfg.getRevisionFieldName(), revisionData ); - auditStrategy.performCollectionChange(session, getEntityName(), referencingPropertyName, verCfg, persistentCollectionChangeData, revisionData); - } - } + auditStrategy.performCollectionChange( + session, + getEntityName(), + referencingPropertyName, + verCfg, + persistentCollectionChangeData, + revisionData + ); + } + } - public String getReferencingPropertyName() { - return referencingPropertyName; - } + public String getReferencingPropertyName() { + return referencingPropertyName; + } - public List getCollectionChanges() { - return collectionChanges; - } + public List getCollectionChanges() { + return collectionChanges; + } - public AuditWorkUnit merge(AddWorkUnit second) { - return null; - } + @Override + public AuditWorkUnit merge(AddWorkUnit second) { + return null; + } - public AuditWorkUnit merge(ModWorkUnit second) { - return null; - } + @Override + public AuditWorkUnit merge(ModWorkUnit second) { + return null; + } - public AuditWorkUnit merge(DelWorkUnit second) { - return null; - } + @Override + public AuditWorkUnit merge(DelWorkUnit second) { + return null; + } - public AuditWorkUnit merge(CollectionChangeWorkUnit second) { - return null; - } + @Override + public AuditWorkUnit merge(CollectionChangeWorkUnit second) { + return null; + } - public AuditWorkUnit merge(FakeBidirectionalRelationWorkUnit second) { - return null; - } + @Override + public AuditWorkUnit merge(FakeBidirectionalRelationWorkUnit second) { + return null; + } - public AuditWorkUnit dispatch(WorkUnitMergeVisitor first) { - if (first instanceof PersistentCollectionChangeWorkUnit) { - PersistentCollectionChangeWorkUnit original = (PersistentCollectionChangeWorkUnit) first; + @Override + public AuditWorkUnit dispatch(WorkUnitMergeVisitor first) { + if ( first instanceof PersistentCollectionChangeWorkUnit ) { + final PersistentCollectionChangeWorkUnit original = (PersistentCollectionChangeWorkUnit) first; - // Merging the collection changes in both work units. + // Merging the collection changes in both work units. - // First building a map from the ids of the collection-entry-entities from the "second" collection changes, - // to the PCCD objects. That way, we will be later able to check if an "original" collection change - // should be added, or if it is overshadowed by a new one. - Map newChangesIdMap = new HashMap(); - for (PersistentCollectionChangeData persistentCollectionChangeData : getCollectionChanges()) { - newChangesIdMap.put( - getOriginalId(persistentCollectionChangeData), - persistentCollectionChangeData); - } + // First building a map from the ids of the collection-entry-entities from the "second" collection changes, + // to the PCCD objects. That way, we will be later able to check if an "original" collection change + // should be added, or if it is overshadowed by a new one. + final Map newChangesIdMap = new HashMap(); + for ( PersistentCollectionChangeData persistentCollectionChangeData : getCollectionChanges() ) { + newChangesIdMap.put( + getOriginalId( persistentCollectionChangeData ), + persistentCollectionChangeData + ); + } - // This will be the list with the resulting (merged) changes. - List mergedChanges = new ArrayList(); + // This will be the list with the resulting (merged) changes. + final List mergedChanges = new ArrayList(); - // Including only those original changes, which are not overshadowed by new ones. - for (PersistentCollectionChangeData originalCollectionChangeData : original.getCollectionChanges()) { - Object originalOriginalId = getOriginalId(originalCollectionChangeData); - if (!newChangesIdMap.containsKey(originalOriginalId)) { - mergedChanges.add(originalCollectionChangeData); - } else { - // If the changes collide, checking if the first one isn't a DEL, and the second a subsequent ADD - // If so, removing the change alltogether. - String revTypePropName = verCfg.getAuditEntCfg().getRevisionTypePropName(); - if (RevisionType.ADD.equals(newChangesIdMap.get(originalOriginalId).getData().get( - revTypePropName)) && RevisionType.DEL.equals(originalCollectionChangeData.getData().get( - revTypePropName))) { - newChangesIdMap.remove(originalOriginalId); - } - } - } + // Including only those original changes, which are not overshadowed by new ones. + for ( PersistentCollectionChangeData originalCollectionChangeData : original.getCollectionChanges() ) { + final Object originalOriginalId = getOriginalId( originalCollectionChangeData ); + if ( !newChangesIdMap.containsKey( originalOriginalId ) ) { + mergedChanges.add( originalCollectionChangeData ); + } + else { + // If the changes collide, checking if the first one isn't a DEL, and the second a subsequent ADD + // If so, removing the change alltogether. + final String revTypePropName = verCfg.getAuditEntCfg().getRevisionTypePropName(); + if ( RevisionType.ADD.equals( newChangesIdMap.get( originalOriginalId ).getData().get( revTypePropName ) ) + && RevisionType.DEL.equals( originalCollectionChangeData.getData().get( revTypePropName ) ) ) { + newChangesIdMap.remove( originalOriginalId ); + } + } + } - // Finally adding all of the new changes to the end of the list (the map values may differ from - // getCollectionChanges() because of the last operation above). - mergedChanges.addAll(newChangesIdMap.values()); + // Finally adding all of the new changes to the end of the list (the map values may differ from + // getCollectionChanges() because of the last operation above). + mergedChanges.addAll( newChangesIdMap.values() ); - return new PersistentCollectionChangeWorkUnit(sessionImplementor, entityName, verCfg, id, mergedChanges, - referencingPropertyName); - } else { - throw new RuntimeException("Trying to merge a " + first + " with a PersitentCollectionChangeWorkUnit. " + - "This is not really possible."); - } - } + return new PersistentCollectionChangeWorkUnit( + sessionImplementor, + entityName, + verCfg, + id, + mergedChanges, + referencingPropertyName + ); + } + else { + throw new RuntimeException( + "Trying to merge a " + first + " with a PersitentCollectionChangeWorkUnit. " + + "This is not really possible." + ); + } + } - private Object getOriginalId(PersistentCollectionChangeData persistentCollectionChangeData) { - return persistentCollectionChangeData.getData().get(verCfg.getAuditEntCfg().getOriginalIdPropName()); - } + private Object getOriginalId(PersistentCollectionChangeData persistentCollectionChangeData) { + return persistentCollectionChangeData.getData().get( verCfg.getAuditEntCfg().getOriginalIdPropName() ); + } - /** - * A unique identifier for a collection work unit. Consists of an id of the owning entity and the name of - * the entity plus the name of the field (the role). This is needed because such collections aren't entities - * in the "normal" mapping, but they are entities for Envers. - */ - public static class PersistentCollectionChangeWorkUnitId implements Serializable { - private static final long serialVersionUID = -8007831518629167537L; - - private final Serializable ownerId; - private final String role; + /** + * A unique identifier for a collection work unit. Consists of an id of the owning entity and the name of + * the entity plus the name of the field (the role). This is needed because such collections aren't entities + * in the "normal" mapping, but they are entities for Envers. + */ + public static class PersistentCollectionChangeWorkUnitId implements Serializable { + private static final long serialVersionUID = -8007831518629167537L; - public PersistentCollectionChangeWorkUnitId(Serializable ownerId, String role) { - this.ownerId = ownerId; - this.role = role; - } + private final Serializable ownerId; + private final String role; - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + public PersistentCollectionChangeWorkUnitId(Serializable ownerId, String role) { + this.ownerId = ownerId; + this.role = role; + } - PersistentCollectionChangeWorkUnitId that = (PersistentCollectionChangeWorkUnitId) o; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } - if (ownerId != null ? !ownerId.equals(that.ownerId) : that.ownerId != null) return false; - //noinspection RedundantIfStatement - if (role != null ? !role.equals(that.role) : that.role != null) return false; + final PersistentCollectionChangeWorkUnitId that = (PersistentCollectionChangeWorkUnitId) o; - return true; - } + if ( ownerId != null ? !ownerId.equals( that.ownerId ) : that.ownerId != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( role != null ? !role.equals( that.role ) : that.role != null ) { + return false; + } - @Override - public int hashCode() { - int result = ownerId != null ? ownerId.hashCode() : 0; - result = 31 * result + (role != null ? role.hashCode() : 0); - return result; - } + return true; + } - public Serializable getOwnerId() { - return ownerId; - } - } + @Override + public int hashCode() { + int result = ownerId != null ? ownerId.hashCode() : 0; + result = 31 * result + (role != null ? role.hashCode() : 0); + return result; + } + + public Serializable getOwnerId() { + return ownerId; + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/WorkUnitMergeDispatcher.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/WorkUnitMergeDispatcher.java index 0359343771..7047bc6c5b 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/WorkUnitMergeDispatcher.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/WorkUnitMergeDispatcher.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -26,13 +26,16 @@ package org.hibernate.envers.internal.synchronization.work; /** * Visitor patter dispatcher. + * * @author Adam Warski (adam at warski dot org) */ public interface WorkUnitMergeDispatcher { - /** - * Should be invoked on the second work unit. - * @param first First work unit (that is, the one added earlier). - * @return The work unit that is the result of the merge. - */ - AuditWorkUnit dispatch(WorkUnitMergeVisitor first); + /** + * Should be invoked on the second work unit. + * + * @param first First work unit (that is, the one added earlier). + * + * @return The work unit that is the result of the merge. + */ + AuditWorkUnit dispatch(WorkUnitMergeVisitor first); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/WorkUnitMergeVisitor.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/WorkUnitMergeVisitor.java index c47840ed00..9d5acf2af8 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/WorkUnitMergeVisitor.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/synchronization/work/WorkUnitMergeVisitor.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -26,12 +26,17 @@ package org.hibernate.envers.internal.synchronization.work; /** * Visitor pattern visitor. All methods should be invoked on the first work unit. + * * @author Adam Warski (adam at warski dot org) */ public interface WorkUnitMergeVisitor { - AuditWorkUnit merge(AddWorkUnit second); - AuditWorkUnit merge(ModWorkUnit second); - AuditWorkUnit merge(DelWorkUnit second); - AuditWorkUnit merge(CollectionChangeWorkUnit second); - AuditWorkUnit merge(FakeBidirectionalRelationWorkUnit second); + AuditWorkUnit merge(AddWorkUnit second); + + AuditWorkUnit merge(ModWorkUnit second); + + AuditWorkUnit merge(DelWorkUnit second); + + AuditWorkUnit merge(CollectionChangeWorkUnit second); + + AuditWorkUnit merge(FakeBidirectionalRelationWorkUnit second); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/ArgumentsTools.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/ArgumentsTools.java index d4d50ca54c..8f481b70a0 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/ArgumentsTools.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/ArgumentsTools.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/ArraysTools.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/ArraysTools.java index 8b3e5d4b71..5671ff2af1 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/ArraysTools.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/ArraysTools.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -56,13 +56,15 @@ public abstract class ArraysTools { /** * Converts map's value set to an array. {@code keys} parameter specifies requested elements and their order. + * * @param data Source map. * @param keys Array of keys that represent requested map values. + * * @return Array of values stored in the map under specified keys. If map does not contain requested key, * {@code null} is inserted. */ public static Object[] mapToArray(Map data, String[] keys) { - Object[] ret = new Object[keys.length]; + final Object[] ret = new Object[keys.length]; for ( int i = 0; i < keys.length; ++i ) { ret[i] = data.get( keys[i] ); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/EntityTools.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/EntityTools.java index f0d36f41d1..25cca6bab4 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/EntityTools.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/EntityTools.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.internal.tools; import javassist.util.proxy.ProxyFactory; @@ -13,8 +36,8 @@ import org.hibernate.proxy.HibernateProxy; */ public abstract class EntityTools { public static boolean entitiesEqual(SessionImplementor session, String entityName, Object obj1, Object obj2) { - Object id1 = getIdentifier( session, entityName, obj1 ); - Object id2 = getIdentifier( session, entityName, obj2 ); + final Object id1 = getIdentifier( session, entityName, obj1 ); + final Object id2 = getIdentifier( session, entityName, obj2 ); return Tools.objectsEqual( id1, id2 ); } @@ -25,7 +48,7 @@ public abstract class EntityTools { } if ( obj instanceof HibernateProxy ) { - HibernateProxy hibernateProxy = (HibernateProxy) obj; + final HibernateProxy hibernateProxy = (HibernateProxy) obj; return hibernateProxy.getHibernateLazyInitializer().getIdentifier(); } @@ -37,16 +60,15 @@ public abstract class EntityTools { return proxy.getHibernateLazyInitializer().getImplementation(); } - SessionImplementor sessionImplementor = proxy.getHibernateLazyInitializer().getSession(); - Session tempSession = sessionImplementor == null + final SessionImplementor sessionImplementor = proxy.getHibernateLazyInitializer().getSession(); + final Session tempSession = sessionImplementor == null ? sessionFactoryImplementor.openTemporarySession() : sessionImplementor.getFactory().openTemporarySession(); try { - Object target = tempSession.get( + return tempSession.get( proxy.getHibernateLazyInitializer().getEntityName(), proxy.getHibernateLazyInitializer().getIdentifier() ); - return target; } finally { tempSession.close(); @@ -54,17 +76,18 @@ public abstract class EntityTools { } private static boolean activeProxySession(HibernateProxy proxy) { - Session session = (Session) proxy.getHibernateLazyInitializer().getSession(); + final Session session = (Session) proxy.getHibernateLazyInitializer().getSession(); return session != null && session.isOpen() && session.isConnected(); } /** * @param clazz Class wrapped with a proxy or not. * @param Class type. + * * @return Returns target class in case it has been wrapped with a proxy. If {@code null} reference is passed, * method returns {@code null}. */ - @SuppressWarnings({ "unchecked" }) + @SuppressWarnings({"unchecked"}) public static Class getTargetClassIfProxied(Class clazz) { if ( clazz == null ) { return null; @@ -80,7 +103,7 @@ public abstract class EntityTools { * @return Java class mapped to specified entity name. */ public static Class getEntityClass(SessionImplementor sessionImplementor, Session session, String entityName) { - EntityPersister entityPersister = sessionImplementor.getFactory().getEntityPersister( entityName ); + final EntityPersister entityPersister = sessionImplementor.getFactory().getEntityPersister( entityName ); return entityPersister.getMappedClass(); } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/MappingTools.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/MappingTools.java index 5060e96eb5..d91cbe3364 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/MappingTools.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/MappingTools.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.internal.tools; import org.hibernate.mapping.Collection; @@ -29,13 +52,13 @@ public abstract class MappingTools { public static String getReferencedEntityName(Value value) { if ( value instanceof ToOne ) { - return ( (ToOne) value ).getReferencedEntityName(); + return ((ToOne) value).getReferencedEntityName(); } else if ( value instanceof OneToMany ) { - return ( (OneToMany) value ).getReferencedEntityName(); + return ((OneToMany) value).getReferencedEntityName(); } else if ( value instanceof Collection ) { - return getReferencedEntityName( ( (Collection) value ).getElement() ); + return getReferencedEntityName( ((Collection) value).getElement() ); } return null; diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/MutableBoolean.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/MutableBoolean.java index d0db6c9220..614b85e7a0 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/MutableBoolean.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/MutableBoolean.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -28,24 +28,24 @@ package org.hibernate.envers.internal.tools; * @author Adam Warski (adam at warski dot org) */ public class MutableBoolean { - private boolean value; + private boolean value; - public MutableBoolean() { - } + public MutableBoolean() { + } - public MutableBoolean(boolean value) { - this.value = value; - } + public MutableBoolean(boolean value) { + this.value = value; + } - public boolean isSet() { - return value; - } + public boolean isSet() { + return value; + } - public void set() { - value = true; - } + public void set() { + value = true; + } - public void unset() { - value = false; - } + public void unset() { + value = false; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/MutableInteger.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/MutableInteger.java index 4b658ba9ad..6b1c79fb21 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/MutableInteger.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/MutableInteger.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -27,32 +27,32 @@ package org.hibernate.envers.internal.tools; * @author Adam Warski (adam at warski dot org) */ public class MutableInteger { - private int value = 0; + private int value = 0; - public MutableInteger() { - } + public MutableInteger() { + } - public MutableInteger(int value) { - this.value = value; - } + public MutableInteger(int value) { + this.value = value; + } public MutableInteger deepCopy() { return new MutableInteger( value ); } - public int getAndIncrease() { - return value++; - } + public int getAndIncrease() { + return value++; + } - public int get() { - return value; - } + public int get() { + return value; + } - public void set(int value) { - this.value = value; - } + public void set(int value) { + this.value = value; + } - public void increase() { - ++value; - } + public void increase() { + ++value; + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/ReflectionTools.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/ReflectionTools.java index 653013aafe..9db7c3a23d 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/ReflectionTools.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/ReflectionTools.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -44,14 +44,16 @@ import org.hibernate.property.Setter; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public abstract class ReflectionTools { - private static final Map, Getter> getterCache = - new ConcurrentReferenceHashMap, Getter>( - 10, ConcurrentReferenceHashMap.ReferenceType.SOFT, ConcurrentReferenceHashMap.ReferenceType.SOFT - ); - private static final Map, Setter> setterCache = - new ConcurrentReferenceHashMap, Setter>( - 10, ConcurrentReferenceHashMap.ReferenceType.SOFT, ConcurrentReferenceHashMap.ReferenceType.SOFT - ); + private static final Map, Getter> GETTER_CACHE = new ConcurrentReferenceHashMap, Getter>( + 10, + ConcurrentReferenceHashMap.ReferenceType.SOFT, + ConcurrentReferenceHashMap.ReferenceType.SOFT + ); + private static final Map, Setter> SETTER_CACHE = new ConcurrentReferenceHashMap, Setter>( + 10, + ConcurrentReferenceHashMap.ReferenceType.SOFT, + ConcurrentReferenceHashMap.ReferenceType.SOFT + ); private static PropertyAccessor getAccessor(String accessorType) { return PropertyAccessorFactory.getPropertyAccessor( accessorType ); @@ -62,12 +64,12 @@ public abstract class ReflectionTools { } public static Getter getGetter(Class cls, String propertyName, String accessorType) { - Pair key = Pair.make( cls, propertyName ); - Getter value = getterCache.get( key ); + final Pair key = Pair.make( cls, propertyName ); + Getter value = GETTER_CACHE.get( key ); if ( value == null ) { value = getAccessor( accessorType ).getGetter( cls, propertyName ); // It's ok if two getters are generated concurrently - getterCache.put( key, value ); + GETTER_CACHE.put( key, value ); } return value; @@ -78,12 +80,12 @@ public abstract class ReflectionTools { } private static Setter getSetter(Class cls, String propertyName, String accessorType) { - Pair key = Pair.make( cls, propertyName ); - Setter value = setterCache.get( key ); + final Pair key = Pair.make( cls, propertyName ); + Setter value = SETTER_CACHE.get( key ); if ( value == null ) { value = getAccessor( accessorType ).getSetter( cls, propertyName ); // It's ok if two setters are generated concurrently - setterCache.put( key, value ); + SETTER_CACHE.put( key, value ); } return value; @@ -92,6 +94,7 @@ public abstract class ReflectionTools { /** * @param clazz Source class. * @param propertyName Property name. + * * @return Property object or {@code null} if none with expected name has been found. */ public static XProperty getProperty(XClass clazz, String propertyName) { @@ -106,6 +109,7 @@ public abstract class ReflectionTools { * @param clazz Source class. * @param propertyName Property name. * @param accessType Expected access type. Legal values are field and property. + * * @return Property object or {@code null} if none with expected name and access type has been found. */ public static XProperty getProperty(XClass clazz, String propertyName, String accessType) { @@ -119,14 +123,18 @@ public abstract class ReflectionTools { /** * Locate class with a given name. + * * @param name Fully qualified class name. * @param classLoaderService Class loading service. Passing {@code null} reference - * in case of {@link AuditConfiguration#getFor(Configuration)} usage. + * in case of {@link AuditConfiguration#getFor(Configuration)} usage. + * * @return The cass reference. + * * @throws ClassLoadingException Indicates the class could not be found. */ @SuppressWarnings("unchecked") - public static Class loadClass(String name, ClassLoaderService classLoaderService) throws ClassLoadingException { + public static Class loadClass(String name, ClassLoaderService classLoaderService) + throws ClassLoadingException { try { if ( classLoaderService != null ) { return classLoaderService.classForName( name ); @@ -135,7 +143,7 @@ public abstract class ReflectionTools { return (Class) Thread.currentThread().getContextClassLoader().loadClass( name ); } } - catch ( Exception e ) { + catch (Exception e) { throw new ClassLoadingException( "Unable to load class [" + name + "]", e ); } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/StringTools.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/StringTools.java index e44d78f3e2..a583f3ff54 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/StringTools.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/StringTools.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -47,7 +47,7 @@ public abstract class StringTools { if ( s == null ) { return null; } - int lastDot = s.lastIndexOf( "." ); + final int lastDot = s.lastIndexOf( "." ); if ( lastDot == -1 ) { return s; } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/Tools.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/Tools.java index da7e29937e..0fafa83c1d 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/Tools.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/Tools.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -61,7 +61,7 @@ public abstract class Tools { } public static List iteratorToList(Iterator iter) { - List ret = new ArrayList(); + final List ret = new ArrayList(); while ( iter.hasNext() ) { ret.add( iter.next() ); } @@ -92,8 +92,8 @@ public abstract class Tools { * @return A list of pairs: ((0, element_at_index_0), (1, element_at_index_1), ...) */ public static List> listToIndexElementPairList(List list) { - List> ret = new ArrayList>(); - Iterator listIter = list.iterator(); + final List> ret = new ArrayList>(); + final Iterator listIter = list.iterator(); for ( int i = 0; i < list.size(); i++ ) { ret.add( Pair.make( i, listIter.next() ) ); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/Triple.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/Triple.java index c63c30f560..171203010d 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/Triple.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/Triple.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -23,58 +23,65 @@ */ package org.hibernate.envers.internal.tools; +import org.hibernate.internal.util.compare.EqualsHelper; + /** * A triple of objects. + * * @param * @param * @param + * * @author Adam Warski (adamw@aster.pl) */ public class Triple { - private T1 obj1; - private T2 obj2; - private T3 obj3; + private T1 obj1; + private T2 obj2; + private T3 obj3; - public Triple(T1 obj1, T2 obj2, T3 obj3) { - this.obj1 = obj1; - this.obj2 = obj2; - this.obj3 = obj3; - } + public Triple(T1 obj1, T2 obj2, T3 obj3) { + this.obj1 = obj1; + this.obj2 = obj2; + this.obj3 = obj3; + } - public T1 getFirst() { - return obj1; - } + public T1 getFirst() { + return obj1; + } - public T2 getSecond() { - return obj2; - } + public T2 getSecond() { + return obj2; + } - public T3 getThird() { - return obj3; - } + public T3 getThird() { + return obj3; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Triple)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Triple) ) { + return false; + } - Triple triple = (Triple) o; + final Triple other = (Triple) o; + return EqualsHelper.equals( obj1, other.obj1 ) + && EqualsHelper.equals( obj2, other.obj2 ) + && EqualsHelper.equals( obj3, other.obj3 ); + } - if (obj1 != null ? !obj1.equals(triple.obj1) : triple.obj1 != null) return false; - if (obj2 != null ? !obj2.equals(triple.obj2) : triple.obj2 != null) return false; - if (obj3 != null ? !obj3.equals(triple.obj3) : triple.obj3 != null) return false; + @Override + public int hashCode() { + int result; + result = (obj1 != null ? obj1.hashCode() : 0); + result = 31 * result + (obj2 != null ? obj2.hashCode() : 0); + result = 31 * result + (obj3 != null ? obj3.hashCode() : 0); + return result; + } - return true; - } - - public int hashCode() { - int result; - result = (obj1 != null ? obj1.hashCode() : 0); - result = 31 * result + (obj2 != null ? obj2.hashCode() : 0); - result = 31 * result + (obj3 != null ? obj3.hashCode() : 0); - return result; - } - - public static Triple make(T1 obj1, T2 obj2, T3 obj3) { - return new Triple(obj1, obj2, obj3); - } + public static Triple make(T1 obj1, T2 obj2, T3 obj3) { + return new Triple( obj1, obj2, obj3 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/graph/GraphDefiner.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/graph/GraphDefiner.java index 81856b16cd..1cf4de91e7 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/graph/GraphDefiner.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/graph/GraphDefiner.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,16 +22,21 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.tools.graph; + import java.util.List; /** * Defines a graph, where each vertex has a representation, which identifies uniquely a value. * Representations are comparable, values - not. + * * @author Adam Warski (adam at warski dot org) */ public interface GraphDefiner { - R getRepresentation(V v); - V getValue(R r); - List getNeighbours(V v); - List getValues(); + R getRepresentation(V v); + + V getValue(R r); + + List getNeighbours(V v); + + List getValues(); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/graph/GraphTopologicalSort.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/graph/GraphTopologicalSort.java index bd79f46540..99e3da169e 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/graph/GraphTopologicalSort.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/graph/GraphTopologicalSort.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.tools.graph; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -31,37 +32,40 @@ import java.util.Map; * @author Adam Warski (adam at warski dot org) */ public class GraphTopologicalSort { - /** - * Sorts a graph topologically. - * @param definer Defines a graph (values and representations) to sort. - * @return Values of the graph, sorted topologically. - */ - public static List sort(GraphDefiner definer) { - List values = definer.getValues(); - Map> vertices = new HashMap>(); + /** + * Sorts a graph topologically. + * + * @param definer Defines a graph (values and representations) to sort. + * + * @return Values of the graph, sorted topologically. + */ + public static List sort(GraphDefiner definer) { + final List values = definer.getValues(); + final Map> vertices = new HashMap>(); - // Creating a vertex for each representation - for (V v : values) { - R rep = definer.getRepresentation(v); - vertices.put(rep, new Vertex(rep)); - } + // Creating a vertex for each representation + for ( V v : values ) { + final R rep = definer.getRepresentation( v ); + vertices.put( rep, new Vertex( rep ) ); + } - // Connecting neighbourhooding vertices - for (V v : values) { - for (V vn : definer.getNeighbours(v)) { - vertices.get(definer.getRepresentation(v)).addNeighbour(vertices.get(definer.getRepresentation(vn))); - } - } + // Connecting neighbourhooding vertices + for ( V v : values ) { + for ( V vn : definer.getNeighbours( v ) ) { + vertices.get( definer.getRepresentation( v ) ) + .addNeighbour( vertices.get( definer.getRepresentation( vn ) ) ); + } + } - // Sorting the representations - List sortedReps = new TopologicalSort().sort(vertices.values()); + // Sorting the representations + final List sortedReps = new TopologicalSort().sort( vertices.values() ); - // Transforming the sorted representations to sorted values - List sortedValues = new ArrayList(sortedReps.size()); - for (R rep : sortedReps) { - sortedValues.add(definer.getValue(rep)); - } + // Transforming the sorted representations to sorted values + final List sortedValues = new ArrayList( sortedReps.size() ); + for ( R rep : sortedReps ) { + sortedValues.add( definer.getValue( rep ) ); + } - return sortedValues; - } + return sortedValues; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/graph/TopologicalSort.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/graph/TopologicalSort.java index da68cdebea..840b3c87e5 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/graph/TopologicalSort.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/graph/TopologicalSort.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.tools.graph; + import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -29,42 +30,43 @@ import java.util.List; /** * Topological sorting of a graph - based on DFS. + * * @author Adam Warski (adam at warski dot org) */ public class TopologicalSort { - private List sorted; - private int time; + private List sorted; + private int time; - private void process(Vertex v) { - if (v.getStartTime() != 0) { - // alread processed - return; - } + private void process(Vertex v) { + if ( v.getStartTime() != 0 ) { + // alread processed + return; + } - v.setStartTime(time++); + v.setStartTime( time++ ); - for (Vertex n : v.getNeighbours()) { - process(n); - } + for ( Vertex n : v.getNeighbours() ) { + process( n ); + } - v.setEndTime(time++); + v.setEndTime( time++ ); - sorted.add(v.getRepresentation()); - } + sorted.add( v.getRepresentation() ); + } - public List sort(Collection> vertices) { - sorted = new ArrayList(vertices.size()); - - time = 1; + public List sort(Collection> vertices) { + sorted = new ArrayList( vertices.size() ); - for (Vertex v : vertices) { - if (v.getEndTime() == 0) { - process(v); - } - } + time = 1; - Collections.reverse(sorted); + for ( Vertex v : vertices ) { + if ( v.getEndTime() == 0 ) { + process( v ); + } + } - return sorted; - } + Collections.reverse( sorted ); + + return sorted; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/graph/Vertex.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/graph/Vertex.java index c15035d7b7..92857d80c5 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/graph/Vertex.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/graph/Vertex.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,52 +22,54 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.tools.graph; + import java.util.ArrayList; import java.util.List; /** * A graph vertex - stores its representation, neighbours, start and end time in (D|B)FS. + * * @author Adam Warski (adam at warski dot org) */ public class Vertex { - private final R representation; - private final List> neighbours; - - private int startTime; - private int endTime; + private final R representation; + private final List> neighbours; - public Vertex(R representation) { - this.representation = representation; - this.neighbours = new ArrayList>(); - this.startTime = 0; - this.endTime = 0; - } + private int startTime; + private int endTime; - public R getRepresentation() { - return representation; - } + public Vertex(R representation) { + this.representation = representation; + this.neighbours = new ArrayList>(); + this.startTime = 0; + this.endTime = 0; + } - public List> getNeighbours() { - return neighbours; - } + public R getRepresentation() { + return representation; + } - public void addNeighbour(Vertex n) { - neighbours.add(n); - } + public List> getNeighbours() { + return neighbours; + } - public int getStartTime() { - return startTime; - } + public void addNeighbour(Vertex n) { + neighbours.add( n ); + } - public void setStartTime(int startTime) { - this.startTime = startTime; - } + public int getStartTime() { + return startTime; + } - public int getEndTime() { - return endTime; - } + public void setStartTime(int startTime) { + this.startTime = startTime; + } - public void setEndTime(int endTime) { - this.endTime = endTime; - } + public int getEndTime() { + return endTime; + } + + public void setEndTime(int endTime) { + this.endTime = endTime; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/query/Parameters.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/query/Parameters.java index 08a7a30275..18caf91982 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/query/Parameters.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/query/Parameters.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.internal.tools.query; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -32,52 +33,53 @@ import org.hibernate.envers.internal.tools.MutableInteger; /** * Parameters of a query, built using {@link QueryBuilder}. + * * @author Adam Warski (adam at warski dot org) */ public class Parameters { - public final static String AND = "and"; - public final static String OR = "or"; - - /** - * Main alias of the entity. - */ - private final String alias; - /** - * Connective between these parameters - "and" or "or". - */ - private final String connective; - /** - * For use by the parameter generator. Must be the same in all "child" (and parent) parameters. - */ - private final MutableInteger queryParamCounter; + public final static String AND = "and"; + public final static String OR = "or"; - /** - * A list of sub-parameters (parameters with a different connective). - */ - private final List subParameters; - /** - * A list of negated parameters. - */ - private final List negatedParameters; - /** - * A list of complete where-expressions. - */ - private final List expressions; - /** - * Values of parameters used in expressions. - */ - private final Map localQueryParamValues; + /** + * Main alias of the entity. + */ + private final String alias; + /** + * Connective between these parameters - "and" or "or". + */ + private final String connective; + /** + * For use by the parameter generator. Must be the same in all "child" (and parent) parameters. + */ + private final MutableInteger queryParamCounter; - Parameters(String alias, String connective, MutableInteger queryParamCounter) { - this.alias = alias; - this.connective = connective; - this.queryParamCounter = queryParamCounter; + /** + * A list of sub-parameters (parameters with a different connective). + */ + private final List subParameters; + /** + * A list of negated parameters. + */ + private final List negatedParameters; + /** + * A list of complete where-expressions. + */ + private final List expressions; + /** + * Values of parameters used in expressions. + */ + private final Map localQueryParamValues; - subParameters = new ArrayList(); - negatedParameters = new ArrayList(); - expressions = new ArrayList(); - localQueryParamValues = new HashMap(); - } + Parameters(String alias, String connective, MutableInteger queryParamCounter) { + this.alias = alias; + this.connective = connective; + this.queryParamCounter = queryParamCounter; + + subParameters = new ArrayList(); + negatedParameters = new ArrayList(); + expressions = new ArrayList(); + localQueryParamValues = new HashMap(); + } // Only for deep copy purpose. private Parameters(Parameters other) { @@ -101,181 +103,193 @@ public class Parameters { return new Parameters( this ); } - private String generateQueryParam() { - return "_p" + queryParamCounter.getAndIncrease(); - } + private String generateQueryParam() { + return "_p" + queryParamCounter.getAndIncrease(); + } - /** - * Adds sub-parameters with a new connective. That is, the parameters will be grouped in parentheses in the - * generated query, e.g.: ... and (exp1 or exp2) and ..., assuming the old connective is "and", and the - * new connective is "or". - * @param newConnective New connective of the parameters. - * @return Sub-parameters with the given connective. - */ - public Parameters addSubParameters(String newConnective) { - if (connective.equals(newConnective)) { - return this; - } else { - Parameters newParams = new Parameters(alias, newConnective, queryParamCounter); - subParameters.add(newParams); - return newParams; - } - } + /** + * Adds sub-parameters with a new connective. That is, the parameters will be grouped in parentheses in the + * generated query, e.g.: ... and (exp1 or exp2) and ..., assuming the old connective is "and", and the + * new connective is "or". + * + * @param newConnective New connective of the parameters. + * + * @return Sub-parameters with the given connective. + */ + public Parameters addSubParameters(String newConnective) { + if ( connective.equals( newConnective ) ) { + return this; + } + else { + final Parameters newParams = new Parameters( alias, newConnective, queryParamCounter ); + subParameters.add( newParams ); + return newParams; + } + } - /** - * Adds negated parameters, by default with the "and" connective. These paremeters will be grouped in parentheses - * in the generated query and negated, e.g. ... not (exp1 and exp2) ... - * @return Negated sub paremters. - */ - public Parameters addNegatedParameters() { - Parameters newParams = new Parameters(alias, AND, queryParamCounter); - negatedParameters.add(newParams); - return newParams; - } + /** + * Adds negated parameters, by default with the "and" connective. These paremeters will be grouped in parentheses + * in the generated query and negated, e.g. ... not (exp1 and exp2) ... + * + * @return Negated sub paremters. + */ + public Parameters addNegatedParameters() { + final Parameters newParams = new Parameters( alias, AND, queryParamCounter ); + negatedParameters.add( newParams ); + return newParams; + } - public void addWhere(String left, String op, String right) { - addWhere(left, true, op, right, true); - } + public void addWhere(String left, String op, String right) { + addWhere( left, true, op, right, true ); + } - /** - * Adds IS NULL restriction. - * @param propertyName Property name. - * @param addAlias Positive if an alias to property name shall be added. - */ - public void addNullRestriction(String propertyName, boolean addAlias) { - addWhere(propertyName, addAlias, "is", "null", false); - } + /** + * Adds IS NULL restriction. + * + * @param propertyName Property name. + * @param addAlias Positive if an alias to property name shall be added. + */ + public void addNullRestriction(String propertyName, boolean addAlias) { + addWhere( propertyName, addAlias, "is", "null", false ); + } - /** - * Adds IS NOT NULL restriction. - * @param propertyName Property name. - * @param addAlias Positive if an alias to property name shall be added. - */ - public void addNotNullRestriction(String propertyName, boolean addAlias) { - addWhere(propertyName, addAlias, "is not", "null", false); - } + /** + * Adds IS NOT NULL restriction. + * + * @param propertyName Property name. + * @param addAlias Positive if an alias to property name shall be added. + */ + public void addNotNullRestriction(String propertyName, boolean addAlias) { + addWhere( propertyName, addAlias, "is not", "null", false ); + } - public void addWhere(String left, boolean addAliasLeft, String op, String right, boolean addAliasRight) { - StringBuilder expression = new StringBuilder(); + public void addWhere(String left, boolean addAliasLeft, String op, String right, boolean addAliasRight) { + final StringBuilder expression = new StringBuilder(); - if (addAliasLeft) { expression.append(alias).append("."); } - expression.append(left); + if ( addAliasLeft ) { + expression.append( alias ).append( "." ); + } + expression.append( left ); - expression.append(" ").append(op).append(" "); + expression.append( " " ).append( op ).append( " " ); - if (addAliasRight) { expression.append(alias).append("."); } - expression.append(right); + if ( addAliasRight ) { + expression.append( alias ).append( "." ); + } + expression.append( right ); - expressions.add(expression.toString()); - } + expressions.add( expression.toString() ); + } - public void addWhereWithParam(String left, String op, Object paramValue) { - addWhereWithParam(left, true, op, paramValue); - } + public void addWhereWithParam(String left, String op, Object paramValue) { + addWhereWithParam( left, true, op, paramValue ); + } - public void addWhereWithParam(String left, boolean addAlias, String op, Object paramValue) { - String paramName = generateQueryParam(); - localQueryParamValues.put(paramName, paramValue); + public void addWhereWithParam(String left, boolean addAlias, String op, Object paramValue) { + final String paramName = generateQueryParam(); + localQueryParamValues.put( paramName, paramValue ); - addWhereWithNamedParam(left, addAlias, op, paramName); - } + addWhereWithNamedParam( left, addAlias, op, paramName ); + } - public void addWhereWithNamedParam(String left, String op, String paramName) { - addWhereWithNamedParam(left, true, op, paramName); - } + public void addWhereWithNamedParam(String left, String op, String paramName) { + addWhereWithNamedParam( left, true, op, paramName ); + } - public void addWhereWithNamedParam(String left, boolean addAlias, String op, String paramName) { - StringBuilder expression = new StringBuilder(); + public void addWhereWithNamedParam(String left, boolean addAlias, String op, String paramName) { + final StringBuilder expression = new StringBuilder(); - if (addAlias) { expression.append(alias).append("."); } - expression.append(left); - expression.append(" ").append(op).append(" "); - expression.append(":").append(paramName); + if ( addAlias ) { + expression.append( alias ).append( "." ); + } + expression.append( left ); + expression.append( " " ).append( op ).append( " " ); + expression.append( ":" ).append( paramName ); - expressions.add(expression.toString()); - } + expressions.add( expression.toString() ); + } - public void addWhereWithParams(String left, String opStart, Object[] paramValues, String opEnd) { - StringBuilder expression = new StringBuilder(); + public void addWhereWithParams(String left, String opStart, Object[] paramValues, String opEnd) { + final StringBuilder expression = new StringBuilder(); - expression.append(alias).append(".").append(left).append(" ").append(opStart); + expression.append( alias ).append( "." ).append( left ).append( " " ).append( opStart ); - for (int i=0; i queryParamValues) { - MutableBoolean isFirst = new MutableBoolean(true); + boolean isEmpty() { + return expressions.size() == 0 && subParameters.size() == 0 && negatedParameters.size() == 0; + } - for (String expression : expressions) { - append(sb, expression, isFirst); - } + void build(StringBuilder sb, Map queryParamValues) { + final MutableBoolean isFirst = new MutableBoolean( true ); - for (Parameters sub : subParameters) { - if (!subParameters.isEmpty()) { - append(sb, "(", isFirst); - sub.build(sb, queryParamValues); - sb.append(")"); - } - } + for ( String expression : expressions ) { + append( sb, expression, isFirst ); + } - for (Parameters negated : negatedParameters) { - if (!negatedParameters.isEmpty()) { - append(sb, "not (", isFirst); - negated.build(sb, queryParamValues); - sb.append(")"); - } - } + for ( Parameters sub : subParameters ) { + if ( !subParameters.isEmpty() ) { + append( sb, "(", isFirst ); + sub.build( sb, queryParamValues ); + sb.append( ")" ); + } + } - queryParamValues.putAll(localQueryParamValues); - } + for ( Parameters negated : negatedParameters ) { + if ( !negatedParameters.isEmpty() ) { + append( sb, "not (", isFirst ); + negated.build( sb, queryParamValues ); + sb.append( ")" ); + } + } + + queryParamValues.putAll( localQueryParamValues ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/query/QueryBuilder.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/query/QueryBuilder.java index 6377318a05..0a75c65a8c 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/query/QueryBuilder.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/query/QueryBuilder.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2013, 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 @@ -35,63 +35,63 @@ import org.hibernate.envers.internal.tools.StringTools; import org.hibernate.envers.tools.Pair; /** - * A class for incrementaly building a HQL query. + * A class for incrementally building a HQL query. + * * @author Adam Warski (adam at warski dot org) */ public class QueryBuilder { - private final String entityName; - private final String alias; + private final String entityName; + private final String alias; - /** - * For use by alias generator (in case an alias is not provided by the user). - */ - private final MutableInteger aliasCounter; - /** - * For use by parameter generator, in {@link Parameters}. This counter must be - * the same in all parameters and sub-queries of this query. - */ - private final MutableInteger paramCounter; - /** - * Main "where" parameters for this query. - */ - private final Parameters rootParameters; + /** + * For use by alias generator (in case an alias is not provided by the user). + */ + private final MutableInteger aliasCounter; + /** + * For use by parameter generator, in {@link Parameters}. This counter must be + * the same in all parameters and sub-queries of this query. + */ + private final MutableInteger paramCounter; + /** + * Main "where" parameters for this query. + */ + private final Parameters rootParameters; - /** - * A list of pairs (from entity name, alias name). - */ - private final List> froms; - /** - * A list of pairs (property name, order ascending?). - */ - private final List> orders; - /** - * A list of complete projection definitions: either a sole property name, or a function(property name). - */ - private final List projections; + /** + * A list of pairs (from entity name, alias name). + */ + private final List> froms; + /** + * A list of pairs (property name, order ascending?). + */ + private final List> orders; + /** + * A list of complete projection definitions: either a sole property name, or a function(property name). + */ + private final List projections; - /** - * - * @param entityName Main entity which should be selected. - * @param alias Alias of the entity - */ - public QueryBuilder(String entityName, String alias) { - this(entityName, alias, new MutableInteger(), new MutableInteger()); - } + /** + * @param entityName Main entity which should be selected. + * @param alias Alias of the entity + */ + public QueryBuilder(String entityName, String alias) { + this( entityName, alias, new MutableInteger(), new MutableInteger() ); + } - private QueryBuilder(String entityName, String alias, MutableInteger aliasCounter, MutableInteger paramCounter) { - this.entityName = entityName; - this.alias = alias; - this.aliasCounter = aliasCounter; - this.paramCounter = paramCounter; + private QueryBuilder(String entityName, String alias, MutableInteger aliasCounter, MutableInteger paramCounter) { + this.entityName = entityName; + this.alias = alias; + this.aliasCounter = aliasCounter; + this.paramCounter = paramCounter; - rootParameters = new Parameters(alias, "and", paramCounter); + rootParameters = new Parameters( alias, "and", paramCounter ); - froms = new ArrayList>(); - orders = new ArrayList>(); - projections = new ArrayList(); + froms = new ArrayList>(); + orders = new ArrayList>(); + projections = new ArrayList(); - addFrom(entityName, alias); - } + addFrom( entityName, alias ); + } // Only for deep copy purpose. private QueryBuilder(QueryBuilder other) { @@ -110,129 +110,138 @@ public class QueryBuilder { return new QueryBuilder( this ); } - /** - * Add an entity from which to select. - * @param entityName Name of the entity from which to select. - * @param alias Alias of the entity. Should be different than all other aliases. - */ - public void addFrom(String entityName, String alias) { - froms.add(Pair.make(entityName, alias)); - } + /** + * Add an entity from which to select. + * + * @param entityName Name of the entity from which to select. + * @param alias Alias of the entity. Should be different than all other aliases. + */ + public void addFrom(String entityName, String alias) { + froms.add( Pair.make( entityName, alias ) ); + } - private String generateAlias() { - return "_e" + aliasCounter.getAndIncrease(); - } + private String generateAlias() { + return "_e" + aliasCounter.getAndIncrease(); + } - /** - * @return A sub-query builder for the same entity (with an auto-generated alias). The sub-query can - * be later used as a value of a parameter. - */ - public QueryBuilder newSubQueryBuilder() { - return newSubQueryBuilder(entityName, generateAlias()); - } + /** + * @return A sub-query builder for the same entity (with an auto-generated alias). The sub-query can + * be later used as a value of a parameter. + */ + public QueryBuilder newSubQueryBuilder() { + return newSubQueryBuilder( entityName, generateAlias() ); + } - /** - * @param entityName Entity name, which will be the main entity for the sub-query. - * @param alias Alias of the entity, which can later be used in parameters. - * @return A sub-query builder for the given entity, with the given alias. The sub-query can - * be later used as a value of a parameter. - */ - public QueryBuilder newSubQueryBuilder(String entityName, String alias) { - return new QueryBuilder(entityName, alias, aliasCounter, paramCounter); - } + /** + * @param entityName Entity name, which will be the main entity for the sub-query. + * @param alias Alias of the entity, which can later be used in parameters. + * + * @return A sub-query builder for the given entity, with the given alias. The sub-query can + * be later used as a value of a parameter. + */ + public QueryBuilder newSubQueryBuilder(String entityName, String alias) { + return new QueryBuilder( entityName, alias, aliasCounter, paramCounter ); + } - public Parameters getRootParameters() { - return rootParameters; - } + public Parameters getRootParameters() { + return rootParameters; + } - public void addOrder(String propertyName, boolean ascending) { - orders.add(Pair.make(propertyName, ascending)); - } + public void addOrder(String propertyName, boolean ascending) { + orders.add( Pair.make( propertyName, ascending ) ); + } - public void addProjection(String function, String propertyName, boolean distinct) { - addProjection(function, propertyName, distinct, true); - } + public void addProjection(String function, String propertyName, boolean distinct) { + addProjection( function, propertyName, distinct, true ); + } - public void addProjection(String function, String propertyName, boolean distinct, boolean addAlias) { - if (function == null) { - projections.add((distinct ? "distinct " : "") + (addAlias ? alias+ "." : "") + propertyName); - } else { - projections.add(function + "(" + (distinct ? "distinct " : "") + (addAlias ? alias + "." : "") + propertyName + ")"); - } - } + public void addProjection(String function, String propertyName, boolean distinct, boolean addAlias) { + if ( function == null ) { + projections.add( (distinct ? "distinct " : "") + (addAlias ? alias + "." : "") + propertyName ); + } + else { + projections.add( + function + "(" + (distinct ? "distinct " : "") + (addAlias ? + alias + "." : + "") + propertyName + ")" + ); + } + } - /** - * Builds the given query, appending results to the given string buffer, and adding all query parameter values - * that are used to the map provided. - * @param sb String builder to which the query will be appended. - * @param queryParamValues Map to which name and values of parameters used in the query should be added. - */ - public void build(StringBuilder sb, Map queryParamValues) { - sb.append("select "); - if (projections.size() > 0) { - // all projections separated with commas - StringTools.append(sb, projections.iterator(), ", "); - } else { - // all aliases separated with commas - StringTools.append(sb, getAliasList().iterator(), ", "); - } - sb.append(" from "); - // all from entities with aliases, separated with commas - StringTools.append(sb, getFromList().iterator(), ", "); - // where part - rootParameters - if (!rootParameters.isEmpty()) { - sb.append(" where "); - rootParameters.build(sb, queryParamValues); - } - // orders - if (orders.size() > 0) { - sb.append(" order by "); - StringTools.append(sb, getOrderList().iterator(), ", "); - } - } + /** + * Builds the given query, appending results to the given string buffer, and adding all query parameter values + * that are used to the map provided. + * + * @param sb String builder to which the query will be appended. + * @param queryParamValues Map to which name and values of parameters used in the query should be added. + */ + public void build(StringBuilder sb, Map queryParamValues) { + sb.append( "select " ); + if ( projections.size() > 0 ) { + // all projections separated with commas + StringTools.append( sb, projections.iterator(), ", " ); + } + else { + // all aliases separated with commas + StringTools.append( sb, getAliasList().iterator(), ", " ); + } + sb.append( " from " ); + // all from entities with aliases, separated with commas + StringTools.append( sb, getFromList().iterator(), ", " ); + // where part - rootParameters + if ( !rootParameters.isEmpty() ) { + sb.append( " where " ); + rootParameters.build( sb, queryParamValues ); + } + // orders + if ( orders.size() > 0 ) { + sb.append( " order by " ); + StringTools.append( sb, getOrderList().iterator(), ", " ); + } + } - private List getAliasList() { - List aliasList = new ArrayList(); - for (Pair from : froms) { - aliasList.add(from.getSecond()); - } + private List getAliasList() { + final List aliasList = new ArrayList(); + for ( Pair from : froms ) { + aliasList.add( from.getSecond() ); + } - return aliasList; - } + return aliasList; + } public String getRootAlias() { return alias; } - private List getFromList() { - List fromList = new ArrayList(); - for (Pair from : froms) { - fromList.add(from.getFirst() + " " + from.getSecond()); - } + private List getFromList() { + final List fromList = new ArrayList(); + for ( Pair from : froms ) { + fromList.add( from.getFirst() + " " + from.getSecond() ); + } - return fromList; - } + return fromList; + } - private List getOrderList() { - List orderList = new ArrayList(); - for (Pair order : orders) { - orderList.add(alias + "." + order.getFirst() + " " + (order.getSecond() ? "asc" : "desc")); - } + private List getOrderList() { + final List orderList = new ArrayList(); + for ( Pair order : orders ) { + orderList.add( alias + "." + order.getFirst() + " " + (order.getSecond() ? "asc" : "desc") ); + } - return orderList; - } + return orderList; + } - public Query toQuery(Session session) { - StringBuilder querySb = new StringBuilder(); - Map queryParamValues = new HashMap(); + public Query toQuery(Session session) { + final StringBuilder querySb = new StringBuilder(); + final Map queryParamValues = new HashMap(); - build(querySb, queryParamValues); + build( querySb, queryParamValues ); - Query query = session.createQuery(querySb.toString()); - for (Map.Entry paramValue : queryParamValues.entrySet()) { - query.setParameter(paramValue.getKey(), paramValue.getValue()); - } + final Query query = session.createQuery( querySb.toString() ); + for ( Map.Entry paramValue : queryParamValues.entrySet() ) { + query.setParameter( paramValue.getKey(), paramValue.getValue() ); + } - return query; - } + return query; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/query/UpdateBuilder.java b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/query/UpdateBuilder.java index 99729fd1eb..f790e78fc3 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/query/UpdateBuilder.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/query/UpdateBuilder.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.internal.tools.query; import java.util.HashMap; @@ -11,66 +34,66 @@ import org.hibernate.envers.internal.tools.MutableInteger; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class UpdateBuilder { - private final String entityName; - private final String alias; - private final MutableInteger paramCounter; - private final Parameters rootParameters; - private final Map updates; + private final String entityName; + private final String alias; + private final MutableInteger paramCounter; + private final Parameters rootParameters; + private final Map updates; - public UpdateBuilder(String entityName, String alias) { - this(entityName, alias, new MutableInteger()); - } + public UpdateBuilder(String entityName, String alias) { + this( entityName, alias, new MutableInteger() ); + } - private UpdateBuilder(String entityName, String alias, MutableInteger paramCounter) { - this.entityName = entityName; - this.alias = alias; - this.paramCounter = paramCounter; - rootParameters = new Parameters(alias, "and", paramCounter); - updates = new HashMap(); - } + private UpdateBuilder(String entityName, String alias, MutableInteger paramCounter) { + this.entityName = entityName; + this.alias = alias; + this.paramCounter = paramCounter; + rootParameters = new Parameters( alias, "and", paramCounter ); + updates = new HashMap(); + } - public Parameters getRootParameters() { - return rootParameters; - } + public Parameters getRootParameters() { + return rootParameters; + } - public void updateValue(String propertyName, Object value) { - updates.put(propertyName, value); - } + public void updateValue(String propertyName, Object value) { + updates.put( propertyName, value ); + } - public void build(StringBuilder sb, Map updateParamValues) { - sb.append("update ").append(entityName).append(" ").append(alias); - sb.append(" set "); - int i = 1; - for (String property : updates.keySet()) { - final String paramName = generateParameterName(); - sb.append(alias).append(".").append(property).append(" = ").append(":").append(paramName); - updateParamValues.put(paramName, updates.get(property)); - if (i < updates.size()) { - sb.append(", "); - } - ++i; - } - if (!rootParameters.isEmpty()) { - sb.append(" where "); - rootParameters.build(sb, updateParamValues); - } - } + public void build(StringBuilder sb, Map updateParamValues) { + sb.append( "update " ).append( entityName ).append( " " ).append( alias ); + sb.append( " set " ); + int i = 1; + for ( String property : updates.keySet() ) { + final String paramName = generateParameterName(); + sb.append( alias ).append( "." ).append( property ).append( " = " ).append( ":" ).append( paramName ); + updateParamValues.put( paramName, updates.get( property ) ); + if ( i < updates.size() ) { + sb.append( ", " ); + } + ++i; + } + if ( !rootParameters.isEmpty() ) { + sb.append( " where " ); + rootParameters.build( sb, updateParamValues ); + } + } - private String generateParameterName() { - return "_u" + paramCounter.getAndIncrease(); - } + private String generateParameterName() { + return "_u" + paramCounter.getAndIncrease(); + } - public Query toQuery(Session session) { - StringBuilder querySb = new StringBuilder(); - Map queryParamValues = new HashMap(); + public Query toQuery(Session session) { + final StringBuilder querySb = new StringBuilder(); + final Map queryParamValues = new HashMap(); - build(querySb, queryParamValues); + build( querySb, queryParamValues ); - Query query = session.createQuery(querySb.toString()); - for (Map.Entry paramValue : queryParamValues.entrySet()) { - query.setParameter(paramValue.getKey(), paramValue.getValue()); - } + final Query query = session.createQuery( querySb.toString() ); + for ( Map.Entry paramValue : queryParamValues.entrySet() ) { + query.setParameter( paramValue.getKey(), paramValue.getValue() ); + } - return query; - } + return query; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/AuditEntity.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/AuditEntity.java index a6df9c09e3..5b6e67dc7d 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/AuditEntity.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/AuditEntity.java @@ -40,77 +40,82 @@ import org.hibernate.envers.query.internal.property.RevisionTypePropertyName; /** * TODO: ilike + * * @author Adam Warski (adam at warski dot org) * @see Restrictions */ @SuppressWarnings({"JavaDoc"}) public class AuditEntity { - private AuditEntity() { } - - public static AuditId id() { - return new AuditId(); - } - - /** - * Create restrictions, projections and specify order for a property of an audited entity. - * @param propertyName Name of the property. - */ - public static AuditProperty property(String propertyName) { - return new AuditProperty(new EntityPropertyName(propertyName)); - } - - /** - * Create restrictions, projections and specify order for the revision number, corresponding to an - * audited entity. - */ - public static AuditProperty revisionNumber() { - return new AuditProperty(new RevisionNumberPropertyName()); - } - - /** - * Create restrictions, projections and specify order for a property of the revision entity, - * corresponding to an audited entity. - * @param propertyName Name of the property. - */ - public static AuditProperty revisionProperty(String propertyName) { - return new AuditProperty(new RevisionPropertyPropertyName(propertyName)); - } - - /** - * Create restrictions, projections and specify order for the revision type, corresponding to an - * audited entity. - */ - public static AuditProperty revisionType() { - return new AuditProperty(new RevisionTypePropertyName()); - } - - /** - * Create restrictions on an id of a related entity. - * @param propertyName Name of the property, which is the relation. - */ - public static AuditRelatedId relatedId(String propertyName) { - return new AuditRelatedId(new EntityPropertyName(propertyName)); + private AuditEntity() { } - /** + public static AuditId id() { + return new AuditId(); + } + + /** + * Create restrictions, projections and specify order for a property of an audited entity. + * + * @param propertyName Name of the property. + */ + public static AuditProperty property(String propertyName) { + return new AuditProperty( new EntityPropertyName( propertyName ) ); + } + + /** + * Create restrictions, projections and specify order for the revision number, corresponding to an + * audited entity. + */ + public static AuditProperty revisionNumber() { + return new AuditProperty( new RevisionNumberPropertyName() ); + } + + /** + * Create restrictions, projections and specify order for a property of the revision entity, + * corresponding to an audited entity. + * + * @param propertyName Name of the property. + */ + public static AuditProperty revisionProperty(String propertyName) { + return new AuditProperty( new RevisionPropertyPropertyName( propertyName ) ); + } + + /** + * Create restrictions, projections and specify order for the revision type, corresponding to an + * audited entity. + */ + public static AuditProperty revisionType() { + return new AuditProperty( new RevisionTypePropertyName() ); + } + + /** + * Create restrictions on an id of a related entity. + * + * @param propertyName Name of the property, which is the relation. + */ + public static AuditRelatedId relatedId(String propertyName) { + return new AuditRelatedId( new EntityPropertyName( propertyName ) ); + } + + /** * Return the conjuction of two criterions. */ public static AuditCriterion and(AuditCriterion lhs, AuditCriterion rhs) { - return new LogicalAuditExpression(lhs, rhs, "and"); + return new LogicalAuditExpression( lhs, rhs, "and" ); } - /** + /** * Return the disjuction of two criterions. */ public static AuditCriterion or(AuditCriterion lhs, AuditCriterion rhs) { - return new LogicalAuditExpression(lhs, rhs, "or"); + return new LogicalAuditExpression( lhs, rhs, "or" ); } - /** + /** * Return the negation of a criterion. */ public static AuditCriterion not(AuditCriterion expression) { - return new NotAuditExpression(expression); + return new NotAuditExpression( expression ); } /** diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/AuditQuery.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/AuditQuery.java index 72717d93a0..6ac16e51f6 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/AuditQuery.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/AuditQuery.java @@ -22,9 +22,10 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.query; -import java.util.List; + import javax.persistence.NoResultException; import javax.persistence.NonUniqueResultException; +import java.util.List; import org.hibernate.CacheMode; import org.hibernate.FlushMode; @@ -39,31 +40,31 @@ import org.hibernate.envers.query.projection.AuditProjection; * @see org.hibernate.Criteria */ public interface AuditQuery { - List getResultList() throws AuditException; + List getResultList() throws AuditException; - Object getSingleResult() throws AuditException, NonUniqueResultException, NoResultException; + Object getSingleResult() throws AuditException, NonUniqueResultException, NoResultException; - AuditQuery add(AuditCriterion criterion); + AuditQuery add(AuditCriterion criterion); - AuditQuery addProjection(AuditProjection projection); + AuditQuery addProjection(AuditProjection projection); - AuditQuery addOrder(AuditOrder order); + AuditQuery addOrder(AuditOrder order); - AuditQuery setMaxResults(int maxResults); + AuditQuery setMaxResults(int maxResults); AuditQuery setFirstResult(int firstResult); - AuditQuery setCacheable(boolean cacheable); + AuditQuery setCacheable(boolean cacheable); - AuditQuery setCacheRegion(String cacheRegion); + AuditQuery setCacheRegion(String cacheRegion); - AuditQuery setComment(String comment); + AuditQuery setComment(String comment); - AuditQuery setFlushMode(FlushMode flushMode); + AuditQuery setFlushMode(FlushMode flushMode); - AuditQuery setCacheMode(CacheMode cacheMode); + AuditQuery setCacheMode(CacheMode cacheMode); - AuditQuery setTimeout(int timeout); + AuditQuery setTimeout(int timeout); - AuditQuery setLockMode(LockMode lockMode); + AuditQuery setLockMode(LockMode lockMode); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/AuditQueryCreator.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/AuditQueryCreator.java index a682cc8dd6..958be1e6cf 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/AuditQueryCreator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/AuditQueryCreator.java @@ -39,150 +39,188 @@ import static org.hibernate.envers.internal.tools.EntityTools.getTargetClassIfPr * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class AuditQueryCreator { - private final AuditConfiguration auditCfg; - private final AuditReaderImplementor auditReaderImplementor; + private final AuditConfiguration auditCfg; + private final AuditReaderImplementor auditReaderImplementor; - public AuditQueryCreator(AuditConfiguration auditCfg, AuditReaderImplementor auditReaderImplementor) { - this.auditCfg = auditCfg; - this.auditReaderImplementor = auditReaderImplementor; - } + public AuditQueryCreator(AuditConfiguration auditCfg, AuditReaderImplementor auditReaderImplementor) { + this.auditCfg = auditCfg; + this.auditReaderImplementor = auditReaderImplementor; + } - /** - * Creates a query, which will return entities satisfying some conditions (specified later), - * at a given revision. Deleted entities are not included. - * @param c Class of the entities for which to query. - * @param revision Revision number at which to execute the query. - * @return A query for entities at a given revision, to which conditions can be added and which - * can then be executed. The result of the query will be a list of entities (beans), unless a - * projection is added. - */ - public AuditQuery forEntitiesAtRevision(Class c, Number revision) { - checkNotNull(revision, "Entity revision"); - checkPositive(revision, "Entity revision"); - c = getTargetClassIfProxied(c); - return new EntitiesAtRevisionQuery(auditCfg, auditReaderImplementor, c, revision, false); - } - - /** - * Creates a query, which will return entities satisfying some conditions (specified later), - * at a given revision and a given entityName. Deleted entities are not included. - * @param c Class of the entities for which to query. - * @param entityName Name of the entity (if can't be guessed basing on the {@code c}). - * @param revision Revision number at which to execute the query. - * @return A query for entities at a given revision, to which conditions can be added and which - * can then be executed. The result of the query will be a list of entities (beans), unless a - * projection is added. - */ - public AuditQuery forEntitiesAtRevision(Class c, String entityName, Number revision) { - return forEntitiesAtRevision(c, entityName, revision, false); - } + /** + * Creates a query, which will return entities satisfying some conditions (specified later), + * at a given revision. Deleted entities are not included. + * + * @param c Class of the entities for which to query. + * @param revision Revision number at which to execute the query. + * + * @return A query for entities at a given revision, to which conditions can be added and which + * can then be executed. The result of the query will be a list of entities (beans), unless a + * projection is added. + */ + public AuditQuery forEntitiesAtRevision(Class c, Number revision) { + checkNotNull( revision, "Entity revision" ); + checkPositive( revision, "Entity revision" ); + c = getTargetClassIfProxied( c ); + return new EntitiesAtRevisionQuery( auditCfg, auditReaderImplementor, c, revision, false ); + } - /** - * Creates a query, which will return entities satisfying some conditions (specified later), - * at a given revision and a given entityName. Deleted entities may be optionally - * included. - * @param c Class of the entities for which to query. - * @param entityName Name of the entity (if can't be guessed basing on the {@code c}). - * @param revision Revision number at which to execute the query. - * @param includeDeletions Whether to include deleted entities in the search. - * @return A query for entities at a given revision, to which conditions can be added and which - * can then be executed. The result of the query will be a list of entities (beans), unless a - * projection is added. - */ - public AuditQuery forEntitiesAtRevision(Class c, String entityName, Number revision, boolean includeDeletions) { - checkNotNull(revision, "Entity revision"); - checkPositive(revision, "Entity revision"); - c = getTargetClassIfProxied(c); - return new EntitiesAtRevisionQuery(auditCfg, auditReaderImplementor, c, entityName, revision, includeDeletions); - } + /** + * Creates a query, which will return entities satisfying some conditions (specified later), + * at a given revision and a given entityName. Deleted entities are not included. + * + * @param c Class of the entities for which to query. + * @param entityName Name of the entity (if can't be guessed basing on the {@code c}). + * @param revision Revision number at which to execute the query. + * + * @return A query for entities at a given revision, to which conditions can be added and which + * can then be executed. The result of the query will be a list of entities (beans), unless a + * projection is added. + */ + public AuditQuery forEntitiesAtRevision(Class c, String entityName, Number revision) { + return forEntitiesAtRevision( c, entityName, revision, false ); + } - /** - * Creates a query, which will return entities modified at the specified revision. - * - * In comparison, the {@link #forEntitiesAtRevision(Class, String, Number)} query takes into all entities - * which were present at a given revision, even if they were not modified. - * - * @param c Class of the entities for which to query. - * @param entityName Name of the entity (if can't be guessed basing on the {@code c}). - * @param revision Revision number at which to execute the query. - * @return A query for entities changed at a given revision, to which conditions can be added and which - * can then be executed. - * @see #forEntitiesAtRevision(Class, String, Number) - */ - public AuditQuery forEntitiesModifiedAtRevision(Class c, String entityName, Number revision) { - checkNotNull(revision, "Entity revision"); - checkPositive(revision, "Entity revision"); - c = getTargetClassIfProxied(c); - return new EntitiesModifiedAtRevisionQuery(auditCfg, auditReaderImplementor, c, entityName, revision); - } + /** + * Creates a query, which will return entities satisfying some conditions (specified later), + * at a given revision and a given entityName. Deleted entities may be optionally + * included. + * + * @param c Class of the entities for which to query. + * @param entityName Name of the entity (if can't be guessed basing on the {@code c}). + * @param revision Revision number at which to execute the query. + * @param includeDeletions Whether to include deleted entities in the search. + * + * @return A query for entities at a given revision, to which conditions can be added and which + * can then be executed. The result of the query will be a list of entities (beans), unless a + * projection is added. + */ + public AuditQuery forEntitiesAtRevision(Class c, String entityName, Number revision, boolean includeDeletions) { + checkNotNull( revision, "Entity revision" ); + checkPositive( revision, "Entity revision" ); + c = getTargetClassIfProxied( c ); + return new EntitiesAtRevisionQuery( + auditCfg, + auditReaderImplementor, + c, + entityName, + revision, + includeDeletions + ); + } - /** - * Creates a query, which will return entities modified at the specified revision. - * - * In comparison, the {@link #forEntitiesAtRevision(Class, String, Number)} query takes into all entities - * which were present at a given revision, even if they were not modified. - * - * @param c Class of the entities for which to query. - * @param revision Revision number at which to execute the query. - * @return A query for entities changed at a given revision, to which conditions can be added and which - * can then be executed. - * @see #forEntitiesAtRevision(Class, Number) - */ - public AuditQuery forEntitiesModifiedAtRevision(Class c, Number revision) { - checkNotNull(revision, "Entity revision"); - checkPositive(revision, "Entity revision"); - c = getTargetClassIfProxied(c); - return new EntitiesModifiedAtRevisionQuery(auditCfg, auditReaderImplementor, c, revision); - } + /** + * Creates a query, which will return entities modified at the specified revision. + *

      + * In comparison, the {@link #forEntitiesAtRevision(Class, String, Number)} query takes into all entities + * which were present at a given revision, even if they were not modified. + * + * @param c Class of the entities for which to query. + * @param entityName Name of the entity (if can't be guessed basing on the {@code c}). + * @param revision Revision number at which to execute the query. + * + * @return A query for entities changed at a given revision, to which conditions can be added and which + * can then be executed. + * + * @see #forEntitiesAtRevision(Class, String, Number) + */ + public AuditQuery forEntitiesModifiedAtRevision(Class c, String entityName, Number revision) { + checkNotNull( revision, "Entity revision" ); + checkPositive( revision, "Entity revision" ); + c = getTargetClassIfProxied( c ); + return new EntitiesModifiedAtRevisionQuery( auditCfg, auditReaderImplementor, c, entityName, revision ); + } - /** - * Creates a query, which selects the revisions, at which the given entity was modified. - * Unless an explicit projection is set, the result will be a list of three-element arrays, containing: - *

        - *
      1. the entity instance
      2. - *
      3. revision entity, corresponding to the revision at which the entity was modified. If no custom - * revision entity is used, this will be an instance of {@link org.hibernate.envers.DefaultRevisionEntity}
      4. - *
      5. type of the revision (an enum instance of class {@link org.hibernate.envers.RevisionType})
      6. . - *
      - * Additional conditions that the results must satisfy may be specified. - * @param c Class of the entities for which to query. - * @param selectEntitiesOnly If true, instead of a list of three-element arrays, a list of entites will be - * returned as a result of executing this query. - * @param selectDeletedEntities If true, also revisions where entities were deleted will be returned. The additional - * entities will have revision type "delete", and contain no data (all fields null), except for the id field. - * @return A query for revisions at which instances of the given entity were modified, to which - * conditions can be added (for example - a specific id of an entity of class c), and which - * can then be executed. The results of the query will be sorted in ascending order by the revision number, - * unless an order or projection is added. - */ - public AuditQuery forRevisionsOfEntity(Class c, boolean selectEntitiesOnly, boolean selectDeletedEntities) { - c = getTargetClassIfProxied(c); - return new RevisionsOfEntityQuery(auditCfg, auditReaderImplementor, c, selectEntitiesOnly,selectDeletedEntities); - } - - /** - * Creates a query, which selects the revisions, at which the given entity was modified and with a given entityName. - * Unless an explicit projection is set, the result will be a list of three-element arrays, containing: - *
        - *
      1. the entity instance
      2. - *
      3. revision entity, corresponding to the revision at which the entity was modified. If no custom - * revision entity is used, this will be an instance of {@link org.hibernate.envers.DefaultRevisionEntity}
      4. - *
      5. type of the revision (an enum instance of class {@link org.hibernate.envers.RevisionType})
      6. . - *
      - * Additional conditions that the results must satisfy may be specified. - * @param c Class of the entities for which to query. - * @param entityName Name of the entity (if can't be guessed basing on the {@code c}). - * @param selectEntitiesOnly If true, instead of a list of three-element arrays, a list of entites will be - * returned as a result of executing this query. - * @param selectDeletedEntities If true, also revisions where entities were deleted will be returned. The additional - * entities will have revision type "delete", and contain no data (all fields null), except for the id field. - * @return A query for revisions at which instances of the given entity were modified, to which - * conditions can be added (for example - a specific id of an entity of class c), and which - * can then be executed. The results of the query will be sorted in ascending order by the revision number, - * unless an order or projection is added. - */ - public AuditQuery forRevisionsOfEntity(Class c, String entityName, boolean selectEntitiesOnly, boolean selectDeletedEntities) { - c = getTargetClassIfProxied(c); - return new RevisionsOfEntityQuery(auditCfg, auditReaderImplementor, c, entityName, selectEntitiesOnly,selectDeletedEntities); - } + /** + * Creates a query, which will return entities modified at the specified revision. + *

      + * In comparison, the {@link #forEntitiesAtRevision(Class, String, Number)} query takes into all entities + * which were present at a given revision, even if they were not modified. + * + * @param c Class of the entities for which to query. + * @param revision Revision number at which to execute the query. + * + * @return A query for entities changed at a given revision, to which conditions can be added and which + * can then be executed. + * + * @see #forEntitiesAtRevision(Class, Number) + */ + public AuditQuery forEntitiesModifiedAtRevision(Class c, Number revision) { + checkNotNull( revision, "Entity revision" ); + checkPositive( revision, "Entity revision" ); + c = getTargetClassIfProxied( c ); + return new EntitiesModifiedAtRevisionQuery( auditCfg, auditReaderImplementor, c, revision ); + } + + /** + * Creates a query, which selects the revisions, at which the given entity was modified. + * Unless an explicit projection is set, the result will be a list of three-element arrays, containing: + *

        + *
      1. the entity instance
      2. + *
      3. revision entity, corresponding to the revision at which the entity was modified. If no custom + * revision entity is used, this will be an instance of {@link org.hibernate.envers.DefaultRevisionEntity}
      4. + *
      5. type of the revision (an enum instance of class {@link org.hibernate.envers.RevisionType})
      6. . + *
      + * Additional conditions that the results must satisfy may be specified. + * + * @param c Class of the entities for which to query. + * @param selectEntitiesOnly If true, instead of a list of three-element arrays, a list of entites will be + * returned as a result of executing this query. + * @param selectDeletedEntities If true, also revisions where entities were deleted will be returned. The additional + * entities will have revision type "delete", and contain no data (all fields null), except for the id field. + * + * @return A query for revisions at which instances of the given entity were modified, to which + * conditions can be added (for example - a specific id of an entity of class c), and which + * can then be executed. The results of the query will be sorted in ascending order by the revision number, + * unless an order or projection is added. + */ + public AuditQuery forRevisionsOfEntity(Class c, boolean selectEntitiesOnly, boolean selectDeletedEntities) { + c = getTargetClassIfProxied( c ); + return new RevisionsOfEntityQuery( + auditCfg, + auditReaderImplementor, + c, + selectEntitiesOnly, + selectDeletedEntities + ); + } + + /** + * Creates a query, which selects the revisions, at which the given entity was modified and with a given entityName. + * Unless an explicit projection is set, the result will be a list of three-element arrays, containing: + *
        + *
      1. the entity instance
      2. + *
      3. revision entity, corresponding to the revision at which the entity was modified. If no custom + * revision entity is used, this will be an instance of {@link org.hibernate.envers.DefaultRevisionEntity}
      4. + *
      5. type of the revision (an enum instance of class {@link org.hibernate.envers.RevisionType})
      6. . + *
      + * Additional conditions that the results must satisfy may be specified. + * + * @param c Class of the entities for which to query. + * @param entityName Name of the entity (if can't be guessed basing on the {@code c}). + * @param selectEntitiesOnly If true, instead of a list of three-element arrays, a list of entites will be + * returned as a result of executing this query. + * @param selectDeletedEntities If true, also revisions where entities were deleted will be returned. The additional + * entities will have revision type "delete", and contain no data (all fields null), except for the id field. + * + * @return A query for revisions at which instances of the given entity were modified, to which + * conditions can be added (for example - a specific id of an entity of class c), and which + * can then be executed. The results of the query will be sorted in ascending order by the revision number, + * unless an order or projection is added. + */ + public AuditQuery forRevisionsOfEntity( + Class c, + String entityName, + boolean selectEntitiesOnly, + boolean selectDeletedEntities) { + c = getTargetClassIfProxied( c ); + return new RevisionsOfEntityQuery( + auditCfg, + auditReaderImplementor, + c, + entityName, + selectEntitiesOnly, + selectDeletedEntities + ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AggregatedAuditExpression.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AggregatedAuditExpression.java index 1bd81eae31..ac232152a5 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AggregatedAuditExpression.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AggregatedAuditExpression.java @@ -38,53 +38,59 @@ import org.hibernate.envers.query.internal.property.PropertyNameGetter; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class AggregatedAuditExpression implements AuditCriterion, ExtendableCriterion { - private PropertyNameGetter propertyNameGetter; - private AggregatedMode mode; + private PropertyNameGetter propertyNameGetter; + private AggregatedMode mode; private boolean correlate = false; // Correlate subquery with outer query by entity id. - private List criterions; + private List criterions; - public AggregatedAuditExpression(PropertyNameGetter propertyNameGetter, AggregatedMode mode) { - this.propertyNameGetter = propertyNameGetter; - this.mode = mode; - criterions = new ArrayList(); - } + public AggregatedAuditExpression(PropertyNameGetter propertyNameGetter, AggregatedMode mode) { + this.propertyNameGetter = propertyNameGetter; + this.mode = mode; + criterions = new ArrayList(); + } - public static enum AggregatedMode { - MAX, - MIN - } + public static enum AggregatedMode { + MAX, + MIN + } - public AggregatedAuditExpression add(AuditCriterion criterion) { - criterions.add(criterion); - return this; - } + public AggregatedAuditExpression add(AuditCriterion criterion) { + criterions.add( criterion ); + return this; + } - public void addToQuery(AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, - QueryBuilder qb, Parameters parameters) { - String propertyName = CriteriaTools.determinePropertyName( auditCfg, versionsReader, entityName, propertyNameGetter ); + public void addToQuery( + AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, + QueryBuilder qb, Parameters parameters) { + String propertyName = CriteriaTools.determinePropertyName( + auditCfg, + versionsReader, + entityName, + propertyNameGetter + ); - CriteriaTools.checkPropertyNotARelation(auditCfg, entityName, propertyName); + CriteriaTools.checkPropertyNotARelation( auditCfg, entityName, propertyName ); - // Make sure our conditions are ANDed together even if the parent Parameters have a different connective - Parameters subParams = parameters.addSubParameters(Parameters.AND); - // This will be the aggregated query, containing all the specified conditions - QueryBuilder subQb = qb.newSubQueryBuilder(); + // Make sure our conditions are ANDed together even if the parent Parameters have a different connective + Parameters subParams = parameters.addSubParameters( Parameters.AND ); + // This will be the aggregated query, containing all the specified conditions + QueryBuilder subQb = qb.newSubQueryBuilder(); - // Adding all specified conditions both to the main query, as well as to the - // aggregated one. - for (AuditCriterion versionsCriteria : criterions) { - versionsCriteria.addToQuery(auditCfg, versionsReader, entityName, qb, subParams); - versionsCriteria.addToQuery(auditCfg, versionsReader, entityName, subQb, subQb.getRootParameters()); - } + // Adding all specified conditions both to the main query, as well as to the + // aggregated one. + for ( AuditCriterion versionsCriteria : criterions ) { + versionsCriteria.addToQuery( auditCfg, versionsReader, entityName, qb, subParams ); + versionsCriteria.addToQuery( auditCfg, versionsReader, entityName, subQb, subQb.getRootParameters() ); + } - // Setting the desired projection of the aggregated query - switch (mode) { - case MIN: - subQb.addProjection("min", propertyName, false); - break; - case MAX: - subQb.addProjection("max", propertyName, false); - } + // Setting the desired projection of the aggregated query + switch ( mode ) { + case MIN: + subQb.addProjection( "min", propertyName, false ); + break; + case MAX: + subQb.addProjection( "max", propertyName, false ); + } // Correlating subquery with the outer query by entity id. See JIRA HHH-7827. if ( correlate ) { @@ -96,14 +102,15 @@ public class AggregatedAuditExpression implements AuditCriterion, ExtendableCrit ); } - // Adding the constrain on the result of the aggregated criteria - subParams.addWhere(propertyName, "=", subQb); - } + // Adding the constrain on the result of the aggregated criteria + subParams.addWhere( propertyName, "=", subQb ); + } /** * Compute aggregated expression in the context of each entity instance separately. Useful for retrieving latest * revisions of all entities of a particular type.
      * Implementation note: Correlates subquery with the outer query by entity id. + * * @return this (for method chaining). */ public AggregatedAuditExpression computeAggregationInInstanceContext() { diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditConjunction.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditConjunction.java index 88db0426c5..4caa107934 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditConjunction.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditConjunction.java @@ -35,27 +35,29 @@ import org.hibernate.envers.internal.tools.query.QueryBuilder; * @author Adam Warski (adam at warski dot org) */ public class AuditConjunction implements AuditCriterion, ExtendableCriterion { - private List criterions; + private List criterions; - public AuditConjunction() { - criterions = new ArrayList(); - } + public AuditConjunction() { + criterions = new ArrayList(); + } - public AuditConjunction add(AuditCriterion criterion) { - criterions.add(criterion); - return this; - } + public AuditConjunction add(AuditCriterion criterion) { + criterions.add( criterion ); + return this; + } - public void addToQuery(AuditConfiguration verCfg, AuditReaderImplementor versionsReader, String entityName, - QueryBuilder qb, Parameters parameters) { - Parameters andParameters = parameters.addSubParameters(Parameters.AND); + public void addToQuery( + AuditConfiguration verCfg, AuditReaderImplementor versionsReader, String entityName, + QueryBuilder qb, Parameters parameters) { + Parameters andParameters = parameters.addSubParameters( Parameters.AND ); - if (criterions.size() == 0) { - andParameters.addWhere("1", false, "=", "1", false); - } else { - for (AuditCriterion criterion : criterions) { - criterion.addToQuery(verCfg, versionsReader, entityName, qb, andParameters); - } - } - } + if ( criterions.size() == 0 ) { + andParameters.addWhere( "1", false, "=", "1", false ); + } + else { + for ( AuditCriterion criterion : criterions ) { + criterion.addToQuery( verCfg, versionsReader, entityName, qb, andParameters ); + } + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditCriterion.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditCriterion.java index 5be631cb23..e71e099c6c 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditCriterion.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditCriterion.java @@ -32,6 +32,7 @@ import org.hibernate.envers.internal.tools.query.QueryBuilder; * @author Adam Warski (adam at warski dot org) */ public interface AuditCriterion { - void addToQuery(AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, - QueryBuilder qb, Parameters parameters); + void addToQuery( + AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, + QueryBuilder qb, Parameters parameters); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditDisjunction.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditDisjunction.java index 4693f6374c..c7c6ed13d6 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditDisjunction.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditDisjunction.java @@ -35,27 +35,29 @@ import org.hibernate.envers.internal.tools.query.QueryBuilder; * @author Adam Warski (adam at warski dot org) */ public class AuditDisjunction implements AuditCriterion, ExtendableCriterion { - private List criterions; + private List criterions; - public AuditDisjunction() { - criterions = new ArrayList(); - } + public AuditDisjunction() { + criterions = new ArrayList(); + } - public AuditDisjunction add(AuditCriterion criterion) { - criterions.add(criterion); - return this; - } + public AuditDisjunction add(AuditCriterion criterion) { + criterions.add( criterion ); + return this; + } - public void addToQuery(AuditConfiguration verCfg, AuditReaderImplementor versionsReader, String entityName, - QueryBuilder qb, Parameters parameters) { - Parameters orParameters = parameters.addSubParameters(Parameters.OR); + public void addToQuery( + AuditConfiguration verCfg, AuditReaderImplementor versionsReader, String entityName, + QueryBuilder qb, Parameters parameters) { + Parameters orParameters = parameters.addSubParameters( Parameters.OR ); - if (criterions.size() == 0) { - orParameters.addWhere("0", false, "=", "1", false); - } else { - for (AuditCriterion criterion : criterions) { - criterion.addToQuery(verCfg, versionsReader, entityName, qb, orParameters); - } - } - } + if ( criterions.size() == 0 ) { + orParameters.addWhere( "0", false, "=", "1", false ); + } + else { + for ( AuditCriterion criterion : criterions ) { + criterion.addToQuery( verCfg, versionsReader, entityName, qb, orParameters ); + } + } + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditId.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditId.java index 08e5f138b4..6ffcc4cd45 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditId.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditId.java @@ -24,11 +24,11 @@ package org.hibernate.envers.query.criteria; import org.hibernate.envers.query.criteria.internal.IdentifierEqAuditExpression; -import org.hibernate.envers.query.projection.AuditProjection; -import org.hibernate.envers.query.projection.internal.PropertyAuditProjection; import org.hibernate.envers.query.internal.property.EntityPropertyName; import org.hibernate.envers.query.internal.property.OriginalIdPropertyName; import org.hibernate.envers.query.internal.property.PropertyNameGetter; +import org.hibernate.envers.query.projection.AuditProjection; +import org.hibernate.envers.query.projection.internal.PropertyAuditProjection; /** * Create restrictions and projections for the id of an audited entity. @@ -36,7 +36,7 @@ import org.hibernate.envers.query.internal.property.PropertyNameGetter; * @author Adam Warski (adam at warski dot org) * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ -@SuppressWarnings({ "JavaDoc" }) +@SuppressWarnings({"JavaDoc"}) public class AuditId extends AuditProperty { public static final String IDENTIFIER_PLACEHOLDER = "$$id$$"; private static final PropertyNameGetter identifierPropertyGetter = new EntityPropertyName( IDENTIFIER_PLACEHOLDER ); diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditProperty.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditProperty.java index a7824ea494..5e0f05be36 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditProperty.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditProperty.java @@ -34,246 +34,247 @@ import org.hibernate.envers.query.criteria.internal.NotNullAuditExpression; import org.hibernate.envers.query.criteria.internal.NullAuditExpression; import org.hibernate.envers.query.criteria.internal.PropertyAuditExpression; import org.hibernate.envers.query.criteria.internal.SimpleAuditExpression; +import org.hibernate.envers.query.internal.property.ModifiedFlagPropertyName; +import org.hibernate.envers.query.internal.property.PropertyNameGetter; import org.hibernate.envers.query.order.AuditOrder; import org.hibernate.envers.query.order.internal.PropertyAuditOrder; import org.hibernate.envers.query.projection.AuditProjection; import org.hibernate.envers.query.projection.internal.PropertyAuditProjection; -import org.hibernate.envers.query.internal.property.ModifiedFlagPropertyName; -import org.hibernate.envers.query.internal.property.PropertyNameGetter; /** * Create restrictions, projections and specify order for a property of an audited entity. + * * @author Adam Warski (adam at warski dot org) * @author Michal Skowronek (mskowr at o2 dot pl) */ @SuppressWarnings({"JavaDoc"}) public class AuditProperty implements AuditProjection { - private final PropertyNameGetter propertyNameGetter; + private final PropertyNameGetter propertyNameGetter; - public AuditProperty(PropertyNameGetter propertyNameGetter) { - this.propertyNameGetter = propertyNameGetter; - } + public AuditProperty(PropertyNameGetter propertyNameGetter) { + this.propertyNameGetter = propertyNameGetter; + } public AuditCriterion hasChanged() { - return new SimpleAuditExpression(new ModifiedFlagPropertyName(propertyNameGetter), true, "="); + return new SimpleAuditExpression( new ModifiedFlagPropertyName( propertyNameGetter ), true, "=" ); } public AuditCriterion hasNotChanged() { - return new SimpleAuditExpression(new ModifiedFlagPropertyName(propertyNameGetter), false, "="); + return new SimpleAuditExpression( new ModifiedFlagPropertyName( propertyNameGetter ), false, "=" ); } /** * Apply an "equal" constraint */ public AuditCriterion eq(T value) { - return new SimpleAuditExpression(propertyNameGetter, value, "="); + return new SimpleAuditExpression( propertyNameGetter, value, "=" ); } - /** + /** * Apply a "not equal" constraint */ public AuditCriterion ne(T value) { - return new SimpleAuditExpression(propertyNameGetter, value, "<>"); + return new SimpleAuditExpression( propertyNameGetter, value, "<>" ); } - /** + /** * Apply a "like" constraint */ public AuditCriterion like(T value) { - return new SimpleAuditExpression(propertyNameGetter, value, " like "); + return new SimpleAuditExpression( propertyNameGetter, value, " like " ); } - /** + /** * Apply a "like" constraint */ public AuditCriterion like(String value, MatchMode matchMode) { - return new SimpleAuditExpression(propertyNameGetter, matchMode.toMatchString(value), " like " ); + return new SimpleAuditExpression( propertyNameGetter, matchMode.toMatchString( value ), " like " ); } - /** + /** * Apply a "greater than" constraint */ public AuditCriterion gt(T value) { - return new SimpleAuditExpression(propertyNameGetter, value, ">"); + return new SimpleAuditExpression( propertyNameGetter, value, ">" ); } - /** + /** * Apply a "less than" constraint */ public AuditCriterion lt(T value) { - return new SimpleAuditExpression(propertyNameGetter, value, "<"); + return new SimpleAuditExpression( propertyNameGetter, value, "<" ); } - /** + /** * Apply a "less than or equal" constraint */ public AuditCriterion le(T value) { - return new SimpleAuditExpression(propertyNameGetter, value, "<="); + return new SimpleAuditExpression( propertyNameGetter, value, "<=" ); } - /** + /** * Apply a "greater than or equal" constraint */ public AuditCriterion ge(T value) { - return new SimpleAuditExpression(propertyNameGetter, value, ">="); + return new SimpleAuditExpression( propertyNameGetter, value, ">=" ); } - /** + /** * Apply a "between" constraint */ public AuditCriterion between(T lo, T hi) { - return new BetweenAuditExpression(propertyNameGetter, lo, hi); + return new BetweenAuditExpression( propertyNameGetter, lo, hi ); } - /** + /** * Apply an "in" constraint */ public AuditCriterion in(T[] values) { - return new InAuditExpression(propertyNameGetter, values); + return new InAuditExpression( propertyNameGetter, values ); } - /** + /** * Apply an "in" constraint */ public AuditCriterion in(Collection values) { - return new InAuditExpression(propertyNameGetter, values.toArray()); + return new InAuditExpression( propertyNameGetter, values.toArray() ); } - /** + /** * Apply an "is null" constraint */ public AuditCriterion isNull() { - return new NullAuditExpression(propertyNameGetter); + return new NullAuditExpression( propertyNameGetter ); } - /** + /** * Apply an "equal" constraint to another property */ public AuditCriterion eqProperty(String otherPropertyName) { - return new PropertyAuditExpression(propertyNameGetter, otherPropertyName, "="); + return new PropertyAuditExpression( propertyNameGetter, otherPropertyName, "=" ); } - /** + /** * Apply a "not equal" constraint to another property */ public AuditCriterion neProperty(String otherPropertyName) { - return new PropertyAuditExpression(propertyNameGetter, otherPropertyName, "<>"); + return new PropertyAuditExpression( propertyNameGetter, otherPropertyName, "<>" ); } - /** + /** * Apply a "less than" constraint to another property */ public AuditCriterion ltProperty(String otherPropertyName) { - return new PropertyAuditExpression(propertyNameGetter, otherPropertyName, "<"); + return new PropertyAuditExpression( propertyNameGetter, otherPropertyName, "<" ); } - /** + /** * Apply a "less than or equal" constraint to another property */ public AuditCriterion leProperty(String otherPropertyName) { - return new PropertyAuditExpression(propertyNameGetter, otherPropertyName, "<="); + return new PropertyAuditExpression( propertyNameGetter, otherPropertyName, "<=" ); } - /** + /** * Apply a "greater than" constraint to another property */ public AuditCriterion gtProperty(String otherPropertyName) { - return new PropertyAuditExpression(propertyNameGetter, otherPropertyName, ">"); + return new PropertyAuditExpression( propertyNameGetter, otherPropertyName, ">" ); } - /** + /** * Apply a "greater than or equal" constraint to another property */ public AuditCriterion geProperty(String otherPropertyName) { - return new PropertyAuditExpression(propertyNameGetter, otherPropertyName, ">="); + return new PropertyAuditExpression( propertyNameGetter, otherPropertyName, ">=" ); } - /** + /** * Apply an "is not null" constraint to the another property */ public AuditCriterion isNotNull() { - return new NotNullAuditExpression(propertyNameGetter); + return new NotNullAuditExpression( propertyNameGetter ); } - /** - * Apply a "maximalize" constraint, with the ability to specify further constraints on the maximized - * property - */ - public AggregatedAuditExpression maximize() { - return new AggregatedAuditExpression(propertyNameGetter, AggregatedAuditExpression.AggregatedMode.MAX); - } + /** + * Apply a "maximalize" constraint, with the ability to specify further constraints on the maximized + * property + */ + public AggregatedAuditExpression maximize() { + return new AggregatedAuditExpression( propertyNameGetter, AggregatedAuditExpression.AggregatedMode.MAX ); + } - /** - * Apply a "minimize" constraint, with the ability to specify further constraints on the minimized - * property - */ - public AggregatedAuditExpression minimize() { - return new AggregatedAuditExpression(propertyNameGetter, AggregatedAuditExpression.AggregatedMode.MIN); - } + /** + * Apply a "minimize" constraint, with the ability to specify further constraints on the minimized + * property + */ + public AggregatedAuditExpression minimize() { + return new AggregatedAuditExpression( propertyNameGetter, AggregatedAuditExpression.AggregatedMode.MIN ); + } - // Projections + // Projections - /** - * Projection on the maximum value - */ - public AuditProjection max() { - return new PropertyAuditProjection(propertyNameGetter, "max", false); - } + /** + * Projection on the maximum value + */ + public AuditProjection max() { + return new PropertyAuditProjection( propertyNameGetter, "max", false ); + } - /** - * Projection on the minimum value - */ - public AuditProjection min() { - return new PropertyAuditProjection(propertyNameGetter, "min", false); - } + /** + * Projection on the minimum value + */ + public AuditProjection min() { + return new PropertyAuditProjection( propertyNameGetter, "min", false ); + } - /** - * Projection counting the values - */ - public AuditProjection count() { - return new PropertyAuditProjection(propertyNameGetter, "count", false); - } + /** + * Projection counting the values + */ + public AuditProjection count() { + return new PropertyAuditProjection( propertyNameGetter, "count", false ); + } - /** - * Projection counting distinct values - */ - public AuditProjection countDistinct() { - return new PropertyAuditProjection(propertyNameGetter, "count", true); - } + /** + * Projection counting distinct values + */ + public AuditProjection countDistinct() { + return new PropertyAuditProjection( propertyNameGetter, "count", true ); + } - /** - * Projection on distinct values - */ - public AuditProjection distinct() { - return new PropertyAuditProjection(propertyNameGetter, null, true); - } + /** + * Projection on distinct values + */ + public AuditProjection distinct() { + return new PropertyAuditProjection( propertyNameGetter, null, true ); + } - /** - * Projection using a custom function - */ - public AuditProjection function(String functionName) { - return new PropertyAuditProjection(propertyNameGetter, functionName, false); - } + /** + * Projection using a custom function + */ + public AuditProjection function(String functionName) { + return new PropertyAuditProjection( propertyNameGetter, functionName, false ); + } - // Projection on this property + // Projection on this property - public Triple getData(AuditConfiguration auditCfg) { - return Triple.make(null, propertyNameGetter.get(auditCfg), false); - } + public Triple getData(AuditConfiguration auditCfg) { + return Triple.make( null, propertyNameGetter.get( auditCfg ), false ); + } - // Order + // Order - /** - * Sort the results by the property in ascending order - */ - public AuditOrder asc() { - return new PropertyAuditOrder(propertyNameGetter, true); - } + /** + * Sort the results by the property in ascending order + */ + public AuditOrder asc() { + return new PropertyAuditOrder( propertyNameGetter, true ); + } - /** - * Sort the results by the property in descending order - */ - public AuditOrder desc() { - return new PropertyAuditOrder(propertyNameGetter, false); - } + /** + * Sort the results by the property in descending order + */ + public AuditOrder desc() { + return new PropertyAuditOrder( propertyNameGetter, false ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditRelatedId.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditRelatedId.java index c18cac02eb..da90c6d1b0 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditRelatedId.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/AuditRelatedId.java @@ -28,27 +28,28 @@ import org.hibernate.envers.query.internal.property.PropertyNameGetter; /** * Create restrictions on an id of an entity related to an audited entity. + * * @author Adam Warski (adam at warski dot org) */ @SuppressWarnings({"JavaDoc"}) public class AuditRelatedId { - private final PropertyNameGetter propertyNameGetter; + private final PropertyNameGetter propertyNameGetter; - public AuditRelatedId(PropertyNameGetter propertyNameGetter) { - this.propertyNameGetter = propertyNameGetter; - } + public AuditRelatedId(PropertyNameGetter propertyNameGetter) { + this.propertyNameGetter = propertyNameGetter; + } - /** + /** * Apply an "equal" constraint */ public AuditCriterion eq(Object id) { - return new RelatedAuditExpression(propertyNameGetter, id, true); + return new RelatedAuditExpression( propertyNameGetter, id, true ); } - /** + /** * Apply a "not equal" constraint */ public AuditCriterion ne(Object id) { - return new RelatedAuditExpression(propertyNameGetter, id, false); + return new RelatedAuditExpression( propertyNameGetter, id, false ); } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/ExtendableCriterion.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/ExtendableCriterion.java index b79c60bd79..35cc1fbbc6 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/ExtendableCriterion.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/ExtendableCriterion.java @@ -28,5 +28,5 @@ package org.hibernate.envers.query.criteria; * @author Adam Warski (adam at warski dot org) */ public interface ExtendableCriterion { - public ExtendableCriterion add(AuditCriterion criterion); + public ExtendableCriterion add(AuditCriterion criterion); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/BetweenAuditExpression.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/BetweenAuditExpression.java index e86e65744b..90a2a95a97 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/BetweenAuditExpression.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/BetweenAuditExpression.java @@ -34,23 +34,29 @@ import org.hibernate.envers.query.internal.property.PropertyNameGetter; * @author Adam Warski (adam at warski dot org) */ public class BetweenAuditExpression implements AuditCriterion { - private PropertyNameGetter propertyNameGetter; - private Object lo; - private Object hi; + private PropertyNameGetter propertyNameGetter; + private Object lo; + private Object hi; - public BetweenAuditExpression(PropertyNameGetter propertyNameGetter, Object lo, Object hi) { - this.propertyNameGetter = propertyNameGetter; - this.lo = lo; - this.hi = hi; - } + public BetweenAuditExpression(PropertyNameGetter propertyNameGetter, Object lo, Object hi) { + this.propertyNameGetter = propertyNameGetter; + this.lo = lo; + this.hi = hi; + } - public void addToQuery(AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, - QueryBuilder qb, Parameters parameters) { - String propertyName = CriteriaTools.determinePropertyName( auditCfg, versionsReader, entityName, propertyNameGetter ); - CriteriaTools.checkPropertyNotARelation(auditCfg, entityName, propertyName); - - Parameters subParams = parameters.addSubParameters(Parameters.AND); - subParams.addWhereWithParam(propertyName, ">=", lo); - subParams.addWhereWithParam(propertyName, "<=", hi); - } + public void addToQuery( + AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, + QueryBuilder qb, Parameters parameters) { + String propertyName = CriteriaTools.determinePropertyName( + auditCfg, + versionsReader, + entityName, + propertyNameGetter + ); + CriteriaTools.checkPropertyNotARelation( auditCfg, entityName, propertyName ); + + Parameters subParams = parameters.addSubParameters( Parameters.AND ); + subParams.addWhereWithParam( propertyName, ">=", lo ); + subParams.addWhereWithParam( propertyName, "<=", hi ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/CriteriaTools.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/CriteriaTools.java index 6bf447f165..c49e766417 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/CriteriaTools.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/CriteriaTools.java @@ -35,35 +35,42 @@ import org.hibernate.envers.query.internal.property.PropertyNameGetter; * @author Adam Warski (adam at warski dot org) */ public abstract class CriteriaTools { - public static void checkPropertyNotARelation(AuditConfiguration verCfg, String entityName, - String propertyName) throws AuditException { - if (verCfg.getEntCfg().get(entityName).isRelation(propertyName)) { - throw new AuditException("This criterion cannot be used on a property that is " + - "a relation to another property."); - } - } + public static void checkPropertyNotARelation( + AuditConfiguration verCfg, String entityName, + String propertyName) throws AuditException { + if ( verCfg.getEntCfg().get( entityName ).isRelation( propertyName ) ) { + throw new AuditException( + "This criterion cannot be used on a property that is " + + "a relation to another property." + ); + } + } - public static RelationDescription getRelatedEntity(AuditConfiguration verCfg, String entityName, - String propertyName) throws AuditException { - RelationDescription relationDesc = verCfg.getEntCfg().getRelationDescription(entityName, propertyName); + public static RelationDescription getRelatedEntity( + AuditConfiguration verCfg, String entityName, + String propertyName) throws AuditException { + RelationDescription relationDesc = verCfg.getEntCfg().getRelationDescription( entityName, propertyName ); - if (relationDesc == null) { - return null; - } + if ( relationDesc == null ) { + return null; + } - if (relationDesc.getRelationType() == RelationType.TO_ONE) { - return relationDesc; - } + if ( relationDesc.getRelationType() == RelationType.TO_ONE ) { + return relationDesc; + } - throw new AuditException("This type of relation (" + entityName + "." + propertyName + - ") isn't supported and can't be used in queries."); - } + throw new AuditException( + "This type of relation (" + entityName + "." + propertyName + + ") isn't supported and can't be used in queries." + ); + } /** * @see #determinePropertyName(AuditConfiguration, AuditReaderImplementor, String, String) */ - public static String determinePropertyName(AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, - String entityName, PropertyNameGetter propertyNameGetter) { + public static String determinePropertyName( + AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, + String entityName, PropertyNameGetter propertyNameGetter) { return determinePropertyName( auditCfg, versionsReader, entityName, propertyNameGetter.get( auditCfg ) ); } @@ -72,12 +79,17 @@ public abstract class CriteriaTools { * @param versionsReader Versions reader. * @param entityName Original entity name (not audited). * @param propertyName Property name or placeholder. + * * @return Path to property. Handles identifier placeholder used by {@link org.hibernate.envers.query.criteria.AuditId}. */ - public static String determinePropertyName(AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, - String entityName, String propertyName) { + public static String determinePropertyName( + AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, + String entityName, String propertyName) { if ( AuditId.IDENTIFIER_PLACEHOLDER.equals( propertyName ) ) { - final String identifierPropertyName = versionsReader.getSessionImplementor().getFactory().getEntityPersister( entityName ).getIdentifierPropertyName(); + final String identifierPropertyName = versionsReader.getSessionImplementor() + .getFactory() + .getEntityPersister( entityName ) + .getIdentifierPropertyName(); propertyName = auditCfg.getAuditEntCfg().getOriginalIdPropName() + "." + identifierPropertyName; } return propertyName; diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/IdentifierEqAuditExpression.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/IdentifierEqAuditExpression.java index 1e916c987c..6f81d26b01 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/IdentifierEqAuditExpression.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/IdentifierEqAuditExpression.java @@ -31,20 +31,22 @@ import org.hibernate.envers.query.criteria.AuditCriterion; /** * A criterion that expresses that the id of an entity is equal or not equal to some specified value. + * * @author Adam Warski (adam at warski dot org) */ public class IdentifierEqAuditExpression implements AuditCriterion { - private final Object id; - private final boolean equals; + private final Object id; + private final boolean equals; - public IdentifierEqAuditExpression(Object id, boolean equals) { - this.id = id; - this.equals = equals; - } + public IdentifierEqAuditExpression(Object id, boolean equals) { + this.id = id; + this.equals = equals; + } - public void addToQuery(AuditConfiguration verCfg, AuditReaderImplementor versionsReader, String entityName, - QueryBuilder qb, Parameters parameters) { - verCfg.getEntCfg().get(entityName).getIdMapper() - .addIdEqualsToQuery(parameters, id, verCfg.getAuditEntCfg().getOriginalIdPropName(), equals); - } + public void addToQuery( + AuditConfiguration verCfg, AuditReaderImplementor versionsReader, String entityName, + QueryBuilder qb, Parameters parameters) { + verCfg.getEntCfg().get( entityName ).getIdMapper() + .addIdEqualsToQuery( parameters, id, verCfg.getAuditEntCfg().getOriginalIdPropName(), equals ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/InAuditExpression.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/InAuditExpression.java index ea009093e4..8e9aca71a9 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/InAuditExpression.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/InAuditExpression.java @@ -28,25 +28,30 @@ import org.hibernate.envers.internal.reader.AuditReaderImplementor; import org.hibernate.envers.internal.tools.query.Parameters; import org.hibernate.envers.internal.tools.query.QueryBuilder; import org.hibernate.envers.query.criteria.AuditCriterion; -import org.hibernate.envers.query.criteria.internal.CriteriaTools; import org.hibernate.envers.query.internal.property.PropertyNameGetter; /** * @author Adam Warski (adam at warski dot org) */ public class InAuditExpression implements AuditCriterion { - private PropertyNameGetter propertyNameGetter; - private Object[] values; + private PropertyNameGetter propertyNameGetter; + private Object[] values; - public InAuditExpression(PropertyNameGetter propertyNameGetter, Object[] values) { - this.propertyNameGetter = propertyNameGetter; - this.values = values; - } + public InAuditExpression(PropertyNameGetter propertyNameGetter, Object[] values) { + this.propertyNameGetter = propertyNameGetter; + this.values = values; + } - public void addToQuery(AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, - QueryBuilder qb, Parameters parameters) { - String propertyName = CriteriaTools.determinePropertyName( auditCfg, versionsReader, entityName, propertyNameGetter ); - CriteriaTools.checkPropertyNotARelation(auditCfg, entityName, propertyName); - parameters.addWhereWithParams(propertyName, "in (", values, ")"); - } + public void addToQuery( + AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, + QueryBuilder qb, Parameters parameters) { + String propertyName = CriteriaTools.determinePropertyName( + auditCfg, + versionsReader, + entityName, + propertyNameGetter + ); + CriteriaTools.checkPropertyNotARelation( auditCfg, entityName, propertyName ); + parameters.addWhereWithParams( propertyName, "in (", values, ")" ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/LogicalAuditExpression.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/LogicalAuditExpression.java index d0f213965e..3888ac120d 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/LogicalAuditExpression.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/LogicalAuditExpression.java @@ -33,21 +33,22 @@ import org.hibernate.envers.query.criteria.AuditCriterion; * @author Adam Warski (adam at warski dot org) */ public class LogicalAuditExpression implements AuditCriterion { - private AuditCriterion lhs; - private AuditCriterion rhs; - private String op; + private AuditCriterion lhs; + private AuditCriterion rhs; + private String op; - public LogicalAuditExpression(AuditCriterion lhs, AuditCriterion rhs, String op) { - this.lhs = lhs; - this.rhs = rhs; - this.op = op; - } + public LogicalAuditExpression(AuditCriterion lhs, AuditCriterion rhs, String op) { + this.lhs = lhs; + this.rhs = rhs; + this.op = op; + } - public void addToQuery(AuditConfiguration verCfg, AuditReaderImplementor versionsReader, String entityName, - QueryBuilder qb, Parameters parameters) { - Parameters opParameters = parameters.addSubParameters(op); + public void addToQuery( + AuditConfiguration verCfg, AuditReaderImplementor versionsReader, String entityName, + QueryBuilder qb, Parameters parameters) { + Parameters opParameters = parameters.addSubParameters( op ); - lhs.addToQuery(verCfg, versionsReader, entityName, qb, opParameters.addSubParameters("and")); - rhs.addToQuery(verCfg, versionsReader, entityName, qb, opParameters.addSubParameters("and")); - } + lhs.addToQuery( verCfg, versionsReader, entityName, qb, opParameters.addSubParameters( "and" ) ); + rhs.addToQuery( verCfg, versionsReader, entityName, qb, opParameters.addSubParameters( "and" ) ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/NotAuditExpression.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/NotAuditExpression.java index cfb5d016ba..95075d29c5 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/NotAuditExpression.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/NotAuditExpression.java @@ -33,14 +33,15 @@ import org.hibernate.envers.query.criteria.AuditCriterion; * @author Adam Warski (adam at warski dot org) */ public class NotAuditExpression implements AuditCriterion { - private AuditCriterion criterion; + private AuditCriterion criterion; - public NotAuditExpression(AuditCriterion criterion) { - this.criterion = criterion; - } + public NotAuditExpression(AuditCriterion criterion) { + this.criterion = criterion; + } - public void addToQuery(AuditConfiguration verCfg, AuditReaderImplementor versionsReader, String entityName, - QueryBuilder qb, Parameters parameters) { - criterion.addToQuery(verCfg, versionsReader, entityName, qb, parameters.addNegatedParameters()); - } + public void addToQuery( + AuditConfiguration verCfg, AuditReaderImplementor versionsReader, String entityName, + QueryBuilder qb, Parameters parameters) { + criterion.addToQuery( verCfg, versionsReader, entityName, qb, parameters.addNegatedParameters() ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/NotNullAuditExpression.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/NotNullAuditExpression.java index 1a3bfc855e..b0d3c1f87b 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/NotNullAuditExpression.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/NotNullAuditExpression.java @@ -35,21 +35,28 @@ import org.hibernate.envers.query.internal.property.PropertyNameGetter; * @author Adam Warski (adam at warski dot org) */ public class NotNullAuditExpression implements AuditCriterion { - private PropertyNameGetter propertyNameGetter; + private PropertyNameGetter propertyNameGetter; - public NotNullAuditExpression(PropertyNameGetter propertyNameGetter) { - this.propertyNameGetter = propertyNameGetter; - } + public NotNullAuditExpression(PropertyNameGetter propertyNameGetter) { + this.propertyNameGetter = propertyNameGetter; + } - public void addToQuery(AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, - QueryBuilder qb, Parameters parameters) { - String propertyName = CriteriaTools.determinePropertyName( auditCfg, versionsReader, entityName, propertyNameGetter ); - RelationDescription relatedEntity = CriteriaTools.getRelatedEntity(auditCfg, entityName, propertyName); + public void addToQuery( + AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, + QueryBuilder qb, Parameters parameters) { + String propertyName = CriteriaTools.determinePropertyName( + auditCfg, + versionsReader, + entityName, + propertyNameGetter + ); + RelationDescription relatedEntity = CriteriaTools.getRelatedEntity( auditCfg, entityName, propertyName ); - if (relatedEntity == null) { - parameters.addNotNullRestriction(propertyName, true); - } else { - relatedEntity.getIdMapper().addIdEqualsToQuery(parameters, null, null, false); - } - } + if ( relatedEntity == null ) { + parameters.addNotNullRestriction( propertyName, true ); + } + else { + relatedEntity.getIdMapper().addIdEqualsToQuery( parameters, null, null, false ); + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/NullAuditExpression.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/NullAuditExpression.java index 5bfa5d97db..5caa070226 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/NullAuditExpression.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/NullAuditExpression.java @@ -35,21 +35,28 @@ import org.hibernate.envers.query.internal.property.PropertyNameGetter; * @author Adam Warski (adam at warski dot org) */ public class NullAuditExpression implements AuditCriterion { - private PropertyNameGetter propertyNameGetter; + private PropertyNameGetter propertyNameGetter; - public NullAuditExpression(PropertyNameGetter propertyNameGetter) { - this.propertyNameGetter = propertyNameGetter; - } + public NullAuditExpression(PropertyNameGetter propertyNameGetter) { + this.propertyNameGetter = propertyNameGetter; + } - public void addToQuery(AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, - QueryBuilder qb, Parameters parameters) { - String propertyName = CriteriaTools.determinePropertyName( auditCfg, versionsReader, entityName, propertyNameGetter ); - RelationDescription relatedEntity = CriteriaTools.getRelatedEntity(auditCfg, entityName, propertyName); + public void addToQuery( + AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, + QueryBuilder qb, Parameters parameters) { + String propertyName = CriteriaTools.determinePropertyName( + auditCfg, + versionsReader, + entityName, + propertyNameGetter + ); + RelationDescription relatedEntity = CriteriaTools.getRelatedEntity( auditCfg, entityName, propertyName ); - if (relatedEntity == null) { - parameters.addNullRestriction(propertyName, true); - } else { - relatedEntity.getIdMapper().addIdEqualsToQuery(parameters, null, null, true); - } - } + if ( relatedEntity == null ) { + parameters.addNullRestriction( propertyName, true ); + } + else { + relatedEntity.getIdMapper().addIdEqualsToQuery( parameters, null, null, true ); + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/PropertyAuditExpression.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/PropertyAuditExpression.java index ba2e6d741d..71f0402336 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/PropertyAuditExpression.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/PropertyAuditExpression.java @@ -34,21 +34,27 @@ import org.hibernate.envers.query.internal.property.PropertyNameGetter; * @author Adam Warski (adam at warski dot org) */ public class PropertyAuditExpression implements AuditCriterion { - private PropertyNameGetter propertyNameGetter; - private String otherPropertyName; - private String op; + private PropertyNameGetter propertyNameGetter; + private String otherPropertyName; + private String op; - public PropertyAuditExpression(PropertyNameGetter propertyNameGetter, String otherPropertyName, String op) { - this.propertyNameGetter = propertyNameGetter; - this.otherPropertyName = otherPropertyName; - this.op = op; - } + public PropertyAuditExpression(PropertyNameGetter propertyNameGetter, String otherPropertyName, String op) { + this.propertyNameGetter = propertyNameGetter; + this.otherPropertyName = otherPropertyName; + this.op = op; + } - public void addToQuery(AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, - QueryBuilder qb, Parameters parameters) { - String propertyName = CriteriaTools.determinePropertyName( auditCfg, versionsReader, entityName, propertyNameGetter ); - CriteriaTools.checkPropertyNotARelation(auditCfg, entityName, propertyName); - CriteriaTools.checkPropertyNotARelation(auditCfg, entityName, otherPropertyName); - parameters.addWhere(propertyName, op, otherPropertyName); - } + public void addToQuery( + AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, + QueryBuilder qb, Parameters parameters) { + String propertyName = CriteriaTools.determinePropertyName( + auditCfg, + versionsReader, + entityName, + propertyNameGetter + ); + CriteriaTools.checkPropertyNotARelation( auditCfg, entityName, propertyName ); + CriteriaTools.checkPropertyNotARelation( auditCfg, entityName, otherPropertyName ); + parameters.addWhere( propertyName, op, otherPropertyName ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/RelatedAuditExpression.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/RelatedAuditExpression.java index 8feefad4ac..b0c66db63a 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/RelatedAuditExpression.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/RelatedAuditExpression.java @@ -36,27 +36,36 @@ import org.hibernate.envers.query.internal.property.PropertyNameGetter; * @author Adam Warski (adam at warski dot org) */ public class RelatedAuditExpression implements AuditCriterion { - private final PropertyNameGetter propertyNameGetter; - private final Object id; - private final boolean equals; + private final PropertyNameGetter propertyNameGetter; + private final Object id; + private final boolean equals; - public RelatedAuditExpression(PropertyNameGetter propertyNameGetter, Object id, boolean equals) { - this.propertyNameGetter = propertyNameGetter; - this.id = id; - this.equals = equals; - } + public RelatedAuditExpression(PropertyNameGetter propertyNameGetter, Object id, boolean equals) { + this.propertyNameGetter = propertyNameGetter; + this.id = id; + this.equals = equals; + } - public void addToQuery(AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, - QueryBuilder qb, Parameters parameters) { - String propertyName = CriteriaTools.determinePropertyName( auditCfg, versionsReader, entityName, propertyNameGetter ); - - RelationDescription relatedEntity = CriteriaTools.getRelatedEntity(auditCfg, entityName, propertyName); + public void addToQuery( + AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, + QueryBuilder qb, Parameters parameters) { + String propertyName = CriteriaTools.determinePropertyName( + auditCfg, + versionsReader, + entityName, + propertyNameGetter + ); - if (relatedEntity == null) { - throw new AuditException("This criterion can only be used on a property that is " + - "a relation to another property."); - } else { - relatedEntity.getIdMapper().addIdEqualsToQuery(parameters, id, null, equals); - } - } + RelationDescription relatedEntity = CriteriaTools.getRelatedEntity( auditCfg, entityName, propertyName ); + + if ( relatedEntity == null ) { + throw new AuditException( + "This criterion can only be used on a property that is " + + "a relation to another property." + ); + } + else { + relatedEntity.getIdMapper().addIdEqualsToQuery( parameters, id, null, equals ); + } + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/RevisionTypeAuditExpression.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/RevisionTypeAuditExpression.java index 59f7b1b802..b08f371c3f 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/RevisionTypeAuditExpression.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/RevisionTypeAuditExpression.java @@ -33,16 +33,17 @@ import org.hibernate.envers.query.criteria.AuditCriterion; * @author Adam Warski (adam at warski dot org) */ public class RevisionTypeAuditExpression implements AuditCriterion { - private Object value; - private String op; + private Object value; + private String op; - public RevisionTypeAuditExpression(Object value, String op) { - this.value = value; - this.op = op; - } + public RevisionTypeAuditExpression(Object value, String op) { + this.value = value; + this.op = op; + } - public void addToQuery(AuditConfiguration verCfg, AuditReaderImplementor versionsReader, String entityName, - QueryBuilder qb, Parameters parameters) { - parameters.addWhereWithParam(verCfg.getAuditEntCfg().getRevisionTypePropName(), op, value); - } + public void addToQuery( + AuditConfiguration verCfg, AuditReaderImplementor versionsReader, String entityName, + QueryBuilder qb, Parameters parameters) { + parameters.addWhereWithParam( verCfg.getAuditEntCfg().getRevisionTypePropName(), op, value ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/SimpleAuditExpression.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/SimpleAuditExpression.java index 8307a90654..4fa8a076d3 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/SimpleAuditExpression.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/criteria/internal/SimpleAuditExpression.java @@ -36,33 +36,42 @@ import org.hibernate.envers.query.internal.property.PropertyNameGetter; * @author Adam Warski (adam at warski dot org) */ public class SimpleAuditExpression implements AuditCriterion { - private PropertyNameGetter propertyNameGetter; - private Object value; - private String op; + private PropertyNameGetter propertyNameGetter; + private Object value; + private String op; - public SimpleAuditExpression(PropertyNameGetter propertyNameGetter, Object value, String op) { - this.propertyNameGetter = propertyNameGetter; - this.value = value; - this.op = op; - } + public SimpleAuditExpression(PropertyNameGetter propertyNameGetter, Object value, String op) { + this.propertyNameGetter = propertyNameGetter; + this.value = value; + this.op = op; + } - public void addToQuery(AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, - QueryBuilder qb, Parameters parameters) { - String propertyName = CriteriaTools.determinePropertyName( auditCfg, versionsReader, entityName, propertyNameGetter ); + public void addToQuery( + AuditConfiguration auditCfg, AuditReaderImplementor versionsReader, String entityName, + QueryBuilder qb, Parameters parameters) { + String propertyName = CriteriaTools.determinePropertyName( + auditCfg, + versionsReader, + entityName, + propertyNameGetter + ); - RelationDescription relatedEntity = CriteriaTools.getRelatedEntity(auditCfg, entityName, propertyName); + RelationDescription relatedEntity = CriteriaTools.getRelatedEntity( auditCfg, entityName, propertyName ); - if (relatedEntity == null) { - parameters.addWhereWithParam(propertyName, op, value); - } else { - if (!"=".equals(op) && !"<>".equals(op)) { - throw new AuditException("This type of operation: " + op + " (" + entityName + "." + propertyName + - ") isn't supported and can't be used in queries."); - } + if ( relatedEntity == null ) { + parameters.addWhereWithParam( propertyName, op, value ); + } + else { + if ( !"=".equals( op ) && !"<>".equals( op ) ) { + throw new AuditException( + "This type of operation: " + op + " (" + entityName + "." + propertyName + + ") isn't supported and can't be used in queries." + ); + } - Object id = relatedEntity.getIdMapper().mapToIdFromEntity(value); + Object id = relatedEntity.getIdMapper().mapToIdFromEntity( value ); - relatedEntity.getIdMapper().addIdEqualsToQuery(parameters, id, null, "=".equals(op)); - } - } + relatedEntity.getIdMapper().addIdEqualsToQuery( parameters, id, null, "=".equals( op ) ); + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/AbstractAuditQuery.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/AbstractAuditQuery.java index ec891363a0..ddcc1f3301 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/AbstractAuditQuery.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/AbstractAuditQuery.java @@ -23,10 +23,10 @@ */ package org.hibernate.envers.query.internal.impl; -import java.util.ArrayList; -import java.util.List; import javax.persistence.NoResultException; import javax.persistence.NonUniqueResultException; +import java.util.ArrayList; +import java.util.List; import org.hibernate.CacheMode; import org.hibernate.FlushMode; @@ -53,179 +53,214 @@ import static org.hibernate.envers.internal.entities.mapper.relation.query.Query * @author HernпїЅn Chanfreau */ public abstract class AbstractAuditQuery implements AuditQuery { - protected EntityInstantiator entityInstantiator; - protected List criterions; + protected EntityInstantiator entityInstantiator; + protected List criterions; - protected String entityName; - protected String entityClassName; - protected String versionsEntityName; - protected QueryBuilder qb; + protected String entityName; + protected String entityClassName; + protected String versionsEntityName; + protected QueryBuilder qb; - protected boolean hasProjection; - protected boolean hasOrder; + protected boolean hasProjection; + protected boolean hasOrder; - protected final AuditConfiguration verCfg; - protected final AuditReaderImplementor versionsReader; + protected final AuditConfiguration verCfg; + protected final AuditReaderImplementor versionsReader; - protected AbstractAuditQuery(AuditConfiguration verCfg, AuditReaderImplementor versionsReader, - Class cls) { - this(verCfg, versionsReader, cls, cls.getName()); - } + protected AbstractAuditQuery( + AuditConfiguration verCfg, AuditReaderImplementor versionsReader, + Class cls) { + this( verCfg, versionsReader, cls, cls.getName() ); + } - protected AbstractAuditQuery(AuditConfiguration verCfg, - AuditReaderImplementor versionsReader, Class cls, String entityName) { + protected AbstractAuditQuery( + AuditConfiguration verCfg, + AuditReaderImplementor versionsReader, Class cls, String entityName) { this.verCfg = verCfg; this.versionsReader = versionsReader; criterions = new ArrayList(); - entityInstantiator = new EntityInstantiator(verCfg, versionsReader); + entityInstantiator = new EntityInstantiator( verCfg, versionsReader ); entityClassName = cls.getName(); this.entityName = entityName; versionsEntityName = verCfg.getAuditEntCfg().getAuditEntityName( - entityName); + entityName + ); - qb = new QueryBuilder(versionsEntityName, REFERENCED_ENTITY_ALIAS); + qb = new QueryBuilder( versionsEntityName, REFERENCED_ENTITY_ALIAS ); } - - protected Query buildQuery() { - Query query = qb.toQuery(versionsReader.getSession()); - setQueryProperties(query); - return query; - } - + + protected Query buildQuery() { + Query query = qb.toQuery( versionsReader.getSession() ); + setQueryProperties( query ); + return query; + } + protected List buildAndExecuteQuery() { - Query query = buildQuery(); + Query query = buildQuery(); - return query.list(); - } + return query.list(); + } - public abstract List list() throws AuditException; + public abstract List list() throws AuditException; - public List getResultList() throws AuditException { - return list(); - } + public List getResultList() throws AuditException { + return list(); + } - public Object getSingleResult() throws AuditException, NonUniqueResultException, NoResultException { - List result = list(); + public Object getSingleResult() throws AuditException, NonUniqueResultException, NoResultException { + List result = list(); - if (result == null || result.size() == 0) { - throw new NoResultException(); - } + if ( result == null || result.size() == 0 ) { + throw new NoResultException(); + } - if (result.size() > 1) { - throw new NonUniqueResultException(); - } + if ( result.size() > 1 ) { + throw new NonUniqueResultException(); + } - return result.get(0); - } + return result.get( 0 ); + } - public AuditQuery add(AuditCriterion criterion) { - criterions.add(criterion); - return this; - } + public AuditQuery add(AuditCriterion criterion) { + criterions.add( criterion ); + return this; + } - // Projection and order + // Projection and order - public AuditQuery addProjection(AuditProjection projection) { - Triple projectionData = projection.getData(verCfg); - hasProjection = true; - String propertyName = CriteriaTools.determinePropertyName( verCfg, versionsReader, entityName, projectionData.getSecond() ); - qb.addProjection(projectionData.getFirst(), propertyName, projectionData.getThird()); - return this; - } + public AuditQuery addProjection(AuditProjection projection) { + Triple projectionData = projection.getData( verCfg ); + hasProjection = true; + String propertyName = CriteriaTools.determinePropertyName( + verCfg, + versionsReader, + entityName, + projectionData.getSecond() + ); + qb.addProjection( projectionData.getFirst(), propertyName, projectionData.getThird() ); + return this; + } - public AuditQuery addOrder(AuditOrder order) { - hasOrder = true; - Pair orderData = order.getData(verCfg); - String propertyName = CriteriaTools.determinePropertyName( verCfg, versionsReader, entityName, orderData.getFirst() ); - qb.addOrder(propertyName, orderData.getSecond()); - return this; - } + public AuditQuery addOrder(AuditOrder order) { + hasOrder = true; + Pair orderData = order.getData( verCfg ); + String propertyName = CriteriaTools.determinePropertyName( + verCfg, + versionsReader, + entityName, + orderData.getFirst() + ); + qb.addOrder( propertyName, orderData.getSecond() ); + return this; + } - // Query properties + // Query properties - private Integer maxResults; - private Integer firstResult; - private Boolean cacheable; - private String cacheRegion; - private String comment; - private FlushMode flushMode; - private CacheMode cacheMode; - private Integer timeout; - private LockOptions lockOptions = new LockOptions(LockMode.NONE); + private Integer maxResults; + private Integer firstResult; + private Boolean cacheable; + private String cacheRegion; + private String comment; + private FlushMode flushMode; + private CacheMode cacheMode; + private Integer timeout; + private LockOptions lockOptions = new LockOptions( LockMode.NONE ); - public AuditQuery setMaxResults(int maxResults) { - this.maxResults = maxResults; - return this; - } + public AuditQuery setMaxResults(int maxResults) { + this.maxResults = maxResults; + return this; + } - public AuditQuery setFirstResult(int firstResult) { - this.firstResult = firstResult; - return this; - } + public AuditQuery setFirstResult(int firstResult) { + this.firstResult = firstResult; + return this; + } - public AuditQuery setCacheable(boolean cacheable) { - this.cacheable = cacheable; - return this; - } + public AuditQuery setCacheable(boolean cacheable) { + this.cacheable = cacheable; + return this; + } - public AuditQuery setCacheRegion(String cacheRegion) { - this.cacheRegion = cacheRegion; - return this; - } + public AuditQuery setCacheRegion(String cacheRegion) { + this.cacheRegion = cacheRegion; + return this; + } - public AuditQuery setComment(String comment) { - this.comment = comment; - return this; - } + public AuditQuery setComment(String comment) { + this.comment = comment; + return this; + } - public AuditQuery setFlushMode(FlushMode flushMode) { - this.flushMode = flushMode; - return this; - } + public AuditQuery setFlushMode(FlushMode flushMode) { + this.flushMode = flushMode; + return this; + } - public AuditQuery setCacheMode(CacheMode cacheMode) { - this.cacheMode = cacheMode; - return this; - } + public AuditQuery setCacheMode(CacheMode cacheMode) { + this.cacheMode = cacheMode; + return this; + } - public AuditQuery setTimeout(int timeout) { - this.timeout = timeout; - return this; - } + public AuditQuery setTimeout(int timeout) { + this.timeout = timeout; + return this; + } /** * Set lock mode + * * @param lockMode The {@link LockMode} used for this query. + * * @return this object + * * @deprecated Instead use setLockOptions */ - public AuditQuery setLockMode(LockMode lockMode) { - lockOptions.setLockMode(lockMode); - return this; - } + public AuditQuery setLockMode(LockMode lockMode) { + lockOptions.setLockMode( lockMode ); + return this; + } /** * Set lock options + * * @param lockOptions The @{link LockOptions} used for this query. + * * @return this object */ public AuditQuery setLockOptions(LockOptions lockOptions) { - LockOptions.copy(lockOptions, this.lockOptions); + LockOptions.copy( lockOptions, this.lockOptions ); return this; } - protected void setQueryProperties(Query query) { - if (maxResults != null) query.setMaxResults(maxResults); - if (firstResult != null) query.setFirstResult(firstResult); - if (cacheable != null) query.setCacheable(cacheable); - if (cacheRegion != null) query.setCacheRegion(cacheRegion); - if (comment != null) query.setComment(comment); - if (flushMode != null) query.setFlushMode(flushMode); - if (cacheMode != null) query.setCacheMode(cacheMode); - if (timeout != null) query.setTimeout(timeout); - if (lockOptions != null && lockOptions.getLockMode() != LockMode.NONE) { - query.setLockMode(REFERENCED_ENTITY_ALIAS, lockOptions.getLockMode()); - } - } + + protected void setQueryProperties(Query query) { + if ( maxResults != null ) { + query.setMaxResults( maxResults ); + } + if ( firstResult != null ) { + query.setFirstResult( firstResult ); + } + if ( cacheable != null ) { + query.setCacheable( cacheable ); + } + if ( cacheRegion != null ) { + query.setCacheRegion( cacheRegion ); + } + if ( comment != null ) { + query.setComment( comment ); + } + if ( flushMode != null ) { + query.setFlushMode( flushMode ); + } + if ( cacheMode != null ) { + query.setCacheMode( cacheMode ); + } + if ( timeout != null ) { + query.setTimeout( timeout ); + } + if ( lockOptions != null && lockOptions.getLockMode() != LockMode.NONE ) { + query.setLockMode( REFERENCED_ENTITY_ALIAS, lockOptions.getLockMode() ); + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/EntitiesAtRevisionQuery.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/EntitiesAtRevisionQuery.java index 8f3930f29a..2bdbd2a7eb 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/EntitiesAtRevisionQuery.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/EntitiesAtRevisionQuery.java @@ -44,28 +44,30 @@ import static org.hibernate.envers.internal.entities.mapper.relation.query.Query * @author HernпїЅn Chanfreau */ public class EntitiesAtRevisionQuery extends AbstractAuditQuery { - private final Number revision; - private final boolean includeDeletions; + private final Number revision; + private final boolean includeDeletions; - public EntitiesAtRevisionQuery(AuditConfiguration verCfg, - AuditReaderImplementor versionsReader, Class cls, - Number revision, boolean includeDeletions) { - super(verCfg, versionsReader, cls); - this.revision = revision; - this.includeDeletions = includeDeletions; - } + public EntitiesAtRevisionQuery( + AuditConfiguration verCfg, + AuditReaderImplementor versionsReader, Class cls, + Number revision, boolean includeDeletions) { + super( verCfg, versionsReader, cls ); + this.revision = revision; + this.includeDeletions = includeDeletions; + } - public EntitiesAtRevisionQuery(AuditConfiguration verCfg, - AuditReaderImplementor versionsReader, Class cls, - String entityName, Number revision, boolean includeDeletions) { - super(verCfg, versionsReader, cls, entityName); - this.revision = revision; - this.includeDeletions = includeDeletions; - } - - @SuppressWarnings({"unchecked"}) - public List list() { - /* + public EntitiesAtRevisionQuery( + AuditConfiguration verCfg, + AuditReaderImplementor versionsReader, Class cls, + String entityName, Number revision, boolean includeDeletions) { + super( verCfg, versionsReader, cls, entityName ); + this.revision = revision; + this.includeDeletions = includeDeletions; + } + + @SuppressWarnings({"unchecked"}) + public List list() { + /* * The query that we need to create: * SELECT new list(e) FROM versionsReferencedEntity e * WHERE @@ -82,44 +84,58 @@ public class EntitiesAtRevisionQuery extends AbstractAuditQuery { * (only non-deleted entities) * e.revision_type != DEL */ - AuditEntitiesConfiguration verEntCfg = verCfg.getAuditEntCfg(); - String revisionPropertyPath = verEntCfg.getRevisionNumberPath(); - String originalIdPropertyName = verEntCfg.getOriginalIdPropName(); + AuditEntitiesConfiguration verEntCfg = verCfg.getAuditEntCfg(); + String revisionPropertyPath = verEntCfg.getRevisionNumberPath(); + String originalIdPropertyName = verEntCfg.getOriginalIdPropName(); - MiddleIdData referencedIdData = new MiddleIdData(verEntCfg, verCfg.getEntCfg().get(entityName).getIdMappingData(), - null, entityName, verCfg.getEntCfg().isVersioned(entityName)); + MiddleIdData referencedIdData = new MiddleIdData( + verEntCfg, verCfg.getEntCfg().get( entityName ).getIdMappingData(), + null, entityName, verCfg.getEntCfg().isVersioned( entityName ) + ); - // (selecting e entities at revision :revision) - // --> based on auditStrategy (see above) - verCfg.getAuditStrategy().addEntityAtRevisionRestriction(verCfg.getGlobalCfg(), qb, qb.getRootParameters(), - revisionPropertyPath, verEntCfg.getRevisionEndFieldName(), true, referencedIdData, - revisionPropertyPath, originalIdPropertyName, REFERENCED_ENTITY_ALIAS, REFERENCED_ENTITY_ALIAS_DEF_AUD_STR, true); + // (selecting e entities at revision :revision) + // --> based on auditStrategy (see above) + verCfg.getAuditStrategy().addEntityAtRevisionRestriction( + verCfg.getGlobalCfg(), + qb, + qb.getRootParameters(), + revisionPropertyPath, + verEntCfg.getRevisionEndFieldName(), + true, + referencedIdData, + revisionPropertyPath, + originalIdPropertyName, + REFERENCED_ENTITY_ALIAS, + REFERENCED_ENTITY_ALIAS_DEF_AUD_STR, + true + ); - if (!includeDeletions) { - // e.revision_type != DEL - qb.getRootParameters().addWhereWithParam(verEntCfg.getRevisionTypePropName(), "<>", RevisionType.DEL); - } + if ( !includeDeletions ) { + // e.revision_type != DEL + qb.getRootParameters().addWhereWithParam( verEntCfg.getRevisionTypePropName(), "<>", RevisionType.DEL ); + } - // all specified conditions - for (AuditCriterion criterion : criterions) { - criterion.addToQuery(verCfg, versionsReader, entityName, qb, qb.getRootParameters()); - } - - Query query = buildQuery(); - // add named parameter (only used for ValidAuditTimeStrategy) - List params = Arrays.asList(query.getNamedParameters()); - if (params.contains(REVISION_PARAMETER)) { - query.setParameter(REVISION_PARAMETER, revision); - } - List queryResult = query.list(); + // all specified conditions + for ( AuditCriterion criterion : criterions ) { + criterion.addToQuery( verCfg, versionsReader, entityName, qb, qb.getRootParameters() ); + } - if (hasProjection) { - return queryResult; - } else { - List result = new ArrayList(); - entityInstantiator.addInstancesFromVersionsEntities(entityName, result, queryResult, revision); + Query query = buildQuery(); + // add named parameter (only used for ValidAuditTimeStrategy) + List params = Arrays.asList( query.getNamedParameters() ); + if ( params.contains( REVISION_PARAMETER ) ) { + query.setParameter( REVISION_PARAMETER, revision ); + } + List queryResult = query.list(); - return result; - } - } + if ( hasProjection ) { + return queryResult; + } + else { + List result = new ArrayList(); + entityInstantiator.addInstancesFromVersionsEntities( entityName, result, queryResult, revision ); + + return result; + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/EntitiesModifiedAtRevisionQuery.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/EntitiesModifiedAtRevisionQuery.java index deb8f41b06..cd1dce0d68 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/EntitiesModifiedAtRevisionQuery.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/EntitiesModifiedAtRevisionQuery.java @@ -12,52 +12,56 @@ import org.hibernate.envers.query.criteria.AuditCriterion; /** * In comparison to {@link EntitiesAtRevisionQuery} this query returns an empty collection if an entity * of a certain type has not been changed in a given revision. - * @see EntitiesAtRevisionQuery + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) + * @see EntitiesAtRevisionQuery */ public class EntitiesModifiedAtRevisionQuery extends AbstractAuditQuery { - private final Number revision; + private final Number revision; - public EntitiesModifiedAtRevisionQuery(AuditConfiguration verCfg, AuditReaderImplementor versionsReader, - Class cls, Number revision) { - super(verCfg, versionsReader, cls); - this.revision = revision; - } + public EntitiesModifiedAtRevisionQuery( + AuditConfiguration verCfg, AuditReaderImplementor versionsReader, + Class cls, Number revision) { + super( verCfg, versionsReader, cls ); + this.revision = revision; + } - public EntitiesModifiedAtRevisionQuery(AuditConfiguration verCfg, AuditReaderImplementor versionsReader, - Class cls, String entityName, Number revision) { - super(verCfg, versionsReader, cls, entityName); - this.revision = revision; - } + public EntitiesModifiedAtRevisionQuery( + AuditConfiguration verCfg, AuditReaderImplementor versionsReader, + Class cls, String entityName, Number revision) { + super( verCfg, versionsReader, cls, entityName ); + this.revision = revision; + } - @SuppressWarnings({"unchecked"}) - public List list() { - /* + @SuppressWarnings({"unchecked"}) + public List list() { + /* * The query that we need to create: * SELECT new list(e) FROM versionsReferencedEntity e * WHERE * (all specified conditions, transformed, on the "e" entity) AND * e.revision = :revision */ - AuditEntitiesConfiguration verEntCfg = verCfg.getAuditEntCfg(); - String revisionPropertyPath = verEntCfg.getRevisionNumberPath(); - qb.getRootParameters().addWhereWithParam(revisionPropertyPath, "=", revision); + AuditEntitiesConfiguration verEntCfg = verCfg.getAuditEntCfg(); + String revisionPropertyPath = verEntCfg.getRevisionNumberPath(); + qb.getRootParameters().addWhereWithParam( revisionPropertyPath, "=", revision ); - // all specified conditions - for (AuditCriterion criterion : criterions) { - criterion.addToQuery(verCfg, versionsReader, entityName, qb, qb.getRootParameters()); - } + // all specified conditions + for ( AuditCriterion criterion : criterions ) { + criterion.addToQuery( verCfg, versionsReader, entityName, qb, qb.getRootParameters() ); + } - Query query = buildQuery(); - List queryResult = query.list(); + Query query = buildQuery(); + List queryResult = query.list(); - if (hasProjection) { - return queryResult; - } else { - List result = new ArrayList(); - entityInstantiator.addInstancesFromVersionsEntities(entityName, result, queryResult, revision); + if ( hasProjection ) { + return queryResult; + } + else { + List result = new ArrayList(); + entityInstantiator.addInstancesFromVersionsEntities( entityName, result, queryResult, revision ); - return result; - } - } + return result; + } + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/RevisionsOfEntityQuery.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/RevisionsOfEntityQuery.java index 93ca0742d3..b60bff02c5 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/RevisionsOfEntityQuery.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/impl/RevisionsOfEntityQuery.java @@ -40,108 +40,124 @@ import org.hibernate.proxy.HibernateProxy; * @author HernпїЅn Chanfreau */ public class RevisionsOfEntityQuery extends AbstractAuditQuery { - private final boolean selectEntitiesOnly; - private final boolean selectDeletedEntities; + private final boolean selectEntitiesOnly; + private final boolean selectDeletedEntities; - public RevisionsOfEntityQuery(AuditConfiguration verCfg, - AuditReaderImplementor versionsReader, - Class cls, boolean selectEntitiesOnly, - boolean selectDeletedEntities) { - super(verCfg, versionsReader, cls); - - this.selectEntitiesOnly = selectEntitiesOnly; - this.selectDeletedEntities = selectDeletedEntities; - } - - public RevisionsOfEntityQuery(AuditConfiguration verCfg, - AuditReaderImplementor versionsReader, Class cls, String entityName, - boolean selectEntitiesOnly, boolean selectDeletedEntities) { - super(verCfg, versionsReader, cls, entityName); + public RevisionsOfEntityQuery( + AuditConfiguration verCfg, + AuditReaderImplementor versionsReader, + Class cls, boolean selectEntitiesOnly, + boolean selectDeletedEntities) { + super( verCfg, versionsReader, cls ); this.selectEntitiesOnly = selectEntitiesOnly; this.selectDeletedEntities = selectDeletedEntities; } - - private Number getRevisionNumber(Map versionsEntity) { - AuditEntitiesConfiguration verEntCfg = verCfg.getAuditEntCfg(); - String originalId = verEntCfg.getOriginalIdPropName(); - String revisionPropertyName = verEntCfg.getRevisionFieldName(); + public RevisionsOfEntityQuery( + AuditConfiguration verCfg, + AuditReaderImplementor versionsReader, Class cls, String entityName, + boolean selectEntitiesOnly, boolean selectDeletedEntities) { + super( verCfg, versionsReader, cls, entityName ); - Object revisionInfoObject = ((Map) versionsEntity.get(originalId)).get(revisionPropertyName); + this.selectEntitiesOnly = selectEntitiesOnly; + this.selectDeletedEntities = selectDeletedEntities; + } - if (revisionInfoObject instanceof HibernateProxy) { - return (Number) ((HibernateProxy) revisionInfoObject).getHibernateLazyInitializer().getIdentifier(); - } else { - // Not a proxy - must be read from cache or with a join - return verCfg.getRevisionInfoNumberReader().getRevisionNumber(revisionInfoObject); - } - } + private Number getRevisionNumber(Map versionsEntity) { + AuditEntitiesConfiguration verEntCfg = verCfg.getAuditEntCfg(); - @SuppressWarnings({"unchecked"}) - public List list() throws AuditException { - AuditEntitiesConfiguration verEntCfg = verCfg.getAuditEntCfg(); + String originalId = verEntCfg.getOriginalIdPropName(); + String revisionPropertyName = verEntCfg.getRevisionFieldName(); + + Object revisionInfoObject = ((Map) versionsEntity.get( originalId )).get( revisionPropertyName ); + + if ( revisionInfoObject instanceof HibernateProxy ) { + return (Number) ((HibernateProxy) revisionInfoObject).getHibernateLazyInitializer().getIdentifier(); + } + else { + // Not a proxy - must be read from cache or with a join + return verCfg.getRevisionInfoNumberReader().getRevisionNumber( revisionInfoObject ); + } + } + + @SuppressWarnings({"unchecked"}) + public List list() throws AuditException { + AuditEntitiesConfiguration verEntCfg = verCfg.getAuditEntCfg(); /* - The query that should be executed in the versions table: + The query that should be executed in the versions table: SELECT e (unless another projection is specified) FROM ent_ver e, rev_entity r WHERE e.revision_type != DEL (if selectDeletedEntities == false) AND e.revision = r.revision AND (all specified conditions, transformed, on the "e" entity) ORDER BY e.revision ASC (unless another order or projection is specified) - */ - if (!selectDeletedEntities) { - // e.revision_type != DEL AND - qb.getRootParameters().addWhereWithParam(verEntCfg.getRevisionTypePropName(), "<>", RevisionType.DEL); - } + */ + if ( !selectDeletedEntities ) { + // e.revision_type != DEL AND + qb.getRootParameters().addWhereWithParam( verEntCfg.getRevisionTypePropName(), "<>", RevisionType.DEL ); + } - // all specified conditions, transformed - for (AuditCriterion criterion : criterions) { - criterion.addToQuery(verCfg, versionsReader, entityName, qb, qb.getRootParameters()); - } + // all specified conditions, transformed + for ( AuditCriterion criterion : criterions ) { + criterion.addToQuery( verCfg, versionsReader, entityName, qb, qb.getRootParameters() ); + } - if (!hasProjection && !hasOrder) { - String revisionPropertyPath = verEntCfg.getRevisionNumberPath(); - qb.addOrder(revisionPropertyPath, true); - } + if ( !hasProjection && !hasOrder ) { + String revisionPropertyPath = verEntCfg.getRevisionNumberPath(); + qb.addOrder( revisionPropertyPath, true ); + } - if (!selectEntitiesOnly) { - qb.addFrom(verCfg.getAuditEntCfg().getRevisionInfoEntityName(), "r"); - qb.getRootParameters().addWhere(verCfg.getAuditEntCfg().getRevisionNumberPath(), true, "=", "r.id", false); - } + if ( !selectEntitiesOnly ) { + qb.addFrom( verCfg.getAuditEntCfg().getRevisionInfoEntityName(), "r" ); + qb.getRootParameters().addWhere( + verCfg.getAuditEntCfg().getRevisionNumberPath(), + true, + "=", + "r.id", + false + ); + } - List queryResult = buildAndExecuteQuery(); - if (hasProjection) { - return queryResult; - } else { - List entities = new ArrayList(); - String revisionTypePropertyName = verEntCfg.getRevisionTypePropName(); + List queryResult = buildAndExecuteQuery(); + if ( hasProjection ) { + return queryResult; + } + else { + List entities = new ArrayList(); + String revisionTypePropertyName = verEntCfg.getRevisionTypePropName(); - for (Object resultRow : queryResult) { - Map versionsEntity; - Object revisionData; + for ( Object resultRow : queryResult ) { + Map versionsEntity; + Object revisionData; - if (selectEntitiesOnly) { - versionsEntity = (Map) resultRow; - revisionData = null; - } else { - Object[] arrayResultRow = (Object[]) resultRow; - versionsEntity = (Map) arrayResultRow[0]; - revisionData = arrayResultRow[1]; - } + if ( selectEntitiesOnly ) { + versionsEntity = (Map) resultRow; + revisionData = null; + } + else { + Object[] arrayResultRow = (Object[]) resultRow; + versionsEntity = (Map) arrayResultRow[0]; + revisionData = arrayResultRow[1]; + } - Number revision = getRevisionNumber(versionsEntity); - - Object entity = entityInstantiator.createInstanceFromVersionsEntity(entityName, versionsEntity, revision); + Number revision = getRevisionNumber( versionsEntity ); - if (!selectEntitiesOnly) { - entities.add(new Object[] { entity, revisionData, versionsEntity.get(revisionTypePropertyName) }); - } else { - entities.add(entity); - } - } + Object entity = entityInstantiator.createInstanceFromVersionsEntity( + entityName, + versionsEntity, + revision + ); - return entities; - } - } + if ( !selectEntitiesOnly ) { + entities.add( new Object[] {entity, revisionData, versionsEntity.get( revisionTypePropertyName )} ); + } + else { + entities.add( entity ); + } + } + + return entities; + } + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/EntityPropertyName.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/EntityPropertyName.java index 7174136bca..daa6d925bf 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/EntityPropertyName.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/EntityPropertyName.java @@ -27,16 +27,17 @@ import org.hibernate.envers.configuration.spi.AuditConfiguration; /** * Used for specifying restrictions on a property of an audited entity. + * * @author Adam Warski (adam at warski dot org) */ public class EntityPropertyName implements PropertyNameGetter { - private final String propertyName; + private final String propertyName; - public EntityPropertyName(String propertyName) { - this.propertyName = propertyName; - } + public EntityPropertyName(String propertyName) { + this.propertyName = propertyName; + } - public String get(AuditConfiguration auditCfg) { - return propertyName; - } + public String get(AuditConfiguration auditCfg) { + return propertyName; + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/ModifiedFlagPropertyName.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/ModifiedFlagPropertyName.java index de4cedef35..902ddeebcb 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/ModifiedFlagPropertyName.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/ModifiedFlagPropertyName.java @@ -28,18 +28,20 @@ import org.hibernate.envers.configuration.spi.AuditConfiguration; /** * PropertyNameGetter for modified flags + * * @author Michal Skowronek (mskowr at o2 dot pl) */ public class ModifiedFlagPropertyName implements PropertyNameGetter { - private final PropertyNameGetter propertyNameGetter; + private final PropertyNameGetter propertyNameGetter; - public ModifiedFlagPropertyName(PropertyNameGetter propertyNameGetter) { - this.propertyNameGetter = propertyNameGetter; - } + public ModifiedFlagPropertyName(PropertyNameGetter propertyNameGetter) { + this.propertyNameGetter = propertyNameGetter; + } - public String get(AuditConfiguration auditCfg) { + public String get(AuditConfiguration auditCfg) { return MetadataTools.getModifiedFlagPropertyName( - propertyNameGetter.get(auditCfg), - auditCfg.getGlobalCfg().getModifiedFlagSuffix()); - } + propertyNameGetter.get( auditCfg ), + auditCfg.getGlobalCfg().getModifiedFlagSuffix() + ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/OriginalIdPropertyName.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/OriginalIdPropertyName.java index a6cbcbd462..5187efc0e2 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/OriginalIdPropertyName.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/OriginalIdPropertyName.java @@ -29,18 +29,17 @@ import org.hibernate.envers.query.criteria.AuditId; /** * Used for specifying restrictions on the identifier. * - * @deprecated To be removed together with {@link AuditId#count(String)} in version 5.0. - * * @author Adam Warski (adam at warski dot org) + * @deprecated To be removed together with {@link AuditId#count(String)} in version 5.0. */ public class OriginalIdPropertyName implements PropertyNameGetter { - private final String idPropertyName; + private final String idPropertyName; - public OriginalIdPropertyName(String idPropertyName) { - this.idPropertyName = idPropertyName; - } + public OriginalIdPropertyName(String idPropertyName) { + this.idPropertyName = idPropertyName; + } - public String get(AuditConfiguration auditCfg) { - return auditCfg.getAuditEntCfg().getOriginalIdPropName() + "." + idPropertyName; - } + public String get(AuditConfiguration auditCfg) { + return auditCfg.getAuditEntCfg().getOriginalIdPropName() + "." + idPropertyName; + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/PropertyNameGetter.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/PropertyNameGetter.java index e49475e23e..b8ce13b04a 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/PropertyNameGetter.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/PropertyNameGetter.java @@ -27,12 +27,14 @@ import org.hibernate.envers.configuration.spi.AuditConfiguration; /** * Provides a function to get the name of a property, which is used in a query, to apply some restrictions on it. + * * @author Adam Warski (adam at warski dot org) */ public interface PropertyNameGetter { - /** - * @param auditCfg Audit configuration. - * @return Name of the property, to be used in a query. - */ - public String get(AuditConfiguration auditCfg); + /** + * @param auditCfg Audit configuration. + * + * @return Name of the property, to be used in a query. + */ + public String get(AuditConfiguration auditCfg); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/RevisionNumberPropertyName.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/RevisionNumberPropertyName.java index 60530df288..640afaeb13 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/RevisionNumberPropertyName.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/RevisionNumberPropertyName.java @@ -27,10 +27,11 @@ import org.hibernate.envers.configuration.spi.AuditConfiguration; /** * Used for specifying restrictions on the revision number, corresponding to an audit entity. + * * @author Adam Warski (adam at warski dot org) */ public class RevisionNumberPropertyName implements PropertyNameGetter { - public String get(AuditConfiguration auditCfg) { - return auditCfg.getAuditEntCfg().getRevisionNumberPath(); - } + public String get(AuditConfiguration auditCfg) { + return auditCfg.getAuditEntCfg().getRevisionNumberPath(); + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/RevisionPropertyPropertyName.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/RevisionPropertyPropertyName.java index 93d300e223..64d4f15427 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/RevisionPropertyPropertyName.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/RevisionPropertyPropertyName.java @@ -27,16 +27,17 @@ import org.hibernate.envers.configuration.spi.AuditConfiguration; /** * Used for specifying restrictions on a property of the revision entity, which is associated with an audit entity. + * * @author Adam Warski (adam at warski dot org) */ public class RevisionPropertyPropertyName implements PropertyNameGetter { - private final String propertyName; + private final String propertyName; - public RevisionPropertyPropertyName(String propertyName) { - this.propertyName = propertyName; - } + public RevisionPropertyPropertyName(String propertyName) { + this.propertyName = propertyName; + } - public String get(AuditConfiguration auditCfg) { - return auditCfg.getAuditEntCfg().getRevisionPropPath(propertyName); - } + public String get(AuditConfiguration auditCfg) { + return auditCfg.getAuditEntCfg().getRevisionPropPath( propertyName ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/RevisionTypePropertyName.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/RevisionTypePropertyName.java index 772015d0ee..33b99d78ae 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/RevisionTypePropertyName.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/internal/property/RevisionTypePropertyName.java @@ -27,10 +27,11 @@ import org.hibernate.envers.configuration.spi.AuditConfiguration; /** * Used for specifying restrictions on the revision number, corresponding to an audit entity. + * * @author Adam Warski (adam at warski dot org) */ public class RevisionTypePropertyName implements PropertyNameGetter { - public String get(AuditConfiguration auditCfg) { - return auditCfg.getAuditEntCfg().getRevisionTypePropName(); - } + public String get(AuditConfiguration auditCfg) { + return auditCfg.getAuditEntCfg().getRevisionTypePropName(); + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/order/AuditOrder.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/order/AuditOrder.java index 8575fc7115..d7c00b5eeb 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/order/AuditOrder.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/order/AuditOrder.java @@ -30,9 +30,10 @@ import org.hibernate.envers.tools.Pair; * @author Adam Warski (adam at warski dot org) */ public interface AuditOrder { - /** - * @param auditCfg Configuration. - * @return A pair: (property name, ascending?). - */ - Pair getData(AuditConfiguration auditCfg); + /** + * @param auditCfg Configuration. + * + * @return A pair: (property name, ascending?). + */ + Pair getData(AuditConfiguration auditCfg); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/order/internal/PropertyAuditOrder.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/order/internal/PropertyAuditOrder.java index 77ec0470f1..f1764f9c96 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/order/internal/PropertyAuditOrder.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/order/internal/PropertyAuditOrder.java @@ -32,15 +32,15 @@ import org.hibernate.envers.tools.Pair; * @author Adam Warski (adam at warski dot org) */ public class PropertyAuditOrder implements AuditOrder { - private final PropertyNameGetter propertyNameGetter; - private final boolean asc; + private final PropertyNameGetter propertyNameGetter; + private final boolean asc; - public PropertyAuditOrder(PropertyNameGetter propertyNameGetter, boolean asc) { - this.propertyNameGetter = propertyNameGetter; - this.asc = asc; - } + public PropertyAuditOrder(PropertyNameGetter propertyNameGetter, boolean asc) { + this.propertyNameGetter = propertyNameGetter; + this.asc = asc; + } - public Pair getData(AuditConfiguration auditCfg) { - return Pair.make(propertyNameGetter.get(auditCfg), asc); - } + public Pair getData(AuditConfiguration auditCfg) { + return Pair.make( propertyNameGetter.get( auditCfg ), asc ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/projection/AuditProjection.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/projection/AuditProjection.java index 469909787c..a1be2c6a63 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/projection/AuditProjection.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/projection/AuditProjection.java @@ -30,9 +30,10 @@ import org.hibernate.envers.internal.tools.Triple; * @author Adam Warski (adam at warski dot org) */ public interface AuditProjection { - /** - * @param auditCfg Configuration. - * @return A triple: (function name - possibly null, property name, add distinct?). - */ - Triple getData(AuditConfiguration auditCfg); + /** + * @param auditCfg Configuration. + * + * @return A triple: (function name - possibly null, property name, add distinct?). + */ + Triple getData(AuditConfiguration auditCfg); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/query/projection/internal/PropertyAuditProjection.java b/hibernate-envers/src/main/java/org/hibernate/envers/query/projection/internal/PropertyAuditProjection.java index 9e3a4ee2a6..1f5b889749 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/query/projection/internal/PropertyAuditProjection.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/query/projection/internal/PropertyAuditProjection.java @@ -32,19 +32,19 @@ import org.hibernate.envers.query.projection.AuditProjection; * @author Adam Warski (adam at warski dot org) */ public class PropertyAuditProjection implements AuditProjection { - private final PropertyNameGetter propertyNameGetter; - private final String function; - private final boolean distinct; + private final PropertyNameGetter propertyNameGetter; + private final String function; + private final boolean distinct; - public PropertyAuditProjection(PropertyNameGetter propertyNameGetter, String function, boolean distinct) { - this.propertyNameGetter = propertyNameGetter; - this.function = function; - this.distinct = distinct; - } + public PropertyAuditProjection(PropertyNameGetter propertyNameGetter, String function, boolean distinct) { + this.propertyNameGetter = propertyNameGetter; + this.function = function; + this.distinct = distinct; + } - public Triple getData(AuditConfiguration auditCfg) { - String propertyName = propertyNameGetter.get(auditCfg); + public Triple getData(AuditConfiguration auditCfg) { + String propertyName = propertyNameGetter.get( auditCfg ); - return Triple.make(function, propertyName, distinct); - } + return Triple.make( function, propertyName, distinct ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/strategy/AuditStrategy.java b/hibernate-envers/src/main/java/org/hibernate/envers/strategy/AuditStrategy.java index 46ab08105d..7dedd7eb78 100755 --- a/hibernate-envers/src/main/java/org/hibernate/envers/strategy/AuditStrategy.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/strategy/AuditStrategy.java @@ -14,85 +14,97 @@ import org.hibernate.envers.internal.tools.query.QueryBuilder; /** * Behaviours of different audit strategy for populating audit data. - * + * * @author Stephanie Pau * @author Adam Warski (adam at warski dot org) */ public interface AuditStrategy { - /** - * Perform the persistence of audited data for regular entities. - * - * @param session Session, which can be used to persist the data. - * @param entityName Name of the entity, in which the audited change happens - * @param auditCfg Audit configuration - * @param id Id of the entity. - * @param data Audit data to persist - * @param revision Current revision data - */ - void perform(Session session, String entityName, AuditConfiguration auditCfg, Serializable id, Object data, - Object revision); + /** + * Perform the persistence of audited data for regular entities. + * + * @param session Session, which can be used to persist the data. + * @param entityName Name of the entity, in which the audited change happens + * @param auditCfg Audit configuration + * @param id Id of the entity. + * @param data Audit data to persist + * @param revision Current revision data + */ + void perform( + Session session, String entityName, AuditConfiguration auditCfg, Serializable id, Object data, + Object revision); - /** - * Perform the persistence of audited data for collection ("middle") entities. - * - * @param session Session, which can be used to persist the data. + /** + * Perform the persistence of audited data for collection ("middle") entities. + * + * @param session Session, which can be used to persist the data. * @param entityName Name of the entity, in which the audited change happens. * @param propertyName The name of the property holding the {@link PersistentCollection}. - * @param auditCfg Audit configuration - * @param persistentCollectionChangeData Collection change data to be persisted. - * @param revision Current revision data - */ - void performCollectionChange(Session session, String entityName, String propertyName, AuditConfiguration auditCfg, - PersistentCollectionChangeData persistentCollectionChangeData, Object revision); - + * @param auditCfg Audit configuration + * @param persistentCollectionChangeData Collection change data to be persisted. + * @param revision Current revision data + */ + void performCollectionChange( + Session session, String entityName, String propertyName, AuditConfiguration auditCfg, + PersistentCollectionChangeData persistentCollectionChangeData, Object revision); - /** + + /** * Update the rootQueryBuilder with an extra WHERE clause to restrict the revision for a two-entity relation. * This WHERE clause depends on the AuditStrategy, as follows: *
        - *
      • For {@link DefaultAuditStrategy} a subquery is created: + *
      • For {@link DefaultAuditStrategy} a subquery is created: *

        e.revision = (SELECT max(...) ...)

        *
      • - *
      • for {@link ValidityAuditStrategy} the revision-end column is used: + *
      • for {@link ValidityAuditStrategy} the revision-end column is used: *

        e.revision <= :revision and (e.endRevision > :revision or e.endRevision is null)

        *
      • *
      - * + * * @param globalCfg the {@link GlobalConfiguration} - * @param rootQueryBuilder the {@link QueryBuilder} that will be updated - * @param parameters root parameters to which restrictions shall be added - * @param revisionProperty property of the revision column - * @param revisionEndProperty property of the revisionEnd column (only used for {@link ValidityAuditStrategy}) - * @param addAlias {@code boolean} indicator if a left alias is needed - * @param idData id-information for the two-entity relation (only used for {@link DefaultAuditStrategy}) - * @param revisionPropertyPath path of the revision property (only used for {@link ValidityAuditStrategy}) - * @param originalIdPropertyName name of the id property (only used for {@link ValidityAuditStrategy}) - * @param alias1 an alias used for subquery (only used for {@link ValidityAuditStrategy}) - * @param alias2 an alias used for subquery (only used for {@link ValidityAuditStrategy}) - * @param inclusive indicates whether revision number shall be treated as inclusive or exclusive - */ - void addEntityAtRevisionRestriction(GlobalConfiguration globalCfg, QueryBuilder rootQueryBuilder, Parameters parameters, - String revisionProperty, String revisionEndProperty, boolean addAlias, MiddleIdData idData, - String revisionPropertyPath, String originalIdPropertyName, String alias1, String alias2, boolean inclusive); - - /** - * Update the rootQueryBuilder with an extra WHERE clause to restrict the revision for a middle-entity - * association. This WHERE clause depends on the AuditStrategy, as follows: - *
        - *
      • For {@link DefaultAuditStrategy} a subquery is created: - *

        e.revision = (SELECT max(...) ...)

        - *
      • - *
      • for {@link ValidityAuditStrategy} the revision-end column is used: - *

        e.revision <= :revision and (e.endRevision > :revision or e.endRevision is null)

        - *
      • - *
      - * * @param rootQueryBuilder the {@link QueryBuilder} that will be updated * @param parameters root parameters to which restrictions shall be added - * @param revisionProperty property of the revision column - * @param revisionEndProperty property of the revisionEnd column (only used for {@link ValidityAuditStrategy}) - * @param addAlias {@code boolean} indicator if a left alias is needed - * @param referencingIdData id-information for the middle-entity association (only used for {@link DefaultAuditStrategy}) + * @param revisionProperty property of the revision column + * @param revisionEndProperty property of the revisionEnd column (only used for {@link ValidityAuditStrategy}) + * @param addAlias {@code boolean} indicator if a left alias is needed + * @param idData id-information for the two-entity relation (only used for {@link DefaultAuditStrategy}) + * @param revisionPropertyPath path of the revision property (only used for {@link ValidityAuditStrategy}) + * @param originalIdPropertyName name of the id property (only used for {@link ValidityAuditStrategy}) + * @param alias1 an alias used for subquery (only used for {@link ValidityAuditStrategy}) + * @param alias2 an alias used for subquery (only used for {@link ValidityAuditStrategy}) + * @param inclusive indicates whether revision number shall be treated as inclusive or exclusive + */ + void addEntityAtRevisionRestriction( + GlobalConfiguration globalCfg, + QueryBuilder rootQueryBuilder, + Parameters parameters, + String revisionProperty, + String revisionEndProperty, + boolean addAlias, + MiddleIdData idData, + String revisionPropertyPath, + String originalIdPropertyName, + String alias1, + String alias2, + boolean inclusive); + + /** + * Update the rootQueryBuilder with an extra WHERE clause to restrict the revision for a middle-entity + * association. This WHERE clause depends on the AuditStrategy, as follows: + *
        + *
      • For {@link DefaultAuditStrategy} a subquery is created: + *

        e.revision = (SELECT max(...) ...)

        + *
      • + *
      • for {@link ValidityAuditStrategy} the revision-end column is used: + *

        e.revision <= :revision and (e.endRevision > :revision or e.endRevision is null)

        + *
      • + *
      + * + * @param rootQueryBuilder the {@link QueryBuilder} that will be updated + * @param parameters root parameters to which restrictions shall be added + * @param revisionProperty property of the revision column + * @param revisionEndProperty property of the revisionEnd column (only used for {@link ValidityAuditStrategy}) + * @param addAlias {@code boolean} indicator if a left alias is needed + * @param referencingIdData id-information for the middle-entity association (only used for {@link DefaultAuditStrategy}) * @param versionsMiddleEntityName name of the middle-entity * @param eeOriginalIdPropertyPath name of the id property (only used for {@link ValidityAuditStrategy}) * @param revisionPropertyPath path of the revision property (only used for {@link ValidityAuditStrategy}) @@ -101,8 +113,9 @@ public interface AuditStrategy { * @param inclusive indicates whether revision number shall be treated as inclusive or exclusive * @param componentDatas information about the middle-entity relation */ - void addAssociationAtRevisionRestriction(QueryBuilder rootQueryBuilder, Parameters parameters, String revisionProperty, - String revisionEndProperty, boolean addAlias, MiddleIdData referencingIdData, + void addAssociationAtRevisionRestriction( + QueryBuilder rootQueryBuilder, Parameters parameters, String revisionProperty, + String revisionEndProperty, boolean addAlias, MiddleIdData referencingIdData, String versionsMiddleEntityName, String eeOriginalIdPropertyPath, String revisionPropertyPath, String originalIdPropertyName, String alias1, boolean inclusive, MiddleComponentData... componentDatas); } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/strategy/DefaultAuditStrategy.java b/hibernate-envers/src/main/java/org/hibernate/envers/strategy/DefaultAuditStrategy.java index 775cd39660..139fa7e3a3 100755 --- a/hibernate-envers/src/main/java/org/hibernate/envers/strategy/DefaultAuditStrategy.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/strategy/DefaultAuditStrategy.java @@ -22,65 +22,102 @@ import static org.hibernate.envers.internal.entities.mapper.relation.query.Query * @author Stephanie Pau */ public class DefaultAuditStrategy implements AuditStrategy { - private final SessionCacheCleaner sessionCacheCleaner; + private final SessionCacheCleaner sessionCacheCleaner; - public DefaultAuditStrategy() { - sessionCacheCleaner = new SessionCacheCleaner(); - } - - public void perform(Session session, String entityName, AuditConfiguration auditCfg, Serializable id, Object data, - Object revision) { - session.save(auditCfg.getAuditEntCfg().getAuditEntityName(entityName), data); - sessionCacheCleaner.scheduleAuditDataRemoval(session, data); - } - - public void performCollectionChange(Session session, String entityName, String propertyName, AuditConfiguration auditCfg, - PersistentCollectionChangeData persistentCollectionChangeData, Object revision) { - session.save(persistentCollectionChangeData.getEntityName(), persistentCollectionChangeData.getData()); - sessionCacheCleaner.scheduleAuditDataRemoval(session, persistentCollectionChangeData.getData()); - } - - - public void addEntityAtRevisionRestriction(GlobalConfiguration globalCfg, QueryBuilder rootQueryBuilder, Parameters parameters, - String revisionProperty, String revisionEndProperty, boolean addAlias, MiddleIdData idData, String revisionPropertyPath, - String originalIdPropertyName, String alias1, String alias2, boolean inclusive) { - // create a subquery builder - // SELECT max(e.revision) FROM versionsReferencedEntity e2 - QueryBuilder maxERevQb = rootQueryBuilder.newSubQueryBuilder(idData.getAuditEntityName(), alias2); - maxERevQb.addProjection("max", revisionPropertyPath, false); - // WHERE - Parameters maxERevQbParameters = maxERevQb.getRootParameters(); - // e2.revision <= :revision - maxERevQbParameters.addWhereWithNamedParam(revisionPropertyPath, inclusive ? "<=" : "<", REVISION_PARAMETER); - // e2.id_ref_ed = e.id_ref_ed - idData.getOriginalMapper().addIdsEqualToQuery(maxERevQbParameters, - alias1 + "." + originalIdPropertyName, alias2 +"." + originalIdPropertyName); - - // add subquery to rootParameters - String subqueryOperator = globalCfg.getCorrelatedSubqueryOperator(); - parameters.addWhere(revisionProperty, addAlias, subqueryOperator, maxERevQb); + public DefaultAuditStrategy() { + sessionCacheCleaner = new SessionCacheCleaner(); } - public void addAssociationAtRevisionRestriction(QueryBuilder rootQueryBuilder, Parameters parameters, String revisionProperty, - String revisionEndProperty, boolean addAlias, MiddleIdData referencingIdData, String versionsMiddleEntityName, - String eeOriginalIdPropertyPath, String revisionPropertyPath, String originalIdPropertyName, String alias1, - boolean inclusive, MiddleComponentData... componentDatas) { - // SELECT max(ee2.revision) FROM middleEntity ee2 - QueryBuilder maxEeRevQb = rootQueryBuilder.newSubQueryBuilder(versionsMiddleEntityName, MIDDLE_ENTITY_ALIAS_DEF_AUD_STR); - maxEeRevQb.addProjection("max", revisionPropertyPath, false); - // WHERE - Parameters maxEeRevQbParameters = maxEeRevQb.getRootParameters(); - // ee2.revision <= :revision - maxEeRevQbParameters.addWhereWithNamedParam(revisionPropertyPath, inclusive ? "<=" : "<", REVISION_PARAMETER); - // ee2.originalId.* = ee.originalId.* - String ee2OriginalIdPropertyPath = MIDDLE_ENTITY_ALIAS_DEF_AUD_STR + "." + originalIdPropertyName; - referencingIdData.getPrefixedMapper().addIdsEqualToQuery(maxEeRevQbParameters, eeOriginalIdPropertyPath, ee2OriginalIdPropertyPath); - for (MiddleComponentData componentData : componentDatas) { - componentData.getComponentMapper().addMiddleEqualToQuery(maxEeRevQbParameters, eeOriginalIdPropertyPath, alias1, ee2OriginalIdPropertyPath, MIDDLE_ENTITY_ALIAS_DEF_AUD_STR); - } + public void perform( + Session session, String entityName, AuditConfiguration auditCfg, Serializable id, Object data, + Object revision) { + session.save( auditCfg.getAuditEntCfg().getAuditEntityName( entityName ), data ); + sessionCacheCleaner.scheduleAuditDataRemoval( session, data ); + } + + public void performCollectionChange( + Session session, String entityName, String propertyName, AuditConfiguration auditCfg, + PersistentCollectionChangeData persistentCollectionChangeData, Object revision) { + session.save( persistentCollectionChangeData.getEntityName(), persistentCollectionChangeData.getData() ); + sessionCacheCleaner.scheduleAuditDataRemoval( session, persistentCollectionChangeData.getData() ); + } + + + public void addEntityAtRevisionRestriction( + GlobalConfiguration globalCfg, + QueryBuilder rootQueryBuilder, + Parameters parameters, + String revisionProperty, + String revisionEndProperty, + boolean addAlias, + MiddleIdData idData, + String revisionPropertyPath, + String originalIdPropertyName, + String alias1, + String alias2, + boolean inclusive) { + // create a subquery builder + // SELECT max(e.revision) FROM versionsReferencedEntity e2 + QueryBuilder maxERevQb = rootQueryBuilder.newSubQueryBuilder( idData.getAuditEntityName(), alias2 ); + maxERevQb.addProjection( "max", revisionPropertyPath, false ); + // WHERE + Parameters maxERevQbParameters = maxERevQb.getRootParameters(); + // e2.revision <= :revision + maxERevQbParameters.addWhereWithNamedParam( revisionPropertyPath, inclusive ? "<=" : "<", REVISION_PARAMETER ); + // e2.id_ref_ed = e.id_ref_ed + idData.getOriginalMapper().addIdsEqualToQuery( + maxERevQbParameters, + alias1 + "." + originalIdPropertyName, alias2 + "." + originalIdPropertyName + ); // add subquery to rootParameters - parameters.addWhere(revisionProperty, addAlias, "=", maxEeRevQb); + String subqueryOperator = globalCfg.getCorrelatedSubqueryOperator(); + parameters.addWhere( revisionProperty, addAlias, subqueryOperator, maxERevQb ); + } + + public void addAssociationAtRevisionRestriction( + QueryBuilder rootQueryBuilder, + Parameters parameters, + String revisionProperty, + String revisionEndProperty, + boolean addAlias, + MiddleIdData referencingIdData, + String versionsMiddleEntityName, + String eeOriginalIdPropertyPath, + String revisionPropertyPath, + String originalIdPropertyName, + String alias1, + boolean inclusive, + MiddleComponentData... componentDatas) { + // SELECT max(ee2.revision) FROM middleEntity ee2 + QueryBuilder maxEeRevQb = rootQueryBuilder.newSubQueryBuilder( + versionsMiddleEntityName, + MIDDLE_ENTITY_ALIAS_DEF_AUD_STR + ); + maxEeRevQb.addProjection( "max", revisionPropertyPath, false ); + // WHERE + Parameters maxEeRevQbParameters = maxEeRevQb.getRootParameters(); + // ee2.revision <= :revision + maxEeRevQbParameters.addWhereWithNamedParam( revisionPropertyPath, inclusive ? "<=" : "<", REVISION_PARAMETER ); + // ee2.originalId.* = ee.originalId.* + String ee2OriginalIdPropertyPath = MIDDLE_ENTITY_ALIAS_DEF_AUD_STR + "." + originalIdPropertyName; + referencingIdData.getPrefixedMapper().addIdsEqualToQuery( + maxEeRevQbParameters, + eeOriginalIdPropertyPath, + ee2OriginalIdPropertyPath + ); + for ( MiddleComponentData componentData : componentDatas ) { + componentData.getComponentMapper().addMiddleEqualToQuery( + maxEeRevQbParameters, + eeOriginalIdPropertyPath, + alias1, + ee2OriginalIdPropertyPath, + MIDDLE_ENTITY_ALIAS_DEF_AUD_STR + ); + } + + // add subquery to rootParameters + parameters.addWhere( revisionProperty, addAlias, "=", maxEeRevQb ); } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/strategy/ValidTimeAuditStrategy.java b/hibernate-envers/src/main/java/org/hibernate/envers/strategy/ValidTimeAuditStrategy.java index bcb790b42f..2d641a0229 100755 --- a/hibernate-envers/src/main/java/org/hibernate/envers/strategy/ValidTimeAuditStrategy.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/strategy/ValidTimeAuditStrategy.java @@ -1,4 +1,5 @@ package org.hibernate.envers.strategy; + import org.jboss.logging.Logger; import org.hibernate.envers.internal.EnversMessageLogger; @@ -8,19 +9,21 @@ import org.hibernate.envers.internal.EnversMessageLogger; * * @author Stephanie Pau * @author Adam Warski (adam at warski dot org) - * * @deprecated use {@link ValidityAuditStrategy} instead. */ @Deprecated public class ValidTimeAuditStrategy extends ValidityAuditStrategy { - public static final EnversMessageLogger LOG = Logger.getMessageLogger(EnversMessageLogger.class, ValidTimeAuditStrategy.class.getName()); + public static final EnversMessageLogger LOG = Logger.getMessageLogger( + EnversMessageLogger.class, + ValidTimeAuditStrategy.class.getName() + ); /** * Default constructor. Log a warn message that this class is deprecated. */ public ValidTimeAuditStrategy() { - LOG.validTimeAuditStrategyDeprecated(); + LOG.validTimeAuditStrategyDeprecated(); } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/strategy/ValidityAuditStrategy.java b/hibernate-envers/src/main/java/org/hibernate/envers/strategy/ValidityAuditStrategy.java index c434feea8f..7de16d118b 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/strategy/ValidityAuditStrategy.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/strategy/ValidityAuditStrategy.java @@ -45,24 +45,24 @@ import static org.hibernate.envers.internal.entities.mapper.relation.query.Query import static org.hibernate.envers.internal.entities.mapper.relation.query.QueryConstants.REVISION_PARAMETER; /** - * Audit strategy which persists and retrieves audit information using a validity algorithm, based on the - * start-revision and end-revision of a row in the audit tables. - *

      This algorithm works as follows: - *

        - *
      • For a new row that is persisted in an audit table, only the start-revision column of that row is set
      • - *
      • At the same time the end-revision field of the previous audit row is set to this revision
      • - *
      • Queries are retrieved using 'between start and end revision', instead of a subquery.
      • - *
      - *

      - * - *

      - * This has a few important consequences that need to be judged against against each other: - *

        - *
      • Persisting audit information is a bit slower, because an extra row is updated
      • - *
      • Retrieving audit information is a lot faster
      • - *
      - *

      - * + * Audit strategy which persists and retrieves audit information using a validity algorithm, based on the + * start-revision and end-revision of a row in the audit tables. + *

      This algorithm works as follows: + *

        + *
      • For a new row that is persisted in an audit table, only the start-revision column of that row is set
      • + *
      • At the same time the end-revision field of the previous audit row is set to this revision
      • + *
      • Queries are retrieved using 'between start and end revision', instead of a subquery.
      • + *
      + *

      + *

      + *

      + * This has a few important consequences that need to be judged against against each other: + *

        + *
      • Persisting audit information is a bit slower, because an extra row is updated
      • + *
      • Retrieving audit information is a lot faster
      • + *
      + *

      + * * @author Stephanie Pau * @author Adam Warski (adam at warski dot org) * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) @@ -70,38 +70,46 @@ import static org.hibernate.envers.internal.entities.mapper.relation.query.Query public class ValidityAuditStrategy implements AuditStrategy { private static final Logger log = Logger.getLogger( ValidityAuditStrategy.class ); - /** getter for the revision entity field annotated with @RevisionTimestamp */ - private Getter revisionTimestampGetter = null; + /** + * getter for the revision entity field annotated with @RevisionTimestamp + */ + private Getter revisionTimestampGetter = null; - private final SessionCacheCleaner sessionCacheCleaner; + private final SessionCacheCleaner sessionCacheCleaner; - public ValidityAuditStrategy() { - sessionCacheCleaner = new SessionCacheCleaner(); - } + public ValidityAuditStrategy() { + sessionCacheCleaner = new SessionCacheCleaner(); + } - public void perform( + public void perform( final Session session, String entityName, final AuditConfiguration auditCfg, final Serializable id, Object data, final Object revision) { - final AuditEntitiesConfiguration audEntitiesCfg = auditCfg.getAuditEntCfg(); - final String auditedEntityName = audEntitiesCfg.getAuditEntityName( entityName ); + final AuditEntitiesConfiguration audEntitiesCfg = auditCfg.getAuditEntCfg(); + final String auditedEntityName = audEntitiesCfg.getAuditEntityName( entityName ); final String revisionInfoEntityName = auditCfg.getAuditEntCfg().getRevisionInfoEntityName(); final SessionImplementor sessionImplementor = (SessionImplementor) session; final Dialect dialect = sessionImplementor.getFactory().getDialect(); - // Save the audit data - session.save(auditedEntityName, data); - sessionCacheCleaner.scheduleAuditDataRemoval(session, data); + // Save the audit data + session.save( auditedEntityName, data ); + sessionCacheCleaner.scheduleAuditDataRemoval( session, data ); - // Update the end date of the previous row if this operation is expected to have a previous row - if (getRevisionType(auditCfg, data) != RevisionType.ADD) { + // Update the end date of the previous row if this operation is expected to have a previous row + if ( getRevisionType( auditCfg, data ) != RevisionType.ADD ) { final Queryable productionEntityQueryable = getQueryable( entityName, sessionImplementor ); - final Queryable rootProductionEntityQueryable = getQueryable( productionEntityQueryable.getRootEntityName(), sessionImplementor ); + final Queryable rootProductionEntityQueryable = getQueryable( + productionEntityQueryable.getRootEntityName(), + sessionImplementor + ); final Queryable auditedEntityQueryable = getQueryable( auditedEntityName, sessionImplementor ); - final Queryable rootAuditedEntityQueryable = getQueryable( auditedEntityQueryable.getRootEntityName(), sessionImplementor ); + final Queryable rootAuditedEntityQueryable = getQueryable( + auditedEntityQueryable.getRootEntityName(), + sessionImplementor + ); final Queryable revisionInfoEntityQueryable = getQueryable( revisionInfoEntityName, sessionImplementor ); final String updateTableName; @@ -127,7 +135,10 @@ public class ValidityAuditStrategy implements AuditStrategy { final Type revisionInfoIdType = sessionImplementor.getFactory() .getEntityPersister( revisionInfoEntityName ) .getIdentifierType(); - final String revEndColumnName = rootAuditedEntityQueryable.toColumns( auditCfg.getAuditEntCfg().getRevisionEndFieldName() )[0]; + final String revEndColumnName = rootAuditedEntityQueryable.toColumns( + auditCfg.getAuditEntCfg() + .getRevisionEndFieldName() + )[0]; final boolean isRevisionEndTimestampEnabled = auditCfg.getAuditEntCfg().isRevisionEndTimestampEnabled(); @@ -163,14 +174,24 @@ public class ValidityAuditStrategy implements AuditStrategy { new ReturningWork() { @Override public Integer execute(Connection connection) throws SQLException { - PreparedStatement preparedStatement = sessionImplementor.getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( updateSql ); + PreparedStatement preparedStatement = sessionImplementor.getTransactionCoordinator() + .getJdbcCoordinator() + .getStatementPreparer() + .prepareStatement( updateSql ); try { int index = 1; // set REVEND = ? - final Number revisionNumber = auditCfg.getRevisionInfoNumberReader().getRevisionNumber( revision ); - revisionInfoIdType.nullSafeSet( preparedStatement, revisionNumber, index, sessionImplementor ); + final Number revisionNumber = auditCfg.getRevisionInfoNumberReader().getRevisionNumber( + revision + ); + revisionInfoIdType.nullSafeSet( + preparedStatement, + revisionNumber, + index, + sessionImplementor + ); index += revisionInfoIdType.getColumnSpan( sessionImplementor.getFactory() ); // set [, REVEND_TSTMP = ?] @@ -180,7 +201,12 @@ public class ValidityAuditStrategy implements AuditStrategy { final Type revEndTsType = rootAuditedEntityQueryable.getPropertyType( auditCfg.getAuditEntCfg().getRevisionEndTimestampFieldName() ); - revEndTsType.nullSafeSet( preparedStatement, revisionEndTimestamp, index, sessionImplementor ); + revEndTsType.nullSafeSet( + preparedStatement, + revisionEndTimestamp, + index, + sessionImplementor + ); index += revEndTsType.getColumnSpan( sessionImplementor.getFactory() ); } @@ -198,10 +224,15 @@ public class ValidityAuditStrategy implements AuditStrategy { // where REVEND is null // nothing to bind.... - return sessionImplementor.getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().executeUpdate( preparedStatement ); + return sessionImplementor.getTransactionCoordinator() + .getJdbcCoordinator() + .getResultSetReturn() + .executeUpdate( preparedStatement ); } finally { - sessionImplementor.getTransactionCoordinator().getJdbcCoordinator().release( preparedStatement ); + sessionImplementor.getTransactionCoordinator().getJdbcCoordinator().release( + preparedStatement + ); } } } @@ -213,7 +244,7 @@ public class ValidityAuditStrategy implements AuditStrategy { ); } } - } + } private Queryable getQueryable(String entityName, SessionImplementor sessionImplementor) { return (Queryable) sessionImplementor.getFactory().getEntityPersister( entityName ); @@ -236,25 +267,30 @@ public class ValidityAuditStrategy implements AuditStrategy { } } - @SuppressWarnings({"unchecked"}) - public void performCollectionChange(Session session, String entityName, String propertyName, AuditConfiguration auditCfg, - PersistentCollectionChangeData persistentCollectionChangeData, Object revision) { - final QueryBuilder qb = new QueryBuilder(persistentCollectionChangeData.getEntityName(), MIDDLE_ENTITY_ALIAS); + @SuppressWarnings({"unchecked"}) + public void performCollectionChange( + Session session, String entityName, String propertyName, AuditConfiguration auditCfg, + PersistentCollectionChangeData persistentCollectionChangeData, Object revision) { + final QueryBuilder qb = new QueryBuilder( persistentCollectionChangeData.getEntityName(), MIDDLE_ENTITY_ALIAS ); - final String originalIdPropName = auditCfg.getAuditEntCfg().getOriginalIdPropName(); - final Map originalId = (Map) persistentCollectionChangeData.getData().get(originalIdPropName); + final String originalIdPropName = auditCfg.getAuditEntCfg().getOriginalIdPropName(); + final Map originalId = (Map) persistentCollectionChangeData.getData().get( + originalIdPropName + ); final String revisionFieldName = auditCfg.getAuditEntCfg().getRevisionFieldName(); final String revisionTypePropName = auditCfg.getAuditEntCfg().getRevisionTypePropName(); // Adding a parameter for each id component, except the rev number and type. - for (Map.Entry originalIdEntry : originalId.entrySet()) { - if (!revisionFieldName.equals(originalIdEntry.getKey()) && !revisionTypePropName.equals(originalIdEntry.getKey())) { - qb.getRootParameters().addWhereWithParam(originalIdPropName + "." + originalIdEntry.getKey(), - true, "=", originalIdEntry.getValue()); - } - } + for ( Map.Entry originalIdEntry : originalId.entrySet() ) { + if ( !revisionFieldName.equals( originalIdEntry.getKey() ) && !revisionTypePropName.equals( originalIdEntry.getKey() ) ) { + qb.getRootParameters().addWhereWithParam( + originalIdPropName + "." + originalIdEntry.getKey(), + true, "=", originalIdEntry.getValue() + ); + } + } - final SessionFactoryImplementor sessionFactory = ( (SessionImplementor) session ).getFactory(); + final SessionFactoryImplementor sessionFactory = ((SessionImplementor) session).getFactory(); final Type propertyType = sessionFactory.getEntityPersister( entityName ).getPropertyType( propertyName ); if ( propertyType.isCollectionType() ) { CollectionType collectionPropertyType = (CollectionType) propertyType; @@ -269,92 +305,109 @@ public class ValidityAuditStrategy implements AuditStrategy { } } - addEndRevisionNullRestriction(auditCfg, qb.getRootParameters()); + addEndRevisionNullRestriction( auditCfg, qb.getRootParameters() ); - final List l = qb.toQuery(session).setLockOptions(LockOptions.UPGRADE).list(); + final List l = qb.toQuery( session ).setLockOptions( LockOptions.UPGRADE ).list(); - // Update the last revision if one exists. - // HHH-5967: with collections, the same element can be added and removed multiple times. So even if it's an - // ADD, we may need to update the last revision. - if (l.size() > 0) { - updateLastRevision(session, auditCfg, l, originalId, persistentCollectionChangeData.getEntityName(), revision); - } + // Update the last revision if one exists. + // HHH-5967: with collections, the same element can be added and removed multiple times. So even if it's an + // ADD, we may need to update the last revision. + if ( l.size() > 0 ) { + updateLastRevision( + session, + auditCfg, + l, + originalId, + persistentCollectionChangeData.getEntityName(), + revision + ); + } - // Save the audit data - session.save(persistentCollectionChangeData.getEntityName(), persistentCollectionChangeData.getData()); - sessionCacheCleaner.scheduleAuditDataRemoval(session, persistentCollectionChangeData.getData()); - } - - private void addEndRevisionNullRestriction(AuditConfiguration auditCfg, Parameters rootParameters) { - rootParameters.addWhere(auditCfg.getAuditEntCfg().getRevisionEndFieldName(), true, "is", "null", false); - } - - public void addEntityAtRevisionRestriction(GlobalConfiguration globalCfg, QueryBuilder rootQueryBuilder, - Parameters parameters, String revisionProperty,String revisionEndProperty, boolean addAlias, - MiddleIdData idData, String revisionPropertyPath, String originalIdPropertyName, - String alias1, String alias2, boolean inclusive) { - addRevisionRestriction(parameters, revisionProperty, revisionEndProperty, addAlias, inclusive); + // Save the audit data + session.save( persistentCollectionChangeData.getEntityName(), persistentCollectionChangeData.getData() ); + sessionCacheCleaner.scheduleAuditDataRemoval( session, persistentCollectionChangeData.getData() ); } - - public void addAssociationAtRevisionRestriction(QueryBuilder rootQueryBuilder, Parameters parameters, String revisionProperty, - String revisionEndProperty, boolean addAlias, MiddleIdData referencingIdData, - String versionsMiddleEntityName, String eeOriginalIdPropertyPath, String revisionPropertyPath, - String originalIdPropertyName, String alias1, boolean inclusive, MiddleComponentData... componentDatas) { - addRevisionRestriction(parameters, revisionProperty, revisionEndProperty, addAlias, inclusive); + + private void addEndRevisionNullRestriction(AuditConfiguration auditCfg, Parameters rootParameters) { + rootParameters.addWhere( auditCfg.getAuditEntCfg().getRevisionEndFieldName(), true, "is", "null", false ); } - + + public void addEntityAtRevisionRestriction( + GlobalConfiguration globalCfg, QueryBuilder rootQueryBuilder, + Parameters parameters, String revisionProperty, String revisionEndProperty, boolean addAlias, + MiddleIdData idData, String revisionPropertyPath, String originalIdPropertyName, + String alias1, String alias2, boolean inclusive) { + addRevisionRestriction( parameters, revisionProperty, revisionEndProperty, addAlias, inclusive ); + } + + public void addAssociationAtRevisionRestriction( + QueryBuilder rootQueryBuilder, Parameters parameters, String revisionProperty, + String revisionEndProperty, boolean addAlias, MiddleIdData referencingIdData, + String versionsMiddleEntityName, String eeOriginalIdPropertyPath, String revisionPropertyPath, + String originalIdPropertyName, String alias1, boolean inclusive, MiddleComponentData... componentDatas) { + addRevisionRestriction( parameters, revisionProperty, revisionEndProperty, addAlias, inclusive ); + } + public void setRevisionTimestampGetter(Getter revisionTimestampGetter) { this.revisionTimestampGetter = revisionTimestampGetter; } - private void addRevisionRestriction(Parameters rootParameters, String revisionProperty, String revisionEndProperty, - boolean addAlias, boolean inclusive) { + private void addRevisionRestriction( + Parameters rootParameters, String revisionProperty, String revisionEndProperty, + boolean addAlias, boolean inclusive) { // e.revision <= _revision and (e.endRevision > _revision or e.endRevision is null) - Parameters subParm = rootParameters.addSubParameters("or"); - rootParameters.addWhereWithNamedParam(revisionProperty, addAlias, inclusive ? "<=" : "<", REVISION_PARAMETER); - subParm.addWhereWithNamedParam(revisionEndProperty + ".id", addAlias, inclusive ? ">" : ">=", REVISION_PARAMETER); - subParm.addWhere(revisionEndProperty, addAlias, "is", "null", false); + Parameters subParm = rootParameters.addSubParameters( "or" ); + rootParameters.addWhereWithNamedParam( revisionProperty, addAlias, inclusive ? "<=" : "<", REVISION_PARAMETER ); + subParm.addWhereWithNamedParam( + revisionEndProperty + ".id", + addAlias, + inclusive ? ">" : ">=", + REVISION_PARAMETER + ); + subParm.addWhere( revisionEndProperty, addAlias, "is", "null", false ); } - @SuppressWarnings({"unchecked"}) - private RevisionType getRevisionType(AuditConfiguration auditCfg, Object data) { - return (RevisionType) ((Map) data).get(auditCfg.getAuditEntCfg().getRevisionTypePropName()); - } + @SuppressWarnings({"unchecked"}) + private RevisionType getRevisionType(AuditConfiguration auditCfg, Object data) { + return (RevisionType) ((Map) data).get( auditCfg.getAuditEntCfg().getRevisionTypePropName() ); + } - @SuppressWarnings({"unchecked"}) - private void updateLastRevision(Session session, AuditConfiguration auditCfg, List l, - Object id, String auditedEntityName, Object revision) { - // There should be one entry - if (l.size() == 1) { - // Setting the end revision to be the current rev - Object previousData = l.get(0); - String revisionEndFieldName = auditCfg.getAuditEntCfg().getRevisionEndFieldName(); - ((Map) previousData).put(revisionEndFieldName, revision); + @SuppressWarnings({"unchecked"}) + private void updateLastRevision( + Session session, AuditConfiguration auditCfg, List l, + Object id, String auditedEntityName, Object revision) { + // There should be one entry + if ( l.size() == 1 ) { + // Setting the end revision to be the current rev + Object previousData = l.get( 0 ); + String revisionEndFieldName = auditCfg.getAuditEntCfg().getRevisionEndFieldName(); + ((Map) previousData).put( revisionEndFieldName, revision ); - if (auditCfg.getAuditEntCfg().isRevisionEndTimestampEnabled()) { - // Determine the value of the revision property annotated with @RevisionTimestamp - String revEndTimestampFieldName = auditCfg.getAuditEntCfg().getRevisionEndTimestampFieldName(); - Object revEndTimestampObj = this.revisionTimestampGetter.get(revision); - Date revisionEndTimestamp = convertRevEndTimestampToDate(revEndTimestampObj); + if ( auditCfg.getAuditEntCfg().isRevisionEndTimestampEnabled() ) { + // Determine the value of the revision property annotated with @RevisionTimestamp + String revEndTimestampFieldName = auditCfg.getAuditEntCfg().getRevisionEndTimestampFieldName(); + Object revEndTimestampObj = this.revisionTimestampGetter.get( revision ); + Date revisionEndTimestamp = convertRevEndTimestampToDate( revEndTimestampObj ); - // Setting the end revision timestamp - ((Map) previousData).put(revEndTimestampFieldName, revisionEndTimestamp); - } - - // Saving the previous version - session.save(auditedEntityName, previousData); - sessionCacheCleaner.scheduleAuditDataRemoval(session, previousData); - } else { - throw new RuntimeException("Cannot find previous revision for entity " + auditedEntityName + " and id " + id); - } - } + // Setting the end revision timestamp + ((Map) previousData).put( revEndTimestampFieldName, revisionEndTimestamp ); + } - private Date convertRevEndTimestampToDate(Object revEndTimestampObj) { - // convert to a java.util.Date - if (revEndTimestampObj instanceof Date) { - return (Date) revEndTimestampObj; - } - return new Date((Long) revEndTimestampObj); - } + // Saving the previous version + session.save( auditedEntityName, previousData ); + sessionCacheCleaner.scheduleAuditDataRemoval( session, previousData ); + } + else { + throw new RuntimeException( "Cannot find previous revision for entity " + auditedEntityName + " and id " + id ); + } + } + + private Date convertRevEndTimestampToDate(Object revEndTimestampObj) { + // convert to a java.util.Date + if ( revEndTimestampObj instanceof Date ) { + return (Date) revEndTimestampObj; + } + return new Date( (Long) revEndTimestampObj ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/tools/Pair.java b/hibernate-envers/src/main/java/org/hibernate/envers/tools/Pair.java index 6edfdc14fa..bad86c8214 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/tools/Pair.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/tools/Pair.java @@ -1,10 +1,10 @@ /* * Hibernate, Relational Persistence for Idiomatic Java * - * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as + * Copyright (c) 2008, 2013, 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 @@ -25,47 +25,59 @@ package org.hibernate.envers.tools; /** * A pair of objects. + * * @param * @param + * * @author Adam Warski (adamw@aster.pl) */ public class Pair { - private final T1 obj1; - private final T2 obj2; + private final T1 obj1; + private final T2 obj2; - public Pair(T1 obj1, T2 obj2) { - this.obj1 = obj1; - this.obj2 = obj2; - } + public Pair(T1 obj1, T2 obj2) { + this.obj1 = obj1; + this.obj2 = obj2; + } - public T1 getFirst() { - return obj1; - } + public T1 getFirst() { + return obj1; + } - public T2 getSecond() { - return obj2; - } + public T2 getSecond() { + return obj2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Pair)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Pair) ) { + return false; + } - Pair pair = (Pair) o; + final Pair pair = (Pair) o; - if (obj1 != null ? !obj1.equals(pair.obj1) : pair.obj1 != null) return false; - if (obj2 != null ? !obj2.equals(pair.obj2) : pair.obj2 != null) return false; + if ( obj1 != null ? !obj1.equals( pair.obj1 ) : pair.obj1 != null ) { + return false; + } + if ( obj2 != null ? !obj2.equals( pair.obj2 ) : pair.obj2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (obj1 != null ? obj1.hashCode() : 0); - result = 31 * result + (obj2 != null ? obj2.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result; + result = (obj1 != null ? obj1.hashCode() : 0); + result = 31 * result + (obj2 != null ? obj2.hashCode() : 0); + return result; + } - public static Pair make(T1 obj1, T2 obj2) { - return new Pair(obj1, obj2); - } + public static Pair make(T1 obj1, T2 obj2) { + return new Pair( obj1, obj2 ); + } } diff --git a/hibernate-envers/src/main/java/org/hibernate/envers/tools/hbm2ddl/EnversSchemaGenerator.java b/hibernate-envers/src/main/java/org/hibernate/envers/tools/hbm2ddl/EnversSchemaGenerator.java index de20ea4463..62d8d23269 100644 --- a/hibernate-envers/src/main/java/org/hibernate/envers/tools/hbm2ddl/EnversSchemaGenerator.java +++ b/hibernate-envers/src/main/java/org/hibernate/envers/tools/hbm2ddl/EnversSchemaGenerator.java @@ -1,3 +1,26 @@ +/* + * Hibernate, Relational Persistence for Idiomatic Java + * + * Copyright (c) 2013, 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.envers.tools.hbm2ddl; import java.sql.Connection; @@ -13,35 +36,35 @@ import org.hibernate.tool.hbm2ddl.SchemaExport; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class EnversSchemaGenerator { - private final SchemaExport export; + private final SchemaExport export; - public EnversSchemaGenerator(ServiceRegistry serviceRegistry, Configuration configuration) { - configuration = configureAuditing(configuration); - export = new SchemaExport(serviceRegistry, configuration); - } + public EnversSchemaGenerator(ServiceRegistry serviceRegistry, Configuration configuration) { + configuration = configureAuditing( configuration ); + export = new SchemaExport( serviceRegistry, configuration ); + } - public EnversSchemaGenerator(Configuration configuration) { - configuration = configureAuditing(configuration); - export = new SchemaExport(configuration); - } + public EnversSchemaGenerator(Configuration configuration) { + configuration = configureAuditing( configuration ); + export = new SchemaExport( configuration ); + } - public EnversSchemaGenerator(Configuration configuration, Properties properties) throws HibernateException { - configuration = configureAuditing(configuration); - export = new SchemaExport(configuration, properties); - } + public EnversSchemaGenerator(Configuration configuration, Properties properties) throws HibernateException { + configuration = configureAuditing( configuration ); + export = new SchemaExport( configuration, properties ); + } - public EnversSchemaGenerator(Configuration configuration, Connection connection) throws HibernateException { - configuration = configureAuditing(configuration); - export = new SchemaExport(configuration, connection); - } + public EnversSchemaGenerator(Configuration configuration, Connection connection) throws HibernateException { + configuration = configureAuditing( configuration ); + export = new SchemaExport( configuration, connection ); + } - public SchemaExport export() { - return export; - } + public SchemaExport export() { + return export; + } - private Configuration configureAuditing(Configuration configuration) { - configuration.buildMappings(); - AuditConfiguration.getFor(configuration); - return configuration; - } + private Configuration configureAuditing(Configuration configuration) { + configuration.buildMappings(); + AuditConfiguration.getFor( configuration ); + return configuration; + } } diff --git a/hibernate-envers/src/test/java/ee/estonia/entities/Child.java b/hibernate-envers/src/test/java/ee/estonia/entities/Child.java index 97b7e8aa69..915f36b08d 100644 --- a/hibernate-envers/src/test/java/ee/estonia/entities/Child.java +++ b/hibernate-envers/src/test/java/ee/estonia/entities/Child.java @@ -1,9 +1,9 @@ package ee.estonia.entities; -import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -13,62 +13,70 @@ import org.hibernate.envers.Audited; @Entity @Audited public class Child implements Serializable { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String data; + private String data; - public Child() { - } + public Child() { + } - public Child(String data) { - this.data = data; - } + public Child(String data) { + this.data = data; + } - public Child(String data, Long id) { - this.id = id; - this.data = data; - } + public Child(String data, Long id) { + this.id = id; + this.data = data; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Child)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Child) ) { + return false; + } - Child that = (Child) o; + Child that = (Child) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "Child(id = " + id + ", data = " + data + ")"; - } + @Override + public String toString() { + return "Child(id = " + id + ", data = " + data + ")"; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/ee/estonia/entities/Parent.java b/hibernate-envers/src/test/java/ee/estonia/entities/Parent.java index c449dc2cd4..a1b63ecbb8 100644 --- a/hibernate-envers/src/test/java/ee/estonia/entities/Parent.java +++ b/hibernate-envers/src/test/java/ee/estonia/entities/Parent.java @@ -1,12 +1,12 @@ package ee.estonia.entities; -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; import org.hibernate.envers.Audited; @@ -16,73 +16,81 @@ import org.hibernate.envers.Audited; @Entity @Audited public class Parent implements Serializable { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String data; + private String data; - @OneToMany - private Set collection = new HashSet(); + @OneToMany + private Set collection = new HashSet(); - public Parent() { - } + public Parent() { + } - public Parent(String data) { - this.data = data; - } + public Parent(String data) { + this.data = data; + } - public Parent(String data, Long id) { - this.id = id; - this.data = data; - } + public Parent(String data, Long id) { + this.id = id; + this.data = data; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Parent)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Parent) ) { + return false; + } - Parent that = (Parent) o; + Parent that = (Parent) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "Parent(id = " + id + ", data = " + data + ")"; - } + @Override + public String toString() { + return "Parent(id = " + id + ", data = " + data + ")"; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Set getCollection() { - return collection; - } + public Set getCollection() { + return collection; + } - public void setCollection(Set collection) { - this.collection = collection; - } + public void setCollection(Set collection) { + this.collection = collection; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/AbstractEnversTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/AbstractEnversTest.java index 6fd640e5fa..85bc1c052f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/AbstractEnversTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/AbstractEnversTest.java @@ -8,22 +8,26 @@ import org.junit.runners.Parameterized; /** * An abstract Envers test which runs the tests using two audit strategies. + * * @author Adam Warski (adam at warski dot org) */ @RunWith(EnversRunner.class) public abstract class AbstractEnversTest { - private String auditStrategy; + private String auditStrategy; - @Parameterized.Parameters - public static List data() { - return Arrays.asList(new Object[]{null}, new Object[]{"org.hibernate.envers.strategy.ValidityAuditStrategy"}); - } + @Parameterized.Parameters + public static List data() { + return Arrays.asList( + new Object[] {null}, + new Object[] {"org.hibernate.envers.strategy.ValidityAuditStrategy"} + ); + } - public void setTestData(Object[] data) { - auditStrategy = (String) data[0]; - } + public void setTestData(Object[] data) { + auditStrategy = (String) data[0]; + } - public String getAuditStrategy() { - return auditStrategy; - } + public String getAuditStrategy() { + return auditStrategy; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/AbstractOneSessionTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/AbstractOneSessionTest.java index 9ece4924be..f8359434e3 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/AbstractOneSessionTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/AbstractOneSessionTest.java @@ -4,8 +4,6 @@ import java.io.File; import java.net.URISyntaxException; import java.net.URL; -import org.junit.Before; - import org.hibernate.MappingException; import org.hibernate.Session; import org.hibernate.SessionFactory; @@ -15,6 +13,9 @@ import org.hibernate.envers.AuditReader; import org.hibernate.envers.AuditReaderFactory; import org.hibernate.envers.configuration.EnversSettings; import org.hibernate.service.ServiceRegistry; + +import org.junit.Before; + import org.hibernate.testing.AfterClassOnce; import org.hibernate.testing.BeforeClassOnce; import org.hibernate.testing.ServiceRegistryBuilder; @@ -24,9 +25,8 @@ import org.hibernate.testing.ServiceRegistryBuilder; * auditReader must be used for the hole test. * * @author Hernán Chanfreau - * */ -public abstract class AbstractOneSessionTest extends AbstractEnversTest { +public abstract class AbstractOneSessionTest extends AbstractEnversTest { protected Configuration config; private ServiceRegistry serviceRegistry; private SessionFactory sessionFactory; @@ -34,41 +34,42 @@ public abstract class AbstractOneSessionTest extends AbstractEnversTest { private AuditReader auditReader; @BeforeClassOnce - public void init() throws URISyntaxException { - config = new Configuration(); - URL url = Thread.currentThread().getContextClassLoader().getResource(getHibernateConfigurationFileName()); - config.configure(new File(url.toURI())); + public void init() throws URISyntaxException { + config = new Configuration(); + URL url = Thread.currentThread().getContextClassLoader().getResource( getHibernateConfigurationFileName() ); + config.configure( new File( url.toURI() ) ); - String auditStrategy = getAuditStrategy(); - if (auditStrategy != null && !"".equals(auditStrategy)) { - config.setProperty(EnversSettings.AUDIT_STRATEGY, auditStrategy); - } - config.setProperty( Environment.USE_NEW_ID_GENERATOR_MAPPINGS, "true" ); - config.setProperty(EnversSettings.USE_REVISION_ENTITY_WITH_NATIVE_ID, "false"); - addProperties(config); + String auditStrategy = getAuditStrategy(); + if ( auditStrategy != null && !"".equals( auditStrategy ) ) { + config.setProperty( EnversSettings.AUDIT_STRATEGY, auditStrategy ); + } + config.setProperty( Environment.USE_NEW_ID_GENERATOR_MAPPINGS, "true" ); + config.setProperty( EnversSettings.USE_REVISION_ENTITY_WITH_NATIVE_ID, "false" ); + addProperties( config ); - this.initMappings(); + this.initMappings(); - serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( config.getProperties() ); + serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( config.getProperties() ); sessionFactory = config.buildSessionFactory( serviceRegistry ); - } + } - protected abstract void initMappings() throws MappingException, URISyntaxException ; + protected abstract void initMappings() throws MappingException, URISyntaxException; - protected void addProperties(Configuration configuration) {} + protected void addProperties(Configuration configuration) { + } - protected String getHibernateConfigurationFileName(){ + protected String getHibernateConfigurationFileName() { return "hibernate.test.session-cfg.xml"; } - private SessionFactory getSessionFactory(){ + private SessionFactory getSessionFactory() { return sessionFactory; - } + } @AfterClassOnce public void closeSessionFactory() { try { - sessionFactory.close(); + sessionFactory.close(); } finally { if ( serviceRegistry != null ) { @@ -84,9 +85,9 @@ public abstract class AbstractOneSessionTest extends AbstractEnversTest { */ @Before public void initializeSession() { - if (getSession() == null) { - session = getSessionFactory().openSession(); - auditReader = AuditReaderFactory.get(session); + if ( getSession() == null ) { + session = getSessionFactory().openSession(); + auditReader = AuditReaderFactory.get( session ); } } @@ -94,8 +95,8 @@ public abstract class AbstractOneSessionTest extends AbstractEnversTest { * Creates a new session and auditReader. */ public void forceNewSession() { - session = getSessionFactory().openSession(); - auditReader = AuditReaderFactory.get(session); + session = getSessionFactory().openSession(); + auditReader = AuditReaderFactory.get( session ); } protected Session getSession() { @@ -103,11 +104,9 @@ public abstract class AbstractOneSessionTest extends AbstractEnversTest { } - protected AuditReader getAuditReader() { return auditReader; } - } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/BaseEnversFunctionalTestCase.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/BaseEnversFunctionalTestCase.java index e6b91a26f5..104725455e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/BaseEnversFunctionalTestCase.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/BaseEnversFunctionalTestCase.java @@ -3,14 +3,15 @@ package org.hibernate.envers.test; import java.util.Arrays; import java.util.List; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - import org.hibernate.Session; import org.hibernate.cfg.Configuration; import org.hibernate.envers.AuditReader; import org.hibernate.envers.AuditReaderFactory; import org.hibernate.envers.configuration.EnversSettings; + +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; + import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; /** @@ -23,8 +24,8 @@ public abstract class BaseEnversFunctionalTestCase extends BaseCoreFunctionalTes @Parameterized.Parameters public static List data() { return Arrays.asList( - new Object[] { null }, - new Object[] { "org.hibernate.envers.strategy.ValidityAuditStrategy" } + new Object[] {null}, + new Object[] {"org.hibernate.envers.strategy.ValidityAuditStrategy"} ); } @@ -43,18 +44,18 @@ public abstract class BaseEnversFunctionalTestCase extends BaseCoreFunctionalTes return session; } - protected AuditReader getAuditReader(){ + protected AuditReader getAuditReader() { return AuditReaderFactory.get( getSession() ); } - @Override - protected Configuration constructConfiguration() { - Configuration configuration = super.constructConfiguration(); - configuration.setProperty(EnversSettings.USE_REVISION_ENTITY_WITH_NATIVE_ID, "false"); - return configuration; - } + @Override + protected Configuration constructConfiguration() { + Configuration configuration = super.constructConfiguration(); + configuration.setProperty( EnversSettings.USE_REVISION_ENTITY_WITH_NATIVE_ID, "false" ); + return configuration; + } - @Override + @Override protected String getBaseForMappings() { return ""; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/BaseEnversJPAFunctionalTestCase.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/BaseEnversJPAFunctionalTestCase.java index 0590352301..0bb267cbc6 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/BaseEnversJPAFunctionalTestCase.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/BaseEnversJPAFunctionalTestCase.java @@ -23,16 +23,15 @@ */ package org.hibernate.envers.test; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.transaction.SystemException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.transaction.SystemException; import org.jboss.logging.Logger; -import org.junit.After; import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl; import org.hibernate.cfg.Configuration; @@ -50,6 +49,9 @@ import org.hibernate.jpa.boot.spi.Bootstrap; import org.hibernate.jpa.boot.spi.PersistenceUnitDescriptor; import org.hibernate.jpa.internal.EntityManagerFactoryImpl; import org.hibernate.jpa.test.PersistenceUnitDescriptorAdapter; + +import org.junit.After; + import org.hibernate.testing.AfterClassOnce; import org.hibernate.testing.BeforeClassOnce; import org.hibernate.testing.jta.TestingJtaPlatformImpl; @@ -88,7 +90,7 @@ public abstract class BaseEnversJPAFunctionalTestCase extends AbstractEnversTest } @BeforeClassOnce - @SuppressWarnings({ "UnusedDeclaration" }) + @SuppressWarnings({"UnusedDeclaration"}) public void buildEntityManagerFactory() throws Exception { log.trace( "Building EntityManagerFactory" ); @@ -117,7 +119,7 @@ public abstract class BaseEnversJPAFunctionalTestCase extends AbstractEnversTest settings.put( org.hibernate.cfg.AvailableSettings.HBM2DDL_AUTO, "create-drop" ); final String secondSchemaName = createSecondSchema(); if ( StringHelper.isNotEmpty( secondSchemaName ) ) { - if ( !( getDialect() instanceof H2Dialect ) ) { + if ( !(getDialect() instanceof H2Dialect) ) { throw new UnsupportedOperationException( "Only H2 dialect supports creation of second schema." ); } Helper.createH2Schema( secondSchemaName, settings ); @@ -128,7 +130,7 @@ public abstract class BaseEnversJPAFunctionalTestCase extends AbstractEnversTest settings.put( EnversSettings.AUDIT_STRATEGY, getAuditStrategy() ); } - if ( ! autoRegisterListeners() ) { + if ( !autoRegisterListeners() ) { settings.put( EnversIntegrator.AUTO_REGISTER, "false" ); } @@ -195,7 +197,7 @@ public abstract class BaseEnversJPAFunctionalTestCase extends AbstractEnversTest } public String[] getEjb3DD() { - return new String[] { }; + return new String[] {}; } protected void afterEntityManagerFactoryBuilt() { @@ -207,6 +209,7 @@ public abstract class BaseEnversJPAFunctionalTestCase extends AbstractEnversTest /** * Feature supported only by H2 dialect. + * * @return Provide not empty name to create second schema. */ protected String createSecondSchema() { @@ -218,14 +221,14 @@ public abstract class BaseEnversJPAFunctionalTestCase extends AbstractEnversTest } @AfterClassOnce - public void releaseEntityManagerFactory(){ + public void releaseEntityManagerFactory() { if ( entityManagerFactory != null && entityManagerFactory.isOpen() ) { entityManagerFactory.close(); } } @After - @SuppressWarnings({ "UnusedDeclaration" }) + @SuppressWarnings({"UnusedDeclaration"}) public void releaseUnclosedEntityManagers() { releaseUnclosedEntityManager( this.em ); auditReader = null; @@ -250,13 +253,13 @@ public abstract class BaseEnversJPAFunctionalTestCase extends AbstractEnversTest catch (SystemException ignored) { } } - try{ + try { if ( em.getTransaction().isActive() ) { em.getTransaction().rollback(); log.warn( "You left an open transaction! Fix your test case. For now, we are closing it for you." ); } } - catch ( IllegalStateException e ) { + catch (IllegalStateException e) { } if ( em.isOpen() ) { // as we open an EM before the test runs, it will still be open if the test uses a custom EM. @@ -265,9 +268,11 @@ public abstract class BaseEnversJPAFunctionalTestCase extends AbstractEnversTest log.warn( "The EntityManager is not closed. Closing it." ); } } - protected EntityManager getEntityManager(){ + + protected EntityManager getEntityManager() { return getOrCreateEntityManager(); } + protected EntityManager getOrCreateEntityManager() { if ( em == null || !em.isOpen() ) { em = entityManagerFactory.createEntityManager(); @@ -275,8 +280,8 @@ public abstract class BaseEnversJPAFunctionalTestCase extends AbstractEnversTest return em; } - protected AuditReader getAuditReader(){ - if(auditReader!=null){ + protected AuditReader getAuditReader() { + if ( auditReader != null ) { return auditReader; } return auditReader = AuditReaderFactory.get( getOrCreateEntityManager() ); diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/EnversRunner.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/EnversRunner.java index 50c2905a4c..75cca41898 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/EnversRunner.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/EnversRunner.java @@ -18,13 +18,14 @@ import org.hibernate.testing.junit4.CustomRunner; /** * Copied & modified from {@link org.junit.runners.Parameterized}. - * + *

      * The modification is that the generated runners extend {@link CustomRunner} instead of the default * {@code TestClassRunnerForParameters}. - * + *

      * The runner itself sets the data using a setter instead of a constructor, and creates only one test instance. Moreover * it doesn't override {@code classBlock} which causes the custom {@code @BeforeClassOnce} and {@code @AfterClassOnce} * annotations to work. + * * @author Adam Warski (adam at warski dot org) */ public class EnversRunner extends Suite { @@ -34,74 +35,88 @@ public class EnversRunner extends Suite { private final List fParameterList; TestClassCustomRunnerForParameters(Class type, List parameterList, int i) - throws InitializationError, NoTestsRemainException { - super(type); - fParameterList= parameterList; - fParameterSetNumber= i; + throws InitializationError, NoTestsRemainException { + super( type ); + fParameterList = parameterList; + fParameterSetNumber = i; } - @Override - protected Object getTestInstance() throws Exception { - Object testInstance = super.getTestInstance(); - if ( AbstractEnversTest.class.isInstance( testInstance ) ) { - ( (AbstractEnversTest) testInstance ).setTestData( computeParams() ); - } - else if ( BaseEnversFunctionalTestCase.class.isInstance( testInstance ) ) { - ( (BaseEnversFunctionalTestCase) testInstance ).setTestData( computeParams() ); - } - return testInstance; - } + @Override + protected Object getTestInstance() throws Exception { + Object testInstance = super.getTestInstance(); + if ( AbstractEnversTest.class.isInstance( testInstance ) ) { + ((AbstractEnversTest) testInstance).setTestData( computeParams() ); + } + else if ( BaseEnversFunctionalTestCase.class.isInstance( testInstance ) ) { + ((BaseEnversFunctionalTestCase) testInstance).setTestData( computeParams() ); + } + return testInstance; + } private Object[] computeParams() throws Exception { try { - return fParameterList.get(fParameterSetNumber); - } catch (ClassCastException e) { - throw new Exception(String.format( - "%s.%s() must return a Collection of arrays.", - getTestClass().getName(), getParametersMethod( - getTestClass()).getName())); + return fParameterList.get( fParameterSetNumber ); + } + catch (ClassCastException e) { + throw new Exception( + String.format( + "%s.%s() must return a Collection of arrays.", + getTestClass().getName(), getParametersMethod( + getTestClass() + ).getName() + ) + ); } } @Override protected String getName() { - return String.format("[%s]", fParameterSetNumber); + return String.format( "[%s]", fParameterSetNumber ); } @Override protected String testName(final FrameworkMethod method) { - return String.format("%s[%s]", method.getName(), - fParameterSetNumber); + return String.format( + "%s[%s]", method.getName(), + fParameterSetNumber + ); } @Override protected void sortMethods(List computedTestMethods) { super.sortMethods( computedTestMethods ); - Collections.sort(computedTestMethods, new Comparator() { + Collections.sort( + computedTestMethods, new Comparator() { private int getPriority(FrameworkMethod fm) { - Priority p = fm.getAnnotation(Priority.class); + Priority p = fm.getAnnotation( Priority.class ); return p == null ? 0 : p.value(); } @Override public int compare(FrameworkMethod fm1, FrameworkMethod fm2) { - return getPriority(fm2) - getPriority(fm1); + return getPriority( fm2 ) - getPriority( fm1 ); } - }); + } + ); } - } + } - private final ArrayList runners= new ArrayList(); + private final ArrayList runners = new ArrayList(); /** * Only called reflectively. Do not use programmatically. */ public EnversRunner(Class klass) throws Throwable { - super(klass, Collections.emptyList()); - List parametersList= getParametersList(getTestClass()); - for (int i= 0; i < parametersList.size(); i++) - runners.add(new TestClassCustomRunnerForParameters(getTestClass().getJavaClass(), - parametersList, i)); + super( klass, Collections.emptyList() ); + List parametersList = getParametersList( getTestClass() ); + for ( int i = 0; i < parametersList.size(); i++ ) { + runners.add( + new TestClassCustomRunnerForParameters( + getTestClass().getJavaClass(), + parametersList, i + ) + ); + } } @Override @@ -112,22 +127,26 @@ public class EnversRunner extends Suite { @SuppressWarnings("unchecked") private List getParametersList(TestClass klass) throws Throwable { - return (List) getParametersMethod(klass).invokeExplosively( - null); + return (List) getParametersMethod( klass ).invokeExplosively( + null + ); } private FrameworkMethod getParametersMethod(TestClass testClass) throws Exception { - List methods= testClass.getAnnotatedMethods(Parameterized.Parameters.class); + List methods = testClass.getAnnotatedMethods( Parameterized.Parameters.class ); - for (FrameworkMethod each : methods) { - int modifiers= each.getMethod().getModifiers(); - if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers)) + for ( FrameworkMethod each : methods ) { + int modifiers = each.getMethod().getModifiers(); + if ( Modifier.isStatic( modifiers ) && Modifier.isPublic( modifiers ) ) { return each; + } } - throw new Exception("No public static parameters method on class " - + testClass.getName()); + throw new Exception( + "No public static parameters method on class " + + testClass.getName() + ); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/Priority.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/Priority.java index f18f9d9b8d..0120b55b7f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/Priority.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/Priority.java @@ -8,10 +8,11 @@ import java.lang.annotation.Target; /** * An annotation for specifyfing test method priority. Methods with higher priorities execute earlier. * If the annotation is not present priority 0 is assumed. + * * @author Adam Warski (adam at warski dot org) */ @Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.METHOD, ElementType.TYPE }) +@Target({ElementType.METHOD, ElementType.TYPE}) public @interface Priority { int value(); } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/IntNoAutoIdTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/IntNoAutoIdTestEntity.java index d5af7eb797..5a4891f322 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/IntNoAutoIdTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/IntNoAutoIdTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities; + import javax.persistence.Entity; import javax.persistence.Id; @@ -32,61 +33,69 @@ import org.hibernate.envers.Audited; */ @Entity public class IntNoAutoIdTestEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private Integer numVal; + @Audited + private Integer numVal; - public IntNoAutoIdTestEntity() { - } + public IntNoAutoIdTestEntity() { + } - public IntNoAutoIdTestEntity(Integer numVal, Integer id) { - this.id = id; - this.numVal = numVal; - } + public IntNoAutoIdTestEntity(Integer numVal, Integer id) { + this.id = id; + this.numVal = numVal; + } - public IntNoAutoIdTestEntity(Integer numVal) { - this.numVal = numVal; - } + public IntNoAutoIdTestEntity(Integer numVal) { + this.numVal = numVal; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Integer getNumVal() { - return numVal; - } + public Integer getNumVal() { + return numVal; + } - public void setNumVal(Integer numVal) { - this.numVal = numVal; - } + public void setNumVal(Integer numVal) { + this.numVal = numVal; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof IntNoAutoIdTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof IntNoAutoIdTestEntity) ) { + return false; + } - IntNoAutoIdTestEntity that = (IntNoAutoIdTestEntity) o; + IntNoAutoIdTestEntity that = (IntNoAutoIdTestEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - //noinspection RedundantIfStatement - if (numVal != null ? !numVal.equals(that.numVal) : that.numVal != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( numVal != null ? !numVal.equals( that.numVal ) : that.numVal != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (numVal != null ? numVal.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (numVal != null ? numVal.hashCode() : 0); + return result; + } - public String toString() { - return "INATE(id = " + id + ", numVal = " + numVal + ")"; - } + public String toString() { + return "INATE(id = " + id + ", numVal = " + numVal + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/IntTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/IntTestEntity.java index 3fbd16b2d3..9d73c06ccd 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/IntTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/IntTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -34,61 +35,69 @@ import org.hibernate.envers.Audited; */ @Entity public class IntTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - @Column(name = "NUMERIC_VALUE") - private Integer number; + @Audited + @Column(name = "NUMERIC_VALUE") + private Integer number; - public IntTestEntity() { - } + public IntTestEntity() { + } - public IntTestEntity(Integer number, Integer id) { - this.id = id; - this.number = number; - } + public IntTestEntity(Integer number, Integer id) { + this.id = id; + this.number = number; + } - public IntTestEntity(Integer number) { - this.number = number; - } + public IntTestEntity(Integer number) { + this.number = number; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Integer getNumber() { - return number; - } + public Integer getNumber() { + return number; + } - public void setNumber(Integer number) { - this.number = number; - } + public void setNumber(Integer number) { + this.number = number; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof IntTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof IntTestEntity) ) { + return false; + } - IntTestEntity that = (IntTestEntity) o; + IntTestEntity that = (IntTestEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (number != null ? !number.equals(that.number) : that.number != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( number != null ? !number.equals( that.number ) : that.number != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = (id != null ? id.hashCode() : 0); - result = 31 * result + (number != null ? number.hashCode() : 0); - return result; - } + public int hashCode() { + int result = (id != null ? id.hashCode() : 0); + result = 31 * result + (number != null ? number.hashCode() : 0); + return result; + } - public String toString() { - return "ITE(id = " + id + ", number = " + number + ")"; - } + public String toString() { + return "ITE(id = " + id + ", number = " + number + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/IntTestPrivSeqEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/IntTestPrivSeqEntity.java index ec1f202242..0aa2592d08 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/IntTestPrivSeqEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/IntTestPrivSeqEntity.java @@ -11,67 +11,76 @@ import org.hibernate.envers.Audited; /** * Duplicate of {@link IntTestEntity} but with private sequence generator. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @Entity public class IntTestPrivSeqEntity { - @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "IntTestPrivSeq") - @SequenceGenerator(name = "IntTestPrivSeq", sequenceName="INTTESTPRIV_SEQ", - allocationSize = 1, initialValue = 1) - private Integer id; + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "IntTestPrivSeq") + @SequenceGenerator(name = "IntTestPrivSeq", sequenceName = "INTTESTPRIV_SEQ", + allocationSize = 1, initialValue = 1) + private Integer id; - @Audited - @Column(name = "NUMERIC_VALUE") - private Integer number; + @Audited + @Column(name = "NUMERIC_VALUE") + private Integer number; - public IntTestPrivSeqEntity() { - } + public IntTestPrivSeqEntity() { + } - public IntTestPrivSeqEntity(Integer number, Integer id) { - this.id = id; - this.number = number; - } + public IntTestPrivSeqEntity(Integer number, Integer id) { + this.id = id; + this.number = number; + } - public IntTestPrivSeqEntity(Integer number) { - this.number = number; - } + public IntTestPrivSeqEntity(Integer number) { + this.number = number; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Integer getNumber() { - return number; - } + public Integer getNumber() { + return number; + } - public void setNumber(Integer number) { - this.number = number; - } + public void setNumber(Integer number) { + this.number = number; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof IntTestPrivSeqEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof IntTestPrivSeqEntity) ) { + return false; + } - IntTestPrivSeqEntity that = (IntTestPrivSeqEntity) o; + IntTestPrivSeqEntity that = (IntTestPrivSeqEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (number != null ? !number.equals(that.number) : that.number != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( number != null ? !number.equals( that.number ) : that.number != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = (id != null ? id.hashCode() : 0); - result = 31 * result + (number != null ? number.hashCode() : 0); - return result; - } + public int hashCode() { + int result = (id != null ? id.hashCode() : 0); + result = 31 * result + (number != null ? number.hashCode() : 0); + return result; + } - public String toString() { - return "ITPSE(id = " + id + ", number = " + number + ")"; - } + public String toString() { + return "ITPSE(id = " + id + ", number = " + number + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/PrimitiveTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/PrimitiveTestEntity.java index df383049a7..07a9f9524a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/PrimitiveTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/PrimitiveTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -33,17 +34,17 @@ import org.hibernate.envers.Audited; */ @Entity public class PrimitiveTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - private int numVal1; + @Audited + private int numVal1; private int numVal2; - public PrimitiveTestEntity() { - } + public PrimitiveTestEntity() { + } public PrimitiveTestEntity(int numVal1, int numVal2) { this.numVal1 = numVal1; @@ -57,20 +58,20 @@ public class PrimitiveTestEntity { } public Integer getId() { - return id; - } + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Integer getNumVal1() { - return numVal1; - } + public Integer getNumVal1() { + return numVal1; + } - public void setNumVal1(Integer numVal1) { - this.numVal1 = numVal1; - } + public void setNumVal1(Integer numVal1) { + this.numVal1 = numVal1; + } public int getNumVal2() { return numVal2; @@ -82,14 +83,24 @@ public class PrimitiveTestEntity { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof PrimitiveTestEntity)) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof PrimitiveTestEntity) ) { + return false; + } PrimitiveTestEntity that = (PrimitiveTestEntity) o; - if (numVal1 != that.numVal1) return false; - if (numVal2 != that.numVal2) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( numVal1 != that.numVal1 ) { + return false; + } + if ( numVal2 != that.numVal2 ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } return true; } @@ -103,6 +114,6 @@ public class PrimitiveTestEntity { } public String toString() { - return "PTE(id = " + id + ", numVal1 = " + numVal1 + ", numVal2 = " + numVal2 + ")"; - } + return "PTE(id = " + id + ", numVal1 = " + numVal1 + ", numVal2 = " + numVal2 + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrIntTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrIntTestEntity.java index aad2ee8f2d..ce1e08bff2 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrIntTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrIntTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -34,77 +35,87 @@ import org.hibernate.envers.Audited; */ @Entity public class StrIntTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - private String str1; + @Audited + private String str1; - @Audited - @Column(name = "NUM_VAL") - private Integer number; + @Audited + @Column(name = "NUM_VAL") + private Integer number; - public StrIntTestEntity() { - } + public StrIntTestEntity() { + } - public StrIntTestEntity(String str1, Integer number, Integer id) { - this.id = id; - this.str1 = str1; - this.number = number; - } + public StrIntTestEntity(String str1, Integer number, Integer id) { + this.id = id; + this.str1 = str1; + this.number = number; + } - public StrIntTestEntity(String str1, Integer number) { - this.str1 = str1; - this.number = number; - } + public StrIntTestEntity(String str1, Integer number) { + this.str1 = str1; + this.number = number; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - public Integer getNumber() { - return number; - } + public Integer getNumber() { + return number; + } - public void setNumber(Integer number) { - this.number = number; - } + public void setNumber(Integer number) { + this.number = number; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof StrIntTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof StrIntTestEntity) ) { + return false; + } - StrIntTestEntity that = (StrIntTestEntity) o; + StrIntTestEntity that = (StrIntTestEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (number != null ? !number.equals(that.number) : that.number != null) return false; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( number != null ? !number.equals( that.number ) : that.number != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str1 != null ? str1.hashCode() : 0); - result = 31 * result + (number != null ? number.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str1 != null ? str1.hashCode() : 0); + result = 31 * result + (number != null ? number.hashCode() : 0); + return result; + } - public String toString() { - return "SITE(id = " + id + ", str1 = " + str1 + ", number = " + number + ")"; - } + public String toString() { + return "SITE(id = " + id + ", str1 = " + str1 + ", number = " + number + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrTestEntity.java index aa268f4cde..ad55283b47 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -35,61 +36,69 @@ import org.hibernate.envers.Audited; @Entity @Table(name = "STR_TEST") public class StrTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - private String str; + @Audited + private String str; - public StrTestEntity() { - } + public StrTestEntity() { + } - public StrTestEntity(String str, Integer id) { - this.str = str; - this.id = id; - } + public StrTestEntity(String str, Integer id) { + this.str = str; + this.id = id; + } - public StrTestEntity(String str) { - this.str = str; - } + public StrTestEntity(String str) { + this.str = str; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStr() { - return str; - } + public String getStr() { + return str; + } - public void setStr(String str) { - this.str = str; - } + public void setStr(String str) { + this.str = str; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof StrTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof StrTestEntity) ) { + return false; + } - StrTestEntity that = (StrTestEntity) o; + StrTestEntity that = (StrTestEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (str != null ? !str.equals(that.str) : that.str != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str != null ? !str.equals( that.str ) : that.str != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str != null ? str.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str != null ? str.hashCode() : 0); + return result; + } - public String toString() { - return "STE(id = " + id + ", str = " + str + ")"; - } + public String toString() { + return "STE(id = " + id + ", str = " + str + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrTestEntityComparator.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrTestEntityComparator.java index 5954cc8842..8f8ce8ef41 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrTestEntityComparator.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrTestEntityComparator.java @@ -3,10 +3,10 @@ package org.hibernate.envers.test.entities; import java.util.Comparator; public class StrTestEntityComparator implements Comparator { - public static final StrTestEntityComparator INSTANCE = new StrTestEntityComparator(); + public static final StrTestEntityComparator INSTANCE = new StrTestEntityComparator(); - @Override - public int compare(StrTestEntity o1, StrTestEntity o2) { - return o1.getStr().compareTo(o2.getStr()); - } + @Override + public int compare(StrTestEntity o1, StrTestEntity o2) { + return o1.getStr().compareTo( o2.getStr() ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrTestNoProxyEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrTestNoProxyEntity.java index 7a1ef0fb09..14d0b26e1f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrTestNoProxyEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrTestNoProxyEntity.java @@ -23,11 +23,11 @@ */ package org.hibernate.envers.test.entities; -import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; +import java.io.Serializable; import org.hibernate.annotations.Proxy; import org.hibernate.envers.Audited; @@ -75,20 +75,28 @@ public class StrTestNoProxyEntity implements Serializable { } public boolean equals(Object o) { - if ( this == o ) return true; - if ( !( o instanceof StrTestNoProxyEntity ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof StrTestNoProxyEntity) ) { + return false; + } StrTestNoProxyEntity that = (StrTestNoProxyEntity) o; - if ( id != null ? !id.equals( that.id ) : that.id != null ) return false; - if ( str != null ? !str.equals( that.str ) : that.str != null ) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str != null ? !str.equals( that.str ) : that.str != null ) { + return false; + } return true; } public int hashCode() { - int result = ( id != null ? id.hashCode() : 0 ); - result = 31 * result + ( str != null ? str.hashCode() : 0 ); + int result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str != null ? str.hashCode() : 0); return result; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrTestPrivSeqEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrTestPrivSeqEntity.java index 5f39679322..ff67fe54f9 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrTestPrivSeqEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/StrTestPrivSeqEntity.java @@ -11,68 +11,77 @@ import org.hibernate.envers.Audited; /** * Duplicate of {@link StrTestEntity} but with private sequence generator. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @Entity @Table(name = "STRSEQ") public class StrTestPrivSeqEntity { - @Id - @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "StrTestPrivSeq") - @SequenceGenerator(name = "StrTestPrivSeq", sequenceName="STRTESTPRIV_SEQ", - allocationSize = 1, initialValue = 1) - private Integer id; + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "StrTestPrivSeq") + @SequenceGenerator(name = "StrTestPrivSeq", sequenceName = "STRTESTPRIV_SEQ", + allocationSize = 1, initialValue = 1) + private Integer id; - @Audited - private String str; + @Audited + private String str; - public StrTestPrivSeqEntity() { - } + public StrTestPrivSeqEntity() { + } - public StrTestPrivSeqEntity(String str, Integer id) { - this.str = str; - this.id = id; - } + public StrTestPrivSeqEntity(String str, Integer id) { + this.str = str; + this.id = id; + } - public StrTestPrivSeqEntity(String str) { - this.str = str; - } + public StrTestPrivSeqEntity(String str) { + this.str = str; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStr() { - return str; - } + public String getStr() { + return str; + } - public void setStr(String str) { - this.str = str; - } + public void setStr(String str) { + this.str = str; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof StrTestPrivSeqEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof StrTestPrivSeqEntity) ) { + return false; + } - StrTestPrivSeqEntity that = (StrTestPrivSeqEntity) o; + StrTestPrivSeqEntity that = (StrTestPrivSeqEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (str != null ? !str.equals(that.str) : that.str != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str != null ? !str.equals( that.str ) : that.str != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str != null ? str.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str != null ? str.hashCode() : 0); + return result; + } - public String toString() { - return "STPSE(id = " + id + ", str = " + str + ")"; - } + public String toString() { + return "STPSE(id = " + id + ", str = " + str + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/UnversionedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/UnversionedEntity.java index ac128fefdb..24335d37ef 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/UnversionedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/UnversionedEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities; + import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -36,73 +37,83 @@ import org.hibernate.envers.NotAudited; @Entity @Audited public class UnversionedEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Basic - private String data1; + @Basic + private String data1; - @Basic - @NotAudited - private String data2; + @Basic + @NotAudited + private String data2; - public UnversionedEntity() { - } + public UnversionedEntity() { + } - public UnversionedEntity(String data1, String data2) { - this.data1 = data1; - this.data2 = data2; - } + public UnversionedEntity(String data1, String data2) { + this.data1 = data1; + this.data2 = data2; + } - public UnversionedEntity(Integer id, String data1, String data2) { - this.id = id; - this.data1 = data1; - this.data2 = data2; - } + public UnversionedEntity(Integer id, String data1, String data2) { + this.id = id; + this.data1 = data1; + this.data2 = data2; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData1() { - return data1; - } + public String getData1() { + return data1; + } - public void setData1(String data1) { - this.data1 = data1; - } + public void setData1(String data1) { + this.data1 = data1; + } - public String getData2() { - return data2; - } + public String getData2() { + return data2; + } - public void setData2(String data2) { - this.data2 = data2; - } + public void setData2(String data2) { + this.data2 = data2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof UnversionedEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof UnversionedEntity) ) { + return false; + } - UnversionedEntity that = (UnversionedEntity) o; + UnversionedEntity that = (UnversionedEntity) o; - if (data1 != null ? !data1.equals(that.data1) : that.data1 != null) return false; - if (data2 != null ? !data2.equals(that.data2) : that.data2 != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data1 != null ? !data1.equals( that.data1 ) : that.data1 != null ) { + return false; + } + if ( data2 != null ? !data2.equals( that.data2 ) : that.data2 != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data1 != null ? data1.hashCode() : 0); - result = 31 * result + (data2 != null ? data2.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data1 != null ? data1.hashCode() : 0); + result = 31 * result + (data2 != null ? data2.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/UnversionedStrTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/UnversionedStrTestEntity.java index e4f0d80d6c..a21a157c36 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/UnversionedStrTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/UnversionedStrTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -33,60 +34,68 @@ import javax.persistence.Table; @Entity @Table(name = "UNVER_DATA") public class UnversionedStrTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String str; + private String str; - public UnversionedStrTestEntity() { - } + public UnversionedStrTestEntity() { + } - public UnversionedStrTestEntity(String str, Integer id) { - this.str = str; - this.id = id; - } + public UnversionedStrTestEntity(String str, Integer id) { + this.str = str; + this.id = id; + } - public UnversionedStrTestEntity(String str) { - this.str = str; - } + public UnversionedStrTestEntity(String str) { + this.str = str; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStr() { - return str; - } + public String getStr() { + return str; + } - public void setStr(String str) { - this.str = str; - } + public void setStr(String str) { + this.str = str; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof UnversionedStrTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof UnversionedStrTestEntity) ) { + return false; + } - UnversionedStrTestEntity that = (UnversionedStrTestEntity) o; + UnversionedStrTestEntity that = (UnversionedStrTestEntity) o; - if (id != null ? !id.equals(that.getId()) : that.getId() != null) return false; - if (str != null ? !str.equals(that.getStr()) : that.getStr() != null) return false; + if ( id != null ? !id.equals( that.getId() ) : that.getId() != null ) { + return false; + } + if ( str != null ? !str.equals( that.getStr() ) : that.getStr() != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str != null ? str.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str != null ? str.hashCode() : 0); + return result; + } - public String toString() { - return "USTE(id = " + id + ", str = " + str + ")"; - } + public String toString() { + return "USTE(id = " + id + ", str = " + str + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EmbeddableListEntity1.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EmbeddableListEntity1.java index 8b93599693..ed01a9c864 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EmbeddableListEntity1.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EmbeddableListEntity1.java @@ -23,8 +23,6 @@ */ package org.hibernate.envers.test.entities.collection; -import java.util.ArrayList; -import java.util.List; import javax.persistence.CollectionTable; import javax.persistence.ElementCollection; import javax.persistence.Entity; @@ -32,6 +30,8 @@ import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OrderColumn; import javax.persistence.Table; +import java.util.ArrayList; +import java.util.List; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.components.Component3; @@ -82,18 +82,24 @@ public class EmbeddableListEntity1 { } public boolean equals(Object o) { - if ( this == o ) return true; - if ( !( o instanceof EmbeddableListEntity1 ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof EmbeddableListEntity1) ) { + return false; + } EmbeddableListEntity1 that = (EmbeddableListEntity1) o; - if ( id != null ? !id.equals( that.id ) : that.id != null ) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } return true; } public int hashCode() { - return ( id != null ? id.hashCode() : 0 ); + return (id != null ? id.hashCode() : 0); } public String toString() { diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EmbeddableListEntity2.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EmbeddableListEntity2.java index 82029ab6fa..05b7ebd577 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EmbeddableListEntity2.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EmbeddableListEntity2.java @@ -23,8 +23,6 @@ */ package org.hibernate.envers.test.entities.collection; -import java.util.ArrayList; -import java.util.List; import javax.persistence.CollectionTable; import javax.persistence.ElementCollection; import javax.persistence.Entity; @@ -32,6 +30,8 @@ import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OrderColumn; import javax.persistence.Table; +import java.util.ArrayList; +import java.util.List; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.components.relations.ManyToOneEagerComponent; @@ -74,18 +74,24 @@ public class EmbeddableListEntity2 { } public boolean equals(Object o) { - if ( this == o ) return true; - if ( !( o instanceof EmbeddableListEntity2 ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof EmbeddableListEntity2) ) { + return false; + } EmbeddableListEntity2 that = (EmbeddableListEntity2) o; - if ( id != null ? !id.equals( that.id ) : that.id != null ) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } return true; } public int hashCode() { - return ( id != null ? id.hashCode() : 0 ); + return (id != null ? id.hashCode() : 0); } public String toString() { diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EmbeddableMapEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EmbeddableMapEntity.java index 7e59ce4cce..7f2083558f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EmbeddableMapEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EmbeddableMapEntity.java @@ -23,8 +23,6 @@ */ package org.hibernate.envers.test.entities.collection; -import java.util.HashMap; -import java.util.Map; import javax.persistence.CollectionTable; import javax.persistence.ElementCollection; import javax.persistence.Entity; @@ -32,6 +30,8 @@ import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.MapKeyColumn; import javax.persistence.Table; +import java.util.HashMap; +import java.util.Map; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.components.Component3; @@ -73,18 +73,24 @@ public class EmbeddableMapEntity { } public boolean equals(Object o) { - if ( this == o ) return true; - if ( !( o instanceof EmbeddableMapEntity ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof EmbeddableMapEntity) ) { + return false; + } EmbeddableMapEntity that = (EmbeddableMapEntity) o; - if ( id != null ? !id.equals( that.id ) : that.id != null ) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } return true; } public int hashCode() { - return ( id != null ? id.hashCode() : 0 ); + return (id != null ? id.hashCode() : 0); } public String toString() { diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EmbeddableSetEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EmbeddableSetEntity.java index e5a09afadf..0c7b8087cc 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EmbeddableSetEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EmbeddableSetEntity.java @@ -23,14 +23,14 @@ */ package org.hibernate.envers.test.entities.collection; -import java.util.HashSet; -import java.util.Set; import javax.persistence.CollectionTable; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; +import java.util.HashSet; +import java.util.Set; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.components.Component3; @@ -70,18 +70,24 @@ public class EmbeddableSetEntity { } public boolean equals(Object o) { - if ( this == o ) return true; - if ( !( o instanceof EmbeddableSetEntity ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof EmbeddableSetEntity) ) { + return false; + } EmbeddableSetEntity that = (EmbeddableSetEntity) o; - if ( id != null ? !id.equals( that.id ) : that.id != null ) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } return true; } public int hashCode() { - return ( id != null ? id.hashCode() : 0 ); + return (id != null ? id.hashCode() : 0); } public String toString() { diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EnumSetEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EnumSetEntity.java index f0d3efae39..3d7cecf751 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EnumSetEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/EnumSetEntity.java @@ -22,14 +22,15 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.collection; -import java.util.HashSet; -import java.util.Set; + import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import java.util.HashSet; +import java.util.Set; import org.hibernate.envers.Audited; @@ -38,68 +39,75 @@ import org.hibernate.envers.Audited; */ @Entity public class EnumSetEntity { - public static enum E1 { X, Y } - public static enum E2 { A, B } + public static enum E1 {X, Y} - @Id - @GeneratedValue - private Integer id; + public static enum E2 {A, B} - @Audited - @ElementCollection - @Enumerated(EnumType.STRING) - private Set enums1; + @Id + @GeneratedValue + private Integer id; - @Audited - @ElementCollection - @Enumerated(EnumType.ORDINAL) - private Set enums2; + @Audited + @ElementCollection + @Enumerated(EnumType.STRING) + private Set enums1; - public EnumSetEntity() { - enums1 = new HashSet(); - enums2 = new HashSet(); - } + @Audited + @ElementCollection + @Enumerated(EnumType.ORDINAL) + private Set enums2; - public Integer getId() { - return id; - } + public EnumSetEntity() { + enums1 = new HashSet(); + enums2 = new HashSet(); + } - public void setId(Integer id) { - this.id = id; - } + public Integer getId() { + return id; + } - public Set getEnums1() { - return enums1; - } + public void setId(Integer id) { + this.id = id; + } - public void setEnums1(Set enums1) { - this.enums1 = enums1; - } + public Set getEnums1() { + return enums1; + } - public Set getEnums2() { - return enums2; - } + public void setEnums1(Set enums1) { + this.enums1 = enums1; + } - public void setEnums2(Set enums2) { - this.enums2 = enums2; - } + public Set getEnums2() { + return enums2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof EnumSetEntity)) return false; + public void setEnums2(Set enums2) { + this.enums2 = enums2; + } - EnumSetEntity that = (EnumSetEntity) o; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof EnumSetEntity) ) { + return false; + } - if (id != null ? !id.equals(that.id) : that.id != null) return false; + EnumSetEntity that = (EnumSetEntity) o; - return true; - } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - public int hashCode() { - return (id != null ? id.hashCode() : 0); - } + return true; + } - public String toString() { - return "ESE(id = " + id + ", enums1 = " + enums1 + ", enums2 = " + enums2 + ")"; - } + public int hashCode() { + return (id != null ? id.hashCode() : 0); + } + + public String toString() { + return "ESE(id = " + id + ", enums1 = " + enums1 + ", enums2 = " + enums2 + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/MultipleCollectionEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/MultipleCollectionEntity.java index 443b143ec5..79ed9e7b36 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/MultipleCollectionEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/MultipleCollectionEntity.java @@ -1,8 +1,5 @@ package org.hibernate.envers.test.entities.collection; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; @@ -13,6 +10,9 @@ import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Version; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; import org.hibernate.envers.AuditJoinTable; import org.hibernate.envers.Audited; @@ -59,27 +59,27 @@ public class MultipleCollectionEntity { } public List getRefEntities1() { - return Collections.unmodifiableList(refEntities1); + return Collections.unmodifiableList( refEntities1 ); } public void addRefEntity1(MultipleCollectionRefEntity1 refEntity1) { - refEntities1.add(refEntity1); + refEntities1.add( refEntity1 ); } public void removeRefEntity1(MultipleCollectionRefEntity1 refEntity1) { - refEntities1.remove(refEntity1); + refEntities1.remove( refEntity1 ); } public List getRefEntities2() { - return Collections.unmodifiableList(refEntities2); + return Collections.unmodifiableList( refEntities2 ); } public void addRefEntity2(MultipleCollectionRefEntity2 refEntity2) { - refEntities2.add(refEntity2); + refEntities2.add( refEntity2 ); } public void removeRefEntity2(MultipleCollectionRefEntity2 refEntity2) { - refEntities2.remove(refEntity2); + refEntities2.remove( refEntity2 ); } /** @@ -108,7 +108,7 @@ public class MultipleCollectionEntity { if ( this == o ) { return true; } - if ( ! ( o instanceof MultipleCollectionEntity ) ) { + if ( !(o instanceof MultipleCollectionEntity) ) { return false; } @@ -130,8 +130,8 @@ public class MultipleCollectionEntity { @Override public int hashCode() { int result = text != null ? text.hashCode() : 0; - result = 31 * result + ( refEntities1 != null ? refEntities1.hashCode() : 0 ); - result = 31 * result + ( refEntities2 != null ? refEntities2.hashCode() : 0 ); + result = 31 * result + (refEntities1 != null ? refEntities1.hashCode() : 0); + result = 31 * result + (refEntities2 != null ? refEntities2.hashCode() : 0); return result; } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/MultipleCollectionRefEntity1.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/MultipleCollectionRefEntity1.java index dcc1673874..462762552f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/MultipleCollectionRefEntity1.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/MultipleCollectionRefEntity1.java @@ -82,7 +82,7 @@ public class MultipleCollectionRefEntity1 { if ( this == o ) { return true; } - if ( ! ( o instanceof MultipleCollectionRefEntity1 ) ) { + if ( !(o instanceof MultipleCollectionRefEntity1) ) { return false; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/MultipleCollectionRefEntity2.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/MultipleCollectionRefEntity2.java index a2df6456b7..a9c7dc283e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/MultipleCollectionRefEntity2.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/MultipleCollectionRefEntity2.java @@ -82,7 +82,7 @@ public class MultipleCollectionRefEntity2 { if ( this == o ) { return true; } - if ( ! ( o instanceof MultipleCollectionRefEntity2 ) ) { + if ( !(o instanceof MultipleCollectionRefEntity2) ) { return false; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/StringListEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/StringListEntity.java index de0301f099..7fb7669c26 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/StringListEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/StringListEntity.java @@ -22,12 +22,13 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.collection; -import java.util.ArrayList; -import java.util.List; + import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import java.util.ArrayList; +import java.util.List; import org.hibernate.annotations.IndexColumn; import org.hibernate.envers.Audited; @@ -37,51 +38,57 @@ import org.hibernate.envers.Audited; */ @Entity public class StringListEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - @ElementCollection - @IndexColumn(name = "list_index") - private List strings; + @Audited + @ElementCollection + @IndexColumn(name = "list_index") + private List strings; - public StringListEntity() { - strings = new ArrayList(); - } + public StringListEntity() { + strings = new ArrayList(); + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public List getStrings() { - return strings; - } + public List getStrings() { + return strings; + } - public void setStrings(List strings) { - this.strings = strings; - } + public void setStrings(List strings) { + this.strings = strings; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof StringListEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof StringListEntity) ) { + return false; + } - StringListEntity that = (StringListEntity) o; + StringListEntity that = (StringListEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - return (id != null ? id.hashCode() : 0); - } + public int hashCode() { + return (id != null ? id.hashCode() : 0); + } - public String toString() { - return "SLE(id = " + id + ", strings = " + strings + ")"; - } + public String toString() { + return "SLE(id = " + id + ", strings = " + strings + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/StringMapEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/StringMapEntity.java index 5dd510d50a..717cf13472 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/StringMapEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/StringMapEntity.java @@ -22,13 +22,14 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.collection; -import java.util.HashMap; -import java.util.Map; + import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.MapKeyColumn; +import java.util.HashMap; +import java.util.Map; import org.hibernate.envers.Audited; @@ -37,51 +38,57 @@ import org.hibernate.envers.Audited; */ @Entity public class StringMapEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - @ElementCollection - @MapKeyColumn(nullable=false) - private Map strings; + @Audited + @ElementCollection + @MapKeyColumn(nullable = false) + private Map strings; - public StringMapEntity() { - strings = new HashMap(); - } + public StringMapEntity() { + strings = new HashMap(); + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Map getStrings() { - return strings; - } + public Map getStrings() { + return strings; + } - public void setStrings(Map strings) { - this.strings = strings; - } + public void setStrings(Map strings) { + this.strings = strings; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof StringMapEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof StringMapEntity) ) { + return false; + } - StringMapEntity that = (StringMapEntity) o; + StringMapEntity that = (StringMapEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - return (id != null ? id.hashCode() : 0); - } + public int hashCode() { + return (id != null ? id.hashCode() : 0); + } - public String toString() { - return "SME(id = " + id + ", strings = " + strings + ")"; - } + public String toString() { + return "SME(id = " + id + ", strings = " + strings + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/StringSetEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/StringSetEntity.java index 2a8e75391b..20c3695a25 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/StringSetEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/collection/StringSetEntity.java @@ -22,12 +22,13 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.collection; -import java.util.HashSet; -import java.util.Set; + import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import java.util.HashSet; +import java.util.Set; import org.hibernate.envers.Audited; @@ -36,50 +37,56 @@ import org.hibernate.envers.Audited; */ @Entity public class StringSetEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - @ElementCollection - private Set strings; + @Audited + @ElementCollection + private Set strings; - public StringSetEntity() { - strings = new HashSet(); - } + public StringSetEntity() { + strings = new HashSet(); + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Set getStrings() { - return strings; - } + public Set getStrings() { + return strings; + } - public void setStrings(Set strings) { - this.strings = strings; - } + public void setStrings(Set strings) { + this.strings = strings; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof StringSetEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof StringSetEntity) ) { + return false; + } - StringSetEntity that = (StringSetEntity) o; + StringSetEntity that = (StringSetEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - return (id != null ? id.hashCode() : 0); - } + public int hashCode() { + return (id != null ? id.hashCode() : 0); + } - public String toString() { - return "SSE(id = " + id + ", strings = " + strings + ")"; - } + public String toString() { + return "SSE(id = " + id + ", strings = " + strings + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/Component1.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/Component1.java index dbbd7cd8cd..5019b94186 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/Component1.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/Component1.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.components; + import javax.persistence.Embeddable; /** @@ -29,54 +30,62 @@ import javax.persistence.Embeddable; */ @Embeddable public class Component1 { - private String str1; + private String str1; - private String str2; + private String str2; - public Component1(String str1, String str2) { - this.str1 = str1; - this.str2 = str2; - } + public Component1(String str1, String str2) { + this.str1 = str1; + this.str2 = str2; + } - public Component1() { - } + public Component1() { + } - public String getStr2() { - return str2; - } + public String getStr2() { + return str2; + } - public void setStr2(String str2) { - this.str2 = str2; - } + public void setStr2(String str2) { + this.str2 = str2; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Component1)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Component1) ) { + return false; + } - Component1 that = (Component1) o; + Component1 that = (Component1) o; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; - if (str2 != null ? !str2.equals(that.str2) : that.str2 != null) return false; + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } + if ( str2 != null ? !str2.equals( that.str2 ) : that.str2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (str1 != null ? str1.hashCode() : 0); - result = 31 * result + (str2 != null ? str2.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (str1 != null ? str1.hashCode() : 0); + result = 31 * result + (str2 != null ? str2.hashCode() : 0); + return result; + } - public String toString() { - return "Comp1(str1 = " + str1 + ", " + str2 + ")"; - } + public String toString() { + return "Comp1(str1 = " + str1 + ", " + str2 + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/Component2.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/Component2.java index b0dbf7b22b..72287abb86 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/Component2.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/Component2.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.components; + import javax.persistence.Embeddable; /** @@ -29,54 +30,62 @@ import javax.persistence.Embeddable; */ @Embeddable public class Component2 { - private String str5; + private String str5; - private String str6; + private String str6; - public Component2(String str5, String str6) { - this.str5 = str5; - this.str6 = str6; - } + public Component2(String str5, String str6) { + this.str5 = str5; + this.str6 = str6; + } - public Component2() { - } + public Component2() { + } - public String getStr5() { - return str5; - } + public String getStr5() { + return str5; + } - public void setStr5(String str5) { - this.str5 = str5; - } + public void setStr5(String str5) { + this.str5 = str5; + } - public String getStr6() { - return str6; - } + public String getStr6() { + return str6; + } - public void setStr6(String str6) { - this.str6 = str6; - } + public void setStr6(String str6) { + this.str6 = str6; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Component2)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Component2) ) { + return false; + } - Component2 that = (Component2) o; + Component2 that = (Component2) o; - if (str5 != null ? !str5.equals(that.str5) : that.str5 != null) return false; - if (str6 != null ? !str6.equals(that.str6) : that.str6 != null) return false; + if ( str5 != null ? !str5.equals( that.str5 ) : that.str5 != null ) { + return false; + } + if ( str6 != null ? !str6.equals( that.str6 ) : that.str6 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (str5 != null ? str5.hashCode() : 0); - result = 31 * result + (str6 != null ? str6.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (str5 != null ? str5.hashCode() : 0); + result = 31 * result + (str6 != null ? str6.hashCode() : 0); + return result; + } - public String toString() { - return "Comp2(str1 = " + str5 + ", " + str6 + ")"; - } + public String toString() { + return "Comp2(str1 = " + str5 + ", " + str6 + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/Component3.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/Component3.java index ac6f956b8c..f23351a94b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/Component3.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/Component3.java @@ -43,18 +43,19 @@ public class Component3 { private String str1; @AttributeOverrides({ - @AttributeOverride(name = "key", column = @Column(name = "audComp_key")), - @AttributeOverride(name = "value", column = @Column(name = "audComp_value")), - @AttributeOverride(name = "description", column = @Column(name = "audComp_description")) - }) + @AttributeOverride(name = "key", column = @Column(name = "audComp_key")), + @AttributeOverride(name = "value", column = @Column(name = "audComp_value")), + @AttributeOverride(name = "description", column = @Column(name = "audComp_description")) + }) private Component4 auditedComponent; @NotAudited @AttributeOverrides({ - @AttributeOverride(name = "key", column = @Column(name = "notAudComp_key")), - @AttributeOverride(name = "value", column = @Column(name = "notAudComp_value")), - @AttributeOverride(name = "description", column = @Column(name = "notAudComp_description")) - }) + @AttributeOverride(name = "key", column = @Column(name = "notAudComp_key")), + @AttributeOverride(name = "value", column = @Column(name = "notAudComp_value")), + @AttributeOverride(name = "description", + column = @Column(name = "notAudComp_description")) + }) private Component4 nonAuditedComponent; public Component3() { @@ -94,20 +95,30 @@ public class Component3 { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ( ( auditedComponent == null ) ? 0 : auditedComponent.hashCode() ); - result = prime * result + ( ( str1 == null ) ? 0 : str1.hashCode() ); + result = prime * result + ((auditedComponent == null) ? 0 : auditedComponent.hashCode()); + result = prime * result + ((str1 == null) ? 0 : str1.hashCode()); return result; } @Override public boolean equals(Object obj) { - if ( this == obj ) return true; - if ( !( obj instanceof Component3 ) ) return false; + if ( this == obj ) { + return true; + } + if ( !(obj instanceof Component3) ) { + return false; + } Component3 other = (Component3) obj; - if ( auditedComponent != null ? !auditedComponent.equals( other.auditedComponent ) : other.auditedComponent != null ) return false; - if ( str1 != null ? !str1.equals( other.str1 ) : other.str1 != null ) return false; + if ( auditedComponent != null ? + !auditedComponent.equals( other.auditedComponent ) : + other.auditedComponent != null ) { + return false; + } + if ( str1 != null ? !str1.equals( other.str1 ) : other.str1 != null ) { + return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/Component4.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/Component4.java index 20924c577d..e18bc7e329 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/Component4.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/Component4.java @@ -77,22 +77,32 @@ public class Component4 { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ( ( description == null ) ? 0 : description.hashCode() ); - result = prime * result + ( ( key == null ) ? 0 : key.hashCode() ); - result = prime * result + ( ( value == null ) ? 0 : value.hashCode() ); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((key == null) ? 0 : key.hashCode()); + result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { - if ( this == obj ) return true; - if ( !( obj instanceof Component4 ) ) return false; + if ( this == obj ) { + return true; + } + if ( !(obj instanceof Component4) ) { + return false; + } Component4 other = (Component4) obj; - if ( description != null ? !description.equals( other.description ) : other.description != null ) return false; - if ( key != null ? !key.equals( other.key ) : other.key != null ) return false; - if ( value != null ? !value.equals( other.value ) : other.value != null ) return false; + if ( description != null ? !description.equals( other.description ) : other.description != null ) { + return false; + } + if ( key != null ? !key.equals( other.key ) : other.key != null ) { + return false; + } + if ( value != null ? !value.equals( other.value ) : other.value != null ) { + return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/ComponentSetTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/ComponentSetTestEntity.java index e38661ad7b..a9f0e7d634 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/ComponentSetTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/ComponentSetTestEntity.java @@ -22,12 +22,13 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.components; -import java.util.HashSet; -import java.util.Set; + import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import java.util.HashSet; +import java.util.Set; import org.hibernate.envers.Audited; @@ -37,13 +38,13 @@ import org.hibernate.envers.Audited; @Entity @Audited public class ComponentSetTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Embedded - @Audited - private Set comps = new HashSet(); + @Embedded + @Audited + private Set comps = new HashSet(); public ComponentSetTestEntity() { } @@ -53,12 +54,12 @@ public class ComponentSetTestEntity { } public Integer getId() { - return id; - } + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } public Set getComps() { return comps; @@ -70,13 +71,21 @@ public class ComponentSetTestEntity { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ComponentSetTestEntity)) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof ComponentSetTestEntity) ) { + return false; + } ComponentSetTestEntity that = (ComponentSetTestEntity) o; - if (comps != null ? !comps.equals(that.comps) : that.comps != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( comps != null ? !comps.equals( that.comps ) : that.comps != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/ComponentTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/ComponentTestEntity.java index f27640ae0d..56b79c1104 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/ComponentTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/ComponentTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.components; + import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -36,77 +37,87 @@ import org.hibernate.envers.Audited; @Entity @Table(name = "CompTest") public class ComponentTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Embedded - @Audited - private Component1 comp1; + @Embedded + @Audited + private Component1 comp1; - @Embedded - private Component2 comp2; + @Embedded + private Component2 comp2; - public ComponentTestEntity() { - } + public ComponentTestEntity() { + } - public ComponentTestEntity(Integer id, Component1 comp1, Component2 comp2) { - this.id = id; - this.comp1 = comp1; - this.comp2 = comp2; - } + public ComponentTestEntity(Integer id, Component1 comp1, Component2 comp2) { + this.id = id; + this.comp1 = comp1; + this.comp2 = comp2; + } - public ComponentTestEntity(Component1 comp1, Component2 comp2) { - this.comp1 = comp1; - this.comp2 = comp2; - } + public ComponentTestEntity(Component1 comp1, Component2 comp2) { + this.comp1 = comp1; + this.comp2 = comp2; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Component1 getComp1() { - return comp1; - } + public Component1 getComp1() { + return comp1; + } - public void setComp1(Component1 comp1) { - this.comp1 = comp1; - } + public void setComp1(Component1 comp1) { + this.comp1 = comp1; + } - public Component2 getComp2() { - return comp2; - } + public Component2 getComp2() { + return comp2; + } - public void setComp2(Component2 comp2) { - this.comp2 = comp2; - } + public void setComp2(Component2 comp2) { + this.comp2 = comp2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ComponentTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ComponentTestEntity) ) { + return false; + } - ComponentTestEntity that = (ComponentTestEntity) o; + ComponentTestEntity that = (ComponentTestEntity) o; - if (comp1 != null ? !comp1.equals(that.comp1) : that.comp1 != null) return false; - if (comp2 != null ? !comp2.equals(that.comp2) : that.comp2 != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( comp1 != null ? !comp1.equals( that.comp1 ) : that.comp1 != null ) { + return false; + } + if ( comp2 != null ? !comp2.equals( that.comp2 ) : that.comp2 != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (comp1 != null ? comp1.hashCode() : 0); - result = 31 * result + (comp2 != null ? comp2.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (comp1 != null ? comp1.hashCode() : 0); + result = 31 * result + (comp2 != null ? comp2.hashCode() : 0); + return result; + } - public String toString() { - return "CTE(id = " + id + ", comp1 = " + comp1 + ", comp2 = " + comp2 + ")"; - } + public String toString() { + return "CTE(id = " + id + ", comp1 = " + comp1 + ", comp2 = " + comp2 + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/DefaultValueComponent1.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/DefaultValueComponent1.java index 15a63e6342..753f04dfce 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/DefaultValueComponent1.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/DefaultValueComponent1.java @@ -1,10 +1,9 @@ package org.hibernate.envers.test.entities.components; + import javax.persistence.Embedded; /** - * * @author Erik-Berndt Scheper - * */ public class DefaultValueComponent1 { @@ -13,11 +12,12 @@ public class DefaultValueComponent1 { @Embedded private DefaultValueComponent2 comp2 = new DefaultValueComponent2(); - public static final DefaultValueComponent1 of(String str1, + public static final DefaultValueComponent1 of( + String str1, DefaultValueComponent2 comp2) { DefaultValueComponent1 instance = new DefaultValueComponent1(); - instance.setStr1(str1); - instance.setComp2(comp2); + instance.setStr1( str1 ); + instance.setComp2( comp2 ); return instance; } @@ -38,17 +38,21 @@ public class DefaultValueComponent1 { } public boolean equals(Object o) { - if (this == o) + if ( this == o ) { return true; - if (!(o instanceof DefaultValueComponent1)) + } + if ( !(o instanceof DefaultValueComponent1) ) { return false; + } DefaultValueComponent1 that = (DefaultValueComponent1) o; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { return false; - if (comp2 != null ? !comp2.equals(that.comp2) : that.comp2 != null) + } + if ( comp2 != null ? !comp2.equals( that.comp2 ) : that.comp2 != null ) { return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/DefaultValueComponent2.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/DefaultValueComponent2.java index 3418c4e620..d84b532043 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/DefaultValueComponent2.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/DefaultValueComponent2.java @@ -2,9 +2,7 @@ package org.hibernate.envers.test.entities.components; /** - * * @author Erik-Berndt Scheper - * */ public class DefaultValueComponent2 { @@ -14,8 +12,8 @@ public class DefaultValueComponent2 { public static final DefaultValueComponent2 of(String str1, String str2) { DefaultValueComponent2 instance = new DefaultValueComponent2(); - instance.setStr1(str1); - instance.setStr2(str2); + instance.setStr1( str1 ); + instance.setStr2( str2 ); return instance; } @@ -36,17 +34,21 @@ public class DefaultValueComponent2 { } public boolean equals(Object o) { - if (this == o) + if ( this == o ) { return true; - if (!(o instanceof DefaultValueComponent2)) + } + if ( !(o instanceof DefaultValueComponent2) ) { return false; + } DefaultValueComponent2 that = (DefaultValueComponent2) o; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { return false; - if (str2 != null ? !str2.equals(that.str2) : that.str2 != null) + } + if ( str2 != null ? !str2.equals( that.str2 ) : that.str2 != null ) { return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/DefaultValueComponentTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/DefaultValueComponentTestEntity.java index d6afac3556..4df4c6b4d2 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/DefaultValueComponentTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/DefaultValueComponentTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.components; + import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; @@ -46,7 +47,7 @@ public class DefaultValueComponentTestEntity { @Embedded @Audited - @AttributeOverrides( { @AttributeOverride(name = "comp2.str1", column = @Column(name = "COMP2_STR1")) }) + @AttributeOverrides({@AttributeOverride(name = "comp2.str1", column = @Column(name = "COMP2_STR1"))}) private DefaultValueComponent1 comp1 = null; public DefaultValueComponentTestEntity() { @@ -55,15 +56,16 @@ public class DefaultValueComponentTestEntity { public static DefaultValueComponentTestEntity of( DefaultValueComponent1 comp1) { DefaultValueComponentTestEntity instance = new DefaultValueComponentTestEntity(); - instance.setComp1(comp1); + instance.setComp1( comp1 ); return instance; } - public static DefaultValueComponentTestEntity of(Integer id, + public static DefaultValueComponentTestEntity of( + Integer id, DefaultValueComponent1 comp1) { DefaultValueComponentTestEntity instance = new DefaultValueComponentTestEntity(); - instance.setId(id); - instance.setComp1(comp1); + instance.setId( id ); + instance.setComp1( comp1 ); return instance; } @@ -84,17 +86,21 @@ public class DefaultValueComponentTestEntity { } public boolean equals(Object o) { - if (this == o) + if ( this == o ) { return true; - if (!(o instanceof DefaultValueComponentTestEntity)) + } + if ( !(o instanceof DefaultValueComponentTestEntity) ) { return false; + } DefaultValueComponentTestEntity that = (DefaultValueComponentTestEntity) o; - if (comp1 != null ? !comp1.equals(that.comp1) : that.comp1 != null) + if ( comp1 != null ? !comp1.equals( that.comp1 ) : that.comp1 != null ) { return false; - if (id != null ? !id.equals(that.id) : that.id != null) + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/UniquePropsEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/UniquePropsEntity.java index 7540dd0a09..afea99ee51 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/UniquePropsEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/UniquePropsEntity.java @@ -9,66 +9,76 @@ import org.hibernate.envers.Audited; */ @Audited public class UniquePropsEntity implements Serializable { - private Long id; - private String data1; - private String data2; + private Long id; + private String data1; + private String data2; - public UniquePropsEntity() { - } + public UniquePropsEntity() { + } - public UniquePropsEntity(Long id, String data1, String data2) { - this.id = id; - this.data1 = data1; - this.data2 = data2; - } + public UniquePropsEntity(Long id, String data1, String data2) { + this.id = id; + this.data1 = data1; + this.data2 = data2; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } - UniquePropsEntity that = (UniquePropsEntity) o; + UniquePropsEntity that = (UniquePropsEntity) o; - if (data1 != null ? !data1.equals(that.data1) : that.data1 != null) return false; - if (data2 != null ? !data2.equals(that.data2) : that.data2 != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data1 != null ? !data1.equals( that.data1 ) : that.data1 != null ) { + return false; + } + if ( data2 != null ? !data2.equals( that.data2 ) : that.data2 != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (data1 != null ? data1.hashCode() : 0); - result = 31 * result + (data2 != null ? data2.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (data1 != null ? data1.hashCode() : 0); + result = 31 * result + (data2 != null ? data2.hashCode() : 0); + return result; + } - public String toString() { - return "UniquePropsEntity(id = " + id + ", data1 = " + data1 + ", data2 = " + data2 + ")"; - } + public String toString() { + return "UniquePropsEntity(id = " + id + ", data1 = " + data1 + ", data2 = " + data2 + ")"; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getData1() { - return data1; - } + public String getData1() { + return data1; + } - public void setData1(String data1) { - this.data1 = data1; - } + public void setData1(String data1) { + this.data1 = data1; + } - public String getData2() { - return data2; - } + public String getData2() { + return data2; + } - public void setData2(String data2) { - this.data2 = data2; - } + public void setData2(String data2) { + this.data2 = data2; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/UniquePropsNotAuditedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/UniquePropsNotAuditedEntity.java index cb034843de..8cf82e3647 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/UniquePropsNotAuditedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/UniquePropsNotAuditedEntity.java @@ -8,67 +8,77 @@ import org.hibernate.envers.NotAudited; */ @Audited public class UniquePropsNotAuditedEntity { - private Long id; - private String data1; - private String data2; + private Long id; + private String data1; + private String data2; - public UniquePropsNotAuditedEntity() { - } + public UniquePropsNotAuditedEntity() { + } - public UniquePropsNotAuditedEntity(Long id, String data1, String data2) { - this.id = id; - this.data1 = data1; - this.data2 = data2; - } + public UniquePropsNotAuditedEntity(Long id, String data1, String data2) { + this.id = id; + this.data1 = data1; + this.data2 = data2; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } - UniquePropsNotAuditedEntity that = (UniquePropsNotAuditedEntity) o; + UniquePropsNotAuditedEntity that = (UniquePropsNotAuditedEntity) o; - if (data1 != null ? !data1.equals(that.data1) : that.data1 != null) return false; - if (data2 != null ? !data2.equals(that.data2) : that.data2 != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data1 != null ? !data1.equals( that.data1 ) : that.data1 != null ) { + return false; + } + if ( data2 != null ? !data2.equals( that.data2 ) : that.data2 != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (data1 != null ? data1.hashCode() : 0); - result = 31 * result + (data2 != null ? data2.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (data1 != null ? data1.hashCode() : 0); + result = 31 * result + (data2 != null ? data2.hashCode() : 0); + return result; + } - public String toString() { - return "UniquePropsNotAuditedEntity(id = " + id + ", data1 = " + data1 + ", data2 = " + data2 + ")"; - } + public String toString() { + return "UniquePropsNotAuditedEntity(id = " + id + ", data1 = " + data1 + ", data2 = " + data2 + ")"; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getData1() { - return data1; - } + public String getData1() { + return data1; + } - public void setData1(String data1) { - this.data1 = data1; - } + public void setData1(String data1) { + this.data1 = data1; + } - @NotAudited - public String getData2() { - return data2; - } + @NotAudited + public String getData2() { + return data2; + } - public void setData2(String data2) { - this.data2 = data2; - } + public void setData2(String data2) { + this.data2 = data2; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/ManyToOneComponent.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/ManyToOneComponent.java index 2dd415791f..f3d9d1c8ad 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/ManyToOneComponent.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/ManyToOneComponent.java @@ -36,25 +36,25 @@ import org.hibernate.envers.test.entities.StrTestEntity; @Table(name = "ManyToOneCompEmb") public class ManyToOneComponent { @ManyToOne - private StrTestEntity entity; + private StrTestEntity entity; - private String data; + private String data; public ManyToOneComponent(StrTestEntity entity, String data) { - this.entity = entity; - this.data = data; - } + this.entity = entity; + this.data = data; + } - public ManyToOneComponent() { - } + public ManyToOneComponent() { + } public String getData() { - return data; - } + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } public StrTestEntity getEntity() { return entity; @@ -66,13 +66,21 @@ public class ManyToOneComponent { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } ManyToOneComponent that = (ManyToOneComponent) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (entity != null ? !entity.equals(that.entity) : that.entity != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( entity != null ? !entity.equals( that.entity ) : that.entity != null ) { + return false; + } return true; } @@ -85,6 +93,6 @@ public class ManyToOneComponent { } public String toString() { - return "ManyToOneComponent(str1 = " + data + ")"; - } + return "ManyToOneComponent(str1 = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/ManyToOneComponentTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/ManyToOneComponentTestEntity.java index f5bb47b34c..a0bf0ebf99 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/ManyToOneComponentTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/ManyToOneComponentTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.components.relations; + import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -36,51 +37,59 @@ import org.hibernate.envers.Audited; @Entity @Table(name = "ManyToOneCompEnt") public class ManyToOneComponentTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Embedded - @Audited - private ManyToOneComponent comp1; + @Embedded + @Audited + private ManyToOneComponent comp1; - public ManyToOneComponentTestEntity() { - } + public ManyToOneComponentTestEntity() { + } - public ManyToOneComponentTestEntity(Integer id, ManyToOneComponent comp1) { - this.id = id; - this.comp1 = comp1; - } + public ManyToOneComponentTestEntity(Integer id, ManyToOneComponent comp1) { + this.id = id; + this.comp1 = comp1; + } - public ManyToOneComponentTestEntity(ManyToOneComponent comp1) { - this.comp1 = comp1; - } + public ManyToOneComponentTestEntity(ManyToOneComponent comp1) { + this.comp1 = comp1; + } public Integer getId() { - return id; - } + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public ManyToOneComponent getComp1() { - return comp1; - } + public ManyToOneComponent getComp1() { + return comp1; + } - public void setComp1(ManyToOneComponent comp1) { - this.comp1 = comp1; - } + public void setComp1(ManyToOneComponent comp1) { + this.comp1 = comp1; + } @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } ManyToOneComponentTestEntity that = (ManyToOneComponentTestEntity) o; - if (comp1 != null ? !comp1.equals(that.comp1) : that.comp1 != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( comp1 != null ? !comp1.equals( that.comp1 ) : that.comp1 != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } return true; } @@ -93,6 +102,6 @@ public class ManyToOneComponentTestEntity { } public String toString() { - return "MTOCTE(id = " + id + ", comp1 = " + comp1 + ")"; - } + return "MTOCTE(id = " + id + ", comp1 = " + comp1 + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/ManyToOneEagerComponent.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/ManyToOneEagerComponent.java index 9de66b66ca..490ef371a5 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/ManyToOneEagerComponent.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/ManyToOneEagerComponent.java @@ -70,13 +70,21 @@ public class ManyToOneEagerComponent { @Override public boolean equals(Object o) { - if ( this == o ) return true; - if ( !( o instanceof ManyToOneEagerComponent ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof ManyToOneEagerComponent) ) { + return false; + } ManyToOneEagerComponent that = (ManyToOneEagerComponent) o; - if ( data != null ? !data.equals( that.data ) : that.data != null ) return false; - if ( entity != null ? !entity.equals( that.entity ) : that.entity != null ) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( entity != null ? !entity.equals( that.entity ) : that.entity != null ) { + return false; + } return true; } @@ -84,7 +92,7 @@ public class ManyToOneEagerComponent { @Override public int hashCode() { int result = entity != null ? entity.hashCode() : 0; - result = 31 * result + ( data != null ? data.hashCode() : 0 ); + result = 31 * result + (data != null ? data.hashCode() : 0); return result; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/NotAuditedManyToOneComponent.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/NotAuditedManyToOneComponent.java index d98be4cd53..267513638a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/NotAuditedManyToOneComponent.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/NotAuditedManyToOneComponent.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.components.relations; + import javax.persistence.Embeddable; import javax.persistence.ManyToOne; import javax.persistence.Table; @@ -37,25 +38,25 @@ import org.hibernate.envers.test.entities.UnversionedStrTestEntity; public class NotAuditedManyToOneComponent { @ManyToOne @NotAudited - private UnversionedStrTestEntity entity; + private UnversionedStrTestEntity entity; - private String data; + private String data; public NotAuditedManyToOneComponent(UnversionedStrTestEntity entity, String data) { - this.entity = entity; - this.data = data; - } + this.entity = entity; + this.data = data; + } - public NotAuditedManyToOneComponent() { - } + public NotAuditedManyToOneComponent() { + } public String getData() { - return data; - } + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } public UnversionedStrTestEntity getEntity() { return entity; @@ -67,13 +68,21 @@ public class NotAuditedManyToOneComponent { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } NotAuditedManyToOneComponent that = (NotAuditedManyToOneComponent) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (entity != null ? !entity.equals(that.entity) : that.entity != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( entity != null ? !entity.equals( that.entity ) : that.entity != null ) { + return false; + } return true; } @@ -86,6 +95,6 @@ public class NotAuditedManyToOneComponent { } public String toString() { - return "NotAuditedManyToOneComponent(str1 = " + data + ")"; - } + return "NotAuditedManyToOneComponent(str1 = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/NotAuditedManyToOneComponentTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/NotAuditedManyToOneComponentTestEntity.java index 335802ae9a..7cf7d7191f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/NotAuditedManyToOneComponentTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/NotAuditedManyToOneComponentTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.components.relations; + import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -36,51 +37,59 @@ import org.hibernate.envers.Audited; @Entity @Table(name = "NotAudM2OCompEnt") public class NotAuditedManyToOneComponentTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Embedded - @Audited - private NotAuditedManyToOneComponent comp1; + @Embedded + @Audited + private NotAuditedManyToOneComponent comp1; - public NotAuditedManyToOneComponentTestEntity() { - } + public NotAuditedManyToOneComponentTestEntity() { + } - public NotAuditedManyToOneComponentTestEntity(Integer id, NotAuditedManyToOneComponent comp1) { - this.id = id; - this.comp1 = comp1; - } + public NotAuditedManyToOneComponentTestEntity(Integer id, NotAuditedManyToOneComponent comp1) { + this.id = id; + this.comp1 = comp1; + } - public NotAuditedManyToOneComponentTestEntity(NotAuditedManyToOneComponent comp1) { - this.comp1 = comp1; - } + public NotAuditedManyToOneComponentTestEntity(NotAuditedManyToOneComponent comp1) { + this.comp1 = comp1; + } public Integer getId() { - return id; - } + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public NotAuditedManyToOneComponent getComp1() { - return comp1; - } + public NotAuditedManyToOneComponent getComp1() { + return comp1; + } - public void setComp1(NotAuditedManyToOneComponent comp1) { - this.comp1 = comp1; - } + public void setComp1(NotAuditedManyToOneComponent comp1) { + this.comp1 = comp1; + } @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } NotAuditedManyToOneComponentTestEntity that = (NotAuditedManyToOneComponentTestEntity) o; - if (comp1 != null ? !comp1.equals(that.comp1) : that.comp1 != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( comp1 != null ? !comp1.equals( that.comp1 ) : that.comp1 != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } return true; } @@ -93,6 +102,6 @@ public class NotAuditedManyToOneComponentTestEntity { } public String toString() { - return "NAMTOCTE(id = " + id + ", comp1 = " + comp1 + ")"; - } + return "NAMTOCTE(id = " + id + ", comp1 = " + comp1 + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/OneToManyComponent.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/OneToManyComponent.java index 7be3aa3123..ffbc740e91 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/OneToManyComponent.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/OneToManyComponent.java @@ -22,10 +22,11 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.components.relations; -import java.util.HashSet; -import java.util.Set; + import javax.persistence.Embeddable; import javax.persistence.OneToMany; +import java.util.HashSet; +import java.util.Set; import org.hibernate.envers.test.entities.StrTestEntity; @@ -35,24 +36,24 @@ import org.hibernate.envers.test.entities.StrTestEntity; @Embeddable public class OneToManyComponent { @OneToMany - private Set entities = new HashSet(); + private Set entities = new HashSet(); - private String data; + private String data; public OneToManyComponent(String data) { - this.data = data; - } + this.data = data; + } - public OneToManyComponent() { - } + public OneToManyComponent() { + } public String getData() { - return data; - } + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } public Set getEntities() { return entities; @@ -64,13 +65,21 @@ public class OneToManyComponent { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } OneToManyComponent that = (OneToManyComponent) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (entities != null ? !entities.equals(that.entities) : that.entities != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( entities != null ? !entities.equals( that.entities ) : that.entities != null ) { + return false; + } return true; } @@ -83,6 +92,6 @@ public class OneToManyComponent { } public String toString() { - return "OneToManyComponent(data = " + data + ")"; - } + return "OneToManyComponent(data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/OneToManyComponentTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/OneToManyComponentTestEntity.java index 6669c97a24..e3c4e780d4 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/OneToManyComponentTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/components/relations/OneToManyComponentTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.components.relations; + import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -36,51 +37,59 @@ import org.hibernate.envers.Audited; @Entity @Table(name = "OneToManyComp") public class OneToManyComponentTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Embedded - @Audited - private OneToManyComponent comp1; + @Embedded + @Audited + private OneToManyComponent comp1; - public OneToManyComponentTestEntity() { - } + public OneToManyComponentTestEntity() { + } - public OneToManyComponentTestEntity(Integer id, OneToManyComponent comp1) { - this.id = id; - this.comp1 = comp1; - } + public OneToManyComponentTestEntity(Integer id, OneToManyComponent comp1) { + this.id = id; + this.comp1 = comp1; + } - public OneToManyComponentTestEntity(OneToManyComponent comp1) { - this.comp1 = comp1; - } + public OneToManyComponentTestEntity(OneToManyComponent comp1) { + this.comp1 = comp1; + } public Integer getId() { - return id; - } + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public OneToManyComponent getComp1() { - return comp1; - } + public OneToManyComponent getComp1() { + return comp1; + } - public void setComp1(OneToManyComponent comp1) { - this.comp1 = comp1; - } + public void setComp1(OneToManyComponent comp1) { + this.comp1 = comp1; + } @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } OneToManyComponentTestEntity that = (OneToManyComponentTestEntity) o; - if (comp1 != null ? !comp1.equals(that.comp1) : that.comp1 != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( comp1 != null ? !comp1.equals( that.comp1 ) : that.comp1 != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } return true; } @@ -93,6 +102,6 @@ public class OneToManyComponentTestEntity { } public String toString() { - return "OTMCTE(id = " + id + ", comp1 = " + comp1 + ")"; - } + return "OTMCTE(id = " + id + ", comp1 = " + comp1 + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/Component.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/Component.java index 3ac71e0430..c839fc5daa 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/Component.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/Component.java @@ -22,55 +22,64 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.customtype; + import java.io.Serializable; /** * @author Adam Warski (adam at warski dot org) */ public class Component implements Serializable { - private String prop1; - private int prop2; + private String prop1; + private int prop2; - public Component(String prop1, int prop2) { - this.prop1 = prop1; - this.prop2 = prop2; - } + public Component(String prop1, int prop2) { + this.prop1 = prop1; + this.prop2 = prop2; + } - public Component() { - } + public Component() { + } - public String getProp1() { - return prop1; - } + public String getProp1() { + return prop1; + } - public void setProp1(String prop1) { - this.prop1 = prop1; - } + public void setProp1(String prop1) { + this.prop1 = prop1; + } - public int getProp2() { - return prop2; - } + public int getProp2() { + return prop2; + } - public void setProp2(int prop2) { - this.prop2 = prop2; - } + public void setProp2(int prop2) { + this.prop2 = prop2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Component)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Component) ) { + return false; + } - Component that = (Component) o; + Component that = (Component) o; - if (prop2 != that.prop2) return false; - if (prop1 != null ? !prop1.equals(that.prop1) : that.prop1 != null) return false; + if ( prop2 != that.prop2 ) { + return false; + } + if ( prop1 != null ? !prop1.equals( that.prop1 ) : that.prop1 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (prop1 != null ? prop1.hashCode() : 0); - result = 31 * result + prop2; - return result; - } + public int hashCode() { + int result; + result = (prop1 != null ? prop1.hashCode() : 0); + result = 31 * result + prop2; + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/CompositeCustomTypeEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/CompositeCustomTypeEntity.java index d6b38feb38..37a6c73536 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/CompositeCustomTypeEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/CompositeCustomTypeEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.customtype; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -38,59 +39,67 @@ import org.hibernate.envers.Audited; @Entity @TypeDef(name = "comp", typeClass = CompositeTestUserType.class) public class CompositeCustomTypeEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - @Type(type = "comp") - @Columns(columns = { @Column(name = "str"), @Column(name = "num") }) - private Component component; + @Audited + @Type(type = "comp") + @Columns(columns = {@Column(name = "str"), @Column(name = "num")}) + private Component component; - public CompositeCustomTypeEntity() { - } + public CompositeCustomTypeEntity() { + } - public CompositeCustomTypeEntity(Integer id, Component component) { - this.id = id; - this.component = component; - } + public CompositeCustomTypeEntity(Integer id, Component component) { + this.id = id; + this.component = component; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Component getComponent() { - return component; - } + public Component getComponent() { + return component; + } - public void setComponent(Component component) { - this.component = component; - } + public void setComponent(Component component) { + this.component = component; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof CompositeCustomTypeEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof CompositeCustomTypeEntity) ) { + return false; + } - CompositeCustomTypeEntity that = (CompositeCustomTypeEntity) o; + CompositeCustomTypeEntity that = (CompositeCustomTypeEntity) o; - if (component != null ? !component.equals(that.component) : that.component != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( component != null ? !component.equals( that.component ) : that.component != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (component != null ? component.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (component != null ? component.hashCode() : 0); + return result; + } - public String toString() { - return "CCTE(id = " + id + ", component = " + component + ")"; - } + public String toString() { + return "CCTE(id = " + id + ", component = " + component + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/CompositeTestUserType.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/CompositeTestUserType.java index 1ff0db637c..410896771a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/CompositeTestUserType.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/CompositeTestUserType.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.customtype; + import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -39,99 +40,106 @@ import org.hibernate.usertype.CompositeUserType; * @author Adam Warski (adam at warski dot org) */ public class CompositeTestUserType implements CompositeUserType { - public String[] getPropertyNames() { - return new String[] { "prop1", "prop2" }; - } + public String[] getPropertyNames() { + return new String[] {"prop1", "prop2"}; + } - public Type[] getPropertyTypes() { - return new Type[] { StringType.INSTANCE, IntegerType.INSTANCE }; - } + public Type[] getPropertyTypes() { + return new Type[] {StringType.INSTANCE, IntegerType.INSTANCE}; + } - public Object getPropertyValue(final Object component, final int property) throws HibernateException { - Component comp = (Component) component; - if (property == 0) { - return comp.getProp1(); - } else { - return comp.getProp2(); - } - } + public Object getPropertyValue(final Object component, final int property) throws HibernateException { + Component comp = (Component) component; + if ( property == 0 ) { + return comp.getProp1(); + } + else { + return comp.getProp2(); + } + } - public void setPropertyValue(final Object component, final int property, final Object value) throws HibernateException { - Component comp = (Component) component; - if (property == 0) { - comp.setProp1((String) value); - } else { - comp.setProp2((Integer) value); - } - } + public void setPropertyValue(final Object component, final int property, final Object value) + throws HibernateException { + Component comp = (Component) component; + if ( property == 0 ) { + comp.setProp1( (String) value ); + } + else { + comp.setProp2( (Integer) value ); + } + } - public Class returnedClass() { - return Component.class; - } + public Class returnedClass() { + return Component.class; + } - public boolean equals(final Object x, final Object y) throws HibernateException { - //noinspection ObjectEquality - if (x == y) { - return true; - } + public boolean equals(final Object x, final Object y) throws HibernateException { + //noinspection ObjectEquality + if ( x == y ) { + return true; + } - if (x == null || y == null) { - return false; - } + if ( x == null || y == null ) { + return false; + } - return x.equals(y); - } + return x.equals( y ); + } - public int hashCode(final Object x) throws HibernateException { - return x.hashCode(); - } + public int hashCode(final Object x) throws HibernateException { + return x.hashCode(); + } - public Object nullSafeGet(final ResultSet rs, final String[] names, - final SessionImplementor session, - final Object owner) throws HibernateException, SQLException { - final String prop1 = rs.getString(names[0]); - if (prop1 == null) { - return null; - } - final int prop2 = rs.getInt(names[1]); - - return new Component(prop1, prop2); - } + public Object nullSafeGet( + final ResultSet rs, final String[] names, + final SessionImplementor session, + final Object owner) throws HibernateException, SQLException { + final String prop1 = rs.getString( names[0] ); + if ( prop1 == null ) { + return null; + } + final int prop2 = rs.getInt( names[1] ); - public void nullSafeSet(final PreparedStatement st, final Object value, - final int index, final SessionImplementor session) - throws HibernateException, SQLException - { - if (value == null) { - st.setNull(index, StringType.INSTANCE.sqlType()); - st.setNull(index + 1, IntegerType.INSTANCE.sqlType()); - } else { - final Component comp = (Component) value; - st.setString(index, comp.getProp1()); - st.setInt(index + 1, comp.getProp2()); - } - } + return new Component( prop1, prop2 ); + } - public Object deepCopy(final Object value) throws HibernateException { - Component comp = (Component) value; - return new Component(comp.getProp1(), comp.getProp2()); - } + public void nullSafeSet( + final PreparedStatement st, final Object value, + final int index, final SessionImplementor session) + throws HibernateException, SQLException { + if ( value == null ) { + st.setNull( index, StringType.INSTANCE.sqlType() ); + st.setNull( index + 1, IntegerType.INSTANCE.sqlType() ); + } + else { + final Component comp = (Component) value; + st.setString( index, comp.getProp1() ); + st.setInt( index + 1, comp.getProp2() ); + } + } - public boolean isMutable() { - return true; - } + public Object deepCopy(final Object value) throws HibernateException { + Component comp = (Component) value; + return new Component( comp.getProp1(), comp.getProp2() ); + } - public Serializable disassemble(final Object value, final SessionImplementor session) throws HibernateException { - return (Serializable) value; - } + public boolean isMutable() { + return true; + } - public Object assemble(final Serializable cached, final SessionImplementor session, - final Object owner) throws HibernateException { - return cached; - } + public Serializable disassemble(final Object value, final SessionImplementor session) throws HibernateException { + return (Serializable) value; + } - public Object replace(Object original, Object target, - SessionImplementor session, Object owner) throws HibernateException { - return original; - } + public Object assemble( + final Serializable cached, final SessionImplementor session, + final Object owner) throws HibernateException { + return cached; + } + + public Object replace( + Object original, Object target, + SessionImplementor session, Object owner) throws HibernateException { + return original; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/EnumTypeEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/EnumTypeEntity.java index 570a34cf85..c84c95e6b3 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/EnumTypeEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/EnumTypeEntity.java @@ -14,8 +14,9 @@ import org.hibernate.envers.Audited; @Entity @Audited public class EnumTypeEntity { - public static enum E1 { X, Y } - public static enum E2 { A, B } + public static enum E1 {X, Y} + + public static enum E2 {A, B} @Id @GeneratedValue @@ -43,14 +44,24 @@ public class EnumTypeEntity { @Override public boolean equals(Object o) { - if ( this == o ) return true; - if ( ! ( o instanceof EnumTypeEntity ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof EnumTypeEntity) ) { + return false; + } EnumTypeEntity that = (EnumTypeEntity) o; - if ( enum1 != that.enum1 ) return false; - if ( enum2 != that.enum2 ) return false; - if ( id != null ? !id.equals( that.id ) : that.id != null ) return false; + if ( enum1 != that.enum1 ) { + return false; + } + if ( enum2 != that.enum2 ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } return true; } @@ -58,8 +69,8 @@ public class EnumTypeEntity { @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; - result = 31 * result + ( enum1 != null ? enum1.hashCode() : 0 ); - result = 31 * result + ( enum2 != null ? enum2.hashCode() : 0 ); + result = 31 * result + (enum1 != null ? enum1.hashCode() : 0); + result = 31 * result + (enum2 != null ? enum2.hashCode() : 0); return result; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/ParametrizedCustomTypeEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/ParametrizedCustomTypeEntity.java index 3aa9579dcf..a0620ab1d7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/ParametrizedCustomTypeEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/ParametrizedCustomTypeEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.customtype; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -37,61 +38,69 @@ import org.hibernate.envers.Audited; */ @Entity @TypeDef(name = "param", typeClass = ParametrizedTestUserType.class, - parameters = { @Parameter(name="param1", value = "x"), @Parameter(name="param2", value = "y") }) + parameters = {@Parameter(name = "param1", value = "x"), @Parameter(name = "param2", value = "y")}) @Table(name = "ParamCustType") public class ParametrizedCustomTypeEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - @Type(type = "param") - private String str; + @Audited + @Type(type = "param") + private String str; - public ParametrizedCustomTypeEntity() { - } + public ParametrizedCustomTypeEntity() { + } - public ParametrizedCustomTypeEntity(Integer id, String str) { - this.id = id; - this.str = str; - } + public ParametrizedCustomTypeEntity(Integer id, String str) { + this.id = id; + this.str = str; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStr() { - return str; - } + public String getStr() { + return str; + } - public void setStr(String str) { - this.str = str; - } + public void setStr(String str) { + this.str = str; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ParametrizedCustomTypeEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ParametrizedCustomTypeEntity) ) { + return false; + } - ParametrizedCustomTypeEntity that = (ParametrizedCustomTypeEntity) o; + ParametrizedCustomTypeEntity that = (ParametrizedCustomTypeEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (str != null ? !str.equals(that.str) : that.str != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str != null ? !str.equals( that.str ) : that.str != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str != null ? str.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str != null ? str.hashCode() : 0); + return result; + } - public String toString() { - return "PCTE(id = " + id + ", str = " + str + ")"; - } + public String toString() { + return "PCTE(id = " + id + ", str = " + str + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/ParametrizedTestUserType.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/ParametrizedTestUserType.java index 04d108b262..89999fa8d3 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/ParametrizedTestUserType.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/ParametrizedTestUserType.java @@ -40,78 +40,80 @@ import org.hibernate.usertype.UserType; * @author Adam Warski (adam at warski dot org) */ public class ParametrizedTestUserType implements UserType, ParameterizedType { - private static final int[] TYPES = new int[] { Types.VARCHAR }; + private static final int[] TYPES = new int[] {Types.VARCHAR}; - private String param1; - private String param2; + private String param1; + private String param2; - public void setParameterValues(Properties parameters) { - param1 = parameters.getProperty("param1"); - param2 = parameters.getProperty("param2"); - } + public void setParameterValues(Properties parameters) { + param1 = parameters.getProperty( "param1" ); + param2 = parameters.getProperty( "param2" ); + } - public Class returnedClass() { - return String.class; - } + public Class returnedClass() { + return String.class; + } - public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException { - return StringType.INSTANCE.nullSafeGet( rs, names[0], session ); - } + public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) + throws HibernateException, SQLException { + return StringType.INSTANCE.nullSafeGet( rs, names[0], session ); + } - public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException { - if (value != null) { - String v = (String) value; - if (!v.startsWith(param1)) { - v = param1 + v; - } - if (!v.endsWith(param2)) { - v = v + param2; - } - StringType.INSTANCE.nullSafeSet(st, v, index, session); - } + public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) + throws HibernateException, SQLException { + if ( value != null ) { + String v = (String) value; + if ( !v.startsWith( param1 ) ) { + v = param1 + v; + } + if ( !v.endsWith( param2 ) ) { + v = v + param2; + } + StringType.INSTANCE.nullSafeSet( st, v, index, session ); + } else { - StringType.INSTANCE.nullSafeSet( st, null, index, session ); - } - } + StringType.INSTANCE.nullSafeSet( st, null, index, session ); + } + } - public int[] sqlTypes() { - return TYPES; - } + public int[] sqlTypes() { + return TYPES; + } - public Object assemble(Serializable cached, Object owner) throws HibernateException { - return cached; - } + public Object assemble(Serializable cached, Object owner) throws HibernateException { + return cached; + } - public Object deepCopy(Object value) throws HibernateException { - return value; - } + public Object deepCopy(Object value) throws HibernateException { + return value; + } - public Serializable disassemble(Object value) throws HibernateException { - return (Serializable) value; - } + public Serializable disassemble(Object value) throws HibernateException { + return (Serializable) value; + } - public boolean equals(Object x, Object y) throws HibernateException { - //noinspection ObjectEquality - if (x == y) { - return true; - } + public boolean equals(Object x, Object y) throws HibernateException { + //noinspection ObjectEquality + if ( x == y ) { + return true; + } - if (x == null || y == null) { - return false; - } + if ( x == null || y == null ) { + return false; + } - return x.equals(y); - } + return x.equals( y ); + } - public int hashCode(Object x) throws HibernateException { - return x.hashCode(); - } + public int hashCode(Object x) throws HibernateException { + return x.hashCode(); + } - public boolean isMutable() { - return false; - } + public boolean isMutable() { + return false; + } - public Object replace(Object original, Object target, Object owner) throws HibernateException { - return original; - } + public Object replace(Object original, Object target, Object owner) throws HibernateException { + return original; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/UnspecifiedEnumTypeEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/UnspecifiedEnumTypeEntity.java index c0e8c95a52..04fcc5b818 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/UnspecifiedEnumTypeEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/customtype/UnspecifiedEnumTypeEntity.java @@ -9,8 +9,9 @@ import org.hibernate.envers.Audited; */ @Audited public class UnspecifiedEnumTypeEntity implements Serializable { - public static enum E1 { X, Y } - public static enum E2 { A, B } + public static enum E1 {X, Y} + + public static enum E2 {A, B} private Long id; @@ -34,14 +35,24 @@ public class UnspecifiedEnumTypeEntity implements Serializable { @Override public boolean equals(Object o) { - if ( this == o ) return true; - if ( ! ( o instanceof UnspecifiedEnumTypeEntity ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof UnspecifiedEnumTypeEntity) ) { + return false; + } UnspecifiedEnumTypeEntity that = (UnspecifiedEnumTypeEntity) o; - if ( enum1 != that.enum1 ) return false; - if ( enum2 != that.enum2 ) return false; - if ( id != null ? !id.equals( that.id ) : that.id != null ) return false; + if ( enum1 != that.enum1 ) { + return false; + } + if ( enum2 != that.enum2 ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } return true; } @@ -49,8 +60,8 @@ public class UnspecifiedEnumTypeEntity implements Serializable { @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; - result = 31 * result + ( enum1 != null ? enum1.hashCode() : 0 ); - result = 31 * result + ( enum2 != null ? enum2.hashCode() : 0 ); + result = 31 * result + (enum1 != null ? enum1.hashCode() : 0); + result = 31 * result + (enum2 != null ? enum2.hashCode() : 0); return result; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/CompositeDateIdTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/CompositeDateIdTestEntity.java index 06d3f0a0ad..7e111edaf2 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/CompositeDateIdTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/CompositeDateIdTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.ids; + import javax.persistence.EmbeddedId; import javax.persistence.Entity; @@ -32,57 +33,65 @@ import org.hibernate.envers.Audited; */ @Entity public class CompositeDateIdTestEntity { - @EmbeddedId - private DateEmbId id; + @EmbeddedId + private DateEmbId id; - @Audited - private String str1; + @Audited + private String str1; - public CompositeDateIdTestEntity() { - } + public CompositeDateIdTestEntity() { + } - public CompositeDateIdTestEntity(String str1) { - this.str1 = str1; - } + public CompositeDateIdTestEntity(String str1) { + this.str1 = str1; + } - public CompositeDateIdTestEntity(DateEmbId id, String str1) { - this.id = id; - this.str1 = str1; - } + public CompositeDateIdTestEntity(DateEmbId id, String str1) { + this.id = id; + this.str1 = str1; + } - public DateEmbId getId() { - return id; - } + public DateEmbId getId() { + return id; + } - public void setId(DateEmbId id) { - this.id = id; - } + public void setId(DateEmbId id) { + this.id = id; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } - CompositeDateIdTestEntity that = (CompositeDateIdTestEntity) o; + CompositeDateIdTestEntity that = (CompositeDateIdTestEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (str1 != null ? str1.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (str1 != null ? str1.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/CustomEnum.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/CustomEnum.java index 68e7107353..3616ea079c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/CustomEnum.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/CustomEnum.java @@ -28,14 +28,14 @@ package org.hibernate.envers.test.entities.ids; * @author Slawek Garwol (slawekgarwol at gmail dot com) */ public enum CustomEnum { - YES, - NO; + YES, + NO; - public String toYesNo() { - return this == YES ? "Y" : "N"; - } + public String toYesNo() { + return this == YES ? "Y" : "N"; + } - public static CustomEnum fromYesNo(String value) { - return "Y".equals(value) ? YES : NO; - } + public static CustomEnum fromYesNo(String value) { + return "Y".equals( value ) ? YES : NO; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/CustomEnumUserType.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/CustomEnumUserType.java index 22713d59a3..359683ea99 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/CustomEnumUserType.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/CustomEnumUserType.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.ids; + import java.io.Serializable; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -36,64 +37,67 @@ import org.hibernate.usertype.UserType; * @author Slawek Garwol (slawekgarwol at gmail dot com) */ public class CustomEnumUserType implements UserType { - private static final int[] SQL_TYPES = {Types.VARCHAR}; + private static final int[] SQL_TYPES = {Types.VARCHAR}; - public int[] sqlTypes() { - return SQL_TYPES; - } + public int[] sqlTypes() { + return SQL_TYPES; + } - public Class returnedClass() { - return CustomEnum.class; - } + public Class returnedClass() { + return CustomEnum.class; + } - public boolean equals(Object x, Object y) throws HibernateException { - if (x == y) { - return true; - } - if ((x == null) || (y == null)) { - return false; - } - return x.equals(y); - } + public boolean equals(Object x, Object y) throws HibernateException { + if ( x == y ) { + return true; + } + if ( (x == null) || (y == null) ) { + return false; + } + return x.equals( y ); + } - public int hashCode(Object x) throws HibernateException { - return (x == null) ? 0 : x.hashCode(); - } + public int hashCode(Object x) throws HibernateException { + return (x == null) ? 0 : x.hashCode(); + } - public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException { - String name = rs.getString(names[0]); - if (rs.wasNull()) { - return null; - } - return CustomEnum.fromYesNo(name); - } + public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) + throws HibernateException, SQLException { + String name = rs.getString( names[0] ); + if ( rs.wasNull() ) { + return null; + } + return CustomEnum.fromYesNo( name ); + } - public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException { - CustomEnum val = (CustomEnum) value; - if (val == null) { - st.setNull(index, Types.VARCHAR); - } else { - st.setString(index, val.toYesNo()); - } - } + public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) + throws HibernateException, SQLException { + CustomEnum val = (CustomEnum) value; + if ( val == null ) { + st.setNull( index, Types.VARCHAR ); + } + else { + st.setString( index, val.toYesNo() ); + } + } - public Object deepCopy(Object value) throws HibernateException { - return value; - } + public Object deepCopy(Object value) throws HibernateException { + return value; + } - public boolean isMutable() { - return false; - } + public boolean isMutable() { + return false; + } - public Serializable disassemble(Object value) throws HibernateException { - return (Serializable) value; - } + public Serializable disassemble(Object value) throws HibernateException { + return (Serializable) value; + } - public Object assemble(Serializable cached, Object owner) throws HibernateException { - return cached; - } + public Object assemble(Serializable cached, Object owner) throws HibernateException { + return cached; + } - public Object replace(Object original, Object target, Object owner) throws HibernateException { - return original; - } + public Object replace(Object original, Object target, Object owner) throws HibernateException { + return original; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/DateEmbId.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/DateEmbId.java index 9cbf78aa56..8c47f5420b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/DateEmbId.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/DateEmbId.java @@ -22,62 +22,71 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.ids; + +import javax.persistence.Embeddable; import java.io.Serializable; import java.util.Date; -import javax.persistence.Embeddable; /** * @author Adam Warski (adam at warski dot org) */ @Embeddable public class DateEmbId implements Serializable { - private Date x; - private Date y; + private Date x; + private Date y; - public DateEmbId() { - } + public DateEmbId() { + } - public DateEmbId(Date x, Date y) { - this.x = x; - this.y = y; - } + public DateEmbId(Date x, Date y) { + this.x = x; + this.y = y; + } - public Date getX() { - return x; - } + public Date getX() { + return x; + } - public void setX(Date x) { - this.x = x; - } + public void setX(Date x) { + this.x = x; + } - public Date getY() { - return y; - } + public Date getY() { + return y; + } - public void setY(Date y) { - this.y = y; - } + public void setY(Date y) { + this.y = y; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof DateEmbId)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof DateEmbId) ) { + return false; + } - DateEmbId embId = (DateEmbId) o; + DateEmbId embId = (DateEmbId) o; - if (x != null ? !x.equals(embId.x) : embId.x != null) return false; - if (y != null ? !y.equals(embId.y) : embId.y != null) return false; + if ( x != null ? !x.equals( embId.x ) : embId.x != null ) { + return false; + } + if ( y != null ? !y.equals( embId.y ) : embId.y != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (x != null ? x.hashCode() : 0); - result = 31 * result + (y != null ? y.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (x != null ? x.hashCode() : 0); + result = 31 * result + (y != null ? y.hashCode() : 0); + return result; + } - public String toString() { - return "DateEmbId(" + x + ", " + y + ")"; - } + public String toString() { + return "DateEmbId(" + x + ", " + y + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/DateIdTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/DateIdTestEntity.java index 5796d15957..db7e5ec4c8 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/DateIdTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/DateIdTestEntity.java @@ -22,9 +22,10 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.ids; -import java.util.Date; + import javax.persistence.Entity; import javax.persistence.Id; +import java.util.Date; import org.hibernate.envers.Audited; @@ -33,57 +34,65 @@ import org.hibernate.envers.Audited; */ @Entity public class DateIdTestEntity { - @Id - private Date id; + @Id + private Date id; - @Audited - private String str1; + @Audited + private String str1; - public DateIdTestEntity() { - } + public DateIdTestEntity() { + } - public DateIdTestEntity(String str1) { - this.str1 = str1; - } + public DateIdTestEntity(String str1) { + this.str1 = str1; + } - public DateIdTestEntity(Date id, String str1) { - this.id = id; - this.str1 = str1; - } + public DateIdTestEntity(Date id, String str1) { + this.id = id; + this.str1 = str1; + } - public Date getId() { - return id; - } + public Date getId() { + return id; + } - public void setId(Date id) { - this.id = id; - } + public void setId(Date id) { + this.id = id; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } - DateIdTestEntity that = (DateIdTestEntity) o; + DateIdTestEntity that = (DateIdTestEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (str1 != null ? str1.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (str1 != null ? str1.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/EmbId.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/EmbId.java index 86d6c8b04a..bec79425ed 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/EmbId.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/EmbId.java @@ -22,61 +22,70 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.ids; -import java.io.Serializable; + import javax.persistence.Embeddable; +import java.io.Serializable; /** * @author Adam Warski (adam at warski dot org) */ @Embeddable public class EmbId implements Serializable { - private Integer x; - private Integer y; + private Integer x; + private Integer y; - public EmbId() { - } + public EmbId() { + } - public EmbId(Integer x, Integer y) { - this.x = x; - this.y = y; - } + public EmbId(Integer x, Integer y) { + this.x = x; + this.y = y; + } - public Integer getX() { - return x; - } + public Integer getX() { + return x; + } - public void setX(Integer x) { - this.x = x; - } + public void setX(Integer x) { + this.x = x; + } - public Integer getY() { - return y; - } + public Integer getY() { + return y; + } - public void setY(Integer y) { - this.y = y; - } + public void setY(Integer y) { + this.y = y; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof EmbId)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof EmbId) ) { + return false; + } - EmbId embId = (EmbId) o; + EmbId embId = (EmbId) o; - if (x != null ? !x.equals(embId.x) : embId.x != null) return false; - if (y != null ? !y.equals(embId.y) : embId.y != null) return false; + if ( x != null ? !x.equals( embId.x ) : embId.x != null ) { + return false; + } + if ( y != null ? !y.equals( embId.y ) : embId.y != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (x != null ? x.hashCode() : 0); - result = 31 * result + (y != null ? y.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (x != null ? x.hashCode() : 0); + result = 31 * result + (y != null ? y.hashCode() : 0); + return result; + } - public String toString() { - return "EmbId(" + x + ", " + y + ")"; - } + public String toString() { + return "EmbId(" + x + ", " + y + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/EmbIdTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/EmbIdTestEntity.java index 695bcbdfb4..9632429a3a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/EmbIdTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/EmbIdTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.ids; + import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Table; @@ -34,56 +35,64 @@ import org.hibernate.envers.Audited; @Entity @Table(name = "EmbIdEnt") public class EmbIdTestEntity { - @EmbeddedId - private EmbId id; + @EmbeddedId + private EmbId id; - @Audited - private String str1; + @Audited + private String str1; - public EmbIdTestEntity() { - } + public EmbIdTestEntity() { + } - public EmbIdTestEntity(String str1) { - this.str1 = str1; - } + public EmbIdTestEntity(String str1) { + this.str1 = str1; + } - public EmbIdTestEntity(EmbId id, String str1) { - this.id = id; - this.str1 = str1; - } + public EmbIdTestEntity(EmbId id, String str1) { + this.id = id; + this.str1 = str1; + } - public EmbId getId() { - return id; - } + public EmbId getId() { + return id; + } - public void setId(EmbId id) { - this.id = id; - } + public void setId(EmbId id) { + this.id = id; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof EmbIdTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof EmbIdTestEntity) ) { + return false; + } - EmbIdTestEntity that = (EmbIdTestEntity) o; + EmbIdTestEntity that = (EmbIdTestEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str1 != null ? str1.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str1 != null ? str1.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/EmbIdWithCustomType.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/EmbIdWithCustomType.java index d815d1ce98..03efc0cdec 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/EmbIdWithCustomType.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/EmbIdWithCustomType.java @@ -22,8 +22,9 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.ids; -import java.io.Serializable; + import javax.persistence.Embeddable; +import java.io.Serializable; import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; @@ -34,53 +35,61 @@ import org.hibernate.annotations.TypeDef; @Embeddable @TypeDef(name = "customEnum", typeClass = CustomEnumUserType.class) public class EmbIdWithCustomType implements Serializable { - private Integer x; + private Integer x; - @Type(type = "customEnum") - private CustomEnum customEnum; + @Type(type = "customEnum") + private CustomEnum customEnum; - public EmbIdWithCustomType() { - } + public EmbIdWithCustomType() { + } - public EmbIdWithCustomType(Integer x, CustomEnum customEnum) { - this.x = x; - this.customEnum = customEnum; - } + public EmbIdWithCustomType(Integer x, CustomEnum customEnum) { + this.x = x; + this.customEnum = customEnum; + } - public Integer getX() { - return x; - } + public Integer getX() { + return x; + } - public void setX(Integer x) { - this.x = x; - } + public void setX(Integer x) { + this.x = x; + } - public CustomEnum getCustomEnum() { - return customEnum; - } + public CustomEnum getCustomEnum() { + return customEnum; + } - public void setCustomEnum(CustomEnum customEnum) { - this.customEnum = customEnum; - } + public void setCustomEnum(CustomEnum customEnum) { + this.customEnum = customEnum; + } - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (!(obj instanceof EmbIdWithCustomType)) return false; + @Override + public boolean equals(Object obj) { + if ( this == obj ) { + return true; + } + if ( !(obj instanceof EmbIdWithCustomType) ) { + return false; + } - EmbIdWithCustomType that = (EmbIdWithCustomType) obj; + EmbIdWithCustomType that = (EmbIdWithCustomType) obj; - if (x != null ? !x.equals(that.x) : that.x != null) return false; - if (customEnum != that.customEnum) return false; + if ( x != null ? !x.equals( that.x ) : that.x != null ) { + return false; + } + if ( customEnum != that.customEnum ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result; - result = (x != null ? x.hashCode() : 0); - result = 31 * result + (customEnum != null ? customEnum.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result; + result = (x != null ? x.hashCode() : 0); + result = 31 * result + (customEnum != null ? customEnum.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/EmbIdWithCustomTypeTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/EmbIdWithCustomTypeTestEntity.java index 3d95df4448..54c7dda35b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/EmbIdWithCustomTypeTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/EmbIdWithCustomTypeTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.ids; + import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Table; @@ -34,51 +35,59 @@ import org.hibernate.envers.Audited; @Entity @Table(name = "EmbIdWithCustType") public class EmbIdWithCustomTypeTestEntity { - @EmbeddedId - private EmbIdWithCustomType id; + @EmbeddedId + private EmbIdWithCustomType id; - @Audited - private String str1; + @Audited + private String str1; - public EmbIdWithCustomTypeTestEntity() { - } + public EmbIdWithCustomTypeTestEntity() { + } - public EmbIdWithCustomTypeTestEntity(EmbIdWithCustomType id, String str1) { - this.id = id; - this.str1 = str1; - } + public EmbIdWithCustomTypeTestEntity(EmbIdWithCustomType id, String str1) { + this.id = id; + this.str1 = str1; + } - public EmbIdWithCustomType getId() { - return id; - } + public EmbIdWithCustomType getId() { + return id; + } - public void setId(EmbIdWithCustomType id) { - this.id = id; - } + public void setId(EmbIdWithCustomType id) { + this.id = id; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - public boolean equals(Object obj) { - if (this == obj) return true; - if (!(obj instanceof EmbIdWithCustomTypeTestEntity)) return false; + public boolean equals(Object obj) { + if ( this == obj ) { + return true; + } + if ( !(obj instanceof EmbIdWithCustomTypeTestEntity) ) { + return false; + } - EmbIdWithCustomTypeTestEntity that = (EmbIdWithCustomTypeTestEntity) obj; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; + EmbIdWithCustomTypeTestEntity that = (EmbIdWithCustomTypeTestEntity) obj; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str1 != null ? str1.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str1 != null ? str1.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/ManyToOneIdNotAuditedTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/ManyToOneIdNotAuditedTestEntity.java index 5749ec3860..3be38b2150 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/ManyToOneIdNotAuditedTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/ManyToOneIdNotAuditedTestEntity.java @@ -1,8 +1,9 @@ package org.hibernate.envers.test.entities.ids; -import java.io.Serializable; + import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Table; +import java.io.Serializable; /** * @author Adam Warski (adam at warski dot org) @@ -10,47 +11,55 @@ import javax.persistence.Table; @Entity @Table(name = "ManyToOneIdNotAud") public class ManyToOneIdNotAuditedTestEntity implements Serializable { - @EmbeddedId - private ManyToOneNotAuditedEmbId id; + @EmbeddedId + private ManyToOneNotAuditedEmbId id; - private String data; + private String data; - public ManyToOneIdNotAuditedTestEntity() { - } + public ManyToOneIdNotAuditedTestEntity() { + } - public ManyToOneNotAuditedEmbId getId() { - return id; - } + public ManyToOneNotAuditedEmbId getId() { + return id; + } - public void setId(ManyToOneNotAuditedEmbId id) { - this.id = id; - } + public void setId(ManyToOneNotAuditedEmbId id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } - ManyToOneIdNotAuditedTestEntity that = (ManyToOneIdNotAuditedTestEntity) o; + ManyToOneIdNotAuditedTestEntity that = (ManyToOneIdNotAuditedTestEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/ManyToOneNotAuditedEmbId.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/ManyToOneNotAuditedEmbId.java index 68e2581740..0786b40490 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/ManyToOneNotAuditedEmbId.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/ManyToOneNotAuditedEmbId.java @@ -1,7 +1,8 @@ package org.hibernate.envers.test.entities.ids; -import java.io.Serializable; + import javax.persistence.Embeddable; import javax.persistence.ManyToOne; +import java.io.Serializable; import org.hibernate.envers.test.entities.UnversionedStrTestEntity; @@ -10,38 +11,44 @@ import org.hibernate.envers.test.entities.UnversionedStrTestEntity; */ @Embeddable public class ManyToOneNotAuditedEmbId implements Serializable { - @ManyToOne(optional = false) - private UnversionedStrTestEntity id; + @ManyToOne(optional = false) + private UnversionedStrTestEntity id; - public ManyToOneNotAuditedEmbId() { - } + public ManyToOneNotAuditedEmbId() { + } - public ManyToOneNotAuditedEmbId(UnversionedStrTestEntity id) { - this.id = id; - } + public ManyToOneNotAuditedEmbId(UnversionedStrTestEntity id) { + this.id = id; + } - public UnversionedStrTestEntity getId() { - return id; - } + public UnversionedStrTestEntity getId() { + return id; + } - public void setId(UnversionedStrTestEntity id) { - this.id = id; - } + public void setId(UnversionedStrTestEntity id) { + this.id = id; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } - ManyToOneNotAuditedEmbId that = (ManyToOneNotAuditedEmbId) o; + ManyToOneNotAuditedEmbId that = (ManyToOneNotAuditedEmbId) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - return id != null ? id.hashCode() : 0; - } + @Override + public int hashCode() { + return id != null ? id.hashCode() : 0; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/MulId.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/MulId.java index 18973e11a0..07a9c3a398 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/MulId.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/MulId.java @@ -22,60 +22,69 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.ids; + import java.io.Serializable; /** * @author Adam Warski (adam at warski dot org) */ public class MulId implements Serializable { - private Integer id1; + private Integer id1; - private Integer id2; + private Integer id2; - public MulId() { - } + public MulId() { + } - public MulId(Integer id1, Integer id2) { - this.id1 = id1; - this.id2 = id2; - } + public MulId(Integer id1, Integer id2) { + this.id1 = id1; + this.id2 = id2; + } - public Integer getId1() { - return id1; - } + public Integer getId1() { + return id1; + } - public void setId1(Integer id1) { - this.id1 = id1; - } + public void setId1(Integer id1) { + this.id1 = id1; + } - public Integer getId2() { - return id2; - } + public Integer getId2() { + return id2; + } - public void setId2(Integer id2) { - this.id2 = id2; - } + public void setId2(Integer id2) { + this.id2 = id2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof MulId)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof MulId) ) { + return false; + } - MulId mulId = (MulId) o; + MulId mulId = (MulId) o; - if (id1 != null ? !id1.equals(mulId.id1) : mulId.id1 != null) return false; - if (id2 != null ? !id2.equals(mulId.id2) : mulId.id2 != null) return false; + if ( id1 != null ? !id1.equals( mulId.id1 ) : mulId.id1 != null ) { + return false; + } + if ( id2 != null ? !id2.equals( mulId.id2 ) : mulId.id2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id1 != null ? id1.hashCode() : 0); - result = 31 * result + (id2 != null ? id2.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id1 != null ? id1.hashCode() : 0); + result = 31 * result + (id2 != null ? id2.hashCode() : 0); + return result; + } - public String toString() { - return "MulId(" + id1 + ", " + id2 + ")"; - } + public String toString() { + return "MulId(" + id1 + ", " + id2 + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/MulIdTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/MulIdTestEntity.java index 13ff15114e..dafd2174fb 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/MulIdTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/MulIdTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.ids; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; @@ -36,70 +37,80 @@ import org.hibernate.envers.Audited; @Table(name = "MulId") @IdClass(MulId.class) public class MulIdTestEntity { - @Id - private Integer id1; + @Id + private Integer id1; - @Id - private Integer id2; + @Id + private Integer id2; - @Audited - private String str1; + @Audited + private String str1; - public MulIdTestEntity() { - } + public MulIdTestEntity() { + } - public MulIdTestEntity(String str1) { - this.str1 = str1; - } + public MulIdTestEntity(String str1) { + this.str1 = str1; + } - public MulIdTestEntity(Integer id1, Integer id2, String str1) { - this.id1 = id1; - this.id2 = id2; - this.str1 = str1; - } + public MulIdTestEntity(Integer id1, Integer id2, String str1) { + this.id1 = id1; + this.id2 = id2; + this.str1 = str1; + } - public Integer getId1() { - return id1; - } + public Integer getId1() { + return id1; + } - public void setId1(Integer id1) { - this.id1 = id1; - } + public void setId1(Integer id1) { + this.id1 = id1; + } - public Integer getId2() { - return id2; - } + public Integer getId2() { + return id2; + } - public void setId2(Integer id2) { - this.id2 = id2; - } + public void setId2(Integer id2) { + this.id2 = id2; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof MulIdTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof MulIdTestEntity) ) { + return false; + } - MulIdTestEntity that = (MulIdTestEntity) o; + MulIdTestEntity that = (MulIdTestEntity) o; - if (id1 != null ? !id1.equals(that.id1) : that.id1 != null) return false; - if (id2 != null ? !id2.equals(that.id2) : that.id2 != null) return false; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; + if ( id1 != null ? !id1.equals( that.id1 ) : that.id1 != null ) { + return false; + } + if ( id2 != null ? !id2.equals( that.id2 ) : that.id2 != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id1 != null ? id1.hashCode() : 0); - result = 31 * result + (id2 != null ? id2.hashCode() : 0); - result = 31 * result + (str1 != null ? str1.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id1 != null ? id1.hashCode() : 0); + result = 31 * result + (id2 != null ? id2.hashCode() : 0); + result = 31 * result + (str1 != null ? str1.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/UnusualIdNamingEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/UnusualIdNamingEntity.java index 98f72c4024..fea52af286 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/UnusualIdNamingEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/ids/UnusualIdNamingEntity.java @@ -1,8 +1,8 @@ package org.hibernate.envers.test.entities.ids; -import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.Id; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -27,13 +27,21 @@ public class UnusualIdNamingEntity implements Serializable { @Override public boolean equals(Object o) { - if ( this == o ) return true; - if ( !( o instanceof UnusualIdNamingEntity) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof UnusualIdNamingEntity) ) { + return false; + } UnusualIdNamingEntity that = (UnusualIdNamingEntity) o; - if ( uniqueField != null ? !uniqueField.equals( that.uniqueField ) : that.uniqueField != null ) return false; - if ( variousData != null ? !variousData.equals( that.variousData ) : that.variousData != null ) return false; + if ( uniqueField != null ? !uniqueField.equals( that.uniqueField ) : that.uniqueField != null ) { + return false; + } + if ( variousData != null ? !variousData.equals( that.variousData ) : that.variousData != null ) { + return false; + } return true; } @@ -41,7 +49,7 @@ public class UnusualIdNamingEntity implements Serializable { @Override public int hashCode() { int result = uniqueField != null ? uniqueField.hashCode() : 0; - result = 31 * result + ( variousData != null ? variousData.hashCode() : 0 ); + result = 31 * result + (variousData != null ? variousData.hashCode() : 0); return result; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/ListOwnedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/ListOwnedEntity.java index 16fe4b88e7..5550512808 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/ListOwnedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/ListOwnedEntity.java @@ -22,87 +22,97 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.manytomany; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; +import java.util.List; import org.hibernate.envers.Audited; /** * Many-to-many not-owning entity + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "ListOwned") public class ListOwnedEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToMany(mappedBy="references") - private List referencing; + @Audited + @ManyToMany(mappedBy = "references") + private List referencing; - public ListOwnedEntity() { - } + public ListOwnedEntity() { + } - public ListOwnedEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public ListOwnedEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public ListOwnedEntity(String data) { - this.data = data; - } + public ListOwnedEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public List getReferencing() { - return referencing; - } + public List getReferencing() { + return referencing; + } - public void setReferencing(List referencing) { - this.referencing = referencing; - } + public void setReferencing(List referencing) { + this.referencing = referencing; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ListOwnedEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ListOwnedEntity) ) { + return false; + } - ListOwnedEntity that = (ListOwnedEntity) o; + ListOwnedEntity that = (ListOwnedEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetOwnedEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "SetOwnedEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/ListOwningEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/ListOwningEntity.java index 3548b6c53a..81df629409 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/ListOwningEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/ListOwningEntity.java @@ -22,86 +22,97 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.manytomany; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; +import java.util.List; import org.hibernate.envers.Audited; /** * Entity owning the many-to-many relation + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "ListOwning") public class ListOwningEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToMany - private List references; + @Audited + @ManyToMany + private List references; - public ListOwningEntity() { } + public ListOwningEntity() { + } - public ListOwningEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public ListOwningEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public ListOwningEntity(String data) { - this.data = data; - } + public ListOwningEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public List getReferences() { - return references; - } + public List getReferences() { + return references; + } - public void setReferences(List references) { - this.references = references; - } + public void setReferences(List references) { + this.references = references; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ListOwningEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ListOwningEntity) ) { + return false; + } - ListOwningEntity that = (ListOwningEntity) o; + ListOwningEntity that = (ListOwningEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetOwningEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "SetOwningEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/MapOwnedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/MapOwnedEntity.java index bf1167ff4c..b41612541e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/MapOwnedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/MapOwnedEntity.java @@ -22,87 +22,97 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.manytomany; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; +import java.util.Set; import org.hibernate.envers.Audited; /** * Many-to-many not-owning entity + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "MapOwned") public class MapOwnedEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToMany(mappedBy="references") - private Set referencing; + @Audited + @ManyToMany(mappedBy = "references") + private Set referencing; - public MapOwnedEntity() { - } + public MapOwnedEntity() { + } - public MapOwnedEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public MapOwnedEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public MapOwnedEntity(String data) { - this.data = data; - } + public MapOwnedEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Set getReferencing() { - return referencing; - } + public Set getReferencing() { + return referencing; + } - public void setReferencing(Set referencing) { - this.referencing = referencing; - } + public void setReferencing(Set referencing) { + this.referencing = referencing; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof MapOwnedEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof MapOwnedEntity) ) { + return false; + } - MapOwnedEntity that = (MapOwnedEntity) o; + MapOwnedEntity that = (MapOwnedEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "MapOwnedEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "MapOwnedEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/MapOwningEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/MapOwningEntity.java index 07b0d1ffc1..4cd90c822b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/MapOwningEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/MapOwningEntity.java @@ -22,89 +22,100 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.manytomany; -import java.util.HashMap; -import java.util.Map; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.MapKeyColumn; import javax.persistence.Table; +import java.util.HashMap; +import java.util.Map; import org.hibernate.envers.Audited; /** * Entity owning the many-to-many relation + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "MapOwning") public class MapOwningEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToMany - @MapKeyColumn(nullable=false) - private Map references = new HashMap(); + @Audited + @ManyToMany + @MapKeyColumn(nullable = false) + private Map references = new HashMap(); - public MapOwningEntity() { } + public MapOwningEntity() { + } - public MapOwningEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public MapOwningEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public MapOwningEntity(String data) { - this.data = data; - } + public MapOwningEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Map getReferences() { - return references; - } + public Map getReferences() { + return references; + } - public void setReferences(Map references) { - this.references = references; - } + public void setReferences(Map references) { + this.references = references; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof MapOwningEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof MapOwningEntity) ) { + return false; + } - MapOwningEntity that = (MapOwningEntity) o; + MapOwningEntity that = (MapOwningEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "MapOwningEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "MapOwningEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/SetOwnedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/SetOwnedEntity.java index c7fc832665..262ec1c3ad 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/SetOwnedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/SetOwnedEntity.java @@ -22,87 +22,97 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.manytomany; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; +import java.util.Set; import org.hibernate.envers.Audited; /** * Many-to-many not-owning entity + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "SetOwned") public class SetOwnedEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToMany(mappedBy="references") - private Set referencing; + @Audited + @ManyToMany(mappedBy = "references") + private Set referencing; - public SetOwnedEntity() { - } + public SetOwnedEntity() { + } - public SetOwnedEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public SetOwnedEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public SetOwnedEntity(String data) { - this.data = data; - } + public SetOwnedEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Set getReferencing() { - return referencing; - } + public Set getReferencing() { + return referencing; + } - public void setReferencing(Set referencing) { - this.referencing = referencing; - } + public void setReferencing(Set referencing) { + this.referencing = referencing; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SetOwnedEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SetOwnedEntity) ) { + return false; + } - SetOwnedEntity that = (SetOwnedEntity) o; + SetOwnedEntity that = (SetOwnedEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetOwnedEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "SetOwnedEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/SetOwningEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/SetOwningEntity.java index ab351bfbb7..22a0f210ca 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/SetOwningEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/SetOwningEntity.java @@ -22,86 +22,97 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.manytomany; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; +import java.util.Set; import org.hibernate.envers.Audited; /** * Entity owning the many-to-many relation + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "SetOwning") public class SetOwningEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToMany - private Set references; + @Audited + @ManyToMany + private Set references; - public SetOwningEntity() { } + public SetOwningEntity() { + } - public SetOwningEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public SetOwningEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public SetOwningEntity(String data) { - this.data = data; - } + public SetOwningEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Set getReferences() { - return references; - } + public Set getReferences() { + return references; + } - public void setReferences(Set references) { - this.references = references; - } + public void setReferences(Set references) { + this.references = references; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SetOwningEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SetOwningEntity) ) { + return false; + } - SetOwningEntity that = (SetOwningEntity) o; + SetOwningEntity that = (SetOwningEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetOwningEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "SetOwningEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/SortedSetEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/SortedSetEntity.java index 1e0f22efd1..f88dcf09fa 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/SortedSetEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/SortedSetEntity.java @@ -23,15 +23,15 @@ */ package org.hibernate.envers.test.entities.manytomany; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeMap; -import java.util.TreeSet; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.MapKeyJoinColumn; +import java.util.SortedMap; +import java.util.SortedSet; +import java.util.TreeMap; +import java.util.TreeSet; import org.hibernate.annotations.Sort; import org.hibernate.annotations.SortType; @@ -46,57 +46,57 @@ import org.hibernate.envers.test.entities.StrTestEntityComparator; */ @Entity public class SortedSetEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToMany - @Sort(type = SortType.COMPARATOR, comparator = StrTestEntityComparator.class) - private SortedSet sortedSet = new TreeSet(StrTestEntityComparator.INSTANCE); - @Audited + @Audited + @ManyToMany + @Sort(type = SortType.COMPARATOR, comparator = StrTestEntityComparator.class) + private SortedSet sortedSet = new TreeSet( StrTestEntityComparator.INSTANCE ); + @Audited @ElementCollection @MapKeyJoinColumn - @Sort(type = SortType.COMPARATOR, comparator = StrTestEntityComparator.class) - private SortedMap sortedMap = new TreeMap(StrTestEntityComparator.INSTANCE); + @Sort(type = SortType.COMPARATOR, comparator = StrTestEntityComparator.class) + private SortedMap sortedMap = new TreeMap( StrTestEntityComparator.INSTANCE ); - public SortedSetEntity() { - } + public SortedSetEntity() { + } - public SortedSetEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public SortedSetEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public SortedSetEntity(String data) { - this.data = data; - } + public SortedSetEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public SortedSet getSortedSet() { - return sortedSet; - } + public SortedSet getSortedSet() { + return sortedSet; + } - public void setSortedSet(SortedSet sortedSet) { - this.sortedSet = sortedSet; - } + public void setSortedSet(SortedSet sortedSet) { + this.sortedSet = sortedSet; + } public SortedMap getSortedMap() { return sortedMap; @@ -107,22 +107,28 @@ public class SortedSetEntity { } public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SortedSetEntity)) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof SortedSetEntity) ) { + return false; + } - SortedSetEntity that = (SortedSetEntity) o; + SortedSetEntity that = (SortedSetEntity) o; - return !(data != null ? !data.equals(that.data) : that.data != null) && !(id != null ? !id.equals(that.id) : that.id != null); + return !(data != null ? !data.equals( that.data ) : that.data != null) && !(id != null ? + !id.equals( that.id ) : + that.id != null); } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetOwnedEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "SetOwnedEntity(id = " + id + ", data = " + data + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/WhereJoinTableEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/WhereJoinTableEntity.java index 7df21a862e..35998cef89 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/WhereJoinTableEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/WhereJoinTableEntity.java @@ -1,11 +1,12 @@ package org.hibernate.envers.test.entities.manytomany; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; +import java.util.List; import org.hibernate.annotations.WhereJoinTable; import org.hibernate.envers.Audited; @@ -17,84 +18,92 @@ import org.hibernate.envers.test.entities.IntNoAutoIdTestEntity; @Entity @Audited public class WhereJoinTableEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String data; + private String data; - @ManyToMany - @JoinTable( - name = "wjte_ite_join", - joinColumns = @JoinColumn(name = "wjte_id"), - inverseJoinColumns = @JoinColumn(name = "ite_id") - ) - @WhereJoinTable(clause = "ite_id < 20") - private List references1; + @ManyToMany + @JoinTable( + name = "wjte_ite_join", + joinColumns = @JoinColumn(name = "wjte_id"), + inverseJoinColumns = @JoinColumn(name = "ite_id") + ) + @WhereJoinTable(clause = "ite_id < 20") + private List references1; - @ManyToMany - @JoinTable( - name = "wjte_ite_join", - joinColumns = @JoinColumn(name = "wjte_id"), - inverseJoinColumns = @JoinColumn(name = "ite_id") - ) - @WhereJoinTable(clause = "ite_id >= 20") - private List references2; + @ManyToMany + @JoinTable( + name = "wjte_ite_join", + joinColumns = @JoinColumn(name = "wjte_id"), + inverseJoinColumns = @JoinColumn(name = "ite_id") + ) + @WhereJoinTable(clause = "ite_id >= 20") + private List references2; - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public List getReferences1() { - return references1; - } + public List getReferences1() { + return references1; + } - public void setReferences1(List references1) { - this.references1 = references1; - } + public void setReferences1(List references1) { + this.references1 = references1; + } - public List getReferences2() { - return references2; - } + public List getReferences2() { + return references2; + } - public void setReferences2(List references2) { - this.references2 = references2; - } + public void setReferences2(List references2) { + this.references2 = references2; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } - WhereJoinTableEntity that = (WhereJoinTableEntity) o; + WhereJoinTableEntity that = (WhereJoinTableEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - //noinspection RedundantIfStatement - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "WJTE(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "WJTE(id = " + id + ", data = " + data + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/biowned/ListBiowning1Entity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/biowned/ListBiowning1Entity.java index 13f2984fe7..dc9c9716cb 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/biowned/ListBiowning1Entity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/biowned/ListBiowning1Entity.java @@ -22,94 +22,105 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.manytomany.biowned; -import java.util.ArrayList; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; +import java.util.ArrayList; +import java.util.List; import org.hibernate.envers.Audited; /** * Entity owning a many-to-many relation, where the other entity also owns the relation. + * * @author Adam Warski (adam at warski dot org) */ @Entity @Audited public class ListBiowning1Entity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String data; + private String data; - @ManyToMany - @JoinTable( - name = "biowning", - joinColumns = @JoinColumn(name = "biowning1_id"), - inverseJoinColumns = @JoinColumn(name = "biowning2_id", insertable = false, updatable = false) + @ManyToMany + @JoinTable( + name = "biowning", + joinColumns = @JoinColumn(name = "biowning1_id"), + inverseJoinColumns = @JoinColumn(name = "biowning2_id", insertable = false, updatable = false) ) - private List references = new ArrayList(); + private List references = new ArrayList(); - public ListBiowning1Entity() { } + public ListBiowning1Entity() { + } - public ListBiowning1Entity(Integer id, String data) { - this.id = id; - this.data = data; - } + public ListBiowning1Entity(Integer id, String data) { + this.id = id; + this.data = data; + } - public ListBiowning1Entity(String data) { - this.data = data; - } + public ListBiowning1Entity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public List getReferences() { - return references; - } + public List getReferences() { + return references; + } - public void setReferences(List references) { - this.references = references; - } + public void setReferences(List references) { + this.references = references; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ListBiowning1Entity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ListBiowning1Entity) ) { + return false; + } - ListBiowning1Entity that = (ListBiowning1Entity) o; + ListBiowning1Entity that = (ListBiowning1Entity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - //noinspection RedundantIfStatement - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ListBiowning1Entity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "ListBiowning1Entity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/biowned/ListBiowning2Entity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/biowned/ListBiowning2Entity.java index d17322d98a..e341a9ff0a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/biowned/ListBiowning2Entity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/biowned/ListBiowning2Entity.java @@ -22,94 +22,105 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.manytomany.biowned; -import java.util.ArrayList; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; +import java.util.ArrayList; +import java.util.List; import org.hibernate.envers.Audited; /** * Entity owning a many-to-many relation, where the other entity also owns the relation. + * * @author Adam Warski (adam at warski dot org) */ @Entity @Audited public class ListBiowning2Entity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String data; + private String data; - @ManyToMany - @JoinTable( - name = "biowning", - joinColumns = @JoinColumn(name = "biowning2_id"), - inverseJoinColumns = @JoinColumn(name = "biowning1_id", insertable = false, updatable = false) + @ManyToMany + @JoinTable( + name = "biowning", + joinColumns = @JoinColumn(name = "biowning2_id"), + inverseJoinColumns = @JoinColumn(name = "biowning1_id", insertable = false, updatable = false) ) - private List references = new ArrayList(); + private List references = new ArrayList(); - public ListBiowning2Entity() { } + public ListBiowning2Entity() { + } - public ListBiowning2Entity(Integer id, String data) { - this.id = id; - this.data = data; - } + public ListBiowning2Entity(Integer id, String data) { + this.id = id; + this.data = data; + } - public ListBiowning2Entity(String data) { - this.data = data; - } + public ListBiowning2Entity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public List getReferences() { - return references; - } + public List getReferences() { + return references; + } - public void setReferences(List references) { - this.references = references; - } + public void setReferences(List references) { + this.references = references; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ListBiowning2Entity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ListBiowning2Entity) ) { + return false; + } - ListBiowning2Entity that = (ListBiowning2Entity) o; + ListBiowning2Entity that = (ListBiowning2Entity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - //noinspection RedundantIfStatement - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ListBiowning2Entity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "ListBiowning2Entity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/sametable/Child1Entity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/sametable/Child1Entity.java index 9b4a70ed78..fb05746f06 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/sametable/Child1Entity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/sametable/Child1Entity.java @@ -1,6 +1,5 @@ package org.hibernate.envers.test.entities.manytomany.sametable; -import java.util.ArrayList; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; @@ -8,6 +7,8 @@ import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; +import java.util.ArrayList; +import java.util.List; import org.hibernate.annotations.WhereJoinTable; import org.hibernate.envers.Audited; @@ -18,79 +19,87 @@ import org.hibernate.envers.Audited; @Entity @Audited public class Child1Entity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String child1Data; + private String child1Data; - public Child1Entity() { - } + public Child1Entity() { + } - public Child1Entity(String child1Data) { - this.child1Data = child1Data; - } + public Child1Entity(String child1Data) { + this.child1Data = child1Data; + } - public Child1Entity(String child1Data, Integer id) { - this.child1Data = child1Data; - this.id = id; - } + public Child1Entity(String child1Data, Integer id) { + this.child1Data = child1Data; + this.id = id; + } - @ManyToMany(fetch = FetchType.LAZY) + @ManyToMany(fetch = FetchType.LAZY) @JoinTable( - name = "children", - joinColumns = @JoinColumn(name = "child1_id"), - inverseJoinColumns = @JoinColumn(name = "parent_id", insertable = false, updatable = false) + name = "children", + joinColumns = @JoinColumn(name = "child1_id"), + inverseJoinColumns = @JoinColumn(name = "parent_id", insertable = false, updatable = false) ) @WhereJoinTable(clause = "child1_id is not null") private List parents = new ArrayList(); - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getChild1Data() { - return child1Data; - } + public String getChild1Data() { + return child1Data; + } - public void setChild1Data(String child1Data) { - this.child1Data = child1Data; - } + public void setChild1Data(String child1Data) { + this.child1Data = child1Data; + } - public List getParents() { - return parents; - } + public List getParents() { + return parents; + } - public void setParents(List parents) { - this.parents = parents; - } + public void setParents(List parents) { + this.parents = parents; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } - Child1Entity that = (Child1Entity) o; + Child1Entity that = (Child1Entity) o; - if (child1Data != null ? !child1Data.equals(that.child1Data) : that.child1Data != null) return false; - //noinspection RedundantIfStatement - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( child1Data != null ? !child1Data.equals( that.child1Data ) : that.child1Data != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (child1Data != null ? child1Data.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (child1Data != null ? child1Data.hashCode() : 0); + return result; + } - public String toString() { - return "C1E(id = " + id + ", child1Data = " + child1Data + ")"; - } + public String toString() { + return "C1E(id = " + id + ", child1Data = " + child1Data + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/sametable/Child2Entity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/sametable/Child2Entity.java index 4a2db0fd35..87963f4251 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/sametable/Child2Entity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/sametable/Child2Entity.java @@ -1,6 +1,5 @@ package org.hibernate.envers.test.entities.manytomany.sametable; -import java.util.ArrayList; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; @@ -8,6 +7,8 @@ import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; +import java.util.ArrayList; +import java.util.List; import org.hibernate.annotations.WhereJoinTable; import org.hibernate.envers.Audited; @@ -18,79 +19,87 @@ import org.hibernate.envers.Audited; @Entity @Audited public class Child2Entity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String child2Data; + private String child2Data; - public Child2Entity() { - } + public Child2Entity() { + } - public Child2Entity(String child2Data) { - this.child2Data = child2Data; - } + public Child2Entity(String child2Data) { + this.child2Data = child2Data; + } - public Child2Entity(Integer id, String child2Data) { - this.id = id; - this.child2Data = child2Data; - } + public Child2Entity(Integer id, String child2Data) { + this.id = id; + this.child2Data = child2Data; + } - @ManyToMany(fetch = FetchType.LAZY) + @ManyToMany(fetch = FetchType.LAZY) @JoinTable( - name = "children", - joinColumns = @JoinColumn(name = "child2_id"), - inverseJoinColumns = @JoinColumn(name = "parent_id", insertable = false, updatable = false) + name = "children", + joinColumns = @JoinColumn(name = "child2_id"), + inverseJoinColumns = @JoinColumn(name = "parent_id", insertable = false, updatable = false) ) @WhereJoinTable(clause = "child2_id is not null") private List parents = new ArrayList(); - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getChild2Data() { - return child2Data; - } + public String getChild2Data() { + return child2Data; + } - public void setChild2Data(String child2Data) { - this.child2Data = child2Data; - } + public void setChild2Data(String child2Data) { + this.child2Data = child2Data; + } - public List getParents() { - return parents; - } + public List getParents() { + return parents; + } - public void setParents(List parents) { - this.parents = parents; - } + public void setParents(List parents) { + this.parents = parents; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } - Child2Entity that = (Child2Entity) o; + Child2Entity that = (Child2Entity) o; - if (child2Data != null ? !child2Data.equals(that.child2Data) : that.child2Data != null) return false; - //noinspection RedundantIfStatement - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( child2Data != null ? !child2Data.equals( that.child2Data ) : that.child2Data != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (child2Data != null ? child2Data.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (child2Data != null ? child2Data.hashCode() : 0); + return result; + } - public String toString() { - return "C2E(id = " + id + ", child2Data = " + child2Data + ")"; - } + public String toString() { + return "C2E(id = " + id + ", child2Data = " + child2Data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/sametable/ParentEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/sametable/ParentEntity.java index 8442bdd882..c75a4fd021 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/sametable/ParentEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/sametable/ParentEntity.java @@ -1,6 +1,5 @@ package org.hibernate.envers.test.entities.manytomany.sametable; -import java.util.ArrayList; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; @@ -8,6 +7,8 @@ import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; +import java.util.ArrayList; +import java.util.List; import org.hibernate.annotations.WhereJoinTable; import org.hibernate.envers.Audited; @@ -18,96 +19,104 @@ import org.hibernate.envers.Audited; @Entity @Audited public class ParentEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String parentData; + private String parentData; - public ParentEntity() { - } + public ParentEntity() { + } - public ParentEntity(String parentData) { - this.parentData = parentData; - } + public ParentEntity(String parentData) { + this.parentData = parentData; + } - public ParentEntity(Integer id, String parentData) { - this.id = id; - this.parentData = parentData; - } + public ParentEntity(Integer id, String parentData) { + this.id = id; + this.parentData = parentData; + } - @ManyToMany(fetch = FetchType.LAZY) + @ManyToMany(fetch = FetchType.LAZY) @JoinTable( - name = "children", - joinColumns = @JoinColumn(name = "parent_id"), - inverseJoinColumns = @JoinColumn(name = "child1_id", insertable = false, updatable = false) + name = "children", + joinColumns = @JoinColumn(name = "parent_id"), + inverseJoinColumns = @JoinColumn(name = "child1_id", insertable = false, updatable = false) ) @WhereJoinTable(clause = "child1_id is not null") private List children1 = new ArrayList(); - @ManyToMany(fetch = FetchType.LAZY) + @ManyToMany(fetch = FetchType.LAZY) @JoinTable( - name = "children", - joinColumns = @JoinColumn(name = "parent_id"), - inverseJoinColumns = @JoinColumn(name = "child2_id", insertable = false, updatable = false) + name = "children", + joinColumns = @JoinColumn(name = "parent_id"), + inverseJoinColumns = @JoinColumn(name = "child2_id", insertable = false, updatable = false) ) @WhereJoinTable(clause = "child2_id is not null") private List children2 = new ArrayList(); - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getParentData() { - return parentData; - } + public String getParentData() { + return parentData; + } - public void setParentData(String parentData) { - this.parentData = parentData; - } + public void setParentData(String parentData) { + this.parentData = parentData; + } - public List getChildren1() { - return children1; - } + public List getChildren1() { + return children1; + } - public void setChildren1(List children1) { - this.children1 = children1; - } + public void setChildren1(List children1) { + this.children1 = children1; + } - public List getChildren2() { - return children2; - } + public List getChildren2() { + return children2; + } - public void setChildren2(List children2) { - this.children2 = children2; - } + public void setChildren2(List children2) { + this.children2 = children2; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } - ParentEntity that = (ParentEntity) o; + ParentEntity that = (ParentEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - //noinspection RedundantIfStatement - if (parentData != null ? !parentData.equals(that.parentData) : that.parentData != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( parentData != null ? !parentData.equals( that.parentData ) : that.parentData != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (parentData != null ? parentData.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (parentData != null ? parentData.hashCode() : 0); + return result; + } - public String toString() { - return "PE(id = " + id + ", parentData = " + parentData + ")"; - } + public String toString() { + return "PE(id = " + id + ", parentData = " + parentData + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/JoinTableEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/JoinTableEntity.java index 1e5c162b08..916e2220e1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/JoinTableEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/JoinTableEntity.java @@ -1,14 +1,14 @@ package org.hibernate.envers.test.entities.manytomany.unidirectional; -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.StrTestEntity; @@ -27,8 +27,8 @@ public class JoinTableEntity implements Serializable { @ManyToMany @JoinTable(name = "test_join_table", - joinColumns = @JoinColumn(name = "assoc_id1"), - inverseJoinColumns = @JoinColumn(name = "assoc_id2") + joinColumns = @JoinColumn(name = "assoc_id1"), + inverseJoinColumns = @JoinColumn(name = "assoc_id2") ) private Set references = new HashSet(); @@ -46,13 +46,21 @@ public class JoinTableEntity implements Serializable { @Override public boolean equals(Object o) { - if ( this == o ) return true; - if ( !( o instanceof JoinTableEntity ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof JoinTableEntity) ) { + return false; + } JoinTableEntity that = (JoinTableEntity) o; - if ( data != null ? !data.equals( that.data ) : that.data != null ) return false; - if ( id != null ? !id.equals( that.id ) : that.id != null ) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } return true; } @@ -60,7 +68,7 @@ public class JoinTableEntity implements Serializable { @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; - result = 31 * result + ( data != null ? data.hashCode() : 0 ); + result = 31 * result + (data != null ? data.hashCode() : 0); return result; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/ListUniEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/ListUniEntity.java index 7c3b78ef64..52b846e1a3 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/ListUniEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/ListUniEntity.java @@ -22,85 +22,96 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.manytomany.unidirectional; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; +import java.util.List; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.StrTestEntity; /** * Entity owning the many-to-many relation + * * @author Adam Warski (adam at warski dot org) */ @Entity public class ListUniEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToMany - private List references; + @Audited + @ManyToMany + private List references; - public ListUniEntity() { } + public ListUniEntity() { + } - public ListUniEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public ListUniEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public ListUniEntity(String data) { - this.data = data; - } + public ListUniEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public List getReferences() { - return references; - } + public List getReferences() { + return references; + } - public void setReferences(List references) { - this.references = references; - } + public void setReferences(List references) { + this.references = references; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ListUniEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ListUniEntity) ) { + return false; + } - ListUniEntity that = (ListUniEntity) o; + ListUniEntity that = (ListUniEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ListUniEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "ListUniEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/M2MIndexedListTargetNotAuditedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/M2MIndexedListTargetNotAuditedEntity.java index 1b36f14a4b..2caa3a8540 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/M2MIndexedListTargetNotAuditedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/M2MIndexedListTargetNotAuditedEntity.java @@ -1,12 +1,13 @@ package org.hibernate.envers.test.entities.manytomany.unidirectional; -import java.util.ArrayList; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.OrderColumn; import javax.persistence.Table; +import java.util.ArrayList; +import java.util.List; import org.hibernate.envers.Audited; import org.hibernate.envers.RelationTargetAuditMode; @@ -19,79 +20,85 @@ import org.hibernate.envers.test.entities.UnversionedStrTestEntity; @Table(name = "M2M_IDX_LIST") public class M2MIndexedListTargetNotAuditedEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) - @OrderColumn(name = "sortOrder") - @ManyToMany(fetch = FetchType.LAZY) - private List references = new ArrayList(); + @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) + @OrderColumn(name = "sortOrder") + @ManyToMany(fetch = FetchType.LAZY) + private List references = new ArrayList(); - public M2MIndexedListTargetNotAuditedEntity() { - } + public M2MIndexedListTargetNotAuditedEntity() { + } - public M2MIndexedListTargetNotAuditedEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public M2MIndexedListTargetNotAuditedEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public M2MIndexedListTargetNotAuditedEntity(Integer id, String data, List references) { - this.id = id; - this.data = data; - this.references = references; - } + public M2MIndexedListTargetNotAuditedEntity(Integer id, String data, List references) { + this.id = id; + this.data = data; + this.references = references; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public List getReferences() { - return references; - } + public List getReferences() { + return references; + } - public void setReferences(List references) { - this.references = references; - } + public void setReferences(List references) { + this.references = references; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } - M2MIndexedListTargetNotAuditedEntity that = (M2MIndexedListTargetNotAuditedEntity) o; + M2MIndexedListTargetNotAuditedEntity that = (M2MIndexedListTargetNotAuditedEntity) o; - //noinspection RedundantIfStatement - if (data != null ? !data.equals(that.data) : that.data != null) return false; + //noinspection RedundantIfStatement + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - return data != null ? data.hashCode() : 0; - } + @Override + public int hashCode() { + return data != null ? data.hashCode() : 0; + } - @Override - public String toString() { + @Override + public String toString() { return "M2MIndexedListTargetNotAuditedEntity(id = " + id + ", data = " + data + ")"; - } + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/M2MTargetNotAuditedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/M2MTargetNotAuditedEntity.java index aa9f13b296..ae8e52117f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/M2MTargetNotAuditedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/M2MTargetNotAuditedEntity.java @@ -22,12 +22,13 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.manytomany.unidirectional; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; +import java.util.List; import org.hibernate.envers.Audited; import org.hibernate.envers.RelationTargetAuditMode; @@ -35,6 +36,7 @@ import org.hibernate.envers.test.entities.UnversionedStrTestEntity; /** * Audited entity with a many-to-many-reference to not audited entity. + * * @author Toamsz Bech * @author Adam Warski */ @@ -51,7 +53,8 @@ public class M2MTargetNotAuditedEntity { @ManyToMany(fetch = FetchType.LAZY) private List references; - public M2MTargetNotAuditedEntity() { } + public M2MTargetNotAuditedEntity() { + } public M2MTargetNotAuditedEntity(Integer id, String data, List references) { this.id = id; @@ -85,23 +88,31 @@ public class M2MTargetNotAuditedEntity { this.data = data; } - public List getReferences() { - return references; - } + public List getReferences() { + return references; + } - public void setReferences(List references) { - this.references = references; - } + public void setReferences(List references) { + this.references = references; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof M2MTargetNotAuditedEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof M2MTargetNotAuditedEntity) ) { + return false; + } M2MTargetNotAuditedEntity that = (M2MTargetNotAuditedEntity) o; - if (data != null ? !data.equals(that.getData()) : that.getData() != null) return false; - //noinspection RedundantIfStatement - if (id != null ? !id.equals(that.getId()) : that.getId() != null) return false; + if ( data != null ? !data.equals( that.getData() ) : that.getData() != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( id != null ? !id.equals( that.getId() ) : that.getId() != null ) { + return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/MapUniEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/MapUniEntity.java index 9ea50a77bd..e1430e39f0 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/MapUniEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/MapUniEntity.java @@ -22,88 +22,98 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.manytomany.unidirectional; -import java.util.Map; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.MapKeyColumn; +import java.util.Map; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.StrTestEntity; /** * Entity with a map from a string to an entity + * * @author Adam Warski (adam at warski dot org) */ @Entity public class MapUniEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToMany - @MapKeyColumn(nullable=false) - private Map map; + @Audited + @ManyToMany + @MapKeyColumn(nullable = false) + private Map map; - public MapUniEntity() { - } + public MapUniEntity() { + } - public MapUniEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public MapUniEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public MapUniEntity(String data) { - this.data = data; - } + public MapUniEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Map getMap() { - return map; - } + public Map getMap() { + return map; + } - public void setMap(Map map) { - this.map = map; - } + public void setMap(Map map) { + this.map = map; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof MapUniEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof MapUniEntity) ) { + return false; + } - MapUniEntity that = (MapUniEntity) o; + MapUniEntity that = (MapUniEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "MapUniEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "MapUniEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/SetUniEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/SetUniEntity.java index a53c4284ee..7454725161 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/SetUniEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytomany/unidirectional/SetUniEntity.java @@ -22,85 +22,96 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.manytomany.unidirectional; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToMany; +import java.util.Set; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.StrTestEntity; /** * Entity owning the many-to-many relation + * * @author Adam Warski (adam at warski dot org) */ @Entity public class SetUniEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToMany - private Set references; + @Audited + @ManyToMany + private Set references; - public SetUniEntity() { } + public SetUniEntity() { + } - public SetUniEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public SetUniEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public SetUniEntity(String data) { - this.data = data; - } + public SetUniEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Set getReferences() { - return references; - } + public Set getReferences() { + return references; + } - public void setReferences(Set references) { - this.references = references; - } + public void setReferences(Set references) { + this.references = references; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SetUniEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SetUniEntity) ) { + return false; + } - SetUniEntity that = (SetUniEntity) o; + SetUniEntity that = (SetUniEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetUniEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "SetUniEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytoone/unidirectional/TargetNotAuditedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytoone/unidirectional/TargetNotAuditedEntity.java index 6b2578964f..d655e605d5 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytoone/unidirectional/TargetNotAuditedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/manytoone/unidirectional/TargetNotAuditedEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.manytoone.unidirectional; + import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; @@ -33,6 +34,7 @@ import org.hibernate.envers.test.entities.UnversionedStrTestEntity; /** * Audited entity with a reference to not audited entity. + * * @author Toamsz Bech */ @Entity @@ -47,7 +49,8 @@ public class TargetNotAuditedEntity { @ManyToOne(fetch = FetchType.LAZY) private UnversionedStrTestEntity reference; - public TargetNotAuditedEntity() { } + public TargetNotAuditedEntity() { + } public TargetNotAuditedEntity(Integer id, String data, UnversionedStrTestEntity reference) { this.id = id; @@ -90,13 +93,21 @@ public class TargetNotAuditedEntity { } public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof TargetNotAuditedEntity)) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof TargetNotAuditedEntity) ) { + return false; + } TargetNotAuditedEntity that = (TargetNotAuditedEntity) o; - if (data != null ? !data.equals(that.getData()) : that.getData() != null) return false; - if (id != null ? !id.equals(that.getId()) : that.getId() != null) return false; + if ( data != null ? !data.equals( that.getData() ) : that.getData() != null ) { + return false; + } + if ( id != null ? !id.equals( that.getId() ) : that.getId() != null ) { + return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/CollectionRefEdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/CollectionRefEdEntity.java index cedf8e4b57..8e6baedddd 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/CollectionRefEdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/CollectionRefEdEntity.java @@ -22,88 +22,98 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.onetomany; -import java.io.Serializable; -import java.util.Collection; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.io.Serializable; +import java.util.Collection; import org.hibernate.envers.Audited; /** * ReferencEd entity + * * @author Adam Warski (adam at warski dot org) */ @Entity public class CollectionRefEdEntity implements Serializable { private static final long serialVersionUID = -1694020123633796683L; - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToMany(mappedBy="reference") - private Collection reffering; + @Audited + @OneToMany(mappedBy = "reference") + private Collection reffering; public CollectionRefEdEntity() { - } + } - public CollectionRefEdEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public CollectionRefEdEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public CollectionRefEdEntity(String data) { - this.data = data; - } + public CollectionRefEdEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Collection getReffering() { - return reffering; - } + public Collection getReffering() { + return reffering; + } - public void setReffering(Collection reffering) { - this.reffering = reffering; - } + public void setReffering(Collection reffering) { + this.reffering = reffering; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof CollectionRefEdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof CollectionRefEdEntity) ) { + return false; + } - CollectionRefEdEntity that = (CollectionRefEdEntity) o; + CollectionRefEdEntity that = (CollectionRefEdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "CollectionRefEdEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "CollectionRefEdEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/CollectionRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/CollectionRefIngEntity.java index 6242faf02b..67992c838b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/CollectionRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/CollectionRefIngEntity.java @@ -22,88 +22,99 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.onetomany; -import java.io.Serializable; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToOne; +import java.io.Serializable; import org.hibernate.envers.Audited; /** * ReferencIng entity + * * @author Adam Warski (adam at warski dot org) */ @Entity public class CollectionRefIngEntity implements Serializable { private static final long serialVersionUID = -9019967223928425707L; - - @Id - private Integer id; - @Audited - private String data; + @Id + private Integer id; - @Audited - @ManyToOne - private CollectionRefEdEntity reference; + @Audited + private String data; - public CollectionRefIngEntity() { } + @Audited + @ManyToOne + private CollectionRefEdEntity reference; - public CollectionRefIngEntity(Integer id, String data, CollectionRefEdEntity reference) { - this.id = id; - this.data = data; - this.reference = reference; - } + public CollectionRefIngEntity() { + } - public CollectionRefIngEntity(String data, CollectionRefEdEntity reference) { - this.data = data; - this.reference = reference; - } + public CollectionRefIngEntity(Integer id, String data, CollectionRefEdEntity reference) { + this.id = id; + this.data = data; + this.reference = reference; + } - public Integer getId() { - return id; - } + public CollectionRefIngEntity(String data, CollectionRefEdEntity reference) { + this.data = data; + this.reference = reference; + } - public void setId(Integer id) { - this.id = id; - } + public Integer getId() { + return id; + } - public String getData() { - return data; - } + public void setId(Integer id) { + this.id = id; + } - public void setData(String data) { - this.data = data; - } + public String getData() { + return data; + } - public CollectionRefEdEntity getReference() { - return reference; - } + public void setData(String data) { + this.data = data; + } - public void setReference(CollectionRefEdEntity reference) { - this.reference = reference; - } + public CollectionRefEdEntity getReference() { + return reference; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof CollectionRefIngEntity)) return false; + public void setReference(CollectionRefEdEntity reference) { + this.reference = reference; + } - CollectionRefIngEntity that = (CollectionRefIngEntity) o; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof CollectionRefIngEntity) ) { + return false; + } - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + CollectionRefIngEntity that = (CollectionRefIngEntity) o; - return true; - } + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + return true; + } - public String toString() { - return "CollectionRefIngEntity(id = " + id + ", data = " + data + ")"; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } + + public String toString() { + return "CollectionRefIngEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ListRefEdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ListRefEdEntity.java index b1ea8ff8d0..446d38801c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ListRefEdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ListRefEdEntity.java @@ -22,85 +22,95 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.onetomany; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.util.List; import org.hibernate.envers.Audited; /** * ReferencEd entity + * * @author Adam Warski (adam at warski dot org) */ @Entity public class ListRefEdEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToMany(mappedBy="reference") - private List reffering; + @Audited + @OneToMany(mappedBy = "reference") + private List reffering; - public ListRefEdEntity() { - } + public ListRefEdEntity() { + } - public ListRefEdEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public ListRefEdEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public ListRefEdEntity(String data) { - this.data = data; - } + public ListRefEdEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public List getReffering() { - return reffering; - } + public List getReffering() { + return reffering; + } - public void setReffering(List reffering) { - this.reffering = reffering; - } + public void setReffering(List reffering) { + this.reffering = reffering; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ListRefEdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ListRefEdEntity) ) { + return false; + } - ListRefEdEntity that = (ListRefEdEntity) o; + ListRefEdEntity that = (ListRefEdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ListRefEdEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "ListRefEdEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ListRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ListRefIngEntity.java index 49ab705301..e20c8974ca 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ListRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ListRefIngEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.onetomany; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToOne; @@ -30,77 +31,87 @@ import org.hibernate.envers.Audited; /** * ReferencIng entity + * * @author Adam Warski (adam at warski dot org) */ @Entity public class ListRefIngEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToOne - private ListRefEdEntity reference; + @Audited + @ManyToOne + private ListRefEdEntity reference; - public ListRefIngEntity() { } + public ListRefIngEntity() { + } - public ListRefIngEntity(Integer id, String data, ListRefEdEntity reference) { - this.id = id; - this.data = data; - this.reference = reference; - } + public ListRefIngEntity(Integer id, String data, ListRefEdEntity reference) { + this.id = id; + this.data = data; + this.reference = reference; + } - public ListRefIngEntity(String data, ListRefEdEntity reference) { - this.data = data; - this.reference = reference; - } + public ListRefIngEntity(String data, ListRefEdEntity reference) { + this.data = data; + this.reference = reference; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public ListRefEdEntity getReference() { - return reference; - } + public ListRefEdEntity getReference() { + return reference; + } - public void setReference(ListRefEdEntity reference) { - this.reference = reference; - } + public void setReference(ListRefEdEntity reference) { + this.reference = reference; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ListRefIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ListRefIngEntity) ) { + return false; + } - ListRefIngEntity that = (ListRefIngEntity) o; + ListRefIngEntity that = (ListRefIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ListRefIngEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "ListRefIngEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/SetRefEdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/SetRefEdEntity.java index ce479b3ca7..1551ee9f77 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/SetRefEdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/SetRefEdEntity.java @@ -22,85 +22,95 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.onetomany; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.util.Set; import org.hibernate.envers.Audited; /** * ReferencEd entity + * * @author Adam Warski (adam at warski dot org) */ @Entity public class SetRefEdEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToMany(mappedBy="reference") - private Set reffering; + @Audited + @OneToMany(mappedBy = "reference") + private Set reffering; - public SetRefEdEntity() { - } + public SetRefEdEntity() { + } - public SetRefEdEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public SetRefEdEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public SetRefEdEntity(String data) { - this.data = data; - } + public SetRefEdEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Set getReffering() { - return reffering; - } + public Set getReffering() { + return reffering; + } - public void setReffering(Set reffering) { - this.reffering = reffering; - } + public void setReffering(Set reffering) { + this.reffering = reffering; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SetRefEdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SetRefEdEntity) ) { + return false; + } - SetRefEdEntity that = (SetRefEdEntity) o; + SetRefEdEntity that = (SetRefEdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetRefEdEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "SetRefEdEntity(id = " + id + ", data = " + data + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/SetRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/SetRefIngEntity.java index 0d03282fc4..11d96f0b9e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/SetRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/SetRefIngEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.onetomany; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToOne; @@ -30,82 +31,92 @@ import org.hibernate.envers.Audited; /** * ReferencIng entity + * * @author Adam Warski (adam at warski dot org) */ @Entity public class SetRefIngEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToOne - private SetRefEdEntity reference; + @Audited + @ManyToOne + private SetRefEdEntity reference; - public SetRefIngEntity() { } + public SetRefIngEntity() { + } - public SetRefIngEntity(Integer id, String data, SetRefEdEntity reference) { - this.id = id; - this.data = data; - this.reference = reference; - } + public SetRefIngEntity(Integer id, String data, SetRefEdEntity reference) { + this.id = id; + this.data = data; + this.reference = reference; + } - public SetRefIngEntity(String data, SetRefEdEntity reference) { - this.data = data; - this.reference = reference; - } + public SetRefIngEntity(String data, SetRefEdEntity reference) { + this.data = data; + this.reference = reference; + } - public SetRefIngEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public SetRefIngEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public SetRefEdEntity getReference() { - return reference; - } + public SetRefEdEntity getReference() { + return reference; + } - public void setReference(SetRefEdEntity reference) { - this.reference = reference; - } + public void setReference(SetRefEdEntity reference) { + this.reference = reference; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SetRefIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SetRefIngEntity) ) { + return false; + } - SetRefIngEntity that = (SetRefIngEntity) o; + SetRefIngEntity that = (SetRefIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetRefIngEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "SetRefIngEntity(id = " + id + ", data = " + data + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/DoubleListJoinColumnBidirectionalRefEdEntity1.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/DoubleListJoinColumnBidirectionalRefEdEntity1.java index e159870ce7..707e9a8889 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/DoubleListJoinColumnBidirectionalRefEdEntity1.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/DoubleListJoinColumnBidirectionalRefEdEntity1.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.entities.onetomany.detached; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -11,80 +12,95 @@ import org.hibernate.envers.Audited; /** * Entity for {@link org.hibernate.envers.test.integration.onetomany.detached.DoubleJoinColumnBidirectionalList} test. * Owned side of the first relation. + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "DoubleJoinColBiRefEd1") @Audited public class DoubleListJoinColumnBidirectionalRefEdEntity1 { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String data; + private String data; - @ManyToOne - @JoinColumn(name = "some_join_column_1", insertable = false, updatable = false) - private DoubleListJoinColumnBidirectionalRefIngEntity owner; + @ManyToOne + @JoinColumn(name = "some_join_column_1", insertable = false, updatable = false) + private DoubleListJoinColumnBidirectionalRefIngEntity owner; - public DoubleListJoinColumnBidirectionalRefEdEntity1() { } + public DoubleListJoinColumnBidirectionalRefEdEntity1() { + } - public DoubleListJoinColumnBidirectionalRefEdEntity1(Integer id, String data, DoubleListJoinColumnBidirectionalRefIngEntity owner) { - this.id = id; - this.data = data; - this.owner = owner; - } + public DoubleListJoinColumnBidirectionalRefEdEntity1( + Integer id, + String data, + DoubleListJoinColumnBidirectionalRefIngEntity owner) { + this.id = id; + this.data = data; + this.owner = owner; + } - public DoubleListJoinColumnBidirectionalRefEdEntity1(String data, DoubleListJoinColumnBidirectionalRefIngEntity owner) { - this.data = data; - this.owner = owner; - } + public DoubleListJoinColumnBidirectionalRefEdEntity1( + String data, + DoubleListJoinColumnBidirectionalRefIngEntity owner) { + this.data = data; + this.owner = owner; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public DoubleListJoinColumnBidirectionalRefIngEntity getOwner() { - return owner; - } + public DoubleListJoinColumnBidirectionalRefIngEntity getOwner() { + return owner; + } - public void setOwner(DoubleListJoinColumnBidirectionalRefIngEntity owner) { - this.owner = owner; - } + public void setOwner(DoubleListJoinColumnBidirectionalRefIngEntity owner) { + this.owner = owner; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof DoubleListJoinColumnBidirectionalRefEdEntity1)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof DoubleListJoinColumnBidirectionalRefEdEntity1) ) { + return false; + } - DoubleListJoinColumnBidirectionalRefEdEntity1 that = (DoubleListJoinColumnBidirectionalRefEdEntity1) o; + DoubleListJoinColumnBidirectionalRefEdEntity1 that = (DoubleListJoinColumnBidirectionalRefEdEntity1) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - //noinspection RedundantIfStatement - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "DoubleListJoinColumnBidirectionalRefIngEntity1(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "DoubleListJoinColumnBidirectionalRefIngEntity1(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/DoubleListJoinColumnBidirectionalRefEdEntity2.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/DoubleListJoinColumnBidirectionalRefEdEntity2.java index df19877308..8d2103dbe1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/DoubleListJoinColumnBidirectionalRefEdEntity2.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/DoubleListJoinColumnBidirectionalRefEdEntity2.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.entities.onetomany.detached; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -11,80 +12,95 @@ import org.hibernate.envers.Audited; /** * Entity for {@link org.hibernate.envers.test.integration.onetomany.detached.DoubleJoinColumnBidirectionalList} test. * Owned side of the second relation. + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "DoubleJoinColBiRefEd2") @Audited public class DoubleListJoinColumnBidirectionalRefEdEntity2 { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String data; + private String data; - @ManyToOne - @JoinColumn(name = "some_join_column_2", insertable = false, updatable = false) - private DoubleListJoinColumnBidirectionalRefIngEntity owner; + @ManyToOne + @JoinColumn(name = "some_join_column_2", insertable = false, updatable = false) + private DoubleListJoinColumnBidirectionalRefIngEntity owner; - public DoubleListJoinColumnBidirectionalRefEdEntity2() { } + public DoubleListJoinColumnBidirectionalRefEdEntity2() { + } - public DoubleListJoinColumnBidirectionalRefEdEntity2(Integer id, String data, DoubleListJoinColumnBidirectionalRefIngEntity owner) { - this.id = id; - this.data = data; - this.owner = owner; - } + public DoubleListJoinColumnBidirectionalRefEdEntity2( + Integer id, + String data, + DoubleListJoinColumnBidirectionalRefIngEntity owner) { + this.id = id; + this.data = data; + this.owner = owner; + } - public DoubleListJoinColumnBidirectionalRefEdEntity2(String data, DoubleListJoinColumnBidirectionalRefIngEntity owner) { - this.data = data; - this.owner = owner; - } + public DoubleListJoinColumnBidirectionalRefEdEntity2( + String data, + DoubleListJoinColumnBidirectionalRefIngEntity owner) { + this.data = data; + this.owner = owner; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public DoubleListJoinColumnBidirectionalRefIngEntity getOwner() { - return owner; - } + public DoubleListJoinColumnBidirectionalRefIngEntity getOwner() { + return owner; + } - public void setOwner(DoubleListJoinColumnBidirectionalRefIngEntity owner) { - this.owner = owner; - } + public void setOwner(DoubleListJoinColumnBidirectionalRefIngEntity owner) { + this.owner = owner; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof DoubleListJoinColumnBidirectionalRefEdEntity2)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof DoubleListJoinColumnBidirectionalRefEdEntity2) ) { + return false; + } - DoubleListJoinColumnBidirectionalRefEdEntity2 that = (DoubleListJoinColumnBidirectionalRefEdEntity2) o; + DoubleListJoinColumnBidirectionalRefEdEntity2 that = (DoubleListJoinColumnBidirectionalRefEdEntity2) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - //noinspection RedundantIfStatement - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "DoubleListJoinColumnBidirectionalRefIngEntity2(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "DoubleListJoinColumnBidirectionalRefIngEntity2(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/DoubleListJoinColumnBidirectionalRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/DoubleListJoinColumnBidirectionalRefIngEntity.java index 89a8682e84..9d787f299d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/DoubleListJoinColumnBidirectionalRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/DoubleListJoinColumnBidirectionalRefIngEntity.java @@ -1,12 +1,13 @@ package org.hibernate.envers.test.entities.onetomany.detached; -import java.util.ArrayList; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; +import java.util.ArrayList; +import java.util.List; import org.hibernate.envers.AuditMappedBy; import org.hibernate.envers.Audited; @@ -14,92 +15,102 @@ import org.hibernate.envers.Audited; /** * Entity for {@link org.hibernate.envers.test.integration.onetomany.detached.DoubleJoinColumnBidirectionalList} test. * Owning side of the relations. + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "DoubleJoinColBiRefIng") @Audited public class DoubleListJoinColumnBidirectionalRefIngEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String data; + private String data; - @OneToMany - @JoinColumn(name = "some_join_column_1") - @AuditMappedBy(mappedBy = "owner") - private List references1 = new ArrayList(); + @OneToMany + @JoinColumn(name = "some_join_column_1") + @AuditMappedBy(mappedBy = "owner") + private List references1 = new ArrayList(); - @OneToMany - @JoinColumn(name = "some_join_column_2") - @AuditMappedBy(mappedBy = "owner") - private List references2 = new ArrayList(); + @OneToMany + @JoinColumn(name = "some_join_column_2") + @AuditMappedBy(mappedBy = "owner") + private List references2 = new ArrayList(); - public DoubleListJoinColumnBidirectionalRefIngEntity() { } + public DoubleListJoinColumnBidirectionalRefIngEntity() { + } - public DoubleListJoinColumnBidirectionalRefIngEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public DoubleListJoinColumnBidirectionalRefIngEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public DoubleListJoinColumnBidirectionalRefIngEntity(String data) { - this(null, data); - } + public DoubleListJoinColumnBidirectionalRefIngEntity(String data) { + this( null, data ); + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public List getReferences1() { - return references1; - } + public List getReferences1() { + return references1; + } - public void setReferences1(List references1) { - this.references1 = references1; - } + public void setReferences1(List references1) { + this.references1 = references1; + } - public List getReferences2() { - return references2; - } + public List getReferences2() { + return references2; + } - public void setReferences2(List references2) { - this.references2 = references2; - } + public void setReferences2(List references2) { + this.references2 = references2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof DoubleListJoinColumnBidirectionalRefIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof DoubleListJoinColumnBidirectionalRefIngEntity) ) { + return false; + } - DoubleListJoinColumnBidirectionalRefIngEntity that = (DoubleListJoinColumnBidirectionalRefIngEntity) o; + DoubleListJoinColumnBidirectionalRefIngEntity that = (DoubleListJoinColumnBidirectionalRefIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - //noinspection RedundantIfStatement - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "DoubleListJoinColumnBidirectionalRefIngEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "DoubleListJoinColumnBidirectionalRefIngEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/DoubleSetRefCollEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/DoubleSetRefCollEntity.java index bdb30bccbd..4f2290cf2a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/DoubleSetRefCollEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/DoubleSetRefCollEntity.java @@ -22,101 +22,111 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.onetomany.detached; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinTable; import javax.persistence.OneToMany; +import java.util.Set; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.StrTestEntity; /** * Set collection of references entity + * * @author Adam Warski (adam at warski dot org) */ @Entity public class DoubleSetRefCollEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToMany - @JoinTable(name = "DOUBLE_STR_1") - private Set collection; + @Audited + @OneToMany + @JoinTable(name = "DOUBLE_STR_1") + private Set collection; - @Audited - @OneToMany - @JoinTable(name = "DOUBLE_STR_2") - private Set collection2; + @Audited + @OneToMany + @JoinTable(name = "DOUBLE_STR_2") + private Set collection2; - public DoubleSetRefCollEntity() { - } + public DoubleSetRefCollEntity() { + } - public DoubleSetRefCollEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public DoubleSetRefCollEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public DoubleSetRefCollEntity(String data) { - this.data = data; - } + public DoubleSetRefCollEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Set getCollection() { - return collection; - } + public Set getCollection() { + return collection; + } - public void setCollection(Set collection) { - this.collection = collection; - } + public void setCollection(Set collection) { + this.collection = collection; + } - public Set getCollection2() { - return collection2; - } + public Set getCollection2() { + return collection2; + } - public void setCollection2(Set collection2) { - this.collection2 = collection2; - } + public void setCollection2(Set collection2) { + this.collection2 = collection2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof DoubleSetRefCollEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof DoubleSetRefCollEntity) ) { + return false; + } - DoubleSetRefCollEntity that = (DoubleSetRefCollEntity) o; + DoubleSetRefCollEntity that = (DoubleSetRefCollEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "DoubleSetRefEdEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "DoubleSetRefEdEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/IndexedListJoinColumnBidirectionalRefEdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/IndexedListJoinColumnBidirectionalRefEdEntity.java index b53e4056a8..57a6fd3a80 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/IndexedListJoinColumnBidirectionalRefEdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/IndexedListJoinColumnBidirectionalRefEdEntity.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.entities.onetomany.detached; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -12,91 +13,106 @@ import org.hibernate.envers.Audited; /** * Entity for {@link org.hibernate.envers.test.integration.onetomany.detached.IndexedJoinColumnBidirectionalList} test. * Owned side of the relation. + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "IdxListJoinColBiRefEd") @Audited public class IndexedListJoinColumnBidirectionalRefEdEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String data; + private String data; - @Column(name = "indexed_index", insertable = false, updatable = false) - private Integer position; + @Column(name = "indexed_index", insertable = false, updatable = false) + private Integer position; - @ManyToOne - @JoinColumn(name = "indexed_join_column", insertable = false, updatable = false) - private IndexedListJoinColumnBidirectionalRefIngEntity owner; + @ManyToOne + @JoinColumn(name = "indexed_join_column", insertable = false, updatable = false) + private IndexedListJoinColumnBidirectionalRefIngEntity owner; - public IndexedListJoinColumnBidirectionalRefEdEntity() { } + public IndexedListJoinColumnBidirectionalRefEdEntity() { + } - public IndexedListJoinColumnBidirectionalRefEdEntity(Integer id, String data, IndexedListJoinColumnBidirectionalRefIngEntity owner) { - this.id = id; - this.data = data; - this.owner = owner; - } + public IndexedListJoinColumnBidirectionalRefEdEntity( + Integer id, + String data, + IndexedListJoinColumnBidirectionalRefIngEntity owner) { + this.id = id; + this.data = data; + this.owner = owner; + } - public IndexedListJoinColumnBidirectionalRefEdEntity(String data, IndexedListJoinColumnBidirectionalRefIngEntity owner) { - this.data = data; - this.owner = owner; - } + public IndexedListJoinColumnBidirectionalRefEdEntity( + String data, + IndexedListJoinColumnBidirectionalRefIngEntity owner) { + this.data = data; + this.owner = owner; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public IndexedListJoinColumnBidirectionalRefIngEntity getOwner() { - return owner; - } + public IndexedListJoinColumnBidirectionalRefIngEntity getOwner() { + return owner; + } - public void setOwner(IndexedListJoinColumnBidirectionalRefIngEntity owner) { - this.owner = owner; - } + public void setOwner(IndexedListJoinColumnBidirectionalRefIngEntity owner) { + this.owner = owner; + } - public Integer getPosition() { - return position; - } + public Integer getPosition() { + return position; + } - public void setPosition(Integer position) { - this.position = position; - } + public void setPosition(Integer position) { + this.position = position; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof IndexedListJoinColumnBidirectionalRefEdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof IndexedListJoinColumnBidirectionalRefEdEntity) ) { + return false; + } - IndexedListJoinColumnBidirectionalRefEdEntity that = (IndexedListJoinColumnBidirectionalRefEdEntity) o; + IndexedListJoinColumnBidirectionalRefEdEntity that = (IndexedListJoinColumnBidirectionalRefEdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - //noinspection RedundantIfStatement - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "IndexedListJoinColumnBidirectionalRefEdEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "IndexedListJoinColumnBidirectionalRefEdEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/IndexedListJoinColumnBidirectionalRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/IndexedListJoinColumnBidirectionalRefIngEntity.java index df5e1869ff..712838b824 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/IndexedListJoinColumnBidirectionalRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/IndexedListJoinColumnBidirectionalRefIngEntity.java @@ -1,13 +1,14 @@ package org.hibernate.envers.test.entities.onetomany.detached; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import org.hibernate.annotations.IndexColumn; import org.hibernate.envers.AuditMappedBy; @@ -16,82 +17,97 @@ import org.hibernate.envers.Audited; /** * Entity for {@link org.hibernate.envers.test.integration.onetomany.detached.IndexedJoinColumnBidirectionalList} test. * Owning side of the relation. + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "IdxListJoinColBiRefIng") @Audited public class IndexedListJoinColumnBidirectionalRefIngEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String data; + private String data; - @OneToMany - @JoinColumn(name = "indexed_join_column") - @IndexColumn(name = "indexed_index") - @AuditMappedBy(mappedBy = "owner", positionMappedBy = "position") - private List references; + @OneToMany + @JoinColumn(name = "indexed_join_column") + @IndexColumn(name = "indexed_index") + @AuditMappedBy(mappedBy = "owner", positionMappedBy = "position") + private List references; - public IndexedListJoinColumnBidirectionalRefIngEntity() { } + public IndexedListJoinColumnBidirectionalRefIngEntity() { + } - public IndexedListJoinColumnBidirectionalRefIngEntity(Integer id, String data, IndexedListJoinColumnBidirectionalRefEdEntity... references) { - this.id = id; - this.data = data; - this.references = new ArrayList(); - this.references.addAll(Arrays.asList(references)); - } + public IndexedListJoinColumnBidirectionalRefIngEntity( + Integer id, + String data, + IndexedListJoinColumnBidirectionalRefEdEntity... references) { + this.id = id; + this.data = data; + this.references = new ArrayList(); + this.references.addAll( Arrays.asList( references ) ); + } - public IndexedListJoinColumnBidirectionalRefIngEntity(String data, IndexedListJoinColumnBidirectionalRefEdEntity... references) { - this(null, data, references); - } + public IndexedListJoinColumnBidirectionalRefIngEntity( + String data, + IndexedListJoinColumnBidirectionalRefEdEntity... references) { + this( null, data, references ); + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public List getReferences() { - return references; - } + public List getReferences() { + return references; + } - public void setReferences(List references) { - this.references = references; - } + public void setReferences(List references) { + this.references = references; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof IndexedListJoinColumnBidirectionalRefIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof IndexedListJoinColumnBidirectionalRefIngEntity) ) { + return false; + } - IndexedListJoinColumnBidirectionalRefIngEntity that = (IndexedListJoinColumnBidirectionalRefIngEntity) o; + IndexedListJoinColumnBidirectionalRefIngEntity that = (IndexedListJoinColumnBidirectionalRefIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - //noinspection RedundantIfStatement - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "IndexedListJoinColumnBidirectionalRefIngEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "IndexedListJoinColumnBidirectionalRefIngEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalInheritanceRefEdChildEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalInheritanceRefEdChildEntity.java index 3ffa9004be..7d315ac867 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalInheritanceRefEdChildEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalInheritanceRefEdChildEntity.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.entities.onetomany.detached; + import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; import javax.persistence.Table; @@ -8,58 +9,76 @@ import org.hibernate.envers.Audited; /** * Entity for {@link org.hibernate.envers.test.integration.onetomany.detached.JoinColumnBidirectionalListWithInheritance} test. * Owned child side of the relation. + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "ListJoinColBiInhRefEdChild") @DiscriminatorValue("2") @Audited -public class ListJoinColumnBidirectionalInheritanceRefEdChildEntity extends ListJoinColumnBidirectionalInheritanceRefEdParentEntity { - private String childData; +public class ListJoinColumnBidirectionalInheritanceRefEdChildEntity + extends ListJoinColumnBidirectionalInheritanceRefEdParentEntity { + private String childData; - public ListJoinColumnBidirectionalInheritanceRefEdChildEntity() { } + public ListJoinColumnBidirectionalInheritanceRefEdChildEntity() { + } - public ListJoinColumnBidirectionalInheritanceRefEdChildEntity(Integer id, String parentData, ListJoinColumnBidirectionalInheritanceRefIngEntity owner, String childData) { - super(id, parentData, owner); - this.childData = childData; - } + public ListJoinColumnBidirectionalInheritanceRefEdChildEntity( + Integer id, + String parentData, + ListJoinColumnBidirectionalInheritanceRefIngEntity owner, + String childData) { + super( id, parentData, owner ); + this.childData = childData; + } - public ListJoinColumnBidirectionalInheritanceRefEdChildEntity(String parentData, ListJoinColumnBidirectionalInheritanceRefIngEntity owner, String childData) { - super(parentData, owner); - this.childData = childData; - } + public ListJoinColumnBidirectionalInheritanceRefEdChildEntity( + String parentData, + ListJoinColumnBidirectionalInheritanceRefIngEntity owner, + String childData) { + super( parentData, owner ); + this.childData = childData; + } - public String getChildData() { - return childData; - } + public String getChildData() { + return childData; + } - public void setChildData(String childData) { - this.childData = childData; - } + public void setChildData(String childData) { + this.childData = childData; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - if (!super.equals(o)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ListJoinColumnBidirectionalInheritanceRefEdChildEntity that = (ListJoinColumnBidirectionalInheritanceRefEdChildEntity) o; + ListJoinColumnBidirectionalInheritanceRefEdChildEntity that = (ListJoinColumnBidirectionalInheritanceRefEdChildEntity) o; - //noinspection RedundantIfStatement - if (childData != null ? !childData.equals(that.childData) : that.childData != null) return false; + //noinspection RedundantIfStatement + if ( childData != null ? !childData.equals( that.childData ) : that.childData != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (childData != null ? childData.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (childData != null ? childData.hashCode() : 0); + return result; + } - public String toString() { - return "ListJoinColumnBidirectionalInheritanceRefEdChildEntity(id = " + getId() + - ", parentData = " + getParentData() + ", childData = " + childData + ")"; - } + public String toString() { + return "ListJoinColumnBidirectionalInheritanceRefEdChildEntity(id = " + getId() + + ", parentData = " + getParentData() + ", childData = " + childData + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalInheritanceRefEdParentEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalInheritanceRefEdParentEntity.java index 801f8648a9..29698315a8 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalInheritanceRefEdParentEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalInheritanceRefEdParentEntity.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.entities.onetomany.detached; + import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; import javax.persistence.DiscriminatorValue; @@ -16,6 +17,7 @@ import org.hibernate.envers.Audited; /** * Entity for {@link org.hibernate.envers.test.integration.onetomany.detached.JoinColumnBidirectionalListWithInheritance} test. * Owned parent side of the relation. + * * @author Adam Warski (adam at warski dot org) */ @Entity @@ -25,74 +27,88 @@ import org.hibernate.envers.Audited; @DiscriminatorValue("1") @Audited public class ListJoinColumnBidirectionalInheritanceRefEdParentEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String parentData; + private String parentData; - @ManyToOne - @JoinColumn(name = "some_join_column", insertable = false, updatable = false) - private ListJoinColumnBidirectionalInheritanceRefIngEntity owner; + @ManyToOne + @JoinColumn(name = "some_join_column", insertable = false, updatable = false) + private ListJoinColumnBidirectionalInheritanceRefIngEntity owner; - public ListJoinColumnBidirectionalInheritanceRefEdParentEntity() { } + public ListJoinColumnBidirectionalInheritanceRefEdParentEntity() { + } - public ListJoinColumnBidirectionalInheritanceRefEdParentEntity(Integer id, String parentData, ListJoinColumnBidirectionalInheritanceRefIngEntity owner) { - this.id = id; - this.parentData = parentData; - this.owner = owner; - } + public ListJoinColumnBidirectionalInheritanceRefEdParentEntity( + Integer id, + String parentData, + ListJoinColumnBidirectionalInheritanceRefIngEntity owner) { + this.id = id; + this.parentData = parentData; + this.owner = owner; + } - public ListJoinColumnBidirectionalInheritanceRefEdParentEntity(String parentData, ListJoinColumnBidirectionalInheritanceRefIngEntity owner) { - this.parentData = parentData; - this.owner = owner; - } + public ListJoinColumnBidirectionalInheritanceRefEdParentEntity( + String parentData, + ListJoinColumnBidirectionalInheritanceRefIngEntity owner) { + this.parentData = parentData; + this.owner = owner; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public ListJoinColumnBidirectionalInheritanceRefIngEntity getOwner() { - return owner; - } + public ListJoinColumnBidirectionalInheritanceRefIngEntity getOwner() { + return owner; + } - public void setOwner(ListJoinColumnBidirectionalInheritanceRefIngEntity owner) { - this.owner = owner; - } + public void setOwner(ListJoinColumnBidirectionalInheritanceRefIngEntity owner) { + this.owner = owner; + } - public String getParentData() { - return parentData; - } + public String getParentData() { + return parentData; + } - public void setParentData(String parentData) { - this.parentData = parentData; - } + public void setParentData(String parentData) { + this.parentData = parentData; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ListJoinColumnBidirectionalInheritanceRefEdParentEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ListJoinColumnBidirectionalInheritanceRefEdParentEntity) ) { + return false; + } - ListJoinColumnBidirectionalInheritanceRefEdParentEntity that = (ListJoinColumnBidirectionalInheritanceRefEdParentEntity) o; + ListJoinColumnBidirectionalInheritanceRefEdParentEntity that = (ListJoinColumnBidirectionalInheritanceRefEdParentEntity) o; - if (parentData != null ? !parentData.equals(that.parentData) : that.parentData != null) return false; - //noinspection RedundantIfStatement - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( parentData != null ? !parentData.equals( that.parentData ) : that.parentData != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (parentData != null ? parentData.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (parentData != null ? parentData.hashCode() : 0); + return result; + } - public String toString() { - return "ListJoinColumnBidirectionalInheritanceRefEdParentEntity(id = " + id + ", parentData = " + parentData + ")"; - } + public String toString() { + return "ListJoinColumnBidirectionalInheritanceRefEdParentEntity(id = " + id + ", parentData = " + parentData + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalInheritanceRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalInheritanceRefIngEntity.java index ede9812a4d..04a02eebd3 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalInheritanceRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalInheritanceRefIngEntity.java @@ -1,13 +1,14 @@ package org.hibernate.envers.test.entities.onetomany.detached; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import org.hibernate.envers.AuditMappedBy; import org.hibernate.envers.Audited; @@ -15,81 +16,96 @@ import org.hibernate.envers.Audited; /** * Entity for {@link org.hibernate.envers.test.integration.onetomany.detached.JoinColumnBidirectionalListWithInheritance} test. * Owning side of the relation. + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "ListJoinColBiInhRefIng") @Audited public class ListJoinColumnBidirectionalInheritanceRefIngEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String data; + private String data; - @OneToMany - @JoinColumn(name = "some_join_column") - @AuditMappedBy(mappedBy = "owner") - private List references; + @OneToMany + @JoinColumn(name = "some_join_column") + @AuditMappedBy(mappedBy = "owner") + private List references; - public ListJoinColumnBidirectionalInheritanceRefIngEntity() { } + public ListJoinColumnBidirectionalInheritanceRefIngEntity() { + } - public ListJoinColumnBidirectionalInheritanceRefIngEntity(Integer id, String data, ListJoinColumnBidirectionalInheritanceRefEdParentEntity... references) { - this.id = id; - this.data = data; - this.references = new ArrayList(); - this.references.addAll(Arrays.asList(references)); - } + public ListJoinColumnBidirectionalInheritanceRefIngEntity( + Integer id, + String data, + ListJoinColumnBidirectionalInheritanceRefEdParentEntity... references) { + this.id = id; + this.data = data; + this.references = new ArrayList(); + this.references.addAll( Arrays.asList( references ) ); + } - public ListJoinColumnBidirectionalInheritanceRefIngEntity(String data, ListJoinColumnBidirectionalInheritanceRefEdParentEntity... references) { - this(null, data, references); - } + public ListJoinColumnBidirectionalInheritanceRefIngEntity( + String data, + ListJoinColumnBidirectionalInheritanceRefEdParentEntity... references) { + this( null, data, references ); + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public List getReferences() { - return references; - } + public List getReferences() { + return references; + } - public void setReferences(List references) { - this.references = references; - } + public void setReferences(List references) { + this.references = references; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ListJoinColumnBidirectionalInheritanceRefIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ListJoinColumnBidirectionalInheritanceRefIngEntity) ) { + return false; + } - ListJoinColumnBidirectionalInheritanceRefIngEntity that = (ListJoinColumnBidirectionalInheritanceRefIngEntity) o; + ListJoinColumnBidirectionalInheritanceRefIngEntity that = (ListJoinColumnBidirectionalInheritanceRefIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - //noinspection RedundantIfStatement - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ListJoinColumnBidirectionalInheritanceRefIngEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "ListJoinColumnBidirectionalInheritanceRefIngEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalRefEdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalRefEdEntity.java index eb41598caa..e5abbbb177 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalRefEdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalRefEdEntity.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.entities.onetomany.detached; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -11,80 +12,93 @@ import org.hibernate.envers.Audited; /** * Entity for {@link org.hibernate.envers.test.integration.onetomany.detached.JoinColumnBidirectionalList} test. * Owned side of the relation. + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "ListJoinColBiRefEd") @Audited public class ListJoinColumnBidirectionalRefEdEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String data; + private String data; - @ManyToOne - @JoinColumn(name = "some_join_column", insertable = false, updatable = false) - private ListJoinColumnBidirectionalRefIngEntity owner; + @ManyToOne + @JoinColumn(name = "some_join_column", insertable = false, updatable = false) + private ListJoinColumnBidirectionalRefIngEntity owner; - public ListJoinColumnBidirectionalRefEdEntity() { } + public ListJoinColumnBidirectionalRefEdEntity() { + } - public ListJoinColumnBidirectionalRefEdEntity(Integer id, String data, ListJoinColumnBidirectionalRefIngEntity owner) { - this.id = id; - this.data = data; - this.owner = owner; - } + public ListJoinColumnBidirectionalRefEdEntity( + Integer id, + String data, + ListJoinColumnBidirectionalRefIngEntity owner) { + this.id = id; + this.data = data; + this.owner = owner; + } - public ListJoinColumnBidirectionalRefEdEntity(String data, ListJoinColumnBidirectionalRefIngEntity owner) { - this.data = data; - this.owner = owner; - } + public ListJoinColumnBidirectionalRefEdEntity(String data, ListJoinColumnBidirectionalRefIngEntity owner) { + this.data = data; + this.owner = owner; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public ListJoinColumnBidirectionalRefIngEntity getOwner() { - return owner; - } + public ListJoinColumnBidirectionalRefIngEntity getOwner() { + return owner; + } - public void setOwner(ListJoinColumnBidirectionalRefIngEntity owner) { - this.owner = owner; - } + public void setOwner(ListJoinColumnBidirectionalRefIngEntity owner) { + this.owner = owner; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ListJoinColumnBidirectionalRefEdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ListJoinColumnBidirectionalRefEdEntity) ) { + return false; + } - ListJoinColumnBidirectionalRefEdEntity that = (ListJoinColumnBidirectionalRefEdEntity) o; + ListJoinColumnBidirectionalRefEdEntity that = (ListJoinColumnBidirectionalRefEdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - //noinspection RedundantIfStatement - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ListJoinColumnBidirectionalRefEdEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "ListJoinColumnBidirectionalRefEdEntity(id = " + id + ", data = " + data + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalRefIngEntity.java index f99a9900b0..dbd393ace4 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListJoinColumnBidirectionalRefIngEntity.java @@ -1,13 +1,14 @@ package org.hibernate.envers.test.entities.onetomany.detached; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import org.hibernate.envers.AuditMappedBy; import org.hibernate.envers.Audited; @@ -15,81 +16,94 @@ import org.hibernate.envers.Audited; /** * Entity for {@link org.hibernate.envers.test.integration.onetomany.detached.JoinColumnBidirectionalList} test. * Owning side of the relation. + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "ListJoinColBiRefIng") @Audited public class ListJoinColumnBidirectionalRefIngEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String data; + private String data; - @OneToMany - @JoinColumn(name = "some_join_column") - @AuditMappedBy(mappedBy = "owner") - private List references; + @OneToMany + @JoinColumn(name = "some_join_column") + @AuditMappedBy(mappedBy = "owner") + private List references; - public ListJoinColumnBidirectionalRefIngEntity() { } + public ListJoinColumnBidirectionalRefIngEntity() { + } - public ListJoinColumnBidirectionalRefIngEntity(Integer id, String data, ListJoinColumnBidirectionalRefEdEntity... references) { - this.id = id; - this.data = data; - this.references = new ArrayList(); - this.references.addAll(Arrays.asList(references)); - } + public ListJoinColumnBidirectionalRefIngEntity( + Integer id, + String data, + ListJoinColumnBidirectionalRefEdEntity... references) { + this.id = id; + this.data = data; + this.references = new ArrayList(); + this.references.addAll( Arrays.asList( references ) ); + } - public ListJoinColumnBidirectionalRefIngEntity(String data, ListJoinColumnBidirectionalRefEdEntity... references) { - this(null, data, references); - } + public ListJoinColumnBidirectionalRefIngEntity(String data, ListJoinColumnBidirectionalRefEdEntity... references) { + this( null, data, references ); + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public List getReferences() { - return references; - } + public List getReferences() { + return references; + } - public void setReferences(List references) { - this.references = references; - } + public void setReferences(List references) { + this.references = references; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ListJoinColumnBidirectionalRefIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ListJoinColumnBidirectionalRefIngEntity) ) { + return false; + } - ListJoinColumnBidirectionalRefIngEntity that = (ListJoinColumnBidirectionalRefIngEntity) o; + ListJoinColumnBidirectionalRefIngEntity that = (ListJoinColumnBidirectionalRefIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - //noinspection RedundantIfStatement - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ListJoinColumnBidirectionalRefIngEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "ListJoinColumnBidirectionalRefIngEntity(id = " + id + ", data = " + data + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListRefCollEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListRefCollEntity.java index dade398587..3ca3999d26 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListRefCollEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ListRefCollEntity.java @@ -22,86 +22,96 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.onetomany.detached; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.util.List; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.StrTestEntity; /** * Set collection of references entity + * * @author Adam Warski (adam at warski dot org) */ @Entity public class ListRefCollEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToMany - private List collection; + @Audited + @OneToMany + private List collection; - public ListRefCollEntity() { - } + public ListRefCollEntity() { + } - public ListRefCollEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public ListRefCollEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public ListRefCollEntity(String data) { - this.data = data; - } + public ListRefCollEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public List getCollection() { - return collection; - } + public List getCollection() { + return collection; + } - public void setCollection(List collection) { - this.collection = collection; - } + public void setCollection(List collection) { + this.collection = collection; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ListRefCollEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ListRefCollEntity) ) { + return false; + } - ListRefCollEntity that = (ListRefCollEntity) o; + ListRefCollEntity that = (ListRefCollEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetRefEdEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "SetRefEdEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/SetJoinColumnRefCollEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/SetJoinColumnRefCollEntity.java index 3c3ff051b2..171a245446 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/SetJoinColumnRefCollEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/SetJoinColumnRefCollEntity.java @@ -22,12 +22,13 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.onetomany.detached; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; +import java.util.Set; import org.hibernate.envers.AuditJoinTable; import org.hibernate.envers.Audited; @@ -35,79 +36,88 @@ import org.hibernate.envers.test.entities.StrTestEntity; /** * A detached relation to another entity, with a @OneToMany+@JoinColumn mapping. + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "SetJoinColRefColl") public class SetJoinColumnRefCollEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToMany - @JoinColumn(name = "SJCR_ID") - @AuditJoinTable(name = "SetJoinColRefColl_StrTest_AUD") - private Set collection; + @Audited + @OneToMany + @JoinColumn(name = "SJCR_ID") + @AuditJoinTable(name = "SetJoinColRefColl_StrTest_AUD") + private Set collection; - public SetJoinColumnRefCollEntity() { - } + public SetJoinColumnRefCollEntity() { + } - public SetJoinColumnRefCollEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public SetJoinColumnRefCollEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public SetJoinColumnRefCollEntity(String data) { - this.data = data; - } + public SetJoinColumnRefCollEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Set getCollection() { - return collection; - } + public Set getCollection() { + return collection; + } - public void setCollection(Set collection) { - this.collection = collection; - } + public void setCollection(Set collection) { + this.collection = collection; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SetJoinColumnRefCollEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SetJoinColumnRefCollEntity) ) { + return false; + } - SetJoinColumnRefCollEntity that = (SetJoinColumnRefCollEntity) o; + SetJoinColumnRefCollEntity that = (SetJoinColumnRefCollEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetJoinColumnRefCollEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "SetJoinColumnRefCollEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/SetRefCollEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/SetRefCollEntity.java index 5ae7ef49ab..17477d9c14 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/SetRefCollEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/SetRefCollEntity.java @@ -22,86 +22,96 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.onetomany.detached; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.util.Set; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.StrTestEntity; /** * Set collection of references entity + * * @author Adam Warski (adam at warski dot org) */ @Entity public class SetRefCollEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToMany - private Set collection; + @Audited + @OneToMany + private Set collection; - public SetRefCollEntity() { - } + public SetRefCollEntity() { + } - public SetRefCollEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public SetRefCollEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public SetRefCollEntity(String data) { - this.data = data; - } + public SetRefCollEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Set getCollection() { - return collection; - } + public Set getCollection() { + return collection; + } - public void setCollection(Set collection) { - this.collection = collection; - } + public void setCollection(Set collection) { + this.collection = collection; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SetRefCollEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SetRefCollEntity) ) { + return false; + } - SetRefCollEntity that = (SetRefCollEntity) o; + SetRefCollEntity that = (SetRefCollEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetRefEdEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "SetRefEdEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ids/SetRefCollEntityEmbId.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ids/SetRefCollEntityEmbId.java index 3261064e46..d96d0190ca 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ids/SetRefCollEntityEmbId.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ids/SetRefCollEntityEmbId.java @@ -22,11 +22,12 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.onetomany.detached.ids; -import java.util.Set; + import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.OneToMany; import javax.persistence.Table; +import java.util.Set; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.ids.EmbId; @@ -34,77 +35,86 @@ import org.hibernate.envers.test.entities.ids.EmbIdTestEntity; /** * Set collection of references entity + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "SetRefCollEmbId") public class SetRefCollEntityEmbId { - @EmbeddedId - private EmbId id; + @EmbeddedId + private EmbId id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToMany - private Set collection; + @Audited + @OneToMany + private Set collection; - public SetRefCollEntityEmbId() { - } + public SetRefCollEntityEmbId() { + } - public SetRefCollEntityEmbId(EmbId id, String data) { - this.id = id; - this.data = data; - } + public SetRefCollEntityEmbId(EmbId id, String data) { + this.id = id; + this.data = data; + } - public SetRefCollEntityEmbId(String data) { - this.data = data; - } + public SetRefCollEntityEmbId(String data) { + this.data = data; + } - public EmbId getId() { - return id; - } + public EmbId getId() { + return id; + } - public void setId(EmbId id) { - this.id = id; - } + public void setId(EmbId id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Set getCollection() { - return collection; - } + public Set getCollection() { + return collection; + } - public void setCollection(Set collection) { - this.collection = collection; - } + public void setCollection(Set collection) { + this.collection = collection; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SetRefCollEntityEmbId)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SetRefCollEntityEmbId) ) { + return false; + } - SetRefCollEntityEmbId that = (SetRefCollEntityEmbId) o; + SetRefCollEntityEmbId that = (SetRefCollEntityEmbId) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetRefCollEntityEmbId(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "SetRefCollEntityEmbId(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ids/SetRefCollEntityMulId.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ids/SetRefCollEntityMulId.java index 1234647dc3..28cfc0cb03 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ids/SetRefCollEntityMulId.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/ids/SetRefCollEntityMulId.java @@ -22,12 +22,13 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.onetomany.detached.ids; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.OneToMany; import javax.persistence.Table; +import java.util.Set; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.ids.MulId; @@ -35,92 +36,103 @@ import org.hibernate.envers.test.entities.ids.MulIdTestEntity; /** * Set collection of references entity + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "SetRefCollMulId") @IdClass(MulId.class) public class SetRefCollEntityMulId { - @Id - private Integer id1; + @Id + private Integer id1; - @Id - private Integer id2; + @Id + private Integer id2; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToMany - private Set collection; + @Audited + @OneToMany + private Set collection; - public SetRefCollEntityMulId() { - } + public SetRefCollEntityMulId() { + } - public SetRefCollEntityMulId(Integer id1, Integer id2, String data) { - this.id1 = id1; - this.id2 = id2; - this.data = data; - } + public SetRefCollEntityMulId(Integer id1, Integer id2, String data) { + this.id1 = id1; + this.id2 = id2; + this.data = data; + } - public SetRefCollEntityMulId(String data) { - this.data = data; - } + public SetRefCollEntityMulId(String data) { + this.data = data; + } - public Integer getId1() { - return id1; - } + public Integer getId1() { + return id1; + } - public void setId1(Integer id1) { - this.id1 = id1; - } + public void setId1(Integer id1) { + this.id1 = id1; + } - public Integer getId2() { - return id2; - } + public Integer getId2() { + return id2; + } - public void setId2(Integer id2) { - this.id2 = id2; - } + public void setId2(Integer id2) { + this.id2 = id2; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Set getCollection() { - return collection; - } + public Set getCollection() { + return collection; + } - public void setCollection(Set collection) { - this.collection = collection; - } + public void setCollection(Set collection) { + this.collection = collection; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SetRefCollEntityMulId)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SetRefCollEntityMulId) ) { + return false; + } - SetRefCollEntityMulId that = (SetRefCollEntityMulId) o; + SetRefCollEntityMulId that = (SetRefCollEntityMulId) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id1 != null ? !id1.equals(that.id1) : that.id1 != null) return false; - if (id2 != null ? !id2.equals(that.id2) : that.id2 != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id1 != null ? !id1.equals( that.id1 ) : that.id1 != null ) { + return false; + } + if ( id2 != null ? !id2.equals( that.id2 ) : that.id2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id1 != null ? id1.hashCode() : 0); - result = 31 * result + (id2 != null ? id2.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id1 != null ? id1.hashCode() : 0); + result = 31 * result + (id2 != null ? id2.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetRefCollEntityMulId(id1 = " + id1 + ", id2 = " + id2 + ", data = " + data + ")"; - } + public String toString() { + return "SetRefCollEntityMulId(id1 = " + id1 + ", id2 = " + id2 + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/inheritance/ChildIndexedListJoinColumnBidirectionalRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/inheritance/ChildIndexedListJoinColumnBidirectionalRefIngEntity.java index 08dc43820c..43780b43df 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/inheritance/ChildIndexedListJoinColumnBidirectionalRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/inheritance/ChildIndexedListJoinColumnBidirectionalRefIngEntity.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.entities.onetomany.detached.inheritance; + import javax.persistence.Entity; import javax.persistence.Table; @@ -7,56 +8,73 @@ import org.hibernate.envers.Audited; /** * Entity for {@link org.hibernate.envers.test.integration.onetomany.detached.InheritanceIndexedJoinColumnBidirectionalList} test. * Child, owning side of the relation. + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "ChildIdxJoinColBiRefIng") @Audited -public class ChildIndexedListJoinColumnBidirectionalRefIngEntity extends ParentIndexedListJoinColumnBidirectionalRefIngEntity { - private String data2; +public class ChildIndexedListJoinColumnBidirectionalRefIngEntity + extends ParentIndexedListJoinColumnBidirectionalRefIngEntity { + private String data2; - public ChildIndexedListJoinColumnBidirectionalRefIngEntity() { - } + public ChildIndexedListJoinColumnBidirectionalRefIngEntity() { + } - public ChildIndexedListJoinColumnBidirectionalRefIngEntity(Integer id, String data, String data2, ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity... references) { - super(id, data, references); - this.data2 = data2; - } + public ChildIndexedListJoinColumnBidirectionalRefIngEntity( + Integer id, + String data, + String data2, + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity... references) { + super( id, data, references ); + this.data2 = data2; + } - public ChildIndexedListJoinColumnBidirectionalRefIngEntity(String data, String data2, ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity... references) { - super(data, references); - this.data2 = data2; - } + public ChildIndexedListJoinColumnBidirectionalRefIngEntity( + String data, + String data2, + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity... references) { + super( data, references ); + this.data2 = data2; + } - public String getData2() { - return data2; - } + public String getData2() { + return data2; + } - public void setData2(String data2) { - this.data2 = data2; - } + public void setData2(String data2) { + this.data2 = data2; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ChildIndexedListJoinColumnBidirectionalRefIngEntity)) return false; - if (!super.equals(o)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ChildIndexedListJoinColumnBidirectionalRefIngEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ChildIndexedListJoinColumnBidirectionalRefIngEntity that = (ChildIndexedListJoinColumnBidirectionalRefIngEntity) o; + ChildIndexedListJoinColumnBidirectionalRefIngEntity that = (ChildIndexedListJoinColumnBidirectionalRefIngEntity) o; - if (data2 != null ? !data2.equals(that.data2) : that.data2 != null) return false; + if ( data2 != null ? !data2.equals( that.data2 ) : that.data2 != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (data2 != null ? data2.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (data2 != null ? data2.hashCode() : 0); + return result; + } - public String toString() { - return "ChildIndexedListJoinColumnBidirectionalRefIngEntity(id = " + getId() + ", data = " + getData() + ", data2 = " + data2 + ")"; - } + public String toString() { + return "ChildIndexedListJoinColumnBidirectionalRefIngEntity(id = " + getId() + ", data = " + getData() + ", data2 = " + data2 + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/inheritance/ParentIndexedListJoinColumnBidirectionalRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/inheritance/ParentIndexedListJoinColumnBidirectionalRefIngEntity.java index 6d9bbaf52d..2f37ff3986 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/inheritance/ParentIndexedListJoinColumnBidirectionalRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/inheritance/ParentIndexedListJoinColumnBidirectionalRefIngEntity.java @@ -1,7 +1,5 @@ package org.hibernate.envers.test.entities.onetomany.detached.inheritance; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -10,6 +8,9 @@ import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import org.hibernate.annotations.IndexColumn; import org.hibernate.envers.AuditMappedBy; @@ -18,6 +19,7 @@ import org.hibernate.envers.Audited; /** * Entity for {@link org.hibernate.envers.test.integration.onetomany.detached.InheritanceIndexedJoinColumnBidirectionalList} test. * Parent, owning side of the relation. + * * @author Adam Warski (adam at warski dot org) */ @Entity @@ -25,76 +27,90 @@ import org.hibernate.envers.Audited; @Table(name = "ParentIdxJoinColBiRefIng") @Inheritance(strategy = InheritanceType.JOINED) public abstract class ParentIndexedListJoinColumnBidirectionalRefIngEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String data; + private String data; - @OneToMany - @JoinColumn(name = "indexed_join_column") - @IndexColumn(name = "indexed_index") - @AuditMappedBy(mappedBy = "owner", positionMappedBy = "position") - private List references; + @OneToMany + @JoinColumn(name = "indexed_join_column") + @IndexColumn(name = "indexed_index") + @AuditMappedBy(mappedBy = "owner", positionMappedBy = "position") + private List references; - public ParentIndexedListJoinColumnBidirectionalRefIngEntity() { } + public ParentIndexedListJoinColumnBidirectionalRefIngEntity() { + } - public ParentIndexedListJoinColumnBidirectionalRefIngEntity(Integer id, String data, ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity... references) { - this.id = id; - this.data = data; - this.references = new ArrayList(); - this.references.addAll(Arrays.asList(references)); - } + public ParentIndexedListJoinColumnBidirectionalRefIngEntity( + Integer id, + String data, + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity... references) { + this.id = id; + this.data = data; + this.references = new ArrayList(); + this.references.addAll( Arrays.asList( references ) ); + } - public ParentIndexedListJoinColumnBidirectionalRefIngEntity(String data, ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity... references) { - this(null, data, references); - } + public ParentIndexedListJoinColumnBidirectionalRefIngEntity( + String data, + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity... references) { + this( null, data, references ); + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public List getReferences() { - return references; - } + public List getReferences() { + return references; + } - public void setReferences(List references) { - this.references = references; - } + public void setReferences(List references) { + this.references = references; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ParentIndexedListJoinColumnBidirectionalRefIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ParentIndexedListJoinColumnBidirectionalRefIngEntity) ) { + return false; + } - ParentIndexedListJoinColumnBidirectionalRefIngEntity that = (ParentIndexedListJoinColumnBidirectionalRefIngEntity) o; + ParentIndexedListJoinColumnBidirectionalRefIngEntity that = (ParentIndexedListJoinColumnBidirectionalRefIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - //noinspection RedundantIfStatement - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ParentIndexedListJoinColumnBidirectionalRefIngEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "ParentIndexedListJoinColumnBidirectionalRefIngEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/inheritance/ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/inheritance/ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.java index caacfedcd8..ee41f89d20 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/inheritance/ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/detached/inheritance/ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.entities.onetomany.detached.inheritance; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -12,91 +13,106 @@ import org.hibernate.envers.Audited; /** * Entity for {@link org.hibernate.envers.test.integration.onetomany.detached.InheritanceIndexedJoinColumnBidirectionalList} test. * Owned side of the relation. + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "ParOwnedIdxJoinColBiRefEd") @Audited public class ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String data; + private String data; - @Column(name = "indexed_index", insertable = false, updatable = false) - private Integer position; + @Column(name = "indexed_index", insertable = false, updatable = false) + private Integer position; - @ManyToOne - @JoinColumn(name = "indexed_join_column", insertable = false, updatable = false) - private ParentIndexedListJoinColumnBidirectionalRefIngEntity owner; + @ManyToOne + @JoinColumn(name = "indexed_join_column", insertable = false, updatable = false) + private ParentIndexedListJoinColumnBidirectionalRefIngEntity owner; - public ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity() { } + public ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity() { + } - public ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity(Integer id, String data, ParentIndexedListJoinColumnBidirectionalRefIngEntity owner) { - this.id = id; - this.data = data; - this.owner = owner; - } + public ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity( + Integer id, + String data, + ParentIndexedListJoinColumnBidirectionalRefIngEntity owner) { + this.id = id; + this.data = data; + this.owner = owner; + } - public ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity(String data, ParentIndexedListJoinColumnBidirectionalRefIngEntity owner) { - this.data = data; - this.owner = owner; - } + public ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity( + String data, + ParentIndexedListJoinColumnBidirectionalRefIngEntity owner) { + this.data = data; + this.owner = owner; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public ParentIndexedListJoinColumnBidirectionalRefIngEntity getOwner() { - return owner; - } + public ParentIndexedListJoinColumnBidirectionalRefIngEntity getOwner() { + return owner; + } - public void setOwner(ParentIndexedListJoinColumnBidirectionalRefIngEntity owner) { - this.owner = owner; - } + public void setOwner(ParentIndexedListJoinColumnBidirectionalRefIngEntity owner) { + this.owner = owner; + } - public Integer getPosition() { - return position; - } + public Integer getPosition() { + return position; + } - public void setPosition(Integer position) { - this.position = position; - } + public void setPosition(Integer position) { + this.position = position; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity) ) { + return false; + } - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity that = (ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity) o; + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity that = (ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - //noinspection RedundantIfStatement - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + //noinspection RedundantIfStatement + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ids/SetRefEdEmbIdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ids/SetRefEdEmbIdEntity.java index 4d3664456f..cb1bf03436 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ids/SetRefEdEmbIdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ids/SetRefEdEmbIdEntity.java @@ -22,86 +22,96 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.onetomany.ids; -import java.util.Set; + import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.OneToMany; +import java.util.Set; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.ids.EmbId; /** * ReferencEd entity + * * @author Adam Warski (adam at warski dot org) */ @Entity public class SetRefEdEmbIdEntity { - @EmbeddedId - private EmbId id; + @EmbeddedId + private EmbId id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToMany(mappedBy="reference") - private Set reffering; + @Audited + @OneToMany(mappedBy = "reference") + private Set reffering; - public SetRefEdEmbIdEntity() { - } + public SetRefEdEmbIdEntity() { + } - public SetRefEdEmbIdEntity(EmbId id, String data) { - this.id = id; - this.data = data; - } + public SetRefEdEmbIdEntity(EmbId id, String data) { + this.id = id; + this.data = data; + } - public SetRefEdEmbIdEntity(String data) { - this.data = data; - } + public SetRefEdEmbIdEntity(String data) { + this.data = data; + } - public EmbId getId() { - return id; - } + public EmbId getId() { + return id; + } - public void setId(EmbId id) { - this.id = id; - } + public void setId(EmbId id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Set getReffering() { - return reffering; - } + public Set getReffering() { + return reffering; + } - public void setReffering(Set reffering) { - this.reffering = reffering; - } + public void setReffering(Set reffering) { + this.reffering = reffering; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SetRefEdEmbIdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SetRefEdEmbIdEntity) ) { + return false; + } - SetRefEdEmbIdEntity that = (SetRefEdEmbIdEntity) o; + SetRefEdEmbIdEntity that = (SetRefEdEmbIdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetRefEdEmbIdEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "SetRefEdEmbIdEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ids/SetRefEdMulIdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ids/SetRefEdMulIdEntity.java index 833bd94f0e..810d6509b7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ids/SetRefEdMulIdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ids/SetRefEdMulIdEntity.java @@ -22,108 +22,120 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.onetomany.ids; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.OneToMany; +import java.util.Set; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.ids.MulId; /** * ReferencEd entity + * * @author Adam Warski (adam at warski dot org) */ @Entity @IdClass(MulId.class) public class SetRefEdMulIdEntity { - @Id - private Integer id1; + @Id + private Integer id1; - @Id - private Integer id2; + @Id + private Integer id2; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToMany(mappedBy="reference") - private Set reffering; + @Audited + @OneToMany(mappedBy = "reference") + private Set reffering; - public SetRefEdMulIdEntity() { - } + public SetRefEdMulIdEntity() { + } - public SetRefEdMulIdEntity(MulId id, String data) { - this.id1 = id.getId1(); - this.id2 = id.getId2(); - this.data = data; - } + public SetRefEdMulIdEntity(MulId id, String data) { + this.id1 = id.getId1(); + this.id2 = id.getId2(); + this.data = data; + } - public SetRefEdMulIdEntity(Integer id1, Integer id2, String data) { - this.id1 = id1; - this.id2 = id2; - this.data = data; - } + public SetRefEdMulIdEntity(Integer id1, Integer id2, String data) { + this.id1 = id1; + this.id2 = id2; + this.data = data; + } - public SetRefEdMulIdEntity(String data) { - this.data = data; - } + public SetRefEdMulIdEntity(String data) { + this.data = data; + } - public Integer getId1() { - return id1; - } + public Integer getId1() { + return id1; + } - public void setId1(Integer id1) { - this.id1 = id1; - } + public void setId1(Integer id1) { + this.id1 = id1; + } - public Integer getId2() { - return id2; - } + public Integer getId2() { + return id2; + } - public void setId2(Integer id2) { - this.id2 = id2; - } + public void setId2(Integer id2) { + this.id2 = id2; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Set getReffering() { - return reffering; - } + public Set getReffering() { + return reffering; + } - public void setReffering(Set reffering) { - this.reffering = reffering; - } + public void setReffering(Set reffering) { + this.reffering = reffering; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SetRefEdMulIdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SetRefEdMulIdEntity) ) { + return false; + } - SetRefEdMulIdEntity that = (SetRefEdMulIdEntity) o; + SetRefEdMulIdEntity that = (SetRefEdMulIdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id1 != null ? !id1.equals(that.id1) : that.id1 != null) return false; - if (id2 != null ? !id2.equals(that.id2) : that.id2 != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id1 != null ? !id1.equals( that.id1 ) : that.id1 != null ) { + return false; + } + if ( id2 != null ? !id2.equals( that.id2 ) : that.id2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id1 != null ? id1.hashCode() : 0); - result = 31 * result + (id2 != null ? id2.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id1 != null ? id1.hashCode() : 0); + result = 31 * result + (id2 != null ? id2.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetRefEdMulIdEntity(id1 = " + id1 + ", id2 = " + id2 + ", data = " + data + ")"; - } + public String toString() { + return "SetRefEdMulIdEntity(id1 = " + id1 + ", id2 = " + id2 + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ids/SetRefIngEmbIdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ids/SetRefIngEmbIdEntity.java index f3e15fe22e..1b2791629e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ids/SetRefIngEmbIdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ids/SetRefIngEmbIdEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.onetomany.ids; + import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.ManyToOne; @@ -31,77 +32,87 @@ import org.hibernate.envers.test.entities.ids.EmbId; /** * ReferencIng entity + * * @author Adam Warski (adam at warski dot org) */ @Entity public class SetRefIngEmbIdEntity { - @EmbeddedId - private EmbId id; + @EmbeddedId + private EmbId id; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToOne - private SetRefEdEmbIdEntity reference; + @Audited + @ManyToOne + private SetRefEdEmbIdEntity reference; - public SetRefIngEmbIdEntity() { } + public SetRefIngEmbIdEntity() { + } - public SetRefIngEmbIdEntity(EmbId id, String data, SetRefEdEmbIdEntity reference) { - this.id = id; - this.data = data; - this.reference = reference; - } + public SetRefIngEmbIdEntity(EmbId id, String data, SetRefEdEmbIdEntity reference) { + this.id = id; + this.data = data; + this.reference = reference; + } - public SetRefIngEmbIdEntity(String data, SetRefEdEmbIdEntity reference) { - this.data = data; - this.reference = reference; - } + public SetRefIngEmbIdEntity(String data, SetRefEdEmbIdEntity reference) { + this.data = data; + this.reference = reference; + } - public EmbId getId() { - return id; - } + public EmbId getId() { + return id; + } - public void setId(EmbId id) { - this.id = id; - } + public void setId(EmbId id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public SetRefEdEmbIdEntity getReference() { - return reference; - } + public SetRefEdEmbIdEntity getReference() { + return reference; + } - public void setReference(SetRefEdEmbIdEntity reference) { - this.reference = reference; - } + public void setReference(SetRefEdEmbIdEntity reference) { + this.reference = reference; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SetRefIngEmbIdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SetRefIngEmbIdEntity) ) { + return false; + } - SetRefIngEmbIdEntity that = (SetRefIngEmbIdEntity) o; + SetRefIngEmbIdEntity that = (SetRefIngEmbIdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetRefIngEmbIdEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "SetRefIngEmbIdEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ids/SetRefIngMulIdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ids/SetRefIngMulIdEntity.java index e4ffefcd16..a02967d611 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ids/SetRefIngMulIdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetomany/ids/SetRefIngMulIdEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.onetomany.ids; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; @@ -32,99 +33,111 @@ import org.hibernate.envers.test.entities.ids.MulId; /** * ReferencIng entity + * * @author Adam Warski (adam at warski dot org) */ @Entity @IdClass(MulId.class) public class SetRefIngMulIdEntity { - @Id - private Integer id1; + @Id + private Integer id1; - @Id - private Integer id2; + @Id + private Integer id2; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToOne - private SetRefEdMulIdEntity reference; + @Audited + @ManyToOne + private SetRefEdMulIdEntity reference; - public SetRefIngMulIdEntity() { } + public SetRefIngMulIdEntity() { + } - public SetRefIngMulIdEntity(MulId id, String data, SetRefEdMulIdEntity reference) { - this.id1 = id.getId1(); - this.id2 = id.getId2(); - this.data = data; - this.reference = reference; - } + public SetRefIngMulIdEntity(MulId id, String data, SetRefEdMulIdEntity reference) { + this.id1 = id.getId1(); + this.id2 = id.getId2(); + this.data = data; + this.reference = reference; + } - public SetRefIngMulIdEntity(Integer id1, Integer id2, String data, SetRefEdMulIdEntity reference) { - this.id1 = id1; - this.id2 = id2; - this.data = data; - this.reference = reference; - } + public SetRefIngMulIdEntity(Integer id1, Integer id2, String data, SetRefEdMulIdEntity reference) { + this.id1 = id1; + this.id2 = id2; + this.data = data; + this.reference = reference; + } - public SetRefIngMulIdEntity(String data, SetRefEdMulIdEntity reference) { - this.data = data; - this.reference = reference; - } + public SetRefIngMulIdEntity(String data, SetRefEdMulIdEntity reference) { + this.data = data; + this.reference = reference; + } - public Integer getId1() { - return id1; - } + public Integer getId1() { + return id1; + } - public void setId1(Integer id1) { - this.id1 = id1; - } + public void setId1(Integer id1) { + this.id1 = id1; + } - public Integer getId2() { - return id2; - } + public Integer getId2() { + return id2; + } - public void setId2(Integer id2) { - this.id2 = id2; - } + public void setId2(Integer id2) { + this.id2 = id2; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public SetRefEdMulIdEntity getReference() { - return reference; - } + public SetRefEdMulIdEntity getReference() { + return reference; + } - public void setReference(SetRefEdMulIdEntity reference) { - this.reference = reference; - } + public void setReference(SetRefEdMulIdEntity reference) { + this.reference = reference; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SetRefIngMulIdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SetRefIngMulIdEntity) ) { + return false; + } - SetRefIngMulIdEntity that = (SetRefIngMulIdEntity) o; + SetRefIngMulIdEntity that = (SetRefIngMulIdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id1 != null ? !id1.equals(that.id1) : that.id1 != null) return false; - if (id2 != null ? !id2.equals(that.id2) : that.id2 != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id1 != null ? !id1.equals( that.id1 ) : that.id1 != null ) { + return false; + } + if ( id2 != null ? !id2.equals( that.id2 ) : that.id2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id1 != null ? id1.hashCode() : 0); - result = 31 * result + (id2 != null ? id2.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id1 != null ? id1.hashCode() : 0); + result = 31 * result + (id2 != null ? id2.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetRefIngMulIdEntity(id1 = " + id1 + ", id2 = " + id2 + ", data = " + data + ")"; - } + public String toString() { + return "SetRefIngMulIdEntity(id1 = " + id1 + ", id2 = " + id2 + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetoone/BidirectionalEagerAnnotationRefEdOneToOne.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetoone/BidirectionalEagerAnnotationRefEdOneToOne.java index 8f483bd275..6e04c65e5c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetoone/BidirectionalEagerAnnotationRefEdOneToOne.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetoone/BidirectionalEagerAnnotationRefEdOneToOne.java @@ -39,7 +39,7 @@ import org.hibernate.envers.NotAudited; */ @Entity @Audited -@Proxy(lazy=false) +@Proxy(lazy = false) // Class name is too long of an identifier for Oracle. @Table(name = "EdOneToOne") public final class BidirectionalEagerAnnotationRefEdOneToOne { @@ -64,13 +64,21 @@ public final class BidirectionalEagerAnnotationRefEdOneToOne { @Override public boolean equals(Object o) { - if ( this == o ) return true; - if ( ! ( o instanceof BidirectionalEagerAnnotationRefEdOneToOne ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof BidirectionalEagerAnnotationRefEdOneToOne) ) { + return false; + } BidirectionalEagerAnnotationRefEdOneToOne that = (BidirectionalEagerAnnotationRefEdOneToOne) o; - if ( data != null ? !data.equals( that.data ) : that.data != null ) return false; - if ( id != null ? !id.equals( that.id ) : that.id != null ) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } return true; } @@ -78,7 +86,7 @@ public final class BidirectionalEagerAnnotationRefEdOneToOne { @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; - result = 31 * result + ( data != null ? data.hashCode() : 0 ); + result = 31 * result + (data != null ? data.hashCode() : 0); return result; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetoone/BidirectionalEagerAnnotationRefIngOneToOne.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetoone/BidirectionalEagerAnnotationRefIngOneToOne.java index 3431d29ddd..fae36c712a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetoone/BidirectionalEagerAnnotationRefIngOneToOne.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetoone/BidirectionalEagerAnnotationRefIngOneToOne.java @@ -40,7 +40,7 @@ import org.hibernate.envers.Audited; */ @Entity @Audited -@Proxy(lazy=false) +@Proxy(lazy = false) //Class name is too long of an identifier for Oracle. @Table(name = "IngOneToOne") public final class BidirectionalEagerAnnotationRefIngOneToOne { @@ -72,13 +72,21 @@ public final class BidirectionalEagerAnnotationRefIngOneToOne { @Override public boolean equals(Object o) { - if ( this == o ) return true; - if ( ! ( o instanceof BidirectionalEagerAnnotationRefIngOneToOne ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof BidirectionalEagerAnnotationRefIngOneToOne) ) { + return false; + } BidirectionalEagerAnnotationRefIngOneToOne that = (BidirectionalEagerAnnotationRefIngOneToOne) o; - if ( data != null ? !data.equals( that.data ) : that.data != null ) return false; - if ( id != null ? !id.equals( that.id ) : that.id != null ) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } return true; } @@ -86,7 +94,7 @@ public final class BidirectionalEagerAnnotationRefIngOneToOne { @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; - result = 31 * result + ( data != null ? data.hashCode() : 0 ); + result = 31 * result + (data != null ? data.hashCode() : 0); return result; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetoone/BidirectionalEagerHbmRefEdPK.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetoone/BidirectionalEagerHbmRefEdPK.java index ee3ae95aea..46d3242b22 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetoone/BidirectionalEagerHbmRefEdPK.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetoone/BidirectionalEagerHbmRefEdPK.java @@ -31,7 +31,8 @@ public class BidirectionalEagerHbmRefEdPK { private String data; private BidirectionalEagerHbmRefIngPK referencing; - public BidirectionalEagerHbmRefEdPK() {} + public BidirectionalEagerHbmRefEdPK() { + } public BidirectionalEagerHbmRefEdPK(String data) { this.data = data; @@ -63,21 +64,29 @@ public class BidirectionalEagerHbmRefEdPK { @Override public boolean equals(Object o) { - if ( this == o ) return true; - if ( ! ( o instanceof BidirectionalEagerHbmRefEdPK ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof BidirectionalEagerHbmRefEdPK) ) { + return false; + } BidirectionalEagerHbmRefEdPK that = (BidirectionalEagerHbmRefEdPK) o; - if ( id != that.id ) return false; - if ( data != null ? !data.equals( that.data ) : that.data != null ) return false; + if ( id != that.id ) { + return false; + } + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } return true; } @Override public int hashCode() { - int result = (int) ( id ^ ( id >>> 32 ) ); - result = 31 * result + ( data != null ? data.hashCode() : 0 ); + int result = (int) (id ^ (id >>> 32)); + result = 31 * result + (data != null ? data.hashCode() : 0); return result; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetoone/BidirectionalEagerHbmRefIngPK.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetoone/BidirectionalEagerHbmRefIngPK.java index b7bfa6ce51..991aa89429 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetoone/BidirectionalEagerHbmRefIngPK.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/onetoone/BidirectionalEagerHbmRefIngPK.java @@ -31,7 +31,8 @@ public class BidirectionalEagerHbmRefIngPK { private String data; private BidirectionalEagerHbmRefEdPK reference; - public BidirectionalEagerHbmRefIngPK() {} + public BidirectionalEagerHbmRefIngPK() { + } public BidirectionalEagerHbmRefIngPK(String data) { this.data = data; @@ -63,21 +64,29 @@ public class BidirectionalEagerHbmRefIngPK { @Override public boolean equals(Object o) { - if ( this == o ) return true; - if ( ! ( o instanceof BidirectionalEagerHbmRefIngPK ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof BidirectionalEagerHbmRefIngPK) ) { + return false; + } BidirectionalEagerHbmRefIngPK that = (BidirectionalEagerHbmRefIngPK) o; - if ( id != that.id ) return false; - if ( data != null ? !data.equals( that.data ) : that.data != null ) return false; + if ( id != that.id ) { + return false; + } + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } return true; } @Override public int hashCode() { - int result = (int) ( id ^ ( id >>> 32 ) ); - result = 31 * result + ( data != null ? data.hashCode() : 0 ); + int result = (int) (id ^ (id >>> 32)); + result = 31 * result + (data != null ? data.hashCode() : 0); return result; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomDataRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomDataRevEntity.java index 9f5acfc63f..2f6d32945f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomDataRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomDataRevEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.reventity; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -37,40 +38,41 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = {@Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class CustomDataRevEntity { - @Id - @GeneratedValue(generator = "EnversTestingRevisionGenerator") - @RevisionNumber - private int customId; + @Id + @GeneratedValue(generator = "EnversTestingRevisionGenerator") + @RevisionNumber + private int customId; - @RevisionTimestamp - private long customTimestamp; + @RevisionTimestamp + private long customTimestamp; private String data; - public int getCustomId() { - return customId; - } + public int getCustomId() { + return customId; + } - public void setCustomId(int customId) { - this.customId = customId; - } + public void setCustomId(int customId) { + this.customId = customId; + } - public long getCustomTimestamp() { - return customTimestamp; - } + public long getCustomTimestamp() { + return customTimestamp; + } - public void setCustomTimestamp(long customTimestamp) { - this.customTimestamp = customTimestamp; - } + public void setCustomTimestamp(long customTimestamp) { + this.customTimestamp = customTimestamp; + } public String getData() { return data; @@ -82,14 +84,24 @@ public class CustomDataRevEntity { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof CustomDataRevEntity)) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof CustomDataRevEntity) ) { + return false; + } CustomDataRevEntity that = (CustomDataRevEntity) o; - if (customId != that.customId) return false; - if (customTimestamp != that.customTimestamp) return false; - if (data != null ? !data.equals(that.data) : that.data != null) return false; + if ( customId != that.customId ) { + return false; + } + if ( customTimestamp != that.customTimestamp ) { + return false; + } + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomDateRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomDateRevEntity.java index 7e4f957c15..0a988303ef 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomDateRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomDateRevEntity.java @@ -22,10 +22,11 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.reventity; -import java.util.Date; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import java.util.Date; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @@ -38,57 +39,65 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = {@Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class CustomDateRevEntity { - @Id - @GeneratedValue(generator = "EnversTestingRevisionGenerator") - @RevisionNumber - private int customId; + @Id + @GeneratedValue(generator = "EnversTestingRevisionGenerator") + @RevisionNumber + private int customId; - @RevisionTimestamp - private Date dateTimestamp; + @RevisionTimestamp + private Date dateTimestamp; - public int getCustomId() { - return customId; - } + public int getCustomId() { + return customId; + } - public void setCustomId(int customId) { - this.customId = customId; - } + public void setCustomId(int customId) { + this.customId = customId; + } - public Date getDateTimestamp() { - return dateTimestamp; - } + public Date getDateTimestamp() { + return dateTimestamp; + } - public void setDateTimestamp(Date dateTimestamp) { - this.dateTimestamp = dateTimestamp; - } + public void setDateTimestamp(Date dateTimestamp) { + this.dateTimestamp = dateTimestamp; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } - CustomDateRevEntity that = (CustomDateRevEntity) o; + CustomDateRevEntity that = (CustomDateRevEntity) o; - if (customId != that.customId) return false; - if (dateTimestamp != null ? !dateTimestamp.equals(that.dateTimestamp) : that.dateTimestamp != null) - return false; + if ( customId != that.customId ) { + return false; + } + if ( dateTimestamp != null ? !dateTimestamp.equals( that.dateTimestamp ) : that.dateTimestamp != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = customId; - result = 31 * result + (dateTimestamp != null ? dateTimestamp.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = customId; + result = 31 * result + (dateTimestamp != null ? dateTimestamp.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomPropertyAccessRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomPropertyAccessRevEntity.java index dcb297d662..7bd029b680 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomPropertyAccessRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomPropertyAccessRevEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.reventity; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -37,55 +38,64 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = {@Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class CustomPropertyAccessRevEntity { - private int customId; + private int customId; - private long customTimestamp; + private long customTimestamp; - @Id - @GeneratedValue(generator = "EnversTestingRevisionGenerator") - @RevisionNumber - public int getCustomId() { - return customId; - } + @Id + @GeneratedValue(generator = "EnversTestingRevisionGenerator") + @RevisionNumber + public int getCustomId() { + return customId; + } - public void setCustomId(int customId) { - this.customId = customId; - } + public void setCustomId(int customId) { + this.customId = customId; + } - @RevisionTimestamp - public long getCustomTimestamp() { - return customTimestamp; - } + @RevisionTimestamp + public long getCustomTimestamp() { + return customTimestamp; + } - public void setCustomTimestamp(long customTimestamp) { - this.customTimestamp = customTimestamp; - } + public void setCustomTimestamp(long customTimestamp) { + this.customTimestamp = customTimestamp; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof CustomPropertyAccessRevEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof CustomPropertyAccessRevEntity) ) { + return false; + } - CustomPropertyAccessRevEntity that = (CustomPropertyAccessRevEntity) o; + CustomPropertyAccessRevEntity that = (CustomPropertyAccessRevEntity) o; - if (customId != that.customId) return false; - if (customTimestamp != that.customTimestamp) return false; + if ( customId != that.customId ) { + return false; + } + if ( customTimestamp != that.customTimestamp ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = customId; - result = 31 * result + (int) (customTimestamp ^ (customTimestamp >>> 32)); - return result; - } + public int hashCode() { + int result; + result = customId; + result = 31 * result + (int) (customTimestamp ^ (customTimestamp >>> 32)); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomRevEntity.java index adbf0a0ea1..b497d22b19 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomRevEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.reventity; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -37,55 +38,64 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = {@Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class CustomRevEntity { - @Id - @GeneratedValue(generator = "EnversTestingRevisionGenerator") - @RevisionNumber - private int customId; + @Id + @GeneratedValue(generator = "EnversTestingRevisionGenerator") + @RevisionNumber + private int customId; - @RevisionTimestamp - private long customTimestamp; + @RevisionTimestamp + private long customTimestamp; - public int getCustomId() { - return customId; - } + public int getCustomId() { + return customId; + } - public void setCustomId(int customId) { - this.customId = customId; - } + public void setCustomId(int customId) { + this.customId = customId; + } - public long getCustomTimestamp() { - return customTimestamp; - } + public long getCustomTimestamp() { + return customTimestamp; + } - public void setCustomTimestamp(long customTimestamp) { - this.customTimestamp = customTimestamp; - } + public void setCustomTimestamp(long customTimestamp) { + this.customTimestamp = customTimestamp; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof CustomRevEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof CustomRevEntity) ) { + return false; + } - CustomRevEntity that = (CustomRevEntity) o; + CustomRevEntity that = (CustomRevEntity) o; - if (customId != that.customId) return false; - if (customTimestamp != that.customTimestamp) return false; + if ( customId != that.customId ) { + return false; + } + if ( customTimestamp != that.customTimestamp ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = customId; - result = 31 * result + (int) (customTimestamp ^ (customTimestamp >>> 32)); - return result; - } + public int hashCode() { + int result; + result = customId; + result = 31 * result + (int) (customTimestamp ^ (customTimestamp >>> 32)); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomRevEntityColumnMapping.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomRevEntityColumnMapping.java index b3f77944f7..6cbdfd2ea0 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomRevEntityColumnMapping.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/CustomRevEntityColumnMapping.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.entities.reventity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -38,57 +39,66 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = {@Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class CustomRevEntityColumnMapping { - @Id - @GeneratedValue(generator = "EnversTestingRevisionGenerator") - @Column(columnDefinition = "int") - @RevisionNumber - private Long customId; + @Id + @GeneratedValue(generator = "EnversTestingRevisionGenerator") + @Column(columnDefinition = "int") + @RevisionNumber + private Long customId; - @RevisionTimestamp - private long customTimestamp; + @RevisionTimestamp + private long customTimestamp; - public Long getCustomId() { - return customId; - } + public Long getCustomId() { + return customId; + } - public void setCustomId(Long customId) { - this.customId = customId; - } + public void setCustomId(Long customId) { + this.customId = customId; + } - public long getCustomTimestamp() { - return customTimestamp; - } + public long getCustomTimestamp() { + return customTimestamp; + } - public void setCustomTimestamp(long customTimestamp) { - this.customTimestamp = customTimestamp; - } + public void setCustomTimestamp(long customTimestamp) { + this.customTimestamp = customTimestamp; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } - CustomRevEntityColumnMapping that = (CustomRevEntityColumnMapping) o; + CustomRevEntityColumnMapping that = (CustomRevEntityColumnMapping) o; - if (customTimestamp != that.customTimestamp) return false; - if (customId != null ? !customId.equals(that.customId) : that.customId != null) return false; + if ( customTimestamp != that.customTimestamp ) { + return false; + } + if ( customId != null ? !customId.equals( that.customId ) : that.customId != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = customId != null ? customId.hashCode() : 0; - result = 31 * result + (int) (customTimestamp ^ (customTimestamp >>> 32)); - return result; - } + @Override + public int hashCode() { + int result = customId != null ? customId.hashCode() : 0; + result = 31 * result + (int) (customTimestamp ^ (customTimestamp >>> 32)); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/AnnotatedTrackingRevisionEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/AnnotatedTrackingRevisionEntity.java index 89f88a03e8..8101398461 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/AnnotatedTrackingRevisionEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/AnnotatedTrackingRevisionEntity.java @@ -1,6 +1,5 @@ package org.hibernate.envers.test.entities.reventity.trackmodifiedentities; -import java.util.Set; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; @@ -9,6 +8,7 @@ import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.Table; +import java.util.Set; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @@ -19,80 +19,92 @@ import org.hibernate.envers.RevisionTimestamp; /** * Sample revision entity that uses {@link ModifiedEntityNames} annotation. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @Entity @Table(name = "AnnotatedTrackRevInfo") @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = {@Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class AnnotatedTrackingRevisionEntity { - @Id - @GeneratedValue(generator = "EnversTestingRevisionGenerator") - @RevisionNumber - private int customId; + @Id + @GeneratedValue(generator = "EnversTestingRevisionGenerator") + @RevisionNumber + private int customId; - @RevisionTimestamp - private long customTimestamp; + @RevisionTimestamp + private long customTimestamp; - @ElementCollection - @JoinTable(name = "REVCHANGES", joinColumns = @JoinColumn(name = "REV")) - @Column(name = "ENTITYNAME") - @ModifiedEntityNames - private Set entityNames; + @ElementCollection + @JoinTable(name = "REVCHANGES", joinColumns = @JoinColumn(name = "REV")) + @Column(name = "ENTITYNAME") + @ModifiedEntityNames + private Set entityNames; - public int getCustomId() { - return customId; - } + public int getCustomId() { + return customId; + } - public void setCustomId(int customId) { - this.customId = customId; - } + public void setCustomId(int customId) { + this.customId = customId; + } - public long getCustomTimestamp() { - return customTimestamp; - } + public long getCustomTimestamp() { + return customTimestamp; + } - public void setCustomTimestamp(long customTimestamp) { - this.customTimestamp = customTimestamp; - } + public void setCustomTimestamp(long customTimestamp) { + this.customTimestamp = customTimestamp; + } - public Set getEntityNames() { - return entityNames; - } + public Set getEntityNames() { + return entityNames; + } - public void setEntityNames(Set entityNames) { - this.entityNames = entityNames; - } + public void setEntityNames(Set entityNames) { + this.entityNames = entityNames; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof AnnotatedTrackingRevisionEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof AnnotatedTrackingRevisionEntity) ) { + return false; + } - AnnotatedTrackingRevisionEntity that = (AnnotatedTrackingRevisionEntity) o; + AnnotatedTrackingRevisionEntity that = (AnnotatedTrackingRevisionEntity) o; - if (customId != that.customId) return false; - if (customTimestamp != that.customTimestamp) return false; - if (entityNames != null ? !entityNames.equals(that.entityNames) : that.entityNames != null) return false; + if ( customId != that.customId ) { + return false; + } + if ( customTimestamp != that.customTimestamp ) { + return false; + } + if ( entityNames != null ? !entityNames.equals( that.entityNames ) : that.entityNames != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = customId; - result = 31 * result + (int) (customTimestamp ^ (customTimestamp >>> 32)); - result = 31 * result + (entityNames != null ? entityNames.hashCode() : 0); - return result; - } + public int hashCode() { + int result = customId; + result = 31 * result + (int) (customTimestamp ^ (customTimestamp >>> 32)); + result = 31 * result + (entityNames != null ? entityNames.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "AnnotatedTrackingRevisionEntity(customId = " + customId + ", customTimestamp = " + customTimestamp + ", entityNames=" + entityNames + ")"; - } + @Override + public String toString() { + return "AnnotatedTrackingRevisionEntity(customId = " + customId + ", customTimestamp = " + customTimestamp + ", entityNames=" + entityNames + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/CustomTrackingRevisionEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/CustomTrackingRevisionEntity.java index 143e4c30fb..65be5c4e1f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/CustomTrackingRevisionEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/CustomTrackingRevisionEntity.java @@ -1,13 +1,13 @@ package org.hibernate.envers.test.entities.reventity.trackmodifiedentities; -import java.util.HashSet; -import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; +import java.util.HashSet; +import java.util.Set; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @@ -17,79 +17,89 @@ import org.hibernate.envers.RevisionTimestamp; /** * Revision entity which {@code modifiedEntityTypes} field is manually populated by {@link CustomTrackingRevisionListener}. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @Entity @Table(name = "CustomTrackRevInfo") @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = {@Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity(CustomTrackingRevisionListener.class) public class CustomTrackingRevisionEntity { - @Id - @GeneratedValue(generator = "EnversTestingRevisionGenerator") - @RevisionNumber - private int customId; + @Id + @GeneratedValue(generator = "EnversTestingRevisionGenerator") + @RevisionNumber + private int customId; - @RevisionTimestamp - private long customTimestamp; + @RevisionTimestamp + private long customTimestamp; - @OneToMany(mappedBy="revision", cascade={CascadeType.PERSIST, CascadeType.REMOVE}) - private Set modifiedEntityTypes = new HashSet(); + @OneToMany(mappedBy = "revision", cascade = {CascadeType.PERSIST, CascadeType.REMOVE}) + private Set modifiedEntityTypes = new HashSet(); - public int getCustomId() { - return customId; - } + public int getCustomId() { + return customId; + } - public void setCustomId(int customId) { - this.customId = customId; - } + public void setCustomId(int customId) { + this.customId = customId; + } - public long getCustomTimestamp() { - return customTimestamp; - } + public long getCustomTimestamp() { + return customTimestamp; + } - public void setCustomTimestamp(long customTimestamp) { - this.customTimestamp = customTimestamp; - } + public void setCustomTimestamp(long customTimestamp) { + this.customTimestamp = customTimestamp; + } - public Set getModifiedEntityTypes() { - return modifiedEntityTypes; - } + public Set getModifiedEntityTypes() { + return modifiedEntityTypes; + } - public void setModifiedEntityTypes(Set modifiedEntityTypes) { - this.modifiedEntityTypes = modifiedEntityTypes; - } + public void setModifiedEntityTypes(Set modifiedEntityTypes) { + this.modifiedEntityTypes = modifiedEntityTypes; + } - public void addModifiedEntityType(String entityClassName) { - modifiedEntityTypes.add(new ModifiedEntityTypeEntity(this, entityClassName)); - } + public void addModifiedEntityType(String entityClassName) { + modifiedEntityTypes.add( new ModifiedEntityTypeEntity( this, entityClassName ) ); + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof CustomTrackingRevisionEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof CustomTrackingRevisionEntity) ) { + return false; + } - CustomTrackingRevisionEntity that = (CustomTrackingRevisionEntity) o; + CustomTrackingRevisionEntity that = (CustomTrackingRevisionEntity) o; - if (customId != that.customId) return false; - if (customTimestamp != that.customTimestamp) return false; + if ( customId != that.customId ) { + return false; + } + if ( customTimestamp != that.customTimestamp ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = customId; - result = 31 * result + (int) (customTimestamp ^ (customTimestamp >>> 32)); - return result; - } + public int hashCode() { + int result = customId; + result = 31 * result + (int) (customTimestamp ^ (customTimestamp >>> 32)); + return result; + } - @Override - public String toString() { - return "CustomTrackingRevisionEntity(customId = " + customId + ", customTimestamp = " + customTimestamp + ")"; - } + @Override + public String toString() { + return "CustomTrackingRevisionEntity(customId = " + customId + ", customTimestamp = " + customTimestamp + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/CustomTrackingRevisionListener.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/CustomTrackingRevisionListener.java index 510be1a43a..d9507f7964 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/CustomTrackingRevisionListener.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/CustomTrackingRevisionListener.java @@ -9,13 +9,14 @@ import org.hibernate.envers.RevisionType; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class CustomTrackingRevisionListener implements EntityTrackingRevisionListener { - @Override - public void entityChanged(Class entityClass, String entityName, Serializable entityId, RevisionType revisionType, - Object revisionEntity) { - ((CustomTrackingRevisionEntity)revisionEntity).addModifiedEntityType(entityClass.getName()); - } + @Override + public void entityChanged( + Class entityClass, String entityName, Serializable entityId, RevisionType revisionType, + Object revisionEntity) { + ((CustomTrackingRevisionEntity) revisionEntity).addModifiedEntityType( entityClass.getName() ); + } - @Override - public void newRevision(Object revisionEntity) { - } + @Override + public void newRevision(Object revisionEntity) { + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/ExtendedRevisionEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/ExtendedRevisionEntity.java index 65e838148a..7dbd156917 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/ExtendedRevisionEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/ExtendedRevisionEntity.java @@ -12,14 +12,14 @@ import org.hibernate.envers.enhanced.SequenceIdTrackingModifiedEntitiesRevisionE @Entity @RevisionEntity(ExtendedRevisionListener.class) public class ExtendedRevisionEntity extends SequenceIdTrackingModifiedEntitiesRevisionEntity { - @Column(name = "USER_COMMENT") - private String comment; + @Column(name = "USER_COMMENT") + private String comment; - public String getComment() { - return comment; - } + public String getComment() { + return comment; + } - public void setComment(String comment) { - this.comment = comment; - } + public void setComment(String comment) { + this.comment = comment; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/ExtendedRevisionListener.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/ExtendedRevisionListener.java index d78317497a..0e12df227a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/ExtendedRevisionListener.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/ExtendedRevisionListener.java @@ -6,9 +6,9 @@ import org.hibernate.envers.RevisionListener; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class ExtendedRevisionListener implements RevisionListener { - public static final String COMMENT_VALUE = "Comment"; + public static final String COMMENT_VALUE = "Comment"; - public void newRevision(Object revisionEntity) { - ((ExtendedRevisionEntity)revisionEntity).setComment(COMMENT_VALUE); - } + public void newRevision(Object revisionEntity) { + ((ExtendedRevisionEntity) revisionEntity).setComment( COMMENT_VALUE ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/ModifiedEntityTypeEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/ModifiedEntityTypeEntity.java index 07092f0c28..4c2a72b6dd 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/ModifiedEntityTypeEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/entities/reventity/trackmodifiedentities/ModifiedEntityTypeEntity.java @@ -7,64 +7,73 @@ import javax.persistence.ManyToOne; /** * Custom detail of revision entity. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @Entity public class ModifiedEntityTypeEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @ManyToOne - private CustomTrackingRevisionEntity revision; - - private String entityClassName; + @ManyToOne + private CustomTrackingRevisionEntity revision; - public ModifiedEntityTypeEntity() { - } + private String entityClassName; - public ModifiedEntityTypeEntity(String entityClassName) { - this.entityClassName = entityClassName; - } + public ModifiedEntityTypeEntity() { + } - public ModifiedEntityTypeEntity(CustomTrackingRevisionEntity revision, String entityClassName) { - this.revision = revision; - this.entityClassName = entityClassName; - } + public ModifiedEntityTypeEntity(String entityClassName) { + this.entityClassName = entityClassName; + } - public CustomTrackingRevisionEntity getRevision() { - return revision; - } + public ModifiedEntityTypeEntity(CustomTrackingRevisionEntity revision, String entityClassName) { + this.revision = revision; + this.entityClassName = entityClassName; + } - public void setRevision(CustomTrackingRevisionEntity revision) { - this.revision = revision; - } + public CustomTrackingRevisionEntity getRevision() { + return revision; + } - public String getEntityClassName() { - return entityClassName; - } + public void setRevision(CustomTrackingRevisionEntity revision) { + this.revision = revision; + } - public void setEntityClassName(String entityClassName) { - this.entityClassName = entityClassName; - } + public String getEntityClassName() { + return entityClassName; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ModifiedEntityTypeEntity)) return false; + public void setEntityClassName(String entityClassName) { + this.entityClassName = entityClassName; + } - ModifiedEntityTypeEntity that = (ModifiedEntityTypeEntity) o; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ModifiedEntityTypeEntity) ) { + return false; + } - if (entityClassName != null ? !entityClassName.equals(that.entityClassName) : that.entityClassName != null) return false; + ModifiedEntityTypeEntity that = (ModifiedEntityTypeEntity) o; - return true; - } + if ( entityClassName != null ? + !entityClassName.equals( that.entityClassName ) : + that.entityClassName != null ) { + return false; + } - public int hashCode() { - return entityClassName != null ? entityClassName.hashCode() : 0; - } + return true; + } - @Override - public String toString() { - return "CustomTrackingRevisionEntity(entityClassName = " + entityClassName + ")"; - } + public int hashCode() { + return entityClassName != null ? entityClassName.hashCode() : 0; + } + + @Override + public String toString() { + return "CustomTrackingRevisionEntity(entityClassName = " + entityClassName + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/Country.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/Country.java index 56fc48ac0a..80a9994713 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/Country.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/Country.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.integration.accesstype; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @@ -19,7 +20,8 @@ public class Country { * Default constructor for persistence provider. */ @SuppressWarnings({"UnusedDeclaration"}) - private Country() { } + private Country() { + } private Country(Integer code, String naam) { this.code = code; @@ -35,7 +37,7 @@ public class Country { } public static Country of(Integer code, String name) { - return new Country(code, name); + return new Country( code, name ); } @Override @@ -49,23 +51,32 @@ public class Country { @Override public boolean equals(Object obj) { - if (this == obj) + if ( this == obj ) { return true; - if (obj == null) + } + if ( obj == null ) { return false; - if (getClass() != obj.getClass()) + } + if ( getClass() != obj.getClass() ) { return false; + } Country other = (Country) obj; - if (code == null) { - if (other.code != null) + if ( code == null ) { + if ( other.code != null ) { return false; - } else if (!code.equals(other.code)) + } + } + else if ( !code.equals( other.code ) ) { return false; - if (name == null) { - if (other.name != null) + } + if ( name == null ) { + if ( other.name != null ) { return false; - } else if (!name.equals(other.name)) + } + } + else if ( !name.equals( other.name ) ) { return false; + } return true; } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/FieldAccessType.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/FieldAccessType.java index 144935b7f3..965e8d6eb3 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/FieldAccessType.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/FieldAccessType.java @@ -24,52 +24,52 @@ package org.hibernate.envers.test.integration.accesstype; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Assert; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class FieldAccessType extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { FieldAccessTypeEntity.class }; - } + return new Class[] {FieldAccessTypeEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - FieldAccessTypeEntity fate = new FieldAccessTypeEntity("data"); - em.persist(fate); - id1 = fate.readId(); - em.getTransaction().commit(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + FieldAccessTypeEntity fate = new FieldAccessTypeEntity( "data" ); + em.persist( fate ); + id1 = fate.readId(); + em.getTransaction().commit(); - em.getTransaction().begin(); - fate = em.find(FieldAccessTypeEntity.class, id1); - fate.writeData("data2"); - em.getTransaction().commit(); - } + em.getTransaction().begin(); + fate = em.find( FieldAccessTypeEntity.class, id1 ); + fate.writeData( "data2" ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - Assert.assertEquals( Arrays.asList( 1, 2 ), getAuditReader().getRevisions(FieldAccessTypeEntity.class, id1) ); - } + @Test + public void testRevisionsCounts() { + Assert.assertEquals( Arrays.asList( 1, 2 ), getAuditReader().getRevisions( FieldAccessTypeEntity.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - FieldAccessTypeEntity ver1 = new FieldAccessTypeEntity(id1, "data"); - FieldAccessTypeEntity ver2 = new FieldAccessTypeEntity(id1, "data2"); - Assert.assertEquals(ver1, getAuditReader().find(FieldAccessTypeEntity.class, id1, 1)); - Assert.assertEquals(ver2, getAuditReader().find(FieldAccessTypeEntity.class, id1, 2)); - } + @Test + public void testHistoryOfId1() { + FieldAccessTypeEntity ver1 = new FieldAccessTypeEntity( id1, "data" ); + FieldAccessTypeEntity ver2 = new FieldAccessTypeEntity( id1, "data2" ); + Assert.assertEquals( ver1, getAuditReader().find( FieldAccessTypeEntity.class, id1, 1 ) ); + Assert.assertEquals( ver2, getAuditReader().find( FieldAccessTypeEntity.class, id1, 2 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/FieldAccessTypeEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/FieldAccessTypeEntity.java index 44a50b9872..5e9bce069c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/FieldAccessTypeEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/FieldAccessTypeEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.accesstype; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -34,65 +35,73 @@ import org.hibernate.envers.Audited; */ @Entity public class FieldAccessTypeEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - private String data; + @Audited + private String data; - public FieldAccessTypeEntity() { - } + public FieldAccessTypeEntity() { + } - public FieldAccessTypeEntity(String data) { - this.data = data; - } + public FieldAccessTypeEntity(String data) { + this.data = data; + } - public FieldAccessTypeEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public FieldAccessTypeEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public Integer getId() { - throw new RuntimeException(); - } + public Integer getId() { + throw new RuntimeException(); + } - public void setId(Integer id) { - throw new RuntimeException(); - } + public void setId(Integer id) { + throw new RuntimeException(); + } - public String getData() { - throw new RuntimeException(); - } + public String getData() { + throw new RuntimeException(); + } - public void setData(String data) { - throw new RuntimeException(); - } + public void setData(String data) { + throw new RuntimeException(); + } - public Integer readId() { - return id; - } + public Integer readId() { + return id; + } - public void writeData(String data) { - this.data = data; - } + public void writeData(String data) { + this.data = data; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof FieldAccessTypeEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof FieldAccessTypeEntity) ) { + return false; + } - FieldAccessTypeEntity that = (FieldAccessTypeEntity) o; + FieldAccessTypeEntity that = (FieldAccessTypeEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/ImmutableClassAccessType.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/ImmutableClassAccessType.java index 0a0f8e44d0..87528a1db0 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/ImmutableClassAccessType.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/ImmutableClassAccessType.java @@ -1,13 +1,13 @@ package org.hibernate.envers.test.integration.accesstype; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + import static org.junit.Assert.assertEquals; public class ImmutableClassAccessType extends BaseEnversJPAFunctionalTestCase { @@ -15,38 +15,43 @@ public class ImmutableClassAccessType extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { Country.class }; + return new Class[] {Country.class}; } @Test - @Priority(10) + @Priority(10) public void initData() { EntityManager em = getEntityManager(); // Revision 1 em.getTransaction().begin(); - country = Country.of(123, "Germany"); - em.persist(country); + country = Country.of( 123, "Germany" ); + em.persist( country ); em.getTransaction().commit(); } @Test public void testRevisionsCounts() { - assert Arrays.asList(1) + assert Arrays.asList( 1 ) .equals( - getAuditReader().getRevisions(Country.class, - country.getCode())); + getAuditReader().getRevisions( + Country.class, + country.getCode() + ) + ); } @Test public void testHistoryOfId1() { - Country country1 = getEntityManager().find(Country.class, - country.getCode()); - assertEquals(country1, country); + Country country1 = getEntityManager().find( + Country.class, + country.getCode() + ); + assertEquals( country1, country ); - Country history = getAuditReader().find(Country.class, country1.getCode(), 1); - assertEquals(country, history); + Country history = getAuditReader().find( Country.class, country1.getCode(), 1 ); + assertEquals( country, history ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/MixedAccessType.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/MixedAccessType.java index 5e585aef8c..16da037d15 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/MixedAccessType.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/MixedAccessType.java @@ -23,58 +23,58 @@ */ package org.hibernate.envers.test.integration.accesstype; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class MixedAccessType extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { MixedAccessTypeEntity.class }; - } + return new Class[] {MixedAccessTypeEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - MixedAccessTypeEntity mate = new MixedAccessTypeEntity("data"); - em.persist(mate); - id1 = mate.readId(); - em.getTransaction().commit(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + MixedAccessTypeEntity mate = new MixedAccessTypeEntity( "data" ); + em.persist( mate ); + id1 = mate.readId(); + em.getTransaction().commit(); - em.getTransaction().begin(); - mate = em.find(MixedAccessTypeEntity.class, id1); - mate.writeData("data2"); - em.getTransaction().commit(); - } + em.getTransaction().begin(); + mate = em.find( MixedAccessTypeEntity.class, id1 ); + mate.writeData( "data2" ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(MixedAccessTypeEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( MixedAccessTypeEntity.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - MixedAccessTypeEntity ver1 = new MixedAccessTypeEntity(id1, "data"); - MixedAccessTypeEntity ver2 = new MixedAccessTypeEntity(id1, "data2"); + @Test + public void testHistoryOfId1() { + MixedAccessTypeEntity ver1 = new MixedAccessTypeEntity( id1, "data" ); + MixedAccessTypeEntity ver2 = new MixedAccessTypeEntity( id1, "data2" ); - MixedAccessTypeEntity rev1 = getAuditReader().find(MixedAccessTypeEntity.class, id1, 1); - MixedAccessTypeEntity rev2 = getAuditReader().find(MixedAccessTypeEntity.class, id1, 2); + MixedAccessTypeEntity rev1 = getAuditReader().find( MixedAccessTypeEntity.class, id1, 1 ); + MixedAccessTypeEntity rev2 = getAuditReader().find( MixedAccessTypeEntity.class, id1, 2 ); - assert rev1.isDataSet(); - assert rev2.isDataSet(); + assert rev1.isDataSet(); + assert rev2.isDataSet(); - assert rev1.equals(ver1); - assert rev2.equals(ver2); - } + assert rev1.equals( ver1 ); + assert rev2.equals( ver2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/MixedAccessTypeEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/MixedAccessTypeEntity.java index 20a603d342..df867fc111 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/MixedAccessTypeEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/MixedAccessTypeEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.accesstype; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -35,76 +36,84 @@ import org.hibernate.envers.Audited; */ @Entity public class MixedAccessTypeEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @AccessType("property") - private String data; + @AccessType("property") + private String data; - @Transient - private boolean dataSet; + @Transient + private boolean dataSet; - public MixedAccessTypeEntity() { - } + public MixedAccessTypeEntity() { + } - public MixedAccessTypeEntity(String data) { - this.data = data; - } + public MixedAccessTypeEntity(String data) { + this.data = data; + } - public MixedAccessTypeEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public MixedAccessTypeEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public Integer getId() { - throw new RuntimeException(); - } + public Integer getId() { + throw new RuntimeException(); + } - public void setId(Integer id) { - throw new RuntimeException(); - } + public void setId(Integer id) { + throw new RuntimeException(); + } - // TODO: this should be on the property. But how to discover in AnnotationsMetadataReader that the - // we should read annotations from fields, even though the access type is "property"? - @Audited - public String getData() { - return data; - } + // TODO: this should be on the property. But how to discover in AnnotationsMetadataReader that the + // we should read annotations from fields, even though the access type is "property"? + @Audited + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - dataSet = true; - } + public void setData(String data) { + this.data = data; + dataSet = true; + } - public boolean isDataSet() { - return dataSet; - } + public boolean isDataSet() { + return dataSet; + } - public Integer readId() { - return id; - } + public Integer readId() { + return id; + } - public void writeData(String data) { - this.data = data; - } + public void writeData(String data) { + this.data = data; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof MixedAccessTypeEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof MixedAccessTypeEntity) ) { + return false; + } - MixedAccessTypeEntity that = (MixedAccessTypeEntity) o; + MixedAccessTypeEntity that = (MixedAccessTypeEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/PropertyAccessType.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/PropertyAccessType.java index 1a59940222..d8a838037a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/PropertyAccessType.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/PropertyAccessType.java @@ -23,61 +23,61 @@ */ package org.hibernate.envers.test.integration.accesstype; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class PropertyAccessType extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { PropertyAccessTypeEntity.class }; - } + return new Class[] {PropertyAccessTypeEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - PropertyAccessTypeEntity pate = new PropertyAccessTypeEntity("data"); - em.persist(pate); - id1 = pate.getId(); - em.getTransaction().commit(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + PropertyAccessTypeEntity pate = new PropertyAccessTypeEntity( "data" ); + em.persist( pate ); + id1 = pate.getId(); + em.getTransaction().commit(); - em.getTransaction().begin(); - pate = em.find(PropertyAccessTypeEntity.class, id1); - pate.writeData("data2"); - em.getTransaction().commit(); - } + em.getTransaction().begin(); + pate = em.find( PropertyAccessTypeEntity.class, id1 ); + pate.writeData( "data2" ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(PropertyAccessTypeEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( PropertyAccessTypeEntity.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - PropertyAccessTypeEntity ver1 = new PropertyAccessTypeEntity(id1, "data"); - PropertyAccessTypeEntity ver2 = new PropertyAccessTypeEntity(id1, "data2"); + @Test + public void testHistoryOfId1() { + PropertyAccessTypeEntity ver1 = new PropertyAccessTypeEntity( id1, "data" ); + PropertyAccessTypeEntity ver2 = new PropertyAccessTypeEntity( id1, "data2" ); - PropertyAccessTypeEntity rev1 = getAuditReader().find(PropertyAccessTypeEntity.class, id1, 1); - PropertyAccessTypeEntity rev2 = getAuditReader().find(PropertyAccessTypeEntity.class, id1, 2); + PropertyAccessTypeEntity rev1 = getAuditReader().find( PropertyAccessTypeEntity.class, id1, 1 ); + PropertyAccessTypeEntity rev2 = getAuditReader().find( PropertyAccessTypeEntity.class, id1, 2 ); - assert rev1.isIdSet(); - assert rev2.isIdSet(); + assert rev1.isIdSet(); + assert rev2.isIdSet(); - assert rev1.isDataSet(); - assert rev2.isDataSet(); + assert rev1.isDataSet(); + assert rev2.isDataSet(); - assert rev1.equals(ver1); - assert rev2.equals(ver2); - } + assert rev1.equals( ver1 ); + assert rev2.equals( ver2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/PropertyAccessTypeEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/PropertyAccessTypeEntity.java index 00a051cb85..5de03ec7dc 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/PropertyAccessTypeEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/accesstype/PropertyAccessTypeEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.accesstype; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -35,75 +36,83 @@ import org.hibernate.envers.Audited; */ @Entity public class PropertyAccessTypeEntity { - private Integer id; - private String data; + private Integer id; + private String data; - private boolean idSet; - private boolean dataSet; + private boolean idSet; + private boolean dataSet; - public PropertyAccessTypeEntity() { - } + public PropertyAccessTypeEntity() { + } - public PropertyAccessTypeEntity(String data) { - this.data = data; - } + public PropertyAccessTypeEntity(String data) { + this.data = data; + } - public PropertyAccessTypeEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public PropertyAccessTypeEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - @Id - @GeneratedValue - public Integer getId() { - return id; - } + @Id + @GeneratedValue + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - idSet = true; - } + public void setId(Integer id) { + this.id = id; + idSet = true; + } - @Audited - public String getData() { - return data; - } + @Audited + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - dataSet = true; - } + public void setData(String data) { + this.data = data; + dataSet = true; + } - @Transient - public boolean isIdSet() { - return idSet; - } + @Transient + public boolean isIdSet() { + return idSet; + } - @Transient - public boolean isDataSet() { - return dataSet; - } + @Transient + public boolean isDataSet() { + return dataSet; + } - public void writeData(String data) { - this.data = data; - } + public void writeData(String data) { + this.data = data; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof PropertyAccessTypeEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof PropertyAccessTypeEntity) ) { + return false; + } - PropertyAccessTypeEntity that = (PropertyAccessTypeEntity) o; + PropertyAccessTypeEntity that = (PropertyAccessTypeEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/auditReader/AuditReaderAPITest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/auditReader/AuditReaderAPITest.java index 86e5ff341d..14479e862f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/auditReader/AuditReaderAPITest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/auditReader/AuditReaderAPITest.java @@ -23,66 +23,67 @@ */ package org.hibernate.envers.test.integration.auditReader; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.exception.NotAuditedException; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * A test which checks the correct behavior of AuditReader.isEntityClassAudited(Class entityClass). - * + * * @author Hernan Chanfreau */ public class AuditReaderAPITest extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { AuditedTestEntity.class, NotAuditedTestEntity.class }; - } + return new Class[] {AuditedTestEntity.class, NotAuditedTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - AuditedTestEntity ent1 = new AuditedTestEntity(1, "str1"); - NotAuditedTestEntity ent2 = new NotAuditedTestEntity(1, "str1"); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + AuditedTestEntity ent1 = new AuditedTestEntity( 1, "str1" ); + NotAuditedTestEntity ent2 = new NotAuditedTestEntity( 1, "str1" ); - em.persist(ent1); - em.persist(ent2); - em.getTransaction().commit(); + em.persist( ent1 ); + em.persist( ent2 ); + em.getTransaction().commit(); - em.getTransaction().begin(); - - ent1 = em.find(AuditedTestEntity.class, 1); - ent2 = em.find(NotAuditedTestEntity.class, 1); - ent1.setStr1("str2"); - ent2.setStr1("str2"); - em.getTransaction().commit(); - } + em.getTransaction().begin(); - @Test - public void testIsEntityClassAuditedForAuditedEntity() { - assert getAuditReader().isEntityClassAudited(AuditedTestEntity.class); - - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(AuditedTestEntity.class, 1)); - } + ent1 = em.find( AuditedTestEntity.class, 1 ); + ent2 = em.find( NotAuditedTestEntity.class, 1 ); + ent1.setStr1( "str2" ); + ent2.setStr1( "str2" ); + em.getTransaction().commit(); + } - @Test - public void testIsEntityClassAuditedForNotAuditedEntity() { - - assert !getAuditReader().isEntityClassAudited(NotAuditedTestEntity.class); - - try { - getAuditReader().getRevisions(NotAuditedTestEntity.class, 1); - } catch (NotAuditedException nae) { - // it's ok because the entity is not audited - assert true; + @Test + public void testIsEntityClassAuditedForAuditedEntity() { + assert getAuditReader().isEntityClassAudited( AuditedTestEntity.class ); + + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( AuditedTestEntity.class, 1 ) ); + } + + @Test + public void testIsEntityClassAuditedForNotAuditedEntity() { + + assert !getAuditReader().isEntityClassAudited( NotAuditedTestEntity.class ); + + try { + getAuditReader().getRevisions( NotAuditedTestEntity.class, 1 ); } - } + catch (NotAuditedException nae) { + // it's ok because the entity is not audited + assert true; + } + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/auditReader/AuditedTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/auditReader/AuditedTestEntity.java index e918587ae6..c3d23ed8e5 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/auditReader/AuditedTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/auditReader/AuditedTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.auditReader; + import javax.persistence.Entity; import javax.persistence.Id; @@ -32,56 +33,64 @@ import org.hibernate.envers.Audited; */ @Entity public class AuditedTestEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String str1; + @Audited + private String str1; - public AuditedTestEntity() { - } + public AuditedTestEntity() { + } - public AuditedTestEntity(String str1) { - this.str1 = str1; - } + public AuditedTestEntity(String str1) { + this.str1 = str1; + } - public AuditedTestEntity(Integer id, String str1) { - this.id = id; - this.str1 = str1; - } + public AuditedTestEntity(Integer id, String str1) { + this.id = id; + this.str1 = str1; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof AuditedTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof AuditedTestEntity) ) { + return false; + } - AuditedTestEntity that = (AuditedTestEntity) o; + AuditedTestEntity that = (AuditedTestEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str1 != null ? str1.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str1 != null ? str1.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/auditReader/NotAuditedTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/auditReader/NotAuditedTestEntity.java index 76f375e63b..4238acabc7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/auditReader/NotAuditedTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/auditReader/NotAuditedTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.auditReader; + import javax.persistence.Entity; import javax.persistence.Id; @@ -30,55 +31,63 @@ import javax.persistence.Id; */ @Entity public class NotAuditedTestEntity { - @Id - private Integer id; + @Id + private Integer id; - private String str1; + private String str1; - public NotAuditedTestEntity() { - } + public NotAuditedTestEntity() { + } - public NotAuditedTestEntity(String str1) { - this.str1 = str1; - } + public NotAuditedTestEntity(String str1) { + this.str1 = str1; + } - public NotAuditedTestEntity(Integer id, String str1) { - this.id = id; - this.str1 = str1; - } + public NotAuditedTestEntity(Integer id, String str1) { + this.id = id; + this.str1 = str1; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof NotAuditedTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof NotAuditedTestEntity) ) { + return false; + } - NotAuditedTestEntity that = (NotAuditedTestEntity) o; + NotAuditedTestEntity that = (NotAuditedTestEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str1 != null ? str1.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str1 != null ? str1.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/BasicTestEntity1.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/BasicTestEntity1.java index 995acdf738..b508300b62 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/BasicTestEntity1.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/BasicTestEntity1.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.basic; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -33,72 +34,82 @@ import org.hibernate.envers.Audited; */ @Entity public class BasicTestEntity1 { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - private String str1; + @Audited + private String str1; - @Audited - private long long1; + @Audited + private long long1; - public BasicTestEntity1() { - } + public BasicTestEntity1() { + } - public BasicTestEntity1(String str1, long long1) { - this.str1 = str1; - this.long1 = long1; - } + public BasicTestEntity1(String str1, long long1) { + this.str1 = str1; + this.long1 = long1; + } - public BasicTestEntity1(Integer id, String str1, long long1) { - this.id = id; - this.str1 = str1; - this.long1 = long1; - } + public BasicTestEntity1(Integer id, String str1, long long1) { + this.id = id; + this.str1 = str1; + this.long1 = long1; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - public long getLong1() { - return long1; - } + public long getLong1() { + return long1; + } - public void setLong1(long long1) { - this.long1 = long1; - } + public void setLong1(long long1) { + this.long1 = long1; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof BasicTestEntity1)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof BasicTestEntity1) ) { + return false; + } - BasicTestEntity1 that = (BasicTestEntity1) o; + BasicTestEntity1 that = (BasicTestEntity1) o; - if (long1 != that.long1) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; + if ( long1 != that.long1 ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str1 != null ? str1.hashCode() : 0); - result = 31 * result + (int) (long1 ^ (long1 >>> 32)); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str1 != null ? str1.hashCode() : 0); + result = 31 * result + (int) (long1 ^ (long1 >>> 32)); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/BasicTestEntity2.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/BasicTestEntity2.java index 81d97855e1..dde40d9b95 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/BasicTestEntity2.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/BasicTestEntity2.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.basic; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -33,71 +34,81 @@ import org.hibernate.envers.Audited; */ @Entity public class BasicTestEntity2 { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - private String str1; + @Audited + private String str1; - private String str2; + private String str2; - public BasicTestEntity2() { - } + public BasicTestEntity2() { + } - public BasicTestEntity2(String str1, String str2) { - this.str1 = str1; - this.str2 = str2; - } + public BasicTestEntity2(String str1, String str2) { + this.str1 = str1; + this.str2 = str2; + } - public BasicTestEntity2(Integer id, String str1, String str2) { - this.id = id; - this.str1 = str1; - this.str2 = str2; - } + public BasicTestEntity2(Integer id, String str1, String str2) { + this.id = id; + this.str1 = str1; + this.str2 = str2; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - public String getStr2() { - return str2; - } + public String getStr2() { + return str2; + } - public void setStr2(String str2) { - this.str2 = str2; - } + public void setStr2(String str2) { + this.str2 = str2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof BasicTestEntity2)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof BasicTestEntity2) ) { + return false; + } - BasicTestEntity2 that = (BasicTestEntity2) o; + BasicTestEntity2 that = (BasicTestEntity2) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; - if (str2 != null ? !str2.equals(that.str2) : that.str2 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } + if ( str2 != null ? !str2.equals( that.str2 ) : that.str2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str1 != null ? str1.hashCode() : 0); - result = 31 * result + (str2 != null ? str2.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str1 != null ? str1.hashCode() : 0); + result = 31 * result + (str2 != null ? str2.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/BasicTestEntity3.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/BasicTestEntity3.java index 9e394b5bb8..5b46fafcaf 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/BasicTestEntity3.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/BasicTestEntity3.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.basic; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -31,70 +32,80 @@ import javax.persistence.Id; */ @Entity public class BasicTestEntity3 { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String str1; + private String str1; - private String str2; + private String str2; - public BasicTestEntity3() { - } + public BasicTestEntity3() { + } - public BasicTestEntity3(String str1, String str2) { - this.str1 = str1; - this.str2 = str2; - } + public BasicTestEntity3(String str1, String str2) { + this.str1 = str1; + this.str2 = str2; + } - public BasicTestEntity3(Integer id, String str1, String str2) { - this.id = id; - this.str1 = str1; - this.str2 = str2; - } + public BasicTestEntity3(Integer id, String str1, String str2) { + this.id = id; + this.str1 = str1; + this.str2 = str2; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - public String getStr2() { - return str2; - } + public String getStr2() { + return str2; + } - public void setStr2(String str2) { - this.str2 = str2; - } + public void setStr2(String str2) { + this.str2 = str2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof BasicTestEntity3)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof BasicTestEntity3) ) { + return false; + } - BasicTestEntity3 that = (BasicTestEntity3) o; + BasicTestEntity3 that = (BasicTestEntity3) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; - if (str2 != null ? !str2.equals(that.str2) : that.str2 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } + if ( str2 != null ? !str2.equals( that.str2 ) : that.str2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str1 != null ? str1.hashCode() : 0); - result = 31 * result + (str2 != null ? str2.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str1 != null ? str1.hashCode() : 0); + result = 31 * result + (str2 != null ? str2.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/BasicTestEntity4.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/BasicTestEntity4.java index 6ad0e7ce8a..29e4282594 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/BasicTestEntity4.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/BasicTestEntity4.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.basic; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -34,70 +35,80 @@ import org.hibernate.envers.Audited; @Entity @Audited public class BasicTestEntity4 { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String str1; + private String str1; - private String str2; + private String str2; - public BasicTestEntity4() { - } + public BasicTestEntity4() { + } - public BasicTestEntity4(String str1, String str2) { - this.str1 = str1; - this.str2 = str2; - } + public BasicTestEntity4(String str1, String str2) { + this.str1 = str1; + this.str2 = str2; + } - public BasicTestEntity4(Integer id, String str1, String str2) { - this.id = id; - this.str1 = str1; - this.str2 = str2; - } + public BasicTestEntity4(Integer id, String str1, String str2) { + this.id = id; + this.str1 = str1; + this.str2 = str2; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - public String getStr2() { - return str2; - } + public String getStr2() { + return str2; + } - public void setStr2(String str2) { - this.str2 = str2; - } + public void setStr2(String str2) { + this.str2 = str2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof BasicTestEntity4)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof BasicTestEntity4) ) { + return false; + } - BasicTestEntity4 that = (BasicTestEntity4) o; + BasicTestEntity4 that = (BasicTestEntity4) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; - if (str2 != null ? !str2.equals(that.str2) : that.str2 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } + if ( str2 != null ? !str2.equals( that.str2 ) : that.str2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str1 != null ? str1.hashCode() : 0); - result = 31 * result + (str2 != null ? str2.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str1 != null ? str1.hashCode() : 0); + result = 31 * result + (str2 != null ? str2.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/ColumnScalePrecisionTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/ColumnScalePrecisionTest.java index 5bd1e4222a..d176ee1e8d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/ColumnScalePrecisionTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/ColumnScalePrecisionTest.java @@ -1,15 +1,16 @@ package org.hibernate.envers.test.integration.basic; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.mapping.Column; import org.hibernate.mapping.Table; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -17,51 +18,53 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-7003") public class ColumnScalePrecisionTest extends BaseEnversJPAFunctionalTestCase { - private Table auditTable = null; - private Table originalTable = null; - private Long id = null; + private Table auditTable = null; + private Table originalTable = null; + private Long id = null; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ScalePrecisionEntity.class }; - } + return new Class[] {ScalePrecisionEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 1 - em.getTransaction().begin(); - ScalePrecisionEntity entity = new ScalePrecisionEntity(13.0); - em.persist(entity); - em.getTransaction().commit(); + // Revision 1 + em.getTransaction().begin(); + ScalePrecisionEntity entity = new ScalePrecisionEntity( 13.0 ); + em.persist( entity ); + em.getTransaction().commit(); - id = entity.getId(); - auditTable = getCfg().getClassMapping("org.hibernate.envers.test.integration.basic.ScalePrecisionEntity_AUD").getTable(); - originalTable = getCfg().getClassMapping("org.hibernate.envers.test.integration.basic.ScalePrecisionEntity").getTable(); - } + id = entity.getId(); + auditTable = getCfg().getClassMapping( "org.hibernate.envers.test.integration.basic.ScalePrecisionEntity_AUD" ) + .getTable(); + originalTable = getCfg().getClassMapping( "org.hibernate.envers.test.integration.basic.ScalePrecisionEntity" ) + .getTable(); + } - @Test - public void testColumnScalePrecision() { - Column testColumn = new Column("wholeNumber"); - Column scalePrecisionAuditColumn = auditTable.getColumn(testColumn); - Column scalePrecisionColumn = originalTable.getColumn(testColumn); + @Test + public void testColumnScalePrecision() { + Column testColumn = new Column( "wholeNumber" ); + Column scalePrecisionAuditColumn = auditTable.getColumn( testColumn ); + Column scalePrecisionColumn = originalTable.getColumn( testColumn ); - Assert.assertNotNull(scalePrecisionAuditColumn); - Assert.assertEquals(scalePrecisionColumn.getPrecision(), scalePrecisionAuditColumn.getPrecision()); - Assert.assertEquals(scalePrecisionColumn.getScale(), scalePrecisionAuditColumn.getScale()); - } + Assert.assertNotNull( scalePrecisionAuditColumn ); + Assert.assertEquals( scalePrecisionColumn.getPrecision(), scalePrecisionAuditColumn.getPrecision() ); + Assert.assertEquals( scalePrecisionColumn.getScale(), scalePrecisionAuditColumn.getScale() ); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1).equals(getAuditReader().getRevisions(ScalePrecisionEntity.class, id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( ScalePrecisionEntity.class, id ) ); + } - @Test - public void testHistoryOfScalePrecisionEntity() { - ScalePrecisionEntity ver1 = new ScalePrecisionEntity(13.0, id); + @Test + public void testHistoryOfScalePrecisionEntity() { + ScalePrecisionEntity ver1 = new ScalePrecisionEntity( 13.0, id ); - Assert.assertEquals(ver1, getAuditReader().find(ScalePrecisionEntity.class, id, 1)); - } + Assert.assertEquals( ver1, getAuditReader().find( ScalePrecisionEntity.class, id, 1 ) ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/Delete.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/Delete.java index d3589e03cc..d70e6c761b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/Delete.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/Delete.java @@ -23,116 +23,116 @@ */ package org.hibernate.envers.test.integration.basic; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ -public class Delete extends BaseEnversJPAFunctionalTestCase { - private Integer id1; - private Integer id2; - private Integer id3; +public class Delete extends BaseEnversJPAFunctionalTestCase { + private Integer id1; + private Integer id2; + private Integer id3; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BasicTestEntity2.class }; - } + return new Class[] {BasicTestEntity2.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - BasicTestEntity2 bte1 = new BasicTestEntity2("x", "a"); - BasicTestEntity2 bte2 = new BasicTestEntity2("y", "b"); - BasicTestEntity2 bte3 = new BasicTestEntity2("z", "c"); - em.persist(bte1); - em.persist(bte2); - em.persist(bte3); + BasicTestEntity2 bte1 = new BasicTestEntity2( "x", "a" ); + BasicTestEntity2 bte2 = new BasicTestEntity2( "y", "b" ); + BasicTestEntity2 bte3 = new BasicTestEntity2( "z", "c" ); + em.persist( bte1 ); + em.persist( bte2 ); + em.persist( bte3 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 2 + em = getEntityManager(); + em.getTransaction().begin(); - bte1 = em.find(BasicTestEntity2.class, bte1.getId()); - bte2 = em.find(BasicTestEntity2.class, bte2.getId()); - bte3 = em.find(BasicTestEntity2.class, bte3.getId()); - bte1.setStr1("x2"); - bte2.setStr2("b2"); - em.remove(bte3); + bte1 = em.find( BasicTestEntity2.class, bte1.getId() ); + bte2 = em.find( BasicTestEntity2.class, bte2.getId() ); + bte3 = em.find( BasicTestEntity2.class, bte3.getId() ); + bte1.setStr1( "x2" ); + bte2.setStr2( "b2" ); + em.remove( bte3 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 3 + em = getEntityManager(); + em.getTransaction().begin(); - bte2 = em.find(BasicTestEntity2.class, bte2.getId()); - em.remove(bte2); + bte2 = em.find( BasicTestEntity2.class, bte2.getId() ); + em.remove( bte2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 4 + em = getEntityManager(); + em.getTransaction().begin(); - bte1 = em.find(BasicTestEntity2.class, bte1.getId()); - em.remove(bte1); + bte1 = em.find( BasicTestEntity2.class, bte1.getId() ); + em.remove( bte1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - id1 = bte1.getId(); - id2 = bte2.getId(); - id3 = bte3.getId(); - } + id1 = bte1.getId(); + id2 = bte2.getId(); + id3 = bte3.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 4).equals(getAuditReader().getRevisions(BasicTestEntity2.class, id1)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 4 ).equals( getAuditReader().getRevisions( BasicTestEntity2.class, id1 ) ); - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(BasicTestEntity2.class, id2)); + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( BasicTestEntity2.class, id2 ) ); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(BasicTestEntity2.class, id3)); - } + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( BasicTestEntity2.class, id3 ) ); + } - @Test - public void testHistoryOfId1() { - BasicTestEntity2 ver1 = new BasicTestEntity2(id1, "x", null); - BasicTestEntity2 ver2 = new BasicTestEntity2(id1, "x2", null); + @Test + public void testHistoryOfId1() { + BasicTestEntity2 ver1 = new BasicTestEntity2( id1, "x", null ); + BasicTestEntity2 ver2 = new BasicTestEntity2( id1, "x2", null ); - assert getAuditReader().find(BasicTestEntity2.class, id1, 1).equals(ver1); - assert getAuditReader().find(BasicTestEntity2.class, id1, 2).equals(ver2); - assert getAuditReader().find(BasicTestEntity2.class, id1, 3).equals(ver2); - assert getAuditReader().find(BasicTestEntity2.class, id1, 4) == null; - } + assert getAuditReader().find( BasicTestEntity2.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity2.class, id1, 2 ).equals( ver2 ); + assert getAuditReader().find( BasicTestEntity2.class, id1, 3 ).equals( ver2 ); + assert getAuditReader().find( BasicTestEntity2.class, id1, 4 ) == null; + } - @Test - public void testHistoryOfId2() { - BasicTestEntity2 ver1 = new BasicTestEntity2(id2, "y", null); + @Test + public void testHistoryOfId2() { + BasicTestEntity2 ver1 = new BasicTestEntity2( id2, "y", null ); - assert getAuditReader().find(BasicTestEntity2.class, id2, 1).equals(ver1); - assert getAuditReader().find(BasicTestEntity2.class, id2, 2).equals(ver1); - assert getAuditReader().find(BasicTestEntity2.class, id2, 3) == null; - assert getAuditReader().find(BasicTestEntity2.class, id2, 4) == null; - } + assert getAuditReader().find( BasicTestEntity2.class, id2, 1 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity2.class, id2, 2 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity2.class, id2, 3 ) == null; + assert getAuditReader().find( BasicTestEntity2.class, id2, 4 ) == null; + } - @Test - public void testHistoryOfId3() { - BasicTestEntity2 ver1 = new BasicTestEntity2(id3, "z", null); + @Test + public void testHistoryOfId3() { + BasicTestEntity2 ver1 = new BasicTestEntity2( id3, "z", null ); - assert getAuditReader().find(BasicTestEntity2.class, id3, 1).equals(ver1); - assert getAuditReader().find(BasicTestEntity2.class, id3, 2) == null; - assert getAuditReader().find(BasicTestEntity2.class, id3, 3) == null; - assert getAuditReader().find(BasicTestEntity2.class, id3, 4) == null; - } + assert getAuditReader().find( BasicTestEntity2.class, id3, 1 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity2.class, id3, 2 ) == null; + assert getAuditReader().find( BasicTestEntity2.class, id3, 3 ) == null; + assert getAuditReader().find( BasicTestEntity2.class, id3, 4 ) == null; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/EmptyStringTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/EmptyStringTest.java index 381c28ea9e..e40866fcba 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/EmptyStringTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/EmptyStringTest.java @@ -1,15 +1,16 @@ package org.hibernate.envers.test.integration.basic; -import java.util.Arrays; import javax.persistence.EntityManager; - -import junit.framework.Assert; -import org.junit.Test; +import java.util.Arrays; import org.hibernate.dialect.Oracle8iDialect; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; + +import org.junit.Test; +import junit.framework.Assert; + import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.TestForIssue; @@ -19,49 +20,49 @@ import org.hibernate.testing.TestForIssue; @TestForIssue(jiraKey = "HHH-7246") @RequiresDialect(Oracle8iDialect.class) public class EmptyStringTest extends BaseEnversJPAFunctionalTestCase { - private Integer emptyId = null; - private Integer nullId = null; + private Integer emptyId = null; + private Integer nullId = null; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{StrTestEntity.class}; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {StrTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 1 - em.getTransaction().begin(); - StrTestEntity emptyEntity = new StrTestEntity(""); - em.persist(emptyEntity); - StrTestEntity nullEntity = new StrTestEntity(null); - em.persist(nullEntity); - em.getTransaction().commit(); + // Revision 1 + em.getTransaction().begin(); + StrTestEntity emptyEntity = new StrTestEntity( "" ); + em.persist( emptyEntity ); + StrTestEntity nullEntity = new StrTestEntity( null ); + em.persist( nullEntity ); + em.getTransaction().commit(); - emptyId = emptyEntity.getId(); - nullId = nullEntity.getId(); + emptyId = emptyEntity.getId(); + nullId = nullEntity.getId(); - em.close(); - em = getEntityManager(); + em.close(); + em = getEntityManager(); - // Should not generate revision after NULL to "" modification and vice versa on Oracle. - em.getTransaction().begin(); - emptyEntity = em.find(StrTestEntity.class, emptyId); - emptyEntity.setStr(null); - em.merge(emptyEntity); - nullEntity = em.find(StrTestEntity.class, nullId); - nullEntity.setStr(""); - em.merge(nullEntity); - em.getTransaction().commit(); + // Should not generate revision after NULL to "" modification and vice versa on Oracle. + em.getTransaction().begin(); + emptyEntity = em.find( StrTestEntity.class, emptyId ); + emptyEntity.setStr( null ); + em.merge( emptyEntity ); + nullEntity = em.find( StrTestEntity.class, nullId ); + nullEntity.setStr( "" ); + em.merge( nullEntity ); + em.getTransaction().commit(); - em.close(); - } + em.close(); + } - @Test - public void testRevisionsCounts() { - Assert.assertEquals(Arrays.asList(1), getAuditReader().getRevisions(StrTestEntity.class, emptyId)); - Assert.assertEquals(Arrays.asList(1), getAuditReader().getRevisions(StrTestEntity.class, nullId)); - } + @Test + public void testRevisionsCounts() { + Assert.assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( StrTestEntity.class, emptyId ) ); + Assert.assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( StrTestEntity.class, nullId ) ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/GlobalVersioned.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/GlobalVersioned.java index b323016d17..e51a25816f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/GlobalVersioned.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/GlobalVersioned.java @@ -23,53 +23,53 @@ */ package org.hibernate.envers.test.integration.basic; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class GlobalVersioned extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BasicTestEntity4.class }; - } + return new Class[] {BasicTestEntity4.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - BasicTestEntity4 bte1 = new BasicTestEntity4("x", "y"); - em.persist(bte1); - id1 = bte1.getId(); - em.getTransaction().commit(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + BasicTestEntity4 bte1 = new BasicTestEntity4( "x", "y" ); + em.persist( bte1 ); + id1 = bte1.getId(); + em.getTransaction().commit(); - em.getTransaction().begin(); - bte1 = em.find(BasicTestEntity4.class, id1); - bte1.setStr1("a"); - bte1.setStr2("b"); - em.getTransaction().commit(); - } + em.getTransaction().begin(); + bte1 = em.find( BasicTestEntity4.class, id1 ); + bte1.setStr1( "a" ); + bte1.setStr2( "b" ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(BasicTestEntity4.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( BasicTestEntity4.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - BasicTestEntity4 ver1 = new BasicTestEntity4(id1, "x", "y"); - BasicTestEntity4 ver2 = new BasicTestEntity4(id1, "a", "b"); + @Test + public void testHistoryOfId1() { + BasicTestEntity4 ver1 = new BasicTestEntity4( id1, "x", "y" ); + BasicTestEntity4 ver2 = new BasicTestEntity4( id1, "a", "b" ); - assert getAuditReader().find(BasicTestEntity4.class, id1, 1).equals(ver1); - assert getAuditReader().find(BasicTestEntity4.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( BasicTestEntity4.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity4.class, id1, 2 ).equals( ver2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/ManyOperationsInTransaction.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/ManyOperationsInTransaction.java index c61fff3dbe..46d928c589 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/ManyOperationsInTransaction.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/ManyOperationsInTransaction.java @@ -23,107 +23,107 @@ */ package org.hibernate.envers.test.integration.basic; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class ManyOperationsInTransaction extends BaseEnversJPAFunctionalTestCase { - private Integer id1; - private Integer id2; - private Integer id3; + private Integer id1; + private Integer id2; + private Integer id3; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BasicTestEntity1.class }; - } + return new Class[] {BasicTestEntity1.class}; + } - @Test + @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - BasicTestEntity1 bte1 = new BasicTestEntity1("x", 1); - BasicTestEntity1 bte2 = new BasicTestEntity1("y", 20); - em.persist(bte1); - em.persist(bte2); + BasicTestEntity1 bte1 = new BasicTestEntity1( "x", 1 ); + BasicTestEntity1 bte2 = new BasicTestEntity1( "y", 20 ); + em.persist( bte1 ); + em.persist( bte2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - bte1 = em.find(BasicTestEntity1.class, bte1.getId()); - bte2 = em.find(BasicTestEntity1.class, bte2.getId()); - BasicTestEntity1 bte3 = new BasicTestEntity1("z", 300); - bte1.setStr1("x2"); - bte2.setLong1(21); - em.persist(bte3); + bte1 = em.find( BasicTestEntity1.class, bte1.getId() ); + bte2 = em.find( BasicTestEntity1.class, bte2.getId() ); + BasicTestEntity1 bte3 = new BasicTestEntity1( "z", 300 ); + bte1.setStr1( "x2" ); + bte2.setLong1( 21 ); + em.persist( bte3 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - bte2 = em.find(BasicTestEntity1.class, bte2.getId()); - bte3 = em.find(BasicTestEntity1.class, bte3.getId()); - bte2.setStr1("y3"); - bte2.setLong1(22); - bte3.setStr1("z3"); + bte2 = em.find( BasicTestEntity1.class, bte2.getId() ); + bte3 = em.find( BasicTestEntity1.class, bte3.getId() ); + bte2.setStr1( "y3" ); + bte2.setLong1( 22 ); + bte3.setStr1( "z3" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - id1 = bte1.getId(); - id2 = bte2.getId(); - id3 = bte3.getId(); - } + id1 = bte1.getId(); + id2 = bte2.getId(); + id3 = bte3.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(BasicTestEntity1.class, id1)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( BasicTestEntity1.class, id1 ) ); - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(BasicTestEntity1.class, id2)); + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( BasicTestEntity1.class, id2 ) ); - assert Arrays.asList(2, 3).equals(getAuditReader().getRevisions(BasicTestEntity1.class, id3)); - } + assert Arrays.asList( 2, 3 ).equals( getAuditReader().getRevisions( BasicTestEntity1.class, id3 ) ); + } - @Test - public void testHistoryOfId1() { - BasicTestEntity1 ver1 = new BasicTestEntity1(id1, "x", 1); - BasicTestEntity1 ver2 = new BasicTestEntity1(id1, "x2", 1); + @Test + public void testHistoryOfId1() { + BasicTestEntity1 ver1 = new BasicTestEntity1( id1, "x", 1 ); + BasicTestEntity1 ver2 = new BasicTestEntity1( id1, "x2", 1 ); - assert getAuditReader().find(BasicTestEntity1.class, id1, 1).equals(ver1); - assert getAuditReader().find(BasicTestEntity1.class, id1, 2).equals(ver2); - assert getAuditReader().find(BasicTestEntity1.class, id1, 3).equals(ver2); - } + assert getAuditReader().find( BasicTestEntity1.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity1.class, id1, 2 ).equals( ver2 ); + assert getAuditReader().find( BasicTestEntity1.class, id1, 3 ).equals( ver2 ); + } - @Test - public void testHistoryOfId2() { - BasicTestEntity1 ver1 = new BasicTestEntity1(id2, "y", 20); - BasicTestEntity1 ver2 = new BasicTestEntity1(id2, "y", 21); - BasicTestEntity1 ver3 = new BasicTestEntity1(id2, "y3", 22); + @Test + public void testHistoryOfId2() { + BasicTestEntity1 ver1 = new BasicTestEntity1( id2, "y", 20 ); + BasicTestEntity1 ver2 = new BasicTestEntity1( id2, "y", 21 ); + BasicTestEntity1 ver3 = new BasicTestEntity1( id2, "y3", 22 ); - assert getAuditReader().find(BasicTestEntity1.class, id2, 1).equals(ver1); - assert getAuditReader().find(BasicTestEntity1.class, id2, 2).equals(ver2); - assert getAuditReader().find(BasicTestEntity1.class, id2, 3).equals(ver3); - } + assert getAuditReader().find( BasicTestEntity1.class, id2, 1 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity1.class, id2, 2 ).equals( ver2 ); + assert getAuditReader().find( BasicTestEntity1.class, id2, 3 ).equals( ver3 ); + } - @Test - public void testHistoryOfId3() { - BasicTestEntity1 ver1 = new BasicTestEntity1(id3, "z", 300); - BasicTestEntity1 ver2 = new BasicTestEntity1(id3, "z3", 300); + @Test + public void testHistoryOfId3() { + BasicTestEntity1 ver1 = new BasicTestEntity1( id3, "z", 300 ); + BasicTestEntity1 ver2 = new BasicTestEntity1( id3, "z3", 300 ); - assert getAuditReader().find(BasicTestEntity1.class, id3, 1) == null; - assert getAuditReader().find(BasicTestEntity1.class, id3, 2).equals(ver1); - assert getAuditReader().find(BasicTestEntity1.class, id3, 3).equals(ver2); - } + assert getAuditReader().find( BasicTestEntity1.class, id3, 1 ) == null; + assert getAuditReader().find( BasicTestEntity1.class, id3, 2 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity1.class, id3, 3 ).equals( ver2 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/NoneAudited.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/NoneAudited.java index f294ef5d99..2acf054521 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/NoneAudited.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/NoneAudited.java @@ -27,34 +27,34 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import org.junit.Assert; -import org.junit.Test; - import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.mapping.PersistentClass; +import org.junit.Assert; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class NoneAudited extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BasicTestEntity3.class }; - } + return new Class[] {BasicTestEntity3.class}; + } - @Test - public void testRevisionInfoTableNotCreated() { - @SuppressWarnings({"unchecked"}) List pcs = iteratorToList(getCfg().getClassMappings()); - Assert.assertEquals(1, pcs.size()); - Assert.assertTrue(pcs.get(0).getClassName().contains("BasicTestEntity3")); - } + @Test + public void testRevisionInfoTableNotCreated() { + @SuppressWarnings({"unchecked"}) List pcs = iteratorToList( getCfg().getClassMappings() ); + Assert.assertEquals( 1, pcs.size() ); + Assert.assertTrue( pcs.get( 0 ).getClassName().contains( "BasicTestEntity3" ) ); + } - private List iteratorToList(Iterator it) { - List result = new ArrayList(); - while (it.hasNext()) { - result.add(it.next()); - } + private List iteratorToList(Iterator it) { + List result = new ArrayList(); + while ( it.hasNext() ) { + result.add( it.next() ); + } - return result; - } + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/NotVersioned.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/NotVersioned.java index d9311d97f0..6cd5ee2be6 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/NotVersioned.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/NotVersioned.java @@ -25,47 +25,47 @@ package org.hibernate.envers.test.integration.basic; import javax.persistence.EntityManager; -import org.junit.Test; - import org.hibernate.envers.exception.NotAuditedException; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class NotVersioned extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BasicTestEntity1.class, BasicTestEntity3.class }; - } + return new Class[] {BasicTestEntity1.class, BasicTestEntity3.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - BasicTestEntity3 bte1 = new BasicTestEntity3("x", "y"); - em.persist(bte1); - id1 = bte1.getId(); - em.getTransaction().commit(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + BasicTestEntity3 bte1 = new BasicTestEntity3( "x", "y" ); + em.persist( bte1 ); + id1 = bte1.getId(); + em.getTransaction().commit(); - em.getTransaction().begin(); - bte1 = em.find(BasicTestEntity3.class, id1); - bte1.setStr1("a"); - bte1.setStr2("b"); - em.getTransaction().commit(); - } + em.getTransaction().begin(); + bte1 = em.find( BasicTestEntity3.class, id1 ); + bte1.setStr1( "a" ); + bte1.setStr2( "b" ); + em.getTransaction().commit(); + } - @Test(expected = NotAuditedException.class) - public void testRevisionsCounts() { - getAuditReader().getRevisions(BasicTestEntity3.class, id1); - } + @Test(expected = NotAuditedException.class) + public void testRevisionsCounts() { + getAuditReader().getRevisions( BasicTestEntity3.class, id1 ); + } - @Test(expected = NotAuditedException.class) - public void testHistoryOfId1() { - getAuditReader().find(BasicTestEntity3.class, id1, 1); - } + @Test(expected = NotAuditedException.class) + public void testHistoryOfId1() { + getAuditReader().find( BasicTestEntity3.class, id1, 1 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/NullProperties.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/NullProperties.java index 35e32268d2..b6dc7febd4 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/NullProperties.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/NullProperties.java @@ -23,81 +23,81 @@ */ package org.hibernate.envers.test.integration.basic; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class NullProperties extends BaseEnversJPAFunctionalTestCase { - private Integer id1; - private Integer id2; + private Integer id1; + private Integer id2; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BasicTestEntity1.class }; - } + return new Class[] {BasicTestEntity1.class}; + } - private Integer addNewEntity(String str, long lng) { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - BasicTestEntity1 bte1 = new BasicTestEntity1(str, lng); - em.persist(bte1); - em.getTransaction().commit(); + private Integer addNewEntity(String str, long lng) { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + BasicTestEntity1 bte1 = new BasicTestEntity1( str, lng ); + em.persist( bte1 ); + em.getTransaction().commit(); - return bte1.getId(); - } + return bte1.getId(); + } - private void modifyEntity(Integer id, String str, long lng) { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - BasicTestEntity1 bte1 = em.find(BasicTestEntity1.class, id); - bte1.setLong1(lng); - bte1.setStr1(str); - em.getTransaction().commit(); - } + private void modifyEntity(Integer id, String str, long lng) { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + BasicTestEntity1 bte1 = em.find( BasicTestEntity1.class, id ); + bte1.setLong1( lng ); + bte1.setStr1( str ); + em.getTransaction().commit(); + } - @Test - @Priority(10) - public void initData() { - id1 = addNewEntity("x", 1); // rev 1 - id2 = addNewEntity(null, 20); // rev 2 + @Test + @Priority(10) + public void initData() { + id1 = addNewEntity( "x", 1 ); // rev 1 + id2 = addNewEntity( null, 20 ); // rev 2 - modifyEntity(id1, null, 1); // rev 3 - modifyEntity(id2, "y2", 20); // rev 4 - } + modifyEntity( id1, null, 1 ); // rev 3 + modifyEntity( id2, "y2", 20 ); // rev 4 + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(BasicTestEntity1.class, id1)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( BasicTestEntity1.class, id1 ) ); - assert Arrays.asList(2, 4).equals(getAuditReader().getRevisions(BasicTestEntity1.class, id2)); - } + assert Arrays.asList( 2, 4 ).equals( getAuditReader().getRevisions( BasicTestEntity1.class, id2 ) ); + } - @Test - public void testHistoryOfId1() { - BasicTestEntity1 ver1 = new BasicTestEntity1(id1, "x", 1); - BasicTestEntity1 ver2 = new BasicTestEntity1(id1, null, 1); + @Test + public void testHistoryOfId1() { + BasicTestEntity1 ver1 = new BasicTestEntity1( id1, "x", 1 ); + BasicTestEntity1 ver2 = new BasicTestEntity1( id1, null, 1 ); - assert getAuditReader().find(BasicTestEntity1.class, id1, 1).equals(ver1); - assert getAuditReader().find(BasicTestEntity1.class, id1, 2).equals(ver1); - assert getAuditReader().find(BasicTestEntity1.class, id1, 3).equals(ver2); - assert getAuditReader().find(BasicTestEntity1.class, id1, 4).equals(ver2); - } + assert getAuditReader().find( BasicTestEntity1.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity1.class, id1, 2 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity1.class, id1, 3 ).equals( ver2 ); + assert getAuditReader().find( BasicTestEntity1.class, id1, 4 ).equals( ver2 ); + } - @Test - public void testHistoryOfId2() { - BasicTestEntity1 ver1 = new BasicTestEntity1(id2, null, 20); - BasicTestEntity1 ver2 = new BasicTestEntity1(id2, "y2", 20); + @Test + public void testHistoryOfId2() { + BasicTestEntity1 ver1 = new BasicTestEntity1( id2, null, 20 ); + BasicTestEntity1 ver2 = new BasicTestEntity1( id2, "y2", 20 ); - assert getAuditReader().find(BasicTestEntity1.class, id2, 1) == null; - assert getAuditReader().find(BasicTestEntity1.class, id2, 2).equals(ver1); - assert getAuditReader().find(BasicTestEntity1.class, id2, 3).equals(ver1); - assert getAuditReader().find(BasicTestEntity1.class, id2, 4).equals(ver2); - } + assert getAuditReader().find( BasicTestEntity1.class, id2, 1 ) == null; + assert getAuditReader().find( BasicTestEntity1.class, id2, 2 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity1.class, id2, 3 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity1.class, id2, 4 ).equals( ver2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/OutsideTransactionTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/OutsideTransactionTest.java index 7eeffd735f..32129e1431 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/OutsideTransactionTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/OutsideTransactionTest.java @@ -1,7 +1,5 @@ package org.hibernate.envers.test.integration.basic; -import org.junit.Test; - import org.hibernate.Session; import org.hibernate.cfg.Configuration; import org.hibernate.envers.configuration.EnversSettings; @@ -10,6 +8,9 @@ import org.hibernate.envers.test.BaseEnversFunctionalTestCase; import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.integration.collection.norevision.Name; import org.hibernate.envers.test.integration.collection.norevision.Person; + +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -17,103 +18,103 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-5565") public class OutsideTransactionTest extends BaseEnversFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{StrTestEntity.class, Person.class, Name.class}; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {StrTestEntity.class, Person.class, Name.class}; + } - @Override - protected void configure(Configuration configuration) { - configuration.setProperty(EnversSettings.STORE_DATA_AT_DELETE, "true"); - configuration.setProperty(EnversSettings.REVISION_ON_COLLECTION_CHANGE, "true"); - } + @Override + protected void configure(Configuration configuration) { + configuration.setProperty( EnversSettings.STORE_DATA_AT_DELETE, "true" ); + configuration.setProperty( EnversSettings.REVISION_ON_COLLECTION_CHANGE, "true" ); + } - @Test(expected = AuditException.class) - public void testInsertOutsideActiveTransaction() { - Session session = openSession(); + @Test(expected = AuditException.class) + public void testInsertOutsideActiveTransaction() { + Session session = openSession(); - // Illegal insertion of entity outside of active transaction. - StrTestEntity entity = new StrTestEntity("data"); - session.persist(entity); - session.flush(); + // Illegal insertion of entity outside of active transaction. + StrTestEntity entity = new StrTestEntity( "data" ); + session.persist( entity ); + session.flush(); - session.close(); - } + session.close(); + } - @Test(expected = AuditException.class) - public void testUpdateOutsideActiveTransaction() { - Session session = openSession(); + @Test(expected = AuditException.class) + public void testUpdateOutsideActiveTransaction() { + Session session = openSession(); - // Revision 1 - session.getTransaction().begin(); - StrTestEntity entity = new StrTestEntity("data"); - session.persist(entity); - session.getTransaction().commit(); + // Revision 1 + session.getTransaction().begin(); + StrTestEntity entity = new StrTestEntity( "data" ); + session.persist( entity ); + session.getTransaction().commit(); - // Illegal modification of entity state outside of active transaction. - entity.setStr("modified data"); - session.update(entity); - session.flush(); + // Illegal modification of entity state outside of active transaction. + entity.setStr( "modified data" ); + session.update( entity ); + session.flush(); - session.close(); - } + session.close(); + } - @Test(expected = AuditException.class) - public void testDeleteOutsideActiveTransaction() { - Session session = openSession(); + @Test(expected = AuditException.class) + public void testDeleteOutsideActiveTransaction() { + Session session = openSession(); - // Revision 1 - session.getTransaction().begin(); - StrTestEntity entity = new StrTestEntity("data"); - session.persist(entity); - session.getTransaction().commit(); + // Revision 1 + session.getTransaction().begin(); + StrTestEntity entity = new StrTestEntity( "data" ); + session.persist( entity ); + session.getTransaction().commit(); - // Illegal removal of entity outside of active transaction. - session.delete(entity); - session.flush(); + // Illegal removal of entity outside of active transaction. + session.delete( entity ); + session.flush(); - session.close(); - } + session.close(); + } - @Test(expected = AuditException.class) - public void testCollectionUpdateOutsideActiveTransaction() { - Session session = openSession(); + @Test(expected = AuditException.class) + public void testCollectionUpdateOutsideActiveTransaction() { + Session session = openSession(); - // Revision 1 - session.getTransaction().begin(); - Person person = new Person(); - Name name = new Name(); - name.setName("Name"); - person.getNames().add(name); - session.saveOrUpdate(person); - session.getTransaction().commit(); + // Revision 1 + session.getTransaction().begin(); + Person person = new Person(); + Name name = new Name(); + name.setName( "Name" ); + person.getNames().add( name ); + session.saveOrUpdate( person ); + session.getTransaction().commit(); - // Illegal collection update outside of active transaction. - person.getNames().remove(name); - session.saveOrUpdate(person); - session.flush(); + // Illegal collection update outside of active transaction. + person.getNames().remove( name ); + session.saveOrUpdate( person ); + session.flush(); - session.close(); - } + session.close(); + } - @Test(expected = AuditException.class) - public void testCollectionRemovalOutsideActiveTransaction() { - Session session = openSession(); + @Test(expected = AuditException.class) + public void testCollectionRemovalOutsideActiveTransaction() { + Session session = openSession(); - // Revision 1 - session.getTransaction().begin(); - Person person = new Person(); - Name name = new Name(); - name.setName("Name"); - person.getNames().add(name); - session.saveOrUpdate(person); - session.getTransaction().commit(); + // Revision 1 + session.getTransaction().begin(); + Person person = new Person(); + Name name = new Name(); + name.setName( "Name" ); + person.getNames().add( name ); + session.saveOrUpdate( person ); + session.getTransaction().commit(); - // Illegal collection removal outside of active transaction. - person.setNames(null); - session.saveOrUpdate(person); - session.flush(); + // Illegal collection removal outside of active transaction. + person.setNames( null ); + session.saveOrUpdate( person ); + session.flush(); - session.close(); - } + session.close(); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/RegisterUserEventListenersTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/RegisterUserEventListenersTest.java index 094a08fb52..3f7a090e18 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/RegisterUserEventListenersTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/RegisterUserEventListenersTest.java @@ -12,23 +12,26 @@ import org.hibernate.event.spi.EventType; import org.hibernate.event.spi.PostInsertEvent; import org.hibernate.event.spi.PostInsertEventListener; import org.hibernate.persister.entity.EntityPersister; -import org.hibernate.testing.TestForIssue; + import org.junit.Assert; import org.junit.Test; +import org.hibernate.testing.TestForIssue; + /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class RegisterUserEventListenersTest extends BaseEnversFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class }; + return new Class[] {StrTestEntity.class}; } @Test - @TestForIssue( jiraKey = "HHH-7478" ) + @TestForIssue(jiraKey = "HHH-7478") public void testTransactionProcessSynchronization() { - final EventListenerRegistry registry = sessionFactory().getServiceRegistry().getService( EventListenerRegistry.class ); + final EventListenerRegistry registry = sessionFactory().getServiceRegistry() + .getService( EventListenerRegistry.class ); final CountingPostInsertTransactionBoundaryListener listener = new CountingPostInsertTransactionBoundaryListener(); registry.getEventListenerGroup( EventType.POST_INSERT ).appendListener( listener ); @@ -52,18 +55,22 @@ public class RegisterUserEventListenersTest extends BaseEnversFunctionalTestCase @Override public void onPostInsert(PostInsertEvent event) { - event.getSession().getActionQueue().registerProcess(new BeforeTransactionCompletionProcess() { - @Override - public void doBeforeTransactionCompletion(SessionImplementor session) { - beforeCounter.increase(); - } - }); - event.getSession().getActionQueue().registerProcess(new AfterTransactionCompletionProcess() { - @Override - public void doAfterTransactionCompletion(boolean success, SessionImplementor session) { - afterCounter.increase(); - } - }); + event.getSession().getActionQueue().registerProcess( + new BeforeTransactionCompletionProcess() { + @Override + public void doBeforeTransactionCompletion(SessionImplementor session) { + beforeCounter.increase(); + } + } + ); + event.getSession().getActionQueue().registerProcess( + new AfterTransactionCompletionProcess() { + @Override + public void doAfterTransactionCompletion(boolean success, SessionImplementor session) { + afterCounter.increase(); + } + } + ); } @Override diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/ScalePrecisionEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/ScalePrecisionEntity.java index 2139e4430b..a3c5a20e14 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/ScalePrecisionEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/ScalePrecisionEntity.java @@ -1,10 +1,10 @@ package org.hibernate.envers.test.integration.basic; -import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -14,63 +14,71 @@ import org.hibernate.envers.Audited; @Entity @Audited public class ScalePrecisionEntity implements Serializable { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @Column(precision = 3, scale = 0) - private Double wholeNumber; + @Column(precision = 3, scale = 0) + private Double wholeNumber; - public ScalePrecisionEntity() { - } + public ScalePrecisionEntity() { + } - public ScalePrecisionEntity(Double wholeNumber) { - this.wholeNumber = wholeNumber; - } + public ScalePrecisionEntity(Double wholeNumber) { + this.wholeNumber = wholeNumber; + } - public ScalePrecisionEntity(Double wholeNumber, Long id) { - this.id = id; - this.wholeNumber = wholeNumber; - } + public ScalePrecisionEntity(Double wholeNumber, Long id) { + this.id = id; + this.wholeNumber = wholeNumber; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ScalePrecisionEntity)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ScalePrecisionEntity) ) { + return false; + } - ScalePrecisionEntity that = (ScalePrecisionEntity) o; + ScalePrecisionEntity that = (ScalePrecisionEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (wholeNumber != null ? !wholeNumber.equals(that.wholeNumber) : that.wholeNumber != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( wholeNumber != null ? !wholeNumber.equals( that.wholeNumber ) : that.wholeNumber != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (wholeNumber != null ? wholeNumber.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (wholeNumber != null ? wholeNumber.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "ScalePrecisionEntity(id = " + id + ", wholeNumber = " + wholeNumber + ")"; - } + @Override + public String toString() { + return "ScalePrecisionEntity(id = " + id + ", wholeNumber = " + wholeNumber + ")"; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public Double getWholeNumber() { - return wholeNumber; - } + public Double getWholeNumber() { + return wholeNumber; + } - public void setWholeNumber(Double wholeNumber) { - this.wholeNumber = wholeNumber; - } + public void setWholeNumber(Double wholeNumber) { + this.wholeNumber = wholeNumber; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/Simple.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/Simple.java index 612a276763..757b8c0923 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/Simple.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/Simple.java @@ -23,53 +23,53 @@ */ package org.hibernate.envers.test.integration.basic; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.IntTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class Simple extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { IntTestEntity.class }; - } + return new Class[] {IntTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - IntTestEntity ite = new IntTestEntity(10); - em.persist(ite); - id1 = ite.getId(); - em.getTransaction().commit(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + IntTestEntity ite = new IntTestEntity( 10 ); + em.persist( ite ); + id1 = ite.getId(); + em.getTransaction().commit(); - em.getTransaction().begin(); - ite = em.find(IntTestEntity.class, id1); - ite.setNumber(20); - em.getTransaction().commit(); - } + em.getTransaction().begin(); + ite = em.find( IntTestEntity.class, id1 ); + ite.setNumber( 20 ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(IntTestEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( IntTestEntity.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - IntTestEntity ver1 = new IntTestEntity(10, id1); - IntTestEntity ver2 = new IntTestEntity(20, id1); + @Test + public void testHistoryOfId1() { + IntTestEntity ver1 = new IntTestEntity( 10, id1 ); + IntTestEntity ver2 = new IntTestEntity( 20, id1 ); - assert getAuditReader().find(IntTestEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(IntTestEntity.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( IntTestEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( IntTestEntity.class, id1, 2 ).equals( ver2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/SingleOperationInTransaction.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/SingleOperationInTransaction.java index afe4c5f529..8e1b074b4a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/SingleOperationInTransaction.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/SingleOperationInTransaction.java @@ -23,139 +23,139 @@ */ package org.hibernate.envers.test.integration.basic; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.exception.RevisionDoesNotExistException; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class SingleOperationInTransaction extends BaseEnversJPAFunctionalTestCase { - private Integer id1; - private Integer id2; - private Integer id3; + private Integer id1; + private Integer id2; + private Integer id3; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BasicTestEntity1.class }; - } + return new Class[] {BasicTestEntity1.class}; + } - private Integer addNewEntity(String str, long lng) { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - BasicTestEntity1 bte1 = new BasicTestEntity1(str, lng); - em.persist(bte1); - em.getTransaction().commit(); + private Integer addNewEntity(String str, long lng) { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + BasicTestEntity1 bte1 = new BasicTestEntity1( str, lng ); + em.persist( bte1 ); + em.getTransaction().commit(); - return bte1.getId(); - } + return bte1.getId(); + } - private void modifyEntity(Integer id, String str, long lng) { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - BasicTestEntity1 bte1 = em.find(BasicTestEntity1.class, id); - bte1.setLong1(lng); - bte1.setStr1(str); - em.getTransaction().commit(); - } + private void modifyEntity(Integer id, String str, long lng) { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + BasicTestEntity1 bte1 = em.find( BasicTestEntity1.class, id ); + bte1.setLong1( lng ); + bte1.setStr1( str ); + em.getTransaction().commit(); + } - @Test - @Priority(10) - public void initData() { - id1 = addNewEntity("x", 1); // rev 1 - id2 = addNewEntity("y", 20); // rev 2 - id3 = addNewEntity("z", 30); // rev 3 + @Test + @Priority(10) + public void initData() { + id1 = addNewEntity( "x", 1 ); // rev 1 + id2 = addNewEntity( "y", 20 ); // rev 2 + id3 = addNewEntity( "z", 30 ); // rev 3 - modifyEntity(id1, "x2", 2); // rev 4 - modifyEntity(id2, "y2", 20); // rev 5 - modifyEntity(id1, "x3", 3); // rev 6 - modifyEntity(id1, "x3", 3); // no rev - modifyEntity(id2, "y3", 21); // rev 7 - } + modifyEntity( id1, "x2", 2 ); // rev 4 + modifyEntity( id2, "y2", 20 ); // rev 5 + modifyEntity( id1, "x3", 3 ); // rev 6 + modifyEntity( id1, "x3", 3 ); // no rev + modifyEntity( id2, "y3", 21 ); // rev 7 + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 4, 6).equals(getAuditReader().getRevisions(BasicTestEntity1.class, id1)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 4, 6 ).equals( getAuditReader().getRevisions( BasicTestEntity1.class, id1 ) ); - assert Arrays.asList(2, 5, 7).equals(getAuditReader().getRevisions(BasicTestEntity1.class, id2)); + assert Arrays.asList( 2, 5, 7 ).equals( getAuditReader().getRevisions( BasicTestEntity1.class, id2 ) ); - assert Arrays.asList(3).equals(getAuditReader().getRevisions(BasicTestEntity1.class, id3)); - } + assert Arrays.asList( 3 ).equals( getAuditReader().getRevisions( BasicTestEntity1.class, id3 ) ); + } - @Test - public void testRevisionsDates() { - for (int i=1; i<7; i++) { - assert getAuditReader().getRevisionDate(i).getTime() <= - getAuditReader().getRevisionDate(i+1).getTime(); - } - } + @Test + public void testRevisionsDates() { + for ( int i = 1; i < 7; i++ ) { + assert getAuditReader().getRevisionDate( i ).getTime() <= + getAuditReader().getRevisionDate( i + 1 ).getTime(); + } + } - @Test(expected = RevisionDoesNotExistException.class) - public void testNotExistingRevision() { - getAuditReader().getRevisionDate(8); - } + @Test(expected = RevisionDoesNotExistException.class) + public void testNotExistingRevision() { + getAuditReader().getRevisionDate( 8 ); + } - @Test(expected = IllegalArgumentException.class) - public void testIllegalRevision() { - getAuditReader().getRevisionDate(0); - } + @Test(expected = IllegalArgumentException.class) + public void testIllegalRevision() { + getAuditReader().getRevisionDate( 0 ); + } - @Test - public void testHistoryOfId1() { - BasicTestEntity1 ver1 = new BasicTestEntity1(id1, "x", 1); - BasicTestEntity1 ver2 = new BasicTestEntity1(id1, "x2", 2); - BasicTestEntity1 ver3 = new BasicTestEntity1(id1, "x3", 3); + @Test + public void testHistoryOfId1() { + BasicTestEntity1 ver1 = new BasicTestEntity1( id1, "x", 1 ); + BasicTestEntity1 ver2 = new BasicTestEntity1( id1, "x2", 2 ); + BasicTestEntity1 ver3 = new BasicTestEntity1( id1, "x3", 3 ); - assert getAuditReader().find(BasicTestEntity1.class, id1, 1).equals(ver1); - assert getAuditReader().find(BasicTestEntity1.class, id1, 2).equals(ver1); - assert getAuditReader().find(BasicTestEntity1.class, id1, 3).equals(ver1); - assert getAuditReader().find(BasicTestEntity1.class, id1, 4).equals(ver2); - assert getAuditReader().find(BasicTestEntity1.class, id1, 5).equals(ver2); - assert getAuditReader().find(BasicTestEntity1.class, id1, 6).equals(ver3); - assert getAuditReader().find(BasicTestEntity1.class, id1, 7).equals(ver3); - } + assert getAuditReader().find( BasicTestEntity1.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity1.class, id1, 2 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity1.class, id1, 3 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity1.class, id1, 4 ).equals( ver2 ); + assert getAuditReader().find( BasicTestEntity1.class, id1, 5 ).equals( ver2 ); + assert getAuditReader().find( BasicTestEntity1.class, id1, 6 ).equals( ver3 ); + assert getAuditReader().find( BasicTestEntity1.class, id1, 7 ).equals( ver3 ); + } - @Test - public void testHistoryOfId2() { - BasicTestEntity1 ver1 = new BasicTestEntity1(id2, "y", 20); - BasicTestEntity1 ver2 = new BasicTestEntity1(id2, "y2", 20); - BasicTestEntity1 ver3 = new BasicTestEntity1(id2, "y3", 21); + @Test + public void testHistoryOfId2() { + BasicTestEntity1 ver1 = new BasicTestEntity1( id2, "y", 20 ); + BasicTestEntity1 ver2 = new BasicTestEntity1( id2, "y2", 20 ); + BasicTestEntity1 ver3 = new BasicTestEntity1( id2, "y3", 21 ); - assert getAuditReader().find(BasicTestEntity1.class, id2, 1) == null; - assert getAuditReader().find(BasicTestEntity1.class, id2, 2).equals(ver1); - assert getAuditReader().find(BasicTestEntity1.class, id2, 3).equals(ver1); - assert getAuditReader().find(BasicTestEntity1.class, id2, 4).equals(ver1); - assert getAuditReader().find(BasicTestEntity1.class, id2, 5).equals(ver2); - assert getAuditReader().find(BasicTestEntity1.class, id2, 6).equals(ver2); - assert getAuditReader().find(BasicTestEntity1.class, id2, 7).equals(ver3); - } + assert getAuditReader().find( BasicTestEntity1.class, id2, 1 ) == null; + assert getAuditReader().find( BasicTestEntity1.class, id2, 2 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity1.class, id2, 3 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity1.class, id2, 4 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity1.class, id2, 5 ).equals( ver2 ); + assert getAuditReader().find( BasicTestEntity1.class, id2, 6 ).equals( ver2 ); + assert getAuditReader().find( BasicTestEntity1.class, id2, 7 ).equals( ver3 ); + } - @Test - public void testHistoryOfId3() { - BasicTestEntity1 ver1 = new BasicTestEntity1(id3, "z", 30); + @Test + public void testHistoryOfId3() { + BasicTestEntity1 ver1 = new BasicTestEntity1( id3, "z", 30 ); - assert getAuditReader().find(BasicTestEntity1.class, id3, 1) == null; - assert getAuditReader().find(BasicTestEntity1.class, id3, 2) == null; - assert getAuditReader().find(BasicTestEntity1.class, id3, 3).equals(ver1); - assert getAuditReader().find(BasicTestEntity1.class, id3, 4).equals(ver1); - assert getAuditReader().find(BasicTestEntity1.class, id3, 5).equals(ver1); - assert getAuditReader().find(BasicTestEntity1.class, id3, 6).equals(ver1); - assert getAuditReader().find(BasicTestEntity1.class, id3, 7).equals(ver1); - } + assert getAuditReader().find( BasicTestEntity1.class, id3, 1 ) == null; + assert getAuditReader().find( BasicTestEntity1.class, id3, 2 ) == null; + assert getAuditReader().find( BasicTestEntity1.class, id3, 3 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity1.class, id3, 4 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity1.class, id3, 5 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity1.class, id3, 6 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity1.class, id3, 7 ).equals( ver1 ); + } - @Test - public void testHistoryOfNotExistingEntity() { - assert getAuditReader().find(BasicTestEntity1.class, id1+id2+id3, 1) == null; - assert getAuditReader().find(BasicTestEntity1.class, id1+id2+id3, 7) == null; - } + @Test + public void testHistoryOfNotExistingEntity() { + assert getAuditReader().find( BasicTestEntity1.class, id1 + id2 + id3, 1 ) == null; + assert getAuditReader().find( BasicTestEntity1.class, id1 + id2 + id3, 7 ) == null; + } - @Test - public void testRevisionsOfNotExistingEntity() { - assert getAuditReader().getRevisions(BasicTestEntity1.class, id1+id2+id3).size() == 0; - } + @Test + public void testRevisionsOfNotExistingEntity() { + assert getAuditReader().getRevisions( BasicTestEntity1.class, id1 + id2 + id3 ).size() == 0; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/TransactionRollbackBehaviour.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/TransactionRollbackBehaviour.java index 98c0e5cb27..1ea650515f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/TransactionRollbackBehaviour.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/TransactionRollbackBehaviour.java @@ -1,13 +1,14 @@ package org.hibernate.envers.test.integration.basic; -import java.util.List; import javax.persistence.EntityManager; +import java.util.List; + +import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; +import org.hibernate.envers.test.entities.IntTestEntity; import org.junit.Assert; import org.junit.Test; -import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; -import org.hibernate.envers.test.entities.IntTestEntity; import org.hibernate.testing.TestForIssue; /** @@ -35,12 +36,19 @@ public class TransactionRollbackBehaviour extends BaseEnversJPAFunctionalTestCas List revisionsForSavedClass = getAuditReader().getRevisions( IntTestEntity.class, ite2Id ); Assert.assertEquals( "There should be one revision for inserted entity.", 1, revisionsForSavedClass.size() ); - List revisionsForRolledbackClass = getAuditReader().getRevisions( IntTestEntity.class, rollbackedIteId ); - Assert.assertEquals( "There should be no revision for rolled back transaction.", 0, revisionsForRolledbackClass.size() ); + List revisionsForRolledbackClass = getAuditReader().getRevisions( + IntTestEntity.class, + rollbackedIteId + ); + Assert.assertEquals( + "There should be no revision for rolled back transaction.", + 0, + revisionsForRolledbackClass.size() + ); } @Test - @TestForIssue( jiraKey = "HHH-8189" ) + @TestForIssue(jiraKey = "HHH-8189") public void testFlushedAuditRecordsRollback() { // Given EntityManager em = getEntityManager(); @@ -63,12 +71,19 @@ public class TransactionRollbackBehaviour extends BaseEnversJPAFunctionalTestCas List revisionsForSavedClass = getAuditReader().getRevisions( IntTestEntity.class, ite2Id ); Assert.assertEquals( "There should be one revision for inserted entity.", 1, revisionsForSavedClass.size() ); - List revisionsForRolledbackClass = getAuditReader().getRevisions( IntTestEntity.class, rollbackedIteId ); - Assert.assertEquals( "There should be no revision for rolled back transaction.", 0, revisionsForRolledbackClass.size() ); + List revisionsForRolledbackClass = getAuditReader().getRevisions( + IntTestEntity.class, + rollbackedIteId + ); + Assert.assertEquals( + "There should be no revision for rolled back transaction.", + 0, + revisionsForRolledbackClass.size() + ); } @Override protected Class[] getAnnotatedClasses() { - return new Class[] { IntTestEntity.class }; + return new Class[] {IntTestEntity.class}; } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/UnversionedPropertiesChange.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/UnversionedPropertiesChange.java index 1779f41546..62fcd5f30d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/UnversionedPropertiesChange.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/UnversionedPropertiesChange.java @@ -23,64 +23,64 @@ */ package org.hibernate.envers.test.integration.basic; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class UnversionedPropertiesChange extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BasicTestEntity2.class }; - } + return new Class[] {BasicTestEntity2.class}; + } - private Integer addNewEntity(String str1, String str2) { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - BasicTestEntity2 bte2 = new BasicTestEntity2(str1, str2); - em.persist(bte2); - em.getTransaction().commit(); + private Integer addNewEntity(String str1, String str2) { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + BasicTestEntity2 bte2 = new BasicTestEntity2( str1, str2 ); + em.persist( bte2 ); + em.getTransaction().commit(); - return bte2.getId(); - } + return bte2.getId(); + } - private void modifyEntity(Integer id, String str1, String str2) { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - BasicTestEntity2 bte2 = em.find(BasicTestEntity2.class, id); - bte2.setStr1(str1); - bte2.setStr2(str2); - em.getTransaction().commit(); - } + private void modifyEntity(Integer id, String str1, String str2) { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + BasicTestEntity2 bte2 = em.find( BasicTestEntity2.class, id ); + bte2.setStr1( str1 ); + bte2.setStr2( str2 ); + em.getTransaction().commit(); + } - @Test - @Priority(10) - public void initData() { - id1 = addNewEntity("x", "a"); // rev 1 - modifyEntity(id1, "x", "a"); // no rev - modifyEntity(id1, "y", "b"); // rev 2 - modifyEntity(id1, "y", "c"); // no rev - } + @Test + @Priority(10) + public void initData() { + id1 = addNewEntity( "x", "a" ); // rev 1 + modifyEntity( id1, "x", "a" ); // no rev + modifyEntity( id1, "y", "b" ); // rev 2 + modifyEntity( id1, "y", "c" ); // no rev + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(BasicTestEntity2.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( BasicTestEntity2.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - BasicTestEntity2 ver1 = new BasicTestEntity2(id1, "x", null); - BasicTestEntity2 ver2 = new BasicTestEntity2(id1, "y", null); + @Test + public void testHistoryOfId1() { + BasicTestEntity2 ver1 = new BasicTestEntity2( id1, "x", null ); + BasicTestEntity2 ver2 = new BasicTestEntity2( id1, "y", null ); - assert getAuditReader().find(BasicTestEntity2.class, id1, 1).equals(ver1); - assert getAuditReader().find(BasicTestEntity2.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( BasicTestEntity2.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( BasicTestEntity2.class, id1, 2 ).equals( ver2 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/UnversionedProperty.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/UnversionedProperty.java index 7ecb37da29..f2ca6e0a2c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/UnversionedProperty.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/basic/UnversionedProperty.java @@ -23,57 +23,57 @@ */ package org.hibernate.envers.test.integration.basic; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.UnversionedEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ -public class UnversionedProperty extends BaseEnversJPAFunctionalTestCase { - private Integer id1; +public class UnversionedProperty extends BaseEnversJPAFunctionalTestCase { + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { UnversionedEntity.class }; - } + return new Class[] {UnversionedEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Rev 1 - em.getTransaction().begin(); - UnversionedEntity ue1 = new UnversionedEntity("a1", "b1"); - em.persist(ue1); - id1 = ue1.getId(); - em.getTransaction().commit(); + // Rev 1 + em.getTransaction().begin(); + UnversionedEntity ue1 = new UnversionedEntity( "a1", "b1" ); + em.persist( ue1 ); + id1 = ue1.getId(); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); - ue1 = em.find(UnversionedEntity.class, id1); - ue1.setData1("a2"); - ue1.setData2("b2"); - em.getTransaction().commit(); - } + // Rev 2 + em.getTransaction().begin(); + ue1 = em.find( UnversionedEntity.class, id1 ); + ue1.setData1( "a2" ); + ue1.setData2( "b2" ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(UnversionedEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( UnversionedEntity.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - UnversionedEntity rev1 = new UnversionedEntity(id1, "a1", null); - UnversionedEntity rev2 = new UnversionedEntity(id1, "a2", null); + @Test + public void testHistoryOfId1() { + UnversionedEntity rev1 = new UnversionedEntity( id1, "a1", null ); + UnversionedEntity rev2 = new UnversionedEntity( id1, "a2", null ); - assert getAuditReader().find(UnversionedEntity.class, id1, 1).equals(rev1); - assert getAuditReader().find(UnversionedEntity.class, id1, 2).equals(rev2); - } + assert getAuditReader().find( UnversionedEntity.class, id1, 1 ).equals( rev1 ); + assert getAuditReader().find( UnversionedEntity.class, id1, 2 ).equals( rev2 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/cache/OneToManyCache.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/cache/OneToManyCache.java index f680242389..86487781d9 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/cache/OneToManyCache.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/cache/OneToManyCache.java @@ -25,120 +25,120 @@ package org.hibernate.envers.test.integration.cache; import javax.persistence.EntityManager; -import org.junit.Test; - import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.onetomany.SetRefEdEntity; import org.hibernate.envers.test.entities.onetomany.SetRefIngEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ @SuppressWarnings({"ObjectEquality"}) public class OneToManyCache extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SetRefEdEntity.class, SetRefIngEntity.class }; - } + return new Class[] {SetRefEdEntity.class, SetRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - SetRefEdEntity ed1 = new SetRefEdEntity(1, "data_ed_1"); - SetRefEdEntity ed2 = new SetRefEdEntity(2, "data_ed_2"); + SetRefEdEntity ed1 = new SetRefEdEntity( 1, "data_ed_1" ); + SetRefEdEntity ed2 = new SetRefEdEntity( 2, "data_ed_2" ); - SetRefIngEntity ing1 = new SetRefIngEntity(1, "data_ing_1"); - SetRefIngEntity ing2 = new SetRefIngEntity(2, "data_ing_2"); + SetRefIngEntity ing1 = new SetRefIngEntity( 1, "data_ing_1" ); + SetRefIngEntity ing2 = new SetRefIngEntity( 2, "data_ing_2" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); + em.persist( ed1 ); + em.persist( ed2 ); - ing1.setReference(ed1); - ing2.setReference(ed1); + ing1.setReference( ed1 ); + ing2.setReference( ed1 ); - em.persist(ing1); - em.persist(ing2); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ing1 = em.find(SetRefIngEntity.class, ing1.getId()); - ing2 = em.find(SetRefIngEntity.class, ing2.getId()); - ed2 = em.find(SetRefEdEntity.class, ed2.getId()); + ing1 = em.find( SetRefIngEntity.class, ing1.getId() ); + ing2 = em.find( SetRefIngEntity.class, ing2.getId() ); + ed2 = em.find( SetRefEdEntity.class, ed2.getId() ); - ing1.setReference(ed2); - ing2.setReference(ed2); + ing1.setReference( ed2 ); + ing2.setReference( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); - } + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); + } - @Test - public void testCacheReferenceAccessAfterFind() { - SetRefEdEntity ed1_rev1 = getAuditReader().find(SetRefEdEntity.class, ed1_id, 1); + @Test + public void testCacheReferenceAccessAfterFind() { + SetRefEdEntity ed1_rev1 = getAuditReader().find( SetRefEdEntity.class, ed1_id, 1 ); - SetRefIngEntity ing1_rev1 = getAuditReader().find(SetRefIngEntity.class, ing1_id, 1); - SetRefIngEntity ing2_rev1 = getAuditReader().find(SetRefIngEntity.class, ing2_id, 1); + SetRefIngEntity ing1_rev1 = getAuditReader().find( SetRefIngEntity.class, ing1_id, 1 ); + SetRefIngEntity ing2_rev1 = getAuditReader().find( SetRefIngEntity.class, ing2_id, 1 ); - // It should be exactly the same object - assert ing1_rev1.getReference() == ed1_rev1; - assert ing2_rev1.getReference() == ed1_rev1; - } + // It should be exactly the same object + assert ing1_rev1.getReference() == ed1_rev1; + assert ing2_rev1.getReference() == ed1_rev1; + } - @Test - public void testCacheReferenceAccessAfterCollectionAccessRev1() { - SetRefEdEntity ed1_rev1 = getAuditReader().find(SetRefEdEntity.class, ed1_id, 1); + @Test + public void testCacheReferenceAccessAfterCollectionAccessRev1() { + SetRefEdEntity ed1_rev1 = getAuditReader().find( SetRefEdEntity.class, ed1_id, 1 ); - // It should be exactly the same object - assert ed1_rev1.getReffering().size() == 2; - for (SetRefIngEntity setRefIngEntity : ed1_rev1.getReffering()) { - assert setRefIngEntity.getReference() == ed1_rev1; - } - } + // It should be exactly the same object + assert ed1_rev1.getReffering().size() == 2; + for ( SetRefIngEntity setRefIngEntity : ed1_rev1.getReffering() ) { + assert setRefIngEntity.getReference() == ed1_rev1; + } + } - @Test - public void testCacheReferenceAccessAfterCollectionAccessRev2() { - SetRefEdEntity ed2_rev2 = getAuditReader().find(SetRefEdEntity.class, ed2_id, 2); + @Test + public void testCacheReferenceAccessAfterCollectionAccessRev2() { + SetRefEdEntity ed2_rev2 = getAuditReader().find( SetRefEdEntity.class, ed2_id, 2 ); - assert ed2_rev2.getReffering().size() == 2; - for (SetRefIngEntity setRefIngEntity : ed2_rev2.getReffering()) { - assert setRefIngEntity.getReference() == ed2_rev2; - } - } + assert ed2_rev2.getReffering().size() == 2; + for ( SetRefIngEntity setRefIngEntity : ed2_rev2.getReffering() ) { + assert setRefIngEntity.getReference() == ed2_rev2; + } + } - @Test - public void testCacheFindAfterCollectionAccessRev1() { - SetRefEdEntity ed1_rev1 = getAuditReader().find(SetRefEdEntity.class, ed1_id, 1); + @Test + public void testCacheFindAfterCollectionAccessRev1() { + SetRefEdEntity ed1_rev1 = getAuditReader().find( SetRefEdEntity.class, ed1_id, 1 ); - // Reading the collection - assert ed1_rev1.getReffering().size() == 2; + // Reading the collection + assert ed1_rev1.getReffering().size() == 2; - SetRefIngEntity ing1_rev1 = getAuditReader().find(SetRefIngEntity.class, ing1_id, 1); - SetRefIngEntity ing2_rev1 = getAuditReader().find(SetRefIngEntity.class, ing2_id, 1); + SetRefIngEntity ing1_rev1 = getAuditReader().find( SetRefIngEntity.class, ing1_id, 1 ); + SetRefIngEntity ing2_rev1 = getAuditReader().find( SetRefIngEntity.class, ing2_id, 1 ); - for (SetRefIngEntity setRefIngEntity : ed1_rev1.getReffering()) { - assert setRefIngEntity == ing1_rev1 || setRefIngEntity == ing2_rev1; - } - } + for ( SetRefIngEntity setRefIngEntity : ed1_rev1.getReffering() ) { + assert setRefIngEntity == ing1_rev1 || setRefIngEntity == ing2_rev1; + } + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/cache/OneToOneCache.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/cache/OneToOneCache.java index e97f410d25..2e494f14c2 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/cache/OneToOneCache.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/cache/OneToOneCache.java @@ -25,78 +25,78 @@ package org.hibernate.envers.test.integration.cache; import javax.persistence.EntityManager; -import org.junit.Test; - import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.onetoone.bidirectional.BiRefEdEntity; import org.hibernate.envers.test.integration.onetoone.bidirectional.BiRefIngEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ @SuppressWarnings({"ObjectEquality"}) public class OneToOneCache extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; + private Integer ing1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BiRefEdEntity.class, BiRefIngEntity.class }; - } + return new Class[] {BiRefEdEntity.class, BiRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - BiRefEdEntity ed1 = new BiRefEdEntity(1, "data_ed_1"); - BiRefEdEntity ed2 = new BiRefEdEntity(2, "data_ed_2"); + @Test + @Priority(10) + public void initData() { + BiRefEdEntity ed1 = new BiRefEdEntity( 1, "data_ed_1" ); + BiRefEdEntity ed2 = new BiRefEdEntity( 2, "data_ed_2" ); - BiRefIngEntity ing1 = new BiRefIngEntity(3, "data_ing_1"); + BiRefIngEntity ing1 = new BiRefIngEntity( 3, "data_ing_1" ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - ing1.setReference(ed1); + ing1.setReference( ed1 ); - em.persist(ed1); - em.persist(ed2); + em.persist( ed1 ); + em.persist( ed2 ); - em.persist(ing1); + em.persist( ing1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ing1 = em.find(BiRefIngEntity.class, ing1.getId()); - ed2 = em.find(BiRefEdEntity.class, ed2.getId()); + ing1 = em.find( BiRefIngEntity.class, ing1.getId() ); + ed2 = em.find( BiRefEdEntity.class, ed2.getId() ); - ing1.setReference(ed2); + ing1.setReference( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); - ing1_id = ing1.getId(); - } + ing1_id = ing1.getId(); + } - @Test - public void testCacheReferenceAccessAfterFindRev1() { - BiRefEdEntity ed1_rev1 = getAuditReader().find(BiRefEdEntity.class, ed1_id, 1); - BiRefIngEntity ing1_rev1 = getAuditReader().find(BiRefIngEntity.class, ing1_id, 1); + @Test + public void testCacheReferenceAccessAfterFindRev1() { + BiRefEdEntity ed1_rev1 = getAuditReader().find( BiRefEdEntity.class, ed1_id, 1 ); + BiRefIngEntity ing1_rev1 = getAuditReader().find( BiRefIngEntity.class, ing1_id, 1 ); - assert ing1_rev1.getReference() == ed1_rev1; - } + assert ing1_rev1.getReference() == ed1_rev1; + } - @Test - public void testCacheReferenceAccessAfterFindRev2() { - BiRefEdEntity ed2_rev2 = getAuditReader().find(BiRefEdEntity.class, ed2_id, 2); - BiRefIngEntity ing1_rev2 = getAuditReader().find(BiRefIngEntity.class, ing1_id, 2); + @Test + public void testCacheReferenceAccessAfterFindRev2() { + BiRefEdEntity ed2_rev2 = getAuditReader().find( BiRefEdEntity.class, ed2_id, 2 ); + BiRefIngEntity ing1_rev2 = getAuditReader().find( BiRefIngEntity.class, ing1_id, 2 ); - assert ing1_rev2.getReference() == ed2_rev2; - } + assert ing1_rev2.getReference() == ed2_rev2; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/cache/QueryCache.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/cache/QueryCache.java index 2bf21a3726..1e32fbe6e1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/cache/QueryCache.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/cache/QueryCache.java @@ -23,66 +23,66 @@ */ package org.hibernate.envers.test.integration.cache; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.IntTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ @SuppressWarnings({"ObjectEquality"}) public class QueryCache extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { IntTestEntity.class }; - } + return new Class[] {IntTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - IntTestEntity ite = new IntTestEntity(10); - em.persist(ite); - id1 = ite.getId(); - em.getTransaction().commit(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + IntTestEntity ite = new IntTestEntity( 10 ); + em.persist( ite ); + id1 = ite.getId(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); - ite = em.find(IntTestEntity.class, id1); - ite.setNumber(20); - em.getTransaction().commit(); - } + // Revision 2 + em.getTransaction().begin(); + ite = em.find( IntTestEntity.class, id1 ); + ite.setNumber( 20 ); + em.getTransaction().commit(); + } - @Test - public void testCacheFindAfterRevisionsOfEntityQuery() { - List entsFromQuery = getAuditReader().createQuery() - .forRevisionsOfEntity(IntTestEntity.class, true, false) - .getResultList(); + @Test + public void testCacheFindAfterRevisionsOfEntityQuery() { + List entsFromQuery = getAuditReader().createQuery() + .forRevisionsOfEntity( IntTestEntity.class, true, false ) + .getResultList(); - IntTestEntity entFromFindRev1 = getAuditReader().find(IntTestEntity.class, id1, 1); - IntTestEntity entFromFindRev2 = getAuditReader().find(IntTestEntity.class, id1, 2); + IntTestEntity entFromFindRev1 = getAuditReader().find( IntTestEntity.class, id1, 1 ); + IntTestEntity entFromFindRev2 = getAuditReader().find( IntTestEntity.class, id1, 2 ); - assert entFromFindRev1 == entsFromQuery.get(0); - assert entFromFindRev2 == entsFromQuery.get(1); - } + assert entFromFindRev1 == entsFromQuery.get( 0 ); + assert entFromFindRev2 == entsFromQuery.get( 1 ); + } - @Test - public void testCacheFindAfterEntitiesAtRevisionQuery() { - IntTestEntity entFromQuery = (IntTestEntity) getAuditReader().createQuery() - .forEntitiesAtRevision(IntTestEntity.class, 1) - .getSingleResult(); + @Test + public void testCacheFindAfterEntitiesAtRevisionQuery() { + IntTestEntity entFromQuery = (IntTestEntity) getAuditReader().createQuery() + .forEntitiesAtRevision( IntTestEntity.class, 1 ) + .getSingleResult(); - IntTestEntity entFromFind = getAuditReader().find(IntTestEntity.class, id1, 1); + IntTestEntity entFromFind = getAuditReader().find( IntTestEntity.class, id1, 1 ); - assert entFromFind == entFromQuery; - } + assert entFromFind == entFromQuery; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/DetachedMultipleCollectionChangeTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/DetachedMultipleCollectionChangeTest.java index 1c0e524d28..198d4bcd4d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/DetachedMultipleCollectionChangeTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/DetachedMultipleCollectionChangeTest.java @@ -1,15 +1,13 @@ package org.hibernate.envers.test.integration.collection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.transaction.Status; import javax.transaction.TransactionManager; - -import org.junit.Test; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; import org.hibernate.dialect.Oracle8iDialect; import org.hibernate.envers.RevisionType; @@ -19,6 +17,9 @@ import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.collection.MultipleCollectionEntity; import org.hibernate.envers.test.entities.collection.MultipleCollectionRefEntity1; import org.hibernate.envers.test.entities.collection.MultipleCollectionRefEntity2; + +import org.junit.Test; + import org.hibernate.testing.SkipForDialect; import org.hibernate.testing.TestForIssue; import org.hibernate.testing.jta.TestingJtaBootstrap; @@ -35,7 +36,7 @@ import static org.junit.Assert.assertNotNull; */ @TestForIssue(jiraKey = "HHH-6349") @SkipForDialect(value = Oracle8iDialect.class, - comment = "Oracle does not support identity key generation") + comment = "Oracle does not support identity key generation") public class DetachedMultipleCollectionChangeTest extends BaseEnversJPAFunctionalTestCase { private TransactionManager tm = null; @@ -276,10 +277,11 @@ public class DetachedMultipleCollectionChangeTest extends BaseEnversJPAFunctiona ); } - private List getAuditJoinTableRows(String middleEntityName, String joinColumnIdName, - String joinColumnIdProp, String inverseJoinColumnIdName, - String inverseJoinColumnIdProp, String revProp, String revIdProp, - String revTypeProp) throws Exception { + private List getAuditJoinTableRows( + String middleEntityName, String joinColumnIdName, + String joinColumnIdProp, String inverseJoinColumnIdName, + String inverseJoinColumnIdProp, String revProp, String revIdProp, + String revTypeProp) throws Exception { StringBuilder qryBuilder = new StringBuilder( "select " ); qryBuilder.append( "aud " ); qryBuilder.append( ", " ).append( joinColumnIdProp ).append( " as joinColumnId" ); @@ -324,9 +326,10 @@ public class DetachedMultipleCollectionChangeTest extends BaseEnversJPAFunctiona private final String inverseJoinColumnName; private final Long inverseJoinColumnId; - private AuditJoinTableInfo(String name, SequenceIdRevisionEntity rev, - RevisionType revType, String joinColumnName, Long joinColumnId, - String inverseJoinColumnName, Long inverseJoinColumnId) { + private AuditJoinTableInfo( + String name, SequenceIdRevisionEntity rev, + RevisionType revType, String joinColumnName, Long joinColumnId, + String inverseJoinColumnName, Long inverseJoinColumnId) { this.name = name; this.revId = rev.getId(); this.revType = revType; @@ -349,13 +352,15 @@ public class DetachedMultipleCollectionChangeTest extends BaseEnversJPAFunctiona if ( this == o ) { return true; } - if ( !( o instanceof AuditJoinTableInfo ) ) { + if ( !(o instanceof AuditJoinTableInfo) ) { return false; } AuditJoinTableInfo that = (AuditJoinTableInfo) o; - if ( inverseJoinColumnId != null ? !inverseJoinColumnId.equals( that.inverseJoinColumnId ) : that.inverseJoinColumnId != null ) { + if ( inverseJoinColumnId != null ? + !inverseJoinColumnId.equals( that.inverseJoinColumnId ) : + that.inverseJoinColumnId != null ) { return false; } if ( joinColumnId != null ? !joinColumnId.equals( that.joinColumnId ) : that.joinColumnId != null ) { @@ -377,10 +382,10 @@ public class DetachedMultipleCollectionChangeTest extends BaseEnversJPAFunctiona @Override public int hashCode() { int result = name != null ? name.hashCode() : 0; - result = 31 * result + ( revId != null ? revId.hashCode() : 0 ); - result = 31 * result + ( revType != null ? revType.hashCode() : 0 ); - result = 31 * result + ( joinColumnId != null ? joinColumnId.hashCode() : 0 ); - result = 31 * result + ( inverseJoinColumnId != null ? inverseJoinColumnId.hashCode() : 0 ); + result = 31 * result + (revId != null ? revId.hashCode() : 0); + result = 31 * result + (revType != null ? revType.hashCode() : 0); + result = 31 * result + (joinColumnId != null ? joinColumnId.hashCode() : 0); + result = 31 * result + (inverseJoinColumnId != null ? inverseJoinColumnId.hashCode() : 0); return result; } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/EnumSet.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/EnumSet.java index 92239ec28c..370a9e10af 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/EnumSet.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/EnumSet.java @@ -23,12 +23,9 @@ */ package org.hibernate.envers.test.integration.collection; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -36,87 +33,95 @@ import org.hibernate.envers.test.entities.collection.EnumSetEntity; import org.hibernate.envers.test.entities.collection.EnumSetEntity.E1; import org.hibernate.envers.test.entities.collection.EnumSetEntity.E2; import org.hibernate.envers.test.tools.TestTools; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** * @author Adam Warski (adam at warski dot org) */ -public class EnumSet extends BaseEnversJPAFunctionalTestCase { - private Integer sse1_id; +public class EnumSet extends BaseEnversJPAFunctionalTestCase { + private Integer sse1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { EnumSetEntity.class }; - } - - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - - EnumSetEntity sse1 = new EnumSetEntity(); - - // Revision 1 (sse1: initialy 1 element) - em.getTransaction().begin(); - - sse1.getEnums1().add(E1.X); - sse1.getEnums2().add(E2.A); - - em.persist(sse1); - - em.getTransaction().commit(); - - // Revision 2 (sse1: adding 1 element/removing a non-existing element) - em.getTransaction().begin(); - - sse1 = em.find(EnumSetEntity.class, sse1.getId()); - - sse1.getEnums1().add(E1.Y); - sse1.getEnums2().remove(E2.B); - - em.getTransaction().commit(); - - // Revision 3 (sse1: removing 1 element/adding an exisiting element) - em.getTransaction().begin(); - - sse1 = em.find(EnumSetEntity.class, sse1.getId()); - - sse1.getEnums1().remove(E1.X); - sse1.getEnums2().add(E2.A); - - em.getTransaction().commit(); - - // - - sse1_id = sse1.getId(); - } - - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(EnumSetEntity.class, sse1_id)); - } - - @Test - public void testHistoryOfSse1() { - EnumSetEntity rev1 = getAuditReader().find(EnumSetEntity.class, sse1_id, 1); - EnumSetEntity rev2 = getAuditReader().find(EnumSetEntity.class, sse1_id, 2); - EnumSetEntity rev3 = getAuditReader().find(EnumSetEntity.class, sse1_id, 3); - - assert rev1.getEnums1().equals(TestTools.makeSet(E1.X)); - assert rev2.getEnums1().equals(TestTools.makeSet(E1.X, E1.Y)); - assert rev3.getEnums1().equals(TestTools.makeSet(E1.Y)); - - assert rev1.getEnums2().equals(TestTools.makeSet(E2.A)); - assert rev2.getEnums2().equals(TestTools.makeSet(E2.A)); - assert rev3.getEnums2().equals(TestTools.makeSet(E2.A)); - } + return new Class[] {EnumSetEntity.class}; + } @Test - @TestForIssue( jiraKey = "HHH-7780" ) + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + + EnumSetEntity sse1 = new EnumSetEntity(); + + // Revision 1 (sse1: initialy 1 element) + em.getTransaction().begin(); + + sse1.getEnums1().add( E1.X ); + sse1.getEnums2().add( E2.A ); + + em.persist( sse1 ); + + em.getTransaction().commit(); + + // Revision 2 (sse1: adding 1 element/removing a non-existing element) + em.getTransaction().begin(); + + sse1 = em.find( EnumSetEntity.class, sse1.getId() ); + + sse1.getEnums1().add( E1.Y ); + sse1.getEnums2().remove( E2.B ); + + em.getTransaction().commit(); + + // Revision 3 (sse1: removing 1 element/adding an exisiting element) + em.getTransaction().begin(); + + sse1 = em.find( EnumSetEntity.class, sse1.getId() ); + + sse1.getEnums1().remove( E1.X ); + sse1.getEnums2().add( E2.A ); + + em.getTransaction().commit(); + + // + + sse1_id = sse1.getId(); + } + + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( EnumSetEntity.class, sse1_id ) ); + } + + @Test + public void testHistoryOfSse1() { + EnumSetEntity rev1 = getAuditReader().find( EnumSetEntity.class, sse1_id, 1 ); + EnumSetEntity rev2 = getAuditReader().find( EnumSetEntity.class, sse1_id, 2 ); + EnumSetEntity rev3 = getAuditReader().find( EnumSetEntity.class, sse1_id, 3 ); + + assert rev1.getEnums1().equals( TestTools.makeSet( E1.X ) ); + assert rev2.getEnums1().equals( TestTools.makeSet( E1.X, E1.Y ) ); + assert rev3.getEnums1().equals( TestTools.makeSet( E1.Y ) ); + + assert rev1.getEnums2().equals( TestTools.makeSet( E2.A ) ); + assert rev2.getEnums2().equals( TestTools.makeSet( E2.A ) ); + assert rev3.getEnums2().equals( TestTools.makeSet( E2.A ) ); + } + + @Test + @TestForIssue(jiraKey = "HHH-7780") public void testEnumRepresentation() { EntityManager entityManager = getEntityManager(); - List enums1 = entityManager.createNativeQuery( "SELECT enums1 FROM EnumSetEntity_enums1_AUD ORDER BY rev ASC" ).getResultList(); - List enums2 = entityManager.createNativeQuery( "SELECT enums2 FROM EnumSetEntity_enums2_AUD ORDER BY rev ASC" ).getResultList(); + List enums1 = entityManager.createNativeQuery( + "SELECT enums1 FROM EnumSetEntity_enums1_AUD ORDER BY rev ASC" + ).getResultList(); + List enums2 = entityManager.createNativeQuery( + "SELECT enums2 FROM EnumSetEntity_enums2_AUD ORDER BY rev ASC" + ).getResultList(); entityManager.close(); Assert.assertEquals( Arrays.asList( "X", "Y", "X" ), enums1 ); diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/StringList.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/StringList.java index 0829fb420e..94e05f726a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/StringList.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/StringList.java @@ -23,104 +23,104 @@ */ package org.hibernate.envers.test.integration.collection; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Collections; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.collection.StringListEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class StringList extends BaseEnversJPAFunctionalTestCase { - private Integer sle1_id; - private Integer sle2_id; + private Integer sle1_id; + private Integer sle2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StringListEntity.class }; - } + return new Class[] {StringListEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - StringListEntity sle1 = new StringListEntity(); - StringListEntity sle2 = new StringListEntity(); + StringListEntity sle1 = new StringListEntity(); + StringListEntity sle2 = new StringListEntity(); - // Revision 1 (sle1: initialy empty, sle2: initialy 2 elements) - em.getTransaction().begin(); + // Revision 1 (sle1: initialy empty, sle2: initialy 2 elements) + em.getTransaction().begin(); - sle2.getStrings().add("sle2_string1"); - sle2.getStrings().add("sle2_string2"); + sle2.getStrings().add( "sle2_string1" ); + sle2.getStrings().add( "sle2_string2" ); - em.persist(sle1); - em.persist(sle2); + em.persist( sle1 ); + em.persist( sle2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (sle1: adding 2 elements, sle2: adding an existing element) - em.getTransaction().begin(); + // Revision 2 (sle1: adding 2 elements, sle2: adding an existing element) + em.getTransaction().begin(); - sle1 = em.find(StringListEntity.class, sle1.getId()); - sle2 = em.find(StringListEntity.class, sle2.getId()); + sle1 = em.find( StringListEntity.class, sle1.getId() ); + sle2 = em.find( StringListEntity.class, sle2.getId() ); - sle1.getStrings().add("sle1_string1"); - sle1.getStrings().add("sle1_string2"); + sle1.getStrings().add( "sle1_string1" ); + sle1.getStrings().add( "sle1_string2" ); - sle2.getStrings().add("sle2_string1"); + sle2.getStrings().add( "sle2_string1" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 (sle1: replacing an element at index 0, sle2: removing an element at index 0) - em.getTransaction().begin(); + // Revision 3 (sle1: replacing an element at index 0, sle2: removing an element at index 0) + em.getTransaction().begin(); - sle1 = em.find(StringListEntity.class, sle1.getId()); - sle2 = em.find(StringListEntity.class, sle2.getId()); + sle1 = em.find( StringListEntity.class, sle1.getId() ); + sle2 = em.find( StringListEntity.class, sle2.getId() ); - sle1.getStrings().set(0, "sle1_string3"); + sle1.getStrings().set( 0, "sle1_string3" ); - sle2.getStrings().remove(0); + sle2.getStrings().remove( 0 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - sle1_id = sle1.getId(); - sle2_id = sle2.getId(); - } + sle1_id = sle1.getId(); + sle2_id = sle2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(StringListEntity.class, sle1_id)); - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(StringListEntity.class, sle2_id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( StringListEntity.class, sle1_id ) ); + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( StringListEntity.class, sle2_id ) ); + } - @Test - public void testHistoryOfSle1() { - StringListEntity rev1 = getAuditReader().find(StringListEntity.class, sle1_id, 1); - StringListEntity rev2 = getAuditReader().find(StringListEntity.class, sle1_id, 2); - StringListEntity rev3 = getAuditReader().find(StringListEntity.class, sle1_id, 3); + @Test + public void testHistoryOfSle1() { + StringListEntity rev1 = getAuditReader().find( StringListEntity.class, sle1_id, 1 ); + StringListEntity rev2 = getAuditReader().find( StringListEntity.class, sle1_id, 2 ); + StringListEntity rev3 = getAuditReader().find( StringListEntity.class, sle1_id, 3 ); - assert rev1.getStrings().equals(Collections.EMPTY_LIST); - assert rev2.getStrings().equals(TestTools.makeList("sle1_string1", "sle1_string2")); - assert rev3.getStrings().equals(TestTools.makeList("sle1_string3", "sle1_string2")); - } + assert rev1.getStrings().equals( Collections.EMPTY_LIST ); + assert rev2.getStrings().equals( TestTools.makeList( "sle1_string1", "sle1_string2" ) ); + assert rev3.getStrings().equals( TestTools.makeList( "sle1_string3", "sle1_string2" ) ); + } - @Test - public void testHistoryOfSse2() { - StringListEntity rev1 = getAuditReader().find(StringListEntity.class, sle2_id, 1); - StringListEntity rev2 = getAuditReader().find(StringListEntity.class, sle2_id, 2); - StringListEntity rev3 = getAuditReader().find(StringListEntity.class, sle2_id, 3); + @Test + public void testHistoryOfSse2() { + StringListEntity rev1 = getAuditReader().find( StringListEntity.class, sle2_id, 1 ); + StringListEntity rev2 = getAuditReader().find( StringListEntity.class, sle2_id, 2 ); + StringListEntity rev3 = getAuditReader().find( StringListEntity.class, sle2_id, 3 ); - assert rev1.getStrings().equals(TestTools.makeList("sle2_string1", "sle2_string2")); - assert rev2.getStrings().equals(TestTools.makeList("sle2_string1", "sle2_string2", "sle2_string1")); - assert rev3.getStrings().equals(TestTools.makeList("sle2_string2", "sle2_string1")); - } + assert rev1.getStrings().equals( TestTools.makeList( "sle2_string1", "sle2_string2" ) ); + assert rev2.getStrings().equals( TestTools.makeList( "sle2_string1", "sle2_string2", "sle2_string1" ) ); + assert rev3.getStrings().equals( TestTools.makeList( "sle2_string2", "sle2_string1" ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/StringMap.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/StringMap.java index 1888108051..be1f21b619 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/StringMap.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/StringMap.java @@ -23,115 +23,115 @@ */ package org.hibernate.envers.test.integration.collection; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Collections; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.collection.StringMapEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class StringMap extends BaseEnversJPAFunctionalTestCase { - private Integer sme1_id; - private Integer sme2_id; + private Integer sme1_id; + private Integer sme2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StringMapEntity.class }; - } + return new Class[] {StringMapEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - StringMapEntity sme1 = new StringMapEntity(); - StringMapEntity sme2 = new StringMapEntity(); + StringMapEntity sme1 = new StringMapEntity(); + StringMapEntity sme2 = new StringMapEntity(); - // Revision 1 (sme1: initialy empty, sme2: initialy 1 mapping) - em.getTransaction().begin(); + // Revision 1 (sme1: initialy empty, sme2: initialy 1 mapping) + em.getTransaction().begin(); - sme2.getStrings().put("1", "a"); + sme2.getStrings().put( "1", "a" ); - em.persist(sme1); - em.persist(sme2); + em.persist( sme1 ); + em.persist( sme2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (sme1: adding 2 mappings, sme2: no changes) - em.getTransaction().begin(); + // Revision 2 (sme1: adding 2 mappings, sme2: no changes) + em.getTransaction().begin(); - sme1 = em.find(StringMapEntity.class, sme1.getId()); - sme2 = em.find(StringMapEntity.class, sme2.getId()); + sme1 = em.find( StringMapEntity.class, sme1.getId() ); + sme2 = em.find( StringMapEntity.class, sme2.getId() ); - sme1.getStrings().put("1", "a"); - sme1.getStrings().put("2", "b"); + sme1.getStrings().put( "1", "a" ); + sme1.getStrings().put( "2", "b" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 (sme1: removing an existing mapping, sme2: replacing a value) - em.getTransaction().begin(); + // Revision 3 (sme1: removing an existing mapping, sme2: replacing a value) + em.getTransaction().begin(); - sme1 = em.find(StringMapEntity.class, sme1.getId()); - sme2 = em.find(StringMapEntity.class, sme2.getId()); + sme1 = em.find( StringMapEntity.class, sme1.getId() ); + sme2 = em.find( StringMapEntity.class, sme2.getId() ); - sme1.getStrings().remove("1"); - sme2.getStrings().put("1", "b"); - - em.getTransaction().commit(); + sme1.getStrings().remove( "1" ); + sme2.getStrings().put( "1", "b" ); - // No revision (sme1: removing a non-existing mapping, sme2: replacing with the same value) - em.getTransaction().begin(); + em.getTransaction().commit(); - sme1 = em.find(StringMapEntity.class, sme1.getId()); - sme2 = em.find(StringMapEntity.class, sme2.getId()); + // No revision (sme1: removing a non-existing mapping, sme2: replacing with the same value) + em.getTransaction().begin(); - sme1.getStrings().remove("3"); - sme2.getStrings().put("1", "b"); + sme1 = em.find( StringMapEntity.class, sme1.getId() ); + sme2 = em.find( StringMapEntity.class, sme2.getId() ); - em.getTransaction().commit(); + sme1.getStrings().remove( "3" ); + sme2.getStrings().put( "1", "b" ); - // + em.getTransaction().commit(); - sme1_id = sme1.getId(); - sme2_id = sme2.getId(); - } + // - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(StringMapEntity.class, sme1_id)); - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(StringMapEntity.class, sme2_id)); - } + sme1_id = sme1.getId(); + sme2_id = sme2.getId(); + } - @Test - public void testHistoryOfSse1() { - StringMapEntity rev1 = getAuditReader().find(StringMapEntity.class, sme1_id, 1); - StringMapEntity rev2 = getAuditReader().find(StringMapEntity.class, sme1_id, 2); - StringMapEntity rev3 = getAuditReader().find(StringMapEntity.class, sme1_id, 3); - StringMapEntity rev4 = getAuditReader().find(StringMapEntity.class, sme1_id, 4); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( StringMapEntity.class, sme1_id ) ); + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( StringMapEntity.class, sme2_id ) ); + } - assert rev1.getStrings().equals(Collections.EMPTY_MAP); - assert rev2.getStrings().equals(TestTools.makeMap("1", "a", "2", "b")); - assert rev3.getStrings().equals(TestTools.makeMap("2", "b")); - assert rev4.getStrings().equals(TestTools.makeMap("2", "b")); - } + @Test + public void testHistoryOfSse1() { + StringMapEntity rev1 = getAuditReader().find( StringMapEntity.class, sme1_id, 1 ); + StringMapEntity rev2 = getAuditReader().find( StringMapEntity.class, sme1_id, 2 ); + StringMapEntity rev3 = getAuditReader().find( StringMapEntity.class, sme1_id, 3 ); + StringMapEntity rev4 = getAuditReader().find( StringMapEntity.class, sme1_id, 4 ); - @Test - public void testHistoryOfSse2() { - StringMapEntity rev1 = getAuditReader().find(StringMapEntity.class, sme2_id, 1); - StringMapEntity rev2 = getAuditReader().find(StringMapEntity.class, sme2_id, 2); - StringMapEntity rev3 = getAuditReader().find(StringMapEntity.class, sme2_id, 3); - StringMapEntity rev4 = getAuditReader().find(StringMapEntity.class, sme2_id, 4); + assert rev1.getStrings().equals( Collections.EMPTY_MAP ); + assert rev2.getStrings().equals( TestTools.makeMap( "1", "a", "2", "b" ) ); + assert rev3.getStrings().equals( TestTools.makeMap( "2", "b" ) ); + assert rev4.getStrings().equals( TestTools.makeMap( "2", "b" ) ); + } - assert rev1.getStrings().equals(TestTools.makeMap("1", "a")); - assert rev2.getStrings().equals(TestTools.makeMap("1", "a")); - assert rev3.getStrings().equals(TestTools.makeMap("1", "b")); - assert rev4.getStrings().equals(TestTools.makeMap("1", "b")); - } + @Test + public void testHistoryOfSse2() { + StringMapEntity rev1 = getAuditReader().find( StringMapEntity.class, sme2_id, 1 ); + StringMapEntity rev2 = getAuditReader().find( StringMapEntity.class, sme2_id, 2 ); + StringMapEntity rev3 = getAuditReader().find( StringMapEntity.class, sme2_id, 3 ); + StringMapEntity rev4 = getAuditReader().find( StringMapEntity.class, sme2_id, 4 ); + + assert rev1.getStrings().equals( TestTools.makeMap( "1", "a" ) ); + assert rev2.getStrings().equals( TestTools.makeMap( "1", "a" ) ); + assert rev3.getStrings().equals( TestTools.makeMap( "1", "b" ) ); + assert rev4.getStrings().equals( TestTools.makeMap( "1", "b" ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/StringSet.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/StringSet.java index 3aed0aa607..898e4679e4 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/StringSet.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/StringSet.java @@ -23,103 +23,103 @@ */ package org.hibernate.envers.test.integration.collection; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Collections; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.collection.StringSetEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class StringSet extends BaseEnversJPAFunctionalTestCase { - private Integer sse1_id; - private Integer sse2_id; + private Integer sse1_id; + private Integer sse2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StringSetEntity.class }; - } + return new Class[] {StringSetEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - StringSetEntity sse1 = new StringSetEntity(); - StringSetEntity sse2 = new StringSetEntity(); + StringSetEntity sse1 = new StringSetEntity(); + StringSetEntity sse2 = new StringSetEntity(); - // Revision 1 (sse1: initialy empty, sse2: initialy 2 elements) - em.getTransaction().begin(); + // Revision 1 (sse1: initialy empty, sse2: initialy 2 elements) + em.getTransaction().begin(); - sse2.getStrings().add("sse2_string1"); - sse2.getStrings().add("sse2_string2"); + sse2.getStrings().add( "sse2_string1" ); + sse2.getStrings().add( "sse2_string2" ); - em.persist(sse1); - em.persist(sse2); + em.persist( sse1 ); + em.persist( sse2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (sse1: adding 2 elements, sse2: adding an existing element) - em.getTransaction().begin(); + // Revision 2 (sse1: adding 2 elements, sse2: adding an existing element) + em.getTransaction().begin(); - sse1 = em.find(StringSetEntity.class, sse1.getId()); - sse2 = em.find(StringSetEntity.class, sse2.getId()); + sse1 = em.find( StringSetEntity.class, sse1.getId() ); + sse2 = em.find( StringSetEntity.class, sse2.getId() ); - sse1.getStrings().add("sse1_string1"); - sse1.getStrings().add("sse1_string2"); + sse1.getStrings().add( "sse1_string1" ); + sse1.getStrings().add( "sse1_string2" ); - sse2.getStrings().add("sse2_string1"); + sse2.getStrings().add( "sse2_string1" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 (sse1: removing a non-existing element, sse2: removing one element) - em.getTransaction().begin(); + // Revision 3 (sse1: removing a non-existing element, sse2: removing one element) + em.getTransaction().begin(); - sse1 = em.find(StringSetEntity.class, sse1.getId()); - sse2 = em.find(StringSetEntity.class, sse2.getId()); + sse1 = em.find( StringSetEntity.class, sse1.getId() ); + sse2 = em.find( StringSetEntity.class, sse2.getId() ); - sse1.getStrings().remove("sse1_string3"); - sse2.getStrings().remove("sse2_string1"); + sse1.getStrings().remove( "sse1_string3" ); + sse2.getStrings().remove( "sse2_string1" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - sse1_id = sse1.getId(); - sse2_id = sse2.getId(); - } + sse1_id = sse1.getId(); + sse2_id = sse2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(StringSetEntity.class, sse1_id)); - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(StringSetEntity.class, sse2_id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( StringSetEntity.class, sse1_id ) ); + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( StringSetEntity.class, sse2_id ) ); + } - @Test - public void testHistoryOfSse1() { - StringSetEntity rev1 = getAuditReader().find(StringSetEntity.class, sse1_id, 1); - StringSetEntity rev2 = getAuditReader().find(StringSetEntity.class, sse1_id, 2); - StringSetEntity rev3 = getAuditReader().find(StringSetEntity.class, sse1_id, 3); + @Test + public void testHistoryOfSse1() { + StringSetEntity rev1 = getAuditReader().find( StringSetEntity.class, sse1_id, 1 ); + StringSetEntity rev2 = getAuditReader().find( StringSetEntity.class, sse1_id, 2 ); + StringSetEntity rev3 = getAuditReader().find( StringSetEntity.class, sse1_id, 3 ); - assert rev1.getStrings().equals(Collections.EMPTY_SET); - assert rev2.getStrings().equals(TestTools.makeSet("sse1_string1", "sse1_string2")); - assert rev3.getStrings().equals(TestTools.makeSet("sse1_string1", "sse1_string2")); - } + assert rev1.getStrings().equals( Collections.EMPTY_SET ); + assert rev2.getStrings().equals( TestTools.makeSet( "sse1_string1", "sse1_string2" ) ); + assert rev3.getStrings().equals( TestTools.makeSet( "sse1_string1", "sse1_string2" ) ); + } - @Test - public void testHistoryOfSse2() { - StringSetEntity rev1 = getAuditReader().find(StringSetEntity.class, sse2_id, 1); - StringSetEntity rev2 = getAuditReader().find(StringSetEntity.class, sse2_id, 2); - StringSetEntity rev3 = getAuditReader().find(StringSetEntity.class, sse2_id, 3); + @Test + public void testHistoryOfSse2() { + StringSetEntity rev1 = getAuditReader().find( StringSetEntity.class, sse2_id, 1 ); + StringSetEntity rev2 = getAuditReader().find( StringSetEntity.class, sse2_id, 2 ); + StringSetEntity rev3 = getAuditReader().find( StringSetEntity.class, sse2_id, 3 ); - assert rev1.getStrings().equals(TestTools.makeSet("sse2_string1", "sse2_string2")); - assert rev2.getStrings().equals(TestTools.makeSet("sse2_string1", "sse2_string2")); - assert rev3.getStrings().equals(TestTools.makeSet("sse2_string2")); - } + assert rev1.getStrings().equals( TestTools.makeSet( "sse2_string1", "sse2_string2" ) ); + assert rev2.getStrings().equals( TestTools.makeSet( "sse2_string1", "sse2_string2" ) ); + assert rev3.getStrings().equals( TestTools.makeSet( "sse2_string2" ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/BasicEmbeddableCollection.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/BasicEmbeddableCollection.java index 6531197709..b917aeede9 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/BasicEmbeddableCollection.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/BasicEmbeddableCollection.java @@ -23,26 +23,27 @@ */ package org.hibernate.envers.test.integration.collection.embeddable; -import java.util.Arrays; import javax.persistence.EntityManager; - -import junit.framework.Assert; -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; + +import org.junit.Test; +import junit.framework.Assert; + import org.hibernate.testing.TestForIssue; /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ -@TestForIssue( jiraKey = "HHH-6613" ) +@TestForIssue(jiraKey = "HHH-6613") public class BasicEmbeddableCollection extends BaseEnversJPAFunctionalTestCase { private int id = -1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { DarkCharacter.class }; + return new Class[] {DarkCharacter.class}; } @Test diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/DarkCharacter.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/DarkCharacter.java index 79db3ff12d..b7ef2afb68 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/DarkCharacter.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/DarkCharacter.java @@ -23,12 +23,12 @@ */ package org.hibernate.envers.test.integration.collection.embeddable; -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.Id; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; import org.hibernate.envers.Audited; @@ -56,13 +56,21 @@ public class DarkCharacter implements Serializable { @Override public boolean equals(Object o) { - if ( this == o ) return true; - if ( ! ( o instanceof DarkCharacter ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof DarkCharacter) ) { + return false; + } DarkCharacter character = (DarkCharacter) o; - if ( id != character.id ) return false; - if ( kills != character.kills ) return false; + if ( id != character.id ) { + return false; + } + if ( kills != character.kills ) { + return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/EmbeddableList1.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/EmbeddableList1.java index 49d207fae8..2de3e23a73 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/EmbeddableList1.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/EmbeddableList1.java @@ -23,17 +23,18 @@ */ package org.hibernate.envers.test.integration.collection.embeddable; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Collections; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.collection.EmbeddableListEntity1; import org.hibernate.envers.test.entities.components.Component3; import org.hibernate.envers.test.entities.components.Component4; + +import org.junit.Test; + import org.hibernate.testing.TestForIssue; import static org.junit.Assert.assertEquals; @@ -41,7 +42,7 @@ import static org.junit.Assert.assertEquals; /** * @author Kristoffer Lundberg (kristoffer at cambio dot se) */ -@TestForIssue( jiraKey = "HHH-6613" ) +@TestForIssue(jiraKey = "HHH-6613") public class EmbeddableList1 extends BaseEnversJPAFunctionalTestCase { private Integer ele1_id = null; @@ -52,7 +53,7 @@ public class EmbeddableList1 extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { EmbeddableListEntity1.class }; + return new Class[] {EmbeddableListEntity1.class}; } @Test @@ -99,7 +100,12 @@ public class EmbeddableList1 extends BaseEnversJPAFunctionalTestCase { @Test public void testRevisionsCounts() { - assertEquals( Arrays.asList( 1, 2, 3, 4 ), getAuditReader().getRevisions( EmbeddableListEntity1.class, ele1_id ) ); + assertEquals( + Arrays.asList( 1, 2, 3, 4 ), getAuditReader().getRevisions( + EmbeddableListEntity1.class, + ele1_id + ) + ); } @Test diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/EmbeddableList2.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/EmbeddableList2.java index 7cfc454008..cd10bcfd0a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/EmbeddableList2.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/EmbeddableList2.java @@ -23,16 +23,17 @@ */ package org.hibernate.envers.test.integration.collection.embeddable; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestNoProxyEntity; import org.hibernate.envers.test.entities.collection.EmbeddableListEntity2; import org.hibernate.envers.test.entities.components.relations.ManyToOneEagerComponent; + +import org.junit.Test; + import org.hibernate.testing.TestForIssue; import static org.junit.Assert.assertEquals; @@ -45,7 +46,7 @@ import static org.junit.Assert.assertTrue; * * @author thiagolrc */ -@TestForIssue( jiraKey = "HHH-6613" ) +@TestForIssue(jiraKey = "HHH-6613") public class EmbeddableList2 extends BaseEnversJPAFunctionalTestCase { private Integer ele_id1 = null; @@ -61,7 +62,7 @@ public class EmbeddableList2 extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { EmbeddableListEntity2.class, StrTestNoProxyEntity.class }; + return new Class[] {EmbeddableListEntity2.class, StrTestNoProxyEntity.class}; } @Test @@ -97,7 +98,9 @@ public class EmbeddableList2 extends BaseEnversJPAFunctionalTestCase { ele1 = em.find( EmbeddableListEntity2.class, ele1.getId() ); em.persist( entity3 ); ele1.getComponentList().get( ele1.getComponentList().indexOf( manyToOneComponent2 ) ).setEntity( entity3 ); - ele1.getComponentList().get( ele1.getComponentList().indexOf( manyToOneComponent2 ) ).setData( "dataComponent3" ); + ele1.getComponentList() + .get( ele1.getComponentList().indexOf( manyToOneComponent2 ) ) + .setData( "dataComponent3" ); em.getTransaction().commit(); // Revision 5 (ele1: adding a new many-to-one component) @@ -111,7 +114,10 @@ public class EmbeddableList2 extends BaseEnversJPAFunctionalTestCase { // Revision 6 (ele1: changing the component's entity properties) em.getTransaction().begin(); ele1 = em.find( EmbeddableListEntity2.class, ele1.getId() ); - ele1.getComponentList().get( ele1.getComponentList().indexOf( manyToOneComponent4 ) ).getEntity().setStr( "sat4" ); + ele1.getComponentList() + .get( ele1.getComponentList().indexOf( manyToOneComponent4 ) ) + .getEntity() + .setStr( "sat4" ); em.getTransaction().commit(); // Revision 7 (ele1: removing component) diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/EmbeddableMap.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/EmbeddableMap.java index 869c908cc2..2fa9be12dd 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/EmbeddableMap.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/EmbeddableMap.java @@ -23,12 +23,9 @@ */ package org.hibernate.envers.test.integration.collection.embeddable; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Collections; -import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -36,12 +33,16 @@ import org.hibernate.envers.test.entities.collection.EmbeddableMapEntity; import org.hibernate.envers.test.entities.components.Component3; import org.hibernate.envers.test.entities.components.Component4; import org.hibernate.envers.test.tools.TestTools; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** * @author Kristoffer Lundberg (kristoffer at cambio dot se) */ -@TestForIssue( jiraKey = "HHH-6613" ) +@TestForIssue(jiraKey = "HHH-6613") public class EmbeddableMap extends BaseEnversJPAFunctionalTestCase { private Integer eme1_id = null; private Integer eme2_id = null; @@ -53,7 +54,7 @@ public class EmbeddableMap extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { EmbeddableMapEntity.class }; + return new Class[] {EmbeddableMapEntity.class}; } @Test @@ -103,8 +104,18 @@ public class EmbeddableMap extends BaseEnversJPAFunctionalTestCase { @Test public void testRevisionsCounts() { - Assert.assertEquals( Arrays.asList( 1, 2, 3 ), getAuditReader().getRevisions( EmbeddableMapEntity.class, eme1_id ) ); - Assert.assertEquals( Arrays.asList( 1, 3 ), getAuditReader().getRevisions( EmbeddableMapEntity.class, eme2_id ) ); + Assert.assertEquals( + Arrays.asList( 1, 2, 3 ), getAuditReader().getRevisions( + EmbeddableMapEntity.class, + eme1_id + ) + ); + Assert.assertEquals( + Arrays.asList( 1, 3 ), getAuditReader().getRevisions( + EmbeddableMapEntity.class, + eme2_id + ) + ); } @Test diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/EmbeddableSet.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/EmbeddableSet.java index 0243319e9b..3bdb433431 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/EmbeddableSet.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/EmbeddableSet.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.collection.embeddable; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -34,6 +32,9 @@ import org.hibernate.envers.test.entities.collection.EmbeddableSetEntity; import org.hibernate.envers.test.entities.components.Component3; import org.hibernate.envers.test.entities.components.Component4; import org.hibernate.envers.test.tools.TestTools; + +import org.junit.Test; + import org.hibernate.testing.TestForIssue; import static org.junit.Assert.assertEquals; @@ -41,7 +42,7 @@ import static org.junit.Assert.assertEquals; /** * @author Kristoffer Lundberg (kristoffer at cambio dot se) */ -@TestForIssue( jiraKey = "HHH-6613" ) +@TestForIssue(jiraKey = "HHH-6613") public class EmbeddableSet extends BaseEnversJPAFunctionalTestCase { private Integer ese1_id = null; @@ -54,7 +55,7 @@ public class EmbeddableSet extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { EmbeddableSetEntity.class }; + return new Class[] {EmbeddableSetEntity.class}; } @Test @@ -131,7 +132,12 @@ public class EmbeddableSet extends BaseEnversJPAFunctionalTestCase { @Test public void testRevisionsCounts() { - assertEquals( Arrays.asList( 1, 2, 3, 4, 5, 6, 7 ), getAuditReader().getRevisions( EmbeddableSetEntity.class, ese1_id ) ); + assertEquals( + Arrays.asList( 1, 2, 3, 4, 5, 6, 7 ), getAuditReader().getRevisions( + EmbeddableSetEntity.class, + ese1_id + ) + ); } @Test diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/Name.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/Name.java index c9581814ff..d46d2a4a2d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/Name.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/embeddable/Name.java @@ -23,8 +23,8 @@ */ package org.hibernate.envers.test.integration.collection.embeddable; -import java.io.Serializable; import javax.persistence.Embeddable; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -47,12 +47,20 @@ public class Name implements Serializable { @Override public boolean equals(Object o) { - if ( this == o ) return true; - if ( !( o instanceof Name ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof Name) ) { + return false; + } Name name = (Name) o; - if ( firstName != null ? !firstName.equals( name.firstName ) : name.firstName != null ) return false; - if ( lastName != null ? !lastName.equals( name.lastName ) : name.lastName != null ) return false; + if ( firstName != null ? !firstName.equals( name.firstName ) : name.firstName != null ) { + return false; + } + if ( lastName != null ? !lastName.equals( name.lastName ) : name.lastName != null ) { + return false; + } return true; } @@ -60,7 +68,7 @@ public class Name implements Serializable { @Override public int hashCode() { int result = firstName != null ? firstName.hashCode() : 0; - result = 31 * result + ( lastName != null ? lastName.hashCode() : 0 ); + result = 31 * result + (lastName != null ? lastName.hashCode() : 0); return result; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/mapkey/ComponentMapKey.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/mapkey/ComponentMapKey.java index 827dad8194..c2ba8a0711 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/mapkey/ComponentMapKey.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/mapkey/ComponentMapKey.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.collection.mapkey; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -35,78 +33,90 @@ import org.hibernate.envers.test.entities.components.Component2; import org.hibernate.envers.test.entities.components.ComponentTestEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class ComponentMapKey extends BaseEnversJPAFunctionalTestCase { - private Integer cmke_id; + private Integer cmke_id; - private Integer cte1_id; - private Integer cte2_id; + private Integer cte1_id; + private Integer cte2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ComponentMapKeyEntity.class, ComponentTestEntity.class }; - } + return new Class[] {ComponentMapKeyEntity.class, ComponentTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - ComponentMapKeyEntity imke = new ComponentMapKeyEntity(); + ComponentMapKeyEntity imke = new ComponentMapKeyEntity(); - // Revision 1 (intialy 1 mapping) - em.getTransaction().begin(); + // Revision 1 (intialy 1 mapping) + em.getTransaction().begin(); - ComponentTestEntity cte1 = new ComponentTestEntity(new Component1("x1", "y2"), new Component2("a1", "b2")); - ComponentTestEntity cte2 = new ComponentTestEntity(new Component1("x1", "y2"), new Component2("a1", "b2")); + ComponentTestEntity cte1 = new ComponentTestEntity( + new Component1( "x1", "y2" ), new Component2( + "a1", + "b2" + ) + ); + ComponentTestEntity cte2 = new ComponentTestEntity( + new Component1( "x1", "y2" ), new Component2( + "a1", + "b2" + ) + ); - em.persist(cte1); - em.persist(cte2); + em.persist( cte1 ); + em.persist( cte2 ); - imke.getIdmap().put(cte1.getComp1(), cte1); + imke.getIdmap().put( cte1.getComp1(), cte1 ); - em.persist(imke); + em.persist( imke ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (sse1: adding 1 mapping) - em.getTransaction().begin(); + // Revision 2 (sse1: adding 1 mapping) + em.getTransaction().begin(); - cte2 = em.find(ComponentTestEntity.class, cte2.getId()); - imke = em.find(ComponentMapKeyEntity.class, imke.getId()); + cte2 = em.find( ComponentTestEntity.class, cte2.getId() ); + imke = em.find( ComponentMapKeyEntity.class, imke.getId() ); - imke.getIdmap().put(cte2.getComp1(), cte2); + imke.getIdmap().put( cte2.getComp1(), cte2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - cmke_id = imke.getId(); + cmke_id = imke.getId(); - cte1_id = cte1.getId(); - cte2_id = cte2.getId(); - } + cte1_id = cte1.getId(); + cte2_id = cte2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(ComponentMapKeyEntity.class, cmke_id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( ComponentMapKeyEntity.class, cmke_id ) ); + } - @Test - public void testHistoryOfImke() { - ComponentTestEntity cte1 = getEntityManager().find(ComponentTestEntity.class, cte1_id); - ComponentTestEntity cte2 = getEntityManager().find(ComponentTestEntity.class, cte2_id); + @Test + public void testHistoryOfImke() { + ComponentTestEntity cte1 = getEntityManager().find( ComponentTestEntity.class, cte1_id ); + ComponentTestEntity cte2 = getEntityManager().find( ComponentTestEntity.class, cte2_id ); - // These fields are unversioned. - cte1.setComp2(null); - cte2.setComp2(null); + // These fields are unversioned. + cte1.setComp2( null ); + cte2.setComp2( null ); - ComponentMapKeyEntity rev1 = getAuditReader().find(ComponentMapKeyEntity.class, cmke_id, 1); - ComponentMapKeyEntity rev2 = getAuditReader().find(ComponentMapKeyEntity.class, cmke_id, 2); + ComponentMapKeyEntity rev1 = getAuditReader().find( ComponentMapKeyEntity.class, cmke_id, 1 ); + ComponentMapKeyEntity rev2 = getAuditReader().find( ComponentMapKeyEntity.class, cmke_id, 2 ); - assert rev1.getIdmap().equals(TestTools.makeMap(cte1.getComp1(), cte1)); - assert rev2.getIdmap().equals(TestTools.makeMap(cte1.getComp1(), cte1, cte2.getComp1(), cte2)); - } + assert rev1.getIdmap().equals( TestTools.makeMap( cte1.getComp1(), cte1 ) ); + assert rev2.getIdmap().equals( TestTools.makeMap( cte1.getComp1(), cte1, cte2.getComp1(), cte2 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/mapkey/ComponentMapKeyEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/mapkey/ComponentMapKeyEntity.java index cd90b800ab..466024a354 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/mapkey/ComponentMapKeyEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/mapkey/ComponentMapKeyEntity.java @@ -22,14 +22,15 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.collection.mapkey; -import java.util.HashMap; -import java.util.Map; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.MapKey; import javax.persistence.Table; +import java.util.HashMap; +import java.util.Map; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.components.Component1; @@ -41,51 +42,57 @@ import org.hibernate.envers.test.entities.components.ComponentTestEntity; @Entity @Table(name = "CompMapKey") public class ComponentMapKeyEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - @ManyToMany - @MapKey(name = "comp1") - private Map idmap; + @Audited + @ManyToMany + @MapKey(name = "comp1") + private Map idmap; - public ComponentMapKeyEntity() { - idmap = new HashMap(); - } + public ComponentMapKeyEntity() { + idmap = new HashMap(); + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Map getIdmap() { - return idmap; - } + public Map getIdmap() { + return idmap; + } - public void setIdmap(Map idmap) { - this.idmap = idmap; - } + public void setIdmap(Map idmap) { + this.idmap = idmap; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ComponentMapKeyEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ComponentMapKeyEntity) ) { + return false; + } - ComponentMapKeyEntity that = (ComponentMapKeyEntity) o; + ComponentMapKeyEntity that = (ComponentMapKeyEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - return (id != null ? id.hashCode() : 0); - } + public int hashCode() { + return (id != null ? id.hashCode() : 0); + } - public String toString() { - return "CMKE(id = " + id + ", idmap = " + idmap + ")"; - } + public String toString() { + return "CMKE(id = " + id + ", idmap = " + idmap + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/mapkey/IdMapKey.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/mapkey/IdMapKey.java index 4a55f6678d..de6288fb4c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/mapkey/IdMapKey.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/mapkey/IdMapKey.java @@ -23,84 +23,84 @@ */ package org.hibernate.envers.test.integration.collection.mapkey; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class IdMapKey extends BaseEnversJPAFunctionalTestCase { - private Integer imke_id; + private Integer imke_id; - private Integer ste1_id; - private Integer ste2_id; + private Integer ste1_id; + private Integer ste2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { IdMapKeyEntity.class, StrTestEntity.class }; - } + return new Class[] {IdMapKeyEntity.class, StrTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - IdMapKeyEntity imke = new IdMapKeyEntity(); + IdMapKeyEntity imke = new IdMapKeyEntity(); - // Revision 1 (intialy 1 mapping) - em.getTransaction().begin(); + // Revision 1 (intialy 1 mapping) + em.getTransaction().begin(); - StrTestEntity ste1 = new StrTestEntity("x"); - StrTestEntity ste2 = new StrTestEntity("y"); + StrTestEntity ste1 = new StrTestEntity( "x" ); + StrTestEntity ste2 = new StrTestEntity( "y" ); - em.persist(ste1); - em.persist(ste2); + em.persist( ste1 ); + em.persist( ste2 ); - imke.getIdmap().put(ste1.getId(), ste1); + imke.getIdmap().put( ste1.getId(), ste1 ); - em.persist(imke); + em.persist( imke ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (sse1: adding 1 mapping) - em.getTransaction().begin(); + // Revision 2 (sse1: adding 1 mapping) + em.getTransaction().begin(); - ste2 = em.find(StrTestEntity.class, ste2.getId()); - imke = em.find(IdMapKeyEntity.class, imke.getId()); + ste2 = em.find( StrTestEntity.class, ste2.getId() ); + imke = em.find( IdMapKeyEntity.class, imke.getId() ); - imke.getIdmap().put(ste2.getId(), ste2); + imke.getIdmap().put( ste2.getId(), ste2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - imke_id = imke.getId(); + imke_id = imke.getId(); - ste1_id = ste1.getId(); - ste2_id = ste2.getId(); - } + ste1_id = ste1.getId(); + ste2_id = ste2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(IdMapKeyEntity.class, imke_id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( IdMapKeyEntity.class, imke_id ) ); + } - @Test - public void testHistoryOfImke() { - StrTestEntity ste1 = getEntityManager().find(StrTestEntity.class, ste1_id); - StrTestEntity ste2 = getEntityManager().find(StrTestEntity.class, ste2_id); + @Test + public void testHistoryOfImke() { + StrTestEntity ste1 = getEntityManager().find( StrTestEntity.class, ste1_id ); + StrTestEntity ste2 = getEntityManager().find( StrTestEntity.class, ste2_id ); - IdMapKeyEntity rev1 = getAuditReader().find(IdMapKeyEntity.class, imke_id, 1); - IdMapKeyEntity rev2 = getAuditReader().find(IdMapKeyEntity.class, imke_id, 2); + IdMapKeyEntity rev1 = getAuditReader().find( IdMapKeyEntity.class, imke_id, 1 ); + IdMapKeyEntity rev2 = getAuditReader().find( IdMapKeyEntity.class, imke_id, 2 ); - assert rev1.getIdmap().equals(TestTools.makeMap(ste1.getId(), ste1)); - assert rev2.getIdmap().equals(TestTools.makeMap(ste1.getId(), ste1, ste2.getId(), ste2)); - } + assert rev1.getIdmap().equals( TestTools.makeMap( ste1.getId(), ste1 ) ); + assert rev2.getIdmap().equals( TestTools.makeMap( ste1.getId(), ste1, ste2.getId(), ste2 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/mapkey/IdMapKeyEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/mapkey/IdMapKeyEntity.java index 50d144bf74..16fc4bd845 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/mapkey/IdMapKeyEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/mapkey/IdMapKeyEntity.java @@ -22,14 +22,15 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.collection.mapkey; -import java.util.HashMap; -import java.util.Map; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.MapKey; import javax.persistence.Table; +import java.util.HashMap; +import java.util.Map; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.StrTestEntity; @@ -40,51 +41,57 @@ import org.hibernate.envers.test.entities.StrTestEntity; @Entity @Table(name = "IdMapKey") public class IdMapKeyEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - @ManyToMany - @MapKey - private Map idmap; + @Audited + @ManyToMany + @MapKey + private Map idmap; - public IdMapKeyEntity() { - idmap = new HashMap(); - } + public IdMapKeyEntity() { + idmap = new HashMap(); + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Map getIdmap() { - return idmap; - } + public Map getIdmap() { + return idmap; + } - public void setIdmap(Map idmap) { - this.idmap = idmap; - } + public void setIdmap(Map idmap) { + this.idmap = idmap; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof IdMapKeyEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof IdMapKeyEntity) ) { + return false; + } - IdMapKeyEntity that = (IdMapKeyEntity) o; + IdMapKeyEntity that = (IdMapKeyEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - return (id != null ? id.hashCode() : 0); - } + public int hashCode() { + return (id != null ? id.hashCode() : 0); + } - public String toString() { - return "IMKE(id = " + id + ", idmap = " + idmap + ")"; - } + public String toString() { + return "IMKE(id = " + id + ", idmap = " + idmap + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/AbstractCollectionChangeTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/AbstractCollectionChangeTest.java index 194bf6cbe7..294f109f21 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/AbstractCollectionChangeTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/AbstractCollectionChangeTest.java @@ -2,63 +2,63 @@ package org.hibernate.envers.test.integration.collection.norevision; import java.util.List; -import org.junit.Test; - import org.hibernate.Session; import org.hibernate.cfg.Configuration; import org.hibernate.envers.configuration.EnversSettings; import org.hibernate.envers.test.BaseEnversFunctionalTestCase; import org.hibernate.envers.test.Priority; -public abstract class AbstractCollectionChangeTest extends BaseEnversFunctionalTestCase { - protected Integer personId; +import org.junit.Test; - @Override - protected void configure(Configuration configuration) { - configuration.setProperty(EnversSettings.REVISION_ON_COLLECTION_CHANGE, getCollectionChangeValue()); - } +public abstract class AbstractCollectionChangeTest extends BaseEnversFunctionalTestCase { + protected Integer personId; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{Person.class, Name.class}; - } + @Override + protected void configure(Configuration configuration) { + configuration.setProperty( EnversSettings.REVISION_ON_COLLECTION_CHANGE, getCollectionChangeValue() ); + } - protected abstract String getCollectionChangeValue(); + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {Person.class, Name.class}; + } - protected abstract List getExpectedPersonRevisions(); + protected abstract String getCollectionChangeValue(); - @Test - @Priority(10) - public void initData() { - Session session = openSession(); + protected abstract List getExpectedPersonRevisions(); - // Rev 1 - session.getTransaction().begin(); - Person p = new Person(); - Name n = new Name(); - n.setName("name1"); - p.getNames().add(n); - session.saveOrUpdate(p); - session.getTransaction().commit(); + @Test + @Priority(10) + public void initData() { + Session session = openSession(); - // Rev 2 - session.getTransaction().begin(); - n.setName("Changed name"); - session.saveOrUpdate(p); - session.getTransaction().commit(); + // Rev 1 + session.getTransaction().begin(); + Person p = new Person(); + Name n = new Name(); + n.setName( "name1" ); + p.getNames().add( n ); + session.saveOrUpdate( p ); + session.getTransaction().commit(); - // Rev 3 - session.getTransaction().begin(); - Name n2 = new Name(); - n2.setName("name2"); - p.getNames().add(n2); - session.getTransaction().commit(); + // Rev 2 + session.getTransaction().begin(); + n.setName( "Changed name" ); + session.saveOrUpdate( p ); + session.getTransaction().commit(); - personId = p.getId(); - } + // Rev 3 + session.getTransaction().begin(); + Name n2 = new Name(); + n2.setName( "name2" ); + p.getNames().add( n2 ); + session.getTransaction().commit(); - @Test - public void testPersonRevisionCount() { - assert getAuditReader().getRevisions(Person.class, personId).equals(getExpectedPersonRevisions()); - } + personId = p.getId(); + } + + @Test + public void testPersonRevisionCount() { + assert getAuditReader().getRevisions( Person.class, personId ).equals( getExpectedPersonRevisions() ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/CollectionChangeNoRevisionTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/CollectionChangeNoRevisionTest.java index 58f9f982d9..73d0a4d56a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/CollectionChangeNoRevisionTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/CollectionChangeNoRevisionTest.java @@ -1,14 +1,15 @@ package org.hibernate.envers.test.integration.collection.norevision; + import java.util.Arrays; import java.util.List; public class CollectionChangeNoRevisionTest extends AbstractCollectionChangeTest { - protected String getCollectionChangeValue() { - return "false"; - } + protected String getCollectionChangeValue() { + return "false"; + } - @Override - protected List getExpectedPersonRevisions() { - return Arrays.asList(1); - } + @Override + protected List getExpectedPersonRevisions() { + return Arrays.asList( 1 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/CollectionChangeRevisionTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/CollectionChangeRevisionTest.java index 66026527fc..57a98a7b1a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/CollectionChangeRevisionTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/CollectionChangeRevisionTest.java @@ -1,15 +1,16 @@ package org.hibernate.envers.test.integration.collection.norevision; + import java.util.Arrays; import java.util.List; -public class CollectionChangeRevisionTest extends AbstractCollectionChangeTest { - @Override - protected String getCollectionChangeValue() { - return "true"; - } +public class CollectionChangeRevisionTest extends AbstractCollectionChangeTest { + @Override + protected String getCollectionChangeValue() { + return "true"; + } - @Override - protected List getExpectedPersonRevisions() { - return Arrays.asList(1, 3); - } + @Override + protected List getExpectedPersonRevisions() { + return Arrays.asList( 1, 3 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/Name.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/Name.java index 9d6fa4ef4d..9427dc0ed3 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/Name.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/Name.java @@ -1,46 +1,47 @@ package org.hibernate.envers.test.integration.collection.norevision; -import java.io.Serializable; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; +import java.io.Serializable; import org.hibernate.envers.Audited; @Audited @Entity public class Name implements Serializable { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String name; - @ManyToOne - @JoinColumn(name = "person_id", insertable = false, updatable = false) - private Person person; + private String name; + @ManyToOne + @JoinColumn(name = "person_id", insertable = false, updatable = false) + private Person person; - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Person getPerson() { - return person; - } + public Person getPerson() { + return person; + } - public void setPerson(Person person) { - this.person = person; - } + public void setPerson(Person person) { + this.person = person; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/Person.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/Person.java index 3c01c1f518..bc1c5acd1b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/Person.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/collection/norevision/Person.java @@ -1,13 +1,14 @@ package org.hibernate.envers.test.integration.collection.norevision; -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; + import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; import org.hibernate.envers.AuditMappedBy; import org.hibernate.envers.Audited; @@ -15,30 +16,31 @@ import org.hibernate.envers.Audited; @Audited @Entity public class Person implements Serializable { - @Id @GeneratedValue - private Integer id; - @AuditMappedBy(mappedBy = "person") - @OneToMany(cascade = CascadeType.ALL) - @JoinColumn(name = "person_id") - private Set names; + @Id + @GeneratedValue + private Integer id; + @AuditMappedBy(mappedBy = "person") + @OneToMany(cascade = CascadeType.ALL) + @JoinColumn(name = "person_id") + private Set names; - public Person() { - names = new HashSet(); - } + public Person() { + names = new HashSet(); + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Set getNames() { - return names; - } + public Set getNames() { + return names; + } - public void setNames(Set names) { - this.names = names; - } + public void setNames(Set names) { + this.names = names; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/Components.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/Components.java index 56ed7f0d76..3e54435d33 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/Components.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/Components.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.components; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -34,143 +32,155 @@ import org.hibernate.envers.test.entities.components.Component1; import org.hibernate.envers.test.entities.components.Component2; import org.hibernate.envers.test.entities.components.ComponentTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ -public class Components extends BaseEnversJPAFunctionalTestCase { - private Integer id1; - private Integer id2; - private Integer id3; - private Integer id4; +public class Components extends BaseEnversJPAFunctionalTestCase { + private Integer id1; + private Integer id2; + private Integer id3; + private Integer id4; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ComponentTestEntity.class }; - } + return new Class[] {ComponentTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - ComponentTestEntity cte1 = new ComponentTestEntity(new Component1("a", "b"), new Component2("x", "y")); - ComponentTestEntity cte2 = new ComponentTestEntity(new Component1("a2", "b2"), new Component2("x2", "y2")); - ComponentTestEntity cte3 = new ComponentTestEntity(new Component1("a3", "b3"), new Component2("x3", "y3")); - ComponentTestEntity cte4 = new ComponentTestEntity(null, null); + ComponentTestEntity cte1 = new ComponentTestEntity( new Component1( "a", "b" ), new Component2( "x", "y" ) ); + ComponentTestEntity cte2 = new ComponentTestEntity( + new Component1( "a2", "b2" ), new Component2( + "x2", + "y2" + ) + ); + ComponentTestEntity cte3 = new ComponentTestEntity( + new Component1( "a3", "b3" ), new Component2( + "x3", + "y3" + ) + ); + ComponentTestEntity cte4 = new ComponentTestEntity( null, null ); - em.persist(cte1); - em.persist(cte2); - em.persist(cte3); - em.persist(cte4); + em.persist( cte1 ); + em.persist( cte2 ); + em.persist( cte3 ); + em.persist( cte4 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 2 + em = getEntityManager(); + em.getTransaction().begin(); - cte1 = em.find(ComponentTestEntity.class, cte1.getId()); - cte2 = em.find(ComponentTestEntity.class, cte2.getId()); - cte3 = em.find(ComponentTestEntity.class, cte3.getId()); - cte4 = em.find(ComponentTestEntity.class, cte4.getId()); + cte1 = em.find( ComponentTestEntity.class, cte1.getId() ); + cte2 = em.find( ComponentTestEntity.class, cte2.getId() ); + cte3 = em.find( ComponentTestEntity.class, cte3.getId() ); + cte4 = em.find( ComponentTestEntity.class, cte4.getId() ); - cte1.setComp1(new Component1("a'", "b'")); - cte2.getComp1().setStr1("a2'"); - cte3.getComp2().setStr6("y3'"); - cte4.setComp1(new Component1()); - cte4.getComp1().setStr1("n"); - cte4.setComp2(new Component2()); - cte4.getComp2().setStr5("m"); + cte1.setComp1( new Component1( "a'", "b'" ) ); + cte2.getComp1().setStr1( "a2'" ); + cte3.getComp2().setStr6( "y3'" ); + cte4.setComp1( new Component1() ); + cte4.getComp1().setStr1( "n" ); + cte4.setComp2( new Component2() ); + cte4.getComp2().setStr5( "m" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 3 + em = getEntityManager(); + em.getTransaction().begin(); - cte1 = em.find(ComponentTestEntity.class, cte1.getId()); - cte2 = em.find(ComponentTestEntity.class, cte2.getId()); - cte3 = em.find(ComponentTestEntity.class, cte3.getId()); - cte4 = em.find(ComponentTestEntity.class, cte4.getId()); + cte1 = em.find( ComponentTestEntity.class, cte1.getId() ); + cte2 = em.find( ComponentTestEntity.class, cte2.getId() ); + cte3 = em.find( ComponentTestEntity.class, cte3.getId() ); + cte4 = em.find( ComponentTestEntity.class, cte4.getId() ); - cte1.setComp2(new Component2("x'", "y'")); - cte3.getComp1().setStr2("b3'"); - cte4.setComp1(null); - cte4.setComp2(null); + cte1.setComp2( new Component2( "x'", "y'" ) ); + cte3.getComp1().setStr2( "b3'" ); + cte4.setComp1( null ); + cte4.setComp2( null ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 4 + em = getEntityManager(); + em.getTransaction().begin(); - cte2 = em.find(ComponentTestEntity.class, cte2.getId()); + cte2 = em.find( ComponentTestEntity.class, cte2.getId() ); - em.remove(cte2); + em.remove( cte2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - id1 = cte1.getId(); - id2 = cte2.getId(); - id3 = cte3.getId(); - id4 = cte4.getId(); - } + id1 = cte1.getId(); + id2 = cte2.getId(); + id3 = cte3.getId(); + id4 = cte4.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(ComponentTestEntity.class, id1)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( ComponentTestEntity.class, id1 ) ); - assert Arrays.asList(1, 2, 4).equals(getAuditReader().getRevisions(ComponentTestEntity.class, id2)); + assert Arrays.asList( 1, 2, 4 ).equals( getAuditReader().getRevisions( ComponentTestEntity.class, id2 ) ); - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(ComponentTestEntity.class, id3)); + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( ComponentTestEntity.class, id3 ) ); - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(ComponentTestEntity.class, id4)); - } + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( ComponentTestEntity.class, id4 ) ); + } - @Test - public void testHistoryOfId1() { - ComponentTestEntity ver1 = new ComponentTestEntity(id1, new Component1("a", "b"), null); - ComponentTestEntity ver2 = new ComponentTestEntity(id1, new Component1("a'", "b'"), null); + @Test + public void testHistoryOfId1() { + ComponentTestEntity ver1 = new ComponentTestEntity( id1, new Component1( "a", "b" ), null ); + ComponentTestEntity ver2 = new ComponentTestEntity( id1, new Component1( "a'", "b'" ), null ); - assert getAuditReader().find(ComponentTestEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(ComponentTestEntity.class, id1, 2).equals(ver2); - assert getAuditReader().find(ComponentTestEntity.class, id1, 3).equals(ver2); - assert getAuditReader().find(ComponentTestEntity.class, id1, 4).equals(ver2); - } + assert getAuditReader().find( ComponentTestEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( ComponentTestEntity.class, id1, 2 ).equals( ver2 ); + assert getAuditReader().find( ComponentTestEntity.class, id1, 3 ).equals( ver2 ); + assert getAuditReader().find( ComponentTestEntity.class, id1, 4 ).equals( ver2 ); + } - @Test - public void testHistoryOfId2() { - ComponentTestEntity ver1 = new ComponentTestEntity(id2, new Component1("a2", "b2"), null); - ComponentTestEntity ver2 = new ComponentTestEntity(id2, new Component1("a2'", "b2"), null); + @Test + public void testHistoryOfId2() { + ComponentTestEntity ver1 = new ComponentTestEntity( id2, new Component1( "a2", "b2" ), null ); + ComponentTestEntity ver2 = new ComponentTestEntity( id2, new Component1( "a2'", "b2" ), null ); - assert getAuditReader().find(ComponentTestEntity.class, id2, 1).equals(ver1); - assert getAuditReader().find(ComponentTestEntity.class, id2, 2).equals(ver2); - assert getAuditReader().find(ComponentTestEntity.class, id2, 3).equals(ver2); - assert getAuditReader().find(ComponentTestEntity.class, id2, 4) == null; - } + assert getAuditReader().find( ComponentTestEntity.class, id2, 1 ).equals( ver1 ); + assert getAuditReader().find( ComponentTestEntity.class, id2, 2 ).equals( ver2 ); + assert getAuditReader().find( ComponentTestEntity.class, id2, 3 ).equals( ver2 ); + assert getAuditReader().find( ComponentTestEntity.class, id2, 4 ) == null; + } - @Test - public void testHistoryOfId3() { - ComponentTestEntity ver1 = new ComponentTestEntity(id3, new Component1("a3", "b3"), null); - ComponentTestEntity ver2 = new ComponentTestEntity(id3, new Component1("a3", "b3'"), null); + @Test + public void testHistoryOfId3() { + ComponentTestEntity ver1 = new ComponentTestEntity( id3, new Component1( "a3", "b3" ), null ); + ComponentTestEntity ver2 = new ComponentTestEntity( id3, new Component1( "a3", "b3'" ), null ); - assert getAuditReader().find(ComponentTestEntity.class, id3, 1).equals(ver1); - assert getAuditReader().find(ComponentTestEntity.class, id3, 2).equals(ver1); - assert getAuditReader().find(ComponentTestEntity.class, id3, 3).equals(ver2); - assert getAuditReader().find(ComponentTestEntity.class, id3, 4).equals(ver2); - } + assert getAuditReader().find( ComponentTestEntity.class, id3, 1 ).equals( ver1 ); + assert getAuditReader().find( ComponentTestEntity.class, id3, 2 ).equals( ver1 ); + assert getAuditReader().find( ComponentTestEntity.class, id3, 3 ).equals( ver2 ); + assert getAuditReader().find( ComponentTestEntity.class, id3, 4 ).equals( ver2 ); + } - @Test - public void testHistoryOfId4() { - ComponentTestEntity ver1 = new ComponentTestEntity(id4, null, null); - ComponentTestEntity ver2 = new ComponentTestEntity(id4, new Component1("n", null), null); - ComponentTestEntity ver3 = new ComponentTestEntity(id4, null, null); + @Test + public void testHistoryOfId4() { + ComponentTestEntity ver1 = new ComponentTestEntity( id4, null, null ); + ComponentTestEntity ver2 = new ComponentTestEntity( id4, new Component1( "n", null ), null ); + ComponentTestEntity ver3 = new ComponentTestEntity( id4, null, null ); - assert getAuditReader().find(ComponentTestEntity.class, id4, 1).equals(ver1); - assert getAuditReader().find(ComponentTestEntity.class, id4, 2).equals(ver2); - assert getAuditReader().find(ComponentTestEntity.class, id4, 3).equals(ver3); - assert getAuditReader().find(ComponentTestEntity.class, id4, 4).equals(ver3); - } + assert getAuditReader().find( ComponentTestEntity.class, id4, 1 ).equals( ver1 ); + assert getAuditReader().find( ComponentTestEntity.class, id4, 2 ).equals( ver2 ); + assert getAuditReader().find( ComponentTestEntity.class, id4, 3 ).equals( ver3 ); + assert getAuditReader().find( ComponentTestEntity.class, id4, 4 ).equals( ver3 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/DefaultValueComponents.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/DefaultValueComponents.java index ab284bfe1f..b35529ce71 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/DefaultValueComponents.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/DefaultValueComponents.java @@ -23,11 +23,10 @@ */ package org.hibernate.envers.test.integration.components; -import java.util.Arrays; import javax.persistence.EntityManager; +import java.util.Arrays; import org.jboss.logging.Logger; -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -35,14 +34,15 @@ import org.hibernate.envers.test.entities.components.DefaultValueComponent1; import org.hibernate.envers.test.entities.components.DefaultValueComponent2; import org.hibernate.envers.test.entities.components.DefaultValueComponentTestEntity; +import org.junit.Test; + /** * Test class for components with default values. * + * @author Erik-Berndt Scheper * @see * Hibernate JIRA - * - * @author Erik-Berndt Scheper */ public class DefaultValueComponents extends BaseEnversJPAFunctionalTestCase { private static final Logger log = Logger.getLogger( DefaultValueComponents.class ); @@ -57,49 +57,73 @@ public class DefaultValueComponents extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { DefaultValueComponentTestEntity.class }; + return new Class[] {DefaultValueComponentTestEntity.class}; } @Test - @Priority(10) + @Priority(10) public void initData() { // Revision 1 EntityManager em = getEntityManager(); em.getTransaction().begin(); DefaultValueComponentTestEntity cte0 = DefaultValueComponentTestEntity - .of(null); + .of( null ); DefaultValueComponentTestEntity cte1 = DefaultValueComponentTestEntity - .of(DefaultValueComponent1.of("c1-str1", null)); + .of( DefaultValueComponent1.of( "c1-str1", null ) ); DefaultValueComponentTestEntity cte2 = DefaultValueComponentTestEntity - .of(DefaultValueComponent1.of("c1-str1", DefaultValueComponent2 - .of("c2-str1", "c2-str2"))); + .of( + DefaultValueComponent1.of( + "c1-str1", DefaultValueComponent2 + .of( "c2-str1", "c2-str2" ) + ) + ); DefaultValueComponentTestEntity cte3 = DefaultValueComponentTestEntity - .of(DefaultValueComponent1.of(null, DefaultValueComponent2.of( - "c2-str1", "c2-str2"))); + .of( + DefaultValueComponent1.of( + null, DefaultValueComponent2.of( + "c2-str1", "c2-str2" + ) + ) + ); DefaultValueComponentTestEntity cte4 = DefaultValueComponentTestEntity - .of(DefaultValueComponent1.of(null, DefaultValueComponent2.of( - null, "c2-str2"))); + .of( + DefaultValueComponent1.of( + null, DefaultValueComponent2.of( + null, "c2-str2" + ) + ) + ); DefaultValueComponentTestEntity cte5 = DefaultValueComponentTestEntity - .of(DefaultValueComponent1.of(null, DefaultValueComponent2.of( - "c2-str1", null))); + .of( + DefaultValueComponent1.of( + null, DefaultValueComponent2.of( + "c2-str1", null + ) + ) + ); DefaultValueComponentTestEntity cte6 = DefaultValueComponentTestEntity - .of(DefaultValueComponent1.of(null, DefaultValueComponent2.of( - null, null))); + .of( + DefaultValueComponent1.of( + null, DefaultValueComponent2.of( + null, null + ) + ) + ); - em.persist(cte0); - em.persist(cte1); - em.persist(cte2); - em.persist(cte3); - em.persist(cte4); - em.persist(cte5); - em.persist(cte6); + em.persist( cte0 ); + em.persist( cte1 ); + em.persist( cte2 ); + em.persist( cte3 ); + em.persist( cte4 ); + em.persist( cte5 ); + em.persist( cte6 ); em.getTransaction().commit(); @@ -107,22 +131,26 @@ public class DefaultValueComponents extends BaseEnversJPAFunctionalTestCase { em = getEntityManager(); em.getTransaction().begin(); - cte0 = em.find(DefaultValueComponentTestEntity.class, cte0.getId()); - cte1 = em.find(DefaultValueComponentTestEntity.class, cte1.getId()); - cte2 = em.find(DefaultValueComponentTestEntity.class, cte2.getId()); - cte3 = em.find(DefaultValueComponentTestEntity.class, cte3.getId()); - cte4 = em.find(DefaultValueComponentTestEntity.class, cte4.getId()); - cte5 = em.find(DefaultValueComponentTestEntity.class, cte5.getId()); - cte6 = em.find(DefaultValueComponentTestEntity.class, cte6.getId()); + cte0 = em.find( DefaultValueComponentTestEntity.class, cte0.getId() ); + cte1 = em.find( DefaultValueComponentTestEntity.class, cte1.getId() ); + cte2 = em.find( DefaultValueComponentTestEntity.class, cte2.getId() ); + cte3 = em.find( DefaultValueComponentTestEntity.class, cte3.getId() ); + cte4 = em.find( DefaultValueComponentTestEntity.class, cte4.getId() ); + cte5 = em.find( DefaultValueComponentTestEntity.class, cte5.getId() ); + cte6 = em.find( DefaultValueComponentTestEntity.class, cte6.getId() ); - cte0.setComp1(DefaultValueComponent1.of("upd-c1-str1", null)); - cte1.setComp1(DefaultValueComponent1.of(null, DefaultValueComponent2 - .of("upd-c2-str1", "upd-c2-str2"))); - cte2.getComp1().getComp2().setStr1("upd-c2-str1"); - cte3.getComp1().getComp2().setStr1("upd-c2-str1"); - cte4.getComp1().getComp2().setStr1("upd-c2-str1"); - cte5.getComp1().getComp2().setStr1("upd-c2-str1"); - cte6.getComp1().getComp2().setStr1("upd-c2-str1"); + cte0.setComp1( DefaultValueComponent1.of( "upd-c1-str1", null ) ); + cte1.setComp1( + DefaultValueComponent1.of( + null, DefaultValueComponent2 + .of( "upd-c2-str1", "upd-c2-str2" ) + ) + ); + cte2.getComp1().getComp2().setStr1( "upd-c2-str1" ); + cte3.getComp1().getComp2().setStr1( "upd-c2-str1" ); + cte4.getComp1().getComp2().setStr1( "upd-c2-str1" ); + cte5.getComp1().getComp2().setStr1( "upd-c2-str1" ); + cte6.getComp1().getComp2().setStr1( "upd-c2-str1" ); em.getTransaction().commit(); @@ -138,243 +166,339 @@ public class DefaultValueComponents extends BaseEnversJPAFunctionalTestCase { @Test public void testRevisionsCounts() { - log.error(getAuditReader().getRevisions( - DefaultValueComponentTestEntity.class, id0).toString()); - log.error(getAuditReader().getRevisions( - DefaultValueComponentTestEntity.class, id1).toString()); - log.error(getAuditReader().getRevisions( - DefaultValueComponentTestEntity.class, id2).toString()); - log.error(getAuditReader().getRevisions( - DefaultValueComponentTestEntity.class, id3).toString()); - log.error(getAuditReader().getRevisions( - DefaultValueComponentTestEntity.class, id4).toString()); - log.error(getAuditReader().getRevisions( - DefaultValueComponentTestEntity.class, id5).toString()); - log.error(getAuditReader().getRevisions( - DefaultValueComponentTestEntity.class, id6).toString()); - - assert Arrays.asList(1, 2).equals( + log.error( getAuditReader().getRevisions( - DefaultValueComponentTestEntity.class, id0)); - - assert Arrays.asList(1, 2).equals( + DefaultValueComponentTestEntity.class, id0 + ).toString() + ); + log.error( getAuditReader().getRevisions( - DefaultValueComponentTestEntity.class, id1)); - - assert Arrays.asList(1, 2).equals( + DefaultValueComponentTestEntity.class, id1 + ).toString() + ); + log.error( getAuditReader().getRevisions( - DefaultValueComponentTestEntity.class, id2)); - - assert Arrays.asList(1, 2).equals( + DefaultValueComponentTestEntity.class, id2 + ).toString() + ); + log.error( getAuditReader().getRevisions( - DefaultValueComponentTestEntity.class, id3)); - - assert Arrays.asList(1, 2).equals( + DefaultValueComponentTestEntity.class, id3 + ).toString() + ); + log.error( getAuditReader().getRevisions( - DefaultValueComponentTestEntity.class, id4)); - - assert Arrays.asList(1, 2).equals( + DefaultValueComponentTestEntity.class, id4 + ).toString() + ); + log.error( getAuditReader().getRevisions( - DefaultValueComponentTestEntity.class, id5)); - - assert Arrays.asList(1, 2).equals( + DefaultValueComponentTestEntity.class, id5 + ).toString() + ); + log.error( getAuditReader().getRevisions( - DefaultValueComponentTestEntity.class, id6)); + DefaultValueComponentTestEntity.class, id6 + ).toString() + ); + + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( + DefaultValueComponentTestEntity.class, id0 + ) + ); + + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( + DefaultValueComponentTestEntity.class, id1 + ) + ); + + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( + DefaultValueComponentTestEntity.class, id2 + ) + ); + + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( + DefaultValueComponentTestEntity.class, id3 + ) + ); + + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( + DefaultValueComponentTestEntity.class, id4 + ) + ); + + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( + DefaultValueComponentTestEntity.class, id5 + ) + ); + + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( + DefaultValueComponentTestEntity.class, id6 + ) + ); } @Test public void testHistoryOfId0() { DefaultValueComponentTestEntity ent1 = getAuditReader().find( - DefaultValueComponentTestEntity.class, id0, 1); + DefaultValueComponentTestEntity.class, id0, 1 + ); DefaultValueComponentTestEntity ent2 = getAuditReader().find( - DefaultValueComponentTestEntity.class, id0, 2); + DefaultValueComponentTestEntity.class, id0, 2 + ); - log.error("------------ id0 -------------"); - log.error(ent1.toString()); - log.error(ent2.toString()); + log.error( "------------ id0 -------------" ); + log.error( ent1.toString() ); + log.error( ent2.toString() ); - checkCorrectlyPersisted(id0, null, null); + checkCorrectlyPersisted( id0, null, null ); DefaultValueComponentTestEntity expectedVer1 = DefaultValueComponentTestEntity - .of(id0, DefaultValueComponent1.of(null, null)); + .of( id0, DefaultValueComponent1.of( null, null ) ); DefaultValueComponentTestEntity expectedVer2 = DefaultValueComponentTestEntity - .of(id0, DefaultValueComponent1.of("upd-c1-str1", null)); + .of( id0, DefaultValueComponent1.of( "upd-c1-str1", null ) ); - assert ent1.equals(expectedVer1); - assert ent2.equals(expectedVer2); + assert ent1.equals( expectedVer1 ); + assert ent2.equals( expectedVer2 ); } @Test public void testHistoryOfId1() { DefaultValueComponentTestEntity ent1 = getAuditReader().find( - DefaultValueComponentTestEntity.class, id1, 1); + DefaultValueComponentTestEntity.class, id1, 1 + ); DefaultValueComponentTestEntity ent2 = getAuditReader().find( - DefaultValueComponentTestEntity.class, id1, 2); + DefaultValueComponentTestEntity.class, id1, 2 + ); - log.error("------------ id1 -------------"); - log.error(ent1.toString()); - log.error(ent2.toString()); + log.error( "------------ id1 -------------" ); + log.error( ent1.toString() ); + log.error( ent2.toString() ); - checkCorrectlyPersisted(id1, null, "upd-c2-str1"); + checkCorrectlyPersisted( id1, null, "upd-c2-str1" ); DefaultValueComponentTestEntity expectedVer1 = DefaultValueComponentTestEntity - .of(id1, DefaultValueComponent1.of("c1-str1", null)); + .of( id1, DefaultValueComponent1.of( "c1-str1", null ) ); DefaultValueComponentTestEntity expectedVer2 = DefaultValueComponentTestEntity - .of(id1, DefaultValueComponent1.of(null, DefaultValueComponent2 - .of("upd-c2-str1", "upd-c2-str2"))); + .of( + id1, DefaultValueComponent1.of( + null, DefaultValueComponent2 + .of( "upd-c2-str1", "upd-c2-str2" ) + ) + ); - assert ent2.equals(expectedVer2); - assert ent1.equals(expectedVer1); + assert ent2.equals( expectedVer2 ); + assert ent1.equals( expectedVer1 ); } @Test public void testHistoryOfId2() { DefaultValueComponentTestEntity ent1 = getAuditReader().find( - DefaultValueComponentTestEntity.class, id2, 1); + DefaultValueComponentTestEntity.class, id2, 1 + ); DefaultValueComponentTestEntity ent2 = getAuditReader().find( - DefaultValueComponentTestEntity.class, id2, 2); + DefaultValueComponentTestEntity.class, id2, 2 + ); - log.error("------------ id2 -------------"); - log.error(ent1.toString()); - log.error(ent2.toString()); + log.error( "------------ id2 -------------" ); + log.error( ent1.toString() ); + log.error( ent2.toString() ); DefaultValueComponentTestEntity expectedVer1 = DefaultValueComponentTestEntity - .of(id2, DefaultValueComponent1.of("c1-str1", - DefaultValueComponent2.of("c2-str1", "c2-str2"))); + .of( + id2, DefaultValueComponent1.of( + "c1-str1", + DefaultValueComponent2.of( "c2-str1", "c2-str2" ) + ) + ); DefaultValueComponentTestEntity expectedVer2 = DefaultValueComponentTestEntity - .of(id2, DefaultValueComponent1.of("c1-str1", - DefaultValueComponent2.of("upd-c2-str1", "c2-str2"))); + .of( + id2, DefaultValueComponent1.of( + "c1-str1", + DefaultValueComponent2.of( "upd-c2-str1", "c2-str2" ) + ) + ); - assert ent1.equals(expectedVer1); - assert ent2.equals(expectedVer2); + assert ent1.equals( expectedVer1 ); + assert ent2.equals( expectedVer2 ); } @Test public void testHistoryOfId3() { DefaultValueComponentTestEntity ent1 = getAuditReader().find( - DefaultValueComponentTestEntity.class, id3, 1); + DefaultValueComponentTestEntity.class, id3, 1 + ); DefaultValueComponentTestEntity ent2 = getAuditReader().find( - DefaultValueComponentTestEntity.class, id3, 2); + DefaultValueComponentTestEntity.class, id3, 2 + ); - log.error("------------ id3 -------------"); - log.error(ent1.toString()); - log.error(ent2.toString()); + log.error( "------------ id3 -------------" ); + log.error( ent1.toString() ); + log.error( ent2.toString() ); DefaultValueComponentTestEntity expectedVer1 = DefaultValueComponentTestEntity - .of(id3, DefaultValueComponent1.of(null, DefaultValueComponent2 - .of("c2-str1", "c2-str2"))); + .of( + id3, DefaultValueComponent1.of( + null, DefaultValueComponent2 + .of( "c2-str1", "c2-str2" ) + ) + ); DefaultValueComponentTestEntity expectedVer2 = DefaultValueComponentTestEntity - .of(id3, DefaultValueComponent1.of(null, DefaultValueComponent2 - .of("upd-c2-str1", "c2-str2"))); + .of( + id3, DefaultValueComponent1.of( + null, DefaultValueComponent2 + .of( "upd-c2-str1", "c2-str2" ) + ) + ); - assert ent1.equals(expectedVer1); - assert ent2.equals(expectedVer2); + assert ent1.equals( expectedVer1 ); + assert ent2.equals( expectedVer2 ); } @Test public void testHistoryOfId4() { DefaultValueComponentTestEntity ent1 = getAuditReader().find( - DefaultValueComponentTestEntity.class, id4, 1); + DefaultValueComponentTestEntity.class, id4, 1 + ); DefaultValueComponentTestEntity ent2 = getAuditReader().find( - DefaultValueComponentTestEntity.class, id4, 2); + DefaultValueComponentTestEntity.class, id4, 2 + ); - log.error("------------ id4 -------------"); - log.error(ent1.toString()); - log.error(ent2.toString()); + log.error( "------------ id4 -------------" ); + log.error( ent1.toString() ); + log.error( ent2.toString() ); DefaultValueComponentTestEntity expectedVer1 = DefaultValueComponentTestEntity - .of(id4, DefaultValueComponent1.of(null, DefaultValueComponent2 - .of(null, "c2-str2"))); + .of( + id4, DefaultValueComponent1.of( + null, DefaultValueComponent2 + .of( null, "c2-str2" ) + ) + ); DefaultValueComponentTestEntity expectedVer2 = DefaultValueComponentTestEntity - .of(id4, DefaultValueComponent1.of(null, DefaultValueComponent2 - .of("upd-c2-str1", "c2-str2"))); + .of( + id4, DefaultValueComponent1.of( + null, DefaultValueComponent2 + .of( "upd-c2-str1", "c2-str2" ) + ) + ); - assert ent1.equals(expectedVer1); - assert ent2.equals(expectedVer2); + assert ent1.equals( expectedVer1 ); + assert ent2.equals( expectedVer2 ); } @Test public void testHistoryOfId5() { DefaultValueComponentTestEntity ent1 = getAuditReader().find( - DefaultValueComponentTestEntity.class, id5, 1); + DefaultValueComponentTestEntity.class, id5, 1 + ); DefaultValueComponentTestEntity ent2 = getAuditReader().find( - DefaultValueComponentTestEntity.class, id5, 2); + DefaultValueComponentTestEntity.class, id5, 2 + ); - log.error("------------ id5 -------------"); - log.error(ent1.toString()); - log.error(ent2.toString()); + log.error( "------------ id5 -------------" ); + log.error( ent1.toString() ); + log.error( ent2.toString() ); DefaultValueComponentTestEntity expectedVer1 = DefaultValueComponentTestEntity - .of(id5, DefaultValueComponent1.of(null, DefaultValueComponent2 - .of("c2-str1", null))); + .of( + id5, DefaultValueComponent1.of( + null, DefaultValueComponent2 + .of( "c2-str1", null ) + ) + ); DefaultValueComponentTestEntity expectedVer2 = DefaultValueComponentTestEntity - .of(id5, DefaultValueComponent1.of(null, DefaultValueComponent2 - .of("upd-c2-str1", null))); + .of( + id5, DefaultValueComponent1.of( + null, DefaultValueComponent2 + .of( "upd-c2-str1", null ) + ) + ); - assert ent1.equals(expectedVer1); - assert ent2.equals(expectedVer2); + assert ent1.equals( expectedVer1 ); + assert ent2.equals( expectedVer2 ); } @Test public void testHistoryOfId6() { DefaultValueComponentTestEntity ent1 = getAuditReader().find( - DefaultValueComponentTestEntity.class, id6, 1); + DefaultValueComponentTestEntity.class, id6, 1 + ); DefaultValueComponentTestEntity ent2 = getAuditReader().find( - DefaultValueComponentTestEntity.class, id6, 2); + DefaultValueComponentTestEntity.class, id6, 2 + ); - log.error("------------ id6 -------------"); - log.error(ent1.toString()); - log.error(ent2.toString()); + log.error( "------------ id6 -------------" ); + log.error( ent1.toString() ); + log.error( ent2.toString() ); DefaultValueComponentTestEntity expectedVer1 = DefaultValueComponentTestEntity - .of(id6, DefaultValueComponent1.of(null, null)); + .of( id6, DefaultValueComponent1.of( null, null ) ); DefaultValueComponentTestEntity expectedVer2 = DefaultValueComponentTestEntity - .of(id6, DefaultValueComponent1.of(null, DefaultValueComponent2 - .of("upd-c2-str1", null))); + .of( + id6, DefaultValueComponent1.of( + null, DefaultValueComponent2 + .of( "upd-c2-str1", null ) + ) + ); - assert ent2.equals(expectedVer2); - assert ent1.equals(expectedVer1); + assert ent2.equals( expectedVer2 ); + assert ent1.equals( expectedVer1 ); } - private void checkCorrectlyPersisted(Integer expectedId, + private void checkCorrectlyPersisted( + Integer expectedId, String expectedComp2Str1Rev1, String expectedComp2Str1Rev2) { // Verify that the entity was correctly persisted EntityManager em = getEntityManager(); em.getTransaction().begin(); Long entCount = (Long) em.createQuery( "select count(s) from DefaultValueComponentTestEntity s where s.id = " - + expectedId.toString()).getSingleResult(); + + expectedId.toString() + ).getSingleResult(); Number auditCount = (Number) em.createNativeQuery( "select count(ID) from DefaultValueComponent_AUD s where s.id = " - + expectedId.toString()).getSingleResult(); + + expectedId.toString() + ).getSingleResult(); String comp2Str1Rev1 = (String) em .createNativeQuery( "select COMP2_STR1 from DefaultValueComponent_AUD s where rev=1 and s.id = " - + expectedId.toString()).getSingleResult(); + + expectedId.toString() + ).getSingleResult(); String comp2Str1Rev2 = (String) em .createNativeQuery( "select COMP2_STR1 from DefaultValueComponent_AUD s where rev=2 and s.id = " - + expectedId.toString()).getSingleResult(); - assert Long.valueOf(1L).equals(entCount); - assert Integer.valueOf(2).equals(auditCount.intValue()); + + expectedId.toString() + ).getSingleResult(); + assert Long.valueOf( 1L ).equals( entCount ); + assert Integer.valueOf( 2 ).equals( auditCount.intValue() ); - if (expectedComp2Str1Rev1 == null) { + if ( expectedComp2Str1Rev1 == null ) { assert comp2Str1Rev1 == null; - } else { - assert expectedComp2Str1Rev1.equals(comp2Str1Rev1); + } + else { + assert expectedComp2Str1Rev1.equals( comp2Str1Rev1 ); } - if (expectedComp2Str1Rev2 == null) { + if ( expectedComp2Str1Rev2 == null ) { assert comp2Str1Rev2 == null; - } else { - assert expectedComp2Str1Rev2.equals(comp2Str1Rev2); + } + else { + assert expectedComp2Str1Rev2.equals( comp2Str1Rev2 ); } em.getTransaction().commit(); } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/PropertiesGroupTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/PropertiesGroupTest.java index 34c6b0e4a6..db70b09c9c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/PropertiesGroupTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/PropertiesGroupTest.java @@ -1,8 +1,5 @@ package org.hibernate.envers.test.integration.components; -import org.junit.Assert; -import org.junit.Test; - import org.hibernate.Session; import org.hibernate.envers.test.BaseEnversFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -10,6 +7,10 @@ import org.hibernate.envers.test.entities.components.UniquePropsEntity; import org.hibernate.envers.test.entities.components.UniquePropsNotAuditedEntity; import org.hibernate.mapping.Column; import org.hibernate.mapping.PersistentClass; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -17,63 +18,73 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-6636") public class PropertiesGroupTest extends BaseEnversFunctionalTestCase { - private PersistentClass uniquePropsAudit = null; - private PersistentClass uniquePropsNotAuditedAudit = null; - private UniquePropsEntity entityRev1 = null; - private UniquePropsNotAuditedEntity entityNotAuditedRev2 = null; + private PersistentClass uniquePropsAudit = null; + private PersistentClass uniquePropsNotAuditedAudit = null; + private UniquePropsEntity entityRev1 = null; + private UniquePropsNotAuditedEntity entityNotAuditedRev2 = null; - @Override - protected String[] getMappings() { - return new String[] { - "mappings/components/UniquePropsEntity.hbm.xml", - "mappings/components/UniquePropsNotAuditedEntity.hbm.xml" - }; - } + @Override + protected String[] getMappings() { + return new String[] { + "mappings/components/UniquePropsEntity.hbm.xml", + "mappings/components/UniquePropsNotAuditedEntity.hbm.xml" + }; + } - @Test - @Priority(10) - public void initData() { - uniquePropsAudit = configuration().getClassMapping("org.hibernate.envers.test.entities.components.UniquePropsEntity_AUD"); - uniquePropsNotAuditedAudit = configuration().getClassMapping("org.hibernate.envers.test.entities.components.UniquePropsNotAuditedEntity_AUD"); + @Test + @Priority(10) + public void initData() { + uniquePropsAudit = configuration().getClassMapping( + "org.hibernate.envers.test.entities.components.UniquePropsEntity_AUD" + ); + uniquePropsNotAuditedAudit = configuration().getClassMapping( + "org.hibernate.envers.test.entities.components.UniquePropsNotAuditedEntity_AUD" + ); - // Revision 1 - Session session = openSession(); - session.getTransaction().begin(); - UniquePropsEntity ent = new UniquePropsEntity(); - ent.setData1("data1"); - ent.setData2("data2"); - session.persist(ent); - session.getTransaction().commit(); + // Revision 1 + Session session = openSession(); + session.getTransaction().begin(); + UniquePropsEntity ent = new UniquePropsEntity(); + ent.setData1( "data1" ); + ent.setData2( "data2" ); + session.persist( ent ); + session.getTransaction().commit(); - entityRev1 = new UniquePropsEntity(ent.getId(), ent.getData1(), ent.getData2()); + entityRev1 = new UniquePropsEntity( ent.getId(), ent.getData1(), ent.getData2() ); - // Revision 2 - session.getTransaction().begin(); - UniquePropsNotAuditedEntity entNotAud = new UniquePropsNotAuditedEntity(); - entNotAud.setData1("data3"); - entNotAud.setData2("data4"); - session.persist(entNotAud); - session.getTransaction().commit(); + // Revision 2 + session.getTransaction().begin(); + UniquePropsNotAuditedEntity entNotAud = new UniquePropsNotAuditedEntity(); + entNotAud.setData1( "data3" ); + entNotAud.setData2( "data4" ); + session.persist( entNotAud ); + session.getTransaction().commit(); - entityNotAuditedRev2 = new UniquePropsNotAuditedEntity(entNotAud.getId(), entNotAud.getData1(), null); - } + entityNotAuditedRev2 = new UniquePropsNotAuditedEntity( entNotAud.getId(), entNotAud.getData1(), null ); + } - @Test - public void testAuditTableColumns() { - Assert.assertNotNull(uniquePropsAudit.getTable().getColumn(new Column("DATA1"))); - Assert.assertNotNull(uniquePropsAudit.getTable().getColumn(new Column("DATA2"))); + @Test + public void testAuditTableColumns() { + Assert.assertNotNull( uniquePropsAudit.getTable().getColumn( new Column( "DATA1" ) ) ); + Assert.assertNotNull( uniquePropsAudit.getTable().getColumn( new Column( "DATA2" ) ) ); - Assert.assertNotNull(uniquePropsNotAuditedAudit.getTable().getColumn(new Column("DATA1"))); - Assert.assertNull(uniquePropsNotAuditedAudit.getTable().getColumn(new Column("DATA2"))); - } + Assert.assertNotNull( uniquePropsNotAuditedAudit.getTable().getColumn( new Column( "DATA1" ) ) ); + Assert.assertNull( uniquePropsNotAuditedAudit.getTable().getColumn( new Column( "DATA2" ) ) ); + } - @Test - public void testHistoryOfUniquePropsEntity() { - Assert.assertEquals(entityRev1, getAuditReader().find(UniquePropsEntity.class, entityRev1.getId(), 1)); - } + @Test + public void testHistoryOfUniquePropsEntity() { + Assert.assertEquals( entityRev1, getAuditReader().find( UniquePropsEntity.class, entityRev1.getId(), 1 ) ); + } - @Test - public void testHistoryOfUniquePropsNotAuditedEntity() { - Assert.assertEquals(entityNotAuditedRev2, getAuditReader().find(UniquePropsNotAuditedEntity.class, entityNotAuditedRev2.getId(), 2)); - } + @Test + public void testHistoryOfUniquePropsNotAuditedEntity() { + Assert.assertEquals( + entityNotAuditedRev2, getAuditReader().find( + UniquePropsNotAuditedEntity.class, + entityNotAuditedRev2.getId(), + 2 + ) + ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/collections/CollectionOfComponents.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/collections/CollectionOfComponents.java index 52e52a6647..9f8317bb4d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/collections/CollectionOfComponents.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/collections/CollectionOfComponents.java @@ -23,68 +23,69 @@ */ package org.hibernate.envers.test.integration.components.collections; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Set; -import javax.persistence.EntityManager; - -import org.junit.Ignore; -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.components.Component1; import org.hibernate.envers.test.entities.components.ComponentSetTestEntity; +import org.junit.Ignore; +import org.junit.Test; + /** * TODO: enable and implement + * * @author Adam Warski (adam at warski dot org) */ @Ignore public class CollectionOfComponents extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ComponentSetTestEntity.class }; - } + return new Class[] {ComponentSetTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - ComponentSetTestEntity cte1 = new ComponentSetTestEntity(); + ComponentSetTestEntity cte1 = new ComponentSetTestEntity(); - em.persist(cte1); + em.persist( cte1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 2 + em = getEntityManager(); + em.getTransaction().begin(); - cte1 = em.find(ComponentSetTestEntity.class, cte1.getId()); + cte1 = em.find( ComponentSetTestEntity.class, cte1.getId() ); - cte1.getComps().add(new Component1("a", "b")); + cte1.getComps().add( new Component1( "a", "b" ) ); - em.getTransaction().commit(); + em.getTransaction().commit(); - id1 = cte1.getId(); - } + id1 = cte1.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(ComponentSetTestEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( ComponentSetTestEntity.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - assert getAuditReader().find(ComponentSetTestEntity.class, id1, 1).getComps().size() == 0; - - Set comps1 = getAuditReader().find(ComponentSetTestEntity.class, id1, 2).getComps(); - assert comps1.size() == 1; - assert comps1.contains(new Component1("a", "b")); - } + @Test + public void testHistoryOfId1() { + assert getAuditReader().find( ComponentSetTestEntity.class, id1, 1 ).getComps().size() == 0; + + Set comps1 = getAuditReader().find( ComponentSetTestEntity.class, id1, 2 ).getComps(); + assert comps1.size() == 1; + assert comps1.contains( new Component1( "a", "b" ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/dynamic/AuditedDynamicComponentTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/dynamic/AuditedDynamicComponentTest.java index f0e44ccfc2..418be712ff 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/dynamic/AuditedDynamicComponentTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/dynamic/AuditedDynamicComponentTest.java @@ -7,9 +7,6 @@ import java.net.URL; import java.util.HashMap; import java.util.Map; -import junit.framework.Assert; -import org.junit.Test; - import org.hibernate.MappingException; import org.hibernate.cfg.Configuration; import org.hibernate.envers.Audited; @@ -17,18 +14,24 @@ import org.hibernate.envers.configuration.EnversSettings; import org.hibernate.envers.internal.tools.StringTools; import org.hibernate.envers.test.AbstractEnversTest; import org.hibernate.service.ServiceRegistry; + +import org.junit.Test; +import junit.framework.Assert; + import org.hibernate.testing.ServiceRegistryBuilder; import org.hibernate.testing.TestForIssue; /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ -@TestForIssue( jiraKey = "HHH-8049" ) +@TestForIssue(jiraKey = "HHH-8049") public class AuditedDynamicComponentTest extends AbstractEnversTest { @Test public void testAuditedDynamicComponentFailure() throws URISyntaxException { final Configuration config = new Configuration(); - final URL hbm = Thread.currentThread().getContextClassLoader().getResource( "mappings/dynamicComponents/mapAudited.hbm.xml" ); + final URL hbm = Thread.currentThread().getContextClassLoader().getResource( + "mappings/dynamicComponents/mapAudited.hbm.xml" + ); config.addFile( new File( hbm.toURI() ) ); final String auditStrategy = getAuditStrategy(); @@ -41,7 +44,7 @@ public class AuditedDynamicComponentTest extends AbstractEnversTest { config.buildSessionFactory( serviceRegistry ); Assert.fail( "MappingException expected" ); } - catch ( MappingException e ) { + catch (MappingException e) { Assert.assertEquals( "Audited dynamic-component properties are not supported. Consider applying @NotAudited annotation to " + AuditedDynamicMapComponent.class.getName() + "#customFields.", diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/dynamic/NotAuditedDynamicComponentTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/dynamic/NotAuditedDynamicComponentTest.java index f20026f6b4..7a0e3d5e71 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/dynamic/NotAuditedDynamicComponentTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/dynamic/NotAuditedDynamicComponentTest.java @@ -2,22 +2,23 @@ package org.hibernate.envers.test.integration.components.dynamic; import java.util.Arrays; -import junit.framework.Assert; -import org.junit.Test; - import org.hibernate.Session; import org.hibernate.envers.test.BaseEnversFunctionalTestCase; import org.hibernate.envers.test.Priority; + +import org.junit.Test; +import junit.framework.Assert; + import org.hibernate.testing.TestForIssue; /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ -@TestForIssue( jiraKey = "HHH-8049" ) +@TestForIssue(jiraKey = "HHH-8049") public class NotAuditedDynamicComponentTest extends BaseEnversFunctionalTestCase { @Override protected String[] getMappings() { - return new String[] { "mappings/dynamicComponents/mapNotAudited.hbm.xml" }; + return new String[] {"mappings/dynamicComponents/mapNotAudited.hbm.xml"}; } @Test @@ -58,21 +59,32 @@ public class NotAuditedDynamicComponentTest extends BaseEnversFunctionalTestCase @Test public void testRevisionsCounts() { - Assert.assertEquals( Arrays.asList( 1, 2, 3 ), getAuditReader().getRevisions( NotAuditedDynamicMapComponent.class, 1L ) ); + Assert.assertEquals( + Arrays.asList( 1, 2, 3 ), + getAuditReader().getRevisions( NotAuditedDynamicMapComponent.class, 1L ) + ); } @Test public void testHistoryOfId1() { // Revision 1 NotAuditedDynamicMapComponent entity = new NotAuditedDynamicMapComponent( 1L, "static field value" ); - NotAuditedDynamicMapComponent ver1 = getAuditReader().find( NotAuditedDynamicMapComponent.class, entity.getId(), 1 ); + NotAuditedDynamicMapComponent ver1 = getAuditReader().find( + NotAuditedDynamicMapComponent.class, + entity.getId(), + 1 + ); Assert.assertEquals( entity, ver1 ); // Assume empty NotAuditedDynamicMapComponent#customFields map, because dynamic-component is not audited. Assert.assertTrue( ver1.getCustomFields().isEmpty() ); // Revision 2 entity.setNote( "updated note" ); - NotAuditedDynamicMapComponent ver2 = getAuditReader().find( NotAuditedDynamicMapComponent.class, entity.getId(), 2 ); + NotAuditedDynamicMapComponent ver2 = getAuditReader().find( + NotAuditedDynamicMapComponent.class, + entity.getId(), + 2 + ); Assert.assertEquals( entity, ver2 ); // Assume empty NotAuditedDynamicMapComponent#customFields map, because dynamic-component is not audited. Assert.assertTrue( ver2.getCustomFields().isEmpty() ); diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/dynamic/NotAuditedDynamicMapComponent.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/dynamic/NotAuditedDynamicMapComponent.java index 28e4b2634b..df747c1d72 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/dynamic/NotAuditedDynamicMapComponent.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/dynamic/NotAuditedDynamicMapComponent.java @@ -26,23 +26,33 @@ public class NotAuditedDynamicMapComponent implements Serializable { @Override public boolean equals(Object o) { - if ( this == o ) return true; - if ( !( o instanceof NotAuditedDynamicMapComponent ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof NotAuditedDynamicMapComponent) ) { + return false; + } NotAuditedDynamicMapComponent that = (NotAuditedDynamicMapComponent) o; - if ( id != that.id ) return false; - if ( customFields != null ? !customFields.equals( that.customFields ) : that.customFields != null ) return false; - if ( note != null ? !note.equals( that.note ) : that.note != null ) return false; + if ( id != that.id ) { + return false; + } + if ( customFields != null ? !customFields.equals( that.customFields ) : that.customFields != null ) { + return false; + } + if ( note != null ? !note.equals( that.note ) : that.note != null ) { + return false; + } return true; } @Override public int hashCode() { - int result = (int) ( id ^ ( id >>> 32 ) ); - result = 31 * result + ( note != null ? note.hashCode() : 0 ); - result = 31 * result + ( customFields != null ? customFields.hashCode() : 0 ); + int result = (int) (id ^ (id >>> 32)); + result = 31 * result + (note != null ? note.hashCode() : 0); + result = 31 * result + (customFields != null ? customFields.hashCode() : 0); return result; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/relations/ManyToOneInComponent.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/relations/ManyToOneInComponent.java index 4ef4e24211..fd7882acea 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/relations/ManyToOneInComponent.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/relations/ManyToOneInComponent.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.components.relations; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -34,77 +32,99 @@ import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.components.relations.ManyToOneComponent; import org.hibernate.envers.test.entities.components.relations.ManyToOneComponentTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ -public class ManyToOneInComponent extends BaseEnversJPAFunctionalTestCase { - private Integer mtocte_id1; +public class ManyToOneInComponent extends BaseEnversJPAFunctionalTestCase { + private Integer mtocte_id1; private Integer ste_id1; private Integer ste_id2; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ManyToOneComponentTestEntity.class, StrTestEntity.class}; + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {ManyToOneComponentTestEntity.class, StrTestEntity.class}; - } + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); StrTestEntity ste1 = new StrTestEntity(); - ste1.setStr("str1"); + ste1.setStr( "str1" ); StrTestEntity ste2 = new StrTestEntity(); - ste2.setStr("str2"); + ste2.setStr( "str2" ); - em.persist(ste1); - em.persist(ste2); + em.persist( ste1 ); + em.persist( ste2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 2 + em = getEntityManager(); + em.getTransaction().begin(); - ManyToOneComponentTestEntity mtocte1 = new ManyToOneComponentTestEntity(new ManyToOneComponent(ste1, "data1")); + ManyToOneComponentTestEntity mtocte1 = new ManyToOneComponentTestEntity( + new ManyToOneComponent( + ste1, + "data1" + ) + ); - em.persist(mtocte1); + em.persist( mtocte1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 3 + em = getEntityManager(); + em.getTransaction().begin(); - mtocte1 = em.find(ManyToOneComponentTestEntity.class, mtocte1.getId()); - mtocte1.getComp1().setEntity(ste2); + mtocte1 = em.find( ManyToOneComponentTestEntity.class, mtocte1.getId() ); + mtocte1.getComp1().setEntity( ste2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - mtocte_id1 = mtocte1.getId(); + mtocte_id1 = mtocte1.getId(); ste_id1 = ste1.getId(); ste_id2 = ste2.getId(); - } + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(2, 3).equals(getAuditReader().getRevisions(ManyToOneComponentTestEntity.class, mtocte_id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 2, 3 ).equals( + getAuditReader().getRevisions( + ManyToOneComponentTestEntity.class, + mtocte_id1 + ) + ); + } - @Test - public void testHistoryOfId1() { - StrTestEntity ste1 = getEntityManager().find(StrTestEntity.class, ste_id1); - StrTestEntity ste2 = getEntityManager().find(StrTestEntity.class, ste_id2); + @Test + public void testHistoryOfId1() { + StrTestEntity ste1 = getEntityManager().find( StrTestEntity.class, ste_id1 ); + StrTestEntity ste2 = getEntityManager().find( StrTestEntity.class, ste_id2 ); - ManyToOneComponentTestEntity ver2 = new ManyToOneComponentTestEntity(mtocte_id1, new ManyToOneComponent(ste1, "data1")); - ManyToOneComponentTestEntity ver3 = new ManyToOneComponentTestEntity(mtocte_id1, new ManyToOneComponent(ste2, "data1")); + ManyToOneComponentTestEntity ver2 = new ManyToOneComponentTestEntity( + mtocte_id1, new ManyToOneComponent( + ste1, + "data1" + ) + ); + ManyToOneComponentTestEntity ver3 = new ManyToOneComponentTestEntity( + mtocte_id1, new ManyToOneComponent( + ste2, + "data1" + ) + ); - assert getAuditReader().find(ManyToOneComponentTestEntity.class, mtocte_id1, 1) == null; - assert getAuditReader().find(ManyToOneComponentTestEntity.class, mtocte_id1, 2).equals(ver2); - assert getAuditReader().find(ManyToOneComponentTestEntity.class, mtocte_id1, 3).equals(ver3); - } + assert getAuditReader().find( ManyToOneComponentTestEntity.class, mtocte_id1, 1 ) == null; + assert getAuditReader().find( ManyToOneComponentTestEntity.class, mtocte_id1, 2 ).equals( ver2 ); + assert getAuditReader().find( ManyToOneComponentTestEntity.class, mtocte_id1, 3 ).equals( ver3 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/relations/NotAuditedManyToOneInComponent.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/relations/NotAuditedManyToOneInComponent.java index 5492ca744b..114cdd9c51 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/relations/NotAuditedManyToOneInComponent.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/relations/NotAuditedManyToOneInComponent.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.components.relations; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -34,80 +32,88 @@ import org.hibernate.envers.test.entities.UnversionedStrTestEntity; import org.hibernate.envers.test.entities.components.relations.NotAuditedManyToOneComponent; import org.hibernate.envers.test.entities.components.relations.NotAuditedManyToOneComponentTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class NotAuditedManyToOneInComponent extends BaseEnversJPAFunctionalTestCase { - private Integer mtocte_id1; + private Integer mtocte_id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { NotAuditedManyToOneComponentTestEntity.class, UnversionedStrTestEntity.class }; - } + return new Class[] {NotAuditedManyToOneComponentTestEntity.class, UnversionedStrTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { + @Test + @Priority(10) + public void initData() { // No revision - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + EntityManager em = getEntityManager(); + em.getTransaction().begin(); UnversionedStrTestEntity ste1 = new UnversionedStrTestEntity(); - ste1.setStr("str1"); + ste1.setStr( "str1" ); UnversionedStrTestEntity ste2 = new UnversionedStrTestEntity(); - ste2.setStr("str2"); + ste2.setStr( "str2" ); - em.persist(ste1); - em.persist(ste2); + em.persist( ste1 ); + em.persist( ste2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 1 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + em = getEntityManager(); + em.getTransaction().begin(); NotAuditedManyToOneComponentTestEntity mtocte1 = new NotAuditedManyToOneComponentTestEntity( - new NotAuditedManyToOneComponent(ste1, "data1")); + new NotAuditedManyToOneComponent( ste1, "data1" ) + ); - em.persist(mtocte1); + em.persist( mtocte1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // No revision - em = getEntityManager(); - em.getTransaction().begin(); + // No revision + em = getEntityManager(); + em.getTransaction().begin(); - mtocte1 = em.find(NotAuditedManyToOneComponentTestEntity.class, mtocte1.getId()); - mtocte1.getComp1().setEntity(ste2); + mtocte1 = em.find( NotAuditedManyToOneComponentTestEntity.class, mtocte1.getId() ); + mtocte1.getComp1().setEntity( ste2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 2 + em = getEntityManager(); + em.getTransaction().begin(); - mtocte1 = em.find(NotAuditedManyToOneComponentTestEntity.class, mtocte1.getId()); - mtocte1.getComp1().setData("data2"); + mtocte1 = em.find( NotAuditedManyToOneComponentTestEntity.class, mtocte1.getId() ); + mtocte1.getComp1().setData( "data2" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - mtocte_id1 = mtocte1.getId(); - } + mtocte_id1 = mtocte1.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(NotAuditedManyToOneComponentTestEntity.class, mtocte_id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ) + .equals( getAuditReader().getRevisions( NotAuditedManyToOneComponentTestEntity.class, mtocte_id1 ) ); + } - @Test - public void testHistoryOfId1() { - NotAuditedManyToOneComponentTestEntity ver1 = new NotAuditedManyToOneComponentTestEntity(mtocte_id1, - new NotAuditedManyToOneComponent(null, "data1")); - NotAuditedManyToOneComponentTestEntity ver2 = new NotAuditedManyToOneComponentTestEntity(mtocte_id1, - new NotAuditedManyToOneComponent(null, "data2")); + @Test + public void testHistoryOfId1() { + NotAuditedManyToOneComponentTestEntity ver1 = new NotAuditedManyToOneComponentTestEntity( + mtocte_id1, + new NotAuditedManyToOneComponent( null, "data1" ) + ); + NotAuditedManyToOneComponentTestEntity ver2 = new NotAuditedManyToOneComponentTestEntity( + mtocte_id1, + new NotAuditedManyToOneComponent( null, "data2" ) + ); - assert getAuditReader().find(NotAuditedManyToOneComponentTestEntity.class, mtocte_id1, 1).equals(ver1); - assert getAuditReader().find(NotAuditedManyToOneComponentTestEntity.class, mtocte_id1, 2).equals(ver2); - } + assert getAuditReader().find( NotAuditedManyToOneComponentTestEntity.class, mtocte_id1, 1 ).equals( ver1 ); + assert getAuditReader().find( NotAuditedManyToOneComponentTestEntity.class, mtocte_id1, 2 ).equals( ver2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/relations/OneToManyInComponent.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/relations/OneToManyInComponent.java index 480c1a277f..d2076681e6 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/relations/OneToManyInComponent.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/components/relations/OneToManyInComponent.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.components.relations; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -34,80 +32,95 @@ import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.components.relations.OneToManyComponent; import org.hibernate.envers.test.entities.components.relations.OneToManyComponentTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ -public class OneToManyInComponent extends BaseEnversJPAFunctionalTestCase { - private Integer otmcte_id1; +public class OneToManyInComponent extends BaseEnversJPAFunctionalTestCase { + private Integer otmcte_id1; private Integer ste_id1; private Integer ste_id2; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { OneToManyComponentTestEntity.class, StrTestEntity.class }; - } + return new Class[] {OneToManyComponentTestEntity.class, StrTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); StrTestEntity ste1 = new StrTestEntity(); - ste1.setStr("str1"); + ste1.setStr( "str1" ); StrTestEntity ste2 = new StrTestEntity(); - ste2.setStr("str2"); + ste2.setStr( "str2" ); - em.persist(ste1); - em.persist(ste2); + em.persist( ste1 ); + em.persist( ste2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 2 + em = getEntityManager(); + em.getTransaction().begin(); - OneToManyComponentTestEntity otmcte1 = new OneToManyComponentTestEntity(new OneToManyComponent("data1")); - otmcte1.getComp1().getEntities().add(ste1); + OneToManyComponentTestEntity otmcte1 = new OneToManyComponentTestEntity( new OneToManyComponent( "data1" ) ); + otmcte1.getComp1().getEntities().add( ste1 ); - em.persist(otmcte1); + em.persist( otmcte1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 3 + em = getEntityManager(); + em.getTransaction().begin(); - otmcte1 = em.find(OneToManyComponentTestEntity.class, otmcte1.getId()); - otmcte1.getComp1().getEntities().add(ste2); + otmcte1 = em.find( OneToManyComponentTestEntity.class, otmcte1.getId() ); + otmcte1.getComp1().getEntities().add( ste2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - otmcte_id1 = otmcte1.getId(); + otmcte_id1 = otmcte1.getId(); ste_id1 = ste1.getId(); ste_id2 = ste2.getId(); - } + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(2, 3).equals(getAuditReader().getRevisions(OneToManyComponentTestEntity.class, otmcte_id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 2, 3 ).equals( + getAuditReader().getRevisions( + OneToManyComponentTestEntity.class, + otmcte_id1 + ) + ); + } - @Test - public void testHistoryOfId1() { - StrTestEntity ste1 = getEntityManager().find(StrTestEntity.class, ste_id1); - StrTestEntity ste2 = getEntityManager().find(StrTestEntity.class, ste_id2); + @Test + public void testHistoryOfId1() { + StrTestEntity ste1 = getEntityManager().find( StrTestEntity.class, ste_id1 ); + StrTestEntity ste2 = getEntityManager().find( StrTestEntity.class, ste_id2 ); - OneToManyComponentTestEntity ver2 = new OneToManyComponentTestEntity(otmcte_id1, new OneToManyComponent("data1")); - ver2.getComp1().getEntities().add(ste1); - OneToManyComponentTestEntity ver3 = new OneToManyComponentTestEntity(otmcte_id1, new OneToManyComponent("data1")); - ver3.getComp1().getEntities().add(ste1); - ver3.getComp1().getEntities().add(ste2); + OneToManyComponentTestEntity ver2 = new OneToManyComponentTestEntity( + otmcte_id1, new OneToManyComponent( + "data1" + ) + ); + ver2.getComp1().getEntities().add( ste1 ); + OneToManyComponentTestEntity ver3 = new OneToManyComponentTestEntity( + otmcte_id1, new OneToManyComponent( + "data1" + ) + ); + ver3.getComp1().getEntities().add( ste1 ); + ver3.getComp1().getEntities().add( ste2 ); - assert getAuditReader().find(OneToManyComponentTestEntity.class, otmcte_id1, 1) == null; - assert getAuditReader().find(OneToManyComponentTestEntity.class, otmcte_id1, 2).equals(ver2); - assert getAuditReader().find(OneToManyComponentTestEntity.class, otmcte_id1, 3).equals(ver3); - } + assert getAuditReader().find( OneToManyComponentTestEntity.class, otmcte_id1, 1 ) == null; + assert getAuditReader().find( OneToManyComponentTestEntity.class, otmcte_id1, 2 ).equals( ver2 ); + assert getAuditReader().find( OneToManyComponentTestEntity.class, otmcte_id1, 3 ).equals( ver3 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/CompositeCustom.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/CompositeCustom.java index bca9b9f543..d0288c22bc 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/CompositeCustom.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/CompositeCustom.java @@ -23,79 +23,84 @@ */ package org.hibernate.envers.test.integration.customtype; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.customtype.Component; import org.hibernate.envers.test.entities.customtype.CompositeCustomTypeEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class CompositeCustom extends BaseEnversJPAFunctionalTestCase { - private Integer ccte_id; + private Integer ccte_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { CompositeCustomTypeEntity.class }; - } + return new Class[] {CompositeCustomTypeEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - CompositeCustomTypeEntity ccte = new CompositeCustomTypeEntity(); + CompositeCustomTypeEntity ccte = new CompositeCustomTypeEntity(); - // Revision 1 (persisting 1 entity) - em.getTransaction().begin(); + // Revision 1 (persisting 1 entity) + em.getTransaction().begin(); - ccte.setComponent(new Component("a", 1)); + ccte.setComponent( new Component( "a", 1 ) ); - em.persist(ccte); + em.persist( ccte ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (changing the component) - em.getTransaction().begin(); + // Revision 2 (changing the component) + em.getTransaction().begin(); - ccte = em.find(CompositeCustomTypeEntity.class, ccte.getId()); + ccte = em.find( CompositeCustomTypeEntity.class, ccte.getId() ); - ccte.getComponent().setProp1("b"); + ccte.getComponent().setProp1( "b" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 (replacing the component) - em.getTransaction().begin(); + // Revision 3 (replacing the component) + em.getTransaction().begin(); - ccte = em.find(CompositeCustomTypeEntity.class, ccte.getId()); + ccte = em.find( CompositeCustomTypeEntity.class, ccte.getId() ); - ccte.setComponent(new Component("c", 3)); + ccte.setComponent( new Component( "c", 3 ) ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ccte_id = ccte.getId(); - } + ccte_id = ccte.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(CompositeCustomTypeEntity.class, ccte_id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( + getAuditReader().getRevisions( + CompositeCustomTypeEntity.class, + ccte_id + ) + ); + } - @Test - public void testHistoryOfCcte() { - CompositeCustomTypeEntity rev1 = getAuditReader().find(CompositeCustomTypeEntity.class, ccte_id, 1); - CompositeCustomTypeEntity rev2 = getAuditReader().find(CompositeCustomTypeEntity.class, ccte_id, 2); - CompositeCustomTypeEntity rev3 = getAuditReader().find(CompositeCustomTypeEntity.class, ccte_id, 3); + @Test + public void testHistoryOfCcte() { + CompositeCustomTypeEntity rev1 = getAuditReader().find( CompositeCustomTypeEntity.class, ccte_id, 1 ); + CompositeCustomTypeEntity rev2 = getAuditReader().find( CompositeCustomTypeEntity.class, ccte_id, 2 ); + CompositeCustomTypeEntity rev3 = getAuditReader().find( CompositeCustomTypeEntity.class, ccte_id, 3 ); - assert rev1.getComponent().equals(new Component("a", 1)); - assert rev2.getComponent().equals(new Component("b", 1)); - assert rev3.getComponent().equals(new Component("c", 3)); - } + assert rev1.getComponent().equals( new Component( "a", 1 ) ); + assert rev2.getComponent().equals( new Component( "b", 1 ) ); + assert rev3.getComponent().equals( new Component( "c", 3 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/EnumTypeTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/EnumTypeTest.java index df82aec2bf..c4f6bd3e0b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/EnumTypeTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/EnumTypeTest.java @@ -1,24 +1,25 @@ package org.hibernate.envers.test.integration.customtype; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; +import java.util.List; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.customtype.EnumTypeEntity; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ -@TestForIssue( jiraKey = "HHH-7780" ) +@TestForIssue(jiraKey = "HHH-7780") public class EnumTypeTest extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { EnumTypeEntity.class }; + return new Class[] {EnumTypeEntity.class}; } @Test @@ -37,7 +38,9 @@ public class EnumTypeTest extends BaseEnversJPAFunctionalTestCase { @Test public void testEnumRepresentation() { EntityManager entityManager = getEntityManager(); - List values = entityManager.createNativeQuery( "SELECT enum1, enum2 FROM EnumTypeEntity_AUD ORDER BY rev ASC" ).getResultList(); + List values = entityManager.createNativeQuery( + "SELECT enum1, enum2 FROM EnumTypeEntity_AUD ORDER BY rev ASC" + ).getResultList(); entityManager.close(); Assert.assertNotNull( values ); diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/ObjectUserType.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/ObjectUserType.java index b848d8960a..44f9dedf74 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/ObjectUserType.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/ObjectUserType.java @@ -21,10 +21,11 @@ import org.hibernate.usertype.UserType; * Custom type used to persist binary representation of Java object in the database. * Spans over two columns - one storing text representation of Java class name and the second one * containing binary data. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class ObjectUserType implements UserType { - private static final int[] TYPES = new int[] { Types.VARCHAR, Types.BLOB }; + private static final int[] TYPES = new int[] {Types.VARCHAR, Types.BLOB}; @Override public int[] sqlTypes() { @@ -38,8 +39,12 @@ public class ObjectUserType implements UserType { @Override public boolean equals(Object x, Object y) throws HibernateException { - if ( x == y ) return true; - if ( x == null || y == null ) return false; + if ( x == y ) { + return true; + } + if ( x == null || y == null ) { + return false; + } return x.equals( y ); } @@ -77,7 +82,7 @@ public class ObjectUserType implements UserType { objectOutputStream.flush(); return new ByteArrayInputStream( byteArrayOutputStream.toByteArray() ); } - catch ( IOException e ) { + catch (IOException e) { throw new RuntimeException( e ); } finally { @@ -91,7 +96,7 @@ public class ObjectUserType implements UserType { objectInputStream = new ObjectInputStream( inputStream ); return objectInputStream.readObject(); } - catch ( Exception e ) { + catch (Exception e) { throw new RuntimeException( e ); } finally { @@ -104,7 +109,7 @@ public class ObjectUserType implements UserType { try { stream.close(); } - catch ( IOException e ) { + catch (IOException e) { } } } @@ -114,7 +119,7 @@ public class ObjectUserType implements UserType { try { stream.close(); } - catch ( IOException e ) { + catch (IOException e) { } } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/ObjectUserTypeEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/ObjectUserTypeEntity.java index f1f39e4eb2..d4aa73a798 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/ObjectUserTypeEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/ObjectUserTypeEntity.java @@ -1,10 +1,10 @@ package org.hibernate.envers.test.integration.customtype; -import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import java.io.Serializable; import org.hibernate.annotations.Columns; import org.hibernate.annotations.Type; @@ -12,6 +12,7 @@ import org.hibernate.envers.Audited; /** * Entity encapsulating {@link Object} property which concrete type may change during subsequent updates. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @Entity @@ -24,7 +25,7 @@ public class ObjectUserTypeEntity implements Serializable { private String buildInType; @Type(type = "org.hibernate.envers.test.integration.customtype.ObjectUserType") - @Columns(columns = { @Column(name = "OBJ_TYPE"), @Column(name = "OBJ_VALUE") }) + @Columns(columns = {@Column(name = "OBJ_TYPE"), @Column(name = "OBJ_VALUE")}) private Object userType; public ObjectUserTypeEntity() { @@ -43,14 +44,24 @@ public class ObjectUserTypeEntity implements Serializable { @Override public boolean equals(Object o) { - if ( this == o ) return true; - if ( ! ( o instanceof ObjectUserTypeEntity ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof ObjectUserTypeEntity) ) { + return false; + } ObjectUserTypeEntity that = (ObjectUserTypeEntity) o; - if ( id != that.id ) return false; - if ( buildInType != null ? !buildInType.equals( that.buildInType ) : that.buildInType != null ) return false; - if ( userType != null ? !userType.equals( that.userType ) : that.userType != null ) return false; + if ( id != that.id ) { + return false; + } + if ( buildInType != null ? !buildInType.equals( that.buildInType ) : that.buildInType != null ) { + return false; + } + if ( userType != null ? !userType.equals( that.userType ) : that.userType != null ) { + return false; + } return true; } @@ -58,8 +69,8 @@ public class ObjectUserTypeEntity implements Serializable { @Override public int hashCode() { int result = id; - result = 31 * result + ( buildInType != null ? buildInType.hashCode() : 0 ); - result = 31 * result + ( userType != null ? userType.hashCode() : 0 ); + result = 31 * result + (buildInType != null ? buildInType.hashCode() : 0); + result = 31 * result + (userType != null ? userType.hashCode() : 0); return result; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/ObjectUserTypeTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/ObjectUserTypeTest.java index f6d7a87613..28c5782fb0 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/ObjectUserTypeTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/ObjectUserTypeTest.java @@ -1,16 +1,17 @@ package org.hibernate.envers.test.integration.customtype; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Map; -import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; import org.hibernate.dialect.Oracle8iDialect; import org.hibernate.envers.configuration.EnversSettings; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.TestForIssue; @@ -24,7 +25,7 @@ public class ObjectUserTypeTest extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ObjectUserTypeEntity.class }; + return new Class[] {ObjectUserTypeEntity.class}; } @Override @@ -79,7 +80,10 @@ public class ObjectUserTypeTest extends BaseEnversJPAFunctionalTestCase { Assert.assertEquals( ver2, getAuditReader().find( ObjectUserTypeEntity.class, id, 2 ) ); Assert.assertEquals( ver2, - getAuditReader().createQuery().forRevisionsOfEntity( ObjectUserTypeEntity.class, true, true ).getResultList().get( 2 ) + getAuditReader().createQuery() + .forRevisionsOfEntity( ObjectUserTypeEntity.class, true, true ) + .getResultList() + .get( 2 ) ); // Checking delete state. } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/ParametrizedCustom.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/ParametrizedCustom.java index 7426d5447e..0074192cfd 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/ParametrizedCustom.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/ParametrizedCustom.java @@ -23,67 +23,72 @@ */ package org.hibernate.envers.test.integration.customtype; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.customtype.ParametrizedCustomTypeEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class ParametrizedCustom extends BaseEnversJPAFunctionalTestCase { - private Integer pcte_id; + private Integer pcte_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ParametrizedCustomTypeEntity.class }; - } + return new Class[] {ParametrizedCustomTypeEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - ParametrizedCustomTypeEntity pcte = new ParametrizedCustomTypeEntity(); + ParametrizedCustomTypeEntity pcte = new ParametrizedCustomTypeEntity(); - // Revision 1 (persisting 1 entity) - em.getTransaction().begin(); + // Revision 1 (persisting 1 entity) + em.getTransaction().begin(); - pcte.setStr("U"); + pcte.setStr( "U" ); - em.persist(pcte); + em.persist( pcte ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (changing the value) - em.getTransaction().begin(); + // Revision 2 (changing the value) + em.getTransaction().begin(); - pcte = em.find(ParametrizedCustomTypeEntity.class, pcte.getId()); + pcte = em.find( ParametrizedCustomTypeEntity.class, pcte.getId() ); - pcte.setStr("V"); + pcte.setStr( "V" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - pcte_id = pcte.getId(); - } + pcte_id = pcte.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(ParametrizedCustomTypeEntity.class, pcte_id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( + ParametrizedCustomTypeEntity.class, + pcte_id + ) + ); + } - @Test - public void testHistoryOfCcte() { - ParametrizedCustomTypeEntity rev1 = getAuditReader().find(ParametrizedCustomTypeEntity.class, pcte_id, 1); - ParametrizedCustomTypeEntity rev2 = getAuditReader().find(ParametrizedCustomTypeEntity.class, pcte_id, 2); + @Test + public void testHistoryOfCcte() { + ParametrizedCustomTypeEntity rev1 = getAuditReader().find( ParametrizedCustomTypeEntity.class, pcte_id, 1 ); + ParametrizedCustomTypeEntity rev2 = getAuditReader().find( ParametrizedCustomTypeEntity.class, pcte_id, 2 ); - assert "xUy".equals(rev1.getStr()); - assert "xVy".equals(rev2.getStr()); - } + assert "xUy".equals( rev1.getStr() ); + assert "xVy".equals( rev2.getStr() ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/UnspecifiedEnumTypeTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/UnspecifiedEnumTypeTest.java index f370967626..97cc813613 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/UnspecifiedEnumTypeTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/customtype/UnspecifiedEnumTypeTest.java @@ -3,9 +3,6 @@ package org.hibernate.envers.test.integration.customtype; import java.util.Arrays; import java.util.List; -import org.junit.Assert; -import org.junit.Test; - import org.hibernate.Session; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; @@ -13,20 +10,24 @@ import org.hibernate.dialect.H2Dialect; import org.hibernate.envers.test.BaseEnversFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.customtype.UnspecifiedEnumTypeEntity; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.TestForIssue; /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ -@TestForIssue( jiraKey = "HHH-7780" ) -@RequiresDialect( value = H2Dialect.class ) +@TestForIssue(jiraKey = "HHH-7780") +@RequiresDialect(value = H2Dialect.class) public class UnspecifiedEnumTypeTest extends BaseEnversFunctionalTestCase { private Long id = null; @Override protected String[] getMappings() { - return new String[] { "mappings/customType/mappings.hbm.xml" }; + return new String[] {"mappings/customType/mappings.hbm.xml"}; } @Override @@ -82,7 +83,7 @@ public class UnspecifiedEnumTypeTest extends BaseEnversFunctionalTestCase { try { session.createSQLQuery( query ).executeUpdate(); } - catch ( Exception e ) { + catch (Exception e) { } } @@ -93,7 +94,10 @@ public class UnspecifiedEnumTypeTest extends BaseEnversFunctionalTestCase { // Revision 1 session.getTransaction().begin(); - UnspecifiedEnumTypeEntity entity = new UnspecifiedEnumTypeEntity( UnspecifiedEnumTypeEntity.E1.X, UnspecifiedEnumTypeEntity.E2.A ); + UnspecifiedEnumTypeEntity entity = new UnspecifiedEnumTypeEntity( + UnspecifiedEnumTypeEntity.E1.X, + UnspecifiedEnumTypeEntity.E2.A + ); session.persist( entity ); session.getTransaction().commit(); @@ -113,29 +117,43 @@ public class UnspecifiedEnumTypeTest extends BaseEnversFunctionalTestCase { @Test @Priority(8) public void testRevisionCount() { - Assert.assertEquals( Arrays.asList( 1, 2 ), getAuditReader().getRevisions( UnspecifiedEnumTypeEntity.class, id ) ); + Assert.assertEquals( + Arrays.asList( 1, 2 ), getAuditReader().getRevisions( + UnspecifiedEnumTypeEntity.class, + id + ) + ); } @Test @Priority(7) public void testHistoryOfEnums() { - UnspecifiedEnumTypeEntity ver1 = new UnspecifiedEnumTypeEntity( UnspecifiedEnumTypeEntity.E1.X, UnspecifiedEnumTypeEntity.E2.A, id ); - UnspecifiedEnumTypeEntity ver2 = new UnspecifiedEnumTypeEntity( UnspecifiedEnumTypeEntity.E1.Y, UnspecifiedEnumTypeEntity.E2.B, id ); + UnspecifiedEnumTypeEntity ver1 = new UnspecifiedEnumTypeEntity( + UnspecifiedEnumTypeEntity.E1.X, + UnspecifiedEnumTypeEntity.E2.A, + id + ); + UnspecifiedEnumTypeEntity ver2 = new UnspecifiedEnumTypeEntity( + UnspecifiedEnumTypeEntity.E1.Y, + UnspecifiedEnumTypeEntity.E2.B, + id + ); - Assert.assertEquals( ver1, getAuditReader().find(UnspecifiedEnumTypeEntity.class, id, 1) ); - Assert.assertEquals( ver2, getAuditReader().find(UnspecifiedEnumTypeEntity.class, id, 2) ); + Assert.assertEquals( ver1, getAuditReader().find( UnspecifiedEnumTypeEntity.class, id, 1 ) ); + Assert.assertEquals( ver2, getAuditReader().find( UnspecifiedEnumTypeEntity.class, id, 2 ) ); } @Test @Priority(6) public void testEnumRepresentation() { Session session = getSession(); - List values = session.createSQLQuery( "SELECT enum1, enum2 FROM enum_entity_aud ORDER BY rev ASC" ).list(); + List values = session.createSQLQuery( "SELECT enum1, enum2 FROM enum_entity_aud ORDER BY rev ASC" ) + .list(); session.close(); Assert.assertNotNull( values ); Assert.assertEquals( 2, values.size() ); - Assert.assertArrayEquals( new Object[] { "X", 0 }, values.get( 0 ) ); - Assert.assertArrayEquals( new Object[] { "Y", 1 }, values.get( 1 ) ); + Assert.assertArrayEquals( new Object[] {"X", 0}, values.get( 0 ) ); + Assert.assertArrayEquals( new Object[] {"Y", 1}, values.get( 1 ) ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/DateTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/DateTestEntity.java index 0ff1f570c8..325c090a38 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/DateTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/DateTestEntity.java @@ -22,10 +22,11 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.data; -import java.util.Date; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import java.util.Date; import org.hibernate.envers.Audited; @@ -34,66 +35,72 @@ import org.hibernate.envers.Audited; */ @Entity public class DateTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - private Date dateValue; + @Audited + private Date dateValue; - public DateTestEntity() { - } + public DateTestEntity() { + } - public DateTestEntity(Date dateValue) { - this.dateValue = dateValue; - } + public DateTestEntity(Date dateValue) { + this.dateValue = dateValue; + } - public DateTestEntity(Integer id, Date date) { - this.id = id; - this.dateValue = date; - } + public DateTestEntity(Integer id, Date date) { + this.id = id; + this.dateValue = date; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Date getDateValue() { - return dateValue; - } + public Date getDateValue() { + return dateValue; + } - public void setDateValue(Date dateValue) { - this.dateValue = dateValue; - } + public void setDateValue(Date dateValue) { + this.dateValue = dateValue; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof DateTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof DateTestEntity) ) { + return false; + } - DateTestEntity that = (DateTestEntity) o; + DateTestEntity that = (DateTestEntity) o; - if (dateValue != null) { - if (that.dateValue == null) { - return false; - } + if ( dateValue != null ) { + if ( that.dateValue == null ) { + return false; + } - if (dateValue.getTime() != that.dateValue.getTime()) { - return false; - } - } - - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( dateValue.getTime() != that.dateValue.getTime() ) { + return false; + } + } - return true; - } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (dateValue != null ? dateValue.hashCode() : 0); - return result; - } + return true; + } + + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (dateValue != null ? dateValue.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/Dates.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/Dates.java index 8820dbfdae..cb1580d6b2 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/Dates.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/Dates.java @@ -23,54 +23,54 @@ */ package org.hibernate.envers.test.integration.data; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Date; -import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Assert; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class Dates extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { DateTestEntity.class }; - } + return new Class[] {DateTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - DateTestEntity dte = new DateTestEntity(new Date(12345000)); - em.persist(dte); - id1 = dte.getId(); - em.getTransaction().commit(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + DateTestEntity dte = new DateTestEntity( new Date( 12345000 ) ); + em.persist( dte ); + id1 = dte.getId(); + em.getTransaction().commit(); - em.getTransaction().begin(); - dte = em.find(DateTestEntity.class, id1); - dte.setDateValue(new Date(45678000)); - em.getTransaction().commit(); - } + em.getTransaction().begin(); + dte = em.find( DateTestEntity.class, id1 ); + dte.setDateValue( new Date( 45678000 ) ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(DateTestEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( DateTestEntity.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - DateTestEntity ver1 = new DateTestEntity(id1, new Date(12345000)); - DateTestEntity ver2 = new DateTestEntity(id1, new Date(45678000)); + @Test + public void testHistoryOfId1() { + DateTestEntity ver1 = new DateTestEntity( id1, new Date( 12345000 ) ); + DateTestEntity ver2 = new DateTestEntity( id1, new Date( 45678000 ) ); - Assert.assertEquals(ver1, getAuditReader().find(DateTestEntity.class, id1, 1)); - Assert.assertEquals(ver2, getAuditReader().find(DateTestEntity.class, id1, 2)); - } + Assert.assertEquals( ver1, getAuditReader().find( DateTestEntity.class, id1, 1 ) ); + Assert.assertEquals( ver2, getAuditReader().find( DateTestEntity.class, id1, 2 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/EnumTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/EnumTestEntity.java index 19821bd7e9..8ac80cf36a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/EnumTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/EnumTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.data; + import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; @@ -36,75 +37,86 @@ import org.hibernate.envers.Audited; @Entity @Audited public class EnumTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - public enum E1 { X, Y } - public enum E2 { A, B } + public enum E1 {X, Y} - @Enumerated(EnumType.STRING) - private E1 enum1; + public enum E2 {A, B} - @Enumerated(EnumType.ORDINAL) - private E2 enum2; + @Enumerated(EnumType.STRING) + private E1 enum1; - public EnumTestEntity() { - } + @Enumerated(EnumType.ORDINAL) + private E2 enum2; - public EnumTestEntity(E1 enum1, E2 enum2) { - this.enum1 = enum1; - this.enum2 = enum2; - } + public EnumTestEntity() { + } - public EnumTestEntity(Integer id, E1 enum1, E2 enum2) { - this.id = id; - this.enum1 = enum1; - this.enum2 = enum2; - } + public EnumTestEntity(E1 enum1, E2 enum2) { + this.enum1 = enum1; + this.enum2 = enum2; + } - public Integer getId() { - return id; - } + public EnumTestEntity(Integer id, E1 enum1, E2 enum2) { + this.id = id; + this.enum1 = enum1; + this.enum2 = enum2; + } - public void setId(Integer id) { - this.id = id; - } + public Integer getId() { + return id; + } - public E1 getEnum1() { - return enum1; - } + public void setId(Integer id) { + this.id = id; + } - public void setEnum1(E1 enum1) { - this.enum1 = enum1; - } + public E1 getEnum1() { + return enum1; + } - public E2 getEnum2() { - return enum2; - } + public void setEnum1(E1 enum1) { + this.enum1 = enum1; + } - public void setEnum2(E2 enum2) { - this.enum2 = enum2; - } + public E2 getEnum2() { + return enum2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof EnumTestEntity)) return false; + public void setEnum2(E2 enum2) { + this.enum2 = enum2; + } - EnumTestEntity that = (EnumTestEntity) o; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof EnumTestEntity) ) { + return false; + } - if (enum1 != that.enum1) return false; - if (enum2 != that.enum2) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + EnumTestEntity that = (EnumTestEntity) o; - return true; - } + if ( enum1 != that.enum1 ) { + return false; + } + if ( enum2 != that.enum2 ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (enum1 != null ? enum1.hashCode() : 0); - result = 31 * result + (enum2 != null ? enum2.hashCode() : 0); - return result; - } + return true; + } + + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (enum1 != null ? enum1.hashCode() : 0); + result = 31 * result + (enum2 != null ? enum2.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/Enums.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/Enums.java index bc4d7b37b2..ba693f818e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/Enums.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/Enums.java @@ -23,53 +23,53 @@ */ package org.hibernate.envers.test.integration.data; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class Enums extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { EnumTestEntity.class }; - } + return new Class[] {EnumTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - EnumTestEntity ete = new EnumTestEntity(EnumTestEntity.E1.X, EnumTestEntity.E2.A); - em.persist(ete); - id1 = ete.getId(); - em.getTransaction().commit(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + EnumTestEntity ete = new EnumTestEntity( EnumTestEntity.E1.X, EnumTestEntity.E2.A ); + em.persist( ete ); + id1 = ete.getId(); + em.getTransaction().commit(); - em.getTransaction().begin(); - ete = em.find(EnumTestEntity.class, id1); - ete.setEnum1(EnumTestEntity.E1.Y); - ete.setEnum2(EnumTestEntity.E2.B); - em.getTransaction().commit(); - } + em.getTransaction().begin(); + ete = em.find( EnumTestEntity.class, id1 ); + ete.setEnum1( EnumTestEntity.E1.Y ); + ete.setEnum2( EnumTestEntity.E2.B ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(EnumTestEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( EnumTestEntity.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - EnumTestEntity ver1 = new EnumTestEntity(id1, EnumTestEntity.E1.X, EnumTestEntity.E2.A); - EnumTestEntity ver2 = new EnumTestEntity(id1, EnumTestEntity.E1.Y, EnumTestEntity.E2.B); + @Test + public void testHistoryOfId1() { + EnumTestEntity ver1 = new EnumTestEntity( id1, EnumTestEntity.E1.X, EnumTestEntity.E2.A ); + EnumTestEntity ver2 = new EnumTestEntity( id1, EnumTestEntity.E1.Y, EnumTestEntity.E2.B ); - assert getAuditReader().find(EnumTestEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(EnumTestEntity.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( EnumTestEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( EnumTestEntity.class, id1, 2 ).equals( ver2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/LobSerializableTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/LobSerializableTestEntity.java index 6e16554ecb..09082ae17c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/LobSerializableTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/LobSerializableTestEntity.java @@ -35,58 +35,66 @@ import org.hibernate.envers.Audited; */ @Entity public class LobSerializableTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - @Lob - private SerObject obj; + @Audited + @Lob + private SerObject obj; - public LobSerializableTestEntity() { - } + public LobSerializableTestEntity() { + } - public LobSerializableTestEntity(SerObject obj) { - this.obj = obj; - } + public LobSerializableTestEntity(SerObject obj) { + this.obj = obj; + } - public LobSerializableTestEntity(Integer id, SerObject obj) { - this.obj = obj; - this.id = id; - } + public LobSerializableTestEntity(Integer id, SerObject obj) { + this.obj = obj; + this.id = id; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public SerObject getObj() { - return obj; - } + public SerObject getObj() { + return obj; + } - public void setObj(SerObject obj) { - this.obj = obj; - } + public void setObj(SerObject obj) { + this.obj = obj; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof LobSerializableTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof LobSerializableTestEntity) ) { + return false; + } - LobSerializableTestEntity that = (LobSerializableTestEntity) o; + LobSerializableTestEntity that = (LobSerializableTestEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (obj != null ? !obj.equals(that.obj) : that.obj != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( obj != null ? !obj.equals( that.obj ) : that.obj != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (obj != null ? obj.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (obj != null ? obj.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/LobSerializables.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/LobSerializables.java index 07402f1fcd..0f9970d70e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/LobSerializables.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/LobSerializables.java @@ -23,14 +23,15 @@ */ package org.hibernate.envers.test.integration.data; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Map; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.dialect.PostgreSQL82Dialect; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; + +import org.junit.Test; + import org.hibernate.testing.DialectChecks; import org.hibernate.testing.RequiresDialectFeature; @@ -39,48 +40,48 @@ import org.hibernate.testing.RequiresDialectFeature; */ @RequiresDialectFeature(DialectChecks.SupportsExpectedLobUsagePattern.class) public class LobSerializables extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { LobSerializableTestEntity.class }; - } + return new Class[] {LobSerializableTestEntity.class}; + } - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions(options); - if (getDialect() instanceof PostgreSQL82Dialect) { - // In PostgreSQL LOBs cannot be used in auto-commit mode. - options.put("hibernate.connection.autocommit", "false"); - } - } + @Override + protected void addConfigOptions(Map options) { + super.addConfigOptions( options ); + if ( getDialect() instanceof PostgreSQL82Dialect ) { + // In PostgreSQL LOBs cannot be used in auto-commit mode. + options.put( "hibernate.connection.autocommit", "false" ); + } + } - @Test - public void initData() { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - LobSerializableTestEntity ste = new LobSerializableTestEntity(new SerObject("d1")); - em.persist(ste); - id1 = ste.getId(); - em.getTransaction().commit(); + @Test + public void initData() { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + LobSerializableTestEntity ste = new LobSerializableTestEntity( new SerObject( "d1" ) ); + em.persist( ste ); + id1 = ste.getId(); + em.getTransaction().commit(); - em.getTransaction().begin(); - ste = em.find(LobSerializableTestEntity.class, id1); - ste.setObj(new SerObject("d2")); - em.getTransaction().commit(); - } + em.getTransaction().begin(); + ste = em.find( LobSerializableTestEntity.class, id1 ); + ste.setObj( new SerObject( "d2" ) ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(LobSerializableTestEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( LobSerializableTestEntity.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - LobSerializableTestEntity ver1 = new LobSerializableTestEntity(id1, new SerObject("d1")); - LobSerializableTestEntity ver2 = new LobSerializableTestEntity(id1, new SerObject("d2")); + @Test + public void testHistoryOfId1() { + LobSerializableTestEntity ver1 = new LobSerializableTestEntity( id1, new SerObject( "d1" ) ); + LobSerializableTestEntity ver2 = new LobSerializableTestEntity( id1, new SerObject( "d2" ) ); - assert getAuditReader().find(LobSerializableTestEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(LobSerializableTestEntity.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( LobSerializableTestEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( LobSerializableTestEntity.class, id1, 2 ).equals( ver2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/LobTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/LobTestEntity.java index 7adbb48ff2..4fd6c7c30f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/LobTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/LobTestEntity.java @@ -22,11 +22,12 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.data; -import java.util.Arrays; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Lob; +import java.util.Arrays; import org.hibernate.envers.Audited; @@ -35,90 +36,102 @@ import org.hibernate.envers.Audited; */ @Entity public class LobTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Lob - @Audited - private String stringLob; + @Lob + @Audited + private String stringLob; - @Lob - @Audited - private byte[] byteLob; + @Lob + @Audited + private byte[] byteLob; - @Lob - @Audited - private char[] charLob; + @Lob + @Audited + private char[] charLob; - public LobTestEntity() { - } + public LobTestEntity() { + } - public LobTestEntity(String stringLob, byte[] byteLob, char[] charLob) { - this.stringLob = stringLob; - this.byteLob = byteLob; - this.charLob = charLob; - } + public LobTestEntity(String stringLob, byte[] byteLob, char[] charLob) { + this.stringLob = stringLob; + this.byteLob = byteLob; + this.charLob = charLob; + } - public LobTestEntity(Integer id, String stringLob, byte[] byteLob, char[] charLob) { - this.id = id; - this.stringLob = stringLob; - this.byteLob = byteLob; - this.charLob = charLob; - } + public LobTestEntity(Integer id, String stringLob, byte[] byteLob, char[] charLob) { + this.id = id; + this.stringLob = stringLob; + this.byteLob = byteLob; + this.charLob = charLob; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStringLob() { - return stringLob; - } + public String getStringLob() { + return stringLob; + } - public void setStringLob(String stringLob) { - this.stringLob = stringLob; - } + public void setStringLob(String stringLob) { + this.stringLob = stringLob; + } - public byte[] getByteLob() { - return byteLob; - } + public byte[] getByteLob() { + return byteLob; + } - public void setByteLob(byte[] byteLob) { - this.byteLob = byteLob; - } + public void setByteLob(byte[] byteLob) { + this.byteLob = byteLob; + } - public char[] getCharLob() { - return charLob; - } + public char[] getCharLob() { + return charLob; + } - public void setCharLob(char[] charLob) { - this.charLob = charLob; - } + public void setCharLob(char[] charLob) { + this.charLob = charLob; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof LobTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof LobTestEntity) ) { + return false; + } - LobTestEntity that = (LobTestEntity) o; + LobTestEntity that = (LobTestEntity) o; - if (!Arrays.equals(byteLob, that.byteLob)) return false; - if (!Arrays.equals(charLob, that.charLob)) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (stringLob != null ? !stringLob.equals(that.stringLob) : that.stringLob != null) return false; + if ( !Arrays.equals( byteLob, that.byteLob ) ) { + return false; + } + if ( !Arrays.equals( charLob, that.charLob ) ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( stringLob != null ? !stringLob.equals( that.stringLob ) : that.stringLob != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (stringLob != null ? stringLob.hashCode() : 0); - result = 31 * result + (byteLob != null ? Arrays.hashCode(byteLob) : 0); - result = 31 * result + (charLob != null ? Arrays.hashCode(charLob) : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (stringLob != null ? stringLob.hashCode() : 0); + result = 31 * result + (byteLob != null ? Arrays.hashCode( byteLob ) : 0); + result = 31 * result + (charLob != null ? Arrays.hashCode( charLob ) : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/Lobs.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/Lobs.java index 03663d91ed..5c69f77cef 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/Lobs.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/Lobs.java @@ -23,15 +23,16 @@ */ package org.hibernate.envers.test.integration.data; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Map; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.dialect.PostgreSQL82Dialect; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; + +import org.junit.Test; + import org.hibernate.testing.DialectChecks; import org.hibernate.testing.RequiresDialectFeature; @@ -40,51 +41,51 @@ import org.hibernate.testing.RequiresDialectFeature; */ @RequiresDialectFeature(DialectChecks.SupportsExpectedLobUsagePattern.class) public class Lobs extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { LobTestEntity.class }; - } + return new Class[] {LobTestEntity.class}; + } - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions(options); - if (getDialect() instanceof PostgreSQL82Dialect) { - // In PostgreSQL LOBs cannot be used in auto-commit mode. - options.put("hibernate.connection.autocommit", "false"); - } - } + @Override + protected void addConfigOptions(Map options) { + super.addConfigOptions( options ); + if ( getDialect() instanceof PostgreSQL82Dialect ) { + // In PostgreSQL LOBs cannot be used in auto-commit mode. + options.put( "hibernate.connection.autocommit", "false" ); + } + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - LobTestEntity lte = new LobTestEntity("abc", new byte[] { 0, 1, 2 }, new char[] { 'x', 'y', 'z' }); - em.persist(lte); - id1 = lte.getId(); - em.getTransaction().commit(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + LobTestEntity lte = new LobTestEntity( "abc", new byte[] {0, 1, 2}, new char[] {'x', 'y', 'z'} ); + em.persist( lte ); + id1 = lte.getId(); + em.getTransaction().commit(); - em.getTransaction().begin(); - lte = em.find(LobTestEntity.class, id1); - lte.setStringLob("def"); - lte.setByteLob(new byte[] { 3, 4, 5 }); - lte.setCharLob(new char[] { 'h', 'i', 'j' }); - em.getTransaction().commit(); - } + em.getTransaction().begin(); + lte = em.find( LobTestEntity.class, id1 ); + lte.setStringLob( "def" ); + lte.setByteLob( new byte[] {3, 4, 5} ); + lte.setCharLob( new char[] {'h', 'i', 'j'} ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(LobTestEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( LobTestEntity.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - LobTestEntity ver1 = new LobTestEntity(id1, "abc", new byte[] { 0, 1, 2 }, new char[] { 'x', 'y', 'z' }); - LobTestEntity ver2 = new LobTestEntity(id1, "def", new byte[] { 3, 4, 5 }, new char[] { 'h', 'i', 'j' }); + @Test + public void testHistoryOfId1() { + LobTestEntity ver1 = new LobTestEntity( id1, "abc", new byte[] {0, 1, 2}, new char[] {'x', 'y', 'z'} ); + LobTestEntity ver2 = new LobTestEntity( id1, "def", new byte[] {3, 4, 5}, new char[] {'h', 'i', 'j'} ); - assert getAuditReader().find(LobTestEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(LobTestEntity.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( LobTestEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( LobTestEntity.class, id1, 2 ).equals( ver2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/SerObject.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/SerObject.java index 2738e690cf..7cae26bcaa 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/SerObject.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/SerObject.java @@ -22,43 +22,50 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.data; + import java.io.Serializable; /** * @author Adam Warski (adam at warski dot org) */ public class SerObject implements Serializable { - static final long serialVersionUID = 982352321924L; + static final long serialVersionUID = 982352321924L; - private String data; + private String data; - public SerObject() { - } + public SerObject() { + } - public SerObject(String data) { - this.data = data; - } + public SerObject(String data) { + this.data = data; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SerObject)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SerObject) ) { + return false; + } - SerObject serObject = (SerObject) o; + SerObject serObject = (SerObject) o; - if (data != null ? !data.equals(serObject.data) : serObject.data != null) return false; + if ( data != null ? !data.equals( serObject.data ) : serObject.data != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - return (data != null ? data.hashCode() : 0); - } + public int hashCode() { + return (data != null ? data.hashCode() : 0); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/SerializableTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/SerializableTestEntity.java index e394edf436..7ac19396a9 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/SerializableTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/SerializableTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.data; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -33,57 +34,65 @@ import org.hibernate.envers.Audited; */ @Entity public class SerializableTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - private SerObject obj; + @Audited + private SerObject obj; - public SerializableTestEntity() { - } + public SerializableTestEntity() { + } - public SerializableTestEntity(SerObject obj) { - this.obj = obj; - } + public SerializableTestEntity(SerObject obj) { + this.obj = obj; + } - public SerializableTestEntity(Integer id, SerObject obj) { - this.obj = obj; - this.id = id; - } + public SerializableTestEntity(Integer id, SerObject obj) { + this.obj = obj; + this.id = id; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public SerObject getObj() { - return obj; - } + public SerObject getObj() { + return obj; + } - public void setObj(SerObject obj) { - this.obj = obj; - } + public void setObj(SerObject obj) { + this.obj = obj; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SerializableTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SerializableTestEntity) ) { + return false; + } - SerializableTestEntity that = (SerializableTestEntity) o; + SerializableTestEntity that = (SerializableTestEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (obj != null ? !obj.equals(that.obj) : that.obj != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( obj != null ? !obj.equals( that.obj ) : that.obj != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (obj != null ? obj.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (obj != null ? obj.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/Serializables.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/Serializables.java index 4f146c7de4..d022ad3cc7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/Serializables.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/data/Serializables.java @@ -23,52 +23,52 @@ */ package org.hibernate.envers.test.integration.data; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class Serializables extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SerializableTestEntity.class }; - } + return new Class[] {SerializableTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - SerializableTestEntity ste = new SerializableTestEntity(new SerObject("d1")); - em.persist(ste); - id1 = ste.getId(); - em.getTransaction().commit(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + SerializableTestEntity ste = new SerializableTestEntity( new SerObject( "d1" ) ); + em.persist( ste ); + id1 = ste.getId(); + em.getTransaction().commit(); - em.getTransaction().begin(); - ste = em.find(SerializableTestEntity.class, id1); - ste.setObj(new SerObject("d2")); - em.getTransaction().commit(); - } + em.getTransaction().begin(); + ste = em.find( SerializableTestEntity.class, id1 ); + ste.setObj( new SerObject( "d2" ) ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(SerializableTestEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( SerializableTestEntity.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - SerializableTestEntity ver1 = new SerializableTestEntity(id1, new SerObject("d1")); - SerializableTestEntity ver2 = new SerializableTestEntity(id1, new SerObject("d2")); + @Test + public void testHistoryOfId1() { + SerializableTestEntity ver1 = new SerializableTestEntity( id1, new SerObject( "d1" ) ); + SerializableTestEntity ver2 = new SerializableTestEntity( id1, new SerObject( "d2" ) ); - assert getAuditReader().find(SerializableTestEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(SerializableTestEntity.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( SerializableTestEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( SerializableTestEntity.class, id1, 2 ).equals( ver2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/auditedEntity/Person.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/auditedEntity/Person.java index 2c4991a990..8ae91e2587 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/auditedEntity/Person.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/auditedEntity/Person.java @@ -1,27 +1,28 @@ package org.hibernate.envers.test.integration.entityNames.auditedEntity; + import org.hibernate.envers.Audited; /** * @author Hernán Chanfreau - * */ @Audited public class Person { - + private long id; - + private String name; - + private int age; - - public Person(){ } - - public Person(String name, int age){ + + public Person() { + } + + public Person(String name, int age) { this.name = name; this.age = age; } - + public long getId() { return id; diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/auditedEntity/ReadEntityWhitEntityNameTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/auditedEntity/ReadEntityWhitEntityNameTest.java index 3803f5438d..7dd5e33c4e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/auditedEntity/ReadEntityWhitEntityNameTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/auditedEntity/ReadEntityWhitEntityNameTest.java @@ -5,134 +5,135 @@ import java.net.URISyntaxException; import java.net.URL; import java.util.List; -import org.junit.Test; - import org.hibernate.MappingException; import org.hibernate.envers.test.AbstractOneSessionTest; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Hernán Chanfreau - * */ -public class ReadEntityWhitEntityNameTest extends AbstractOneSessionTest{ +public class ReadEntityWhitEntityNameTest extends AbstractOneSessionTest { private long id_pers1; private long id_pers2; private long id_pers3; - + private Person person1_1; private Person person1_2; private Person person1_3; - + private Person currentPers1; - + protected void initMappings() throws MappingException, URISyntaxException { - URL url = Thread.currentThread().getContextClassLoader().getResource("mappings/entityNames/auditedEntity/mappings.hbm.xml"); - config.addFile(new File(url.toURI())); + URL url = Thread.currentThread().getContextClassLoader().getResource( + "mappings/entityNames/auditedEntity/mappings.hbm.xml" + ); + config.addFile( new File( url.toURI() ) ); } - - - @Test - @Priority(10) - public void initData() { - - initializeSession(); - Person pers1 = new Person("Hernan", 28); - Person pers2 = new Person("Leandro", 29); - Person pers3 = new Person("Barba", 30); - - //REV 1 - getSession().getTransaction().begin(); - getSession().persist("Personaje",pers1); - id_pers1 = pers1.getId(); - getSession().getTransaction().commit(); - //REV 2 - getSession().getTransaction().begin(); - pers1 = (Person)getSession().get("Personaje", id_pers1); - pers1.setAge(29); - getSession().persist("Personaje",pers1); - getSession().persist("Personaje",pers2); - id_pers2 = pers2.getId(); - getSession().getTransaction().commit(); - - //REV - getSession().getTransaction().begin(); - pers1 = (Person)getSession().get("Personaje", id_pers1); - pers1.setName("Hernan David"); - pers2 = (Person)getSession().get("Personaje", id_pers2); - pers2.setAge(30); - getSession().persist("Personaje",pers1); - getSession().persist("Personaje",pers2); - getSession().persist("Personaje",pers3); - id_pers3 = pers3.getId(); - getSession().getTransaction().commit(); - - getSession().getTransaction().begin(); - currentPers1 = (Person)getSession().get("Personaje", id_pers1); - getSession().getTransaction().commit(); - - } - - - @Test - public void testRetrieveRevisionsWithEntityName() { - List pers1Revs = getAuditReader().getRevisions(Person.class,"Personaje", id_pers1); - List pers2Revs = getAuditReader().getRevisions(Person.class,"Personaje", id_pers2); - List pers3Revs = getAuditReader().getRevisions(Person.class,"Personaje", id_pers3); - - assert(pers1Revs.size() == 3); - assert(pers2Revs.size() == 2); - assert(pers3Revs.size() == 1); - } - - @Test - public void testRetrieveAuditedEntityWithEntityName() { - person1_1 = getAuditReader().find(Person.class, "Personaje", id_pers1, 1); - person1_2 = getAuditReader().find(Person.class, "Personaje", id_pers1, 2); - person1_3 = getAuditReader().find(Person.class, "Personaje", id_pers1, 3); - - assert(person1_1 != null); - assert(person1_2 != null); - assert(person1_3 != null); - - } - - @Test - public void testObtainEntityNameAuditedEntityWithEntityName() { - person1_1 = getAuditReader().find(Person.class, "Personaje", id_pers1, 1); - person1_2 = getAuditReader().find(Person.class, "Personaje", id_pers1, 2); - person1_3 = getAuditReader().find(Person.class, "Personaje", id_pers1, 3); - - String currentPers1EN = getSession().getEntityName(currentPers1); - - String person1EN = getAuditReader().getEntityName(person1_1.getId(), 1, person1_1); - assert (currentPers1EN.equals(person1EN)); + @Test + @Priority(10) + public void initData() { - String person2EN = getAuditReader().getEntityName(person1_2.getId(), 2, person1_2); - assert (currentPers1EN.equals(person2EN)); + initializeSession(); - String person3EN = getAuditReader().getEntityName(person1_3.getId(), 3, person1_3); - assert (currentPers1EN.equals(person3EN)); + Person pers1 = new Person( "Hernan", 28 ); + Person pers2 = new Person( "Leandro", 29 ); + Person pers3 = new Person( "Barba", 30 ); + + //REV 1 + getSession().getTransaction().begin(); + getSession().persist( "Personaje", pers1 ); + id_pers1 = pers1.getId(); + getSession().getTransaction().commit(); + + //REV 2 + getSession().getTransaction().begin(); + pers1 = (Person) getSession().get( "Personaje", id_pers1 ); + pers1.setAge( 29 ); + getSession().persist( "Personaje", pers1 ); + getSession().persist( "Personaje", pers2 ); + id_pers2 = pers2.getId(); + getSession().getTransaction().commit(); + + //REV + getSession().getTransaction().begin(); + pers1 = (Person) getSession().get( "Personaje", id_pers1 ); + pers1.setName( "Hernan David" ); + pers2 = (Person) getSession().get( "Personaje", id_pers2 ); + pers2.setAge( 30 ); + getSession().persist( "Personaje", pers1 ); + getSession().persist( "Personaje", pers2 ); + getSession().persist( "Personaje", pers3 ); + id_pers3 = pers3.getId(); + getSession().getTransaction().commit(); + + getSession().getTransaction().begin(); + currentPers1 = (Person) getSession().get( "Personaje", id_pers1 ); + getSession().getTransaction().commit(); + + } + + + @Test + public void testRetrieveRevisionsWithEntityName() { + List pers1Revs = getAuditReader().getRevisions( Person.class, "Personaje", id_pers1 ); + List pers2Revs = getAuditReader().getRevisions( Person.class, "Personaje", id_pers2 ); + List pers3Revs = getAuditReader().getRevisions( Person.class, "Personaje", id_pers3 ); + + assert (pers1Revs.size() == 3); + assert (pers2Revs.size() == 2); + assert (pers3Revs.size() == 1); + } + + @Test + public void testRetrieveAuditedEntityWithEntityName() { + person1_1 = getAuditReader().find( Person.class, "Personaje", id_pers1, 1 ); + person1_2 = getAuditReader().find( Person.class, "Personaje", id_pers1, 2 ); + person1_3 = getAuditReader().find( Person.class, "Personaje", id_pers1, 3 ); + + assert (person1_1 != null); + assert (person1_2 != null); + assert (person1_3 != null); + + } + + @Test + public void testObtainEntityNameAuditedEntityWithEntityName() { + person1_1 = getAuditReader().find( Person.class, "Personaje", id_pers1, 1 ); + person1_2 = getAuditReader().find( Person.class, "Personaje", id_pers1, 2 ); + person1_3 = getAuditReader().find( Person.class, "Personaje", id_pers1, 3 ); + + String currentPers1EN = getSession().getEntityName( currentPers1 ); + + String person1EN = getAuditReader().getEntityName( person1_1.getId(), 1, person1_1 ); + assert (currentPers1EN.equals( person1EN )); + + String person2EN = getAuditReader().getEntityName( person1_2.getId(), 2, person1_2 ); + assert (currentPers1EN.equals( person2EN )); + + String person3EN = getAuditReader().getEntityName( person1_3.getId(), 3, person1_3 ); + assert (currentPers1EN.equals( person3EN )); + + } + + @Test + public void testRetrieveAuditedEntityWithEntityNameWithNewSession() { + + // force a new session and AR + forceNewSession(); + + person1_1 = getAuditReader().find( Person.class, "Personaje", id_pers1, 1 ); + person1_2 = getAuditReader().find( Person.class, "Personaje", id_pers1, 2 ); + person1_3 = getAuditReader().find( Person.class, "Personaje", id_pers1, 3 ); + + assert (person1_1 != null); + assert (person1_2 != null); + assert (person1_3 != null); + } - } - - @Test - public void testRetrieveAuditedEntityWithEntityNameWithNewSession() { - - // force a new session and AR - forceNewSession(); - person1_1 = getAuditReader().find(Person.class, "Personaje", id_pers1, 1); - person1_2 = getAuditReader().find(Person.class, "Personaje", id_pers1, 2); - person1_3 = getAuditReader().find(Person.class, "Personaje", id_pers1, 3); - - assert(person1_1 != null); - assert(person1_2 != null); - assert(person1_3 != null); - } - - } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/manyToManyAudited/Car.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/manyToManyAudited/Car.java index 813cb29786..0767b176c4 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/manyToManyAudited/Car.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/manyToManyAudited/Car.java @@ -1,31 +1,32 @@ package org.hibernate.envers.test.integration.entityNames.manyToManyAudited; + import java.util.List; import org.hibernate.envers.Audited; /** * @author Hernán Chanfreau - * */ @Audited public class Car { - + private long id; - + private int registrationNumber; - + private List owners; - - public Car() { } + + public Car() { + } public Car(int registrationNumber, List owners) { this.registrationNumber = registrationNumber; this.owners = owners; } - + public long getId() { return id; } @@ -40,7 +41,7 @@ public class Car { public void setOwners(List owners) { this.owners = owners; - } + } public int getRegistrationNumber() { return registrationNumber; @@ -51,5 +52,4 @@ public class Car { } - } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/manyToManyAudited/Person.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/manyToManyAudited/Person.java index 59295270f4..6aa6afa3c7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/manyToManyAudited/Person.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/manyToManyAudited/Person.java @@ -1,31 +1,32 @@ package org.hibernate.envers.test.integration.entityNames.manyToManyAudited; + import java.util.List; import org.hibernate.envers.Audited; /** * @author Hernán Chanfreau - * */ @Audited public class Person { - + private long id; - + private String name; - + private int age; - + private List cars; - - public Person(){ } - - public Person(String name, int age){ + + public Person() { + } + + public Person(String name, int age) { this.name = name; this.age = age; } - + public long getId() { return id; diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/manyToManyAudited/ReadEntityWithAuditedManyToManyTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/manyToManyAudited/ReadEntityWithAuditedManyToManyTest.java index b1f9b50d80..d18900cfb4 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/manyToManyAudited/ReadEntityWithAuditedManyToManyTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/manyToManyAudited/ReadEntityWithAuditedManyToManyTest.java @@ -6,126 +6,126 @@ import java.net.URL; import java.util.ArrayList; import java.util.List; -import org.junit.Test; - import org.hibernate.MappingException; import org.hibernate.envers.test.AbstractOneSessionTest; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Hernán Chanfreau - * */ -public class ReadEntityWithAuditedManyToManyTest extends AbstractOneSessionTest{ +public class ReadEntityWithAuditedManyToManyTest extends AbstractOneSessionTest { private long id_car1; private long id_car2; - + private long id_pers1; - + private Person person1; private Car car1; - + private Person person1_1; private Car car1_2; - + protected void initMappings() throws MappingException, URISyntaxException { - URL url = Thread.currentThread().getContextClassLoader().getResource("mappings/entityNames/manyToManyAudited/mappings.hbm.xml"); - config.addFile(new File(url.toURI())); + URL url = Thread.currentThread().getContextClassLoader().getResource( + "mappings/entityNames/manyToManyAudited/mappings.hbm.xml" + ); + config.addFile( new File( url.toURI() ) ); } - - - @Test - @Priority(10) - public void initData() { - - initializeSession(); - Person pers1 = new Person("Hernan", 28); - Person pers2 = new Person("Leandro", 29); - Person pers3 = new Person("Barba", 32); - Person pers4 = new Person("Camomo", 15); - //REV 1 - getSession().getTransaction().begin(); - List owners = new ArrayList(); - owners.add(pers1); - owners.add(pers2); - owners.add(pers3); - Car car1 = new Car(5, owners); + @Test + @Priority(10) + public void initData() { - getSession().persist(car1); - getSession().getTransaction().commit(); - id_pers1 = pers1.getId(); - id_car1 = car1.getId(); + initializeSession(); - owners = new ArrayList(); - owners.add(pers2); - owners.add(pers3); - owners.add(pers4); - Car car2 = new Car(27, owners); - //REV 2 - getSession().getTransaction().begin(); - Person person1 = (Person)getSession().get("Personaje", id_pers1); - person1.setName("Hernan David"); - person1.setAge(40); - getSession().persist(car1); - getSession().persist(car2); - getSession().getTransaction().commit(); - id_car2 = car2.getId(); - } - - private void loadDataOnSessionAndAuditReader() { - - car1_2 = getAuditReader().find(Car.class, id_car1, 2); - Car car2_2 = getAuditReader().find(Car.class, id_car2, 2); + Person pers1 = new Person( "Hernan", 28 ); + Person pers2 = new Person( "Leandro", 29 ); + Person pers3 = new Person( "Barba", 32 ); + Person pers4 = new Person( "Camomo", 15 ); - // navigate through relations to load objects - for (Person owner : car1_2.getOwners()) { - for (Car ownedCar : owner.getCars()) { - ownedCar.getRegistrationNumber(); - } - } - for (Person owner : car2_2.getOwners()) { - for (Car ownedCar : owner.getCars()) { + //REV 1 + getSession().getTransaction().begin(); + List owners = new ArrayList(); + owners.add( pers1 ); + owners.add( pers2 ); + owners.add( pers3 ); + Car car1 = new Car( 5, owners ); + + getSession().persist( car1 ); + getSession().getTransaction().commit(); + id_pers1 = pers1.getId(); + id_car1 = car1.getId(); + + owners = new ArrayList(); + owners.add( pers2 ); + owners.add( pers3 ); + owners.add( pers4 ); + Car car2 = new Car( 27, owners ); + //REV 2 + getSession().getTransaction().begin(); + Person person1 = (Person) getSession().get( "Personaje", id_pers1 ); + person1.setName( "Hernan David" ); + person1.setAge( 40 ); + getSession().persist( car1 ); + getSession().persist( car2 ); + getSession().getTransaction().commit(); + id_car2 = car2.getId(); + } + + private void loadDataOnSessionAndAuditReader() { + + car1_2 = getAuditReader().find( Car.class, id_car1, 2 ); + Car car2_2 = getAuditReader().find( Car.class, id_car2, 2 ); + + // navigate through relations to load objects + for ( Person owner : car1_2.getOwners() ) { + for ( Car ownedCar : owner.getCars() ) { ownedCar.getRegistrationNumber(); } } - - car1 = (Car)getSession().get(Car.class, id_car1); - person1 = (Person)getSession().get("Personaje", id_pers1); - person1_1 = getAuditReader().find(Person.class, "Personaje", id_pers1, 1); - } - + for ( Person owner : car2_2.getOwners() ) { + for ( Car ownedCar : owner.getCars() ) { + ownedCar.getRegistrationNumber(); + } + } + + car1 = (Car) getSession().get( Car.class, id_car1 ); + person1 = (Person) getSession().get( "Personaje", id_pers1 ); + person1_1 = getAuditReader().find( Person.class, "Personaje", id_pers1, 1 ); + } private void checkEntityNames() { - String currPerson1EN = getSession().getEntityName(person1); - String currCar1EN = getSession().getEntityName(car1); - - String person1_1EN = getAuditReader().getEntityName(id_pers1, 1, person1_1); - assert(currPerson1EN.equals(person1_1EN)); - - String car1_2EN = getAuditReader().getEntityName(id_car1, 2, car1_2); - assert(currCar1EN.equals(car1_2EN)); + String currPerson1EN = getSession().getEntityName( person1 ); + String currCar1EN = getSession().getEntityName( car1 ); + + String person1_1EN = getAuditReader().getEntityName( id_pers1, 1, person1_1 ); + assert (currPerson1EN.equals( person1_1EN )); + + String car1_2EN = getAuditReader().getEntityName( id_car1, 2, car1_2 ); + assert (currCar1EN.equals( car1_2EN )); } - - @Test - public void testGetEntityNameManyYoManyWithEntityName() { - - loadDataOnSessionAndAuditReader(); - - checkEntityNames(); - } - - @Test - public void testGetEntityNameManyYoManyWithEntityNameInNewSession() { - //force new session and AR - forceNewSession(); - loadDataOnSessionAndAuditReader(); - - checkEntityNames(); + @Test + public void testGetEntityNameManyYoManyWithEntityName() { - } + loadDataOnSessionAndAuditReader(); + + checkEntityNames(); + } + + + @Test + public void testGetEntityNameManyYoManyWithEntityNameInNewSession() { + //force new session and AR + forceNewSession(); + loadDataOnSessionAndAuditReader(); + + checkEntityNames(); + + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyAudited/Car.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyAudited/Car.java index 5498c1ddbf..fe7a5766f9 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyAudited/Car.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyAudited/Car.java @@ -1,31 +1,32 @@ package org.hibernate.envers.test.integration.entityNames.oneToManyAudited; + import java.util.List; import org.hibernate.envers.Audited; /** * @author Hernán Chanfreau - * */ @Audited public class Car { - + private long id; - + private int number; - + private List owners; - - public Car() { } + + public Car() { + } public Car(int number, List owners) { this.number = number; this.owners = owners; } - + public long getId() { return id; } @@ -40,7 +41,7 @@ public class Car { public void setOwners(List owners) { this.owners = owners; - } + } public int getNumber() { return number; @@ -51,5 +52,4 @@ public class Car { } - } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyAudited/Person.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyAudited/Person.java index b253ebff5a..4e341d2647 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyAudited/Person.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyAudited/Person.java @@ -1,27 +1,28 @@ package org.hibernate.envers.test.integration.entityNames.oneToManyAudited; + import org.hibernate.envers.Audited; /** * @author Hernán Chanfreau - * */ @Audited public class Person { - + private long id; - + private String name; - + private int age; - - public Person(){ } - - public Person(String name, int age){ + + public Person() { + } + + public Person(String name, int age) { this.name = name; this.age = age; } - + public long getId() { return id; diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyAudited/ReadEntityWithAuditedCollectionTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyAudited/ReadEntityWithAuditedCollectionTest.java index 0ac4945258..f65fc0b464 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyAudited/ReadEntityWithAuditedCollectionTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyAudited/ReadEntityWithAuditedCollectionTest.java @@ -6,123 +6,123 @@ import java.net.URL; import java.util.ArrayList; import java.util.List; -import org.junit.Test; - import org.hibernate.MappingException; import org.hibernate.envers.test.AbstractOneSessionTest; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Hernán Chanfreau - * */ -public class ReadEntityWithAuditedCollectionTest extends AbstractOneSessionTest{ +public class ReadEntityWithAuditedCollectionTest extends AbstractOneSessionTest { private long id_car1; private long id_car2; - + private Car currentCar1; private Person currentPerson1; - + private long id_pers1; - + private Car car1_1; - private Person person1_1; - + private Person person1_1; + protected void initMappings() throws MappingException, URISyntaxException { - URL url = Thread.currentThread().getContextClassLoader().getResource("mappings/entityNames/oneToManyAudited/mappings.hbm.xml"); - config.addFile(new File(url.toURI())); + URL url = Thread.currentThread().getContextClassLoader().getResource( + "mappings/entityNames/oneToManyAudited/mappings.hbm.xml" + ); + config.addFile( new File( url.toURI() ) ); } - - @Test - @Priority(10) - public void initData() { - - initializeSession(); - Person pers1 = new Person("Hernan", 28); - Person pers2 = new Person("Leandro", 29); - Person pers4 = new Person("Camomo", 15); + @Test + @Priority(10) + public void initData() { - List owners = new ArrayList(); - owners.add(pers1); - owners.add(pers2); - Car car1 = new Car(5, owners); + initializeSession(); - //REV 1 - getSession().getTransaction().begin(); - getSession().persist(car1); - getSession().getTransaction().commit(); - id_pers1 = pers1.getId(); - id_car1 = car1.getId(); + Person pers1 = new Person( "Hernan", 28 ); + Person pers2 = new Person( "Leandro", 29 ); + Person pers4 = new Person( "Camomo", 15 ); - owners = new ArrayList(); - owners.add(pers2); - owners.add(pers4); - Car car2 = new Car(27, owners); - //REV 2 - getSession().getTransaction().begin(); - Person person1 = (Person)getSession().get("Personaje", id_pers1); - person1.setName("Hernan David"); - person1.setAge(40); - getSession().persist(car1); - getSession().persist(car2); - getSession().getTransaction().commit(); - id_car2 = car2.getId(); + List owners = new ArrayList(); + owners.add( pers1 ); + owners.add( pers2 ); + Car car1 = new Car( 5, owners ); - } - - private void loadDataOnSessionAndAuditReader() { - - currentCar1 = (Car)getSession().get(Car.class, id_car1); - currentPerson1 = (Person)getSession().get("Personaje", id_pers1); - - person1_1 = getAuditReader().find(Person.class,"Personaje", id_pers1, 1); - car1_1 = getAuditReader().find(Car.class, id_car1, 2); - Car car2 = getAuditReader().find(Car.class, id_car2, 2); + //REV 1 + getSession().getTransaction().begin(); + getSession().persist( car1 ); + getSession().getTransaction().commit(); + id_pers1 = pers1.getId(); + id_car1 = car1.getId(); - for (Person owner : car1_1.getOwners()) { - owner.getName(); - owner.getAge(); + owners = new ArrayList(); + owners.add( pers2 ); + owners.add( pers4 ); + Car car2 = new Car( 27, owners ); + //REV 2 + getSession().getTransaction().begin(); + Person person1 = (Person) getSession().get( "Personaje", id_pers1 ); + person1.setName( "Hernan David" ); + person1.setAge( 40 ); + getSession().persist( car1 ); + getSession().persist( car2 ); + getSession().getTransaction().commit(); + id_car2 = car2.getId(); + + } + + private void loadDataOnSessionAndAuditReader() { + + currentCar1 = (Car) getSession().get( Car.class, id_car1 ); + currentPerson1 = (Person) getSession().get( "Personaje", id_pers1 ); + + person1_1 = getAuditReader().find( Person.class, "Personaje", id_pers1, 1 ); + car1_1 = getAuditReader().find( Car.class, id_car1, 2 ); + Car car2 = getAuditReader().find( Car.class, id_car2, 2 ); + + for ( Person owner : car1_1.getOwners() ) { + owner.getName(); + owner.getAge(); } - for (Person owner : car2.getOwners()) { - owner.getName(); - owner.getAge(); + for ( Person owner : car2.getOwners() ) { + owner.getName(); + owner.getAge(); } - } + } private void checkEntityNames() { - String currCar1EN = getSession().getEntityName(currentCar1); - String currPerson1EN = getSession().getEntityName(currentPerson1); - - String car1_1EN = getAuditReader().getEntityName(id_car1, 2, car1_1); - assert(currCar1EN.equals(car1_1EN)); - - String person1_1EN = getAuditReader().getEntityName(id_pers1, 1, person1_1); - assert(currPerson1EN.equals(person1_1EN)); - } - - @Test - public void testObtainEntityNameAuditedCollectionWithEntityName() { - - this.loadDataOnSessionAndAuditReader(); - - checkEntityNames(); - - } + String currCar1EN = getSession().getEntityName( currentCar1 ); + String currPerson1EN = getSession().getEntityName( currentPerson1 ); + + String car1_1EN = getAuditReader().getEntityName( id_car1, 2, car1_1 ); + assert (currCar1EN.equals( car1_1EN )); + + String person1_1EN = getAuditReader().getEntityName( id_pers1, 1, person1_1 ); + assert (currPerson1EN.equals( person1_1EN )); + } + + @Test + public void testObtainEntityNameAuditedCollectionWithEntityName() { + + this.loadDataOnSessionAndAuditReader(); + + checkEntityNames(); + + } - - @Test - public void testObtainEntityNameAuditedCollectionWithEntityNameInNewSession() { - // force a new session and AR - forceNewSession(); - - loadDataOnSessionAndAuditReader(); - - checkEntityNames(); - - } + @Test + public void testObtainEntityNameAuditedCollectionWithEntityNameInNewSession() { + // force a new session and AR + forceNewSession(); + + loadDataOnSessionAndAuditReader(); + + checkEntityNames(); + + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyNotAudited/Car.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyNotAudited/Car.java index ffafbc259c..b8421b7e91 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyNotAudited/Car.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyNotAudited/Car.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.integration.entityNames.oneToManyNotAudited; + import java.util.List; import org.hibernate.envers.Audited; @@ -6,26 +7,26 @@ import org.hibernate.envers.RelationTargetAuditMode; /** * @author Hernán Chanfreau - * */ public class Car { - + private long id; - + private int number; - + private List owners; - - public Car() { } + + public Car() { + } public Car(int number, List owners) { this.number = number; this.owners = owners; } - + public long getId() { return id; } @@ -34,14 +35,14 @@ public class Car { this.id = id; } - @Audited(targetAuditMode=RelationTargetAuditMode.NOT_AUDITED) + @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) public List getOwners() { return owners; } public void setOwners(List owners) { this.owners = owners; - } + } @Audited public int getNumber() { @@ -53,5 +54,4 @@ public class Car { } - } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyNotAudited/Person.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyNotAudited/Person.java index dbd112abd0..f02d4b32fb 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyNotAudited/Person.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyNotAudited/Person.java @@ -3,24 +3,24 @@ package org.hibernate.envers.test.integration.entityNames.oneToManyNotAudited; /** * @author Hernán Chanfreau - * */ public class Person { - + private long id; - + private String name; - + private int age; - - public Person(){ } - - public Person(String name, int age){ + + public Person() { + } + + public Person(String name, int age) { this.name = name; this.age = age; } - + public long getId() { return id; diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyNotAudited/ReadEntityWithAuditedCollectionTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyNotAudited/ReadEntityWithAuditedCollectionTest.java index acdd3b391d..2e59e9218d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyNotAudited/ReadEntityWithAuditedCollectionTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/oneToManyNotAudited/ReadEntityWithAuditedCollectionTest.java @@ -6,126 +6,124 @@ import java.net.URL; import java.util.ArrayList; import java.util.List; -import org.junit.Test; - import org.hibernate.MappingException; import org.hibernate.envers.test.AbstractOneSessionTest; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Hernán Chanfreau - * */ -public class ReadEntityWithAuditedCollectionTest extends AbstractOneSessionTest{ +public class ReadEntityWithAuditedCollectionTest extends AbstractOneSessionTest { private long id_car1; private long id_car2; - + private Car currentCar1; private Person currentPerson1; - + private long id_pers1; - + private Car car1_1; - + protected void initMappings() throws MappingException, URISyntaxException { - URL url = Thread.currentThread().getContextClassLoader().getResource("mappings/entityNames/oneToManyNotAudited/mappings.hbm.xml"); - config.addFile(new File(url.toURI())); + URL url = Thread.currentThread().getContextClassLoader().getResource( + "mappings/entityNames/oneToManyNotAudited/mappings.hbm.xml" + ); + config.addFile( new File( url.toURI() ) ); } - - - @Test - @Priority(10) - public void initData() { - - initializeSession(); - Person pers1 = new Person("Hernan", 28); - Person pers2 = new Person("Leandro", 29); - Person pers4 = new Person("Camomo", 15); - List owners = new ArrayList(); - owners.add(pers1); - owners.add(pers2); - Car car1 = new Car(5, owners); + @Test + @Priority(10) + public void initData() { - //REV 1 - getSession().getTransaction().begin(); - getSession().persist(car1); - getSession().getTransaction().commit(); - id_pers1 = pers1.getId(); - id_car1 = car1.getId(); + initializeSession(); - owners = new ArrayList(); - owners.add(pers2); - owners.add(pers4); - Car car2 = new Car(27, owners); - //REV 2 - getSession().getTransaction().begin(); - Person person1 = (Person)getSession().get("Personaje", id_pers1); - person1.setName("Hernan David"); - person1.setAge(40); - getSession().persist(car1); - getSession().persist(car2); - getSession().getTransaction().commit(); - id_car2 = car2.getId(); + Person pers1 = new Person( "Hernan", 28 ); + Person pers2 = new Person( "Leandro", 29 ); + Person pers4 = new Person( "Camomo", 15 ); - } - - private void loadDataOnSessionAndAuditReader() { - - currentCar1 = (Car)getSession().get(Car.class, id_car1); - currentPerson1 = (Person)getSession().get("Personaje", id_pers1); - - car1_1 = getAuditReader().find(Car.class, id_car1, 2); - Car car2 = getAuditReader().find(Car.class, id_car2, 2); + List owners = new ArrayList(); + owners.add( pers1 ); + owners.add( pers2 ); + Car car1 = new Car( 5, owners ); - for (Person owner : car1_1.getOwners()) { - owner.getName(); - owner.getAge(); + //REV 1 + getSession().getTransaction().begin(); + getSession().persist( car1 ); + getSession().getTransaction().commit(); + id_pers1 = pers1.getId(); + id_car1 = car1.getId(); + + owners = new ArrayList(); + owners.add( pers2 ); + owners.add( pers4 ); + Car car2 = new Car( 27, owners ); + //REV 2 + getSession().getTransaction().begin(); + Person person1 = (Person) getSession().get( "Personaje", id_pers1 ); + person1.setName( "Hernan David" ); + person1.setAge( 40 ); + getSession().persist( car1 ); + getSession().persist( car2 ); + getSession().getTransaction().commit(); + id_car2 = car2.getId(); + + } + + private void loadDataOnSessionAndAuditReader() { + + currentCar1 = (Car) getSession().get( Car.class, id_car1 ); + currentPerson1 = (Person) getSession().get( "Personaje", id_pers1 ); + + car1_1 = getAuditReader().find( Car.class, id_car1, 2 ); + Car car2 = getAuditReader().find( Car.class, id_car2, 2 ); + + for ( Person owner : car1_1.getOwners() ) { + owner.getName(); + owner.getAge(); } - for (Person owner : car2.getOwners()) { - owner.getName(); - owner.getAge(); + for ( Person owner : car2.getOwners() ) { + owner.getName(); + owner.getAge(); } - } - - private void checkEntityNames() { - - String currCar1EN = getSession().getEntityName(currentCar1); - String currPerson1EN = getSession().getEntityName(currentPerson1); + } - String car1_1EN = getAuditReader().getEntityName(id_car1, 2, car1_1); - assert(currCar1EN.equals(car1_1EN)); - - String person1_1EN = getSession().getEntityName(currentPerson1); - assert(currPerson1EN.equals(person1_1EN)); - } + private void checkEntityNames() { - @Test - public void testObtainEntityNameCollectionWithEntityNameAndNotAuditedMode() { - loadDataOnSessionAndAuditReader(); - - checkEntityNames(); + String currCar1EN = getSession().getEntityName( currentCar1 ); + String currPerson1EN = getSession().getEntityName( currentPerson1 ); - - } + String car1_1EN = getAuditReader().getEntityName( id_car1, 2, car1_1 ); + assert (currCar1EN.equals( car1_1EN )); - @Test - public void testObtainEntityNameCollectionWithEntityNameAndNotAuditedModeInNewSession() { - // force new session and AR - forceNewSession(); - - loadDataOnSessionAndAuditReader(); - - checkEntityNames(); + String person1_1EN = getSession().getEntityName( currentPerson1 ); + assert (currPerson1EN.equals( person1_1EN )); + } + + @Test + public void testObtainEntityNameCollectionWithEntityNameAndNotAuditedMode() { + loadDataOnSessionAndAuditReader(); + + checkEntityNames(); + + + } + + @Test + public void testObtainEntityNameCollectionWithEntityNameAndNotAuditedModeInNewSession() { + // force new session and AR + forceNewSession(); + + loadDataOnSessionAndAuditReader(); + + checkEntityNames(); + + + } - - } - - - - } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedAudited/Car.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedAudited/Car.java index 5bdd0a8758..507bbcbd71 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedAudited/Car.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedAudited/Car.java @@ -1,31 +1,32 @@ package org.hibernate.envers.test.integration.entityNames.singleAssociatedAudited; + import org.hibernate.envers.Audited; /** * @author Hernán Chanfreau - * */ @Audited public class Car { - + private long id; - + private int number; - + private Person owner; - private Person driver; - - public Car() { } + private Person driver; + + public Car() { + } public Car(int number, Person owner, Person driver) { this.number = number; this.owner = owner; - this.driver = driver; + this.driver = driver; } - + public long getId() { return id; } @@ -40,7 +41,7 @@ public class Car { public void setOwner(Person owner) { this.owner = owner; - } + } public int getNumber() { return number; @@ -50,11 +51,11 @@ public class Car { this.number = number; } - public Person getDriver() { - return driver; - } + public Person getDriver() { + return driver; + } - public void setDriver(Person driver) { - this.driver = driver; - } + public void setDriver(Person driver) { + this.driver = driver; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedAudited/Person.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedAudited/Person.java index 6758e13a2d..5768954935 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedAudited/Person.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedAudited/Person.java @@ -1,27 +1,28 @@ package org.hibernate.envers.test.integration.entityNames.singleAssociatedAudited; + import org.hibernate.envers.Audited; /** * @author Hernán Chanfreau - * */ @Audited public class Person { - + private long id; - + private String name; - + private int age; - - public Person(){ } - - public Person(String name, int age){ + + public Person() { + } + + public Person(String name, int age) { this.name = name; this.age = age; } - + public long getId() { return id; diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedAudited/ReadEntityAssociatedAuditedTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedAudited/ReadEntityAssociatedAuditedTest.java index 7c9dcedb72..bdc40336ab 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedAudited/ReadEntityAssociatedAuditedTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedAudited/ReadEntityAssociatedAuditedTest.java @@ -4,120 +4,119 @@ import java.io.File; import java.net.URISyntaxException; import java.net.URL; -import org.junit.Test; - import org.hibernate.MappingException; import org.hibernate.envers.test.AbstractOneSessionTest; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Hernán Chanfreau - * */ -public class ReadEntityAssociatedAuditedTest extends AbstractOneSessionTest{ +public class ReadEntityAssociatedAuditedTest extends AbstractOneSessionTest { private long id_car1; private long id_car2; - + private Car currentCar1; private Car car1; - - private long id_pers1; + + private long id_pers1; private long id_pers2; - + private Person currentPerson1; private Person person1; - - - - + + protected void initMappings() throws MappingException, URISyntaxException { - URL url = Thread.currentThread().getContextClassLoader().getResource("mappings/entityNames/singleAssociatedAudited/mappings.hbm.xml"); - config.addFile(new File(url.toURI())); + URL url = Thread.currentThread().getContextClassLoader().getResource( + "mappings/entityNames/singleAssociatedAudited/mappings.hbm.xml" + ); + config.addFile( new File( url.toURI() ) ); } - - @Test - @Priority(10) - public void initData() { - - initializeSession(); - Person pers1 = new Person("Hernan", 15); - Person pers2 = new Person("Leandro", 19); - - Car car1 = new Car(1, pers1, null); - Car car2 = new Car(2, pers2, null); - - //REV 1 - getSession().getTransaction().begin(); - getSession().persist("Personaje",pers1); - getSession().persist(car1); - getSession().getTransaction().commit(); - id_car1 = car1.getId(); - id_pers1 = pers1.getId(); + @Test + @Priority(10) + public void initData() { + + initializeSession(); + + Person pers1 = new Person( "Hernan", 15 ); + Person pers2 = new Person( "Leandro", 19 ); + + Car car1 = new Car( 1, pers1, null ); + Car car2 = new Car( 2, pers2, null ); + + //REV 1 + getSession().getTransaction().begin(); + getSession().persist( "Personaje", pers1 ); + getSession().persist( car1 ); + getSession().getTransaction().commit(); + id_car1 = car1.getId(); + id_pers1 = pers1.getId(); + + //REV 2 + getSession().getTransaction().begin(); + pers1.setAge( 50 ); + getSession().persist( "Personaje", pers1 ); + getSession().persist( "Personaje", pers2 ); + getSession().persist( car2 ); + getSession().getTransaction().commit(); + id_car2 = car2.getId(); + id_pers2 = pers2.getId(); + + } + + private void loadDataOnSessionAndAuditReader() { + currentCar1 = (Car) getSession().get( Car.class, id_car1 ); + currentPerson1 = (Person) getSession().get( "Personaje", id_pers1 ); + car1 = getAuditReader().find( Car.class, id_car1, 1 ); + person1 = car1.getOwner(); + + } - //REV 2 - getSession().getTransaction().begin(); - pers1.setAge(50); - getSession().persist("Personaje", pers1); - getSession().persist("Personaje", pers2); - getSession().persist(car2); - getSession().getTransaction().commit(); - id_car2 = car2.getId(); - id_pers2 = pers2.getId(); - - } - - private void loadDataOnSessionAndAuditReader() { - currentCar1 = (Car)getSession().get(Car.class, id_car1); - currentPerson1 = (Person)getSession().get("Personaje", id_pers1); - car1 = getAuditReader().find(Car.class, id_car1, 1); - person1 = car1.getOwner(); - - } - private void checkEntities() { - assert(currentPerson1.getAge() != person1.getAge()); - - Person person2 = (Person)getSession().get("Personaje", id_pers2); - Car car2 = getAuditReader().find(Car.class, id_car2, 2); - Person person2_1 = car2.getOwner(); - assert(person2.getAge() == person2_1.getAge()); + assert (currentPerson1.getAge() != person1.getAge()); + + Person person2 = (Person) getSession().get( "Personaje", id_pers2 ); + Car car2 = getAuditReader().find( Car.class, id_car2, 2 ); + Person person2_1 = car2.getOwner(); + assert (person2.getAge() == person2_1.getAge()); } - + private void checkEntityNames() { - String currentCar1EN = getSession().getEntityName(currentCar1); - - String currentPerson1EN = getSession().getEntityName(currentPerson1); - - String car1EN = getAuditReader().getEntityName(id_car1, 1, car1); - assert (currentCar1EN.equals(car1EN)); - - String person1EN = getAuditReader().getEntityName(id_pers1, 1, person1); - assert (currentPerson1EN.equals(person1EN)); - } - - @Test - public void testGetAssociationWithEntityName() { - loadDataOnSessionAndAuditReader(); - checkEntities(); - checkEntityNames(); - } + String currentCar1EN = getSession().getEntityName( currentCar1 ); + + String currentPerson1EN = getSession().getEntityName( currentPerson1 ); + + String car1EN = getAuditReader().getEntityName( id_car1, 1, car1 ); + assert (currentCar1EN.equals( car1EN )); + + String person1EN = getAuditReader().getEntityName( id_pers1, 1, person1 ); + assert (currentPerson1EN.equals( person1EN )); + } + + @Test + public void testGetAssociationWithEntityName() { + loadDataOnSessionAndAuditReader(); + checkEntities(); + checkEntityNames(); + } - @Test - public void testGetAssociationWithEntityNameInNewSession() { - //force a new session and AR - forceNewSession(); + @Test + public void testGetAssociationWithEntityNameInNewSession() { + //force a new session and AR + forceNewSession(); - loadDataOnSessionAndAuditReader(); + loadDataOnSessionAndAuditReader(); - checkEntities(); - - checkEntityNames(); - - } + checkEntities(); + + checkEntityNames(); + + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedAudited/SingleDomainObjectToMultipleTablesTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedAudited/SingleDomainObjectToMultipleTablesTest.java index e702cca368..2f7f8731a2 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedAudited/SingleDomainObjectToMultipleTablesTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedAudited/SingleDomainObjectToMultipleTablesTest.java @@ -4,62 +4,65 @@ import java.io.File; import java.net.URISyntaxException; import java.net.URL; -import org.junit.Assert; -import org.junit.Test; - import org.hibernate.MappingException; import org.hibernate.envers.test.AbstractOneSessionTest; import org.hibernate.envers.test.Priority; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class SingleDomainObjectToMultipleTablesTest extends AbstractOneSessionTest { - private long carId = 0; - private long ownerId = 0; - private long driverId = 0; + private long carId = 0; + private long ownerId = 0; + private long driverId = 0; - protected void initMappings() throws MappingException, URISyntaxException { - URL url = Thread.currentThread().getContextClassLoader().getResource("mappings/entityNames/singleAssociatedAudited/mappings.hbm.xml"); - config.addFile(new File(url.toURI())); - } + protected void initMappings() throws MappingException, URISyntaxException { + URL url = Thread.currentThread().getContextClassLoader().getResource( + "mappings/entityNames/singleAssociatedAudited/mappings.hbm.xml" + ); + config.addFile( new File( url.toURI() ) ); + } - @Test - @Priority(10) - public void initData() { - initializeSession(); + @Test + @Priority(10) + public void initData() { + initializeSession(); - //REV 1 - getSession().getTransaction().begin(); - Person owner = new Person("Lukasz", 25); - Person driver = new Person("Kinga", 24); - Car car = new Car(1, owner, driver); - getSession().persist("Personaje", owner); - getSession().persist("Driveraje", driver); - getSession().persist(car); - getSession().getTransaction().commit(); - - carId = car.getId(); - ownerId = owner.getId(); - driverId = driver.getId(); - } + //REV 1 + getSession().getTransaction().begin(); + Person owner = new Person( "Lukasz", 25 ); + Person driver = new Person( "Kinga", 24 ); + Car car = new Car( 1, owner, driver ); + getSession().persist( "Personaje", owner ); + getSession().persist( "Driveraje", driver ); + getSession().persist( car ); + getSession().getTransaction().commit(); - @Test - @TestForIssue(jiraKey="HHH-4648") - public void testSingleDomainObjectToMultipleTablesMapping() { - Car carVer1 = getAuditReader().find(Car.class, carId, 1); - Person ownerVer1 = getAuditReader().find(Person.class, "Personaje", ownerId, 1); - Person driverVer1 = getAuditReader().find(Person.class, "Driveraje", driverId, 1); + carId = car.getId(); + ownerId = owner.getId(); + driverId = driver.getId(); + } + + @Test + @TestForIssue(jiraKey = "HHH-4648") + public void testSingleDomainObjectToMultipleTablesMapping() { + Car carVer1 = getAuditReader().find( Car.class, carId, 1 ); + Person ownerVer1 = getAuditReader().find( Person.class, "Personaje", ownerId, 1 ); + Person driverVer1 = getAuditReader().find( Person.class, "Driveraje", driverId, 1 ); /* Check ids. */ - Assert.assertEquals(ownerVer1.getId(), carVer1.getOwner().getId()); - Assert.assertEquals(driverVer1.getId(), carVer1.getDriver().getId()); + Assert.assertEquals( ownerVer1.getId(), carVer1.getOwner().getId() ); + Assert.assertEquals( driverVer1.getId(), carVer1.getDriver().getId() ); /* Check object properties. */ - Assert.assertEquals("Lukasz", ownerVer1.getName()); - Assert.assertEquals("Kinga", driverVer1.getName()); - Assert.assertEquals(1, carVer1.getNumber()); - } + Assert.assertEquals( "Lukasz", ownerVer1.getName() ); + Assert.assertEquals( "Kinga", driverVer1.getName() ); + Assert.assertEquals( 1, carVer1.getNumber() ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedNotAudited/Car.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedNotAudited/Car.java index 92d35dc096..da4f1e1953 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedNotAudited/Car.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedNotAudited/Car.java @@ -1,29 +1,30 @@ package org.hibernate.envers.test.integration.entityNames.singleAssociatedNotAudited; + import org.hibernate.envers.Audited; import org.hibernate.envers.RelationTargetAuditMode; /** * @author Hernán Chanfreau - * */ public class Car { - + private long id; - + private int number; - + private Person owner; - - public Car() { } + + public Car() { + } public Car(int number, Person owner) { this.number = number; this.owner = owner; } - + public long getId() { return id; } @@ -32,14 +33,14 @@ public class Car { this.id = id; } - @Audited(targetAuditMode=RelationTargetAuditMode.NOT_AUDITED) + @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) public Person getOwner() { return owner; } public void setOwner(Person owner) { this.owner = owner; - } + } @Audited public int getNumber() { @@ -51,5 +52,4 @@ public class Car { } - } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedNotAudited/Person.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedNotAudited/Person.java index 14d79ff0d1..9a9b327053 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedNotAudited/Person.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedNotAudited/Person.java @@ -3,24 +3,24 @@ package org.hibernate.envers.test.integration.entityNames.singleAssociatedNotAud /** * @author Hernán Chanfreau - * */ public class Person { - + private long id; - + private String name; - + private int age; - - public Person(){ } - - public Person(String name, int age){ + + public Person() { + } + + public Person(String name, int age) { this.name = name; this.age = age; } - + public long getId() { return id; diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedNotAudited/ReadEntityAssociatedNotAuditedTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedNotAudited/ReadEntityAssociatedNotAuditedTest.java index 4b8625f7b4..3fcb36bb83 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedNotAudited/ReadEntityAssociatedNotAuditedTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/entityNames/singleAssociatedNotAudited/ReadEntityAssociatedNotAuditedTest.java @@ -4,120 +4,121 @@ import java.io.File; import java.net.URISyntaxException; import java.net.URL; -import org.junit.Test; - import org.hibernate.MappingException; import org.hibernate.envers.test.AbstractOneSessionTest; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Hernán Chanfreau - * */ public class ReadEntityAssociatedNotAuditedTest extends AbstractOneSessionTest { private long id_car1; private long id_car2; - - private long id_pers1; - private long id_pers2; - + + private long id_pers1; + private long id_pers2; + private Car car1; private Car car2; private Person person1_1; private Person person2; private Person currentPerson1; private Car currentCar1; - - + + protected void initMappings() throws MappingException, URISyntaxException { - URL url = Thread.currentThread().getContextClassLoader().getResource("mappings/entityNames/singleAssociatedNotAudited/mappings.hbm.xml"); - config.addFile(new File(url.toURI())); + URL url = Thread.currentThread().getContextClassLoader().getResource( + "mappings/entityNames/singleAssociatedNotAudited/mappings.hbm.xml" + ); + config.addFile( new File( url.toURI() ) ); } - @Test - @Priority(10) - public void initData() { - - initializeSession(); + @Test + @Priority(10) + public void initData() { - Person pers1 = new Person("Hernan", 15); - Person pers2 = new Person("Leandro", 19); - - Car car1 = new Car(1, pers1); - Car car2 = new Car(2, pers2); - - //REV 1 - getSession().getTransaction().begin(); - getSession().persist("Personaje",pers1); - getSession().persist(car1); - getSession().getTransaction().commit(); - id_car1 = car1.getId(); - id_pers1 = pers1.getId(); + initializeSession(); - //REV 2 - getSession().getTransaction().begin(); - pers1.setAge(50); - getSession().persist("Personaje", pers1); - getSession().persist("Personaje", pers2); - getSession().persist(car2); - getSession().getTransaction().commit(); - id_car2 = car2.getId(); - id_pers2 = pers2.getId(); + Person pers1 = new Person( "Hernan", 15 ); + Person pers2 = new Person( "Leandro", 19 ); - } - - private void loadDataOnSessionAndAuditReader() { - currentPerson1 = (Person)getSession().get("Personaje", id_pers1); - person2 = (Person)getSession().get("Personaje", id_pers2); - - currentCar1 = (Car)getSession().get(Car.class, id_car1); - - car1 = getAuditReader().find(Car.class, id_car1, 1); - car2 = getAuditReader().find(Car.class, id_car2, 2); - - } - - private void checkEntityNames() { - - String currentCar1EN = getSession().getEntityName(currentCar1); - - String car1EN = getAuditReader().getEntityName(id_car1, 1, car1); - - assert (currentCar1EN.equals(car1EN)); - - } - - private void checkEntities() { + Car car1 = new Car( 1, pers1 ); + Car car2 = new Car( 2, pers2 ); - person1_1 = car1.getOwner(); - Person person2_1 = car2.getOwner(); - - assert(currentPerson1.getAge() == person1_1.getAge()); - assert(person2.getAge() == person2_1.getAge()); - } - - @Test - public void testObtainEntityNameAssociationWithEntityNameAndNotAuditedMode() { - loadDataOnSessionAndAuditReader(); - - checkEntities(); - - checkEntityNames(); - } - + //REV 1 + getSession().getTransaction().begin(); + getSession().persist( "Personaje", pers1 ); + getSession().persist( car1 ); + getSession().getTransaction().commit(); + id_car1 = car1.getId(); + id_pers1 = pers1.getId(); - @Test - public void testObtainEntityNameAssociationWithEntityNameAndNotAuditedModeInNewSession() { - //force a new session and AR - forceNewSession(); - - loadDataOnSessionAndAuditReader(); - - checkEntities(); - - checkEntityNames(); + //REV 2 + getSession().getTransaction().begin(); + pers1.setAge( 50 ); + getSession().persist( "Personaje", pers1 ); + getSession().persist( "Personaje", pers2 ); + getSession().persist( car2 ); + getSession().getTransaction().commit(); + id_car2 = car2.getId(); + id_pers2 = pers2.getId(); - } + } + + private void loadDataOnSessionAndAuditReader() { + currentPerson1 = (Person) getSession().get( "Personaje", id_pers1 ); + person2 = (Person) getSession().get( "Personaje", id_pers2 ); + + currentCar1 = (Car) getSession().get( Car.class, id_car1 ); + + car1 = getAuditReader().find( Car.class, id_car1, 1 ); + car2 = getAuditReader().find( Car.class, id_car2, 2 ); + + } + + private void checkEntityNames() { + + String currentCar1EN = getSession().getEntityName( currentCar1 ); + + String car1EN = getAuditReader().getEntityName( id_car1, 1, car1 ); + + assert (currentCar1EN.equals( car1EN )); + + } + + private void checkEntities() { + + person1_1 = car1.getOwner(); + Person person2_1 = car2.getOwner(); + + assert (currentPerson1.getAge() == person1_1.getAge()); + assert (person2.getAge() == person2_1.getAge()); + } + + @Test + public void testObtainEntityNameAssociationWithEntityNameAndNotAuditedMode() { + loadDataOnSessionAndAuditReader(); + + checkEntities(); + + checkEntityNames(); + } + + + @Test + public void testObtainEntityNameAssociationWithEntityNameAndNotAuditedModeInNewSession() { + //force a new session and AR + forceNewSession(); + + loadDataOnSessionAndAuditReader(); + + checkEntities(); + + checkEntityNames(); + + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/AbstractFlushTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/AbstractFlushTest.java index 0defbb2ce2..c5319000dd 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/AbstractFlushTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/AbstractFlushTest.java @@ -23,45 +23,46 @@ */ package org.hibernate.envers.test.integration.flush; -import java.io.IOException; import javax.persistence.EntityManager; - -import org.junit.Before; +import java.io.IOException; import org.hibernate.FlushMode; import org.hibernate.Session; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.entities.StrTestEntity; +import org.junit.Before; + /** * @author Adam Warski (adam at warski dot org) */ public abstract class AbstractFlushTest extends BaseEnversJPAFunctionalTestCase { - public abstract FlushMode getFlushMode(); + public abstract FlushMode getFlushMode(); @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class }; + return new Class[] {StrTestEntity.class}; } - private static Session getSession(EntityManager em) { - Object delegate = em.getDelegate(); - if (delegate instanceof Session) { - return (Session) delegate; - } else if (delegate instanceof EntityManager) { - Object delegate2 = ((EntityManager) delegate).getDelegate(); + private static Session getSession(EntityManager em) { + Object delegate = em.getDelegate(); + if ( delegate instanceof Session ) { + return (Session) delegate; + } + else if ( delegate instanceof EntityManager ) { + Object delegate2 = ((EntityManager) delegate).getDelegate(); - if (delegate2 instanceof Session) { - return (Session) delegate2; - } - } + if ( delegate2 instanceof Session ) { + return (Session) delegate2; + } + } - throw new RuntimeException("Invalid entity manager"); - } + throw new RuntimeException( "Invalid entity manager" ); + } - @Before - public void initFlush() throws IOException { - Session session = getSession(getEntityManager()); - session.setFlushMode(getFlushMode()); - } + @Before + public void initFlush() throws IOException { + Session session = getSession( getEntityManager() ); + session.setFlushMode( getFlushMode() ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/DoubleFlushAddDel.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/DoubleFlushAddDel.java index 37d2bdb387..347f096692 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/DoubleFlushAddDel.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/DoubleFlushAddDel.java @@ -23,55 +23,55 @@ */ package org.hibernate.envers.test.integration.flush; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.FlushMode; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class DoubleFlushAddDel extends AbstractFlushTest { - private Integer id; + private Integer id; - public FlushMode getFlushMode() { - return FlushMode.MANUAL; - } + public FlushMode getFlushMode() { + return FlushMode.MANUAL; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - StrTestEntity fe = new StrTestEntity("x"); - em.persist(fe); + StrTestEntity fe = new StrTestEntity( "x" ); + em.persist( fe ); - em.flush(); + em.flush(); - em.remove(em.find(StrTestEntity.class, fe.getId())); + em.remove( em.find( StrTestEntity.class, fe.getId() ) ); - em.flush(); + em.flush(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - id = fe.getId(); - } + id = fe.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList().equals(getAuditReader().getRevisions(StrTestEntity.class, id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList().equals( getAuditReader().getRevisions( StrTestEntity.class, id ) ); + } - @Test - public void testHistoryOfId() { - assert getAuditReader().find(StrTestEntity.class, id, 1) == null; - } + @Test + public void testHistoryOfId() { + assert getAuditReader().find( StrTestEntity.class, id, 1 ) == null; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/DoubleFlushAddMod.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/DoubleFlushAddMod.java index b2c2a13880..cf19d1f6e1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/DoubleFlushAddMod.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/DoubleFlushAddMod.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.flush; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.FlushMode; import org.hibernate.envers.RevisionType; @@ -35,74 +33,76 @@ import org.hibernate.envers.query.AuditEntity; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; +import org.junit.Test; + import static org.junit.Assert.assertEquals; /** * @author Adam Warski (adam at warski dot org) */ public class DoubleFlushAddMod extends AbstractFlushTest { - private Integer id; + private Integer id; - public FlushMode getFlushMode() { - return FlushMode.MANUAL; - } + public FlushMode getFlushMode() { + return FlushMode.MANUAL; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - StrTestEntity fe = new StrTestEntity("x"); - em.persist(fe); + StrTestEntity fe = new StrTestEntity( "x" ); + em.persist( fe ); - em.flush(); + em.flush(); - fe.setStr("y"); + fe.setStr( "y" ); - em.flush(); + em.flush(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - fe = em.find(StrTestEntity.class, fe.getId()); + fe = em.find( StrTestEntity.class, fe.getId() ); - fe.setStr("z"); - em.flush(); + fe.setStr( "z" ); + em.flush(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - id = fe.getId(); - } + id = fe.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(StrTestEntity.class, id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( StrTestEntity.class, id ) ); + } - @Test - public void testHistoryOfId() { - StrTestEntity ver1 = new StrTestEntity("y", id); - StrTestEntity ver2 = new StrTestEntity("z", id); + @Test + public void testHistoryOfId() { + StrTestEntity ver1 = new StrTestEntity( "y", id ); + StrTestEntity ver2 = new StrTestEntity( "z", id ); - assert getAuditReader().find(StrTestEntity.class, id, 1).equals(ver1); - assert getAuditReader().find(StrTestEntity.class, id, 2).equals(ver2); - } + assert getAuditReader().find( StrTestEntity.class, id, 1 ).equals( ver1 ); + assert getAuditReader().find( StrTestEntity.class, id, 2 ).equals( ver2 ); + } - @Test - public void testRevisionTypes() { - @SuppressWarnings({"unchecked"}) List results = - getAuditReader().createQuery() - .forRevisionsOfEntity(StrTestEntity.class, false, true) - .add(AuditEntity.id().eq(id)) - .getResultList(); - - assertEquals(results.get(0)[2], RevisionType.ADD); - assertEquals(results.get(1)[2], RevisionType.MOD); - } + @Test + public void testRevisionTypes() { + @SuppressWarnings({"unchecked"}) List results = + getAuditReader().createQuery() + .forRevisionsOfEntity( StrTestEntity.class, false, true ) + .add( AuditEntity.id().eq( id ) ) + .getResultList(); + + assertEquals( results.get( 0 )[2], RevisionType.ADD ); + assertEquals( results.get( 1 )[2], RevisionType.MOD ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/DoubleFlushModDel.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/DoubleFlushModDel.java index 2142c01338..26007d0530 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/DoubleFlushModDel.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/DoubleFlushModDel.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.flush; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.FlushMode; import org.hibernate.envers.RevisionType; @@ -35,71 +33,73 @@ import org.hibernate.envers.query.AuditEntity; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; +import org.junit.Test; + import static org.junit.Assert.assertEquals; /** * @author Adam Warski (adam at warski dot org) */ public class DoubleFlushModDel extends AbstractFlushTest { - private Integer id; + private Integer id; - public FlushMode getFlushMode() { - return FlushMode.MANUAL; - } + public FlushMode getFlushMode() { + return FlushMode.MANUAL; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - StrTestEntity fe = new StrTestEntity("x"); - em.persist(fe); - em.flush(); + StrTestEntity fe = new StrTestEntity( "x" ); + em.persist( fe ); + em.flush(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - fe = em.find(StrTestEntity.class, fe.getId()); + fe = em.find( StrTestEntity.class, fe.getId() ); - fe.setStr("y"); - em.flush(); + fe.setStr( "y" ); + em.flush(); - em.remove(em.find(StrTestEntity.class, fe.getId())); - em.flush(); + em.remove( em.find( StrTestEntity.class, fe.getId() ) ); + em.flush(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - id = fe.getId(); - } + id = fe.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(StrTestEntity.class, id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( StrTestEntity.class, id ) ); + } - @Test - public void testHistoryOfId() { - StrTestEntity ver1 = new StrTestEntity("x", id); + @Test + public void testHistoryOfId() { + StrTestEntity ver1 = new StrTestEntity( "x", id ); - assert getAuditReader().find(StrTestEntity.class, id, 1).equals(ver1); - assert getAuditReader().find(StrTestEntity.class, id, 2) == null; - } + assert getAuditReader().find( StrTestEntity.class, id, 1 ).equals( ver1 ); + assert getAuditReader().find( StrTestEntity.class, id, 2 ) == null; + } - @Test - public void testRevisionTypes() { - @SuppressWarnings({"unchecked"}) List results = - getAuditReader().createQuery() - .forRevisionsOfEntity(StrTestEntity.class, false, true) - .add(AuditEntity.id().eq(id)) - .getResultList(); + @Test + public void testRevisionTypes() { + @SuppressWarnings({"unchecked"}) List results = + getAuditReader().createQuery() + .forRevisionsOfEntity( StrTestEntity.class, false, true ) + .add( AuditEntity.id().eq( id ) ) + .getResultList(); - assertEquals(results.get(0)[2], RevisionType.ADD); - assertEquals(results.get(1)[2], RevisionType.DEL); - } + assertEquals( results.get( 0 )[2], RevisionType.ADD ); + assertEquals( results.get( 1 )[2], RevisionType.DEL ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/DoubleFlushModMod.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/DoubleFlushModMod.java index 4d4f5f531b..e01f4e0dbd 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/DoubleFlushModMod.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/DoubleFlushModMod.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.flush; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.FlushMode; import org.hibernate.envers.RevisionType; @@ -35,72 +33,74 @@ import org.hibernate.envers.query.AuditEntity; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; +import org.junit.Test; + import static org.junit.Assert.assertEquals; /** * @author Adam Warski (adam at warski dot org) */ public class DoubleFlushModMod extends AbstractFlushTest { - private Integer id; + private Integer id; - public FlushMode getFlushMode() { - return FlushMode.MANUAL; - } + public FlushMode getFlushMode() { + return FlushMode.MANUAL; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - StrTestEntity fe = new StrTestEntity("x"); - em.persist(fe); - em.flush(); + StrTestEntity fe = new StrTestEntity( "x" ); + em.persist( fe ); + em.flush(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - fe = em.find(StrTestEntity.class, fe.getId()); + fe = em.find( StrTestEntity.class, fe.getId() ); - fe.setStr("y"); - em.flush(); + fe.setStr( "y" ); + em.flush(); - fe.setStr("z"); - em.flush(); + fe.setStr( "z" ); + em.flush(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - id = fe.getId(); - } + id = fe.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(StrTestEntity.class, id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( StrTestEntity.class, id ) ); + } - @Test - public void testHistoryOfId() { - StrTestEntity ver1 = new StrTestEntity("x", id); - StrTestEntity ver2 = new StrTestEntity("z", id); + @Test + public void testHistoryOfId() { + StrTestEntity ver1 = new StrTestEntity( "x", id ); + StrTestEntity ver2 = new StrTestEntity( "z", id ); - assert getAuditReader().find(StrTestEntity.class, id, 1).equals(ver1); - assert getAuditReader().find(StrTestEntity.class, id, 2).equals(ver2); - } + assert getAuditReader().find( StrTestEntity.class, id, 1 ).equals( ver1 ); + assert getAuditReader().find( StrTestEntity.class, id, 2 ).equals( ver2 ); + } - @Test - public void testRevisionTypes() { - @SuppressWarnings({"unchecked"}) List results = - getAuditReader().createQuery() - .forRevisionsOfEntity(StrTestEntity.class, false, true) - .add(AuditEntity.id().eq(id)) - .getResultList(); + @Test + public void testRevisionTypes() { + @SuppressWarnings({"unchecked"}) List results = + getAuditReader().createQuery() + .forRevisionsOfEntity( StrTestEntity.class, false, true ) + .add( AuditEntity.id().eq( id ) ) + .getResultList(); - assertEquals(results.get(0)[2], RevisionType.ADD); - assertEquals(results.get(1)[2], RevisionType.MOD); - } + assertEquals( results.get( 0 )[2], RevisionType.ADD ); + assertEquals( results.get( 1 )[2], RevisionType.MOD ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/ManualFlush.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/ManualFlush.java index 47ed0022d4..15c7d547b6 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/ManualFlush.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/ManualFlush.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.flush; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.FlushMode; import org.hibernate.envers.RevisionType; @@ -35,84 +33,86 @@ import org.hibernate.envers.query.AuditEntity; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; +import org.junit.Test; + import static org.junit.Assert.assertEquals; /** * @author Adam Warski (adam at warski dot org) */ public class ManualFlush extends AbstractFlushTest { - private Integer id; + private Integer id; - public FlushMode getFlushMode() { - return FlushMode.MANUAL; - } + public FlushMode getFlushMode() { + return FlushMode.MANUAL; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - StrTestEntity fe = new StrTestEntity("x"); - em.persist(fe); - em.flush(); + StrTestEntity fe = new StrTestEntity( "x" ); + em.persist( fe ); + em.flush(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // No revision - we change the data, but do not flush the session - em.getTransaction().begin(); + // No revision - we change the data, but do not flush the session + em.getTransaction().begin(); - fe = em.find(StrTestEntity.class, fe.getId()); - fe.setStr("y"); + fe = em.find( StrTestEntity.class, fe.getId() ); + fe.setStr( "y" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - only the first change should be saved - em.getTransaction().begin(); + // Revision 2 - only the first change should be saved + em.getTransaction().begin(); - fe = em.find(StrTestEntity.class, fe.getId()); - fe.setStr("z"); - em.flush(); + fe = em.find( StrTestEntity.class, fe.getId() ); + fe.setStr( "z" ); + em.flush(); - fe = em.find(StrTestEntity.class, fe.getId()); - fe.setStr("z2"); + fe = em.find( StrTestEntity.class, fe.getId() ); + fe.setStr( "z2" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - id = fe.getId(); - } + id = fe.getId(); + } - @Test - public void testRevisionsCounts() { - assertEquals(Arrays.asList(1, 2), getAuditReader().getRevisions(StrTestEntity.class, id)); - } + @Test + public void testRevisionsCounts() { + assertEquals( Arrays.asList( 1, 2 ), getAuditReader().getRevisions( StrTestEntity.class, id ) ); + } - @Test - public void testHistoryOfId() { - StrTestEntity ver1 = new StrTestEntity("x", id); - StrTestEntity ver2 = new StrTestEntity("z", id); + @Test + public void testHistoryOfId() { + StrTestEntity ver1 = new StrTestEntity( "x", id ); + StrTestEntity ver2 = new StrTestEntity( "z", id ); - assertEquals(ver1, getAuditReader().find(StrTestEntity.class, id, 1)); - assertEquals(ver2, getAuditReader().find(StrTestEntity.class, id, 2)); - } + assertEquals( ver1, getAuditReader().find( StrTestEntity.class, id, 1 ) ); + assertEquals( ver2, getAuditReader().find( StrTestEntity.class, id, 2 ) ); + } - @Test - public void testCurrent() { - assertEquals(new StrTestEntity("z", id), getEntityManager().find(StrTestEntity.class, id)); - } + @Test + public void testCurrent() { + assertEquals( new StrTestEntity( "z", id ), getEntityManager().find( StrTestEntity.class, id ) ); + } - @Test - public void testRevisionTypes() { - @SuppressWarnings({"unchecked"}) List results = - getAuditReader().createQuery() - .forRevisionsOfEntity(StrTestEntity.class, false, true) - .add(AuditEntity.id().eq(id)) - .getResultList(); + @Test + public void testRevisionTypes() { + @SuppressWarnings({"unchecked"}) List results = + getAuditReader().createQuery() + .forRevisionsOfEntity( StrTestEntity.class, false, true ) + .add( AuditEntity.id().eq( id ) ) + .getResultList(); - assertEquals(results.get(0)[2], RevisionType.ADD); - assertEquals(results.get(1)[2], RevisionType.MOD); - } + assertEquals( results.get( 0 )[2], RevisionType.ADD ); + assertEquals( results.get( 1 )[2], RevisionType.MOD ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/ManualFlushAutoCommitDisabled.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/ManualFlushAutoCommitDisabled.java index d6f94a5fdf..ee6f2f9030 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/ManualFlushAutoCommitDisabled.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/flush/ManualFlushAutoCommitDisabled.java @@ -9,9 +9,9 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-7017") public class ManualFlushAutoCommitDisabled extends ManualFlush { - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions(options); - options.put("hibernate.connection.autocommit", "false"); - } + @Override + protected void addConfigOptions(Map options) { + super.addConfigOptions( options ); + options.put( "hibernate.connection.autocommit", "false" ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/hashcode/ChangingHashcode.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/hashcode/ChangingHashcode.java index 5fad79b7fa..a4b26d6236 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/hashcode/ChangingHashcode.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/hashcode/ChangingHashcode.java @@ -23,15 +23,15 @@ */ package org.hibernate.envers.test.integration.hashcode; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ @@ -41,63 +41,75 @@ public class ChangingHashcode extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { WikiPage.class, WikiImage.class }; - } + return new Class[] {WikiPage.class, WikiImage.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - WikiPage page = new WikiPage("title", "content"); - em.persist(page); + WikiPage page = new WikiPage( "title", "content" ); + em.persist( page ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 2 + em = getEntityManager(); + em.getTransaction().begin(); - WikiImage image = new WikiImage("name1"); - em.persist(image); + WikiImage image = new WikiImage( "name1" ); + em.persist( image ); - page = em.find(WikiPage.class, page.getId()); - page.getImages().add(image); + page = em.find( WikiPage.class, page.getId() ); + page.getImages().add( image ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 3 + em = getEntityManager(); + em.getTransaction().begin(); - image = em.find(WikiImage.class, image.getId()); - image.setName("name2"); + image = em.find( WikiImage.class, image.getId() ); + image.setName( "name2" ); - em.getTransaction().commit(); + em.getTransaction().commit(); pageId = page.getId(); imageId = image.getId(); - } + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(WikiPage.class, pageId)); - assert Arrays.asList(2, 3).equals(getAuditReader().getRevisions(WikiImage.class, imageId)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( WikiPage.class, pageId ) ); + assert Arrays.asList( 2, 3 ).equals( getAuditReader().getRevisions( WikiImage.class, imageId ) ); + } - @Test - public void testHistoryOfImage() { - assert getAuditReader().find(WikiImage.class, imageId, 1) == null; - assert getAuditReader().find(WikiImage.class, imageId, 2).equals(new WikiImage("name1")); - assert getAuditReader().find(WikiImage.class, imageId, 3).equals(new WikiImage("name2")); - } + @Test + public void testHistoryOfImage() { + assert getAuditReader().find( WikiImage.class, imageId, 1 ) == null; + assert getAuditReader().find( WikiImage.class, imageId, 2 ).equals( new WikiImage( "name1" ) ); + assert getAuditReader().find( WikiImage.class, imageId, 3 ).equals( new WikiImage( "name2" ) ); + } - @Test - public void testHistoryOfPage() { - assert getAuditReader().find(WikiPage.class, pageId, 1).getImages().size() == 0; - assert getAuditReader().find(WikiPage.class, pageId, 2).getImages().equals(TestTools.makeSet(new WikiImage("name1"))); - assert getAuditReader().find(WikiPage.class, pageId, 3).getImages().equals(TestTools.makeSet(new WikiImage("name2"))); - } + @Test + public void testHistoryOfPage() { + assert getAuditReader().find( WikiPage.class, pageId, 1 ).getImages().size() == 0; + assert getAuditReader().find( WikiPage.class, pageId, 2 ).getImages().equals( + TestTools.makeSet( + new WikiImage( + "name1" + ) + ) + ); + assert getAuditReader().find( WikiPage.class, pageId, 3 ).getImages().equals( + TestTools.makeSet( + new WikiImage( + "name2" + ) + ) + ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/hashcode/WikiImage.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/hashcode/WikiImage.java index 02cda00fb7..6a9903bad3 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/hashcode/WikiImage.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/hashcode/WikiImage.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.integration.hashcode; + import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -40,12 +41,18 @@ public class WikiImage { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof WikiImage)) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof WikiImage) ) { + return false; + } WikiImage wikiImage = (WikiImage) o; - if (name != null ? !name.equals(wikiImage.name) : wikiImage.name != null) return false; + if ( name != null ? !name.equals( wikiImage.name ) : wikiImage.name != null ) { + return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/hashcode/WikiPage.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/hashcode/WikiPage.java index 454632e75a..ad152b9f8c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/hashcode/WikiPage.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/hashcode/WikiPage.java @@ -1,12 +1,13 @@ package org.hibernate.envers.test.integration.hashcode; -import java.util.HashSet; -import java.util.Set; + import javax.persistence.Basic; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.util.HashSet; +import java.util.Set; import org.hibernate.envers.Audited; @@ -78,13 +79,21 @@ public class WikiPage { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof WikiPage)) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof WikiPage) ) { + return false; + } WikiPage wikiPage = (WikiPage) o; - if (content != null ? !content.equals(wikiPage.content) : wikiPage.content != null) return false; - if (title != null ? !title.equals(wikiPage.title) : wikiPage.title != null) return false; + if ( content != null ? !content.equals( wikiPage.content ) : wikiPage.content != null ) { + return false; + } + if ( title != null ? !title.equals( wikiPage.title ) : wikiPage.title != null ) { + return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/CompositeDateId.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/CompositeDateId.java index 48f6449471..0f3d28d965 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/CompositeDateId.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/CompositeDateId.java @@ -23,64 +23,64 @@ */ package org.hibernate.envers.test.integration.ids; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Date; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.ids.CompositeDateIdTestEntity; import org.hibernate.envers.test.entities.ids.DateEmbId; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class CompositeDateId extends BaseEnversJPAFunctionalTestCase { - private DateEmbId id1; + private DateEmbId id1; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{CompositeDateIdTestEntity.class}; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {CompositeDateIdTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { + @Test + @Priority(10) + public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - CompositeDateIdTestEntity dite = new CompositeDateIdTestEntity(new DateEmbId(new Date(), new Date()), "x"); - em.persist(dite); + CompositeDateIdTestEntity dite = new CompositeDateIdTestEntity( new DateEmbId( new Date(), new Date() ), "x" ); + em.persist( dite ); - id1 = dite.getId(); + id1 = dite.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 2 + em = getEntityManager(); + em.getTransaction().begin(); - dite = em.find(CompositeDateIdTestEntity.class, id1); - dite.setStr1("y"); + dite = em.find( CompositeDateIdTestEntity.class, id1 ); + dite.setStr1( "y" ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(CompositeDateIdTestEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( CompositeDateIdTestEntity.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - CompositeDateIdTestEntity ver1 = new CompositeDateIdTestEntity(id1, "x"); - CompositeDateIdTestEntity ver2 = new CompositeDateIdTestEntity(id1, "y"); + @Test + public void testHistoryOfId1() { + CompositeDateIdTestEntity ver1 = new CompositeDateIdTestEntity( id1, "x" ); + CompositeDateIdTestEntity ver2 = new CompositeDateIdTestEntity( id1, "y" ); - assert getAuditReader().find(CompositeDateIdTestEntity.class, id1, 1).getStr1().equals("x"); - assert getAuditReader().find(CompositeDateIdTestEntity.class, id1, 2).getStr1().equals("y"); - } + assert getAuditReader().find( CompositeDateIdTestEntity.class, id1, 1 ).getStr1().equals( "x" ); + assert getAuditReader().find( CompositeDateIdTestEntity.class, id1, 2 ).getStr1().equals( "y" ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/CompositeIds.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/CompositeIds.java index 66d7758906..fdedd4a2c0 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/CompositeIds.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/CompositeIds.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.ids; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -38,188 +36,200 @@ import org.hibernate.envers.test.entities.ids.EmbIdWithCustomTypeTestEntity; import org.hibernate.envers.test.entities.ids.MulId; import org.hibernate.envers.test.entities.ids.MulIdTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class CompositeIds extends BaseEnversJPAFunctionalTestCase { - private EmbId id1; - private EmbId id2; - private MulId id3; - private MulId id4; - private EmbIdWithCustomType id5; - private EmbIdWithCustomType id6; + private EmbId id1; + private EmbId id2; + private MulId id3; + private MulId id4; + private EmbIdWithCustomType id5; + private EmbIdWithCustomType id6; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { EmbIdTestEntity.class, MulIdTestEntity.class, EmbIdWithCustomTypeTestEntity.class }; - } + return new Class[] {EmbIdTestEntity.class, MulIdTestEntity.class, EmbIdWithCustomTypeTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - id1 = new EmbId(1, 2); - id2 = new EmbId(10, 20); - id3 = new MulId(100, 101); - id4 = new MulId(102, 103); - id5 = new EmbIdWithCustomType(25, CustomEnum.NO); - id6 = new EmbIdWithCustomType(27, CustomEnum.YES); + @Test + @Priority(10) + public void initData() { + id1 = new EmbId( 1, 2 ); + id2 = new EmbId( 10, 20 ); + id3 = new MulId( 100, 101 ); + id4 = new MulId( 102, 103 ); + id5 = new EmbIdWithCustomType( 25, CustomEnum.NO ); + id6 = new EmbIdWithCustomType( 27, CustomEnum.YES ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - em.persist(new EmbIdTestEntity(id1, "x")); - em.persist(new MulIdTestEntity(id3.getId1(), id3.getId2(), "a")); - em.persist(new EmbIdWithCustomTypeTestEntity(id5, "c")); + em.persist( new EmbIdTestEntity( id1, "x" ) ); + em.persist( new MulIdTestEntity( id3.getId1(), id3.getId2(), "a" ) ); + em.persist( new EmbIdWithCustomTypeTestEntity( id5, "c" ) ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 2 + em = getEntityManager(); + em.getTransaction().begin(); - em.persist(new EmbIdTestEntity(id2, "y")); - em.persist(new MulIdTestEntity(id4.getId1(), id4.getId2(), "b")); - em.persist(new EmbIdWithCustomTypeTestEntity(id6, "d")); + em.persist( new EmbIdTestEntity( id2, "y" ) ); + em.persist( new MulIdTestEntity( id4.getId1(), id4.getId2(), "b" ) ); + em.persist( new EmbIdWithCustomTypeTestEntity( id6, "d" ) ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 3 + em = getEntityManager(); + em.getTransaction().begin(); - EmbIdTestEntity ete1 = em.find(EmbIdTestEntity.class, id1); - EmbIdTestEntity ete2 = em.find(EmbIdTestEntity.class, id2); - MulIdTestEntity mte3 = em.find(MulIdTestEntity.class, id3); - MulIdTestEntity mte4 = em.find(MulIdTestEntity.class, id4); - EmbIdWithCustomTypeTestEntity cte5 = em.find(EmbIdWithCustomTypeTestEntity.class, id5); - EmbIdWithCustomTypeTestEntity cte6 = em.find(EmbIdWithCustomTypeTestEntity.class, id6); + EmbIdTestEntity ete1 = em.find( EmbIdTestEntity.class, id1 ); + EmbIdTestEntity ete2 = em.find( EmbIdTestEntity.class, id2 ); + MulIdTestEntity mte3 = em.find( MulIdTestEntity.class, id3 ); + MulIdTestEntity mte4 = em.find( MulIdTestEntity.class, id4 ); + EmbIdWithCustomTypeTestEntity cte5 = em.find( EmbIdWithCustomTypeTestEntity.class, id5 ); + EmbIdWithCustomTypeTestEntity cte6 = em.find( EmbIdWithCustomTypeTestEntity.class, id6 ); - ete1.setStr1("x2"); - ete2.setStr1("y2"); - mte3.setStr1("a2"); - mte4.setStr1("b2"); - cte5.setStr1("c2"); - cte6.setStr1("d2"); + ete1.setStr1( "x2" ); + ete2.setStr1( "y2" ); + mte3.setStr1( "a2" ); + mte4.setStr1( "b2" ); + cte5.setStr1( "c2" ); + cte6.setStr1( "d2" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 4 + em = getEntityManager(); + em.getTransaction().begin(); - ete1 = em.find(EmbIdTestEntity.class, id1); - ete2 = em.find(EmbIdTestEntity.class, id2); - mte3 = em.find(MulIdTestEntity.class, id3); - cte5 = em.find(EmbIdWithCustomTypeTestEntity.class, id5); - cte6 = em.find(EmbIdWithCustomTypeTestEntity.class, id6); + ete1 = em.find( EmbIdTestEntity.class, id1 ); + ete2 = em.find( EmbIdTestEntity.class, id2 ); + mte3 = em.find( MulIdTestEntity.class, id3 ); + cte5 = em.find( EmbIdWithCustomTypeTestEntity.class, id5 ); + cte6 = em.find( EmbIdWithCustomTypeTestEntity.class, id6 ); - em.remove(ete1); - em.remove(mte3); - em.remove(cte6); + em.remove( ete1 ); + em.remove( mte3 ); + em.remove( cte6 ); - ete2.setStr1("y3"); - cte5.setStr1("c3"); + ete2.setStr1( "y3" ); + cte5.setStr1( "c3" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 5 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 5 + em = getEntityManager(); + em.getTransaction().begin(); - ete2 = em.find(EmbIdTestEntity.class, id2); + ete2 = em.find( EmbIdTestEntity.class, id2 ); - em.remove(ete2); + em.remove( ete2 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 3, 4).equals(getAuditReader().getRevisions(EmbIdTestEntity.class, id1)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 3, 4 ).equals( getAuditReader().getRevisions( EmbIdTestEntity.class, id1 ) ); - assert Arrays.asList(2, 3, 4, 5).equals(getAuditReader().getRevisions(EmbIdTestEntity.class, id2)); + assert Arrays.asList( 2, 3, 4, 5 ).equals( getAuditReader().getRevisions( EmbIdTestEntity.class, id2 ) ); - assert Arrays.asList(1, 3, 4).equals(getAuditReader().getRevisions(MulIdTestEntity.class, id3)); + assert Arrays.asList( 1, 3, 4 ).equals( getAuditReader().getRevisions( MulIdTestEntity.class, id3 ) ); - assert Arrays.asList(2, 3).equals(getAuditReader().getRevisions(MulIdTestEntity.class, id4)); + assert Arrays.asList( 2, 3 ).equals( getAuditReader().getRevisions( MulIdTestEntity.class, id4 ) ); - assert Arrays.asList(1, 3, 4).equals(getAuditReader().getRevisions(EmbIdWithCustomTypeTestEntity.class, id5)); + assert Arrays.asList( 1, 3, 4 ).equals( + getAuditReader().getRevisions( + EmbIdWithCustomTypeTestEntity.class, + id5 + ) + ); - assert Arrays.asList(2, 3, 4).equals(getAuditReader().getRevisions(EmbIdWithCustomTypeTestEntity.class, id6)); - } + assert Arrays.asList( 2, 3, 4 ).equals( + getAuditReader().getRevisions( + EmbIdWithCustomTypeTestEntity.class, + id6 + ) + ); + } - @Test - public void testHistoryOfId1() { - EmbIdTestEntity ver1 = new EmbIdTestEntity(id1, "x"); - EmbIdTestEntity ver2 = new EmbIdTestEntity(id1, "x2"); + @Test + public void testHistoryOfId1() { + EmbIdTestEntity ver1 = new EmbIdTestEntity( id1, "x" ); + EmbIdTestEntity ver2 = new EmbIdTestEntity( id1, "x2" ); - assert getAuditReader().find(EmbIdTestEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(EmbIdTestEntity.class, id1, 2).equals(ver1); - assert getAuditReader().find(EmbIdTestEntity.class, id1, 3).equals(ver2); - assert getAuditReader().find(EmbIdTestEntity.class, id1, 4) == null; - assert getAuditReader().find(EmbIdTestEntity.class, id1, 5) == null; - } + assert getAuditReader().find( EmbIdTestEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( EmbIdTestEntity.class, id1, 2 ).equals( ver1 ); + assert getAuditReader().find( EmbIdTestEntity.class, id1, 3 ).equals( ver2 ); + assert getAuditReader().find( EmbIdTestEntity.class, id1, 4 ) == null; + assert getAuditReader().find( EmbIdTestEntity.class, id1, 5 ) == null; + } - @Test - public void testHistoryOfId2() { - EmbIdTestEntity ver1 = new EmbIdTestEntity(id2, "y"); - EmbIdTestEntity ver2 = new EmbIdTestEntity(id2, "y2"); - EmbIdTestEntity ver3 = new EmbIdTestEntity(id2, "y3"); + @Test + public void testHistoryOfId2() { + EmbIdTestEntity ver1 = new EmbIdTestEntity( id2, "y" ); + EmbIdTestEntity ver2 = new EmbIdTestEntity( id2, "y2" ); + EmbIdTestEntity ver3 = new EmbIdTestEntity( id2, "y3" ); - assert getAuditReader().find(EmbIdTestEntity.class, id2, 1) == null; - assert getAuditReader().find(EmbIdTestEntity.class, id2, 2).equals(ver1); - assert getAuditReader().find(EmbIdTestEntity.class, id2, 3).equals(ver2); - assert getAuditReader().find(EmbIdTestEntity.class, id2, 4).equals(ver3); - assert getAuditReader().find(EmbIdTestEntity.class, id2, 5) == null; - } + assert getAuditReader().find( EmbIdTestEntity.class, id2, 1 ) == null; + assert getAuditReader().find( EmbIdTestEntity.class, id2, 2 ).equals( ver1 ); + assert getAuditReader().find( EmbIdTestEntity.class, id2, 3 ).equals( ver2 ); + assert getAuditReader().find( EmbIdTestEntity.class, id2, 4 ).equals( ver3 ); + assert getAuditReader().find( EmbIdTestEntity.class, id2, 5 ) == null; + } - @Test - public void testHistoryOfId3() { - MulIdTestEntity ver1 = new MulIdTestEntity(id3.getId1(), id3.getId2(), "a"); - MulIdTestEntity ver2 = new MulIdTestEntity(id3.getId1(), id3.getId2(), "a2"); + @Test + public void testHistoryOfId3() { + MulIdTestEntity ver1 = new MulIdTestEntity( id3.getId1(), id3.getId2(), "a" ); + MulIdTestEntity ver2 = new MulIdTestEntity( id3.getId1(), id3.getId2(), "a2" ); - assert getAuditReader().find(MulIdTestEntity.class, id3, 1).equals(ver1); - assert getAuditReader().find(MulIdTestEntity.class, id3, 2).equals(ver1); - assert getAuditReader().find(MulIdTestEntity.class, id3, 3).equals(ver2); - assert getAuditReader().find(MulIdTestEntity.class, id3, 4) == null; - assert getAuditReader().find(MulIdTestEntity.class, id3, 5) == null; - } + assert getAuditReader().find( MulIdTestEntity.class, id3, 1 ).equals( ver1 ); + assert getAuditReader().find( MulIdTestEntity.class, id3, 2 ).equals( ver1 ); + assert getAuditReader().find( MulIdTestEntity.class, id3, 3 ).equals( ver2 ); + assert getAuditReader().find( MulIdTestEntity.class, id3, 4 ) == null; + assert getAuditReader().find( MulIdTestEntity.class, id3, 5 ) == null; + } - @Test - public void testHistoryOfId4() { - MulIdTestEntity ver1 = new MulIdTestEntity(id4.getId1(), id4.getId2(), "b"); - MulIdTestEntity ver2 = new MulIdTestEntity(id4.getId1(), id4.getId2(), "b2"); + @Test + public void testHistoryOfId4() { + MulIdTestEntity ver1 = new MulIdTestEntity( id4.getId1(), id4.getId2(), "b" ); + MulIdTestEntity ver2 = new MulIdTestEntity( id4.getId1(), id4.getId2(), "b2" ); - assert getAuditReader().find(MulIdTestEntity.class, id4, 1) == null; - assert getAuditReader().find(MulIdTestEntity.class, id4, 2).equals(ver1); - assert getAuditReader().find(MulIdTestEntity.class, id4, 3).equals(ver2); - assert getAuditReader().find(MulIdTestEntity.class, id4, 4).equals(ver2); - assert getAuditReader().find(MulIdTestEntity.class, id4, 5).equals(ver2); - } + assert getAuditReader().find( MulIdTestEntity.class, id4, 1 ) == null; + assert getAuditReader().find( MulIdTestEntity.class, id4, 2 ).equals( ver1 ); + assert getAuditReader().find( MulIdTestEntity.class, id4, 3 ).equals( ver2 ); + assert getAuditReader().find( MulIdTestEntity.class, id4, 4 ).equals( ver2 ); + assert getAuditReader().find( MulIdTestEntity.class, id4, 5 ).equals( ver2 ); + } - @Test - public void testHistoryOfId5() { - EmbIdWithCustomTypeTestEntity ver1 = new EmbIdWithCustomTypeTestEntity(id5, "c"); - EmbIdWithCustomTypeTestEntity ver2 = new EmbIdWithCustomTypeTestEntity(id5, "c2"); - EmbIdWithCustomTypeTestEntity ver3 = new EmbIdWithCustomTypeTestEntity(id5, "c3"); + @Test + public void testHistoryOfId5() { + EmbIdWithCustomTypeTestEntity ver1 = new EmbIdWithCustomTypeTestEntity( id5, "c" ); + EmbIdWithCustomTypeTestEntity ver2 = new EmbIdWithCustomTypeTestEntity( id5, "c2" ); + EmbIdWithCustomTypeTestEntity ver3 = new EmbIdWithCustomTypeTestEntity( id5, "c3" ); - assert getAuditReader().find(EmbIdWithCustomTypeTestEntity.class, id5, 1).equals(ver1); - assert getAuditReader().find(EmbIdWithCustomTypeTestEntity.class, id5, 2).equals(ver1); - assert getAuditReader().find(EmbIdWithCustomTypeTestEntity.class, id5, 3).equals(ver2); - assert getAuditReader().find(EmbIdWithCustomTypeTestEntity.class, id5, 4).equals(ver3); - assert getAuditReader().find(EmbIdWithCustomTypeTestEntity.class, id5, 5).equals(ver3); - } + assert getAuditReader().find( EmbIdWithCustomTypeTestEntity.class, id5, 1 ).equals( ver1 ); + assert getAuditReader().find( EmbIdWithCustomTypeTestEntity.class, id5, 2 ).equals( ver1 ); + assert getAuditReader().find( EmbIdWithCustomTypeTestEntity.class, id5, 3 ).equals( ver2 ); + assert getAuditReader().find( EmbIdWithCustomTypeTestEntity.class, id5, 4 ).equals( ver3 ); + assert getAuditReader().find( EmbIdWithCustomTypeTestEntity.class, id5, 5 ).equals( ver3 ); + } - @Test - public void testHistoryOfId6() { - EmbIdWithCustomTypeTestEntity ver1 = new EmbIdWithCustomTypeTestEntity(id6, "d"); - EmbIdWithCustomTypeTestEntity ver2 = new EmbIdWithCustomTypeTestEntity(id6, "d2"); + @Test + public void testHistoryOfId6() { + EmbIdWithCustomTypeTestEntity ver1 = new EmbIdWithCustomTypeTestEntity( id6, "d" ); + EmbIdWithCustomTypeTestEntity ver2 = new EmbIdWithCustomTypeTestEntity( id6, "d2" ); - assert getAuditReader().find(EmbIdWithCustomTypeTestEntity.class, id6, 1) == null; - assert getAuditReader().find(EmbIdWithCustomTypeTestEntity.class, id6, 2).equals(ver1); - assert getAuditReader().find(EmbIdWithCustomTypeTestEntity.class, id6, 3).equals(ver2); - assert getAuditReader().find(EmbIdWithCustomTypeTestEntity.class, id6, 4) == null; - assert getAuditReader().find(EmbIdWithCustomTypeTestEntity.class, id6, 5) == null; - } + assert getAuditReader().find( EmbIdWithCustomTypeTestEntity.class, id6, 1 ) == null; + assert getAuditReader().find( EmbIdWithCustomTypeTestEntity.class, id6, 2 ).equals( ver1 ); + assert getAuditReader().find( EmbIdWithCustomTypeTestEntity.class, id6, 3 ).equals( ver2 ); + assert getAuditReader().find( EmbIdWithCustomTypeTestEntity.class, id6, 4 ) == null; + assert getAuditReader().find( EmbIdWithCustomTypeTestEntity.class, id6, 5 ) == null; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/DateId.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/DateId.java index 229a16f790..3eb24a6e25 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/DateId.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/DateId.java @@ -23,63 +23,63 @@ */ package org.hibernate.envers.test.integration.ids; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Date; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.ids.DateIdTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class DateId extends BaseEnversJPAFunctionalTestCase { - private Date id1; + private Date id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { DateIdTestEntity.class }; - } + return new Class[] {DateIdTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { + @Test + @Priority(10) + public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - DateIdTestEntity dite = new DateIdTestEntity(new Date(), "x"); - em.persist(dite); + DateIdTestEntity dite = new DateIdTestEntity( new Date(), "x" ); + em.persist( dite ); - id1 = dite.getId(); + id1 = dite.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 2 + em = getEntityManager(); + em.getTransaction().begin(); - dite = em.find(DateIdTestEntity.class, id1); - dite.setStr1("y"); + dite = em.find( DateIdTestEntity.class, id1 ); + dite.setStr1( "y" ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(DateIdTestEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( DateIdTestEntity.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - DateIdTestEntity ver1 = new DateIdTestEntity(id1, "x"); - DateIdTestEntity ver2 = new DateIdTestEntity(id1, "y"); + @Test + public void testHistoryOfId1() { + DateIdTestEntity ver1 = new DateIdTestEntity( id1, "x" ); + DateIdTestEntity ver2 = new DateIdTestEntity( id1, "y" ); - assert getAuditReader().find(DateIdTestEntity.class, id1, 1).getStr1().equals("x"); - assert getAuditReader().find(DateIdTestEntity.class, id1, 2).getStr1().equals("y"); - } + assert getAuditReader().find( DateIdTestEntity.class, id1, 1 ).getStr1().equals( "x" ); + assert getAuditReader().find( DateIdTestEntity.class, id1, 2 ).getStr1().equals( "y" ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/ManyToOneIdNotAudited.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/ManyToOneIdNotAudited.java index bbb5d8359a..9fb2e9b125 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/ManyToOneIdNotAudited.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/ManyToOneIdNotAudited.java @@ -2,8 +2,6 @@ package org.hibernate.envers.test.integration.ids; import javax.persistence.EntityManager; -import org.junit.Test; - import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; @@ -11,43 +9,46 @@ import org.hibernate.envers.test.entities.UnversionedStrTestEntity; import org.hibernate.envers.test.entities.ids.ManyToOneIdNotAuditedTestEntity; import org.hibernate.envers.test.entities.ids.ManyToOneNotAuditedEmbId; +import org.junit.Test; + /** * A test checking that when using Envers it is possible to have non-audited entities that use unsupported * components in their ids, e.g. a many-to-one join to another entity. + * * @author Adam Warski (adam at warski dot org) */ public class ManyToOneIdNotAudited extends BaseEnversJPAFunctionalTestCase { - private ManyToOneNotAuditedEmbId id1; + private ManyToOneNotAuditedEmbId id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ManyToOneIdNotAuditedTestEntity.class, UnversionedStrTestEntity.class, StrTestEntity.class }; - } + return new Class[] {ManyToOneIdNotAuditedTestEntity.class, UnversionedStrTestEntity.class, StrTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - UnversionedStrTestEntity uste = new UnversionedStrTestEntity(); - uste.setStr("test1"); - em.persist(uste); + UnversionedStrTestEntity uste = new UnversionedStrTestEntity(); + uste.setStr( "test1" ); + em.persist( uste ); - id1 = new ManyToOneNotAuditedEmbId(uste); + id1 = new ManyToOneNotAuditedEmbId( uste ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 2 + em = getEntityManager(); + em.getTransaction().begin(); - ManyToOneIdNotAuditedTestEntity mtoinate = new ManyToOneIdNotAuditedTestEntity(); - mtoinate.setData("data1"); - mtoinate.setId(id1); - em.persist(mtoinate); + ManyToOneIdNotAuditedTestEntity mtoinate = new ManyToOneIdNotAuditedTestEntity(); + mtoinate.setData( "data1" ); + mtoinate.setId( id1 ); + em.persist( mtoinate ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/Item.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/Item.java index b95b70d5ea..5050b1bbab 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/Item.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/Item.java @@ -1,8 +1,8 @@ package org.hibernate.envers.test.integration.ids.embeddedid; -import java.io.Serializable; import javax.persistence.EmbeddedId; import javax.persistence.Entity; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -12,57 +12,65 @@ import org.hibernate.envers.Audited; @Entity @Audited public class Item implements Serializable { - @EmbeddedId - private ItemId id; + @EmbeddedId + private ItemId id; - private Double price; + private Double price; - public Item() { - } + public Item() { + } - public Item(ItemId id, Double price) { - this.id = id; - this.price = price; - } + public Item(ItemId id, Double price) { + this.id = id; + this.price = price; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Item)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Item) ) { + return false; + } - Item item = (Item) o; + Item item = (Item) o; - if (getId() != null ? !getId().equals(item.getId()) : item.getId() != null) return false; - if (getPrice() != null ? !getPrice().equals(item.getPrice()) : item.getPrice() != null) return false; + if ( getId() != null ? !getId().equals( item.getId() ) : item.getId() != null ) { + return false; + } + if ( getPrice() != null ? !getPrice().equals( item.getPrice() ) : item.getPrice() != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (price != null ? price.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (price != null ? price.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "Item(id = " + id + ", price = + " + price + ")"; - } + @Override + public String toString() { + return "Item(id = " + id + ", price = + " + price + ")"; + } - public ItemId getId() { - return id; - } + public ItemId getId() { + return id; + } - public void setId(ItemId id) { - this.id = id; - } + public void setId(ItemId id) { + this.id = id; + } - public Double getPrice() { - return price; - } + public Double getPrice() { + return price; + } - public void setPrice(Double price) { - this.price = price; - } + public void setPrice(Double price) { + this.price = price; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/ItemId.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/ItemId.java index 1afa11765a..bbd2fc4739 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/ItemId.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/ItemId.java @@ -1,83 +1,93 @@ package org.hibernate.envers.test.integration.ids.embeddedid; -import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; +import java.io.Serializable; /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @Embeddable public class ItemId implements Serializable { - @Column(name = "model") - private String model; + @Column(name = "model") + private String model; - @Column(name = "version") - private Integer version; + @Column(name = "version") + private Integer version; - @ManyToOne - @JoinColumn(name = "producer", nullable = false) // NOT NULL for Sybase - private Producer producer; + @ManyToOne + @JoinColumn(name = "producer", nullable = false) // NOT NULL for Sybase + private Producer producer; - public ItemId() { - } + public ItemId() { + } - public ItemId(String model, Integer version, Producer producer) { - this.model = model; - this.version = version; - this.producer = producer; - } + public ItemId(String model, Integer version, Producer producer) { + this.model = model; + this.version = version; + this.producer = producer; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ItemId)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ItemId) ) { + return false; + } - ItemId itemId = (ItemId) o; + ItemId itemId = (ItemId) o; - if (getModel() != null ? !getModel().equals(itemId.getModel()) : itemId.getModel() != null) return false; - if (getProducer() != null ? !getProducer().equals(itemId.getProducer()) : itemId.getProducer() != null) return false; - if (getVersion() != null ? !getVersion().equals(itemId.getVersion()) : itemId.getVersion() != null) return false; + if ( getModel() != null ? !getModel().equals( itemId.getModel() ) : itemId.getModel() != null ) { + return false; + } + if ( getProducer() != null ? !getProducer().equals( itemId.getProducer() ) : itemId.getProducer() != null ) { + return false; + } + if ( getVersion() != null ? !getVersion().equals( itemId.getVersion() ) : itemId.getVersion() != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = model != null ? model.hashCode() : 0; - result = 31 * result + (version != null ? version.hashCode() : 0); - result = 31 * result + (producer != null ? producer.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = model != null ? model.hashCode() : 0; + result = 31 * result + (version != null ? version.hashCode() : 0); + result = 31 * result + (producer != null ? producer.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "ItemId(model = " + model + ", version = " + version + ", producer = " + producer + ")"; - } + @Override + public String toString() { + return "ItemId(model = " + model + ", version = " + version + ", producer = " + producer + ")"; + } - public String getModel() { - return model; - } + public String getModel() { + return model; + } - public void setModel(String model) { - this.model = model; - } + public void setModel(String model) { + this.model = model; + } - public Integer getVersion() { - return version; - } + public Integer getVersion() { + return version; + } - public void setVersion(Integer version) { - this.version = version; - } + public void setVersion(Integer version) { + this.version = version; + } - public Producer getProducer() { - return producer; - } + public Producer getProducer() { + return producer; + } - public void setProducer(Producer producer) { - this.producer = producer; - } + public void setProducer(Producer producer) { + this.producer = producer; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/Producer.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/Producer.java index 27538a6d0b..ccf94210b0 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/Producer.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/Producer.java @@ -1,9 +1,9 @@ package org.hibernate.envers.test.integration.ids.embeddedid; -import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -13,59 +13,67 @@ import org.hibernate.envers.Audited; @Entity @Audited public class Producer implements Serializable { - @Id - @Column(name = "id") - private Integer id; + @Id + @Column(name = "id") + private Integer id; - @Column(name = "name") - private String name; + @Column(name = "name") + private String name; - public Producer() { - } + public Producer() { + } - public Producer(Integer id, String name) { - this.id = id; - this.name = name; - } + public Producer(Integer id, String name) { + this.id = id; + this.name = name; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Producer)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Producer) ) { + return false; + } - Producer producer = (Producer) o; + Producer producer = (Producer) o; - if (getId() != null ? !getId().equals(producer.getId()) : producer.getId() != null) return false; - if (getName() != null ? !getName().equals(producer.getName()) : producer.getName() != null) return false; + if ( getId() != null ? !getId().equals( producer.getId() ) : producer.getId() != null ) { + return false; + } + if ( getName() != null ? !getName().equals( producer.getName() ) : producer.getName() != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (name != null ? name.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (name != null ? name.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "Producer(id = " + id + ", name = " + name + ")"; - } + @Override + public String toString() { + return "Producer(id = " + id + ", name = " + name + ")"; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/PurchaseOrder.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/PurchaseOrder.java index 892e32da72..1540fe961a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/PurchaseOrder.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/PurchaseOrder.java @@ -1,6 +1,5 @@ package org.hibernate.envers.test.integration.ids.embeddedid; -import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -8,6 +7,7 @@ import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.ManyToOne; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -17,82 +17,93 @@ import org.hibernate.envers.Audited; @Entity @Audited public class PurchaseOrder implements Serializable { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @ManyToOne - @JoinColumns({ - @JoinColumn(name = "model", referencedColumnName = "model", nullable = true), - @JoinColumn(name = "version", referencedColumnName = "version", nullable = true), - @JoinColumn(name = "producer", referencedColumnName = "producer", nullable = true)}) - private Item item; + @ManyToOne + @JoinColumns({ + @JoinColumn(name = "model", referencedColumnName = "model", nullable = true), + @JoinColumn(name = "version", referencedColumnName = "version", nullable = true), + @JoinColumn(name = "producer", referencedColumnName = "producer", nullable = true) + }) + private Item item; - @Column(name = "NOTE") - private String comment; + @Column(name = "NOTE") + private String comment; - public PurchaseOrder() { - } + public PurchaseOrder() { + } - public PurchaseOrder(Item item, String comment) { - this.item = item; - this.comment = comment; - } + public PurchaseOrder(Item item, String comment) { + this.item = item; + this.comment = comment; + } - public PurchaseOrder(Integer id, Item item, String comment) { - this.id = id; - this.item = item; - this.comment = comment; - } + public PurchaseOrder(Integer id, Item item, String comment) { + this.id = id; + this.item = item; + this.comment = comment; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof PurchaseOrder)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof PurchaseOrder) ) { + return false; + } - PurchaseOrder that = (PurchaseOrder) o; + PurchaseOrder that = (PurchaseOrder) o; - if (getComment() != null ? !getComment().equals(that.getComment()) : that.getComment() != null) return false; - if (getId() != null ? !getId().equals(that.getId()) : that.getId() != null) return false; - if (getItem() != null ? !getItem().equals(that.getItem()) : that.getItem() != null) return false; + if ( getComment() != null ? !getComment().equals( that.getComment() ) : that.getComment() != null ) { + return false; + } + if ( getId() != null ? !getId().equals( that.getId() ) : that.getId() != null ) { + return false; + } + if ( getItem() != null ? !getItem().equals( that.getItem() ) : that.getItem() != null ) { + return false; + } - return true; - } + return true; + } - @Override - public String toString() { - return "PurchaseOrder(id = " + id + ", item = " + item + ", comment = " + comment + ")"; - } + @Override + public String toString() { + return "PurchaseOrder(id = " + id + ", item = " + item + ", comment = " + comment + ")"; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (item != null ? item.hashCode() : 0); - result = 31 * result + (comment != null ? comment.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (item != null ? item.hashCode() : 0); + result = 31 * result + (comment != null ? comment.hashCode() : 0); + return result; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Item getItem() { - return item; - } + public Item getItem() { + return item; + } - public void setItem(Item item) { - this.item = item; - } + public void setItem(Item item) { + this.item = item; + } - public String getComment() { - return comment; - } + public String getComment() { + return comment; + } - public void setComment(String comment) { - this.comment = comment; - } + public void setComment(String comment) { + this.comment = comment; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/RelationInsideEmbeddableTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/RelationInsideEmbeddableTest.java index 28ee8adacc..cfc6c47c59 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/RelationInsideEmbeddableTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/embeddedid/RelationInsideEmbeddableTest.java @@ -1,13 +1,14 @@ package org.hibernate.envers.test.integration.ids.embeddedid; -import java.util.Arrays; import javax.persistence.EntityManager; +import java.util.Arrays; + +import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; +import org.hibernate.envers.test.Priority; import org.junit.Assert; import org.junit.Test; -import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; -import org.hibernate.envers.test.Priority; import org.hibernate.testing.TestForIssue; /** @@ -15,70 +16,80 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-7690") public class RelationInsideEmbeddableTest extends BaseEnversJPAFunctionalTestCase { - private Integer orderId = null; - private ItemId itemId = null; + private Integer orderId = null; + private ItemId itemId = null; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{PurchaseOrder.class, Item.class, ItemId.class, Producer.class}; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {PurchaseOrder.class, Item.class, ItemId.class, Producer.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 1 - em.getTransaction().begin(); - Producer producer = new Producer(1, "Sony"); - ItemId sonyId = new ItemId("TV", 1, producer); - Item item = new Item(sonyId, 100.50); - PurchaseOrder order = new PurchaseOrder(item, null); - em.persist(producer); - em.persist(item); - em.persist(order); - em.getTransaction().commit(); + // Revision 1 + em.getTransaction().begin(); + Producer producer = new Producer( 1, "Sony" ); + ItemId sonyId = new ItemId( "TV", 1, producer ); + Item item = new Item( sonyId, 100.50 ); + PurchaseOrder order = new PurchaseOrder( item, null ); + em.persist( producer ); + em.persist( item ); + em.persist( order ); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); - order = em.find(PurchaseOrder.class, order.getId()); - order.setComment("fragile"); - order = em.merge(order); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + order = em.find( PurchaseOrder.class, order.getId() ); + order.setComment( "fragile" ); + order = em.merge( order ); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); - item = em.find(Item.class, sonyId); - item.setPrice(110.00); - em.getTransaction().commit(); + // Revision 3 + em.getTransaction().begin(); + item = em.find( Item.class, sonyId ); + item.setPrice( 110.00 ); + em.getTransaction().commit(); - orderId = order.getId(); - itemId = sonyId; + orderId = order.getId(); + itemId = sonyId; - em.close(); - } + em.close(); + } - @Test - public void testRevisionsCounts() throws Exception { - Assert.assertEquals(Arrays.asList(1, 2), getAuditReader().getRevisions(PurchaseOrder.class, orderId)); - Assert.assertEquals(Arrays.asList(1, 3), getAuditReader().getRevisions(Item.class, itemId)); - } + @Test + public void testRevisionsCounts() throws Exception { + Assert.assertEquals( Arrays.asList( 1, 2 ), getAuditReader().getRevisions( PurchaseOrder.class, orderId ) ); + Assert.assertEquals( Arrays.asList( 1, 3 ), getAuditReader().getRevisions( Item.class, itemId ) ); + } - @Test - public void testHistoryOfPurchaseOrder() { - PurchaseOrder ver1 = new PurchaseOrder(orderId, new Item(new ItemId("TV", 1, new Producer(1, "Sony")), 100.50), null); - PurchaseOrder ver2 = new PurchaseOrder(orderId, new Item(new ItemId("TV", 1, new Producer(1, "Sony")), 100.50), "fragile"); + @Test + public void testHistoryOfPurchaseOrder() { + PurchaseOrder ver1 = new PurchaseOrder( + orderId, new Item( + new ItemId( "TV", 1, new Producer( 1, "Sony" ) ), + 100.50 + ), null + ); + PurchaseOrder ver2 = new PurchaseOrder( + orderId, new Item( + new ItemId( "TV", 1, new Producer( 1, "Sony" ) ), + 100.50 + ), "fragile" + ); - Assert.assertEquals(ver1, getAuditReader().find(PurchaseOrder.class, orderId, 1)); - Assert.assertEquals(ver2, getAuditReader().find(PurchaseOrder.class, orderId, 2)); - } + Assert.assertEquals( ver1, getAuditReader().find( PurchaseOrder.class, orderId, 1 ) ); + Assert.assertEquals( ver2, getAuditReader().find( PurchaseOrder.class, orderId, 2 ) ); + } - @Test - public void testHistoryOfItem() { - Item ver1 = new Item(itemId, 100.50); - Item ver2 = new Item(itemId, 110.00); + @Test + public void testHistoryOfItem() { + Item ver1 = new Item( itemId, 100.50 ); + Item ver2 = new Item( itemId, 110.00 ); - Assert.assertEquals(ver1, getAuditReader().find(Item.class, itemId, 1)); - Assert.assertEquals(ver2, getAuditReader().find(Item.class, itemId, 3)); - } + Assert.assertEquals( ver1, getAuditReader().find( Item.class, itemId, 1 ) ); + Assert.assertEquals( ver2, getAuditReader().find( Item.class, itemId, 3 ) ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/idclass/ClassType.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/idclass/ClassType.java index f4a75f2ca4..c1dd7574eb 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/idclass/ClassType.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/idclass/ClassType.java @@ -1,9 +1,9 @@ package org.hibernate.envers.test.integration.ids.idclass; -import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -13,55 +13,61 @@ import org.hibernate.envers.Audited; @Audited @Entity public class ClassType implements Serializable { - @Id - @Column(name = "Name") - private String type; + @Id + @Column(name = "Name") + private String type; - private String description; + private String description; - public ClassType() { - } + public ClassType() { + } - public ClassType(String type, String description) { - this.type = type; - this.description = description; - } + public ClassType(String type, String description) { + this.type = type; + this.description = description; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ClassType)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ClassType) ) { + return false; + } - ClassType classType = (ClassType) o; + ClassType classType = (ClassType) o; - if (type != null ? !type.equals(classType.type) : classType.type != null) return false; + if ( type != null ? !type.equals( classType.type ) : classType.type != null ) { + return false; + } - return true; - } + return true; + } - @Override - public String toString() { - return "ClassType(type = " + type + ", description = " + description + ")"; - } + @Override + public String toString() { + return "ClassType(type = " + type + ", description = " + description + ")"; + } - @Override - public int hashCode() { - return type != null ? type.hashCode() : 0; - } + @Override + public int hashCode() { + return type != null ? type.hashCode() : 0; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/idclass/IdClassWithRelationTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/idclass/IdClassWithRelationTest.java index e76ab25a00..7395f699a0 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/idclass/IdClassWithRelationTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/idclass/IdClassWithRelationTest.java @@ -1,13 +1,14 @@ package org.hibernate.envers.test.integration.ids.idclass; -import java.util.Arrays; import javax.persistence.EntityManager; - -import junit.framework.Assert; -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; + +import org.junit.Test; +import junit.framework.Assert; + import org.hibernate.testing.TestForIssue; /** @@ -15,103 +16,103 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-4751") public class IdClassWithRelationTest extends BaseEnversJPAFunctionalTestCase { - private RelationalClassId entityId = null; - private String typeId = null; + private RelationalClassId entityId = null; + private String typeId = null; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{SampleClass.class, RelationalClassId.class, ClassType.class}; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {SampleClass.class, RelationalClassId.class, ClassType.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 1 - em.getTransaction().begin(); - ClassType type = new ClassType("type", "initial description"); - SampleClass entity = new SampleClass(); - entity.setType(type); - entity.setSampleValue("initial data"); - em.persist(type); - em.persist(entity); - em.getTransaction().commit(); + // Revision 1 + em.getTransaction().begin(); + ClassType type = new ClassType( "type", "initial description" ); + SampleClass entity = new SampleClass(); + entity.setType( type ); + entity.setSampleValue( "initial data" ); + em.persist( type ); + em.persist( entity ); + em.getTransaction().commit(); - typeId = type.getType(); - entityId = new RelationalClassId(entity.getId(), new ClassType("type", "initial description")); + typeId = type.getType(); + entityId = new RelationalClassId( entity.getId(), new ClassType( "type", "initial description" ) ); - // Revision 2 - em.getTransaction().begin(); - type = em.find(ClassType.class, type.getType()); - type.setDescription("modified description"); - em.merge(type); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + type = em.find( ClassType.class, type.getType() ); + type.setDescription( "modified description" ); + em.merge( type ); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); - entity = em.find(SampleClass.class, entityId); - entity.setSampleValue("modified data"); - em.merge(entity); - em.getTransaction().commit(); + // Revision 3 + em.getTransaction().begin(); + entity = em.find( SampleClass.class, entityId ); + entity.setSampleValue( "modified data" ); + em.merge( entity ); + em.getTransaction().commit(); - em.close(); - } + em.close(); + } - @Test - public void testRevisionsCounts() { - Assert.assertEquals(Arrays.asList(1, 2), getAuditReader().getRevisions(ClassType.class, typeId)); - Assert.assertEquals(Arrays.asList(1, 3), getAuditReader().getRevisions(SampleClass.class, entityId)); - } + @Test + public void testRevisionsCounts() { + Assert.assertEquals( Arrays.asList( 1, 2 ), getAuditReader().getRevisions( ClassType.class, typeId ) ); + Assert.assertEquals( Arrays.asList( 1, 3 ), getAuditReader().getRevisions( SampleClass.class, entityId ) ); + } - @Test - public void testHistoryOfEntity() { - // given - SampleClass entity = new SampleClass(entityId.getId(), entityId.getType(), "initial data"); + @Test + public void testHistoryOfEntity() { + // given + SampleClass entity = new SampleClass( entityId.getId(), entityId.getType(), "initial data" ); - // when - SampleClass ver1 = getAuditReader().find(SampleClass.class, entityId, 1); + // when + SampleClass ver1 = getAuditReader().find( SampleClass.class, entityId, 1 ); - // then - Assert.assertEquals(entity.getId(), ver1.getId()); - Assert.assertEquals(entity.getSampleValue(), ver1.getSampleValue()); - Assert.assertEquals(entity.getType().getType(), ver1.getType().getType()); - Assert.assertEquals(entity.getType().getDescription(), ver1.getType().getDescription()); + // then + Assert.assertEquals( entity.getId(), ver1.getId() ); + Assert.assertEquals( entity.getSampleValue(), ver1.getSampleValue() ); + Assert.assertEquals( entity.getType().getType(), ver1.getType().getType() ); + Assert.assertEquals( entity.getType().getDescription(), ver1.getType().getDescription() ); - // given - entity.setSampleValue("modified data"); - entity.getType().setDescription("modified description"); + // given + entity.setSampleValue( "modified data" ); + entity.getType().setDescription( "modified description" ); - // when - SampleClass ver2 = getAuditReader().find(SampleClass.class, entityId, 3); + // when + SampleClass ver2 = getAuditReader().find( SampleClass.class, entityId, 3 ); - // then - Assert.assertEquals(entity.getId(), ver2.getId()); - Assert.assertEquals(entity.getSampleValue(), ver2.getSampleValue()); - Assert.assertEquals(entity.getType().getType(), ver2.getType().getType()); - Assert.assertEquals(entity.getType().getDescription(), ver2.getType().getDescription()); - } + // then + Assert.assertEquals( entity.getId(), ver2.getId() ); + Assert.assertEquals( entity.getSampleValue(), ver2.getSampleValue() ); + Assert.assertEquals( entity.getType().getType(), ver2.getType().getType() ); + Assert.assertEquals( entity.getType().getDescription(), ver2.getType().getDescription() ); + } - @Test - public void testHistoryOfType() { - // given - ClassType type = new ClassType(typeId, "initial description"); + @Test + public void testHistoryOfType() { + // given + ClassType type = new ClassType( typeId, "initial description" ); - // when - ClassType ver1 = getAuditReader().find(ClassType.class, typeId, 1); + // when + ClassType ver1 = getAuditReader().find( ClassType.class, typeId, 1 ); - // then - Assert.assertEquals(type, ver1); - Assert.assertEquals(type.getDescription(), ver1.getDescription()); + // then + Assert.assertEquals( type, ver1 ); + Assert.assertEquals( type.getDescription(), ver1.getDescription() ); - // given - type.setDescription("modified description"); + // given + type.setDescription( "modified description" ); - // when - ClassType ver2 = getAuditReader().find(ClassType.class, typeId, 2); + // when + ClassType ver2 = getAuditReader().find( ClassType.class, typeId, 2 ); - // then - Assert.assertEquals(type, ver2); - Assert.assertEquals(type.getDescription(), ver2.getDescription()); - } + // then + Assert.assertEquals( type, ver2 ); + Assert.assertEquals( type.getDescription(), ver2.getDescription() ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/idclass/RelationalClassId.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/idclass/RelationalClassId.java index a158b9b177..8cf8de32ea 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/idclass/RelationalClassId.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/idclass/RelationalClassId.java @@ -6,55 +6,63 @@ import java.io.Serializable; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class RelationalClassId implements Serializable { - private Long id; - private ClassType type; + private Long id; + private ClassType type; - public RelationalClassId() { - } + public RelationalClassId() { + } - public RelationalClassId(Long id, ClassType type) { - this.id = id; - this.type = type; - } + public RelationalClassId(Long id, ClassType type) { + this.id = id; + this.type = type; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof RelationalClassId)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof RelationalClassId) ) { + return false; + } - RelationalClassId that = (RelationalClassId) o; + RelationalClassId that = (RelationalClassId) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (type != null ? !type.equals(that.type) : that.type != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( type != null ? !type.equals( that.type ) : that.type != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (type != null ? type.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (type != null ? type.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "RelationalClassId(id = " + id + ", type = " + type + ")"; - } + @Override + public String toString() { + return "RelationalClassId(id = " + id + ", type = " + type + ")"; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public ClassType getType() { - return type; - } + public ClassType getType() { + return type; + } - public void setType(ClassType type) { - this.type = type; - } + public void setType(ClassType type) { + this.type = type; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/idclass/SampleClass.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/idclass/SampleClass.java index a5dd4df63a..4658e6de02 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/idclass/SampleClass.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/idclass/SampleClass.java @@ -1,6 +1,5 @@ package org.hibernate.envers.test.integration.ids.idclass; -import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; @@ -8,6 +7,7 @@ import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -18,79 +18,89 @@ import org.hibernate.envers.Audited; @Entity @IdClass(RelationalClassId.class) public class SampleClass implements Serializable { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @Id - @ManyToOne(fetch = FetchType.LAZY, optional = false) - @JoinColumn(name = "ClassTypeName", referencedColumnName = "Name", - insertable = true, updatable = true, nullable = false) - private ClassType type; + @Id + @ManyToOne(fetch = FetchType.LAZY, optional = false) + @JoinColumn(name = "ClassTypeName", referencedColumnName = "Name", + insertable = true, updatable = true, nullable = false) + private ClassType type; - private String sampleValue; + private String sampleValue; - public SampleClass() { - } + public SampleClass() { + } - public SampleClass(ClassType type) { - this.type = type; - } + public SampleClass(ClassType type) { + this.type = type; + } - public SampleClass(Long id, ClassType type) { - this.id = id; - this.type = type; - } + public SampleClass(Long id, ClassType type) { + this.id = id; + this.type = type; + } - public SampleClass(Long id, ClassType type, String sampleValue) { - this.id = id; - this.type = type; - this.sampleValue = sampleValue; - } + public SampleClass(Long id, ClassType type, String sampleValue) { + this.id = id; + this.type = type; + this.sampleValue = sampleValue; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SampleClass)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SampleClass) ) { + return false; + } - SampleClass sampleClass = (SampleClass) o; + SampleClass sampleClass = (SampleClass) o; - if (id != null ? !id.equals(sampleClass.id) : sampleClass.id != null) return false; - if (type != null ? !type.equals(sampleClass.type) : sampleClass.type != null) return false; - if (sampleValue != null ? !sampleValue.equals(sampleClass.sampleValue) : sampleClass.sampleValue != null) return false; + if ( id != null ? !id.equals( sampleClass.id ) : sampleClass.id != null ) { + return false; + } + if ( type != null ? !type.equals( sampleClass.type ) : sampleClass.type != null ) { + return false; + } + if ( sampleValue != null ? !sampleValue.equals( sampleClass.sampleValue ) : sampleClass.sampleValue != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (type != null ? type.hashCode() : 0); - result = 31 * result + (sampleValue != null ? sampleValue.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (type != null ? type.hashCode() : 0); + result = 31 * result + (sampleValue != null ? sampleValue.hashCode() : 0); + return result; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public ClassType getType() { - return type; - } + public ClassType getType() { + return type; + } - public void setType(ClassType type) { - this.type = type; - } + public void setType(ClassType type) { + this.type = type; + } - public String getSampleValue() { - return sampleValue; - } + public String getSampleValue() { + return sampleValue; + } - public void setSampleValue(String sampleValue) { - this.sampleValue = sampleValue; - } + public void setSampleValue(String sampleValue) { + this.sampleValue = sampleValue; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/protectedmodifier/ProtectedConstructorEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/protectedmodifier/ProtectedConstructorEntity.java index bc05df0635..d1d17f41f4 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/protectedmodifier/ProtectedConstructorEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/protectedmodifier/ProtectedConstructorEntity.java @@ -1,8 +1,8 @@ package org.hibernate.envers.test.integration.ids.protectedmodifier; -import java.io.Serializable; import javax.persistence.EmbeddedId; import javax.persistence.Entity; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -25,20 +25,30 @@ public class ProtectedConstructorEntity implements Serializable { } public boolean equals(Object o) { - if ( this == o ) return true; - if ( !( o instanceof ProtectedConstructorEntity ) ) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof ProtectedConstructorEntity) ) { + return false; + } ProtectedConstructorEntity that = (ProtectedConstructorEntity) o; - if ( wrappedStringId != null ? !wrappedStringId.equals( that.wrappedStringId ) : that.wrappedStringId != null ) return false; - if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) return false; + if ( wrappedStringId != null ? + !wrappedStringId.equals( that.wrappedStringId ) : + that.wrappedStringId != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } return true; } public int hashCode() { - int result = ( wrappedStringId != null ? wrappedStringId.hashCode() : 0 ); - result = 31 * result + ( str1 != null ? str1.hashCode() : 0 ); + int result = (wrappedStringId != null ? wrappedStringId.hashCode() : 0); + result = 31 * result + (str1 != null ? str1.hashCode() : 0); return result; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/protectedmodifier/ProtectedConstructorTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/protectedmodifier/ProtectedConstructorTest.java index 7a8f69fe6d..72a5b5baa8 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/protectedmodifier/ProtectedConstructorTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/protectedmodifier/ProtectedConstructorTest.java @@ -1,14 +1,15 @@ package org.hibernate.envers.test.integration.ids.protectedmodifier; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.List; -import javax.persistence.EntityManager; + +import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; +import org.hibernate.envers.test.Priority; import org.junit.Assert; import org.junit.Test; -import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; -import org.hibernate.envers.test.Priority; import org.hibernate.testing.TestForIssue; /** @@ -16,11 +17,15 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-7934") public class ProtectedConstructorTest extends BaseEnversJPAFunctionalTestCase { - private final ProtectedConstructorEntity testEntity = new ProtectedConstructorEntity( new WrappedStringId( "embeddedStringId" ), "string" ); + private final ProtectedConstructorEntity testEntity = new ProtectedConstructorEntity( + new WrappedStringId( + "embeddedStringId" + ), "string" + ); @Override protected Class[] getAnnotatedClasses() { - return new Class[] { WrappedStringId.class, ProtectedConstructorEntity.class }; + return new Class[] {WrappedStringId.class, ProtectedConstructorEntity.class}; } @Test @@ -36,7 +41,9 @@ public class ProtectedConstructorTest extends BaseEnversJPAFunctionalTestCase { @Test public void testAuditEntityInstantiation() { - List result = getAuditReader().createQuery().forEntitiesAtRevision( ProtectedConstructorEntity.class, 1 ).getResultList(); + List result = getAuditReader().createQuery() + .forEntitiesAtRevision( ProtectedConstructorEntity.class, 1 ) + .getResultList(); Assert.assertEquals( Arrays.asList( testEntity ), result ); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/protectedmodifier/WrappedStringId.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/protectedmodifier/WrappedStringId.java index 0c06d8b42f..4e2a528ec1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/protectedmodifier/WrappedStringId.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/ids/protectedmodifier/WrappedStringId.java @@ -1,7 +1,7 @@ package org.hibernate.envers.test.integration.ids.protectedmodifier; -import java.io.Serializable; import javax.persistence.Embeddable; +import java.io.Serializable; @Embeddable public class WrappedStringId implements Serializable { @@ -21,10 +21,14 @@ public class WrappedStringId implements Serializable { } public boolean equals(Object o) { - if ( this == o ) return true; - if ( o == null || getClass() != o.getClass() ) return false; + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } WrappedStringId that = (WrappedStringId) o; - return !( id != null ? !id.equals( that.id ) : that.id != null ); + return !(id != null ? !id.equals( that.id ) : that.id != null); } public int hashCode() { diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ChildAuditing.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ChildAuditing.java index 599d9e96b1..839f83d7be 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ChildAuditing.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ChildAuditing.java @@ -24,71 +24,71 @@ package org.hibernate.envers.test.integration.inheritance.joined; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class ChildAuditing extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ChildEntity.class, ParentEntity.class }; - } + return new Class[] {ChildEntity.class, ParentEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - id1 = 1; + id1 = 1; - // Rev 1 - em.getTransaction().begin(); - ChildEntity ce = new ChildEntity(id1, "x", 1l); - em.persist(ce); - em.getTransaction().commit(); + // Rev 1 + em.getTransaction().begin(); + ChildEntity ce = new ChildEntity( id1, "x", 1l ); + em.persist( ce ); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); - ce = em.find(ChildEntity.class, id1); - ce.setData("y"); - ce.setNumVal(2l); - em.getTransaction().commit(); - } + // Rev 2 + em.getTransaction().begin(); + ce = em.find( ChildEntity.class, id1 ); + ce.setData( "y" ); + ce.setNumVal( 2l ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(ChildEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( ChildEntity.class, id1 ) ); + } - @Test - public void testHistoryOfChildId1() { - ChildEntity ver1 = new ChildEntity(id1, "x", 1l); - ChildEntity ver2 = new ChildEntity(id1, "y", 2l); + @Test + public void testHistoryOfChildId1() { + ChildEntity ver1 = new ChildEntity( id1, "x", 1l ); + ChildEntity ver2 = new ChildEntity( id1, "y", 2l ); - assert getAuditReader().find(ChildEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(ChildEntity.class, id1, 2).equals(ver2); + assert getAuditReader().find( ChildEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( ChildEntity.class, id1, 2 ).equals( ver2 ); - assert getAuditReader().find(ParentEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(ParentEntity.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( ParentEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( ParentEntity.class, id1, 2 ).equals( ver2 ); + } - @Test - public void testPolymorphicQuery() { - ChildEntity childVer1 = new ChildEntity(id1, "x", 1l); + @Test + public void testPolymorphicQuery() { + ChildEntity childVer1 = new ChildEntity( id1, "x", 1l ); - assert getAuditReader().createQuery().forEntitiesAtRevision(ChildEntity.class, 1).getSingleResult() - .equals(childVer1); + assert getAuditReader().createQuery().forEntitiesAtRevision( ChildEntity.class, 1 ).getSingleResult() + .equals( childVer1 ); - assert getAuditReader().createQuery().forEntitiesAtRevision(ParentEntity.class, 1).getSingleResult() - .equals(childVer1); - } + assert getAuditReader().createQuery().forEntitiesAtRevision( ParentEntity.class, 1 ).getSingleResult() + .equals( childVer1 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ChildEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ChildEntity.java index fc68fa982a..37fe522296 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ChildEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ChildEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.joined; + import javax.persistence.Basic; import javax.persistence.Entity; @@ -34,44 +35,52 @@ import org.hibernate.envers.Audited; @Entity @Audited public class ChildEntity extends ParentEntity { - @Basic - private Long numVal; + @Basic + private Long numVal; - public ChildEntity() { - } + public ChildEntity() { + } - public ChildEntity(Integer id, String data, Long numVal) { - super(id, data); - this.numVal = numVal; - } + public ChildEntity(Integer id, String data, Long numVal) { + super( id, data ); + this.numVal = numVal; + } - public Long getNumVal() { - return numVal; - } + public Long getNumVal() { + return numVal; + } - public void setNumVal(Long numVal) { - this.numVal = numVal; - } + public void setNumVal(Long numVal) { + this.numVal = numVal; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ChildEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ChildEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ChildEntity childEntity = (ChildEntity) o; + ChildEntity childEntity = (ChildEntity) o; - if (numVal != null ? !numVal.equals(childEntity.numVal) : childEntity.numVal != null) return false; + if ( numVal != null ? !numVal.equals( childEntity.numVal ) : childEntity.numVal != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (numVal != null ? numVal.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (numVal != null ? numVal.hashCode() : 0); + return result; + } - public String toString() { - return "ChildEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; - } + public String toString() { + return "ChildEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ChildNullAuditing.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ChildNullAuditing.java index 91dd71299e..e1058fdd2d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ChildNullAuditing.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ChildNullAuditing.java @@ -24,71 +24,71 @@ package org.hibernate.envers.test.integration.inheritance.joined; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class ChildNullAuditing extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ChildEntity.class, ParentEntity.class }; - } + return new Class[] {ChildEntity.class, ParentEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - id1 = 1; + id1 = 1; - // Rev 1 - em.getTransaction().begin(); - ChildEntity ce = new ChildEntity(id1, "x", null); - em.persist(ce); - em.getTransaction().commit(); + // Rev 1 + em.getTransaction().begin(); + ChildEntity ce = new ChildEntity( id1, "x", null ); + em.persist( ce ); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); - ce = em.find(ChildEntity.class, id1); - ce.setData(null); - ce.setNumVal(2l); - em.getTransaction().commit(); - } + // Rev 2 + em.getTransaction().begin(); + ce = em.find( ChildEntity.class, id1 ); + ce.setData( null ); + ce.setNumVal( 2l ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(ChildEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( ChildEntity.class, id1 ) ); + } - @Test - public void testHistoryOfChildId1() { - ChildEntity ver1 = new ChildEntity(id1, "x", null); - ChildEntity ver2 = new ChildEntity(id1, null, 2l); + @Test + public void testHistoryOfChildId1() { + ChildEntity ver1 = new ChildEntity( id1, "x", null ); + ChildEntity ver2 = new ChildEntity( id1, null, 2l ); - assert getAuditReader().find(ChildEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(ChildEntity.class, id1, 2).equals(ver2); + assert getAuditReader().find( ChildEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( ChildEntity.class, id1, 2 ).equals( ver2 ); - assert getAuditReader().find(ParentEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(ParentEntity.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( ParentEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( ParentEntity.class, id1, 2 ).equals( ver2 ); + } - @Test - public void testPolymorphicQuery() { - ChildEntity childVer1 = new ChildEntity(id1, "x", null); + @Test + public void testPolymorphicQuery() { + ChildEntity childVer1 = new ChildEntity( id1, "x", null ); - assert getAuditReader().createQuery().forEntitiesAtRevision(ChildEntity.class, 1).getSingleResult() - .equals(childVer1); + assert getAuditReader().createQuery().forEntitiesAtRevision( ChildEntity.class, 1 ).getSingleResult() + .equals( childVer1 ); - assert getAuditReader().createQuery().forEntitiesAtRevision(ParentEntity.class, 1).getSingleResult() - .equals(childVer1); - } + assert getAuditReader().createQuery().forEntitiesAtRevision( ParentEntity.class, 1 ).getSingleResult() + .equals( childVer1 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ParentAuditing.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ParentAuditing.java index 91c91bf0e8..e38d0889e5 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ParentAuditing.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ParentAuditing.java @@ -24,72 +24,72 @@ package org.hibernate.envers.test.integration.inheritance.joined; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class ParentAuditing extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ChildEntity.class, ParentEntity.class }; - } + return new Class[] {ChildEntity.class, ParentEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - id1 = 1; + id1 = 1; - // Rev 1 - em.getTransaction().begin(); - ParentEntity pe = new ParentEntity(id1, "x"); - em.persist(pe); - em.getTransaction().commit(); + // Rev 1 + em.getTransaction().begin(); + ParentEntity pe = new ParentEntity( id1, "x" ); + em.persist( pe ); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); - pe = em.find(ParentEntity.class, id1); - pe.setData("y"); - em.getTransaction().commit(); - } + // Rev 2 + em.getTransaction().begin(); + pe = em.find( ParentEntity.class, id1 ); + pe.setData( "y" ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(ParentEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( ParentEntity.class, id1 ) ); + } - @Test - public void testHistoryOfChildId1() { - assert getAuditReader().find(ChildEntity.class, id1, 1) == null; - assert getAuditReader().find(ChildEntity.class, id1, 2) == null; - } + @Test + public void testHistoryOfChildId1() { + assert getAuditReader().find( ChildEntity.class, id1, 1 ) == null; + assert getAuditReader().find( ChildEntity.class, id1, 2 ) == null; + } - @Test - public void testHistoryOfParentId1() { - ParentEntity ver1 = new ParentEntity(id1, "x"); - ParentEntity ver2 = new ParentEntity(id1, "y"); + @Test + public void testHistoryOfParentId1() { + ParentEntity ver1 = new ParentEntity( id1, "x" ); + ParentEntity ver2 = new ParentEntity( id1, "y" ); - assert getAuditReader().find(ParentEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(ParentEntity.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( ParentEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( ParentEntity.class, id1, 2 ).equals( ver2 ); + } - @Test - public void testPolymorphicQuery() { - ParentEntity parentVer1 = new ParentEntity(id1, "x"); + @Test + public void testPolymorphicQuery() { + ParentEntity parentVer1 = new ParentEntity( id1, "x" ); - assert getAuditReader().createQuery().forEntitiesAtRevision(ParentEntity.class, 1).getSingleResult() - .equals(parentVer1); - assert getAuditReader().createQuery().forEntitiesAtRevision(ChildEntity.class, 1) - .getResultList().size() == 0; - } + assert getAuditReader().createQuery().forEntitiesAtRevision( ParentEntity.class, 1 ).getSingleResult() + .equals( parentVer1 ); + assert getAuditReader().createQuery().forEntitiesAtRevision( ChildEntity.class, 1 ) + .getResultList().size() == 0; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ParentEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ParentEntity.java index eaa731b5d6..5e95eac3b2 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ParentEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/ParentEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.joined; + import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.Id; @@ -38,56 +39,64 @@ import org.hibernate.envers.Audited; @Inheritance(strategy = InheritanceType.JOINED) @Audited public class ParentEntity { - @Id - private Integer id; + @Id + private Integer id; - @Basic - private String data; + @Basic + private String data; - public ParentEntity() { - } + public ParentEntity() { + } - public ParentEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public ParentEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ParentEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ParentEntity) ) { + return false; + } - ParentEntity that = (ParentEntity) o; + ParentEntity that = (ParentEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ParentEntity(id = " + getId() + ", data = " + getData() + ")"; - } + public String toString() { + return "ParentEntity(id = " + getId() + ", data = " + getData() + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/childrelation/ChildIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/childrelation/ChildIngEntity.java index c4b019ecca..0c3a429abb 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/childrelation/ChildIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/childrelation/ChildIngEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.joined.childrelation; + import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.ManyToOne; @@ -35,55 +36,63 @@ import org.hibernate.envers.Audited; @Entity @Audited public class ChildIngEntity extends ParentNotIngEntity { - @Basic - private Long numVal; + @Basic + private Long numVal; - @ManyToOne - private ReferencedEntity referenced; + @ManyToOne + private ReferencedEntity referenced; - public ChildIngEntity() { - } + public ChildIngEntity() { + } - public ChildIngEntity(Integer id, String data, Long numVal) { - super(id, data); - this.numVal = numVal; - } + public ChildIngEntity(Integer id, String data, Long numVal) { + super( id, data ); + this.numVal = numVal; + } - public Long getNumVal() { - return numVal; - } + public Long getNumVal() { + return numVal; + } - public void setNumVal(Long numVal) { - this.numVal = numVal; - } + public void setNumVal(Long numVal) { + this.numVal = numVal; + } - public ReferencedEntity getReferenced() { - return referenced; - } + public ReferencedEntity getReferenced() { + return referenced; + } - public void setReferenced(ReferencedEntity referenced) { - this.referenced = referenced; - } + public void setReferenced(ReferencedEntity referenced) { + this.referenced = referenced; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ChildIngEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ChildIngEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ChildIngEntity childEntity = (ChildIngEntity) o; + ChildIngEntity childEntity = (ChildIngEntity) o; - if (numVal != null ? !numVal.equals(childEntity.numVal) : childEntity.numVal != null) return false; + if ( numVal != null ? !numVal.equals( childEntity.numVal ) : childEntity.numVal != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (numVal != null ? numVal.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (numVal != null ? numVal.hashCode() : 0); + return result; + } - public String toString() { - return "ChildIngEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; - } + public String toString() { + return "ChildIngEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/childrelation/ChildReferencing.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/childrelation/ChildReferencing.java index 553370f11f..bf83568fed 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/childrelation/ChildReferencing.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/childrelation/ChildReferencing.java @@ -24,100 +24,104 @@ package org.hibernate.envers.test.integration.inheritance.joined.childrelation; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class ChildReferencing extends BaseEnversJPAFunctionalTestCase { - private Integer re_id1; - private Integer re_id2; - private Integer c_id; + private Integer re_id1; + private Integer re_id2; + private Integer c_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ChildIngEntity.class, ParentNotIngEntity.class, ReferencedEntity.class }; - } + return new Class[] {ChildIngEntity.class, ParentNotIngEntity.class, ReferencedEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - re_id1 = 1; - re_id2 = 10; - c_id = 100; + re_id1 = 1; + re_id2 = 10; + c_id = 100; - // Rev 1 - em.getTransaction().begin(); + // Rev 1 + em.getTransaction().begin(); - ReferencedEntity re1 = new ReferencedEntity(re_id1); - em.persist(re1); + ReferencedEntity re1 = new ReferencedEntity( re_id1 ); + em.persist( re1 ); - ReferencedEntity re2 = new ReferencedEntity(re_id2); - em.persist(re2); + ReferencedEntity re2 = new ReferencedEntity( re_id2 ); + em.persist( re2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); + // Rev 2 + em.getTransaction().begin(); - re1 = em.find(ReferencedEntity.class, re_id1); + re1 = em.find( ReferencedEntity.class, re_id1 ); - ChildIngEntity cie = new ChildIngEntity(c_id, "y", 1l); - cie.setReferenced(re1); - em.persist(cie); - c_id = cie.getId(); + ChildIngEntity cie = new ChildIngEntity( c_id, "y", 1l ); + cie.setReferenced( re1 ); + em.persist( cie ); + c_id = cie.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 3 - em.getTransaction().begin(); + // Rev 3 + em.getTransaction().begin(); - re2 = em.find(ReferencedEntity.class, re_id2); - cie = em.find(ChildIngEntity.class, c_id); + re2 = em.find( ReferencedEntity.class, re_id2 ); + cie = em.find( ChildIngEntity.class, c_id ); - cie.setReferenced(re2); + cie.setReferenced( re2 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(ReferencedEntity.class, re_id1)); - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(ReferencedEntity.class, re_id2)); - assert Arrays.asList(2, 3).equals(getAuditReader().getRevisions(ChildIngEntity.class, c_id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( ReferencedEntity.class, re_id1 ) ); + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( ReferencedEntity.class, re_id2 ) ); + assert Arrays.asList( 2, 3 ).equals( getAuditReader().getRevisions( ChildIngEntity.class, c_id ) ); + } - @Test - public void testHistoryOfReferencedCollection1() { - assert getAuditReader().find(ReferencedEntity.class, re_id1, 1).getReferencing().size() == 0; - assert getAuditReader().find(ReferencedEntity.class, re_id1, 2).getReferencing().equals( - TestTools.makeSet(new ChildIngEntity(c_id, "y", 1l))); - assert getAuditReader().find(ReferencedEntity.class, re_id1, 3).getReferencing().size() == 0; - } + @Test + public void testHistoryOfReferencedCollection1() { + assert getAuditReader().find( ReferencedEntity.class, re_id1, 1 ).getReferencing().size() == 0; + assert getAuditReader().find( ReferencedEntity.class, re_id1, 2 ).getReferencing().equals( + TestTools.makeSet( new ChildIngEntity( c_id, "y", 1l ) ) + ); + assert getAuditReader().find( ReferencedEntity.class, re_id1, 3 ).getReferencing().size() == 0; + } - @Test - public void testHistoryOfReferencedCollection2() { - assert getAuditReader().find(ReferencedEntity.class, re_id2, 1).getReferencing().size() == 0; - assert getAuditReader().find(ReferencedEntity.class, re_id2, 2).getReferencing().size() == 0; - assert getAuditReader().find(ReferencedEntity.class, re_id2, 3).getReferencing().equals( - TestTools.makeSet(new ChildIngEntity(c_id, "y", 1l))); - } + @Test + public void testHistoryOfReferencedCollection2() { + assert getAuditReader().find( ReferencedEntity.class, re_id2, 1 ).getReferencing().size() == 0; + assert getAuditReader().find( ReferencedEntity.class, re_id2, 2 ).getReferencing().size() == 0; + assert getAuditReader().find( ReferencedEntity.class, re_id2, 3 ).getReferencing().equals( + TestTools.makeSet( new ChildIngEntity( c_id, "y", 1l ) ) + ); + } - @Test - public void testChildHistory() { - assert getAuditReader().find(ChildIngEntity.class, c_id, 1) == null; - assert getAuditReader().find(ChildIngEntity.class, c_id, 2).getReferenced().equals( - new ReferencedEntity(re_id1)); - assert getAuditReader().find(ChildIngEntity.class, c_id, 3).getReferenced().equals( - new ReferencedEntity(re_id2)); - } + @Test + public void testChildHistory() { + assert getAuditReader().find( ChildIngEntity.class, c_id, 1 ) == null; + assert getAuditReader().find( ChildIngEntity.class, c_id, 2 ).getReferenced().equals( + new ReferencedEntity( re_id1 ) + ); + assert getAuditReader().find( ChildIngEntity.class, c_id, 3 ).getReferenced().equals( + new ReferencedEntity( re_id2 ) + ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/childrelation/ParentNotIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/childrelation/ParentNotIngEntity.java index 3e60f965d1..a496ef6582 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/childrelation/ParentNotIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/childrelation/ParentNotIngEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.joined.childrelation; + import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.Id; @@ -38,56 +39,64 @@ import org.hibernate.envers.Audited; @Inheritance(strategy = InheritanceType.JOINED) @Audited public class ParentNotIngEntity { - @Id - private Integer id; + @Id + private Integer id; - @Basic - private String data; + @Basic + private String data; - public ParentNotIngEntity() { - } + public ParentNotIngEntity() { + } - public ParentNotIngEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public ParentNotIngEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ParentNotIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ParentNotIngEntity) ) { + return false; + } - ParentNotIngEntity that = (ParentNotIngEntity) o; + ParentNotIngEntity that = (ParentNotIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ParentNotIngEntity(id = " + getId() + ", data = " + getData() + ")"; - } + public String toString() { + return "ParentNotIngEntity(id = " + getId() + ", data = " + getData() + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/childrelation/ReferencedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/childrelation/ReferencedEntity.java index 46f84e9c05..81778b25ba 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/childrelation/ReferencedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/childrelation/ReferencedEntity.java @@ -23,10 +23,11 @@ */ package org.hibernate.envers.test.integration.inheritance.joined.childrelation; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.util.Set; import org.hibernate.envers.Audited; @@ -36,51 +37,57 @@ import org.hibernate.envers.Audited; @Entity @Audited public class ReferencedEntity { - @Id - private Integer id; + @Id + private Integer id; - @OneToMany(mappedBy = "referenced") - private Set referencing; + @OneToMany(mappedBy = "referenced") + private Set referencing; - public ReferencedEntity(Integer id) { - this.id = id; - } + public ReferencedEntity(Integer id) { + this.id = id; + } - public ReferencedEntity() { - } + public ReferencedEntity() { + } - public Set getReferencing() { - return referencing; - } + public Set getReferencing() { + return referencing; + } - public void setReferencing(Set referencing) { - this.referencing = referencing; - } + public void setReferencing(Set referencing) { + this.referencing = referencing; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ReferencedEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ReferencedEntity) ) { + return false; + } - ReferencedEntity that = (ReferencedEntity) o; + ReferencedEntity that = (ReferencedEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - return id; - } + public int hashCode() { + return id; + } - public String toString() { - return "ReferencedEntity(id = " + getId() + ")"; - } + public String toString() { + return "ReferencedEntity(id = " + getId() + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/emptychild/EmptyChildAuditing.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/emptychild/EmptyChildAuditing.java index 6b445ec732..31953adb33 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/emptychild/EmptyChildAuditing.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/emptychild/EmptyChildAuditing.java @@ -24,70 +24,70 @@ package org.hibernate.envers.test.integration.inheritance.joined.emptychild; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class EmptyChildAuditing extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { EmptyChildEntity.class, ParentEntity.class }; - } + return new Class[] {EmptyChildEntity.class, ParentEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - id1 = 1; + id1 = 1; - // Rev 1 - em.getTransaction().begin(); - EmptyChildEntity pe = new EmptyChildEntity(id1, "x"); - em.persist(pe); - em.getTransaction().commit(); + // Rev 1 + em.getTransaction().begin(); + EmptyChildEntity pe = new EmptyChildEntity( id1, "x" ); + em.persist( pe ); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); - pe = em.find(EmptyChildEntity.class, id1); - pe.setData("y"); - em.getTransaction().commit(); - } + // Rev 2 + em.getTransaction().begin(); + pe = em.find( EmptyChildEntity.class, id1 ); + pe.setData( "y" ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(EmptyChildEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( EmptyChildEntity.class, id1 ) ); + } - @Test - public void testHistoryOfChildId1() { - EmptyChildEntity ver1 = new EmptyChildEntity(id1, "x"); - EmptyChildEntity ver2 = new EmptyChildEntity(id1, "y"); + @Test + public void testHistoryOfChildId1() { + EmptyChildEntity ver1 = new EmptyChildEntity( id1, "x" ); + EmptyChildEntity ver2 = new EmptyChildEntity( id1, "y" ); - assert getAuditReader().find(EmptyChildEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(EmptyChildEntity.class, id1, 2).equals(ver2); + assert getAuditReader().find( EmptyChildEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( EmptyChildEntity.class, id1, 2 ).equals( ver2 ); - assert getAuditReader().find(ParentEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(ParentEntity.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( ParentEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( ParentEntity.class, id1, 2 ).equals( ver2 ); + } - @Test - public void testPolymorphicQuery() { - EmptyChildEntity childVer1 = new EmptyChildEntity(id1, "x"); + @Test + public void testPolymorphicQuery() { + EmptyChildEntity childVer1 = new EmptyChildEntity( id1, "x" ); - assert getAuditReader().createQuery().forEntitiesAtRevision(EmptyChildEntity.class, 1).getSingleResult() - .equals(childVer1); + assert getAuditReader().createQuery().forEntitiesAtRevision( EmptyChildEntity.class, 1 ).getSingleResult() + .equals( childVer1 ); - assert getAuditReader().createQuery().forEntitiesAtRevision(ParentEntity.class, 1).getSingleResult() - .equals(childVer1); - } + assert getAuditReader().createQuery().forEntitiesAtRevision( ParentEntity.class, 1 ).getSingleResult() + .equals( childVer1 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/emptychild/EmptyChildEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/emptychild/EmptyChildEntity.java index 60c1323b40..3644001ead 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/emptychild/EmptyChildEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/emptychild/EmptyChildEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.joined.emptychild; + import javax.persistence.Entity; import org.hibernate.envers.Audited; @@ -37,6 +38,6 @@ public class EmptyChildEntity extends ParentEntity { } public EmptyChildEntity(Integer id, String data) { - super(id, data); + super( id, data ); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/emptychild/ParentEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/emptychild/ParentEntity.java index e4ac929d4d..bea7991354 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/emptychild/ParentEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/emptychild/ParentEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.joined.emptychild; + import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.Id; @@ -38,56 +39,64 @@ import org.hibernate.envers.Audited; @Inheritance(strategy = InheritanceType.JOINED) @Audited public abstract class ParentEntity { - @Id - private Integer id; + @Id + private Integer id; - @Basic - private String data; + @Basic + private String data; - public ParentEntity() { - } + public ParentEntity() { + } - public ParentEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public ParentEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ParentEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ParentEntity) ) { + return false; + } - ParentEntity that = (ParentEntity) o; + ParentEntity that = (ParentEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ParentEntity(id = " + getId() + ", data = " + getData() + ")"; - } + public String toString() { + return "ParentEntity(id = " + getId() + ", data = " + getData() + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/notownedrelation/Address.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/notownedrelation/Address.java index 900af7ad69..1979f6dfc1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/notownedrelation/Address.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/notownedrelation/Address.java @@ -23,10 +23,11 @@ */ package org.hibernate.envers.test.integration.inheritance.joined.notownedrelation; -import java.io.Serializable; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToOne; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -41,15 +42,15 @@ public class Address implements Serializable { @ManyToOne private Contact contact; - public Address() { - } + public Address() { + } - public Address(Long id, String address1) { - this.id = id; - this.address1 = address1; - } + public Address(Long id, String address1) { + this.id = id; + this.address1 = address1; + } - public Long getId() { + public Long getId() { return id; } @@ -73,26 +74,34 @@ public class Address implements Serializable { this.contact = contact; } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Address)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Address) ) { + return false; + } - Address address = (Address) o; + Address address = (Address) o; - if (address1 != null ? !address1.equals(address.address1) : address.address1 != null) return false; - if (id != null ? !id.equals(address.id) : address.id != null) return false; + if ( address1 != null ? !address1.equals( address.address1 ) : address.address1 != null ) { + return false; + } + if ( id != null ? !id.equals( address.id ) : address.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (address1 != null ? address1.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (address1 != null ? address1.hashCode() : 0); + return result; + } - public String toString() { - return "Address(id = " + getId() + ", address1 = " + getAddress1() + ")"; - } + public String toString() { + return "Address(id = " + getId() + ", address1 = " + getAddress1() + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/notownedrelation/Contact.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/notownedrelation/Contact.java index 7eb136ada5..fb47233e4d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/notownedrelation/Contact.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/notownedrelation/Contact.java @@ -23,53 +23,58 @@ */ package org.hibernate.envers.test.integration.inheritance.joined.notownedrelation; -import java.io.Serializable; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.OneToMany; +import java.io.Serializable; +import java.util.Set; import org.hibernate.envers.Audited; @Entity -@Inheritance(strategy=InheritanceType.JOINED) +@Inheritance(strategy = InheritanceType.JOINED) @Audited public class Contact implements Serializable { - @Id - private Long id; + @Id + private Long id; - private String email; + private String email; - @OneToMany(mappedBy="contact") - private Set
      addresses; + @OneToMany(mappedBy = "contact") + private Set
      addresses; - public Contact() { - } + public Contact() { + } - public Contact(Long id, String email) { - this.id = id; - this.email = email; - } + public Contact(Long id, String email) { + this.id = id; + this.email = email; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } public String getEmail() { - return email; - } - public void setEmail(String email) { - this.email = email; - } + return email; + } - public Set
      getAddresses() { - return addresses; - } - public void setAddresses(Set
      addresses) { - this.addresses = addresses; - } + public void setEmail(String email) { + this.email = email; + } + + public Set
      getAddresses() { + return addresses; + } + + public void setAddresses(Set
      addresses) { + this.addresses = addresses; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/notownedrelation/NotOwnedBidirectional.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/notownedrelation/NotOwnedBidirectional.java index 0a088aab98..3d0ef4f614 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/notownedrelation/NotOwnedBidirectional.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/notownedrelation/NotOwnedBidirectional.java @@ -24,91 +24,95 @@ package org.hibernate.envers.test.integration.inheritance.joined.notownedrelation; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class NotOwnedBidirectional extends BaseEnversJPAFunctionalTestCase { - private Long pc_id; - private Long a1_id; - private Long a2_id; + private Long pc_id; + private Long a1_id; + private Long a2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { Address.class, Contact.class, PersonalContact.class }; - } + return new Class[] {Address.class, Contact.class, PersonalContact.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - pc_id = 1l; - a1_id = 10l; - a2_id = 100l; + pc_id = 1l; + a1_id = 10l; + a2_id = 100l; - // Rev 1 - em.getTransaction().begin(); + // Rev 1 + em.getTransaction().begin(); - PersonalContact pc = new PersonalContact(pc_id, "e", "f"); + PersonalContact pc = new PersonalContact( pc_id, "e", "f" ); - Address a1 = new Address(a1_id, "a1"); - a1.setContact(pc); + Address a1 = new Address( a1_id, "a1" ); + a1.setContact( pc ); - em.persist(pc); - em.persist(a1); + em.persist( pc ); + em.persist( a1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); + // Rev 2 + em.getTransaction().begin(); - pc = em.find(PersonalContact.class, pc_id); + pc = em.find( PersonalContact.class, pc_id ); - Address a2 = new Address(a2_id, "a2"); - a2.setContact(pc); + Address a2 = new Address( a2_id, "a2" ); + a2.setContact( pc ); - em.persist(a2); + em.persist( a2 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(Contact.class, pc_id)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(PersonalContact.class, pc_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( Contact.class, pc_id ) ); + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( PersonalContact.class, pc_id ) ); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(Address.class, a1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(Address.class, a1_id)); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( Address.class, a1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( Address.class, a1_id ) ); - assert Arrays.asList(2).equals(getAuditReader().getRevisions(Address.class, a2_id)); - assert Arrays.asList(2).equals(getAuditReader().getRevisions(Address.class, a2_id)); - } + assert Arrays.asList( 2 ).equals( getAuditReader().getRevisions( Address.class, a2_id ) ); + assert Arrays.asList( 2 ).equals( getAuditReader().getRevisions( Address.class, a2_id ) ); + } - @Test - public void testHistoryOfContact() { - assert getAuditReader().find(Contact.class, pc_id, 1).getAddresses().equals( - TestTools.makeSet(new Address(a1_id, "a1"))); + @Test + public void testHistoryOfContact() { + assert getAuditReader().find( Contact.class, pc_id, 1 ).getAddresses().equals( + TestTools.makeSet( new Address( a1_id, "a1" ) ) + ); - assert getAuditReader().find(Contact.class, pc_id, 2).getAddresses().equals( - TestTools.makeSet(new Address(a1_id, "a1"), new Address(a2_id, "a2"))); - } + assert getAuditReader().find( Contact.class, pc_id, 2 ).getAddresses().equals( + TestTools.makeSet( new Address( a1_id, "a1" ), new Address( a2_id, "a2" ) ) + ); + } - @Test - public void testHistoryOfPersonalContact() { - System.out.println(getAuditReader().find(PersonalContact.class, pc_id, 1).getAddresses()); - assert getAuditReader().find(PersonalContact.class, pc_id, 1).getAddresses().equals( - TestTools.makeSet(new Address(a1_id, "a1"))); + @Test + public void testHistoryOfPersonalContact() { + System.out.println( getAuditReader().find( PersonalContact.class, pc_id, 1 ).getAddresses() ); + assert getAuditReader().find( PersonalContact.class, pc_id, 1 ).getAddresses().equals( + TestTools.makeSet( new Address( a1_id, "a1" ) ) + ); - assert getAuditReader().find(PersonalContact.class, pc_id, 2).getAddresses().equals( - TestTools.makeSet(new Address(a1_id, "a1"), new Address(a2_id, "a2"))); - } + assert getAuditReader().find( PersonalContact.class, pc_id, 2 ).getAddresses().equals( + TestTools.makeSet( new Address( a1_id, "a1" ), new Address( a2_id, "a2" ) ) + ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/notownedrelation/PersonalContact.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/notownedrelation/PersonalContact.java index 49c795aa68..e79b952e1c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/notownedrelation/PersonalContact.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/notownedrelation/PersonalContact.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.joined.notownedrelation; + import javax.persistence.Entity; import org.hibernate.envers.Audited; @@ -30,21 +31,21 @@ import org.hibernate.envers.Audited; @Entity @Audited public class PersonalContact extends Contact { - private String firstname; + private String firstname; - public PersonalContact() { - } + public PersonalContact() { + } - public PersonalContact(Long id, String email, String firstname) { - super(id, email); - this.firstname = firstname; - } + public PersonalContact(Long id, String email, String firstname) { + super( id, email ); + this.firstname = firstname; + } - public String getFirstname() { + public String getFirstname() { return firstname; } - public void setFirstname(String firstname) { + public void setFirstname(String firstname) { this.firstname = firstname; } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/primarykeyjoin/ChildPrimaryKeyJoinAuditing.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/primarykeyjoin/ChildPrimaryKeyJoinAuditing.java index 09733bc72d..2d96f5b568 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/primarykeyjoin/ChildPrimaryKeyJoinAuditing.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/primarykeyjoin/ChildPrimaryKeyJoinAuditing.java @@ -24,82 +24,88 @@ package org.hibernate.envers.test.integration.inheritance.joined.primarykeyjoin; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.inheritance.joined.ParentEntity; import org.hibernate.mapping.Column; +import org.junit.Assert; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class ChildPrimaryKeyJoinAuditing extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ChildPrimaryKeyJoinEntity.class, ParentEntity.class }; - } + return new Class[] {ChildPrimaryKeyJoinEntity.class, ParentEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - id1 = 1; + id1 = 1; - // Rev 1 - em.getTransaction().begin(); - ChildPrimaryKeyJoinEntity ce = new ChildPrimaryKeyJoinEntity(id1, "x", 1l); - em.persist(ce); - em.getTransaction().commit(); + // Rev 1 + em.getTransaction().begin(); + ChildPrimaryKeyJoinEntity ce = new ChildPrimaryKeyJoinEntity( id1, "x", 1l ); + em.persist( ce ); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); - ce = em.find(ChildPrimaryKeyJoinEntity.class, id1); - ce.setData("y"); - ce.setNumVal(2l); - em.getTransaction().commit(); - } + // Rev 2 + em.getTransaction().begin(); + ce = em.find( ChildPrimaryKeyJoinEntity.class, id1 ); + ce.setData( "y" ); + ce.setNumVal( 2l ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(ChildPrimaryKeyJoinEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( ChildPrimaryKeyJoinEntity.class, id1 ) ); + } - @Test - public void testHistoryOfChildId1() { - ChildPrimaryKeyJoinEntity ver1 = new ChildPrimaryKeyJoinEntity(id1, "x", 1l); - ChildPrimaryKeyJoinEntity ver2 = new ChildPrimaryKeyJoinEntity(id1, "y", 2l); + @Test + public void testHistoryOfChildId1() { + ChildPrimaryKeyJoinEntity ver1 = new ChildPrimaryKeyJoinEntity( id1, "x", 1l ); + ChildPrimaryKeyJoinEntity ver2 = new ChildPrimaryKeyJoinEntity( id1, "y", 2l ); - assert getAuditReader().find(ChildPrimaryKeyJoinEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(ChildPrimaryKeyJoinEntity.class, id1, 2).equals(ver2); + assert getAuditReader().find( ChildPrimaryKeyJoinEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( ChildPrimaryKeyJoinEntity.class, id1, 2 ).equals( ver2 ); - assert getAuditReader().find(ParentEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(ParentEntity.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( ParentEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( ParentEntity.class, id1, 2 ).equals( ver2 ); + } - @Test - public void testPolymorphicQuery() { - ChildPrimaryKeyJoinEntity childVer1 = new ChildPrimaryKeyJoinEntity(id1, "x", 1l); + @Test + public void testPolymorphicQuery() { + ChildPrimaryKeyJoinEntity childVer1 = new ChildPrimaryKeyJoinEntity( id1, "x", 1l ); - assert getAuditReader().createQuery().forEntitiesAtRevision(ChildPrimaryKeyJoinEntity.class, 1).getSingleResult() - .equals(childVer1); + assert getAuditReader().createQuery() + .forEntitiesAtRevision( ChildPrimaryKeyJoinEntity.class, 1 ) + .getSingleResult() + .equals( childVer1 ); - assert getAuditReader().createQuery().forEntitiesAtRevision(ParentEntity.class, 1).getSingleResult() - .equals(childVer1); - } + assert getAuditReader().createQuery().forEntitiesAtRevision( ParentEntity.class, 1 ).getSingleResult() + .equals( childVer1 ); + } - @Test - public void testChildIdColumnName() { - Assert.assertEquals("other_id", - ((Column) getCfg() - .getClassMapping("org.hibernate.envers.test.integration.inheritance.joined.primarykeyjoin.ChildPrimaryKeyJoinEntity_AUD") - .getKey().getColumnIterator().next()).getName()); - } + @Test + public void testChildIdColumnName() { + Assert.assertEquals( + "other_id", + ((Column) getCfg() + .getClassMapping( + "org.hibernate.envers.test.integration.inheritance.joined.primarykeyjoin.ChildPrimaryKeyJoinEntity_AUD" + ) + .getKey().getColumnIterator().next()).getName() + ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/primarykeyjoin/ChildPrimaryKeyJoinEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/primarykeyjoin/ChildPrimaryKeyJoinEntity.java index af82e9fd83..80f5dbaa1d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/primarykeyjoin/ChildPrimaryKeyJoinEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/primarykeyjoin/ChildPrimaryKeyJoinEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.joined.primarykeyjoin; + import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.PrimaryKeyJoinColumn; @@ -37,45 +38,55 @@ import org.hibernate.envers.test.integration.inheritance.joined.ParentEntity; @Audited @PrimaryKeyJoinColumn(name = "other_id") public class ChildPrimaryKeyJoinEntity extends ParentEntity { - @Basic - private Long namVal; + @Basic + private Long namVal; - public ChildPrimaryKeyJoinEntity() { - } + public ChildPrimaryKeyJoinEntity() { + } - public ChildPrimaryKeyJoinEntity(Integer id, String data, Long namVal) { - super(id, data); - this.namVal = namVal; - } + public ChildPrimaryKeyJoinEntity(Integer id, String data, Long namVal) { + super( id, data ); + this.namVal = namVal; + } - public Long getNumVal() { - return namVal; - } + public Long getNumVal() { + return namVal; + } - public void setNumVal(Long namVal) { - this.namVal = namVal; - } + public void setNumVal(Long namVal) { + this.namVal = namVal; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ChildPrimaryKeyJoinEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ChildPrimaryKeyJoinEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ChildPrimaryKeyJoinEntity childPrimaryKeyJoinEntity = (ChildPrimaryKeyJoinEntity) o; + ChildPrimaryKeyJoinEntity childPrimaryKeyJoinEntity = (ChildPrimaryKeyJoinEntity) o; - //noinspection RedundantIfStatement - if (namVal != null ? !namVal.equals(childPrimaryKeyJoinEntity.namVal) : childPrimaryKeyJoinEntity.namVal != null) return false; + //noinspection RedundantIfStatement + if ( namVal != null ? + !namVal.equals( childPrimaryKeyJoinEntity.namVal ) : + childPrimaryKeyJoinEntity.namVal != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (namVal != null ? namVal.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (namVal != null ? namVal.hashCode() : 0); + return result; + } - public String toString() { - return "CPKJE(id = " + getId() + ", data = " + getData() + ", namVal = " + namVal + ")"; - } + public String toString() { + return "CPKJE(id = " + getId() + ", data = " + getData() + ", namVal = " + namVal + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/ChildIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/ChildIngEntity.java index 8fb953c167..afa542f99a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/ChildIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/ChildIngEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.joined.relation; + import javax.persistence.Basic; import javax.persistence.Entity; @@ -34,44 +35,52 @@ import org.hibernate.envers.Audited; @Entity @Audited public class ChildIngEntity extends ParentIngEntity { - @Basic - private Long numVal; + @Basic + private Long numVal; - public ChildIngEntity() { - } + public ChildIngEntity() { + } - public ChildIngEntity(Integer id, String data, Long numVal) { - super(id, data); - this.numVal = numVal; - } + public ChildIngEntity(Integer id, String data, Long numVal) { + super( id, data ); + this.numVal = numVal; + } - public Long getNumVal() { - return numVal; - } + public Long getNumVal() { + return numVal; + } - public void setNumVal(Long numVal) { - this.numVal = numVal; - } + public void setNumVal(Long numVal) { + this.numVal = numVal; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ChildIngEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ChildIngEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ChildIngEntity childEntity = (ChildIngEntity) o; + ChildIngEntity childEntity = (ChildIngEntity) o; - if (numVal != null ? !numVal.equals(childEntity.numVal) : childEntity.numVal != null) return false; + if ( numVal != null ? !numVal.equals( childEntity.numVal ) : childEntity.numVal != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (numVal != null ? numVal.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (numVal != null ? numVal.hashCode() : 0); + return result; + } - public String toString() { - return "ChildIngEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; - } + public String toString() { + return "ChildIngEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/ParentIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/ParentIngEntity.java index 9e7f4edd4b..7ac7a5ee9e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/ParentIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/ParentIngEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.joined.relation; + import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.Id; @@ -39,67 +40,75 @@ import org.hibernate.envers.Audited; @Inheritance(strategy = InheritanceType.JOINED) @Audited public class ParentIngEntity { - @Id - private Integer id; + @Id + private Integer id; - @Basic - private String data; + @Basic + private String data; - @ManyToOne - private ReferencedEntity referenced; + @ManyToOne + private ReferencedEntity referenced; - public ParentIngEntity() { - } + public ParentIngEntity() { + } - public ParentIngEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public ParentIngEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public ReferencedEntity getReferenced() { - return referenced; - } + public ReferencedEntity getReferenced() { + return referenced; + } - public void setReferenced(ReferencedEntity referenced) { - this.referenced = referenced; - } + public void setReferenced(ReferencedEntity referenced) { + this.referenced = referenced; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ParentIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ParentIngEntity) ) { + return false; + } - ParentIngEntity that = (ParentIngEntity) o; + ParentIngEntity that = (ParentIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ParentIngEntity(id = " + getId() + ", data = " + getData() + ")"; - } + public String toString() { + return "ParentIngEntity(id = " + getId() + ", data = " + getData() + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/ParentReferencingChildTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/ParentReferencingChildTest.java index 3c401f25ea..10824484fa 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/ParentReferencingChildTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/ParentReferencingChildTest.java @@ -1,14 +1,15 @@ package org.hibernate.envers.test.integration.inheritance.joined.relation; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.tools.TestTools; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -16,61 +17,71 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-3843") public class ParentReferencingChildTest extends BaseEnversJPAFunctionalTestCase { - Person expLukaszRev1 = null; - Role expAdminRev1 = null; + Person expLukaszRev1 = null; + Role expAdminRev1 = null; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { Person.class, Role.class, RightsSubject.class }; - } + return new Class[] {Person.class, Role.class, RightsSubject.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 1 - em.getTransaction().begin(); - Person lukasz = new Person(); - lukasz.setName("Lukasz"); - lukasz.setGroup("IT"); - em.persist(lukasz); - Role admin = new Role(); - admin.setName("Admin"); - admin.setGroup("Confidential"); - lukasz.getRoles().add(admin); - admin.getMembers().add(lukasz); - em.persist(admin); - em.getTransaction().commit(); + // Revision 1 + em.getTransaction().begin(); + Person lukasz = new Person(); + lukasz.setName( "Lukasz" ); + lukasz.setGroup( "IT" ); + em.persist( lukasz ); + Role admin = new Role(); + admin.setName( "Admin" ); + admin.setGroup( "Confidential" ); + lukasz.getRoles().add( admin ); + admin.getMembers().add( lukasz ); + em.persist( admin ); + em.getTransaction().commit(); - expLukaszRev1 = new Person(lukasz.getId(), "IT", "Lukasz"); - expAdminRev1 = new Role(admin.getId(), "Confidential", "Admin"); - } + expLukaszRev1 = new Person( lukasz.getId(), "IT", "Lukasz" ); + expAdminRev1 = new Role( admin.getId(), "Confidential", "Admin" ); + } - @Test - public void testRevisionsCounts() { - Assert.assertEquals(Arrays.asList(1), getAuditReader().getRevisions(Person.class, expLukaszRev1.getId())); - Assert.assertEquals(Arrays.asList(1), getAuditReader().getRevisions(RightsSubject.class, expLukaszRev1.getId())); + @Test + public void testRevisionsCounts() { + Assert.assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( Person.class, expLukaszRev1.getId() ) ); + Assert.assertEquals( + Arrays.asList( 1 ), getAuditReader().getRevisions( + RightsSubject.class, + expLukaszRev1.getId() + ) + ); - Assert.assertEquals(Arrays.asList(1), getAuditReader().getRevisions(Role.class, expAdminRev1.getId())); - Assert.assertEquals(Arrays.asList(1), getAuditReader().getRevisions(RightsSubject.class, expAdminRev1.getId())); - } + Assert.assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( Role.class, expAdminRev1.getId() ) ); + Assert.assertEquals( + Arrays.asList( 1 ), getAuditReader().getRevisions( + RightsSubject.class, + expAdminRev1.getId() + ) + ); + } - @Test - public void testHistoryOfLukasz() { - Person lukaszRev1 = getAuditReader().find(Person.class, expLukaszRev1.getId(), 1); - RightsSubject rightsSubjectLukaszRev1 = getAuditReader().find(RightsSubject.class, expLukaszRev1.getId(), 1); + @Test + public void testHistoryOfLukasz() { + Person lukaszRev1 = getAuditReader().find( Person.class, expLukaszRev1.getId(), 1 ); + RightsSubject rightsSubjectLukaszRev1 = getAuditReader().find( RightsSubject.class, expLukaszRev1.getId(), 1 ); - Assert.assertEquals(expLukaszRev1, lukaszRev1); - Assert.assertEquals(TestTools.makeSet(expAdminRev1), lukaszRev1.getRoles()); - Assert.assertEquals(TestTools.makeSet(expAdminRev1), rightsSubjectLukaszRev1.getRoles()); - } + Assert.assertEquals( expLukaszRev1, lukaszRev1 ); + Assert.assertEquals( TestTools.makeSet( expAdminRev1 ), lukaszRev1.getRoles() ); + Assert.assertEquals( TestTools.makeSet( expAdminRev1 ), rightsSubjectLukaszRev1.getRoles() ); + } - @Test - public void testHistoryOfAdmin() { - Role adminRev1 = getAuditReader().find(Role.class, expAdminRev1.getId(), 1); + @Test + public void testHistoryOfAdmin() { + Role adminRev1 = getAuditReader().find( Role.class, expAdminRev1.getId(), 1 ); - Assert.assertEquals(expAdminRev1, adminRev1); - Assert.assertEquals(TestTools.makeSet(expLukaszRev1), adminRev1.getMembers()); - } + Assert.assertEquals( expAdminRev1, adminRev1 ); + Assert.assertEquals( TestTools.makeSet( expLukaszRev1 ), adminRev1.getMembers() ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/Person.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/Person.java index eac7475862..299f33d628 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/Person.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/Person.java @@ -10,45 +10,53 @@ import org.hibernate.envers.Audited; @Entity @Audited public class Person extends RightsSubject { - private String name; + private String name; - public Person() { - } + public Person() { + } - public Person(Long id, String group, String name) { - super(id, group); - this.name = name; - } + public Person(Long id, String group, String name) { + super( id, group ); + this.name = name; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Person)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Person) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - Person person = (Person) o; + Person person = (Person) o; - if (name != null ? !name.equals(person.name) : person.name != null) return false; + if ( name != null ? !name.equals( person.name ) : person.name != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (name != null ? name.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (name != null ? name.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "Person(" + super.toString() + ", name = " + name + ")"; - } + @Override + public String toString() { + return "Person(" + super.toString() + ", name = " + name + ")"; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/PolymorphicCollection.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/PolymorphicCollection.java index cb5e0e561d..fc5f70c716 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/PolymorphicCollection.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/PolymorphicCollection.java @@ -24,83 +24,85 @@ package org.hibernate.envers.test.integration.inheritance.joined.relation; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class PolymorphicCollection extends BaseEnversJPAFunctionalTestCase { - private Integer ed_id1; - private Integer c_id; - private Integer p_id; + private Integer ed_id1; + private Integer c_id; + private Integer p_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ChildIngEntity.class, ParentIngEntity.class, ReferencedEntity.class }; - } + return new Class[] {ChildIngEntity.class, ParentIngEntity.class, ReferencedEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - ed_id1 = 1; - p_id = 10; - c_id = 100; + ed_id1 = 1; + p_id = 10; + c_id = 100; - // Rev 1 - em.getTransaction().begin(); + // Rev 1 + em.getTransaction().begin(); - ReferencedEntity re = new ReferencedEntity(ed_id1); - em.persist(re); + ReferencedEntity re = new ReferencedEntity( ed_id1 ); + em.persist( re ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); + // Rev 2 + em.getTransaction().begin(); - re = em.find(ReferencedEntity.class, ed_id1); + re = em.find( ReferencedEntity.class, ed_id1 ); - ParentIngEntity pie = new ParentIngEntity(p_id,"x"); - pie.setReferenced(re); - em.persist(pie); - p_id = pie.getId(); + ParentIngEntity pie = new ParentIngEntity( p_id, "x" ); + pie.setReferenced( re ); + em.persist( pie ); + p_id = pie.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 3 - em.getTransaction().begin(); + // Rev 3 + em.getTransaction().begin(); - re = em.find(ReferencedEntity.class, ed_id1); + re = em.find( ReferencedEntity.class, ed_id1 ); - ChildIngEntity cie = new ChildIngEntity(c_id, "y", 1l); - cie.setReferenced(re); - em.persist(cie); - c_id = cie.getId(); + ChildIngEntity cie = new ChildIngEntity( c_id, "y", 1l ); + cie.setReferenced( re ); + em.persist( cie ); + c_id = cie.getId(); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(ReferencedEntity.class, ed_id1)); - assert Arrays.asList(2).equals(getAuditReader().getRevisions(ParentIngEntity.class, p_id)); - assert Arrays.asList(3).equals(getAuditReader().getRevisions(ChildIngEntity.class, c_id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( ReferencedEntity.class, ed_id1 ) ); + assert Arrays.asList( 2 ).equals( getAuditReader().getRevisions( ParentIngEntity.class, p_id ) ); + assert Arrays.asList( 3 ).equals( getAuditReader().getRevisions( ChildIngEntity.class, c_id ) ); + } - @Test - public void testHistoryOfReferencedCollection() { - assert getAuditReader().find(ReferencedEntity.class, ed_id1, 1).getReferencing().size() == 0; - assert getAuditReader().find(ReferencedEntity.class, ed_id1, 2).getReferencing().equals( - TestTools.makeSet(new ParentIngEntity(p_id, "x"))); - assert getAuditReader().find(ReferencedEntity.class, ed_id1, 3).getReferencing().equals( - TestTools.makeSet(new ParentIngEntity(p_id, "x"), new ChildIngEntity(c_id, "y", 1l))); - } + @Test + public void testHistoryOfReferencedCollection() { + assert getAuditReader().find( ReferencedEntity.class, ed_id1, 1 ).getReferencing().size() == 0; + assert getAuditReader().find( ReferencedEntity.class, ed_id1, 2 ).getReferencing().equals( + TestTools.makeSet( new ParentIngEntity( p_id, "x" ) ) + ); + assert getAuditReader().find( ReferencedEntity.class, ed_id1, 3 ).getReferencing().equals( + TestTools.makeSet( new ParentIngEntity( p_id, "x" ), new ChildIngEntity( c_id, "y", 1l ) ) + ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/ReferencedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/ReferencedEntity.java index ac393f7da6..6e8e772e0f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/ReferencedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/ReferencedEntity.java @@ -23,10 +23,11 @@ */ package org.hibernate.envers.test.integration.inheritance.joined.relation; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.util.Set; import org.hibernate.envers.Audited; @@ -36,51 +37,57 @@ import org.hibernate.envers.Audited; @Entity @Audited public class ReferencedEntity { - @Id - private Integer id; + @Id + private Integer id; - @OneToMany(mappedBy = "referenced") - private Set referencing; + @OneToMany(mappedBy = "referenced") + private Set referencing; - public ReferencedEntity() { - } + public ReferencedEntity() { + } - public ReferencedEntity(Integer id) { - this.id = id; - } + public ReferencedEntity(Integer id) { + this.id = id; + } - public Set getReferencing() { - return referencing; - } + public Set getReferencing() { + return referencing; + } - public void setReferencing(Set referencing) { - this.referencing = referencing; - } + public void setReferencing(Set referencing) { + this.referencing = referencing; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ReferencedEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ReferencedEntity) ) { + return false; + } - ReferencedEntity that = (ReferencedEntity) o; + ReferencedEntity that = (ReferencedEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - return id; - } + public int hashCode() { + return id; + } - public String toString() { - return "ReferencedEntity(id = " + getId() + ")"; - } + public String toString() { + return "ReferencedEntity(id = " + getId() + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/RightsSubject.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/RightsSubject.java index 2ca029daa4..3da654283d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/RightsSubject.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/RightsSubject.java @@ -1,7 +1,5 @@ package org.hibernate.envers.test.integration.inheritance.joined.relation; -import java.util.HashSet; -import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -9,6 +7,8 @@ import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.ManyToMany; +import java.util.HashSet; +import java.util.Set; import org.hibernate.envers.Audited; @@ -19,70 +19,78 @@ import org.hibernate.envers.Audited; @Inheritance(strategy = InheritanceType.JOINED) @Audited public class RightsSubject { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - @Column(name = "APP_GROUP") - private String group; + @Column(name = "APP_GROUP") + private String group; - @ManyToMany(mappedBy="members") - private Set roles = new HashSet(); + @ManyToMany(mappedBy = "members") + private Set roles = new HashSet(); - public RightsSubject() { - } + public RightsSubject() { + } - public RightsSubject(Long id, String group) { - this.id = id; - this.group = group; - } + public RightsSubject(Long id, String group) { + this.id = id; + this.group = group; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof RightsSubject)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof RightsSubject) ) { + return false; + } - RightsSubject that = (RightsSubject) o; + RightsSubject that = (RightsSubject) o; - if (group != null ? !group.equals(that.group) : that.group != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( group != null ? !group.equals( that.group ) : that.group != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (group != null ? group.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (group != null ? group.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "RightsSubject(id = " + id + ", group = " + group + ")"; - } + @Override + public String toString() { + return "RightsSubject(id = " + id + ", group = " + group + ")"; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public Set getRoles() { - return roles; - } + public Set getRoles() { + return roles; + } - public void setRoles(Set roles) { - this.roles = roles; - } + public void setRoles(Set roles) { + this.roles = roles; + } - public String getGroup() { - return group; - } + public String getGroup() { + return group; + } - public void setGroup(String group) { - this.group = group; - } + public void setGroup(String group) { + this.group = group; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/Role.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/Role.java index ee29971c50..5beba72a86 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/Role.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/Role.java @@ -1,10 +1,10 @@ package org.hibernate.envers.test.integration.inheritance.joined.relation; -import java.util.HashSet; -import java.util.Set; import javax.persistence.Entity; import javax.persistence.ManyToMany; import javax.persistence.Table; +import java.util.HashSet; +import java.util.Set; import org.hibernate.envers.Audited; @@ -15,56 +15,64 @@ import org.hibernate.envers.Audited; @Table(name = "APP_ROLE") @Audited public class Role extends RightsSubject { - private String name; - - @ManyToMany + private String name; + + @ManyToMany private Set members = new HashSet(); - public Role() { - } + public Role() { + } - public Role(Long id, String group, String name) { - super(id, group); - this.name = name; - } + public Role(Long id, String group, String name) { + super( id, group ); + this.name = name; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Role)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Role) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - Role role = (Role) o; + Role role = (Role) o; - if (name != null ? !name.equals(role.name) : role.name != null) return false; + if ( name != null ? !name.equals( role.name ) : role.name != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (name != null ? name.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (name != null ? name.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "Role(" + super.toString() + ", name = " + name + ")"; - } + @Override + public String toString() { + return "Role(" + super.toString() + ", name = " + name + ")"; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Set getMembers() { - return members; - } + public Set getMembers() { + return members; + } - public void setMembers(Set members) { - this.members = members; - } + public void setMembers(Set members) { + this.members = members; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/AbstractContainedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/AbstractContainedEntity.java index 2cdc0c1d02..1e9a813199 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/AbstractContainedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/AbstractContainedEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.joined.relation.unidirectional; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -43,9 +44,9 @@ public abstract class AbstractContainedEntity { @Id @GeneratedValue private Long id; - - public AbstractContainedEntity() { - } + + public AbstractContainedEntity() { + } public Long getId() { return id; @@ -57,12 +58,18 @@ public abstract class AbstractContainedEntity { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof AbstractContainedEntity)) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof AbstractContainedEntity) ) { + return false; + } AbstractContainedEntity that = (AbstractContainedEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/AbstractSetEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/AbstractSetEntity.java index 33f911dddf..9eceab993d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/AbstractSetEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/AbstractSetEntity.java @@ -23,8 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.joined.relation.unidirectional; -import java.util.HashSet; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -32,6 +31,8 @@ import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.OneToMany; import javax.persistence.Table; +import java.util.HashSet; +import java.util.Set; import org.hibernate.envers.Audited; @@ -43,23 +44,23 @@ import org.hibernate.envers.Audited; @Inheritance(strategy = InheritanceType.JOINED) @Audited public abstract class AbstractSetEntity { - @Id + @Id @GeneratedValue - private Integer id; + private Integer id; - @OneToMany - private Set entities = new HashSet(); + @OneToMany + private Set entities = new HashSet(); - public AbstractSetEntity() { - } + public AbstractSetEntity() { + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } public Set getEntities() { return entities; diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/ContainedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/ContainedEntity.java index 81b99d953b..06130466f6 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/ContainedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/ContainedEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.joined.relation.unidirectional; + import javax.persistence.Entity; import javax.persistence.Table; @@ -34,5 +35,5 @@ import org.hibernate.envers.Audited; @Entity @Table(name = "Contained") @Audited -public class ContainedEntity extends AbstractContainedEntity { +public class ContainedEntity extends AbstractContainedEntity { } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/SetEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/SetEntity.java index 559a6d3640..9215585244 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/SetEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/SetEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.joined.relation.unidirectional; + import javax.persistence.Entity; import org.hibernate.envers.Audited; diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/UnidirectionalDoubleAbstract.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/UnidirectionalDoubleAbstract.java index cbab8cb8ed..b959f0fb4b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/UnidirectionalDoubleAbstract.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/joined/relation/unidirectional/UnidirectionalDoubleAbstract.java @@ -24,15 +24,15 @@ package org.hibernate.envers.test.integration.inheritance.joined.relation.unidirectional; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Set; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ @@ -48,42 +48,42 @@ public class UnidirectionalDoubleAbstract extends BaseEnversJPAFunctionalTestCas ContainedEntity.class, SetEntity.class }; - } + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Rev 1 - em.getTransaction().begin(); + // Rev 1 + em.getTransaction().begin(); - ContainedEntity cce1 = new ContainedEntity(); - em.persist(cce1); + ContainedEntity cce1 = new ContainedEntity(); + em.persist( cce1 ); SetEntity cse1 = new SetEntity(); - cse1.getEntities().add(cce1); - em.persist(cse1); + cse1.getEntities().add( cce1 ); + em.persist( cse1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); cce1_id = cce1.getId(); cse1_id = cse1.getId(); - } + } @Test - public void testRevisionsCounts() { - assert Arrays.asList(1).equals(getAuditReader().getRevisions(ContainedEntity.class, cce1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(SetEntity.class, cse1_id)); - } + public void testRevisionsCounts() { + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( ContainedEntity.class, cce1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( SetEntity.class, cse1_id ) ); + } - @Test - public void testHistoryOfReferencedCollection() { - ContainedEntity cce1 = getEntityManager().find(ContainedEntity.class, cce1_id); + @Test + public void testHistoryOfReferencedCollection() { + ContainedEntity cce1 = getEntityManager().find( ContainedEntity.class, cce1_id ); - Set entities = getAuditReader().find(SetEntity.class, cse1_id, 1).getEntities(); - assert entities.size() == 1; + Set entities = getAuditReader().find( SetEntity.class, cse1_id, 1 ).getEntities(); + assert entities.size() == 1; assert entities.iterator().next() instanceof ContainedEntity; - assert entities.contains(cce1); - } + assert entities.contains( cce1 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/MixedInheritanceStrategiesEntityTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/MixedInheritanceStrategiesEntityTest.java index e676e3659d..5b9354e76d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/MixedInheritanceStrategiesEntityTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/MixedInheritanceStrategiesEntityTest.java @@ -2,8 +2,6 @@ package org.hibernate.envers.test.integration.inheritance.mixed; import java.util.Arrays; -import org.junit.Test; - import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.inheritance.mixed.entities.AbstractActivity; @@ -13,12 +11,14 @@ import org.hibernate.envers.test.integration.inheritance.mixed.entities.Activity import org.hibernate.envers.test.integration.inheritance.mixed.entities.CheckInActivity; import org.hibernate.envers.test.integration.inheritance.mixed.entities.NormalActivity; +import org.junit.Test; + import static org.junit.Assert.assertEquals; /** * @author Michal Skowronek (mskowr at o2 pl) */ -public class MixedInheritanceStrategiesEntityTest extends BaseEnversJPAFunctionalTestCase { +public class MixedInheritanceStrategiesEntityTest extends BaseEnversJPAFunctionalTestCase { private ActivityId id2; private ActivityId id1; @@ -32,117 +32,117 @@ public class MixedInheritanceStrategiesEntityTest extends BaseEnversJPAFunctiona CheckInActivity.class, NormalActivity.class }; - } + } - @Test - @Priority(10) - public void initData() { - NormalActivity normalActivity = new NormalActivity(); - id1 = new ActivityId(1, 2); - normalActivity.setId(id1); - normalActivity.setSequenceNumber(1); + @Test + @Priority(10) + public void initData() { + NormalActivity normalActivity = new NormalActivity(); + id1 = new ActivityId( 1, 2 ); + normalActivity.setId( id1 ); + normalActivity.setSequenceNumber( 1 ); - // Revision 1 - getEntityManager().getTransaction().begin(); + // Revision 1 + getEntityManager().getTransaction().begin(); - getEntityManager().persist(normalActivity); + getEntityManager().persist( normalActivity ); - getEntityManager().getTransaction().commit(); - // Revision 2 - getEntityManager().getTransaction().begin(); + getEntityManager().getTransaction().commit(); + // Revision 2 + getEntityManager().getTransaction().begin(); - normalActivity = getEntityManager().find(NormalActivity.class, id1); - CheckInActivity checkInActivity = new CheckInActivity(); - id2 = new ActivityId(2, 3); - checkInActivity.setId(id2); - checkInActivity.setSequenceNumber(0); - checkInActivity.setDurationInMinutes(30); - checkInActivity.setRelatedActivity(normalActivity); + normalActivity = getEntityManager().find( NormalActivity.class, id1 ); + CheckInActivity checkInActivity = new CheckInActivity(); + id2 = new ActivityId( 2, 3 ); + checkInActivity.setId( id2 ); + checkInActivity.setSequenceNumber( 0 ); + checkInActivity.setDurationInMinutes( 30 ); + checkInActivity.setRelatedActivity( normalActivity ); - getEntityManager().persist(checkInActivity); + getEntityManager().persist( checkInActivity ); - getEntityManager().getTransaction().commit(); + getEntityManager().getTransaction().commit(); - // Revision 3 - normalActivity = new NormalActivity(); - id3 = new ActivityId(3, 4); - normalActivity.setId(id3); - normalActivity.setSequenceNumber(2); + // Revision 3 + normalActivity = new NormalActivity(); + id3 = new ActivityId( 3, 4 ); + normalActivity.setId( id3 ); + normalActivity.setSequenceNumber( 2 ); - getEntityManager().getTransaction().begin(); + getEntityManager().getTransaction().begin(); - getEntityManager().persist(normalActivity); + getEntityManager().persist( normalActivity ); - getEntityManager().getTransaction().commit(); + getEntityManager().getTransaction().commit(); - // Revision 4 - getEntityManager().getTransaction().begin(); + // Revision 4 + getEntityManager().getTransaction().begin(); - normalActivity = getEntityManager().find(NormalActivity.class, id3); - checkInActivity = getEntityManager().find(CheckInActivity.class, id2); - checkInActivity.setRelatedActivity(normalActivity); + normalActivity = getEntityManager().find( NormalActivity.class, id3 ); + checkInActivity = getEntityManager().find( CheckInActivity.class, id2 ); + checkInActivity.setRelatedActivity( normalActivity ); - getEntityManager().merge(checkInActivity); + getEntityManager().merge( checkInActivity ); - getEntityManager().getTransaction().commit(); - } + getEntityManager().getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assertEquals(Arrays.asList(1), getAuditReader().getRevisions(NormalActivity.class, id1)); - assertEquals(Arrays.asList(3), getAuditReader().getRevisions(NormalActivity.class, id3)); - assertEquals(Arrays.asList(2, 4), getAuditReader().getRevisions(CheckInActivity.class, id2)); - } + @Test + public void testRevisionsCounts() { + assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( NormalActivity.class, id1 ) ); + assertEquals( Arrays.asList( 3 ), getAuditReader().getRevisions( NormalActivity.class, id3 ) ); + assertEquals( Arrays.asList( 2, 4 ), getAuditReader().getRevisions( CheckInActivity.class, id2 ) ); + } - @Test - public void testCurrentStateOfCheckInActivity() { + @Test + public void testCurrentStateOfCheckInActivity() { - final CheckInActivity checkInActivity = getEntityManager().find(CheckInActivity.class, id2); - final NormalActivity normalActivity = getEntityManager().find(NormalActivity.class, id3); + final CheckInActivity checkInActivity = getEntityManager().find( CheckInActivity.class, id2 ); + final NormalActivity normalActivity = getEntityManager().find( NormalActivity.class, id3 ); - assertEquals(id2, checkInActivity.getId()); - assertEquals(0, checkInActivity.getSequenceNumber().intValue()); - assertEquals(30, checkInActivity.getDurationInMinutes().intValue()); - final Activity relatedActivity = checkInActivity.getRelatedActivity(); - assertEquals(normalActivity.getId(), relatedActivity.getId()); - assertEquals(normalActivity.getSequenceNumber(), relatedActivity.getSequenceNumber()); - } + assertEquals( id2, checkInActivity.getId() ); + assertEquals( 0, checkInActivity.getSequenceNumber().intValue() ); + assertEquals( 30, checkInActivity.getDurationInMinutes().intValue() ); + final Activity relatedActivity = checkInActivity.getRelatedActivity(); + assertEquals( normalActivity.getId(), relatedActivity.getId() ); + assertEquals( normalActivity.getSequenceNumber(), relatedActivity.getSequenceNumber() ); + } - @Test - public void testCheckCurrentStateOfNormalActivities() throws Exception { - final NormalActivity normalActivity1 = getEntityManager().find(NormalActivity.class, id1); - final NormalActivity normalActivity2 = getEntityManager().find(NormalActivity.class, id3); + @Test + public void testCheckCurrentStateOfNormalActivities() throws Exception { + final NormalActivity normalActivity1 = getEntityManager().find( NormalActivity.class, id1 ); + final NormalActivity normalActivity2 = getEntityManager().find( NormalActivity.class, id3 ); - assertEquals(id1, normalActivity1.getId()); - assertEquals(1, normalActivity1.getSequenceNumber().intValue()); - assertEquals(id3, normalActivity2.getId()); - assertEquals(2, normalActivity2.getSequenceNumber().intValue()); - } + assertEquals( id1, normalActivity1.getId() ); + assertEquals( 1, normalActivity1.getSequenceNumber().intValue() ); + assertEquals( id3, normalActivity2.getId() ); + assertEquals( 2, normalActivity2.getSequenceNumber().intValue() ); + } - @Test - public void doTestFirstRevisionOfCheckInActivity() throws Exception { - CheckInActivity checkInActivity = getAuditReader().find(CheckInActivity.class, id2, 2); - NormalActivity normalActivity = getAuditReader().find(NormalActivity.class, id1, 2); + @Test + public void doTestFirstRevisionOfCheckInActivity() throws Exception { + CheckInActivity checkInActivity = getAuditReader().find( CheckInActivity.class, id2, 2 ); + NormalActivity normalActivity = getAuditReader().find( NormalActivity.class, id1, 2 ); - assertEquals(id2, checkInActivity.getId()); - assertEquals(0, checkInActivity.getSequenceNumber().intValue()); - assertEquals(30, checkInActivity.getDurationInMinutes().intValue()); - Activity relatedActivity = checkInActivity.getRelatedActivity(); - assertEquals(normalActivity.getId(), relatedActivity.getId()); - assertEquals(normalActivity.getSequenceNumber(), relatedActivity.getSequenceNumber()); - } + assertEquals( id2, checkInActivity.getId() ); + assertEquals( 0, checkInActivity.getSequenceNumber().intValue() ); + assertEquals( 30, checkInActivity.getDurationInMinutes().intValue() ); + Activity relatedActivity = checkInActivity.getRelatedActivity(); + assertEquals( normalActivity.getId(), relatedActivity.getId() ); + assertEquals( normalActivity.getSequenceNumber(), relatedActivity.getSequenceNumber() ); + } - @Test - public void doTestSecondRevisionOfCheckInActivity() throws Exception { - CheckInActivity checkInActivity = getAuditReader().find(CheckInActivity.class, id2, 4); - NormalActivity normalActivity = getAuditReader().find(NormalActivity.class, id3, 4); + @Test + public void doTestSecondRevisionOfCheckInActivity() throws Exception { + CheckInActivity checkInActivity = getAuditReader().find( CheckInActivity.class, id2, 4 ); + NormalActivity normalActivity = getAuditReader().find( NormalActivity.class, id3, 4 ); - assertEquals(id2, checkInActivity.getId()); - assertEquals(0, checkInActivity.getSequenceNumber().intValue()); - assertEquals(30, checkInActivity.getDurationInMinutes().intValue()); - Activity relatedActivity = checkInActivity.getRelatedActivity(); - assertEquals(normalActivity.getId(), relatedActivity.getId()); - assertEquals(normalActivity.getSequenceNumber(), relatedActivity.getSequenceNumber()); - } + assertEquals( id2, checkInActivity.getId() ); + assertEquals( 0, checkInActivity.getSequenceNumber().intValue() ); + assertEquals( 30, checkInActivity.getDurationInMinutes().intValue() ); + Activity relatedActivity = checkInActivity.getRelatedActivity(); + assertEquals( normalActivity.getId(), relatedActivity.getId() ); + assertEquals( normalActivity.getSequenceNumber(), relatedActivity.getSequenceNumber() ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/AbstractActivity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/AbstractActivity.java index 23d6e5c077..85ec767bfe 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/AbstractActivity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/AbstractActivity.java @@ -12,23 +12,23 @@ import org.hibernate.envers.Audited; @Inheritance(strategy = InheritanceType.SINGLE_TABLE) public abstract class AbstractActivity implements Activity { @EmbeddedId - private ActivityId id; + private ActivityId id; - private Integer sequenceNumber; + private Integer sequenceNumber; - public ActivityId getId() { - return id; - } + public ActivityId getId() { + return id; + } - public void setId(ActivityId id) { - this.id = id; - } + public void setId(ActivityId id) { + this.id = id; + } public Integer getSequenceNumber() { - return sequenceNumber; - } + return sequenceNumber; + } - public void setSequenceNumber(Integer sequenceNumber) { - this.sequenceNumber = sequenceNumber; - } + public void setSequenceNumber(Integer sequenceNumber) { + this.sequenceNumber = sequenceNumber; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/AbstractCheckActivity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/AbstractCheckActivity.java index afc36effa7..4b8c37779b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/AbstractCheckActivity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/AbstractCheckActivity.java @@ -17,29 +17,33 @@ import org.hibernate.envers.Audited; @Entity @DiscriminatorValue(value = "CHECK") @SecondaryTable(name = "ACTIVITY_CHECK", - pkJoinColumns = {@PrimaryKeyJoinColumn(name = "ACTIVITY_ID"), - @PrimaryKeyJoinColumn(name = "ACTIVITY_ID2")}) + pkJoinColumns = { + @PrimaryKeyJoinColumn(name = "ACTIVITY_ID"), + @PrimaryKeyJoinColumn(name = "ACTIVITY_ID2") + }) public abstract class AbstractCheckActivity extends AbstractActivity { - @Column(table = "ACTIVITY_CHECK") - private Integer durationInMinutes; - @ManyToOne(targetEntity = AbstractActivity.class, cascade = CascadeType.MERGE, fetch = FetchType.LAZY) - @JoinColumns({@JoinColumn(table = "ACTIVITY_CHECK", referencedColumnName = "id"), - @JoinColumn(table = "ACTIVITY_CHECK", referencedColumnName = "id2")}) - private Activity relatedActivity; + @Column(table = "ACTIVITY_CHECK") + private Integer durationInMinutes; + @ManyToOne(targetEntity = AbstractActivity.class, cascade = CascadeType.MERGE, fetch = FetchType.LAZY) + @JoinColumns({ + @JoinColumn(table = "ACTIVITY_CHECK", referencedColumnName = "id"), + @JoinColumn(table = "ACTIVITY_CHECK", referencedColumnName = "id2") + }) + private Activity relatedActivity; - public Integer getDurationInMinutes() { - return durationInMinutes; - } + public Integer getDurationInMinutes() { + return durationInMinutes; + } - public void setDurationInMinutes(Integer durationInMinutes) { - this.durationInMinutes = durationInMinutes; - } + public void setDurationInMinutes(Integer durationInMinutes) { + this.durationInMinutes = durationInMinutes; + } - public Activity getRelatedActivity() { - return relatedActivity; - } + public Activity getRelatedActivity() { + return relatedActivity; + } - public void setRelatedActivity(Activity relatedActivity) { - this.relatedActivity = relatedActivity; - } + public void setRelatedActivity(Activity relatedActivity) { + this.relatedActivity = relatedActivity; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/Activity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/Activity.java index ee35f3926f..7db86b0c89 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/Activity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/Activity.java @@ -5,5 +5,5 @@ import java.io.Serializable; public interface Activity extends Serializable { ActivityId getId(); - Integer getSequenceNumber(); + Integer getSequenceNumber(); } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/ActivityId.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/ActivityId.java index c776f165d4..b6333b42e5 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/ActivityId.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/ActivityId.java @@ -1,7 +1,7 @@ package org.hibernate.envers.test.integration.inheritance.mixed.entities; -import java.io.Serializable; import javax.persistence.Embeddable; +import java.io.Serializable; @Embeddable public class ActivityId implements Serializable { @@ -34,14 +34,14 @@ public class ActivityId implements Serializable { @Override public boolean equals(Object obj) { - if (obj == null) { + if ( obj == null ) { return true; } - if (!(obj instanceof ActivityId)) { + if ( !(obj instanceof ActivityId) ) { return false; } ActivityId id = (ActivityId) obj; - return getId().equals(id.getId()) && getId2().equals(id.getId2()); + return getId().equals( id.getId() ) && getId2().equals( id.getId2() ); } @Override diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/CheckInActivity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/CheckInActivity.java index f5943cb2da..c8adb252b6 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/CheckInActivity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/CheckInActivity.java @@ -10,21 +10,21 @@ import org.hibernate.envers.Audited; @DiscriminatorValue(value = "CHECK_IN") public class CheckInActivity extends AbstractCheckActivity { - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof CheckInActivity)) { - return false; - } - CheckInActivity checkInActivity = (CheckInActivity) obj; - return getId().equals(checkInActivity.getId()); - } + @Override + public boolean equals(Object obj) { + if ( obj == this ) { + return true; + } + if ( !(obj instanceof CheckInActivity) ) { + return false; + } + CheckInActivity checkInActivity = (CheckInActivity) obj; + return getId().equals( checkInActivity.getId() ); + } - @Override - public int hashCode() { - return getId().hashCode(); - } + @Override + public int hashCode() { + return getId().hashCode(); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/NormalActivity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/NormalActivity.java index d389aea408..edfac4f95a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/NormalActivity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/mixed/entities/NormalActivity.java @@ -10,20 +10,20 @@ import org.hibernate.envers.Audited; @DiscriminatorValue(value = "NORMAL") public class NormalActivity extends AbstractActivity { - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof NormalActivity)) { - return false; - } - NormalActivity normalActivity = (NormalActivity) obj; - return getId().equals(normalActivity.getId()); - } + @Override + public boolean equals(Object obj) { + if ( obj == this ) { + return true; + } + if ( !(obj instanceof NormalActivity) ) { + return false; + } + NormalActivity normalActivity = (NormalActivity) obj; + return getId().equals( normalActivity.getId() ); + } - @Override - public int hashCode() { - return getId().hashCode(); - } + @Override + public int hashCode() { + return getId().hashCode(); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/ChildAuditing.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/ChildAuditing.java index ad117adbf5..fdd37c1cdd 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/ChildAuditing.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/ChildAuditing.java @@ -23,70 +23,70 @@ */ package org.hibernate.envers.test.integration.inheritance.single; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class ChildAuditing extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ChildEntity.class, ParentEntity.class }; + return new Class[] {ChildEntity.class, ParentEntity.class}; } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Rev 1 - em.getTransaction().begin(); - ChildEntity ce = new ChildEntity("x", 1l); - em.persist(ce); - id1 = ce.getId(); - em.getTransaction().commit(); + // Rev 1 + em.getTransaction().begin(); + ChildEntity ce = new ChildEntity( "x", 1l ); + em.persist( ce ); + id1 = ce.getId(); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); - ce = em.find(ChildEntity.class, id1); - ce.setData("y"); - ce.setNumVal(2l); - em.getTransaction().commit(); - } + // Rev 2 + em.getTransaction().begin(); + ce = em.find( ChildEntity.class, id1 ); + ce.setData( "y" ); + ce.setNumVal( 2l ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(ChildEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( ChildEntity.class, id1 ) ); + } - @Test - public void testHistoryOfChildId1() { - ChildEntity ver1 = new ChildEntity(id1, "x", 1l); - ChildEntity ver2 = new ChildEntity(id1, "y", 2l); + @Test + public void testHistoryOfChildId1() { + ChildEntity ver1 = new ChildEntity( id1, "x", 1l ); + ChildEntity ver2 = new ChildEntity( id1, "y", 2l ); - assert getAuditReader().find(ChildEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(ChildEntity.class, id1, 2).equals(ver2); + assert getAuditReader().find( ChildEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( ChildEntity.class, id1, 2 ).equals( ver2 ); - assert getAuditReader().find(ParentEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(ParentEntity.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( ParentEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( ParentEntity.class, id1, 2 ).equals( ver2 ); + } - @Test - public void testPolymorphicQuery() { - ChildEntity childVer1 = new ChildEntity(id1, "x", 1l); + @Test + public void testPolymorphicQuery() { + ChildEntity childVer1 = new ChildEntity( id1, "x", 1l ); - assert getAuditReader().createQuery().forEntitiesAtRevision(ChildEntity.class, 1).getSingleResult() - .equals(childVer1); + assert getAuditReader().createQuery().forEntitiesAtRevision( ChildEntity.class, 1 ).getSingleResult() + .equals( childVer1 ); - assert getAuditReader().createQuery().forEntitiesAtRevision(ParentEntity.class, 1).getSingleResult() - .equals(childVer1); - } + assert getAuditReader().createQuery().forEntitiesAtRevision( ParentEntity.class, 1 ).getSingleResult() + .equals( childVer1 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/ChildEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/ChildEntity.java index e12dd722e4..292f6f9043 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/ChildEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/ChildEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.inheritance.single; + import javax.persistence.Basic; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @@ -35,49 +36,57 @@ import org.hibernate.envers.Audited; @DiscriminatorValue("2") @Audited public class ChildEntity extends ParentEntity { - @Basic - private Long numVal; + @Basic + private Long numVal; - public ChildEntity() { - } + public ChildEntity() { + } - public ChildEntity(String data, Long numVal) { - super(data); - this.numVal = numVal; - } + public ChildEntity(String data, Long numVal) { + super( data ); + this.numVal = numVal; + } - public ChildEntity(Integer id, String data, Long numVal) { - super(id, data); - this.numVal = numVal; - } + public ChildEntity(Integer id, String data, Long numVal) { + super( id, data ); + this.numVal = numVal; + } - public Long getNumVal() { - return numVal; - } + public Long getNumVal() { + return numVal; + } - public void setNumVal(Long numVal) { - this.numVal = numVal; - } + public void setNumVal(Long numVal) { + this.numVal = numVal; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ChildEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ChildEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ChildEntity childEntity = (ChildEntity) o; + ChildEntity childEntity = (ChildEntity) o; - if (numVal != null ? !numVal.equals(childEntity.numVal) : childEntity.numVal != null) return false; + if ( numVal != null ? !numVal.equals( childEntity.numVal ) : childEntity.numVal != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (numVal != null ? numVal.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (numVal != null ? numVal.hashCode() : 0); + return result; + } - public String toString() { - return "ChildPrimaryKeyJoinEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; - } + public String toString() { + return "ChildPrimaryKeyJoinEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/ParentAuditing.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/ParentAuditing.java index e1869bb8af..d2e1e731a5 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/ParentAuditing.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/ParentAuditing.java @@ -23,71 +23,71 @@ */ package org.hibernate.envers.test.integration.inheritance.single; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class ParentAuditing extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ChildEntity.class, ParentEntity.class }; - } + return new Class[] {ChildEntity.class, ParentEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Rev 1 - em.getTransaction().begin(); - ParentEntity pe = new ParentEntity("x"); - em.persist(pe); - id1 = pe.getId(); - em.getTransaction().commit(); + // Rev 1 + em.getTransaction().begin(); + ParentEntity pe = new ParentEntity( "x" ); + em.persist( pe ); + id1 = pe.getId(); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); - pe = em.find(ParentEntity.class, id1); - pe.setData("y"); - em.getTransaction().commit(); - } + // Rev 2 + em.getTransaction().begin(); + pe = em.find( ParentEntity.class, id1 ); + pe.setData( "y" ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(ParentEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( ParentEntity.class, id1 ) ); + } - @Test - public void testHistoryOfChildId1() { - assert getAuditReader().find(ChildEntity.class, id1, 1) == null; - assert getAuditReader().find(ChildEntity.class, id1, 2) == null; - } + @Test + public void testHistoryOfChildId1() { + assert getAuditReader().find( ChildEntity.class, id1, 1 ) == null; + assert getAuditReader().find( ChildEntity.class, id1, 2 ) == null; + } - @Test - public void testHistoryOfParentId1() { - ParentEntity ver1 = new ParentEntity(id1, "x"); - ParentEntity ver2 = new ParentEntity(id1, "y"); + @Test + public void testHistoryOfParentId1() { + ParentEntity ver1 = new ParentEntity( id1, "x" ); + ParentEntity ver2 = new ParentEntity( id1, "y" ); - assert getAuditReader().find(ParentEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(ParentEntity.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( ParentEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( ParentEntity.class, id1, 2 ).equals( ver2 ); + } - @Test - public void testPolymorphicQuery() { - ParentEntity parentVer1 = new ParentEntity(id1, "x"); + @Test + public void testPolymorphicQuery() { + ParentEntity parentVer1 = new ParentEntity( id1, "x" ); - assert getAuditReader().createQuery().forEntitiesAtRevision(ParentEntity.class, 1).getSingleResult() - .equals(parentVer1); - assert getAuditReader().createQuery().forEntitiesAtRevision(ChildEntity.class, 1) - .getResultList().size() == 0; - } + assert getAuditReader().createQuery().forEntitiesAtRevision( ParentEntity.class, 1 ).getSingleResult() + .equals( parentVer1 ); + assert getAuditReader().createQuery().forEntitiesAtRevision( ChildEntity.class, 1 ) + .getResultList().size() == 0; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/ParentEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/ParentEntity.java index e3104ddd15..7a5085b729 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/ParentEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/ParentEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.inheritance.single; + import javax.persistence.Basic; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; @@ -43,61 +44,69 @@ import org.hibernate.envers.Audited; @DiscriminatorValue("1") @Audited public class ParentEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Basic - private String data; + @Basic + private String data; - public ParentEntity() { - } + public ParentEntity() { + } - public ParentEntity(String data) { - this.data = data; - } + public ParentEntity(String data) { + this.data = data; + } - public ParentEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public ParentEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ParentEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ParentEntity) ) { + return false; + } - ParentEntity that = (ParentEntity) o; + ParentEntity that = (ParentEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ParentEntity(id = " + getId() + ", data = " + getData() + ")"; - } + public String toString() { + return "ParentEntity(id = " + getId() + ", data = " + getData() + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/childrelation/ChildIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/childrelation/ChildIngEntity.java index 2e8c0075b0..2539270640 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/childrelation/ChildIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/childrelation/ChildIngEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.inheritance.single.childrelation; + import javax.persistence.Basic; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @@ -36,60 +37,68 @@ import org.hibernate.envers.Audited; @DiscriminatorValue("2") @Audited public class ChildIngEntity extends ParentNotIngEntity { - @Basic - private Long numVal; + @Basic + private Long numVal; - @ManyToOne - private ReferencedEntity referenced; + @ManyToOne + private ReferencedEntity referenced; - public ChildIngEntity() { - } + public ChildIngEntity() { + } - public ChildIngEntity(String data, Long numVal) { - super(data); - this.numVal = numVal; - } + public ChildIngEntity(String data, Long numVal) { + super( data ); + this.numVal = numVal; + } - public ChildIngEntity(Integer id, String data, Long numVal) { - super(id, data); - this.numVal = numVal; - } + public ChildIngEntity(Integer id, String data, Long numVal) { + super( id, data ); + this.numVal = numVal; + } - public Long getNumVal() { - return numVal; - } + public Long getNumVal() { + return numVal; + } - public void setNumVal(Long numVal) { - this.numVal = numVal; - } + public void setNumVal(Long numVal) { + this.numVal = numVal; + } - public ReferencedEntity getReferenced() { - return referenced; - } + public ReferencedEntity getReferenced() { + return referenced; + } - public void setReferenced(ReferencedEntity referenced) { - this.referenced = referenced; - } + public void setReferenced(ReferencedEntity referenced) { + this.referenced = referenced; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ChildIngEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ChildIngEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ChildIngEntity childEntity = (ChildIngEntity) o; + ChildIngEntity childEntity = (ChildIngEntity) o; - if (numVal != null ? !numVal.equals(childEntity.numVal) : childEntity.numVal != null) return false; + if ( numVal != null ? !numVal.equals( childEntity.numVal ) : childEntity.numVal != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (numVal != null ? numVal.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (numVal != null ? numVal.hashCode() : 0); + return result; + } - public String toString() { - return "ChildIngEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; - } + public String toString() { + return "ChildIngEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/childrelation/ChildReferencing.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/childrelation/ChildReferencing.java index c1d901a5e6..980bf517ad 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/childrelation/ChildReferencing.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/childrelation/ChildReferencing.java @@ -23,98 +23,102 @@ */ package org.hibernate.envers.test.integration.inheritance.single.childrelation; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class ChildReferencing extends BaseEnversJPAFunctionalTestCase { - private Integer re_id1; - private Integer re_id2; - private Integer c_id; + private Integer re_id1; + private Integer re_id2; + private Integer c_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ChildIngEntity.class, ParentNotIngEntity.class, ReferencedEntity.class }; - } + return new Class[] {ChildIngEntity.class, ParentNotIngEntity.class, ReferencedEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Rev 1 - em.getTransaction().begin(); + // Rev 1 + em.getTransaction().begin(); - ReferencedEntity re1 = new ReferencedEntity(); - em.persist(re1); - re_id1 = re1.getId(); + ReferencedEntity re1 = new ReferencedEntity(); + em.persist( re1 ); + re_id1 = re1.getId(); - ReferencedEntity re2 = new ReferencedEntity(); - em.persist(re2); - re_id2 = re2.getId(); + ReferencedEntity re2 = new ReferencedEntity(); + em.persist( re2 ); + re_id2 = re2.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); + // Rev 2 + em.getTransaction().begin(); - re1 = em.find(ReferencedEntity.class, re_id1); + re1 = em.find( ReferencedEntity.class, re_id1 ); - ChildIngEntity cie = new ChildIngEntity("y", 1l); - cie.setReferenced(re1); - em.persist(cie); - c_id = cie.getId(); + ChildIngEntity cie = new ChildIngEntity( "y", 1l ); + cie.setReferenced( re1 ); + em.persist( cie ); + c_id = cie.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 3 - em.getTransaction().begin(); + // Rev 3 + em.getTransaction().begin(); - re2 = em.find(ReferencedEntity.class, re_id2); - cie = em.find(ChildIngEntity.class, c_id); + re2 = em.find( ReferencedEntity.class, re_id2 ); + cie = em.find( ChildIngEntity.class, c_id ); - cie.setReferenced(re2); + cie.setReferenced( re2 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(ReferencedEntity.class, re_id1)); - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(ReferencedEntity.class, re_id2)); - assert Arrays.asList(2, 3).equals(getAuditReader().getRevisions(ChildIngEntity.class, c_id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( ReferencedEntity.class, re_id1 ) ); + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( ReferencedEntity.class, re_id2 ) ); + assert Arrays.asList( 2, 3 ).equals( getAuditReader().getRevisions( ChildIngEntity.class, c_id ) ); + } - @Test - public void testHistoryOfReferencedCollection1() { - assert getAuditReader().find(ReferencedEntity.class, re_id1, 1).getReferencing().size() == 0; - assert getAuditReader().find(ReferencedEntity.class, re_id1, 2).getReferencing().equals( - TestTools.makeSet(new ChildIngEntity(c_id, "y", 1l))); - assert getAuditReader().find(ReferencedEntity.class, re_id1, 3).getReferencing().size() == 0; - } + @Test + public void testHistoryOfReferencedCollection1() { + assert getAuditReader().find( ReferencedEntity.class, re_id1, 1 ).getReferencing().size() == 0; + assert getAuditReader().find( ReferencedEntity.class, re_id1, 2 ).getReferencing().equals( + TestTools.makeSet( new ChildIngEntity( c_id, "y", 1l ) ) + ); + assert getAuditReader().find( ReferencedEntity.class, re_id1, 3 ).getReferencing().size() == 0; + } - @Test - public void testHistoryOfReferencedCollection2() { - assert getAuditReader().find(ReferencedEntity.class, re_id2, 1).getReferencing().size() == 0; - assert getAuditReader().find(ReferencedEntity.class, re_id2, 2).getReferencing().size() == 0; - assert getAuditReader().find(ReferencedEntity.class, re_id2, 3).getReferencing().equals( - TestTools.makeSet(new ChildIngEntity(c_id, "y", 1l))); - } + @Test + public void testHistoryOfReferencedCollection2() { + assert getAuditReader().find( ReferencedEntity.class, re_id2, 1 ).getReferencing().size() == 0; + assert getAuditReader().find( ReferencedEntity.class, re_id2, 2 ).getReferencing().size() == 0; + assert getAuditReader().find( ReferencedEntity.class, re_id2, 3 ).getReferencing().equals( + TestTools.makeSet( new ChildIngEntity( c_id, "y", 1l ) ) + ); + } - @Test - public void testChildHistory() { - assert getAuditReader().find(ChildIngEntity.class, c_id, 1) == null; - assert getAuditReader().find(ChildIngEntity.class, c_id, 2).getReferenced().equals( - new ReferencedEntity(re_id1)); - assert getAuditReader().find(ChildIngEntity.class, c_id, 3).getReferenced().equals( - new ReferencedEntity(re_id2)); - } + @Test + public void testChildHistory() { + assert getAuditReader().find( ChildIngEntity.class, c_id, 1 ) == null; + assert getAuditReader().find( ChildIngEntity.class, c_id, 2 ).getReferenced().equals( + new ReferencedEntity( re_id1 ) + ); + assert getAuditReader().find( ChildIngEntity.class, c_id, 3 ).getReferenced().equals( + new ReferencedEntity( re_id2 ) + ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/childrelation/ParentNotIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/childrelation/ParentNotIngEntity.java index f307bc1ae6..7f36d0829c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/childrelation/ParentNotIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/childrelation/ParentNotIngEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.inheritance.single.childrelation; + import javax.persistence.Basic; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; @@ -43,61 +44,69 @@ import org.hibernate.envers.Audited; @DiscriminatorValue("1") @Audited public class ParentNotIngEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Basic - private String data; + @Basic + private String data; - public ParentNotIngEntity() { - } + public ParentNotIngEntity() { + } - public ParentNotIngEntity(String data) { - this.data = data; - } + public ParentNotIngEntity(String data) { + this.data = data; + } - public ParentNotIngEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public ParentNotIngEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ParentNotIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ParentNotIngEntity) ) { + return false; + } - ParentNotIngEntity that = (ParentNotIngEntity) o; + ParentNotIngEntity that = (ParentNotIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ParentNotIngEntity(id = " + getId() + ", data = " + getData() + ")"; - } + public String toString() { + return "ParentNotIngEntity(id = " + getId() + ", data = " + getData() + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/childrelation/ReferencedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/childrelation/ReferencedEntity.java index 4782c9f022..2da54c49fe 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/childrelation/ReferencedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/childrelation/ReferencedEntity.java @@ -22,11 +22,12 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.inheritance.single.childrelation; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.util.Set; import org.hibernate.envers.Audited; @@ -36,48 +37,54 @@ import org.hibernate.envers.Audited; @Entity @Audited public class ReferencedEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @OneToMany(mappedBy = "referenced") - private Set referencing; + @OneToMany(mappedBy = "referenced") + private Set referencing; - public ReferencedEntity(Integer id) { - this.id = id; - } + public ReferencedEntity(Integer id) { + this.id = id; + } - public ReferencedEntity() { - } + public ReferencedEntity() { + } - public Set getReferencing() { - return referencing; - } + public Set getReferencing() { + return referencing; + } - public void setReferencing(Set referencing) { - this.referencing = referencing; - } + public void setReferencing(Set referencing) { + this.referencing = referencing; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ReferencedEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ReferencedEntity) ) { + return false; + } - ReferencedEntity that = (ReferencedEntity) o; + ReferencedEntity that = (ReferencedEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - return id; - } + public int hashCode() { + return id; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/discriminatorformula/ChildEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/discriminatorformula/ChildEntity.java index ed10a22ecd..a4458d3d64 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/discriminatorformula/ChildEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/discriminatorformula/ChildEntity.java @@ -12,48 +12,56 @@ import org.hibernate.envers.Audited; @DiscriminatorValue(ClassTypeEntity.CHILD_TYPE) @Audited public class ChildEntity extends ParentEntity { - private String specificData; + private String specificData; - public ChildEntity() { - } + public ChildEntity() { + } - public ChildEntity(Long typeId, String data, String specificData) { - super(typeId, data); - this.specificData = specificData; - } + public ChildEntity(Long typeId, String data, String specificData) { + super( typeId, data ); + this.specificData = specificData; + } - public ChildEntity(Long id, Long typeId, String data, String specificData) { - super(id, typeId, data); - this.specificData = specificData; - } + public ChildEntity(Long id, Long typeId, String data, String specificData) { + super( id, typeId, data ); + this.specificData = specificData; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ChildEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ChildEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ChildEntity that = (ChildEntity) o; + ChildEntity that = (ChildEntity) o; - if (specificData != null ? !specificData.equals(that.specificData) : that.specificData != null) return false; + if ( specificData != null ? !specificData.equals( that.specificData ) : that.specificData != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (specificData != null ? specificData.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (specificData != null ? specificData.hashCode() : 0); + return result; + } - public String toString() { - return "ChildEntity(id = " + id + ", typeId = " + typeId + ", data = " + data + ", specificData = " + specificData + ")"; - } + public String toString() { + return "ChildEntity(id = " + id + ", typeId = " + typeId + ", data = " + data + ", specificData = " + specificData + ")"; + } - public String getSpecificData() { - return specificData; - } + public String getSpecificData() { + return specificData; + } - public void setSpecificData(String specificData) { - this.specificData = specificData; - } + public void setSpecificData(String specificData) { + this.specificData = specificData; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/discriminatorformula/ClassTypeEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/discriminatorformula/ClassTypeEntity.java index e3ba0f5f9e..b9f2152a65 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/discriminatorformula/ClassTypeEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/discriminatorformula/ClassTypeEntity.java @@ -9,51 +9,59 @@ import javax.persistence.Id; */ @Entity public class ClassTypeEntity { - public static final String PARENT_TYPE = "Parent"; - public static final String CHILD_TYPE = "Child"; + public static final String PARENT_TYPE = "Parent"; + public static final String CHILD_TYPE = "Child"; - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String type; + private String type; - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ClassTypeEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ClassTypeEntity) ) { + return false; + } - ClassTypeEntity that = (ClassTypeEntity) o; + ClassTypeEntity that = (ClassTypeEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (type != null ? !type.equals(that.type) : that.type != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( type != null ? !type.equals( that.type ) : that.type != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (id != null ? id.hashCode() : 0); - result = 31 * result + (type != null ? type.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (id != null ? id.hashCode() : 0); + result = 31 * result + (type != null ? type.hashCode() : 0); + return result; + } - public String toString() { - return "ClassTypeEntity(id = " + id + ", type = " + type + ")"; - } + public String toString() { + return "ClassTypeEntity(id = " + id + ", type = " + type + ")"; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/discriminatorformula/DiscriminatorFormulaTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/discriminatorformula/DiscriminatorFormulaTest.java index 7229926fe2..d471294988 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/discriminatorformula/DiscriminatorFormulaTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/discriminatorformula/DiscriminatorFormulaTest.java @@ -1,130 +1,158 @@ package org.hibernate.envers.test.integration.inheritance.single.discriminatorformula; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Iterator; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.mapping.Formula; import org.hibernate.mapping.PersistentClass; +import org.junit.Assert; +import org.junit.Test; + /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class DiscriminatorFormulaTest extends BaseEnversJPAFunctionalTestCase { - private PersistentClass parentAudit = null; - private ChildEntity childVer1 = null; - private ChildEntity childVer2 = null; - private ParentEntity parentVer1 = null; - private ParentEntity parentVer2 = null; + private PersistentClass parentAudit = null; + private ChildEntity childVer1 = null; + private ChildEntity childVer2 = null; + private ParentEntity parentVer1 = null; + private ParentEntity parentVer2 = null; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ClassTypeEntity.class, ParentEntity.class, ChildEntity.class }; - } + return new Class[] {ClassTypeEntity.class, ParentEntity.class, ChildEntity.class}; + } - @Test - @Priority(10) - public void initData() { - parentAudit = getCfg().getClassMapping("org.hibernate.envers.test.integration.inheritance.single.discriminatorformula.ParentEntity_AUD"); + @Test + @Priority(10) + public void initData() { + parentAudit = getCfg().getClassMapping( + "org.hibernate.envers.test.integration.inheritance.single.discriminatorformula.ParentEntity_AUD" + ); - EntityManager em = getEntityManager(); + EntityManager em = getEntityManager(); - // Child entity type - em.getTransaction().begin(); - ClassTypeEntity childType = new ClassTypeEntity(); - childType.setType(ClassTypeEntity.CHILD_TYPE); - em.persist(childType); - Long childTypeId = childType.getId(); - em.getTransaction().commit(); + // Child entity type + em.getTransaction().begin(); + ClassTypeEntity childType = new ClassTypeEntity(); + childType.setType( ClassTypeEntity.CHILD_TYPE ); + em.persist( childType ); + Long childTypeId = childType.getId(); + em.getTransaction().commit(); - // Parent entity type - em.getTransaction().begin(); - ClassTypeEntity parentType = new ClassTypeEntity(); - parentType.setType(ClassTypeEntity.PARENT_TYPE); - em.persist(parentType); - Long parentTypeId = parentType.getId(); - em.getTransaction().commit(); + // Parent entity type + em.getTransaction().begin(); + ClassTypeEntity parentType = new ClassTypeEntity(); + parentType.setType( ClassTypeEntity.PARENT_TYPE ); + em.persist( parentType ); + Long parentTypeId = parentType.getId(); + em.getTransaction().commit(); - // Child Rev 1 - em.getTransaction().begin(); - ChildEntity child = new ChildEntity(childTypeId, "Child data", "Child specific data"); - em.persist(child); - Long childId = child.getId(); - em.getTransaction().commit(); + // Child Rev 1 + em.getTransaction().begin(); + ChildEntity child = new ChildEntity( childTypeId, "Child data", "Child specific data" ); + em.persist( child ); + Long childId = child.getId(); + em.getTransaction().commit(); - // Parent Rev 2 - em.getTransaction().begin(); - ParentEntity parent = new ParentEntity(parentTypeId, "Parent data"); - em.persist(parent); - Long parentId = parent.getId(); - em.getTransaction().commit(); + // Parent Rev 2 + em.getTransaction().begin(); + ParentEntity parent = new ParentEntity( parentTypeId, "Parent data" ); + em.persist( parent ); + Long parentId = parent.getId(); + em.getTransaction().commit(); - // Child Rev 3 - em.getTransaction().begin(); - child = em.find(ChildEntity.class, childId); - child.setData("Child data modified"); - em.getTransaction().commit(); + // Child Rev 3 + em.getTransaction().begin(); + child = em.find( ChildEntity.class, childId ); + child.setData( "Child data modified" ); + em.getTransaction().commit(); - // Parent Rev 4 - em.getTransaction().begin(); - parent = em.find(ParentEntity.class, parentId); - parent.setData("Parent data modified"); - em.getTransaction().commit(); + // Parent Rev 4 + em.getTransaction().begin(); + parent = em.find( ParentEntity.class, parentId ); + parent.setData( "Parent data modified" ); + em.getTransaction().commit(); - childVer1 = new ChildEntity(childId, childTypeId, "Child data", "Child specific data"); - childVer2 = new ChildEntity(childId, childTypeId, "Child data modified", "Child specific data"); - parentVer1 = new ParentEntity(parentId, parentTypeId, "Parent data"); - parentVer2 = new ParentEntity(parentId, parentTypeId, "Parent data modified"); - } + childVer1 = new ChildEntity( childId, childTypeId, "Child data", "Child specific data" ); + childVer2 = new ChildEntity( childId, childTypeId, "Child data modified", "Child specific data" ); + parentVer1 = new ParentEntity( parentId, parentTypeId, "Parent data" ); + parentVer2 = new ParentEntity( parentId, parentTypeId, "Parent data modified" ); + } - @Test - public void testDiscriminatorFormulaInAuditTable() { - assert parentAudit.getDiscriminator().hasFormula(); - Iterator iterator = parentAudit.getDiscriminator().getColumnIterator(); - while (iterator.hasNext()) { - Object o = iterator.next(); - if (o instanceof Formula) { - Formula formula = (Formula) o; - Assert.assertEquals(ParentEntity.DISCRIMINATOR_QUERY, formula.getText()); - return; - } - } - assert false; - } + @Test + public void testDiscriminatorFormulaInAuditTable() { + assert parentAudit.getDiscriminator().hasFormula(); + Iterator iterator = parentAudit.getDiscriminator().getColumnIterator(); + while ( iterator.hasNext() ) { + Object o = iterator.next(); + if ( o instanceof Formula ) { + Formula formula = (Formula) o; + Assert.assertEquals( ParentEntity.DISCRIMINATOR_QUERY, formula.getText() ); + return; + } + } + assert false; + } - @Test - public void testRevisionsCounts() { - Assert.assertEquals(Arrays.asList(1, 3), getAuditReader().getRevisions(ChildEntity.class, childVer1.getId())); - Assert.assertEquals(Arrays.asList(2, 4), getAuditReader().getRevisions(ParentEntity.class, parentVer1.getId())); - } + @Test + public void testRevisionsCounts() { + Assert.assertEquals( + Arrays.asList( 1, 3 ), getAuditReader().getRevisions( + ChildEntity.class, + childVer1.getId() + ) + ); + Assert.assertEquals( + Arrays.asList( 2, 4 ), getAuditReader().getRevisions( + ParentEntity.class, + parentVer1.getId() + ) + ); + } - @Test - public void testHistoryOfParent() { - Assert.assertEquals(parentVer1, getAuditReader().find(ParentEntity.class, parentVer1.getId(), 2)); - Assert.assertEquals(parentVer2, getAuditReader().find(ParentEntity.class, parentVer2.getId(), 4)); - } + @Test + public void testHistoryOfParent() { + Assert.assertEquals( parentVer1, getAuditReader().find( ParentEntity.class, parentVer1.getId(), 2 ) ); + Assert.assertEquals( parentVer2, getAuditReader().find( ParentEntity.class, parentVer2.getId(), 4 ) ); + } - @Test - public void testHistoryOfChild() { - Assert.assertEquals(childVer1, getAuditReader().find(ChildEntity.class, childVer1.getId(), 1)); - Assert.assertEquals(childVer2, getAuditReader().find(ChildEntity.class, childVer2.getId(), 3)); - } + @Test + public void testHistoryOfChild() { + Assert.assertEquals( childVer1, getAuditReader().find( ChildEntity.class, childVer1.getId(), 1 ) ); + Assert.assertEquals( childVer2, getAuditReader().find( ChildEntity.class, childVer2.getId(), 3 ) ); + } - @Test - public void testPolymorphicQuery() { - Assert.assertEquals(childVer1, getAuditReader().createQuery().forEntitiesAtRevision(ChildEntity.class, 1).getSingleResult()); - Assert.assertEquals(childVer1, getAuditReader().createQuery().forEntitiesAtRevision(ParentEntity.class, 1).getSingleResult()); + @Test + public void testPolymorphicQuery() { + Assert.assertEquals( + childVer1, getAuditReader().createQuery() + .forEntitiesAtRevision( ChildEntity.class, 1 ) + .getSingleResult() + ); + Assert.assertEquals( + childVer1, getAuditReader().createQuery() + .forEntitiesAtRevision( ParentEntity.class, 1 ) + .getSingleResult() + ); - List childEntityRevisions = getAuditReader().createQuery().forRevisionsOfEntity(ChildEntity.class, true, false).getResultList(); - Assert.assertEquals(Arrays.asList(childVer1, childVer2), childEntityRevisions); + List childEntityRevisions = getAuditReader().createQuery().forRevisionsOfEntity( + ChildEntity.class, + true, + false + ).getResultList(); + Assert.assertEquals( Arrays.asList( childVer1, childVer2 ), childEntityRevisions ); - List parentEntityRevisions = getAuditReader().createQuery().forRevisionsOfEntity(ParentEntity.class, true, false).getResultList(); - Assert.assertEquals(Arrays.asList(childVer1, parentVer1, childVer2, parentVer2), parentEntityRevisions); - } + List parentEntityRevisions = getAuditReader().createQuery().forRevisionsOfEntity( + ParentEntity.class, + true, + false + ).getResultList(); + Assert.assertEquals( Arrays.asList( childVer1, parentVer1, childVer2, parentVer2 ), parentEntityRevisions ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/discriminatorformula/ParentEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/discriminatorformula/ParentEntity.java index ba37c8f802..5f1aa9f636 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/discriminatorformula/ParentEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/discriminatorformula/ParentEntity.java @@ -16,76 +16,86 @@ import org.hibernate.envers.Audited; @DiscriminatorValue(ClassTypeEntity.PARENT_TYPE) @Audited public class ParentEntity { - public static final String DISCRIMINATOR_QUERY = "(SELECT c.type FROM ClassTypeEntity c WHERE c.id = typeId)"; + public static final String DISCRIMINATOR_QUERY = "(SELECT c.type FROM ClassTypeEntity c WHERE c.id = typeId)"; - @Id - @GeneratedValue - protected Long id; + @Id + @GeneratedValue + protected Long id; - protected Long typeId; + protected Long typeId; - protected String data; + protected String data; - public ParentEntity() { - } + public ParentEntity() { + } - public ParentEntity(Long typeId, String data) { - this.typeId = typeId; - this.data = data; - } + public ParentEntity(Long typeId, String data) { + this.typeId = typeId; + this.data = data; + } - public ParentEntity(Long id, Long typeId, String data) { - this.id = id; - this.typeId = typeId; - this.data = data; - } + public ParentEntity(Long id, Long typeId, String data) { + this.id = id; + this.typeId = typeId; + this.data = data; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ParentEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ParentEntity) ) { + return false; + } - ParentEntity that = (ParentEntity) o; + ParentEntity that = (ParentEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (typeId != null ? !typeId.equals(that.typeId) : that.typeId != null) return false; - if (data != null ? !data.equals(that.data) : that.data != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( typeId != null ? !typeId.equals( that.typeId ) : that.typeId != null ) { + return false; + } + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (typeId != null ? typeId.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (typeId != null ? typeId.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ParentEntity(id = " + id + ", typeId = " + typeId + ", data = " + data + ")"; - } + public String toString() { + return "ParentEntity(id = " + id + ", typeId = " + typeId + ", data = " + data + ")"; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public Long getTypeId() { - return typeId; - } + public Long getTypeId() { + return typeId; + } - public void setTypeId(Long typeId) { - this.typeId = typeId; - } + public void setTypeId(Long typeId) { + this.typeId = typeId; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/notownedrelation/Address.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/notownedrelation/Address.java index 5d0b5fc298..d458c92fae 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/notownedrelation/Address.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/notownedrelation/Address.java @@ -1,16 +1,18 @@ package org.hibernate.envers.test.integration.inheritance.single.notownedrelation; -import java.io.Serializable; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; +import java.io.Serializable; import org.hibernate.envers.Audited; @Entity @Audited public class Address implements Serializable { - @Id @GeneratedValue + @Id + @GeneratedValue private Long id; private String address1; @@ -18,15 +20,15 @@ public class Address implements Serializable { @ManyToOne private Contact contact; - public Address() { - } + public Address() { + } - public Address(Long id, String address1) { - this.id = id; - this.address1 = address1; - } + public Address(Long id, String address1) { + this.id = id; + this.address1 = address1; + } - public Long getId() { + public Long getId() { return id; } @@ -50,22 +52,30 @@ public class Address implements Serializable { this.contact = contact; } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Address)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Address) ) { + return false; + } - Address address = (Address) o; + Address address = (Address) o; - if (address1 != null ? !address1.equals(address.address1) : address.address1 != null) return false; - if (id != null ? !id.equals(address.id) : address.id != null) return false; + if ( address1 != null ? !address1.equals( address.address1 ) : address.address1 != null ) { + return false; + } + if ( id != null ? !id.equals( address.id ) : address.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (address1 != null ? address1.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (address1 != null ? address1.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/notownedrelation/Contact.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/notownedrelation/Contact.java index f99abf8818..6872760f67 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/notownedrelation/Contact.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/notownedrelation/Contact.java @@ -1,6 +1,5 @@ package org.hibernate.envers.test.integration.inheritance.single.notownedrelation; -import java.io.Serializable; -import java.util.Set; + import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @@ -9,43 +8,50 @@ import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.OneToMany; +import java.io.Serializable; +import java.util.Set; import org.hibernate.envers.Audited; @Entity -@Inheritance(strategy=InheritanceType.SINGLE_TABLE) +@Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorValue("Contact") -@DiscriminatorColumn(name="contactType",discriminatorType=javax.persistence.DiscriminatorType.STRING) +@DiscriminatorColumn(name = "contactType", discriminatorType = javax.persistence.DiscriminatorType.STRING) @Audited public class Contact implements Serializable { - @Id @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String email; + private String email; - @OneToMany(mappedBy="contact") - private Set
      addresses; + @OneToMany(mappedBy = "contact") + private Set
      addresses; - public Contact() { - } + public Contact() { + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } public String getEmail() { - return email; - } - public void setEmail(String email) { - this.email = email; - } + return email; + } - public Set
      getAddresses() { - return addresses; - } - public void setAddresses(Set
      addresses) { - this.addresses = addresses; - } + public void setEmail(String email) { + this.email = email; + } + + public Set
      getAddresses() { + return addresses; + } + + public void setAddresses(Set
      addresses) { + this.addresses = addresses; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/notownedrelation/NotOwnedBidirectional.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/notownedrelation/NotOwnedBidirectional.java index 46fffcea2e..15de57985e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/notownedrelation/NotOwnedBidirectional.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/notownedrelation/NotOwnedBidirectional.java @@ -24,96 +24,100 @@ package org.hibernate.envers.test.integration.inheritance.single.notownedrelation; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class NotOwnedBidirectional extends BaseEnversJPAFunctionalTestCase { - private Long pc_id; - private Long a1_id; - private Long a2_id; + private Long pc_id; + private Long a1_id; + private Long a2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { Address.class, Contact.class, PersonalContact.class }; - } + return new Class[] {Address.class, Contact.class, PersonalContact.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Rev 1 - em.getTransaction().begin(); + // Rev 1 + em.getTransaction().begin(); - PersonalContact pc = new PersonalContact(); - pc.setEmail("e"); - pc.setFirstname("f"); + PersonalContact pc = new PersonalContact(); + pc.setEmail( "e" ); + pc.setFirstname( "f" ); - Address a1 = new Address(); - a1.setAddress1("a1"); - a1.setContact(pc); + Address a1 = new Address(); + a1.setAddress1( "a1" ); + a1.setContact( pc ); - em.persist(pc); - em.persist(a1); + em.persist( pc ); + em.persist( a1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); + // Rev 2 + em.getTransaction().begin(); - pc = em.find(PersonalContact.class, pc.getId()); + pc = em.find( PersonalContact.class, pc.getId() ); - Address a2 = new Address(); - a2.setAddress1("a2"); - a2.setContact(pc); + Address a2 = new Address(); + a2.setAddress1( "a2" ); + a2.setContact( pc ); - em.persist(a2); + em.persist( a2 ); - em.getTransaction().commit(); - - // + em.getTransaction().commit(); - pc_id = pc.getId(); - a1_id = a1.getId(); - a2_id = a2.getId(); - } + // - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(Contact.class, pc_id)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(PersonalContact.class, pc_id)); + pc_id = pc.getId(); + a1_id = a1.getId(); + a2_id = a2.getId(); + } - assert Arrays.asList(1).equals(getAuditReader().getRevisions(Address.class, a1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(Address.class, a1_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( Contact.class, pc_id ) ); + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( PersonalContact.class, pc_id ) ); - assert Arrays.asList(2).equals(getAuditReader().getRevisions(Address.class, a2_id)); - assert Arrays.asList(2).equals(getAuditReader().getRevisions(Address.class, a2_id)); - } + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( Address.class, a1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( Address.class, a1_id ) ); - @Test - public void testHistoryOfContact() { - assert getAuditReader().find(Contact.class, pc_id, 1).getAddresses().equals( - TestTools.makeSet(new Address(a1_id, "a1"))); + assert Arrays.asList( 2 ).equals( getAuditReader().getRevisions( Address.class, a2_id ) ); + assert Arrays.asList( 2 ).equals( getAuditReader().getRevisions( Address.class, a2_id ) ); + } - assert getAuditReader().find(Contact.class, pc_id, 2).getAddresses().equals( - TestTools.makeSet(new Address(a1_id, "a1"), new Address(a2_id, "a2"))); - } + @Test + public void testHistoryOfContact() { + assert getAuditReader().find( Contact.class, pc_id, 1 ).getAddresses().equals( + TestTools.makeSet( new Address( a1_id, "a1" ) ) + ); - @Test - public void testHistoryOfPersonalContact() { - assert getAuditReader().find(PersonalContact.class, pc_id, 1).getAddresses().equals( - TestTools.makeSet(new Address(a1_id, "a1"))); + assert getAuditReader().find( Contact.class, pc_id, 2 ).getAddresses().equals( + TestTools.makeSet( new Address( a1_id, "a1" ), new Address( a2_id, "a2" ) ) + ); + } - assert getAuditReader().find(PersonalContact.class, pc_id, 2).getAddresses().equals( - TestTools.makeSet(new Address(a1_id, "a1"), new Address(a2_id, "a2"))); - } + @Test + public void testHistoryOfPersonalContact() { + assert getAuditReader().find( PersonalContact.class, pc_id, 1 ).getAddresses().equals( + TestTools.makeSet( new Address( a1_id, "a1" ) ) + ); + + assert getAuditReader().find( PersonalContact.class, pc_id, 2 ).getAddresses().equals( + TestTools.makeSet( new Address( a1_id, "a1" ), new Address( a2_id, "a2" ) ) + ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/notownedrelation/PersonalContact.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/notownedrelation/PersonalContact.java index ddae0cf878..64e400a52a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/notownedrelation/PersonalContact.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/notownedrelation/PersonalContact.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.integration.inheritance.single.notownedrelation; + import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @@ -13,8 +14,8 @@ public class PersonalContact extends Contact { public String getFirstname() { return firstname; } - - public void setFirstname(String firstname) { + + public void setFirstname(String firstname) { this.firstname = firstname; } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/relation/ChildIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/relation/ChildIngEntity.java index bd57edd27e..eb00fb1986 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/relation/ChildIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/relation/ChildIngEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.inheritance.single.relation; + import javax.persistence.Basic; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @@ -35,49 +36,57 @@ import org.hibernate.envers.Audited; @DiscriminatorValue("2") @Audited public class ChildIngEntity extends ParentIngEntity { - @Basic - private Long numVal; + @Basic + private Long numVal; - public ChildIngEntity() { - } + public ChildIngEntity() { + } - public ChildIngEntity(String data, Long numVal) { - super(data); - this.numVal = numVal; - } + public ChildIngEntity(String data, Long numVal) { + super( data ); + this.numVal = numVal; + } - public ChildIngEntity(Integer id, String data, Long numVal) { - super(id, data); - this.numVal = numVal; - } + public ChildIngEntity(Integer id, String data, Long numVal) { + super( id, data ); + this.numVal = numVal; + } - public Long getNumVal() { - return numVal; - } + public Long getNumVal() { + return numVal; + } - public void setNumVal(Long numVal) { - this.numVal = numVal; - } + public void setNumVal(Long numVal) { + this.numVal = numVal; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ChildIngEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ChildIngEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ChildIngEntity childEntity = (ChildIngEntity) o; + ChildIngEntity childEntity = (ChildIngEntity) o; - if (numVal != null ? !numVal.equals(childEntity.numVal) : childEntity.numVal != null) return false; + if ( numVal != null ? !numVal.equals( childEntity.numVal ) : childEntity.numVal != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (numVal != null ? numVal.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (numVal != null ? numVal.hashCode() : 0); + return result; + } - public String toString() { - return "ChildIngEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; - } + public String toString() { + return "ChildIngEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/relation/ParentIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/relation/ParentIngEntity.java index 0f47ac41e5..29ee0006d0 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/relation/ParentIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/relation/ParentIngEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.inheritance.single.relation; + import javax.persistence.Basic; import javax.persistence.DiscriminatorColumn; import javax.persistence.DiscriminatorType; @@ -44,72 +45,80 @@ import org.hibernate.envers.Audited; @DiscriminatorValue("1") @Audited public class ParentIngEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Basic - private String data; + @Basic + private String data; - @ManyToOne - private ReferencedEntity referenced; + @ManyToOne + private ReferencedEntity referenced; - public ParentIngEntity() { - } + public ParentIngEntity() { + } - public ParentIngEntity(String data) { - this.data = data; - } + public ParentIngEntity(String data) { + this.data = data; + } - public ParentIngEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public ParentIngEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public ReferencedEntity getReferenced() { - return referenced; - } + public ReferencedEntity getReferenced() { + return referenced; + } - public void setReferenced(ReferencedEntity referenced) { - this.referenced = referenced; - } + public void setReferenced(ReferencedEntity referenced) { + this.referenced = referenced; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ParentIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ParentIngEntity) ) { + return false; + } - ParentIngEntity that = (ParentIngEntity) o; + ParentIngEntity that = (ParentIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ParentIngEntity(id = " + getId() + ", data = " + getData() + ")"; - } + public String toString() { + return "ParentIngEntity(id = " + getId() + ", data = " + getData() + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/relation/PolymorphicCollection.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/relation/PolymorphicCollection.java index 7d92c65dae..a1049f16b6 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/relation/PolymorphicCollection.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/relation/PolymorphicCollection.java @@ -23,80 +23,82 @@ */ package org.hibernate.envers.test.integration.inheritance.single.relation; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class PolymorphicCollection extends BaseEnversJPAFunctionalTestCase { - private Integer ed_id1; - private Integer c_id; - private Integer p_id; + private Integer ed_id1; + private Integer c_id; + private Integer p_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ChildIngEntity.class, ParentIngEntity.class, ReferencedEntity.class }; - } + return new Class[] {ChildIngEntity.class, ParentIngEntity.class, ReferencedEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Rev 1 - em.getTransaction().begin(); + // Rev 1 + em.getTransaction().begin(); - ReferencedEntity re = new ReferencedEntity(); - em.persist(re); - ed_id1 = re.getId(); + ReferencedEntity re = new ReferencedEntity(); + em.persist( re ); + ed_id1 = re.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); + // Rev 2 + em.getTransaction().begin(); - re = em.find(ReferencedEntity.class, ed_id1); + re = em.find( ReferencedEntity.class, ed_id1 ); - ParentIngEntity pie = new ParentIngEntity("x"); - pie.setReferenced(re); - em.persist(pie); - p_id = pie.getId(); + ParentIngEntity pie = new ParentIngEntity( "x" ); + pie.setReferenced( re ); + em.persist( pie ); + p_id = pie.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 3 - em.getTransaction().begin(); - - re = em.find(ReferencedEntity.class, ed_id1); + // Rev 3 + em.getTransaction().begin(); - ChildIngEntity cie = new ChildIngEntity("y", 1l); - cie.setReferenced(re); - em.persist(cie); - c_id = cie.getId(); + re = em.find( ReferencedEntity.class, ed_id1 ); - em.getTransaction().commit(); - } + ChildIngEntity cie = new ChildIngEntity( "y", 1l ); + cie.setReferenced( re ); + em.persist( cie ); + c_id = cie.getId(); - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(ReferencedEntity.class, ed_id1)); - assert Arrays.asList(2).equals(getAuditReader().getRevisions(ParentIngEntity.class, p_id)); - assert Arrays.asList(3).equals(getAuditReader().getRevisions(ChildIngEntity.class, c_id)); - } + em.getTransaction().commit(); + } - @Test - public void testHistoryOfReferencedCollection() { - assert getAuditReader().find(ReferencedEntity.class, ed_id1, 1).getReferencing().size() == 0; - assert getAuditReader().find(ReferencedEntity.class, ed_id1, 2).getReferencing().equals( - TestTools.makeSet(new ParentIngEntity(p_id, "x"))); - assert getAuditReader().find(ReferencedEntity.class, ed_id1, 3).getReferencing().equals( - TestTools.makeSet(new ParentIngEntity(p_id, "x"), new ChildIngEntity(c_id, "y", 1l))); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( ReferencedEntity.class, ed_id1 ) ); + assert Arrays.asList( 2 ).equals( getAuditReader().getRevisions( ParentIngEntity.class, p_id ) ); + assert Arrays.asList( 3 ).equals( getAuditReader().getRevisions( ChildIngEntity.class, c_id ) ); + } + + @Test + public void testHistoryOfReferencedCollection() { + assert getAuditReader().find( ReferencedEntity.class, ed_id1, 1 ).getReferencing().size() == 0; + assert getAuditReader().find( ReferencedEntity.class, ed_id1, 2 ).getReferencing().equals( + TestTools.makeSet( new ParentIngEntity( p_id, "x" ) ) + ); + assert getAuditReader().find( ReferencedEntity.class, ed_id1, 3 ).getReferencing().equals( + TestTools.makeSet( new ParentIngEntity( p_id, "x" ), new ChildIngEntity( c_id, "y", 1l ) ) + ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/relation/ReferencedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/relation/ReferencedEntity.java index 5caaf46488..a77cf9b68f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/relation/ReferencedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/single/relation/ReferencedEntity.java @@ -22,11 +22,12 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.inheritance.single.relation; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.util.Set; import org.hibernate.envers.Audited; @@ -36,41 +37,47 @@ import org.hibernate.envers.Audited; @Entity @Audited public class ReferencedEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @OneToMany(mappedBy = "referenced") - private Set referencing; + @OneToMany(mappedBy = "referenced") + private Set referencing; - public Set getReferencing() { - return referencing; - } + public Set getReferencing() { + return referencing; + } - public void setReferencing(Set referencing) { - this.referencing = referencing; - } + public void setReferencing(Set referencing) { + this.referencing = referencing; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ReferencedEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ReferencedEntity) ) { + return false; + } - ReferencedEntity that = (ReferencedEntity) o; + ReferencedEntity that = (ReferencedEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - return id; - } + public int hashCode() { + return id; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/ChildAuditing.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/ChildAuditing.java index d13ed2fef8..75423c4617 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/ChildAuditing.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/ChildAuditing.java @@ -24,71 +24,71 @@ package org.hibernate.envers.test.integration.inheritance.tableperclass; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class ChildAuditing extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ChildEntity.class, ParentEntity.class }; - } + return new Class[] {ChildEntity.class, ParentEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - id1 = 1; + id1 = 1; - // Rev 1 - em.getTransaction().begin(); - ChildEntity ce = new ChildEntity(id1, "x", 1l); - em.persist(ce); - em.getTransaction().commit(); + // Rev 1 + em.getTransaction().begin(); + ChildEntity ce = new ChildEntity( id1, "x", 1l ); + em.persist( ce ); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); - ce = em.find(ChildEntity.class, id1); - ce.setData("y"); - ce.setNumVal(2l); - em.getTransaction().commit(); - } + // Rev 2 + em.getTransaction().begin(); + ce = em.find( ChildEntity.class, id1 ); + ce.setData( "y" ); + ce.setNumVal( 2l ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(ChildEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( ChildEntity.class, id1 ) ); + } - @Test - public void testHistoryOfChildId1() { - ChildEntity ver1 = new ChildEntity(id1, "x", 1l); - ChildEntity ver2 = new ChildEntity(id1, "y", 2l); + @Test + public void testHistoryOfChildId1() { + ChildEntity ver1 = new ChildEntity( id1, "x", 1l ); + ChildEntity ver2 = new ChildEntity( id1, "y", 2l ); - assert getAuditReader().find(ChildEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(ChildEntity.class, id1, 2).equals(ver2); + assert getAuditReader().find( ChildEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( ChildEntity.class, id1, 2 ).equals( ver2 ); - assert getAuditReader().find(ParentEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(ParentEntity.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( ParentEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( ParentEntity.class, id1, 2 ).equals( ver2 ); + } - @Test - public void testPolymorphicQuery() { - ChildEntity childVer1 = new ChildEntity(id1, "x", 1l); + @Test + public void testPolymorphicQuery() { + ChildEntity childVer1 = new ChildEntity( id1, "x", 1l ); - assert getAuditReader().createQuery().forEntitiesAtRevision(ChildEntity.class, 1).getSingleResult() - .equals(childVer1); + assert getAuditReader().createQuery().forEntitiesAtRevision( ChildEntity.class, 1 ).getSingleResult() + .equals( childVer1 ); - assert getAuditReader().createQuery().forEntitiesAtRevision(ParentEntity.class, 1).getSingleResult() - .equals(childVer1); - } + assert getAuditReader().createQuery().forEntitiesAtRevision( ParentEntity.class, 1 ).getSingleResult() + .equals( childVer1 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/ChildEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/ChildEntity.java index 345306189f..d7fca93a99 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/ChildEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/ChildEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.tableperclass; + import javax.persistence.Basic; import javax.persistence.Entity; @@ -34,44 +35,52 @@ import org.hibernate.envers.Audited; @Entity @Audited public class ChildEntity extends ParentEntity { - @Basic - private Long numVal; + @Basic + private Long numVal; - public ChildEntity() { - } + public ChildEntity() { + } - public ChildEntity(Integer id, String data, Long numVal) { - super(id, data); - this.numVal = numVal; - } + public ChildEntity(Integer id, String data, Long numVal) { + super( id, data ); + this.numVal = numVal; + } - public Long getNumVal() { - return numVal; - } + public Long getNumVal() { + return numVal; + } - public void setNumVal(Long numVal) { - this.numVal = numVal; - } + public void setNumVal(Long numVal) { + this.numVal = numVal; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ChildEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ChildEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ChildEntity childEntity = (ChildEntity) o; + ChildEntity childEntity = (ChildEntity) o; - if (numVal != null ? !numVal.equals(childEntity.numVal) : childEntity.numVal != null) return false; + if ( numVal != null ? !numVal.equals( childEntity.numVal ) : childEntity.numVal != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (numVal != null ? numVal.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (numVal != null ? numVal.hashCode() : 0); + return result; + } - public String toString() { - return "ChildPrimaryKeyJoinEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; - } + public String toString() { + return "ChildPrimaryKeyJoinEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/ParentAuditing.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/ParentAuditing.java index 97500a5015..69b8549b2e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/ParentAuditing.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/ParentAuditing.java @@ -24,72 +24,72 @@ package org.hibernate.envers.test.integration.inheritance.tableperclass; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class ParentAuditing extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ChildEntity.class, ParentEntity.class }; - } + return new Class[] {ChildEntity.class, ParentEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - id1 = 1; + id1 = 1; - // Rev 1 - em.getTransaction().begin(); - ParentEntity pe = new ParentEntity(id1, "x"); - em.persist(pe); - em.getTransaction().commit(); + // Rev 1 + em.getTransaction().begin(); + ParentEntity pe = new ParentEntity( id1, "x" ); + em.persist( pe ); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); - pe = em.find(ParentEntity.class, id1); - pe.setData("y"); - em.getTransaction().commit(); - } + // Rev 2 + em.getTransaction().begin(); + pe = em.find( ParentEntity.class, id1 ); + pe.setData( "y" ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(ParentEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( ParentEntity.class, id1 ) ); + } - @Test - public void testHistoryOfChildId1() { - assert getAuditReader().find(ChildEntity.class, id1, 1) == null; - assert getAuditReader().find(ChildEntity.class, id1, 2) == null; - } + @Test + public void testHistoryOfChildId1() { + assert getAuditReader().find( ChildEntity.class, id1, 1 ) == null; + assert getAuditReader().find( ChildEntity.class, id1, 2 ) == null; + } - @Test - public void testHistoryOfParentId1() { - ParentEntity ver1 = new ParentEntity(id1, "x"); - ParentEntity ver2 = new ParentEntity(id1, "y"); + @Test + public void testHistoryOfParentId1() { + ParentEntity ver1 = new ParentEntity( id1, "x" ); + ParentEntity ver2 = new ParentEntity( id1, "y" ); - assert getAuditReader().find(ParentEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(ParentEntity.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( ParentEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( ParentEntity.class, id1, 2 ).equals( ver2 ); + } - @Test - public void testPolymorphicQuery() { - ParentEntity parentVer1 = new ParentEntity(id1, "x"); + @Test + public void testPolymorphicQuery() { + ParentEntity parentVer1 = new ParentEntity( id1, "x" ); - assert getAuditReader().createQuery().forEntitiesAtRevision(ParentEntity.class, 1).getSingleResult() - .equals(parentVer1); - assert getAuditReader().createQuery().forEntitiesAtRevision(ChildEntity.class, 1) - .getResultList().size() == 0; - } + assert getAuditReader().createQuery().forEntitiesAtRevision( ParentEntity.class, 1 ).getSingleResult() + .equals( parentVer1 ); + assert getAuditReader().createQuery().forEntitiesAtRevision( ChildEntity.class, 1 ) + .getResultList().size() == 0; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/ParentEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/ParentEntity.java index 268607d052..7b7b5c7cda 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/ParentEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/ParentEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.tableperclass; + import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.Id; @@ -38,56 +39,64 @@ import org.hibernate.envers.Audited; @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) @Audited public class ParentEntity { - @Id - private Integer id; + @Id + private Integer id; - @Basic - private String data; + @Basic + private String data; - public ParentEntity() { - } + public ParentEntity() { + } - public ParentEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public ParentEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ParentEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ParentEntity) ) { + return false; + } - ParentEntity that = (ParentEntity) o; + ParentEntity that = (ParentEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ParentEntity(id = " + getId() + ", data = " + getData() + ")"; - } + public String toString() { + return "ParentEntity(id = " + getId() + ", data = " + getData() + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/abstractparent/AuditedAbstractParentTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/abstractparent/AuditedAbstractParentTest.java index 73553b5472..f6b95aedad 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/abstractparent/AuditedAbstractParentTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/abstractparent/AuditedAbstractParentTest.java @@ -1,14 +1,15 @@ package org.hibernate.envers.test.integration.inheritance.tableperclass.abstractparent; -import java.util.Iterator; import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; +import java.util.Iterator; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.mapping.Table; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -18,7 +19,7 @@ import org.hibernate.testing.TestForIssue; public class AuditedAbstractParentTest extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { AbstractEntity.class, EffectiveEntity1.class }; + return new Class[] {AbstractEntity.class, EffectiveEntity1.class}; } @Test diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/childrelation/ChildIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/childrelation/ChildIngEntity.java index af1b87a605..c391953c0d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/childrelation/ChildIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/childrelation/ChildIngEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.tableperclass.childrelation; + import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.ManyToOne; @@ -35,55 +36,63 @@ import org.hibernate.envers.Audited; @Entity @Audited public class ChildIngEntity extends ParentNotIngEntity { - @Basic - private Long numVal; + @Basic + private Long numVal; - @ManyToOne - private ReferencedEntity referenced; + @ManyToOne + private ReferencedEntity referenced; - public ChildIngEntity() { - } + public ChildIngEntity() { + } - public ChildIngEntity(Integer id, String data, Long numVal) { - super(id, data); - this.numVal = numVal; - } + public ChildIngEntity(Integer id, String data, Long numVal) { + super( id, data ); + this.numVal = numVal; + } - public Long getNumVal() { - return numVal; - } + public Long getNumVal() { + return numVal; + } - public void setNumVal(Long numVal) { - this.numVal = numVal; - } + public void setNumVal(Long numVal) { + this.numVal = numVal; + } - public ReferencedEntity getReferenced() { - return referenced; - } + public ReferencedEntity getReferenced() { + return referenced; + } - public void setReferenced(ReferencedEntity referenced) { - this.referenced = referenced; - } + public void setReferenced(ReferencedEntity referenced) { + this.referenced = referenced; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ChildIngEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ChildIngEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ChildIngEntity childEntity = (ChildIngEntity) o; + ChildIngEntity childEntity = (ChildIngEntity) o; - if (numVal != null ? !numVal.equals(childEntity.numVal) : childEntity.numVal != null) return false; + if ( numVal != null ? !numVal.equals( childEntity.numVal ) : childEntity.numVal != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (numVal != null ? numVal.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (numVal != null ? numVal.hashCode() : 0); + return result; + } - public String toString() { - return "ChildIngEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; - } + public String toString() { + return "ChildIngEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/childrelation/ChildReferencing.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/childrelation/ChildReferencing.java index 2d34eac5fb..27075b4617 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/childrelation/ChildReferencing.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/childrelation/ChildReferencing.java @@ -24,100 +24,104 @@ package org.hibernate.envers.test.integration.inheritance.tableperclass.childrelation; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class ChildReferencing extends BaseEnversJPAFunctionalTestCase { - private Integer re_id1; - private Integer re_id2; - private Integer c_id; + private Integer re_id1; + private Integer re_id2; + private Integer c_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ChildIngEntity.class, ParentNotIngEntity.class, ReferencedEntity.class }; - } + return new Class[] {ChildIngEntity.class, ParentNotIngEntity.class, ReferencedEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - re_id1 = 1; - re_id2 = 10; - c_id = 100; + re_id1 = 1; + re_id2 = 10; + c_id = 100; - // Rev 1 - em.getTransaction().begin(); + // Rev 1 + em.getTransaction().begin(); - ReferencedEntity re1 = new ReferencedEntity(re_id1); - em.persist(re1); + ReferencedEntity re1 = new ReferencedEntity( re_id1 ); + em.persist( re1 ); - ReferencedEntity re2 = new ReferencedEntity(re_id2); - em.persist(re2); + ReferencedEntity re2 = new ReferencedEntity( re_id2 ); + em.persist( re2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); + // Rev 2 + em.getTransaction().begin(); - re1 = em.find(ReferencedEntity.class, re_id1); + re1 = em.find( ReferencedEntity.class, re_id1 ); - ChildIngEntity cie = new ChildIngEntity(c_id, "y", 1l); - cie.setReferenced(re1); - em.persist(cie); - c_id = cie.getId(); + ChildIngEntity cie = new ChildIngEntity( c_id, "y", 1l ); + cie.setReferenced( re1 ); + em.persist( cie ); + c_id = cie.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 3 - em.getTransaction().begin(); + // Rev 3 + em.getTransaction().begin(); - re2 = em.find(ReferencedEntity.class, re_id2); - cie = em.find(ChildIngEntity.class, c_id); + re2 = em.find( ReferencedEntity.class, re_id2 ); + cie = em.find( ChildIngEntity.class, c_id ); - cie.setReferenced(re2); + cie.setReferenced( re2 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(ReferencedEntity.class, re_id1)); - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(ReferencedEntity.class, re_id2)); - assert Arrays.asList(2, 3).equals(getAuditReader().getRevisions(ChildIngEntity.class, c_id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( ReferencedEntity.class, re_id1 ) ); + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( ReferencedEntity.class, re_id2 ) ); + assert Arrays.asList( 2, 3 ).equals( getAuditReader().getRevisions( ChildIngEntity.class, c_id ) ); + } - @Test - public void testHistoryOfReferencedCollection1() { - assert getAuditReader().find(ReferencedEntity.class, re_id1, 1).getReferencing().size() == 0; - assert getAuditReader().find(ReferencedEntity.class, re_id1, 2).getReferencing().equals( - TestTools.makeSet(new ChildIngEntity(c_id, "y", 1l))); - assert getAuditReader().find(ReferencedEntity.class, re_id1, 3).getReferencing().size() == 0; - } + @Test + public void testHistoryOfReferencedCollection1() { + assert getAuditReader().find( ReferencedEntity.class, re_id1, 1 ).getReferencing().size() == 0; + assert getAuditReader().find( ReferencedEntity.class, re_id1, 2 ).getReferencing().equals( + TestTools.makeSet( new ChildIngEntity( c_id, "y", 1l ) ) + ); + assert getAuditReader().find( ReferencedEntity.class, re_id1, 3 ).getReferencing().size() == 0; + } - @Test - public void testHistoryOfReferencedCollection2() { - assert getAuditReader().find(ReferencedEntity.class, re_id2, 1).getReferencing().size() == 0; - assert getAuditReader().find(ReferencedEntity.class, re_id2, 2).getReferencing().size() == 0; - assert getAuditReader().find(ReferencedEntity.class, re_id2, 3).getReferencing().equals( - TestTools.makeSet(new ChildIngEntity(c_id, "y", 1l))); - } + @Test + public void testHistoryOfReferencedCollection2() { + assert getAuditReader().find( ReferencedEntity.class, re_id2, 1 ).getReferencing().size() == 0; + assert getAuditReader().find( ReferencedEntity.class, re_id2, 2 ).getReferencing().size() == 0; + assert getAuditReader().find( ReferencedEntity.class, re_id2, 3 ).getReferencing().equals( + TestTools.makeSet( new ChildIngEntity( c_id, "y", 1l ) ) + ); + } - @Test - public void testChildHistory() { - assert getAuditReader().find(ChildIngEntity.class, c_id, 1) == null; - assert getAuditReader().find(ChildIngEntity.class, c_id, 2).getReferenced().equals( - new ReferencedEntity(re_id1)); - assert getAuditReader().find(ChildIngEntity.class, c_id, 3).getReferenced().equals( - new ReferencedEntity(re_id2)); - } + @Test + public void testChildHistory() { + assert getAuditReader().find( ChildIngEntity.class, c_id, 1 ) == null; + assert getAuditReader().find( ChildIngEntity.class, c_id, 2 ).getReferenced().equals( + new ReferencedEntity( re_id1 ) + ); + assert getAuditReader().find( ChildIngEntity.class, c_id, 3 ).getReferenced().equals( + new ReferencedEntity( re_id2 ) + ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/childrelation/ParentNotIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/childrelation/ParentNotIngEntity.java index fc06884da3..c7fda2de74 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/childrelation/ParentNotIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/childrelation/ParentNotIngEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.tableperclass.childrelation; + import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.Id; @@ -38,56 +39,64 @@ import org.hibernate.envers.Audited; @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) @Audited public class ParentNotIngEntity { - @Id - private Integer id; + @Id + private Integer id; - @Basic - private String data; + @Basic + private String data; - public ParentNotIngEntity() { - } + public ParentNotIngEntity() { + } - public ParentNotIngEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public ParentNotIngEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ParentNotIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ParentNotIngEntity) ) { + return false; + } - ParentNotIngEntity that = (ParentNotIngEntity) o; + ParentNotIngEntity that = (ParentNotIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ParentNotIngEntity(id = " + getId() + ", data = " + getData() + ")"; - } + public String toString() { + return "ParentNotIngEntity(id = " + getId() + ", data = " + getData() + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/childrelation/ReferencedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/childrelation/ReferencedEntity.java index 91f12f0141..f3beec7884 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/childrelation/ReferencedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/childrelation/ReferencedEntity.java @@ -23,10 +23,11 @@ */ package org.hibernate.envers.test.integration.inheritance.tableperclass.childrelation; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.util.Set; import org.hibernate.envers.Audited; @@ -36,51 +37,57 @@ import org.hibernate.envers.Audited; @Entity @Audited public class ReferencedEntity { - @Id - private Integer id; + @Id + private Integer id; - @OneToMany(mappedBy = "referenced") - private Set referencing; + @OneToMany(mappedBy = "referenced") + private Set referencing; - public ReferencedEntity(Integer id) { - this.id = id; - } + public ReferencedEntity(Integer id) { + this.id = id; + } - public ReferencedEntity() { - } + public ReferencedEntity() { + } - public Set getReferencing() { - return referencing; - } + public Set getReferencing() { + return referencing; + } - public void setReferencing(Set referencing) { - this.referencing = referencing; - } + public void setReferencing(Set referencing) { + this.referencing = referencing; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ReferencedEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ReferencedEntity) ) { + return false; + } - ReferencedEntity that = (ReferencedEntity) o; + ReferencedEntity that = (ReferencedEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - return id; - } + public int hashCode() { + return id; + } - public String toString() { - return "ReferencedEntity(id = " + getId() + ")"; - } + public String toString() { + return "ReferencedEntity(id = " + getId() + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/notownedrelation/Address.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/notownedrelation/Address.java index 9894d343e7..0768d117fe 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/notownedrelation/Address.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/notownedrelation/Address.java @@ -23,10 +23,11 @@ */ package org.hibernate.envers.test.integration.inheritance.tableperclass.notownedrelation; -import java.io.Serializable; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToOne; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -41,15 +42,15 @@ public class Address implements Serializable { @ManyToOne private Contact contact; - public Address() { - } + public Address() { + } - public Address(Long id, String address1) { - this.id = id; - this.address1 = address1; - } + public Address(Long id, String address1) { + this.id = id; + this.address1 = address1; + } - public Long getId() { + public Long getId() { return id; } @@ -73,26 +74,34 @@ public class Address implements Serializable { this.contact = contact; } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Address)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Address) ) { + return false; + } - Address address = (Address) o; + Address address = (Address) o; - if (address1 != null ? !address1.equals(address.address1) : address.address1 != null) return false; - if (id != null ? !id.equals(address.id) : address.id != null) return false; + if ( address1 != null ? !address1.equals( address.address1 ) : address.address1 != null ) { + return false; + } + if ( id != null ? !id.equals( address.id ) : address.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (address1 != null ? address1.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (address1 != null ? address1.hashCode() : 0); + return result; + } - public String toString() { - return "Address(id = " + getId() + ", address1 = " + getAddress1() + ")"; - } + public String toString() { + return "Address(id = " + getId() + ", address1 = " + getAddress1() + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/notownedrelation/Contact.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/notownedrelation/Contact.java index a8129d4379..367cbecb59 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/notownedrelation/Contact.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/notownedrelation/Contact.java @@ -23,53 +23,58 @@ */ package org.hibernate.envers.test.integration.inheritance.tableperclass.notownedrelation; -import java.io.Serializable; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.OneToMany; +import java.io.Serializable; +import java.util.Set; import org.hibernate.envers.Audited; @Entity -@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) +@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) @Audited public class Contact implements Serializable { - @Id - private Long id; + @Id + private Long id; - private String email; + private String email; - @OneToMany(mappedBy="contact") - private Set
      addresses; + @OneToMany(mappedBy = "contact") + private Set
      addresses; - public Contact() { - } + public Contact() { + } - public Contact(Long id, String email) { - this.id = id; - this.email = email; - } + public Contact(Long id, String email) { + this.id = id; + this.email = email; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } public String getEmail() { - return email; - } - public void setEmail(String email) { - this.email = email; - } + return email; + } - public Set
      getAddresses() { - return addresses; - } - public void setAddresses(Set
      addresses) { - this.addresses = addresses; - } + public void setEmail(String email) { + this.email = email; + } + + public Set
      getAddresses() { + return addresses; + } + + public void setAddresses(Set
      addresses) { + this.addresses = addresses; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/notownedrelation/NotOwnedBidirectional.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/notownedrelation/NotOwnedBidirectional.java index 612fab0999..5596d82019 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/notownedrelation/NotOwnedBidirectional.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/notownedrelation/NotOwnedBidirectional.java @@ -24,91 +24,95 @@ package org.hibernate.envers.test.integration.inheritance.tableperclass.notownedrelation; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class NotOwnedBidirectional extends BaseEnversJPAFunctionalTestCase { - private Long pc_id; - private Long a1_id; - private Long a2_id; + private Long pc_id; + private Long a1_id; + private Long a2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { Address.class, Contact.class, PersonalContact.class }; - } + return new Class[] {Address.class, Contact.class, PersonalContact.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - pc_id = 1l; - a1_id = 10l; - a2_id = 100l; + pc_id = 1l; + a1_id = 10l; + a2_id = 100l; - // Rev 1 - em.getTransaction().begin(); + // Rev 1 + em.getTransaction().begin(); - PersonalContact pc = new PersonalContact(pc_id, "e", "f"); + PersonalContact pc = new PersonalContact( pc_id, "e", "f" ); - Address a1 = new Address(a1_id, "a1"); - a1.setContact(pc); + Address a1 = new Address( a1_id, "a1" ); + a1.setContact( pc ); - em.persist(pc); - em.persist(a1); + em.persist( pc ); + em.persist( a1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); + // Rev 2 + em.getTransaction().begin(); - pc = em.find(PersonalContact.class, pc_id); + pc = em.find( PersonalContact.class, pc_id ); - Address a2 = new Address(a2_id, "a2"); - a2.setContact(pc); + Address a2 = new Address( a2_id, "a2" ); + a2.setContact( pc ); - em.persist(a2); + em.persist( a2 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(Contact.class, pc_id)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(PersonalContact.class, pc_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( Contact.class, pc_id ) ); + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( PersonalContact.class, pc_id ) ); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(Address.class, a1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(Address.class, a1_id)); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( Address.class, a1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( Address.class, a1_id ) ); - assert Arrays.asList(2).equals(getAuditReader().getRevisions(Address.class, a2_id)); - assert Arrays.asList(2).equals(getAuditReader().getRevisions(Address.class, a2_id)); - } + assert Arrays.asList( 2 ).equals( getAuditReader().getRevisions( Address.class, a2_id ) ); + assert Arrays.asList( 2 ).equals( getAuditReader().getRevisions( Address.class, a2_id ) ); + } - @Test - public void testHistoryOfContact() { - assert getAuditReader().find(Contact.class, pc_id, 1).getAddresses().equals( - TestTools.makeSet(new Address(a1_id, "a1"))); + @Test + public void testHistoryOfContact() { + assert getAuditReader().find( Contact.class, pc_id, 1 ).getAddresses().equals( + TestTools.makeSet( new Address( a1_id, "a1" ) ) + ); - assert getAuditReader().find(Contact.class, pc_id, 2).getAddresses().equals( - TestTools.makeSet(new Address(a1_id, "a1"), new Address(a2_id, "a2"))); - } + assert getAuditReader().find( Contact.class, pc_id, 2 ).getAddresses().equals( + TestTools.makeSet( new Address( a1_id, "a1" ), new Address( a2_id, "a2" ) ) + ); + } - @Test - public void testHistoryOfPersonalContact() { - System.out.println(getAuditReader().find(PersonalContact.class, pc_id, 1).getAddresses()); - assert getAuditReader().find(PersonalContact.class, pc_id, 1).getAddresses().equals( - TestTools.makeSet(new Address(a1_id, "a1"))); + @Test + public void testHistoryOfPersonalContact() { + System.out.println( getAuditReader().find( PersonalContact.class, pc_id, 1 ).getAddresses() ); + assert getAuditReader().find( PersonalContact.class, pc_id, 1 ).getAddresses().equals( + TestTools.makeSet( new Address( a1_id, "a1" ) ) + ); - assert getAuditReader().find(PersonalContact.class, pc_id, 2).getAddresses().equals( - TestTools.makeSet(new Address(a1_id, "a1"), new Address(a2_id, "a2"))); - } + assert getAuditReader().find( PersonalContact.class, pc_id, 2 ).getAddresses().equals( + TestTools.makeSet( new Address( a1_id, "a1" ), new Address( a2_id, "a2" ) ) + ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/notownedrelation/PersonalContact.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/notownedrelation/PersonalContact.java index 647374ccfa..5aefdf77c2 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/notownedrelation/PersonalContact.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/notownedrelation/PersonalContact.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.tableperclass.notownedrelation; + import javax.persistence.Entity; import org.hibernate.envers.Audited; @@ -30,21 +31,21 @@ import org.hibernate.envers.Audited; @Entity @Audited public class PersonalContact extends Contact { - private String firstname; + private String firstname; - public PersonalContact() { - } + public PersonalContact() { + } - public PersonalContact(Long id, String email, String firstname) { - super(id, email); - this.firstname = firstname; - } + public PersonalContact(Long id, String email, String firstname) { + super( id, email ); + this.firstname = firstname; + } - public String getFirstname() { + public String getFirstname() { return firstname; } - public void setFirstname(String firstname) { + public void setFirstname(String firstname) { this.firstname = firstname; } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/relation/ChildIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/relation/ChildIngEntity.java index 2fd18872a0..6c2fc1aa75 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/relation/ChildIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/relation/ChildIngEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.tableperclass.relation; + import javax.persistence.Basic; import javax.persistence.Entity; @@ -34,44 +35,52 @@ import org.hibernate.envers.Audited; @Entity @Audited public class ChildIngEntity extends ParentIngEntity { - @Basic - private Long numVal; + @Basic + private Long numVal; - public ChildIngEntity() { - } + public ChildIngEntity() { + } - public ChildIngEntity(Integer id, String data, Long numVal) { - super(id, data); - this.numVal = numVal; - } + public ChildIngEntity(Integer id, String data, Long numVal) { + super( id, data ); + this.numVal = numVal; + } - public Long getNumVal() { - return numVal; - } + public Long getNumVal() { + return numVal; + } - public void setNumVal(Long numVal) { - this.numVal = numVal; - } + public void setNumVal(Long numVal) { + this.numVal = numVal; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ChildIngEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ChildIngEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ChildIngEntity childEntity = (ChildIngEntity) o; + ChildIngEntity childEntity = (ChildIngEntity) o; - if (numVal != null ? !numVal.equals(childEntity.numVal) : childEntity.numVal != null) return false; + if ( numVal != null ? !numVal.equals( childEntity.numVal ) : childEntity.numVal != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (numVal != null ? numVal.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (numVal != null ? numVal.hashCode() : 0); + return result; + } - public String toString() { - return "ChildIngEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; - } + public String toString() { + return "ChildIngEntity(id = " + getId() + ", data = " + getData() + ", numVal = " + numVal + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/relation/ParentIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/relation/ParentIngEntity.java index 32f8c12cb3..e342368712 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/relation/ParentIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/relation/ParentIngEntity.java @@ -23,6 +23,7 @@ */ package org.hibernate.envers.test.integration.inheritance.tableperclass.relation; + import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.Id; @@ -39,67 +40,75 @@ import org.hibernate.envers.Audited; @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) @Audited public class ParentIngEntity { - @Id - private Integer id; + @Id + private Integer id; - @Basic - private String data; + @Basic + private String data; - @ManyToOne - private ReferencedEntity referenced; + @ManyToOne + private ReferencedEntity referenced; - public ParentIngEntity() { - } + public ParentIngEntity() { + } - public ParentIngEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public ParentIngEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public ReferencedEntity getReferenced() { - return referenced; - } + public ReferencedEntity getReferenced() { + return referenced; + } - public void setReferenced(ReferencedEntity referenced) { - this.referenced = referenced; - } + public void setReferenced(ReferencedEntity referenced) { + this.referenced = referenced; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ParentIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ParentIngEntity) ) { + return false; + } - ParentIngEntity that = (ParentIngEntity) o; + ParentIngEntity that = (ParentIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "ParentIngEntity(id = " + getId() + ", data = " + getData() + ")"; - } + public String toString() { + return "ParentIngEntity(id = " + getId() + ", data = " + getData() + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/relation/PolymorphicCollection.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/relation/PolymorphicCollection.java index 4622934bf5..360bb82a5a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/relation/PolymorphicCollection.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/relation/PolymorphicCollection.java @@ -24,83 +24,85 @@ package org.hibernate.envers.test.integration.inheritance.tableperclass.relation; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class PolymorphicCollection extends BaseEnversJPAFunctionalTestCase { - private Integer ed_id1; - private Integer c_id; - private Integer p_id; + private Integer ed_id1; + private Integer c_id; + private Integer p_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ChildIngEntity.class, ParentIngEntity.class, ReferencedEntity.class }; - } + return new Class[] {ChildIngEntity.class, ParentIngEntity.class, ReferencedEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - ed_id1 = 1; - p_id = 10; - c_id = 100; + ed_id1 = 1; + p_id = 10; + c_id = 100; - // Rev 1 - em.getTransaction().begin(); + // Rev 1 + em.getTransaction().begin(); - ReferencedEntity re = new ReferencedEntity(ed_id1); - em.persist(re); + ReferencedEntity re = new ReferencedEntity( ed_id1 ); + em.persist( re ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); + // Rev 2 + em.getTransaction().begin(); - re = em.find(ReferencedEntity.class, ed_id1); + re = em.find( ReferencedEntity.class, ed_id1 ); - ParentIngEntity pie = new ParentIngEntity(p_id,"x"); - pie.setReferenced(re); - em.persist(pie); - p_id = pie.getId(); + ParentIngEntity pie = new ParentIngEntity( p_id, "x" ); + pie.setReferenced( re ); + em.persist( pie ); + p_id = pie.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 3 - em.getTransaction().begin(); + // Rev 3 + em.getTransaction().begin(); - re = em.find(ReferencedEntity.class, ed_id1); + re = em.find( ReferencedEntity.class, ed_id1 ); - ChildIngEntity cie = new ChildIngEntity(c_id, "y", 1l); - cie.setReferenced(re); - em.persist(cie); - c_id = cie.getId(); + ChildIngEntity cie = new ChildIngEntity( c_id, "y", 1l ); + cie.setReferenced( re ); + em.persist( cie ); + c_id = cie.getId(); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(ReferencedEntity.class, ed_id1)); - assert Arrays.asList(2).equals(getAuditReader().getRevisions(ParentIngEntity.class, p_id)); - assert Arrays.asList(3).equals(getAuditReader().getRevisions(ChildIngEntity.class, c_id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( ReferencedEntity.class, ed_id1 ) ); + assert Arrays.asList( 2 ).equals( getAuditReader().getRevisions( ParentIngEntity.class, p_id ) ); + assert Arrays.asList( 3 ).equals( getAuditReader().getRevisions( ChildIngEntity.class, c_id ) ); + } - @Test - public void testHistoryOfReferencedCollection() { - assert getAuditReader().find(ReferencedEntity.class, ed_id1, 1).getReferencing().size() == 0; - assert getAuditReader().find(ReferencedEntity.class, ed_id1, 2).getReferencing().equals( - TestTools.makeSet(new ParentIngEntity(p_id, "x"))); - assert getAuditReader().find(ReferencedEntity.class, ed_id1, 3).getReferencing().equals( - TestTools.makeSet(new ParentIngEntity(p_id, "x"), new ChildIngEntity(c_id, "y", 1l))); - } + @Test + public void testHistoryOfReferencedCollection() { + assert getAuditReader().find( ReferencedEntity.class, ed_id1, 1 ).getReferencing().size() == 0; + assert getAuditReader().find( ReferencedEntity.class, ed_id1, 2 ).getReferencing().equals( + TestTools.makeSet( new ParentIngEntity( p_id, "x" ) ) + ); + assert getAuditReader().find( ReferencedEntity.class, ed_id1, 3 ).getReferencing().equals( + TestTools.makeSet( new ParentIngEntity( p_id, "x" ), new ChildIngEntity( c_id, "y", 1l ) ) + ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/relation/ReferencedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/relation/ReferencedEntity.java index 79297a6c32..b7e12e8a71 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/relation/ReferencedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/inheritance/tableperclass/relation/ReferencedEntity.java @@ -23,10 +23,11 @@ */ package org.hibernate.envers.test.integration.inheritance.tableperclass.relation; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.util.Set; import org.hibernate.envers.Audited; @@ -36,51 +37,57 @@ import org.hibernate.envers.Audited; @Entity @Audited public class ReferencedEntity { - @Id - private Integer id; + @Id + private Integer id; - @OneToMany(mappedBy = "referenced") - private Set referencing; + @OneToMany(mappedBy = "referenced") + private Set referencing; - public ReferencedEntity() { - } + public ReferencedEntity() { + } - public ReferencedEntity(Integer id) { - this.id = id; - } + public ReferencedEntity(Integer id) { + this.id = id; + } - public Set getReferencing() { - return referencing; - } + public Set getReferencing() { + return referencing; + } - public void setReferencing(Set referencing) { - this.referencing = referencing; - } + public void setReferencing(Set referencing) { + this.referencing = referencing; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ReferencedEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ReferencedEntity) ) { + return false; + } - ReferencedEntity that = (ReferencedEntity) o; + ReferencedEntity that = (ReferencedEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - return id; - } + public int hashCode() { + return id; + } - public String toString() { - return "ReferencedEntity(id = " + getId() + ")"; - } + public String toString() { + return "ReferencedEntity(id = " + getId() + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/components/Component1.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/components/Component1.java index 29c3fae061..af89307640 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/components/Component1.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/components/Component1.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.interfaces.components; + import javax.persistence.Embeddable; /** @@ -29,7 +30,7 @@ import javax.persistence.Embeddable; */ @Embeddable public class Component1 implements IComponent { - private String data; + private String data; public Component1(String data) { this.data = data; @@ -48,12 +49,18 @@ public class Component1 implements IComponent { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Component1)) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof Component1) ) { + return false; + } Component1 that = (Component1) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/components/ComponentTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/components/ComponentTestEntity.java index 47fc53d81d..4901af1b80 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/components/ComponentTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/components/ComponentTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.interfaces.components; + import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -34,18 +35,18 @@ import org.hibernate.envers.Audited; * @author Adam Warski (adam at warski dot org) */ @Entity - @Audited +@Audited public class ComponentTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Embedded + @Embedded @Target(Component1.class) - private IComponent comp1; + private IComponent comp1; - public ComponentTestEntity() { - } + public ComponentTestEntity() { + } public ComponentTestEntity(IComponent comp1) { this.comp1 = comp1; @@ -57,12 +58,12 @@ public class ComponentTestEntity { } public Integer getId() { - return id; - } + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } public IComponent getComp1() { return comp1; @@ -74,12 +75,18 @@ public class ComponentTestEntity { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ComponentTestEntity)) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof ComponentTestEntity) ) { + return false; + } ComponentTestEntity that = (ComponentTestEntity) o; - if (comp1 != null ? !comp1.equals(that.comp1) : that.comp1 != null) return false; + if ( comp1 != null ? !comp1.equals( that.comp1 ) : that.comp1 != null ) { + return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/components/IComponent.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/components/IComponent.java index e0eebf6485..d3d7d7c159 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/components/IComponent.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/components/IComponent.java @@ -6,5 +6,6 @@ package org.hibernate.envers.test.integration.interfaces.components; */ public interface IComponent { String getData(); + void setData(String data); } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/components/InterfacesComponents.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/components/InterfacesComponents.java index ee3dbf8c36..f28e6032ad 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/components/InterfacesComponents.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/components/InterfacesComponents.java @@ -23,74 +23,74 @@ */ package org.hibernate.envers.test.integration.interfaces.components; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class InterfacesComponents extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ComponentTestEntity.class }; - } + return new Class[] {ComponentTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - ComponentTestEntity cte1 = new ComponentTestEntity(new Component1("a")); + ComponentTestEntity cte1 = new ComponentTestEntity( new Component1( "a" ) ); - em.persist(cte1); + em.persist( cte1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 2 + em = getEntityManager(); + em.getTransaction().begin(); - cte1 = em.find(ComponentTestEntity.class, cte1.getId()); + cte1 = em.find( ComponentTestEntity.class, cte1.getId() ); - cte1.setComp1(new Component1("b")); + cte1.setComp1( new Component1( "b" ) ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 3 + em = getEntityManager(); + em.getTransaction().begin(); - cte1 = em.find(ComponentTestEntity.class, cte1.getId()); + cte1 = em.find( ComponentTestEntity.class, cte1.getId() ); - cte1.getComp1().setData("c"); + cte1.getComp1().setData( "c" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - id1 = cte1.getId(); - } + id1 = cte1.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(ComponentTestEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( ComponentTestEntity.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - ComponentTestEntity ver1 = new ComponentTestEntity(id1, new Component1("a")); - ComponentTestEntity ver2 = new ComponentTestEntity(id1, new Component1("b")); - ComponentTestEntity ver3 = new ComponentTestEntity(id1, new Component1("c")); + @Test + public void testHistoryOfId1() { + ComponentTestEntity ver1 = new ComponentTestEntity( id1, new Component1( "a" ) ); + ComponentTestEntity ver2 = new ComponentTestEntity( id1, new Component1( "b" ) ); + ComponentTestEntity ver3 = new ComponentTestEntity( id1, new Component1( "c" ) ); - assert getAuditReader().find(ComponentTestEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(ComponentTestEntity.class, id1, 2).equals(ver2); - assert getAuditReader().find(ComponentTestEntity.class, id1, 3).equals(ver3); - } + assert getAuditReader().find( ComponentTestEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( ComponentTestEntity.class, id1, 2 ).equals( ver2 ); + assert getAuditReader().find( ComponentTestEntity.class, id1, 3 ).equals( ver3 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/AbstractAllAuditedTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/AbstractAllAuditedTest.java index a4f858f1b8..9938e67fd3 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/AbstractAllAuditedTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/AbstractAllAuditedTest.java @@ -1,15 +1,15 @@ package org.hibernate.envers.test.integration.interfaces.hbm.allAudited; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.exception.NotAuditedException; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Assert; +import org.junit.Test; + /** * @author Hern�n Chanfreau * @author Adam Warski (adam at warski dot org) @@ -17,106 +17,107 @@ import org.hibernate.envers.test.Priority; public abstract class AbstractAllAuditedTest extends BaseEnversJPAFunctionalTestCase { private long ai_id; private long nai_id; - - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - AuditedImplementor ai = new AuditedImplementor(); - ai.setData("La data"); - ai.setAuditedImplementorData("audited implementor data"); - - NonAuditedImplementor nai = new NonAuditedImplementor(); - nai.setData("info"); - nai.setNonAuditedImplementorData("sttring"); - - // Revision 1 - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - em.persist(ai); - - em.persist(nai); + AuditedImplementor ai = new AuditedImplementor(); + ai.setData( "La data" ); + ai.setAuditedImplementorData( "audited implementor data" ); - em.getTransaction().commit(); + NonAuditedImplementor nai = new NonAuditedImplementor(); + nai.setData( "info" ); + nai.setNonAuditedImplementorData( "sttring" ); - // Revision 2 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - ai = em.find(AuditedImplementor.class, ai.getId()); - nai = em.find(NonAuditedImplementor.class, nai.getId()); + em.persist( ai ); - ai.setData("La data 2"); - ai.setAuditedImplementorData("audited implementor data 2"); + em.persist( nai ); - nai.setData("info 2"); - nai.setNonAuditedImplementorData("sttring 2"); + em.getTransaction().commit(); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); - // + ai = em.find( AuditedImplementor.class, ai.getId() ); + nai = em.find( NonAuditedImplementor.class, nai.getId() ); - ai_id = ai.getId(); - nai_id = nai.getId(); - } + ai.setData( "La data 2" ); + ai.setAuditedImplementorData( "audited implementor data 2" ); - @Test - public void testRevisions() { - Assert.assertEquals(getAuditReader().getRevisions(AuditedImplementor.class, ai_id), Arrays.asList(1, 2)); - } + nai.setData( "info 2" ); + nai.setNonAuditedImplementorData( "sttring 2" ); - @Test - public void testRetrieveAudited() { - // levanto las versiones actuales - AuditedImplementor ai = getEntityManager().find(AuditedImplementor.class, ai_id); - assert ai != null; - SimpleInterface si = getEntityManager().find(SimpleInterface.class, ai_id); - assert si != null; + em.getTransaction().commit(); - // levanto las de la revisi�n 1, ninguna debe ser null - AuditedImplementor ai_rev1 = getAuditReader().find(AuditedImplementor.class, ai_id, 1); - assert ai_rev1 != null; - SimpleInterface si_rev1 = getAuditReader().find(SimpleInterface.class, ai_id, 1); - assert si_rev1 != null; + // - AuditedImplementor ai_rev2 = getAuditReader().find(AuditedImplementor.class, ai_id, 2); - assert ai_rev2 != null; - SimpleInterface si_rev2 = getAuditReader().find(SimpleInterface.class, ai_id, 2); - assert si_rev2 != null; - - // data de las actuales no debe ser null - Assert.assertEquals(ai.getData(), "La data 2"); - Assert.assertEquals(si.getData(), "La data 2"); - // la data de las revisiones no debe ser null - Assert.assertEquals(ai_rev1.getData(), "La data"); - Assert.assertEquals(si_rev1.getData(), "La data"); + ai_id = ai.getId(); + nai_id = nai.getId(); + } - Assert.assertEquals(ai_rev2.getData(), "La data 2"); - Assert.assertEquals(si_rev2.getData(), "La data 2"); - } - - @Test - public void testRetrieveNonAudited() { - // levanto las versiones actuales - NonAuditedImplementor nai = getEntityManager().find(NonAuditedImplementor.class, nai_id); - assert nai != null; - SimpleInterface si = getEntityManager().find(SimpleInterface.class, nai_id); - assert si != null; - - assert si.getData().equals(nai.getData()); + @Test + public void testRevisions() { + Assert.assertEquals( getAuditReader().getRevisions( AuditedImplementor.class, ai_id ), Arrays.asList( 1, 2 ) ); + } - try { - // levanto la revision - getAuditReader().find(NonAuditedImplementor.class, nai_id, 1); - assert false; - } catch (Exception e) { - // no es auditable!!! - assert (e instanceof NotAuditedException); + @Test + public void testRetrieveAudited() { + // levanto las versiones actuales + AuditedImplementor ai = getEntityManager().find( AuditedImplementor.class, ai_id ); + assert ai != null; + SimpleInterface si = getEntityManager().find( SimpleInterface.class, ai_id ); + assert si != null; + + // levanto las de la revisi�n 1, ninguna debe ser null + AuditedImplementor ai_rev1 = getAuditReader().find( AuditedImplementor.class, ai_id, 1 ); + assert ai_rev1 != null; + SimpleInterface si_rev1 = getAuditReader().find( SimpleInterface.class, ai_id, 1 ); + assert si_rev1 != null; + + AuditedImplementor ai_rev2 = getAuditReader().find( AuditedImplementor.class, ai_id, 2 ); + assert ai_rev2 != null; + SimpleInterface si_rev2 = getAuditReader().find( SimpleInterface.class, ai_id, 2 ); + assert si_rev2 != null; + + // data de las actuales no debe ser null + Assert.assertEquals( ai.getData(), "La data 2" ); + Assert.assertEquals( si.getData(), "La data 2" ); + // la data de las revisiones no debe ser null + Assert.assertEquals( ai_rev1.getData(), "La data" ); + Assert.assertEquals( si_rev1.getData(), "La data" ); + + Assert.assertEquals( ai_rev2.getData(), "La data 2" ); + Assert.assertEquals( si_rev2.getData(), "La data 2" ); + } + + @Test + public void testRetrieveNonAudited() { + // levanto las versiones actuales + NonAuditedImplementor nai = getEntityManager().find( NonAuditedImplementor.class, nai_id ); + assert nai != null; + SimpleInterface si = getEntityManager().find( SimpleInterface.class, nai_id ); + assert si != null; + + assert si.getData().equals( nai.getData() ); + + try { + // levanto la revision + getAuditReader().find( NonAuditedImplementor.class, nai_id, 1 ); + assert false; } - - // levanto la revision que no es auditable pero con la interfaz, el resultado debe ser null - SimpleInterface si_rev1 = getAuditReader().find(SimpleInterface.class, nai_id, 1); - assert si_rev1 == null; - - } + catch (Exception e) { + // no es auditable!!! + assert (e instanceof NotAuditedException); + } + + // levanto la revision que no es auditable pero con la interfaz, el resultado debe ser null + SimpleInterface si_rev1 = getAuditReader().find( SimpleInterface.class, nai_id, 1 ); + assert si_rev1 == null; + + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/AuditedImplementor.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/AuditedImplementor.java index fd10b8ae78..f134b0e38d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/AuditedImplementor.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/AuditedImplementor.java @@ -1,9 +1,9 @@ package org.hibernate.envers.test.integration.interfaces.hbm.allAudited; + import org.hibernate.envers.Audited; /** * @author Hern�n Chanfreau - * */ @Audited public class AuditedImplementor implements SimpleInterface { diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/NonAuditedImplementor.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/NonAuditedImplementor.java index c85ab20d75..83dce67de6 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/NonAuditedImplementor.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/NonAuditedImplementor.java @@ -1,10 +1,8 @@ package org.hibernate.envers.test.integration.interfaces.hbm.allAudited; - /** * @author Hern�n Chanfreau - * */ public class NonAuditedImplementor implements SimpleInterface { private long id; diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/SimpleInterface.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/SimpleInterface.java index 8995125430..97d6fa3e44 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/SimpleInterface.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/SimpleInterface.java @@ -1,19 +1,19 @@ package org.hibernate.envers.test.integration.interfaces.hbm.allAudited; + import org.hibernate.envers.Audited; /** * @author Hern�n Chanfreau - * */ @Audited public interface SimpleInterface { - + long getId(); - + void setId(long id); - + String getData(); - + void setData(String data); } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/joined/JoinedAllAuditedTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/joined/JoinedAllAuditedTest.java index 0589bd6c83..0242ecf0dd 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/joined/JoinedAllAuditedTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/joined/JoinedAllAuditedTest.java @@ -6,8 +6,8 @@ import org.hibernate.envers.test.integration.interfaces.hbm.allAudited.AbstractA * @author Hern�n Chanfreau */ public class JoinedAllAuditedTest extends AbstractAllAuditedTest { - @Override - protected String[] getMappings() { - return new String[]{"mappings/interfaces/joinedAllAuditedMappings.hbm.xml"}; - } + @Override + protected String[] getMappings() { + return new String[] {"mappings/interfaces/joinedAllAuditedMappings.hbm.xml"}; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/subclass/SubclassAllAuditedTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/subclass/SubclassAllAuditedTest.java index 3cf243f48c..6cbb92252d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/subclass/SubclassAllAuditedTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/subclass/SubclassAllAuditedTest.java @@ -6,8 +6,8 @@ import org.hibernate.envers.test.integration.interfaces.hbm.allAudited.AbstractA * @author Hern�n Chanfreau */ public class SubclassAllAuditedTest extends AbstractAllAuditedTest { - @Override - protected String[] getMappings() { - return new String[]{"mappings/interfaces/subclassAllAuditedMappings.hbm.xml"}; - } + @Override + protected String[] getMappings() { + return new String[] {"mappings/interfaces/subclassAllAuditedMappings.hbm.xml"}; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/union/UnionAllAuditedTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/union/UnionAllAuditedTest.java index b84209dea1..033741a0d7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/union/UnionAllAuditedTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/allAudited/union/UnionAllAuditedTest.java @@ -6,8 +6,8 @@ import org.hibernate.envers.test.integration.interfaces.hbm.allAudited.AbstractA * @author Hern�n Chanfreau */ public class UnionAllAuditedTest extends AbstractAllAuditedTest { - @Override - protected String[] getMappings() { - return new String[]{"mappings/interfaces/unionAllAuditedMappings.hbm.xml"}; - } + @Override + protected String[] getMappings() { + return new String[] {"mappings/interfaces/unionAllAuditedMappings.hbm.xml"}; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/AbstractPropertiesAuditedTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/AbstractPropertiesAuditedTest.java index f85c393403..5bf313b22b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/AbstractPropertiesAuditedTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/AbstractPropertiesAuditedTest.java @@ -2,43 +2,42 @@ package org.hibernate.envers.test.integration.interfaces.hbm.propertiesAudited; import javax.persistence.EntityManager; -import org.junit.Test; - import org.hibernate.envers.exception.NotAuditedException; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Hern�n Chanfreau - * */ -public abstract class AbstractPropertiesAuditedTest extends BaseEnversJPAFunctionalTestCase { +public abstract class AbstractPropertiesAuditedTest extends BaseEnversJPAFunctionalTestCase { private long ai_id; private long nai_id; private static int NUMERITO = 555; @Test - @Priority(10) + @Priority(10) public void initData() { EntityManager em = getEntityManager(); AuditedImplementor ai = new AuditedImplementor(); - ai.setData("La data"); - ai.setAuditedImplementorData("audited implementor data"); - ai.setNumerito(NUMERITO); + ai.setData( "La data" ); + ai.setAuditedImplementorData( "audited implementor data" ); + ai.setNumerito( NUMERITO ); NonAuditedImplementor nai = new NonAuditedImplementor(); - nai.setData("info"); - nai.setNonAuditedImplementorData("sttring"); - nai.setNumerito(NUMERITO); + nai.setData( "info" ); + nai.setNonAuditedImplementorData( "sttring" ); + nai.setNumerito( NUMERITO ); // Revision 1 em.getTransaction().begin(); - em.persist(ai); + em.persist( ai ); - em.persist(nai); + em.persist( nai ); em.getTransaction().commit(); @@ -54,18 +53,24 @@ public abstract class AbstractPropertiesAuditedTest extends BaseEnversJPAFunctio public void testRetrieveAudited() { // levanto las versiones actuales AuditedImplementor ai = getEntityManager().find( - AuditedImplementor.class, ai_id); + AuditedImplementor.class, ai_id + ); assert ai != null; - SimpleInterface si = getEntityManager().find(SimpleInterface.class, - ai_id); + SimpleInterface si = getEntityManager().find( + SimpleInterface.class, + ai_id + ); assert si != null; // levanto las de la revisi�n 1, ninguna debe ser null AuditedImplementor ai_rev1 = getAuditReader().find( - AuditedImplementor.class, ai_id, 1); + AuditedImplementor.class, ai_id, 1 + ); assert ai_rev1 != null; - SimpleInterface si_rev1 = getAuditReader().find(SimpleInterface.class, - ai_id, 1); + SimpleInterface si_rev1 = getAuditReader().find( + SimpleInterface.class, + ai_id, 1 + ); assert si_rev1 != null; // data de las actuales no debe ser null @@ -83,27 +88,33 @@ public abstract class AbstractPropertiesAuditedTest extends BaseEnversJPAFunctio public void testRetrieveNonAudited() { // levanto las versiones actuales NonAuditedImplementor nai = getEntityManager().find( - NonAuditedImplementor.class, nai_id); + NonAuditedImplementor.class, nai_id + ); assert nai != null; - SimpleInterface si = getEntityManager().find(SimpleInterface.class, - nai_id); + SimpleInterface si = getEntityManager().find( + SimpleInterface.class, + nai_id + ); assert si != null; - assert si.getData().equals(nai.getData()); + assert si.getData().equals( nai.getData() ); try { // levanto la revision - getAuditReader().find(NonAuditedImplementor.class, nai_id, 1); + getAuditReader().find( NonAuditedImplementor.class, nai_id, 1 ); assert false; - } catch (Exception e) { + } + catch (Exception e) { // no es auditable!!! assert (e instanceof NotAuditedException); } // levanto la revision que no es auditable pero con la interfaz, el // resultado debe ser null - SimpleInterface si_rev1 = getAuditReader().find(SimpleInterface.class, - nai_id, 1); + SimpleInterface si_rev1 = getAuditReader().find( + SimpleInterface.class, + nai_id, 1 + ); assert si_rev1 == null; } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/AuditedImplementor.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/AuditedImplementor.java index 0289ffbe38..608b58849e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/AuditedImplementor.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/AuditedImplementor.java @@ -1,9 +1,9 @@ package org.hibernate.envers.test.integration.interfaces.hbm.propertiesAudited; + import org.hibernate.envers.Audited; /** * @author Hern�n Chanfreau - * */ @Audited public class AuditedImplementor implements SimpleInterface { @@ -38,7 +38,7 @@ public class AuditedImplementor implements SimpleInterface { public void setAuditedImplementorData(String implementorData) { this.auditedImplementorData = implementorData; } - + public int getNumerito() { return numerito; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/SimpleInterface.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/SimpleInterface.java index a125fca35f..08b5d55b64 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/SimpleInterface.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/SimpleInterface.java @@ -1,23 +1,23 @@ package org.hibernate.envers.test.integration.interfaces.hbm.propertiesAudited; + import org.hibernate.envers.Audited; /** * @author Hern�n Chanfreau - * */ public interface SimpleInterface { - + long getId(); - + void setId(long id); - + String getData(); - + void setData(String data); - + @Audited int getNumerito(); - + void setNumerito(int num); } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/joined/JoinedPropertiesAuditedTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/joined/JoinedPropertiesAuditedTest.java index a75f556ae3..ee043e4e48 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/joined/JoinedPropertiesAuditedTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/joined/JoinedPropertiesAuditedTest.java @@ -4,12 +4,11 @@ import org.hibernate.envers.test.integration.interfaces.hbm.propertiesAudited.Ab /** * @author Hern�n Chanfreau - * */ public class JoinedPropertiesAuditedTest extends AbstractPropertiesAuditedTest { @Override protected String[] getMappings() { - return new String[] { "mappings/interfaces/joinedPropertiesAuditedMappings.hbm.xml" }; - } + return new String[] {"mappings/interfaces/joinedPropertiesAuditedMappings.hbm.xml"}; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/subclass/SubclassPropertiesAuditedTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/subclass/SubclassPropertiesAuditedTest.java index fb50cf33b0..7caf878627 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/subclass/SubclassPropertiesAuditedTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/subclass/SubclassPropertiesAuditedTest.java @@ -4,11 +4,10 @@ import org.hibernate.envers.test.integration.interfaces.hbm.propertiesAudited.Ab /** * @author Hern�n Chanfreau - * */ public class SubclassPropertiesAuditedTest extends AbstractPropertiesAuditedTest { @Override protected String[] getMappings() { - return new String[] { "mappings/interfaces/subclassPropertiesAuditedMappings.hbm.xml" }; + return new String[] {"mappings/interfaces/subclassPropertiesAuditedMappings.hbm.xml"}; } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/union/UnionPropertiesAuditedTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/union/UnionPropertiesAuditedTest.java index 39a5da77bd..1ec2f8b854 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/union/UnionPropertiesAuditedTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited/union/UnionPropertiesAuditedTest.java @@ -4,12 +4,11 @@ import org.hibernate.envers.test.integration.interfaces.hbm.propertiesAudited.Ab /** * @author Hern�n Chanfreau - * */ public class UnionPropertiesAuditedTest extends AbstractPropertiesAuditedTest { @Override protected String[] getMappings() { - return new String[] { "mappings/interfaces/unionPropertiesAuditedMappings.hbm.xml" }; - } + return new String[] {"mappings/interfaces/unionPropertiesAuditedMappings.hbm.xml"}; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/AbstractPropertiesAudited2Test.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/AbstractPropertiesAudited2Test.java index 2d287a8810..e87a27ca39 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/AbstractPropertiesAudited2Test.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/AbstractPropertiesAudited2Test.java @@ -2,15 +2,14 @@ package org.hibernate.envers.test.integration.interfaces.hbm.propertiesAudited2; import javax.persistence.EntityManager; -import org.junit.Test; - import org.hibernate.envers.exception.NotAuditedException; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Hern�n Chanfreau - * */ public abstract class AbstractPropertiesAudited2Test extends BaseEnversJPAFunctionalTestCase { private long ai_id; @@ -19,26 +18,26 @@ public abstract class AbstractPropertiesAudited2Test extends BaseEnversJPAFuncti private static int NUMERITO = 555; @Test - @Priority(10) + @Priority(10) public void initData() { EntityManager em = getEntityManager(); AuditedImplementor ai = new AuditedImplementor(); - ai.setData("La data"); - ai.setAuditedImplementorData("audited implementor data"); - ai.setNumerito(NUMERITO); + ai.setData( "La data" ); + ai.setAuditedImplementorData( "audited implementor data" ); + ai.setNumerito( NUMERITO ); NonAuditedImplementor nai = new NonAuditedImplementor(); - nai.setData("info"); - nai.setNonAuditedImplementorData("sttring"); - nai.setNumerito(NUMERITO); + nai.setData( "info" ); + nai.setNonAuditedImplementorData( "sttring" ); + nai.setNumerito( NUMERITO ); // Revision 1 em.getTransaction().begin(); - em.persist(ai); + em.persist( ai ); - em.persist(nai); + em.persist( nai ); em.getTransaction().commit(); @@ -54,18 +53,24 @@ public abstract class AbstractPropertiesAudited2Test extends BaseEnversJPAFuncti public void testRetrieveAudited() { // levanto las versiones actuales AuditedImplementor ai = getEntityManager().find( - AuditedImplementor.class, ai_id); + AuditedImplementor.class, ai_id + ); assert ai != null; - SimpleInterface si = getEntityManager().find(SimpleInterface.class, - ai_id); + SimpleInterface si = getEntityManager().find( + SimpleInterface.class, + ai_id + ); assert si != null; // levanto las de la revisi�n 1, ninguna debe ser null AuditedImplementor ai_rev1 = getAuditReader().find( - AuditedImplementor.class, ai_id, 1); + AuditedImplementor.class, ai_id, 1 + ); assert ai_rev1 != null; - SimpleInterface si_rev1 = getAuditReader().find(SimpleInterface.class, - ai_id, 1); + SimpleInterface si_rev1 = getAuditReader().find( + SimpleInterface.class, + ai_id, 1 + ); assert si_rev1 != null; // data de las actuales no debe ser null @@ -83,27 +88,33 @@ public abstract class AbstractPropertiesAudited2Test extends BaseEnversJPAFuncti public void testRetrieveNonAudited() { // levanto las versiones actuales NonAuditedImplementor nai = getEntityManager().find( - NonAuditedImplementor.class, nai_id); + NonAuditedImplementor.class, nai_id + ); assert nai != null; - SimpleInterface si = getEntityManager().find(SimpleInterface.class, - nai_id); + SimpleInterface si = getEntityManager().find( + SimpleInterface.class, + nai_id + ); assert si != null; - assert si.getData().equals(nai.getData()); + assert si.getData().equals( nai.getData() ); try { // levanto la revision - getAuditReader().find(NonAuditedImplementor.class, nai_id, 1); + getAuditReader().find( NonAuditedImplementor.class, nai_id, 1 ); assert false; - } catch (Exception e) { + } + catch (Exception e) { // no es auditable!!! assert (e instanceof NotAuditedException); } // levanto la revision que no es auditable pero con la interfaz, el // resultado debe ser null - SimpleInterface si_rev1 = getAuditReader().find(SimpleInterface.class, - nai_id, 1); + SimpleInterface si_rev1 = getAuditReader().find( + SimpleInterface.class, + nai_id, 1 + ); assert si_rev1 == null; } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/AuditedImplementor.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/AuditedImplementor.java index 6e9c88b82d..8c736a9278 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/AuditedImplementor.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/AuditedImplementor.java @@ -1,9 +1,9 @@ package org.hibernate.envers.test.integration.interfaces.hbm.propertiesAudited2; + import org.hibernate.envers.Audited; /** * @author Hern�n Chanfreau - * */ @Audited public class AuditedImplementor implements SimpleInterface { @@ -38,7 +38,7 @@ public class AuditedImplementor implements SimpleInterface { public void setAuditedImplementorData(String implementorData) { this.auditedImplementorData = implementorData; } - + public int getNumerito() { return numerito; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/NonAuditedImplementor.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/NonAuditedImplementor.java index 356a686bd9..c252c6a7cb 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/NonAuditedImplementor.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/NonAuditedImplementor.java @@ -3,7 +3,6 @@ package org.hibernate.envers.test.integration.interfaces.hbm.propertiesAudited2; /** * @author Hern�n Chanfreau - * */ public class NonAuditedImplementor implements SimpleInterface { private long id; @@ -37,7 +36,7 @@ public class NonAuditedImplementor implements SimpleInterface { public void setNonAuditedImplementorData(String implementorData) { this.nonAuditedImplementorData = implementorData; } - + public int getNumerito() { return numerito; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/SimpleInterface.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/SimpleInterface.java index 4b7d4e1c2d..ba7153ab49 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/SimpleInterface.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/SimpleInterface.java @@ -1,24 +1,24 @@ package org.hibernate.envers.test.integration.interfaces.hbm.propertiesAudited2; + import org.hibernate.envers.Audited; /** * @author Hern�n Chanfreau - * */ public interface SimpleInterface { - + long getId(); - + void setId(long id); - + @Audited String getData(); - + void setData(String data); - + @Audited int getNumerito(); - + void setNumerito(int num); } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/joined/JoinedPropertiesAudited2Test.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/joined/JoinedPropertiesAudited2Test.java index ab69c7c6ce..7f4acf5475 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/joined/JoinedPropertiesAudited2Test.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/joined/JoinedPropertiesAudited2Test.java @@ -8,6 +8,6 @@ import org.hibernate.envers.test.integration.interfaces.hbm.propertiesAudited2.A public class JoinedPropertiesAudited2Test extends AbstractPropertiesAudited2Test { @Override protected String[] getMappings() { - return new String[] { "mappings/interfaces/joinedPropertiesAudited2Mappings.hbm.xml" }; + return new String[] {"mappings/interfaces/joinedPropertiesAudited2Mappings.hbm.xml"}; } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/subclass/SubclassPropertiesAudited2Test.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/subclass/SubclassPropertiesAudited2Test.java index 9bc97c4979..1adce3c08e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/subclass/SubclassPropertiesAudited2Test.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/subclass/SubclassPropertiesAudited2Test.java @@ -4,12 +4,11 @@ import org.hibernate.envers.test.integration.interfaces.hbm.propertiesAudited2.A /** * @author Hern�n Chanfreau - * */ public class SubclassPropertiesAudited2Test extends AbstractPropertiesAudited2Test { @Override protected String[] getMappings() { - return new String[] { "mappings/interfaces/subclassPropertiesAudited2Mappings.hbm.xml" }; - } - + return new String[] {"mappings/interfaces/subclassPropertiesAudited2Mappings.hbm.xml"}; + } + } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/union/UnionPropertiesAudited2Test.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/union/UnionPropertiesAudited2Test.java index 5c1791599e..01088eafb8 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/union/UnionPropertiesAudited2Test.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/hbm/propertiesAudited2/union/UnionPropertiesAudited2Test.java @@ -4,11 +4,10 @@ import org.hibernate.envers.test.integration.interfaces.hbm.propertiesAudited2.A /** * @author Hern�n Chanfreau - * */ public class UnionPropertiesAudited2Test extends AbstractPropertiesAudited2Test { @Override protected String[] getMappings() { - return new String[] { "mappings/interfaces/unionPropertiesAudited2Mappings.hbm.xml" }; - } + return new String[] {"mappings/interfaces/unionPropertiesAudited2Mappings.hbm.xml"}; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/relation/InterfacesRelation.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/relation/InterfacesRelation.java index c4c3850c6c..2938caa36c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/relation/InterfacesRelation.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/relation/InterfacesRelation.java @@ -23,94 +23,94 @@ */ package org.hibernate.envers.test.integration.interfaces.relation; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class InterfacesRelation extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; + private Integer ing1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SetRefEdEntity.class, SetRefIngEntity.class }; - } + return new Class[] {SetRefEdEntity.class, SetRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - SetRefEdEntity ed1 = new SetRefEdEntity(1, "data_ed_1"); - SetRefEdEntity ed2 = new SetRefEdEntity(2, "data_ed_2"); + SetRefEdEntity ed1 = new SetRefEdEntity( 1, "data_ed_1" ); + SetRefEdEntity ed2 = new SetRefEdEntity( 2, "data_ed_2" ); - SetRefIngEntity ing1 = new SetRefIngEntity(3, "data_ing_1"); + SetRefIngEntity ing1 = new SetRefIngEntity( 3, "data_ing_1" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); + em.persist( ed1 ); + em.persist( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 + // Revision 2 - em.getTransaction().begin(); + em.getTransaction().begin(); - ed1 = em.find(SetRefEdEntity.class, ed1.getId()); + ed1 = em.find( SetRefEdEntity.class, ed1.getId() ); - ing1.setReference(ed1); - em.persist(ing1); + ing1.setReference( ed1 ); + em.persist( ing1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - ing1 = em.find(SetRefIngEntity.class, ing1.getId()); - ed2 = em.find(SetRefEdEntity.class, ed2.getId()); + ing1 = em.find( SetRefIngEntity.class, ing1.getId() ); + ed2 = em.find( SetRefEdEntity.class, ed2.getId() ); - ing1.setReference(ed2); + ing1.setReference( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); - ing1_id = ing1.getId(); - } + ing1_id = ing1.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1).equals(getAuditReader().getRevisions(SetRefEdEntity.class, ed1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(SetRefEdEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( SetRefEdEntity.class, ed1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( SetRefEdEntity.class, ed2_id ) ); - assert Arrays.asList(2, 3).equals(getAuditReader().getRevisions(SetRefIngEntity.class, ing1_id)); - } + assert Arrays.asList( 2, 3 ).equals( getAuditReader().getRevisions( SetRefIngEntity.class, ing1_id ) ); + } - @Test - public void testHistoryOfEdIng1() { - SetRefEdEntity ed1 = getEntityManager().find(SetRefEdEntity.class, ed1_id); - SetRefEdEntity ed2 = getEntityManager().find(SetRefEdEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng1() { + SetRefEdEntity ed1 = getEntityManager().find( SetRefEdEntity.class, ed1_id ); + SetRefEdEntity ed2 = getEntityManager().find( SetRefEdEntity.class, ed2_id ); - SetRefIngEntity rev1 = getAuditReader().find(SetRefIngEntity.class, ing1_id, 1); - SetRefIngEntity rev2 = getAuditReader().find(SetRefIngEntity.class, ing1_id, 2); - SetRefIngEntity rev3 = getAuditReader().find(SetRefIngEntity.class, ing1_id, 3); + SetRefIngEntity rev1 = getAuditReader().find( SetRefIngEntity.class, ing1_id, 1 ); + SetRefIngEntity rev2 = getAuditReader().find( SetRefIngEntity.class, ing1_id, 2 ); + SetRefIngEntity rev3 = getAuditReader().find( SetRefIngEntity.class, ing1_id, 3 ); - assert rev1 == null; - assert rev2.getReference().equals(ed1); - assert rev3.getReference().equals(ed2); - } + assert rev1 == null; + assert rev2.getReference().equals( ed1 ); + assert rev3.getReference().equals( ed2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/relation/SetRefEdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/relation/SetRefEdEntity.java index fa984be5eb..bb17a45716 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/relation/SetRefEdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/relation/SetRefEdEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.interfaces.relation; + import javax.persistence.Entity; import javax.persistence.Id; @@ -29,64 +30,73 @@ import org.hibernate.envers.Audited; /** * ReferencEd entity + * * @author Adam Warski (adam at warski dot org) */ @Entity @Audited public class SetRefEdEntity implements ISetRefEdEntity { - @Id - private Integer id; + @Id + private Integer id; - private String data; + private String data; - public SetRefEdEntity() { - } + public SetRefEdEntity() { + } - public SetRefEdEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public SetRefEdEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public SetRefEdEntity(String data) { - this.data = data; - } + public SetRefEdEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SetRefEdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SetRefEdEntity) ) { + return false; + } - SetRefEdEntity that = (SetRefEdEntity) o; + SetRefEdEntity that = (SetRefEdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetRefEdEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "SetRefEdEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/relation/SetRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/relation/SetRefIngEntity.java index 207305c41a..d45eb04901 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/relation/SetRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/interfaces/relation/SetRefIngEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.interfaces.relation; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToOne; @@ -30,82 +31,92 @@ import org.hibernate.envers.Audited; /** * ReferencIng entity + * * @author Adam Warski (adam at warski dot org) */ @Entity public class SetRefIngEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToOne(targetEntity = SetRefEdEntity.class) - private ISetRefEdEntity reference; + @Audited + @ManyToOne(targetEntity = SetRefEdEntity.class) + private ISetRefEdEntity reference; - public SetRefIngEntity() { } + public SetRefIngEntity() { + } - public SetRefIngEntity(Integer id, String data, ISetRefEdEntity reference) { - this.id = id; - this.data = data; - this.reference = reference; - } + public SetRefIngEntity(Integer id, String data, ISetRefEdEntity reference) { + this.id = id; + this.data = data; + this.reference = reference; + } - public SetRefIngEntity(String data, ISetRefEdEntity reference) { - this.data = data; - this.reference = reference; - } + public SetRefIngEntity(String data, ISetRefEdEntity reference) { + this.data = data; + this.reference = reference; + } - public SetRefIngEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public SetRefIngEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public ISetRefEdEntity getReference() { - return reference; - } + public ISetRefEdEntity getReference() { + return reference; + } - public void setReference(ISetRefEdEntity reference) { - this.reference = reference; - } + public void setReference(ISetRefEdEntity reference) { + this.reference = reference; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SetRefIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SetRefIngEntity) ) { + return false; + } - SetRefIngEntity that = (SetRefIngEntity) o; + SetRefIngEntity that = (SetRefIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "SetRefIngEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "SetRefIngEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/jta/JtaExceptionListener.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/jta/JtaExceptionListener.java index 643f41bf35..476ad0c1b3 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/jta/JtaExceptionListener.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/jta/JtaExceptionListener.java @@ -23,63 +23,67 @@ */ package org.hibernate.envers.test.integration.jta; -import java.util.Map; import javax.persistence.EntityManager; import javax.transaction.RollbackException; - -import org.junit.Assert; -import org.junit.Test; +import java.util.Map; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.integration.reventity.ExceptionListenerRevEntity; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.jta.TestingJtaBootstrap; import org.hibernate.testing.jta.TestingJtaPlatformImpl; /** * Same as {@link org.hibernate.envers.test.integration.reventity.ExceptionListener}, but in a JTA environment. + * * @author Adam Warski (adam at warski dot org) */ public class JtaExceptionListener extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class, ExceptionListenerRevEntity.class }; - } + return new Class[] {StrTestEntity.class, ExceptionListenerRevEntity.class}; + } - @Override - protected void addConfigOptions(Map options) { - TestingJtaBootstrap.prepare(options); - } + @Override + protected void addConfigOptions(Map options) { + TestingJtaBootstrap.prepare( options ); + } - @Test(expected = RollbackException.class) - @Priority(5) // must run before testDataNotPersisted() - public void testTransactionRollback() throws Exception { + @Test(expected = RollbackException.class) + @Priority(5) // must run before testDataNotPersisted() + public void testTransactionRollback() throws Exception { TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin(); - try { + try { EntityManager em = getEntityManager(); - // Trying to persist an entity - however the listener should throw an exception, so the entity - // shouldn't be persisted - StrTestEntity te = new StrTestEntity("x"); - em.persist(te); - } finally { + // Trying to persist an entity - however the listener should throw an exception, so the entity + // shouldn't be persisted + StrTestEntity te = new StrTestEntity( "x" ); + em.persist( te ); + } + finally { TestingJtaPlatformImpl.tryCommit(); - } - } + } + } - @Test - public void testDataNotPersisted() throws Exception { + @Test + public void testDataNotPersisted() throws Exception { TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin(); - try { - // Checking if the entity became persisted - EntityManager em = getEntityManager(); - long count = em.createQuery("from StrTestEntity s where s.str = 'x'").getResultList().size(); - Assert.assertEquals( 0, count ); - } finally { + try { + // Checking if the entity became persisted + EntityManager em = getEntityManager(); + long count = em.createQuery( "from StrTestEntity s where s.str = 'x'" ).getResultList().size(); + Assert.assertEquals( 0, count ); + } + finally { TestingJtaPlatformImpl.tryCommit(); - } - } + } + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/jta/JtaTransaction.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/jta/JtaTransaction.java index 529749f7b7..1e2d62bf87 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/jta/JtaTransaction.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/jta/JtaTransaction.java @@ -1,68 +1,75 @@ package org.hibernate.envers.test.integration.jta; +import javax.persistence.EntityManager; import java.util.List; import java.util.Map; -import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.IntTestEntity; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.jta.TestingJtaBootstrap; import org.hibernate.testing.jta.TestingJtaPlatformImpl; /** * Same as {@link org.hibernate.envers.test.integration.basic.Simple}, but in a JTA environment. + * * @author Adam Warski (adam at warski dot org) */ -public class JtaTransaction extends BaseEnversJPAFunctionalTestCase { - private Integer id1; +public class JtaTransaction extends BaseEnversJPAFunctionalTestCase { + private Integer id1; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{IntTestEntity.class}; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {IntTestEntity.class}; + } - @Override - protected void addConfigOptions(Map options) { - TestingJtaBootstrap.prepare(options); - } + @Override + protected void addConfigOptions(Map options) { + TestingJtaBootstrap.prepare( options ); + } - @Test - @Priority(10) - public void initData() throws Exception { + @Test + @Priority(10) + public void initData() throws Exception { TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin(); - EntityManager em; - IntTestEntity ite; - try { - em = getEntityManager(); - ite = new IntTestEntity(10); - em.persist(ite); - id1 = ite.getId(); - } finally { + EntityManager em; + IntTestEntity ite; + try { + em = getEntityManager(); + ite = new IntTestEntity( 10 ); + em.persist( ite ); + id1 = ite.getId(); + } + finally { TestingJtaPlatformImpl.tryCommit(); - } - em.close(); + } + em.close(); TestingJtaPlatformImpl.INSTANCE.getTransactionManager().begin(); - try { - em = getEntityManager(); - ite = em.find(IntTestEntity.class, id1); - ite.setNumber(20); - } finally { + try { + em = getEntityManager(); + ite = em.find( IntTestEntity.class, id1 ); + ite.setNumber( 20 ); + } + finally { TestingJtaPlatformImpl.tryCommit(); - } - em.close(); - } + } + em.close(); + } @Test public void testRevisionsCounts() throws Exception { - Assert.assertEquals( 2, getAuditReader().getRevisions( - IntTestEntity.class, id1 ).size() ); + Assert.assertEquals( + 2, getAuditReader().getRevisions( + IntTestEntity.class, id1 + ).size() + ); } @Test @@ -70,12 +77,19 @@ public class JtaTransaction extends BaseEnversJPAFunctionalTestCase { IntTestEntity ver1 = new IntTestEntity( 10, id1 ); IntTestEntity ver2 = new IntTestEntity( 20, id1 ); - List revisions = getAuditReader().getRevisions( - IntTestEntity.class, id1 ); + List revisions = getAuditReader().getRevisions( + IntTestEntity.class, id1 + ); - Assert.assertEquals( ver1, getAuditReader().find( - IntTestEntity.class, id1, revisions.get( 0 ) ) ); - Assert.assertEquals( ver2, getAuditReader().find( - IntTestEntity.class, id1, revisions.get( 1 ) ) ); + Assert.assertEquals( + ver1, getAuditReader().find( + IntTestEntity.class, id1, revisions.get( 0 ) + ) + ); + Assert.assertEquals( + ver2, getAuditReader().find( + IntTestEntity.class, id1, revisions.get( 1 ) + ) + ); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/BasicList.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/BasicList.java index 1a9fb5ee27..31818bebac 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/BasicList.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/BasicList.java @@ -23,12 +23,10 @@ */ package org.hibernate.envers.test.integration.manytomany; +import javax.persistence.EntityManager; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -36,178 +34,185 @@ import org.hibernate.envers.test.entities.manytomany.ListOwnedEntity; import org.hibernate.envers.test.entities.manytomany.ListOwningEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BasicList extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ListOwningEntity.class, ListOwnedEntity.class }; - } + return new Class[] {ListOwningEntity.class, ListOwnedEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - ListOwnedEntity ed1 = new ListOwnedEntity(1, "data_ed_1"); - ListOwnedEntity ed2 = new ListOwnedEntity(2, "data_ed_2"); + ListOwnedEntity ed1 = new ListOwnedEntity( 1, "data_ed_1" ); + ListOwnedEntity ed2 = new ListOwnedEntity( 2, "data_ed_2" ); - ListOwningEntity ing1 = new ListOwningEntity(3, "data_ing_1"); - ListOwningEntity ing2 = new ListOwningEntity(4, "data_ing_2"); + ListOwningEntity ing1 = new ListOwningEntity( 3, "data_ing_1" ); + ListOwningEntity ing2 = new ListOwningEntity( 4, "data_ing_2" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); - em.persist(ing1); - em.persist(ing2); + em.persist( ed1 ); + em.persist( ed2 ); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 + // Revision 2 - em.getTransaction().begin(); + em.getTransaction().begin(); - ing1 = em.find(ListOwningEntity.class, ing1.getId()); - ing2 = em.find(ListOwningEntity.class, ing2.getId()); - ed1 = em.find(ListOwnedEntity.class, ed1.getId()); - ed2 = em.find(ListOwnedEntity.class, ed2.getId()); + ing1 = em.find( ListOwningEntity.class, ing1.getId() ); + ing2 = em.find( ListOwningEntity.class, ing2.getId() ); + ed1 = em.find( ListOwnedEntity.class, ed1.getId() ); + ed2 = em.find( ListOwnedEntity.class, ed2.getId() ); - ing1.setReferences(new ArrayList()); - ing1.getReferences().add(ed1); + ing1.setReferences( new ArrayList() ); + ing1.getReferences().add( ed1 ); - ing2.setReferences(new ArrayList()); - ing2.getReferences().add(ed1); - ing2.getReferences().add(ed2); + ing2.setReferences( new ArrayList() ); + ing2.getReferences().add( ed1 ); + ing2.getReferences().add( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - ing1 = em.find(ListOwningEntity.class, ing1.getId()); - ed2 = em.find(ListOwnedEntity.class, ed2.getId()); - ed1 = em.find(ListOwnedEntity.class, ed1.getId()); + ing1 = em.find( ListOwningEntity.class, ing1.getId() ); + ed2 = em.find( ListOwnedEntity.class, ed2.getId() ); + ed1 = em.find( ListOwnedEntity.class, ed1.getId() ); - ing1.getReferences().add(ed2); + ing1.getReferences().add( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); + // Revision 4 + em.getTransaction().begin(); - ing1 = em.find(ListOwningEntity.class, ing1.getId()); - ed2 = em.find(ListOwnedEntity.class, ed2.getId()); - ed1 = em.find(ListOwnedEntity.class, ed1.getId()); + ing1 = em.find( ListOwningEntity.class, ing1.getId() ); + ed2 = em.find( ListOwnedEntity.class, ed2.getId() ); + ed1 = em.find( ListOwnedEntity.class, ed1.getId() ); - ing1.getReferences().remove(ed1); + ing1.getReferences().remove( ed1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 5 - em.getTransaction().begin(); + // Revision 5 + em.getTransaction().begin(); - ing1 = em.find(ListOwningEntity.class, ing1.getId()); + ing1 = em.find( ListOwningEntity.class, ing1.getId() ); - ing1.setReferences(null); + ing1.setReferences( null ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); - } + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 4).equals(getAuditReader().getRevisions(ListOwnedEntity.class, ed1_id)); - assert Arrays.asList(1, 2, 3, 5).equals(getAuditReader().getRevisions(ListOwnedEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 4 ).equals( getAuditReader().getRevisions( ListOwnedEntity.class, ed1_id ) ); + assert Arrays.asList( 1, 2, 3, 5 ).equals( getAuditReader().getRevisions( ListOwnedEntity.class, ed2_id ) ); - assert Arrays.asList(1, 2, 3, 4, 5).equals(getAuditReader().getRevisions(ListOwningEntity.class, ing1_id)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(ListOwningEntity.class, ing2_id)); - } + assert Arrays.asList( 1, 2, 3, 4, 5 ).equals( + getAuditReader().getRevisions( + ListOwningEntity.class, + ing1_id + ) + ); + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( ListOwningEntity.class, ing2_id ) ); + } - @Test - public void testHistoryOfEdId1() { - ListOwningEntity ing1 = getEntityManager().find(ListOwningEntity.class, ing1_id); - ListOwningEntity ing2 = getEntityManager().find(ListOwningEntity.class, ing2_id); + @Test + public void testHistoryOfEdId1() { + ListOwningEntity ing1 = getEntityManager().find( ListOwningEntity.class, ing1_id ); + ListOwningEntity ing2 = getEntityManager().find( ListOwningEntity.class, ing2_id ); - ListOwnedEntity rev1 = getAuditReader().find(ListOwnedEntity.class, ed1_id, 1); - ListOwnedEntity rev2 = getAuditReader().find(ListOwnedEntity.class, ed1_id, 2); - ListOwnedEntity rev3 = getAuditReader().find(ListOwnedEntity.class, ed1_id, 3); - ListOwnedEntity rev4 = getAuditReader().find(ListOwnedEntity.class, ed1_id, 4); - ListOwnedEntity rev5 = getAuditReader().find(ListOwnedEntity.class, ed1_id, 5); + ListOwnedEntity rev1 = getAuditReader().find( ListOwnedEntity.class, ed1_id, 1 ); + ListOwnedEntity rev2 = getAuditReader().find( ListOwnedEntity.class, ed1_id, 2 ); + ListOwnedEntity rev3 = getAuditReader().find( ListOwnedEntity.class, ed1_id, 3 ); + ListOwnedEntity rev4 = getAuditReader().find( ListOwnedEntity.class, ed1_id, 4 ); + ListOwnedEntity rev5 = getAuditReader().find( ListOwnedEntity.class, ed1_id, 5 ); - assert rev1.getReferencing().equals(Collections.EMPTY_LIST); - assert TestTools.checkList(rev2.getReferencing(), ing1, ing2); - assert TestTools.checkList(rev3.getReferencing(), ing1, ing2); - assert TestTools.checkList(rev4.getReferencing(), ing2); - assert TestTools.checkList(rev5.getReferencing(), ing2); - } + assert rev1.getReferencing().equals( Collections.EMPTY_LIST ); + assert TestTools.checkList( rev2.getReferencing(), ing1, ing2 ); + assert TestTools.checkList( rev3.getReferencing(), ing1, ing2 ); + assert TestTools.checkList( rev4.getReferencing(), ing2 ); + assert TestTools.checkList( rev5.getReferencing(), ing2 ); + } - @Test - public void testHistoryOfEdId2() { - ListOwningEntity ing1 = getEntityManager().find(ListOwningEntity.class, ing1_id); - ListOwningEntity ing2 = getEntityManager().find(ListOwningEntity.class, ing2_id); + @Test + public void testHistoryOfEdId2() { + ListOwningEntity ing1 = getEntityManager().find( ListOwningEntity.class, ing1_id ); + ListOwningEntity ing2 = getEntityManager().find( ListOwningEntity.class, ing2_id ); - ListOwnedEntity rev1 = getAuditReader().find(ListOwnedEntity.class, ed2_id, 1); - ListOwnedEntity rev2 = getAuditReader().find(ListOwnedEntity.class, ed2_id, 2); - ListOwnedEntity rev3 = getAuditReader().find(ListOwnedEntity.class, ed2_id, 3); - ListOwnedEntity rev4 = getAuditReader().find(ListOwnedEntity.class, ed2_id, 4); - ListOwnedEntity rev5 = getAuditReader().find(ListOwnedEntity.class, ed2_id, 5); + ListOwnedEntity rev1 = getAuditReader().find( ListOwnedEntity.class, ed2_id, 1 ); + ListOwnedEntity rev2 = getAuditReader().find( ListOwnedEntity.class, ed2_id, 2 ); + ListOwnedEntity rev3 = getAuditReader().find( ListOwnedEntity.class, ed2_id, 3 ); + ListOwnedEntity rev4 = getAuditReader().find( ListOwnedEntity.class, ed2_id, 4 ); + ListOwnedEntity rev5 = getAuditReader().find( ListOwnedEntity.class, ed2_id, 5 ); - assert rev1.getReferencing().equals(Collections.EMPTY_LIST); - assert TestTools.checkList(rev2.getReferencing(), ing2); - assert TestTools.checkList(rev3.getReferencing(), ing1, ing2); - assert TestTools.checkList(rev4.getReferencing(), ing1, ing2); - assert TestTools.checkList(rev5.getReferencing(), ing2); - } + assert rev1.getReferencing().equals( Collections.EMPTY_LIST ); + assert TestTools.checkList( rev2.getReferencing(), ing2 ); + assert TestTools.checkList( rev3.getReferencing(), ing1, ing2 ); + assert TestTools.checkList( rev4.getReferencing(), ing1, ing2 ); + assert TestTools.checkList( rev5.getReferencing(), ing2 ); + } - @Test - public void testHistoryOfEdIng1() { - ListOwnedEntity ed1 = getEntityManager().find(ListOwnedEntity.class, ed1_id); - ListOwnedEntity ed2 = getEntityManager().find(ListOwnedEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng1() { + ListOwnedEntity ed1 = getEntityManager().find( ListOwnedEntity.class, ed1_id ); + ListOwnedEntity ed2 = getEntityManager().find( ListOwnedEntity.class, ed2_id ); - ListOwningEntity rev1 = getAuditReader().find(ListOwningEntity.class, ing1_id, 1); - ListOwningEntity rev2 = getAuditReader().find(ListOwningEntity.class, ing1_id, 2); - ListOwningEntity rev3 = getAuditReader().find(ListOwningEntity.class, ing1_id, 3); - ListOwningEntity rev4 = getAuditReader().find(ListOwningEntity.class, ing1_id, 4); - ListOwningEntity rev5 = getAuditReader().find(ListOwningEntity.class, ing1_id, 5); + ListOwningEntity rev1 = getAuditReader().find( ListOwningEntity.class, ing1_id, 1 ); + ListOwningEntity rev2 = getAuditReader().find( ListOwningEntity.class, ing1_id, 2 ); + ListOwningEntity rev3 = getAuditReader().find( ListOwningEntity.class, ing1_id, 3 ); + ListOwningEntity rev4 = getAuditReader().find( ListOwningEntity.class, ing1_id, 4 ); + ListOwningEntity rev5 = getAuditReader().find( ListOwningEntity.class, ing1_id, 5 ); - assert rev1.getReferences().equals(Collections.EMPTY_LIST); - assert TestTools.checkList(rev2.getReferences(), ed1); - assert TestTools.checkList(rev3.getReferences(), ed1, ed2); - assert TestTools.checkList(rev4.getReferences(), ed2); - assert rev5.getReferences().equals(Collections.EMPTY_LIST); - } + assert rev1.getReferences().equals( Collections.EMPTY_LIST ); + assert TestTools.checkList( rev2.getReferences(), ed1 ); + assert TestTools.checkList( rev3.getReferences(), ed1, ed2 ); + assert TestTools.checkList( rev4.getReferences(), ed2 ); + assert rev5.getReferences().equals( Collections.EMPTY_LIST ); + } - @Test - public void testHistoryOfEdIng2() { - ListOwnedEntity ed1 = getEntityManager().find(ListOwnedEntity.class, ed1_id); - ListOwnedEntity ed2 = getEntityManager().find(ListOwnedEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng2() { + ListOwnedEntity ed1 = getEntityManager().find( ListOwnedEntity.class, ed1_id ); + ListOwnedEntity ed2 = getEntityManager().find( ListOwnedEntity.class, ed2_id ); - ListOwningEntity rev1 = getAuditReader().find(ListOwningEntity.class, ing2_id, 1); - ListOwningEntity rev2 = getAuditReader().find(ListOwningEntity.class, ing2_id, 2); - ListOwningEntity rev3 = getAuditReader().find(ListOwningEntity.class, ing2_id, 3); - ListOwningEntity rev4 = getAuditReader().find(ListOwningEntity.class, ing2_id, 4); - ListOwningEntity rev5 = getAuditReader().find(ListOwningEntity.class, ing2_id, 5); + ListOwningEntity rev1 = getAuditReader().find( ListOwningEntity.class, ing2_id, 1 ); + ListOwningEntity rev2 = getAuditReader().find( ListOwningEntity.class, ing2_id, 2 ); + ListOwningEntity rev3 = getAuditReader().find( ListOwningEntity.class, ing2_id, 3 ); + ListOwningEntity rev4 = getAuditReader().find( ListOwningEntity.class, ing2_id, 4 ); + ListOwningEntity rev5 = getAuditReader().find( ListOwningEntity.class, ing2_id, 5 ); - assert rev1.getReferences().equals(Collections.EMPTY_LIST); - assert TestTools.checkList(rev2.getReferences(), ed1, ed2); - assert TestTools.checkList(rev3.getReferences(), ed1, ed2); - assert TestTools.checkList(rev4.getReferences(), ed1, ed2); - assert TestTools.checkList(rev5.getReferences(), ed1, ed2); - } + assert rev1.getReferences().equals( Collections.EMPTY_LIST ); + assert TestTools.checkList( rev2.getReferences(), ed1, ed2 ); + assert TestTools.checkList( rev3.getReferences(), ed1, ed2 ); + assert TestTools.checkList( rev4.getReferences(), ed1, ed2 ); + assert TestTools.checkList( rev5.getReferences(), ed1, ed2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/BasicMap.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/BasicMap.java index 5114856e4b..2c6340c376 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/BasicMap.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/BasicMap.java @@ -23,12 +23,10 @@ */ package org.hibernate.envers.test.integration.manytomany; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -36,152 +34,154 @@ import org.hibernate.envers.test.entities.manytomany.MapOwnedEntity; import org.hibernate.envers.test.entities.manytomany.MapOwningEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BasicMap extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { MapOwningEntity.class, MapOwnedEntity.class }; + return new Class[] {MapOwningEntity.class, MapOwnedEntity.class}; } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - MapOwnedEntity ed1 = new MapOwnedEntity(1, "data_ed_1"); - MapOwnedEntity ed2 = new MapOwnedEntity(2, "data_ed_2"); + MapOwnedEntity ed1 = new MapOwnedEntity( 1, "data_ed_1" ); + MapOwnedEntity ed2 = new MapOwnedEntity( 2, "data_ed_2" ); - MapOwningEntity ing1 = new MapOwningEntity(3, "data_ing_1"); - MapOwningEntity ing2 = new MapOwningEntity(4, "data_ing_2"); + MapOwningEntity ing1 = new MapOwningEntity( 3, "data_ing_1" ); + MapOwningEntity ing2 = new MapOwningEntity( 4, "data_ing_2" ); - // Revision 1 (ing1: initialy empty, ing2: one mapping) - em.getTransaction().begin(); + // Revision 1 (ing1: initialy empty, ing2: one mapping) + em.getTransaction().begin(); - ing2.getReferences().put("2", ed2); + ing2.getReferences().put( "2", ed2 ); - em.persist(ed1); - em.persist(ed2); - em.persist(ing1); - em.persist(ing2); + em.persist( ed1 ); + em.persist( ed2 ); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (ing1: adding two mappings, ing2: replacing an existing mapping) + // Revision 2 (ing1: adding two mappings, ing2: replacing an existing mapping) - em.getTransaction().begin(); + em.getTransaction().begin(); - ing1 = em.find(MapOwningEntity.class, ing1.getId()); - ing2 = em.find(MapOwningEntity.class, ing2.getId()); - ed1 = em.find(MapOwnedEntity.class, ed1.getId()); - ed2 = em.find(MapOwnedEntity.class, ed2.getId()); + ing1 = em.find( MapOwningEntity.class, ing1.getId() ); + ing2 = em.find( MapOwningEntity.class, ing2.getId() ); + ed1 = em.find( MapOwnedEntity.class, ed1.getId() ); + ed2 = em.find( MapOwnedEntity.class, ed2.getId() ); - ing1.getReferences().put("1", ed1); - ing1.getReferences().put("2", ed1); + ing1.getReferences().put( "1", ed1 ); + ing1.getReferences().put( "2", ed1 ); - ing2.getReferences().put("2", ed1); + ing2.getReferences().put( "2", ed1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // No revision (ing1: adding an existing mapping, ing2: removing a non existing mapping) - em.getTransaction().begin(); + // No revision (ing1: adding an existing mapping, ing2: removing a non existing mapping) + em.getTransaction().begin(); - ing1 = em.find(MapOwningEntity.class, ing1.getId()); - ing2 = em.find(MapOwningEntity.class, ing2.getId()); + ing1 = em.find( MapOwningEntity.class, ing1.getId() ); + ing2 = em.find( MapOwningEntity.class, ing2.getId() ); - ing1.getReferences().put("1", ed1); + ing1.getReferences().put( "1", ed1 ); - ing2.getReferences().remove("3"); + ing2.getReferences().remove( "3" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 (ing1: clearing, ing2: replacing with a new map) - em.getTransaction().begin(); + // Revision 3 (ing1: clearing, ing2: replacing with a new map) + em.getTransaction().begin(); - ing1 = em.find(MapOwningEntity.class, ing1.getId()); - ed1 = em.find(MapOwnedEntity.class, ed1.getId()); + ing1 = em.find( MapOwningEntity.class, ing1.getId() ); + ed1 = em.find( MapOwnedEntity.class, ed1.getId() ); - ing1.getReferences().clear(); - ing2.setReferences(new HashMap()); - ing2.getReferences().put("1", ed2); + ing1.getReferences().clear(); + ing2.setReferences( new HashMap() ); + ing2.getReferences().put( "1", ed2 ); - em.getTransaction().commit(); - // + em.getTransaction().commit(); + // - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); - } + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(MapOwnedEntity.class, ed1_id)); - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(MapOwnedEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( MapOwnedEntity.class, ed1_id ) ); + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( MapOwnedEntity.class, ed2_id ) ); - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(MapOwningEntity.class, ing1_id)); - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(MapOwningEntity.class, ing2_id)); - } + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( MapOwningEntity.class, ing1_id ) ); + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( MapOwningEntity.class, ing2_id ) ); + } - @Test - public void testHistoryOfEdId1() { - MapOwningEntity ing1 = getEntityManager().find(MapOwningEntity.class, ing1_id); - MapOwningEntity ing2 = getEntityManager().find(MapOwningEntity.class, ing2_id); + @Test + public void testHistoryOfEdId1() { + MapOwningEntity ing1 = getEntityManager().find( MapOwningEntity.class, ing1_id ); + MapOwningEntity ing2 = getEntityManager().find( MapOwningEntity.class, ing2_id ); - MapOwnedEntity rev1 = getAuditReader().find(MapOwnedEntity.class, ed1_id, 1); - MapOwnedEntity rev2 = getAuditReader().find(MapOwnedEntity.class, ed1_id, 2); - MapOwnedEntity rev3 = getAuditReader().find(MapOwnedEntity.class, ed1_id, 3); + MapOwnedEntity rev1 = getAuditReader().find( MapOwnedEntity.class, ed1_id, 1 ); + MapOwnedEntity rev2 = getAuditReader().find( MapOwnedEntity.class, ed1_id, 2 ); + MapOwnedEntity rev3 = getAuditReader().find( MapOwnedEntity.class, ed1_id, 3 ); - assert rev1.getReferencing().equals(Collections.EMPTY_SET); - assert rev2.getReferencing().equals(TestTools.makeSet(ing1, ing2)); - assert rev3.getReferencing().equals(Collections.EMPTY_SET); - } + assert rev1.getReferencing().equals( Collections.EMPTY_SET ); + assert rev2.getReferencing().equals( TestTools.makeSet( ing1, ing2 ) ); + assert rev3.getReferencing().equals( Collections.EMPTY_SET ); + } - @Test - public void testHistoryOfEdId2() { - MapOwningEntity ing2 = getEntityManager().find(MapOwningEntity.class, ing2_id); + @Test + public void testHistoryOfEdId2() { + MapOwningEntity ing2 = getEntityManager().find( MapOwningEntity.class, ing2_id ); - MapOwnedEntity rev1 = getAuditReader().find(MapOwnedEntity.class, ed2_id, 1); - MapOwnedEntity rev2 = getAuditReader().find(MapOwnedEntity.class, ed2_id, 2); - MapOwnedEntity rev3 = getAuditReader().find(MapOwnedEntity.class, ed2_id, 3); + MapOwnedEntity rev1 = getAuditReader().find( MapOwnedEntity.class, ed2_id, 1 ); + MapOwnedEntity rev2 = getAuditReader().find( MapOwnedEntity.class, ed2_id, 2 ); + MapOwnedEntity rev3 = getAuditReader().find( MapOwnedEntity.class, ed2_id, 3 ); - assert rev1.getReferencing().equals(TestTools.makeSet(ing2)); - assert rev2.getReferencing().equals(Collections.EMPTY_SET); - assert rev3.getReferencing().equals(TestTools.makeSet(ing2)); - } + assert rev1.getReferencing().equals( TestTools.makeSet( ing2 ) ); + assert rev2.getReferencing().equals( Collections.EMPTY_SET ); + assert rev3.getReferencing().equals( TestTools.makeSet( ing2 ) ); + } - @Test - public void testHistoryOfEdIng1() { - MapOwnedEntity ed1 = getEntityManager().find(MapOwnedEntity.class, ed1_id); + @Test + public void testHistoryOfEdIng1() { + MapOwnedEntity ed1 = getEntityManager().find( MapOwnedEntity.class, ed1_id ); - MapOwningEntity rev1 = getAuditReader().find(MapOwningEntity.class, ing1_id, 1); - MapOwningEntity rev2 = getAuditReader().find(MapOwningEntity.class, ing1_id, 2); - MapOwningEntity rev3 = getAuditReader().find(MapOwningEntity.class, ing1_id, 3); + MapOwningEntity rev1 = getAuditReader().find( MapOwningEntity.class, ing1_id, 1 ); + MapOwningEntity rev2 = getAuditReader().find( MapOwningEntity.class, ing1_id, 2 ); + MapOwningEntity rev3 = getAuditReader().find( MapOwningEntity.class, ing1_id, 3 ); - assert rev1.getReferences().equals(Collections.EMPTY_MAP); - assert rev2.getReferences().equals(TestTools.makeMap("1", ed1, "2", ed1)); - assert rev3.getReferences().equals(Collections.EMPTY_MAP); - } + assert rev1.getReferences().equals( Collections.EMPTY_MAP ); + assert rev2.getReferences().equals( TestTools.makeMap( "1", ed1, "2", ed1 ) ); + assert rev3.getReferences().equals( Collections.EMPTY_MAP ); + } - @Test - public void testHistoryOfEdIng2() { - MapOwnedEntity ed1 = getEntityManager().find(MapOwnedEntity.class, ed1_id); - MapOwnedEntity ed2 = getEntityManager().find(MapOwnedEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng2() { + MapOwnedEntity ed1 = getEntityManager().find( MapOwnedEntity.class, ed1_id ); + MapOwnedEntity ed2 = getEntityManager().find( MapOwnedEntity.class, ed2_id ); - MapOwningEntity rev1 = getAuditReader().find(MapOwningEntity.class, ing2_id, 1); - MapOwningEntity rev2 = getAuditReader().find(MapOwningEntity.class, ing2_id, 2); - MapOwningEntity rev3 = getAuditReader().find(MapOwningEntity.class, ing2_id, 3); + MapOwningEntity rev1 = getAuditReader().find( MapOwningEntity.class, ing2_id, 1 ); + MapOwningEntity rev2 = getAuditReader().find( MapOwningEntity.class, ing2_id, 2 ); + MapOwningEntity rev3 = getAuditReader().find( MapOwningEntity.class, ing2_id, 3 ); - assert rev1.getReferences().equals(TestTools.makeMap("2", ed2)); - assert rev2.getReferences().equals(TestTools.makeMap("2", ed1)); - assert rev3.getReferences().equals(TestTools.makeMap("1", ed2)); - } + assert rev1.getReferences().equals( TestTools.makeMap( "2", ed2 ) ); + assert rev2.getReferences().equals( TestTools.makeMap( "2", ed1 ) ); + assert rev3.getReferences().equals( TestTools.makeMap( "1", ed2 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/BasicSet.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/BasicSet.java index 0355e817e4..eb5c5419d7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/BasicSet.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/BasicSet.java @@ -23,12 +23,10 @@ */ package org.hibernate.envers.test.integration.manytomany; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -36,178 +34,180 @@ import org.hibernate.envers.test.entities.manytomany.SetOwnedEntity; import org.hibernate.envers.test.entities.manytomany.SetOwningEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ -public class BasicSet extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; +public class BasicSet extends BaseEnversJPAFunctionalTestCase { + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SetOwningEntity.class, SetOwnedEntity.class }; - } + return new Class[] {SetOwningEntity.class, SetOwnedEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - SetOwnedEntity ed1 = new SetOwnedEntity(1, "data_ed_1"); - SetOwnedEntity ed2 = new SetOwnedEntity(2, "data_ed_2"); + SetOwnedEntity ed1 = new SetOwnedEntity( 1, "data_ed_1" ); + SetOwnedEntity ed2 = new SetOwnedEntity( 2, "data_ed_2" ); - SetOwningEntity ing1 = new SetOwningEntity(3, "data_ing_1"); - SetOwningEntity ing2 = new SetOwningEntity(4, "data_ing_2"); + SetOwningEntity ing1 = new SetOwningEntity( 3, "data_ing_1" ); + SetOwningEntity ing2 = new SetOwningEntity( 4, "data_ing_2" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); - em.persist(ing1); - em.persist(ing2); + em.persist( ed1 ); + em.persist( ed2 ); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 + // Revision 2 - em.getTransaction().begin(); + em.getTransaction().begin(); - ing1 = em.find(SetOwningEntity.class, ing1.getId()); - ing2 = em.find(SetOwningEntity.class, ing2.getId()); - ed1 = em.find(SetOwnedEntity.class, ed1.getId()); - ed2 = em.find(SetOwnedEntity.class, ed2.getId()); + ing1 = em.find( SetOwningEntity.class, ing1.getId() ); + ing2 = em.find( SetOwningEntity.class, ing2.getId() ); + ed1 = em.find( SetOwnedEntity.class, ed1.getId() ); + ed2 = em.find( SetOwnedEntity.class, ed2.getId() ); - ing1.setReferences(new HashSet()); - ing1.getReferences().add(ed1); + ing1.setReferences( new HashSet() ); + ing1.getReferences().add( ed1 ); - ing2.setReferences(new HashSet()); - ing2.getReferences().add(ed1); - ing2.getReferences().add(ed2); + ing2.setReferences( new HashSet() ); + ing2.getReferences().add( ed1 ); + ing2.getReferences().add( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - ing1 = em.find(SetOwningEntity.class, ing1.getId()); - ed2 = em.find(SetOwnedEntity.class, ed2.getId()); - ed1 = em.find(SetOwnedEntity.class, ed1.getId()); + ing1 = em.find( SetOwningEntity.class, ing1.getId() ); + ed2 = em.find( SetOwnedEntity.class, ed2.getId() ); + ed1 = em.find( SetOwnedEntity.class, ed1.getId() ); - ing1.getReferences().add(ed2); + ing1.getReferences().add( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); + // Revision 4 + em.getTransaction().begin(); - ing1 = em.find(SetOwningEntity.class, ing1.getId()); - ed2 = em.find(SetOwnedEntity.class, ed2.getId()); - ed1 = em.find(SetOwnedEntity.class, ed1.getId()); + ing1 = em.find( SetOwningEntity.class, ing1.getId() ); + ed2 = em.find( SetOwnedEntity.class, ed2.getId() ); + ed1 = em.find( SetOwnedEntity.class, ed1.getId() ); - ing1.getReferences().remove(ed1); + ing1.getReferences().remove( ed1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 5 - em.getTransaction().begin(); + // Revision 5 + em.getTransaction().begin(); - ing1 = em.find(SetOwningEntity.class, ing1.getId()); + ing1 = em.find( SetOwningEntity.class, ing1.getId() ); - ing1.setReferences(null); + ing1.setReferences( null ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); - } + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 4).equals(getAuditReader().getRevisions(SetOwnedEntity.class, ed1_id)); - assert Arrays.asList(1, 2, 3, 5).equals(getAuditReader().getRevisions(SetOwnedEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 4 ).equals( getAuditReader().getRevisions( SetOwnedEntity.class, ed1_id ) ); + assert Arrays.asList( 1, 2, 3, 5 ).equals( getAuditReader().getRevisions( SetOwnedEntity.class, ed2_id ) ); - assert Arrays.asList(1, 2, 3, 4, 5).equals(getAuditReader().getRevisions(SetOwningEntity.class, ing1_id)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(SetOwningEntity.class, ing2_id)); - } + assert Arrays.asList( 1, 2, 3, 4, 5 ).equals( getAuditReader().getRevisions( SetOwningEntity.class, ing1_id ) ); + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( SetOwningEntity.class, ing2_id ) ); + } - @Test - public void testHistoryOfEdId1() { - SetOwningEntity ing1 = getEntityManager().find(SetOwningEntity.class, ing1_id); - SetOwningEntity ing2 = getEntityManager().find(SetOwningEntity.class, ing2_id); + @Test + public void testHistoryOfEdId1() { + SetOwningEntity ing1 = getEntityManager().find( SetOwningEntity.class, ing1_id ); + SetOwningEntity ing2 = getEntityManager().find( SetOwningEntity.class, ing2_id ); - SetOwnedEntity rev1 = getAuditReader().find(SetOwnedEntity.class, ed1_id, 1); - SetOwnedEntity rev2 = getAuditReader().find(SetOwnedEntity.class, ed1_id, 2); - SetOwnedEntity rev3 = getAuditReader().find(SetOwnedEntity.class, ed1_id, 3); - SetOwnedEntity rev4 = getAuditReader().find(SetOwnedEntity.class, ed1_id, 4); - SetOwnedEntity rev5 = getAuditReader().find(SetOwnedEntity.class, ed1_id, 5); + SetOwnedEntity rev1 = getAuditReader().find( SetOwnedEntity.class, ed1_id, 1 ); + SetOwnedEntity rev2 = getAuditReader().find( SetOwnedEntity.class, ed1_id, 2 ); + SetOwnedEntity rev3 = getAuditReader().find( SetOwnedEntity.class, ed1_id, 3 ); + SetOwnedEntity rev4 = getAuditReader().find( SetOwnedEntity.class, ed1_id, 4 ); + SetOwnedEntity rev5 = getAuditReader().find( SetOwnedEntity.class, ed1_id, 5 ); - assert rev1.getReferencing().equals(Collections.EMPTY_SET); - assert rev2.getReferencing().equals(TestTools.makeSet(ing1, ing2)); - assert rev3.getReferencing().equals(TestTools.makeSet(ing1, ing2)); - assert rev4.getReferencing().equals(TestTools.makeSet(ing2)); - assert rev5.getReferencing().equals(TestTools.makeSet(ing2)); - } + assert rev1.getReferencing().equals( Collections.EMPTY_SET ); + assert rev2.getReferencing().equals( TestTools.makeSet( ing1, ing2 ) ); + assert rev3.getReferencing().equals( TestTools.makeSet( ing1, ing2 ) ); + assert rev4.getReferencing().equals( TestTools.makeSet( ing2 ) ); + assert rev5.getReferencing().equals( TestTools.makeSet( ing2 ) ); + } - @Test - public void testHistoryOfEdId2() { - SetOwningEntity ing1 = getEntityManager().find(SetOwningEntity.class, ing1_id); - SetOwningEntity ing2 = getEntityManager().find(SetOwningEntity.class, ing2_id); + @Test + public void testHistoryOfEdId2() { + SetOwningEntity ing1 = getEntityManager().find( SetOwningEntity.class, ing1_id ); + SetOwningEntity ing2 = getEntityManager().find( SetOwningEntity.class, ing2_id ); - SetOwnedEntity rev1 = getAuditReader().find(SetOwnedEntity.class, ed2_id, 1); - SetOwnedEntity rev2 = getAuditReader().find(SetOwnedEntity.class, ed2_id, 2); - SetOwnedEntity rev3 = getAuditReader().find(SetOwnedEntity.class, ed2_id, 3); - SetOwnedEntity rev4 = getAuditReader().find(SetOwnedEntity.class, ed2_id, 4); - SetOwnedEntity rev5 = getAuditReader().find(SetOwnedEntity.class, ed2_id, 5); + SetOwnedEntity rev1 = getAuditReader().find( SetOwnedEntity.class, ed2_id, 1 ); + SetOwnedEntity rev2 = getAuditReader().find( SetOwnedEntity.class, ed2_id, 2 ); + SetOwnedEntity rev3 = getAuditReader().find( SetOwnedEntity.class, ed2_id, 3 ); + SetOwnedEntity rev4 = getAuditReader().find( SetOwnedEntity.class, ed2_id, 4 ); + SetOwnedEntity rev5 = getAuditReader().find( SetOwnedEntity.class, ed2_id, 5 ); - assert rev1.getReferencing().equals(Collections.EMPTY_SET); - assert rev2.getReferencing().equals(TestTools.makeSet(ing2)); - assert rev3.getReferencing().equals(TestTools.makeSet(ing1, ing2)); - assert rev4.getReferencing().equals(TestTools.makeSet(ing1, ing2)); - assert rev5.getReferencing().equals(TestTools.makeSet(ing2)); - } + assert rev1.getReferencing().equals( Collections.EMPTY_SET ); + assert rev2.getReferencing().equals( TestTools.makeSet( ing2 ) ); + assert rev3.getReferencing().equals( TestTools.makeSet( ing1, ing2 ) ); + assert rev4.getReferencing().equals( TestTools.makeSet( ing1, ing2 ) ); + assert rev5.getReferencing().equals( TestTools.makeSet( ing2 ) ); + } - @Test - public void testHistoryOfEdIng1() { - SetOwnedEntity ed1 = getEntityManager().find(SetOwnedEntity.class, ed1_id); - SetOwnedEntity ed2 = getEntityManager().find(SetOwnedEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng1() { + SetOwnedEntity ed1 = getEntityManager().find( SetOwnedEntity.class, ed1_id ); + SetOwnedEntity ed2 = getEntityManager().find( SetOwnedEntity.class, ed2_id ); - SetOwningEntity rev1 = getAuditReader().find(SetOwningEntity.class, ing1_id, 1); - SetOwningEntity rev2 = getAuditReader().find(SetOwningEntity.class, ing1_id, 2); - SetOwningEntity rev3 = getAuditReader().find(SetOwningEntity.class, ing1_id, 3); - SetOwningEntity rev4 = getAuditReader().find(SetOwningEntity.class, ing1_id, 4); - SetOwningEntity rev5 = getAuditReader().find(SetOwningEntity.class, ing1_id, 5); + SetOwningEntity rev1 = getAuditReader().find( SetOwningEntity.class, ing1_id, 1 ); + SetOwningEntity rev2 = getAuditReader().find( SetOwningEntity.class, ing1_id, 2 ); + SetOwningEntity rev3 = getAuditReader().find( SetOwningEntity.class, ing1_id, 3 ); + SetOwningEntity rev4 = getAuditReader().find( SetOwningEntity.class, ing1_id, 4 ); + SetOwningEntity rev5 = getAuditReader().find( SetOwningEntity.class, ing1_id, 5 ); - assert rev1.getReferences().equals(Collections.EMPTY_SET); - assert rev2.getReferences().equals(TestTools.makeSet(ed1)); - assert rev3.getReferences().equals(TestTools.makeSet(ed1, ed2)); - assert rev4.getReferences().equals(TestTools.makeSet(ed2)); - assert rev5.getReferences().equals(Collections.EMPTY_SET); - } + assert rev1.getReferences().equals( Collections.EMPTY_SET ); + assert rev2.getReferences().equals( TestTools.makeSet( ed1 ) ); + assert rev3.getReferences().equals( TestTools.makeSet( ed1, ed2 ) ); + assert rev4.getReferences().equals( TestTools.makeSet( ed2 ) ); + assert rev5.getReferences().equals( Collections.EMPTY_SET ); + } - @Test - public void testHistoryOfEdIng2() { - SetOwnedEntity ed1 = getEntityManager().find(SetOwnedEntity.class, ed1_id); - SetOwnedEntity ed2 = getEntityManager().find(SetOwnedEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng2() { + SetOwnedEntity ed1 = getEntityManager().find( SetOwnedEntity.class, ed1_id ); + SetOwnedEntity ed2 = getEntityManager().find( SetOwnedEntity.class, ed2_id ); - SetOwningEntity rev1 = getAuditReader().find(SetOwningEntity.class, ing2_id, 1); - SetOwningEntity rev2 = getAuditReader().find(SetOwningEntity.class, ing2_id, 2); - SetOwningEntity rev3 = getAuditReader().find(SetOwningEntity.class, ing2_id, 3); - SetOwningEntity rev4 = getAuditReader().find(SetOwningEntity.class, ing2_id, 4); - SetOwningEntity rev5 = getAuditReader().find(SetOwningEntity.class, ing2_id, 5); + SetOwningEntity rev1 = getAuditReader().find( SetOwningEntity.class, ing2_id, 1 ); + SetOwningEntity rev2 = getAuditReader().find( SetOwningEntity.class, ing2_id, 2 ); + SetOwningEntity rev3 = getAuditReader().find( SetOwningEntity.class, ing2_id, 3 ); + SetOwningEntity rev4 = getAuditReader().find( SetOwningEntity.class, ing2_id, 4 ); + SetOwningEntity rev5 = getAuditReader().find( SetOwningEntity.class, ing2_id, 5 ); - assert rev1.getReferences().equals(Collections.EMPTY_SET); - assert rev2.getReferences().equals(TestTools.makeSet(ed1, ed2)); - assert rev3.getReferences().equals(TestTools.makeSet(ed1, ed2)); - assert rev4.getReferences().equals(TestTools.makeSet(ed1, ed2)); - assert rev5.getReferences().equals(TestTools.makeSet(ed1, ed2)); - } + assert rev1.getReferences().equals( Collections.EMPTY_SET ); + assert rev2.getReferences().equals( TestTools.makeSet( ed1, ed2 ) ); + assert rev3.getReferences().equals( TestTools.makeSet( ed1, ed2 ) ); + assert rev4.getReferences().equals( TestTools.makeSet( ed1, ed2 ) ); + assert rev5.getReferences().equals( TestTools.makeSet( ed1, ed2 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/BasicWhereJoinTable.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/BasicWhereJoinTable.java index 2935dffeb9..ca67bbb217 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/BasicWhereJoinTable.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/BasicWhereJoinTable.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.manytomany; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -34,155 +32,157 @@ import org.hibernate.envers.test.entities.IntNoAutoIdTestEntity; import org.hibernate.envers.test.entities.manytomany.WhereJoinTableEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + import static org.junit.Assert.assertEquals; /** * @author Adam Warski (adam at warski dot org) */ public class BasicWhereJoinTable extends BaseEnversJPAFunctionalTestCase { - private Integer ite1_1_id; - private Integer ite1_2_id; - private Integer ite2_1_id; - private Integer ite2_2_id; + private Integer ite1_1_id; + private Integer ite1_2_id; + private Integer ite2_1_id; + private Integer ite2_2_id; - private Integer wjte1_id; - private Integer wjte2_id; + private Integer wjte1_id; + private Integer wjte2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { WhereJoinTableEntity.class, IntNoAutoIdTestEntity.class }; - } + return new Class[] {WhereJoinTableEntity.class, IntNoAutoIdTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - IntNoAutoIdTestEntity ite1_1 = new IntNoAutoIdTestEntity(1, 10); - IntNoAutoIdTestEntity ite1_2 = new IntNoAutoIdTestEntity(1, 11); - IntNoAutoIdTestEntity ite2_1 = new IntNoAutoIdTestEntity(2, 20); - IntNoAutoIdTestEntity ite2_2 = new IntNoAutoIdTestEntity(2, 21); + IntNoAutoIdTestEntity ite1_1 = new IntNoAutoIdTestEntity( 1, 10 ); + IntNoAutoIdTestEntity ite1_2 = new IntNoAutoIdTestEntity( 1, 11 ); + IntNoAutoIdTestEntity ite2_1 = new IntNoAutoIdTestEntity( 2, 20 ); + IntNoAutoIdTestEntity ite2_2 = new IntNoAutoIdTestEntity( 2, 21 ); - WhereJoinTableEntity wjte1 = new WhereJoinTableEntity(); - wjte1.setData("wjte1"); + WhereJoinTableEntity wjte1 = new WhereJoinTableEntity(); + wjte1.setData( "wjte1" ); - WhereJoinTableEntity wjte2 = new WhereJoinTableEntity(); - wjte1.setData("wjte2"); + WhereJoinTableEntity wjte2 = new WhereJoinTableEntity(); + wjte1.setData( "wjte2" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(ite1_1); - em.persist(ite1_2); - em.persist(ite2_1); - em.persist(ite2_2); - em.persist(wjte1); - em.persist(wjte2); + em.persist( ite1_1 ); + em.persist( ite1_2 ); + em.persist( ite2_1 ); + em.persist( ite2_2 ); + em.persist( wjte1 ); + em.persist( wjte2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 2 (wjte1: 1_1, 2_1) + // Revision 2 (wjte1: 1_1, 2_1) - em.getTransaction().begin(); + em.getTransaction().begin(); - wjte1 = em.find(WhereJoinTableEntity.class, wjte1.getId()); + wjte1 = em.find( WhereJoinTableEntity.class, wjte1.getId() ); - wjte1.getReferences1().add(ite1_1); - wjte1.getReferences2().add(ite2_1); + wjte1.getReferences1().add( ite1_1 ); + wjte1.getReferences2().add( ite2_1 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 3 (wjte1: 1_1, 2_1; wjte2: 1_1, 1_2) - em.getTransaction().begin(); + // Revision 3 (wjte1: 1_1, 2_1; wjte2: 1_1, 1_2) + em.getTransaction().begin(); - wjte2 = em.find(WhereJoinTableEntity.class, wjte2.getId()); + wjte2 = em.find( WhereJoinTableEntity.class, wjte2.getId() ); - wjte2.getReferences1().add(ite1_1); - wjte2.getReferences1().add(ite1_2); + wjte2.getReferences1().add( ite1_1 ); + wjte2.getReferences1().add( ite1_2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 4 (wjte1: 2_1; wjte2: 1_1, 1_2, 2_2) - em.getTransaction().begin(); + // Revision 4 (wjte1: 2_1; wjte2: 1_1, 1_2, 2_2) + em.getTransaction().begin(); - wjte1 = em.find(WhereJoinTableEntity.class, wjte1.getId()); - wjte2 = em.find(WhereJoinTableEntity.class, wjte2.getId()); + wjte1 = em.find( WhereJoinTableEntity.class, wjte1.getId() ); + wjte2 = em.find( WhereJoinTableEntity.class, wjte2.getId() ); - wjte1.getReferences1().remove(ite1_1); - wjte2.getReferences2().add(ite2_2); + wjte1.getReferences1().remove( ite1_1 ); + wjte2.getReferences2().add( ite2_2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // + // - ite1_1_id = ite1_1.getId(); - ite1_2_id = ite1_2.getId(); - ite2_1_id = ite2_1.getId(); - ite2_2_id = ite2_2.getId(); + ite1_1_id = ite1_1.getId(); + ite1_2_id = ite1_2.getId(); + ite2_1_id = ite2_1.getId(); + ite2_2_id = ite2_2.getId(); - wjte1_id = wjte1.getId(); - wjte2_id = wjte2.getId(); - } + wjte1_id = wjte1.getId(); + wjte2_id = wjte2.getId(); + } - @Test - public void testRevisionsCounts() { - assertEquals(Arrays.asList(1, 2, 4), getAuditReader().getRevisions(WhereJoinTableEntity.class, wjte1_id)); - assertEquals(Arrays.asList(1, 3, 4), getAuditReader().getRevisions(WhereJoinTableEntity.class, wjte2_id)); + @Test + public void testRevisionsCounts() { + assertEquals( Arrays.asList( 1, 2, 4 ), getAuditReader().getRevisions( WhereJoinTableEntity.class, wjte1_id ) ); + assertEquals( Arrays.asList( 1, 3, 4 ), getAuditReader().getRevisions( WhereJoinTableEntity.class, wjte2_id ) ); - assertEquals(Arrays.asList(1), getAuditReader().getRevisions(IntNoAutoIdTestEntity.class, ite1_1_id)); - assertEquals(Arrays.asList(1), getAuditReader().getRevisions(IntNoAutoIdTestEntity.class, ite1_2_id)); - assertEquals(Arrays.asList(1), getAuditReader().getRevisions(IntNoAutoIdTestEntity.class, ite2_1_id)); - assertEquals(Arrays.asList(1), getAuditReader().getRevisions(IntNoAutoIdTestEntity.class, ite2_2_id)); - } + assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( IntNoAutoIdTestEntity.class, ite1_1_id ) ); + assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( IntNoAutoIdTestEntity.class, ite1_2_id ) ); + assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( IntNoAutoIdTestEntity.class, ite2_1_id ) ); + assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( IntNoAutoIdTestEntity.class, ite2_2_id ) ); + } - @Test - public void testHistoryOfWjte1() { - IntNoAutoIdTestEntity ite1_1 = getEntityManager().find(IntNoAutoIdTestEntity.class, ite1_1_id); - IntNoAutoIdTestEntity ite2_1 = getEntityManager().find(IntNoAutoIdTestEntity.class, ite2_1_id); + @Test + public void testHistoryOfWjte1() { + IntNoAutoIdTestEntity ite1_1 = getEntityManager().find( IntNoAutoIdTestEntity.class, ite1_1_id ); + IntNoAutoIdTestEntity ite2_1 = getEntityManager().find( IntNoAutoIdTestEntity.class, ite2_1_id ); - WhereJoinTableEntity rev1 = getAuditReader().find(WhereJoinTableEntity.class, wjte1_id, 1); - WhereJoinTableEntity rev2 = getAuditReader().find(WhereJoinTableEntity.class, wjte1_id, 2); - WhereJoinTableEntity rev3 = getAuditReader().find(WhereJoinTableEntity.class, wjte1_id, 3); - WhereJoinTableEntity rev4 = getAuditReader().find(WhereJoinTableEntity.class, wjte1_id, 4); + WhereJoinTableEntity rev1 = getAuditReader().find( WhereJoinTableEntity.class, wjte1_id, 1 ); + WhereJoinTableEntity rev2 = getAuditReader().find( WhereJoinTableEntity.class, wjte1_id, 2 ); + WhereJoinTableEntity rev3 = getAuditReader().find( WhereJoinTableEntity.class, wjte1_id, 3 ); + WhereJoinTableEntity rev4 = getAuditReader().find( WhereJoinTableEntity.class, wjte1_id, 4 ); - // Checking 1st list - assert TestTools.checkList(rev1.getReferences1()); - assert TestTools.checkList(rev2.getReferences1(), ite1_1); - assert TestTools.checkList(rev3.getReferences1(), ite1_1); - assert TestTools.checkList(rev4.getReferences1()); + // Checking 1st list + assert TestTools.checkList( rev1.getReferences1() ); + assert TestTools.checkList( rev2.getReferences1(), ite1_1 ); + assert TestTools.checkList( rev3.getReferences1(), ite1_1 ); + assert TestTools.checkList( rev4.getReferences1() ); - // Checking 2nd list - assert TestTools.checkList(rev1.getReferences2()); - assert TestTools.checkList(rev2.getReferences2(), ite2_1); - assert TestTools.checkList(rev3.getReferences2(), ite2_1); - assert TestTools.checkList(rev4.getReferences2(), ite2_1); - } + // Checking 2nd list + assert TestTools.checkList( rev1.getReferences2() ); + assert TestTools.checkList( rev2.getReferences2(), ite2_1 ); + assert TestTools.checkList( rev3.getReferences2(), ite2_1 ); + assert TestTools.checkList( rev4.getReferences2(), ite2_1 ); + } - @Test - public void testHistoryOfWjte2() { - IntNoAutoIdTestEntity ite1_1 = getEntityManager().find(IntNoAutoIdTestEntity.class, ite1_1_id); - IntNoAutoIdTestEntity ite1_2 = getEntityManager().find(IntNoAutoIdTestEntity.class, ite1_2_id); - IntNoAutoIdTestEntity ite2_2 = getEntityManager().find(IntNoAutoIdTestEntity.class, ite2_2_id); + @Test + public void testHistoryOfWjte2() { + IntNoAutoIdTestEntity ite1_1 = getEntityManager().find( IntNoAutoIdTestEntity.class, ite1_1_id ); + IntNoAutoIdTestEntity ite1_2 = getEntityManager().find( IntNoAutoIdTestEntity.class, ite1_2_id ); + IntNoAutoIdTestEntity ite2_2 = getEntityManager().find( IntNoAutoIdTestEntity.class, ite2_2_id ); - WhereJoinTableEntity rev1 = getAuditReader().find(WhereJoinTableEntity.class, wjte2_id, 1); - WhereJoinTableEntity rev2 = getAuditReader().find(WhereJoinTableEntity.class, wjte2_id, 2); - WhereJoinTableEntity rev3 = getAuditReader().find(WhereJoinTableEntity.class, wjte2_id, 3); - WhereJoinTableEntity rev4 = getAuditReader().find(WhereJoinTableEntity.class, wjte2_id, 4); + WhereJoinTableEntity rev1 = getAuditReader().find( WhereJoinTableEntity.class, wjte2_id, 1 ); + WhereJoinTableEntity rev2 = getAuditReader().find( WhereJoinTableEntity.class, wjte2_id, 2 ); + WhereJoinTableEntity rev3 = getAuditReader().find( WhereJoinTableEntity.class, wjte2_id, 3 ); + WhereJoinTableEntity rev4 = getAuditReader().find( WhereJoinTableEntity.class, wjte2_id, 4 ); - // Checking 1st list - assert TestTools.checkList(rev1.getReferences1()); - assert TestTools.checkList(rev2.getReferences1()); - assert TestTools.checkList(rev3.getReferences1(), ite1_1, ite1_2); - assert TestTools.checkList(rev4.getReferences1(), ite1_1, ite1_2); + // Checking 1st list + assert TestTools.checkList( rev1.getReferences1() ); + assert TestTools.checkList( rev2.getReferences1() ); + assert TestTools.checkList( rev3.getReferences1(), ite1_1, ite1_2 ); + assert TestTools.checkList( rev4.getReferences1(), ite1_1, ite1_2 ); - // Checking 2nd list - assert TestTools.checkList(rev1.getReferences2()); - assert TestTools.checkList(rev2.getReferences2()); - assert TestTools.checkList(rev3.getReferences2()); - assert TestTools.checkList(rev4.getReferences2(), ite2_2); - } + // Checking 2nd list + assert TestTools.checkList( rev1.getReferences2() ); + assert TestTools.checkList( rev2.getReferences2() ); + assert TestTools.checkList( rev3.getReferences2() ); + assert TestTools.checkList( rev4.getReferences2(), ite2_2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/CustomComparatorEntityTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/CustomComparatorEntityTest.java index 6282b4078f..cc5bb26d36 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/CustomComparatorEntityTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/CustomComparatorEntityTest.java @@ -23,14 +23,12 @@ */ package org.hibernate.envers.test.integration.manytomany; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import java.util.SortedMap; import java.util.SortedSet; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -38,6 +36,8 @@ import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.StrTestEntityComparator; import org.hibernate.envers.test.entities.manytomany.SortedSetEntity; +import org.junit.Test; + import static org.junit.Assert.assertEquals; /** @@ -45,238 +45,238 @@ import static org.junit.Assert.assertEquals; */ public class CustomComparatorEntityTest extends BaseEnversJPAFunctionalTestCase { - private Integer id1; - private Integer id2; - private Integer id3; - private Integer id4; + private Integer id1; + private Integer id2; + private Integer id3; + private Integer id4; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class, SortedSetEntity.class }; - } + return new Class[] {StrTestEntity.class, SortedSetEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - SortedSetEntity entity1 = new SortedSetEntity(1, "sortedEntity1"); + SortedSetEntity entity1 = new SortedSetEntity( 1, "sortedEntity1" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(entity1); + em.persist( entity1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 + // Revision 2 - em.getTransaction().begin(); + em.getTransaction().begin(); - entity1 = em.find(SortedSetEntity.class, 1); - final StrTestEntity strTestEntity1 = new StrTestEntity("abc"); - em.persist(strTestEntity1); - id1 = strTestEntity1.getId(); - entity1.getSortedSet().add(strTestEntity1); - entity1.getSortedMap().put(strTestEntity1, "abc"); + entity1 = em.find( SortedSetEntity.class, 1 ); + final StrTestEntity strTestEntity1 = new StrTestEntity( "abc" ); + em.persist( strTestEntity1 ); + id1 = strTestEntity1.getId(); + entity1.getSortedSet().add( strTestEntity1 ); + entity1.getSortedMap().put( strTestEntity1, "abc" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - entity1 = em.find(SortedSetEntity.class, 1); - final StrTestEntity strTestEntity2 = new StrTestEntity("aaa"); - em.persist(strTestEntity2); - id2 = strTestEntity2.getId(); - entity1.getSortedSet().add(strTestEntity2); - entity1.getSortedMap().put(strTestEntity2, "aaa"); + entity1 = em.find( SortedSetEntity.class, 1 ); + final StrTestEntity strTestEntity2 = new StrTestEntity( "aaa" ); + em.persist( strTestEntity2 ); + id2 = strTestEntity2.getId(); + entity1.getSortedSet().add( strTestEntity2 ); + entity1.getSortedMap().put( strTestEntity2, "aaa" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); + // Revision 4 + em.getTransaction().begin(); - entity1 = em.find(SortedSetEntity.class, 1); - final StrTestEntity strTestEntity3 = new StrTestEntity("aba"); - em.persist(strTestEntity3); - id3 = strTestEntity3.getId(); - entity1.getSortedSet().add(strTestEntity3); - entity1.getSortedMap().put(strTestEntity3, "aba"); + entity1 = em.find( SortedSetEntity.class, 1 ); + final StrTestEntity strTestEntity3 = new StrTestEntity( "aba" ); + em.persist( strTestEntity3 ); + id3 = strTestEntity3.getId(); + entity1.getSortedSet().add( strTestEntity3 ); + entity1.getSortedMap().put( strTestEntity3, "aba" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 5 - em.getTransaction().begin(); + // Revision 5 + em.getTransaction().begin(); - entity1 = em.find(SortedSetEntity.class, 1); - final StrTestEntity strTestEntity4 = new StrTestEntity("aac"); - em.persist(strTestEntity4); - id4 = strTestEntity4.getId(); - entity1.getSortedSet().add(strTestEntity4); - entity1.getSortedMap().put(strTestEntity4, "aac"); + entity1 = em.find( SortedSetEntity.class, 1 ); + final StrTestEntity strTestEntity4 = new StrTestEntity( "aac" ); + em.persist( strTestEntity4 ); + id4 = strTestEntity4.getId(); + entity1.getSortedSet().add( strTestEntity4 ); + entity1.getSortedMap().put( strTestEntity4, "aac" ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assertEquals(Arrays.asList(1, 2, 3, 4, 5), getAuditReader().getRevisions(SortedSetEntity.class, 1)); - assertEquals(Arrays.asList(2), getAuditReader().getRevisions(StrTestEntity.class, id1)); - assertEquals(Arrays.asList(3), getAuditReader().getRevisions(StrTestEntity.class, id2)); - assertEquals(Arrays.asList(4), getAuditReader().getRevisions(StrTestEntity.class, id3)); - assertEquals(Arrays.asList(5), getAuditReader().getRevisions(StrTestEntity.class, id4)); - } + @Test + public void testRevisionsCounts() { + assertEquals( Arrays.asList( 1, 2, 3, 4, 5 ), getAuditReader().getRevisions( SortedSetEntity.class, 1 ) ); + assertEquals( Arrays.asList( 2 ), getAuditReader().getRevisions( StrTestEntity.class, id1 ) ); + assertEquals( Arrays.asList( 3 ), getAuditReader().getRevisions( StrTestEntity.class, id2 ) ); + assertEquals( Arrays.asList( 4 ), getAuditReader().getRevisions( StrTestEntity.class, id3 ) ); + assertEquals( Arrays.asList( 5 ), getAuditReader().getRevisions( StrTestEntity.class, id4 ) ); + } - @Test - public void testCurrentStateOfEntity1() { - final SortedSetEntity entity1 = getEntityManager().find(SortedSetEntity.class, 1); + @Test + public void testCurrentStateOfEntity1() { + final SortedSetEntity entity1 = getEntityManager().find( SortedSetEntity.class, 1 ); - assertEquals("sortedEntity1", entity1.getData()); - assertEquals(Integer.valueOf(1), entity1.getId()); + assertEquals( "sortedEntity1", entity1.getData() ); + assertEquals( Integer.valueOf( 1 ), entity1.getId() ); - final SortedSet sortedSet = entity1.getSortedSet(); - assertEquals(StrTestEntityComparator.class, sortedSet.comparator().getClass()); - assertEquals(4, sortedSet.size()); - final Iterator iterator = sortedSet.iterator(); - checkStrTestEntity(iterator.next(), id2, "aaa"); - checkStrTestEntity(iterator.next(), id4, "aac"); - checkStrTestEntity(iterator.next(), id3, "aba"); - checkStrTestEntity(iterator.next(), id1, "abc"); + final SortedSet sortedSet = entity1.getSortedSet(); + assertEquals( StrTestEntityComparator.class, sortedSet.comparator().getClass() ); + assertEquals( 4, sortedSet.size() ); + final Iterator iterator = sortedSet.iterator(); + checkStrTestEntity( iterator.next(), id2, "aaa" ); + checkStrTestEntity( iterator.next(), id4, "aac" ); + checkStrTestEntity( iterator.next(), id3, "aba" ); + checkStrTestEntity( iterator.next(), id1, "abc" ); final SortedMap sortedMap = entity1.getSortedMap(); - assertEquals(StrTestEntityComparator.class, sortedMap.comparator().getClass()); - assertEquals(4, sortedMap.size()); + assertEquals( StrTestEntityComparator.class, sortedMap.comparator().getClass() ); + assertEquals( 4, sortedMap.size() ); Iterator> mapIterator = sortedMap.entrySet().iterator(); - checkStrTestEntity(mapIterator.next().getKey(), id2, "aaa"); - checkStrTestEntity(mapIterator.next().getKey(), id4, "aac"); - checkStrTestEntity(mapIterator.next().getKey(), id3, "aba"); - checkStrTestEntity(mapIterator.next().getKey(), id1, "abc"); + checkStrTestEntity( mapIterator.next().getKey(), id2, "aaa" ); + checkStrTestEntity( mapIterator.next().getKey(), id4, "aac" ); + checkStrTestEntity( mapIterator.next().getKey(), id3, "aba" ); + checkStrTestEntity( mapIterator.next().getKey(), id1, "abc" ); - mapIterator = sortedMap.entrySet().iterator(); - assertEquals(mapIterator.next().getValue(), "aaa"); - assertEquals(mapIterator.next().getValue(), "aac"); - assertEquals(mapIterator.next().getValue(), "aba"); - assertEquals(mapIterator.next().getValue(), "abc"); - } + mapIterator = sortedMap.entrySet().iterator(); + assertEquals( mapIterator.next().getValue(), "aaa" ); + assertEquals( mapIterator.next().getValue(), "aac" ); + assertEquals( mapIterator.next().getValue(), "aba" ); + assertEquals( mapIterator.next().getValue(), "abc" ); + } - private void checkStrTestEntity(StrTestEntity entity, Integer id, String sortKey) { - assertEquals(id, entity.getId()); - assertEquals(sortKey, entity.getStr()); - } + private void checkStrTestEntity(StrTestEntity entity, Integer id, String sortKey) { + assertEquals( id, entity.getId() ); + assertEquals( sortKey, entity.getStr() ); + } - @Test - public void testHistoryOfEntity1() throws Exception { - SortedSetEntity entity1 = getAuditReader().find(SortedSetEntity.class, 1, 1); + @Test + public void testHistoryOfEntity1() throws Exception { + SortedSetEntity entity1 = getAuditReader().find( SortedSetEntity.class, 1, 1 ); - assertEquals("sortedEntity1", entity1.getData()); - assertEquals(Integer.valueOf(1), entity1.getId()); + assertEquals( "sortedEntity1", entity1.getData() ); + assertEquals( Integer.valueOf( 1 ), entity1.getId() ); - SortedSet sortedSet = entity1.getSortedSet(); - assertEquals(StrTestEntityComparator.class, sortedSet.comparator().getClass()); - assertEquals(0, sortedSet.size()); + SortedSet sortedSet = entity1.getSortedSet(); + assertEquals( StrTestEntityComparator.class, sortedSet.comparator().getClass() ); + assertEquals( 0, sortedSet.size() ); SortedMap sortedMap = entity1.getSortedMap(); - assertEquals(StrTestEntityComparator.class, sortedMap.comparator().getClass()); - assertEquals(0, sortedMap.size()); + assertEquals( StrTestEntityComparator.class, sortedMap.comparator().getClass() ); + assertEquals( 0, sortedMap.size() ); - entity1 = getAuditReader().find(SortedSetEntity.class, 1, 2); + entity1 = getAuditReader().find( SortedSetEntity.class, 1, 2 ); - assertEquals("sortedEntity1", entity1.getData()); - assertEquals(Integer.valueOf(1), entity1.getId()); + assertEquals( "sortedEntity1", entity1.getData() ); + assertEquals( Integer.valueOf( 1 ), entity1.getId() ); - sortedSet = entity1.getSortedSet(); - assertEquals(StrTestEntityComparator.class, sortedSet.comparator().getClass()); - assertEquals(1, sortedSet.size()); - Iterator iterator = sortedSet.iterator(); - checkStrTestEntity(iterator.next(), id1, "abc"); + sortedSet = entity1.getSortedSet(); + assertEquals( StrTestEntityComparator.class, sortedSet.comparator().getClass() ); + assertEquals( 1, sortedSet.size() ); + Iterator iterator = sortedSet.iterator(); + checkStrTestEntity( iterator.next(), id1, "abc" ); sortedMap = entity1.getSortedMap(); - assertEquals(StrTestEntityComparator.class, sortedMap.comparator().getClass()); - assertEquals(1, sortedMap.size()); + assertEquals( StrTestEntityComparator.class, sortedMap.comparator().getClass() ); + assertEquals( 1, sortedMap.size() ); Iterator> mapIterator = sortedMap.entrySet().iterator(); - checkStrTestEntity(mapIterator.next().getKey(), id1, "abc"); + checkStrTestEntity( mapIterator.next().getKey(), id1, "abc" ); - mapIterator = sortedMap.entrySet().iterator(); - assertEquals(mapIterator.next().getValue(), "abc"); + mapIterator = sortedMap.entrySet().iterator(); + assertEquals( mapIterator.next().getValue(), "abc" ); - entity1 = getAuditReader().find(SortedSetEntity.class, 1, 3); + entity1 = getAuditReader().find( SortedSetEntity.class, 1, 3 ); - assertEquals("sortedEntity1", entity1.getData()); - assertEquals(Integer.valueOf(1), entity1.getId()); + assertEquals( "sortedEntity1", entity1.getData() ); + assertEquals( Integer.valueOf( 1 ), entity1.getId() ); - sortedSet = entity1.getSortedSet(); - assertEquals(StrTestEntityComparator.class, sortedSet.comparator().getClass()); - assertEquals(2, sortedSet.size()); - iterator = sortedSet.iterator(); - checkStrTestEntity(iterator.next(), id2, "aaa"); - checkStrTestEntity(iterator.next(), id1, "abc"); + sortedSet = entity1.getSortedSet(); + assertEquals( StrTestEntityComparator.class, sortedSet.comparator().getClass() ); + assertEquals( 2, sortedSet.size() ); + iterator = sortedSet.iterator(); + checkStrTestEntity( iterator.next(), id2, "aaa" ); + checkStrTestEntity( iterator.next(), id1, "abc" ); sortedMap = entity1.getSortedMap(); - assertEquals(StrTestEntityComparator.class, sortedMap.comparator().getClass()); - assertEquals(2, sortedMap.size()); + assertEquals( StrTestEntityComparator.class, sortedMap.comparator().getClass() ); + assertEquals( 2, sortedMap.size() ); mapIterator = sortedMap.entrySet().iterator(); - checkStrTestEntity(mapIterator.next().getKey(), id2, "aaa"); - checkStrTestEntity(mapIterator.next().getKey(), id1, "abc"); + checkStrTestEntity( mapIterator.next().getKey(), id2, "aaa" ); + checkStrTestEntity( mapIterator.next().getKey(), id1, "abc" ); - mapIterator = sortedMap.entrySet().iterator(); - assertEquals(mapIterator.next().getValue(), "aaa"); - assertEquals(mapIterator.next().getValue(), "abc"); + mapIterator = sortedMap.entrySet().iterator(); + assertEquals( mapIterator.next().getValue(), "aaa" ); + assertEquals( mapIterator.next().getValue(), "abc" ); - entity1 = getAuditReader().find(SortedSetEntity.class, 1, 4); + entity1 = getAuditReader().find( SortedSetEntity.class, 1, 4 ); - assertEquals("sortedEntity1", entity1.getData()); - assertEquals(Integer.valueOf(1), entity1.getId()); + assertEquals( "sortedEntity1", entity1.getData() ); + assertEquals( Integer.valueOf( 1 ), entity1.getId() ); - sortedSet = entity1.getSortedSet(); - assertEquals(StrTestEntityComparator.class, sortedSet.comparator().getClass()); - assertEquals(3, sortedSet.size()); - iterator = sortedSet.iterator(); - checkStrTestEntity(iterator.next(), id2, "aaa"); - checkStrTestEntity(iterator.next(), id3, "aba"); - checkStrTestEntity(iterator.next(), id1, "abc"); + sortedSet = entity1.getSortedSet(); + assertEquals( StrTestEntityComparator.class, sortedSet.comparator().getClass() ); + assertEquals( 3, sortedSet.size() ); + iterator = sortedSet.iterator(); + checkStrTestEntity( iterator.next(), id2, "aaa" ); + checkStrTestEntity( iterator.next(), id3, "aba" ); + checkStrTestEntity( iterator.next(), id1, "abc" ); sortedMap = entity1.getSortedMap(); - assertEquals(StrTestEntityComparator.class, sortedMap.comparator().getClass()); - assertEquals(3, sortedMap.size()); + assertEquals( StrTestEntityComparator.class, sortedMap.comparator().getClass() ); + assertEquals( 3, sortedMap.size() ); mapIterator = sortedMap.entrySet().iterator(); - checkStrTestEntity(mapIterator.next().getKey(), id2, "aaa"); - checkStrTestEntity(mapIterator.next().getKey(), id3, "aba"); - checkStrTestEntity(mapIterator.next().getKey(), id1, "abc"); + checkStrTestEntity( mapIterator.next().getKey(), id2, "aaa" ); + checkStrTestEntity( mapIterator.next().getKey(), id3, "aba" ); + checkStrTestEntity( mapIterator.next().getKey(), id1, "abc" ); - mapIterator = sortedMap.entrySet().iterator(); - assertEquals(mapIterator.next().getValue(), "aaa"); - assertEquals(mapIterator.next().getValue(), "aba"); - assertEquals(mapIterator.next().getValue(), "abc"); + mapIterator = sortedMap.entrySet().iterator(); + assertEquals( mapIterator.next().getValue(), "aaa" ); + assertEquals( mapIterator.next().getValue(), "aba" ); + assertEquals( mapIterator.next().getValue(), "abc" ); - entity1 = getAuditReader().find(SortedSetEntity.class, 1, 5); + entity1 = getAuditReader().find( SortedSetEntity.class, 1, 5 ); - assertEquals("sortedEntity1", entity1.getData()); - assertEquals(Integer.valueOf(1), entity1.getId()); + assertEquals( "sortedEntity1", entity1.getData() ); + assertEquals( Integer.valueOf( 1 ), entity1.getId() ); - sortedSet = entity1.getSortedSet(); - assertEquals(StrTestEntityComparator.class, sortedSet.comparator().getClass()); - assertEquals(4, sortedSet.size()); - iterator = sortedSet.iterator(); - checkStrTestEntity(iterator.next(), id2, "aaa"); - checkStrTestEntity(iterator.next(), id4, "aac"); - checkStrTestEntity(iterator.next(), id3, "aba"); - checkStrTestEntity(iterator.next(), id1, "abc"); + sortedSet = entity1.getSortedSet(); + assertEquals( StrTestEntityComparator.class, sortedSet.comparator().getClass() ); + assertEquals( 4, sortedSet.size() ); + iterator = sortedSet.iterator(); + checkStrTestEntity( iterator.next(), id2, "aaa" ); + checkStrTestEntity( iterator.next(), id4, "aac" ); + checkStrTestEntity( iterator.next(), id3, "aba" ); + checkStrTestEntity( iterator.next(), id1, "abc" ); sortedMap = entity1.getSortedMap(); - assertEquals(StrTestEntityComparator.class, sortedMap.comparator().getClass()); - assertEquals(4, sortedMap.size()); + assertEquals( StrTestEntityComparator.class, sortedMap.comparator().getClass() ); + assertEquals( 4, sortedMap.size() ); mapIterator = sortedMap.entrySet().iterator(); - checkStrTestEntity(mapIterator.next().getKey(), id2, "aaa"); - checkStrTestEntity(mapIterator.next().getKey(), id4, "aac"); - checkStrTestEntity(mapIterator.next().getKey(), id3, "aba"); - checkStrTestEntity(mapIterator.next().getKey(), id1, "abc"); + checkStrTestEntity( mapIterator.next().getKey(), id2, "aaa" ); + checkStrTestEntity( mapIterator.next().getKey(), id4, "aac" ); + checkStrTestEntity( mapIterator.next().getKey(), id3, "aba" ); + checkStrTestEntity( mapIterator.next().getKey(), id1, "abc" ); - mapIterator = sortedMap.entrySet().iterator(); - assertEquals(mapIterator.next().getValue(), "aaa"); - assertEquals(mapIterator.next().getValue(), "aac"); - assertEquals(mapIterator.next().getValue(), "aba"); - assertEquals(mapIterator.next().getValue(), "abc"); - } + mapIterator = sortedMap.entrySet().iterator(); + assertEquals( mapIterator.next().getValue(), "aaa" ); + assertEquals( mapIterator.next().getValue(), "aac" ); + assertEquals( mapIterator.next().getValue(), "aba" ); + assertEquals( mapIterator.next().getValue(), "abc" ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/biowned/BasicBiowned.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/biowned/BasicBiowned.java index 20927626ee..b9af0e5b08 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/biowned/BasicBiowned.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/biowned/BasicBiowned.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.manytomany.biowned; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -34,189 +32,196 @@ import org.hibernate.envers.test.entities.manytomany.biowned.ListBiowning1Entity import org.hibernate.envers.test.entities.manytomany.biowned.ListBiowning2Entity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + import static org.junit.Assert.assertEquals; /** * @author Adam Warski (adam at warski dot org) */ public class BasicBiowned extends BaseEnversJPAFunctionalTestCase { - private Integer o1_1_id; - private Integer o1_2_id; - private Integer o2_1_id; - private Integer o2_2_id; + private Integer o1_1_id; + private Integer o1_2_id; + private Integer o2_1_id; + private Integer o2_2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ListBiowning1Entity.class, ListBiowning2Entity.class }; - } + return new Class[] {ListBiowning1Entity.class, ListBiowning2Entity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - ListBiowning1Entity o1_1 = new ListBiowning1Entity("o1_1"); - ListBiowning1Entity o1_2 = new ListBiowning1Entity("o1_2"); - ListBiowning2Entity o2_1 = new ListBiowning2Entity("o2_1"); - ListBiowning2Entity o2_2 = new ListBiowning2Entity("o2_2"); + ListBiowning1Entity o1_1 = new ListBiowning1Entity( "o1_1" ); + ListBiowning1Entity o1_2 = new ListBiowning1Entity( "o1_2" ); + ListBiowning2Entity o2_1 = new ListBiowning2Entity( "o2_1" ); + ListBiowning2Entity o2_2 = new ListBiowning2Entity( "o2_2" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(o1_1); - em.persist(o1_2); - em.persist(o2_1); - em.persist(o2_2); + em.persist( o1_1 ); + em.persist( o1_2 ); + em.persist( o2_1 ); + em.persist( o2_2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 2 (1_1 <-> 2_1; 1_2 <-> 2_2) + // Revision 2 (1_1 <-> 2_1; 1_2 <-> 2_2) - em.getTransaction().begin(); + em.getTransaction().begin(); - o1_1 = em.find(ListBiowning1Entity.class, o1_1.getId()); - o1_2 = em.find(ListBiowning1Entity.class, o1_2.getId()); - o2_1 = em.find(ListBiowning2Entity.class, o2_1.getId()); - o2_2 = em.find(ListBiowning2Entity.class, o2_2.getId()); + o1_1 = em.find( ListBiowning1Entity.class, o1_1.getId() ); + o1_2 = em.find( ListBiowning1Entity.class, o1_2.getId() ); + o2_1 = em.find( ListBiowning2Entity.class, o2_1.getId() ); + o2_2 = em.find( ListBiowning2Entity.class, o2_2.getId() ); - o1_1.getReferences().add(o2_1); - o1_2.getReferences().add(o2_2); + o1_1.getReferences().add( o2_1 ); + o1_2.getReferences().add( o2_2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 3 (1_1 <-> 2_1, 2_2; 1_2 <-> 2_2) - em.getTransaction().begin(); + // Revision 3 (1_1 <-> 2_1, 2_2; 1_2 <-> 2_2) + em.getTransaction().begin(); - o1_1 = em.find(ListBiowning1Entity.class, o1_1.getId()); - o2_2 = em.find(ListBiowning2Entity.class, o2_2.getId()); + o1_1 = em.find( ListBiowning1Entity.class, o1_1.getId() ); + o2_2 = em.find( ListBiowning2Entity.class, o2_2.getId() ); - o1_1.getReferences().add(o2_2); + o1_1.getReferences().add( o2_2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 4 (1_2 <-> 2_1, 2_2) - em.getTransaction().begin(); + // Revision 4 (1_2 <-> 2_1, 2_2) + em.getTransaction().begin(); - o1_1 = em.find(ListBiowning1Entity.class, o1_1.getId()); - o1_2 = em.find(ListBiowning1Entity.class, o1_2.getId()); - o2_1 = em.find(ListBiowning2Entity.class, o2_1.getId()); - o2_2 = em.find(ListBiowning2Entity.class, o2_2.getId()); + o1_1 = em.find( ListBiowning1Entity.class, o1_1.getId() ); + o1_2 = em.find( ListBiowning1Entity.class, o1_2.getId() ); + o2_1 = em.find( ListBiowning2Entity.class, o2_1.getId() ); + o2_2 = em.find( ListBiowning2Entity.class, o2_2.getId() ); - o2_2.getReferences().remove(o1_1); - o2_1.getReferences().remove(o1_1); - o2_1.getReferences().add(o1_2); + o2_2.getReferences().remove( o1_1 ); + o2_1.getReferences().remove( o1_1 ); + o2_1.getReferences().add( o1_2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 5 (1_1 <-> 2_2, 1_2 <-> 2_2) - em.getTransaction().begin(); + // Revision 5 (1_1 <-> 2_2, 1_2 <-> 2_2) + em.getTransaction().begin(); - o1_1 = em.find(ListBiowning1Entity.class, o1_1.getId()); - o1_2 = em.find(ListBiowning1Entity.class, o1_2.getId()); - o2_1 = em.find(ListBiowning2Entity.class, o2_1.getId()); - o2_2 = em.find(ListBiowning2Entity.class, o2_2.getId()); + o1_1 = em.find( ListBiowning1Entity.class, o1_1.getId() ); + o1_2 = em.find( ListBiowning1Entity.class, o1_2.getId() ); + o2_1 = em.find( ListBiowning2Entity.class, o2_1.getId() ); + o2_2 = em.find( ListBiowning2Entity.class, o2_2.getId() ); - o1_2.getReferences().remove(o2_1); - o1_1.getReferences().add(o2_2); + o1_2.getReferences().remove( o2_1 ); + o1_1.getReferences().add( o2_2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // + // - o1_1_id = o1_1.getId(); - o1_2_id = o1_2.getId(); - o2_1_id = o2_1.getId(); - o2_2_id = o2_2.getId(); - } + o1_1_id = o1_1.getId(); + o1_2_id = o1_2.getId(); + o2_1_id = o2_1.getId(); + o2_2_id = o2_2.getId(); + } - @Test - public void testRevisionsCounts() { - // Although it would seem that when modifying references both entities should be marked as modified, because - // ownly the owning side is notified (because of the bi-owning mapping), a revision is created only for - // the entity where the collection was directly modified. + @Test + public void testRevisionsCounts() { + // Although it would seem that when modifying references both entities should be marked as modified, because + // ownly the owning side is notified (because of the bi-owning mapping), a revision is created only for + // the entity where the collection was directly modified. - assertEquals(Arrays.asList(1, 2, 3, 5), getAuditReader().getRevisions(ListBiowning1Entity.class, o1_1_id)); - assertEquals(Arrays.asList(1, 2, 5), getAuditReader().getRevisions(ListBiowning1Entity.class, o1_2_id)); + assertEquals( + Arrays.asList( 1, 2, 3, 5 ), getAuditReader().getRevisions( + ListBiowning1Entity.class, + o1_1_id + ) + ); + assertEquals( Arrays.asList( 1, 2, 5 ), getAuditReader().getRevisions( ListBiowning1Entity.class, o1_2_id ) ); - assertEquals(Arrays.asList(1, 4), getAuditReader().getRevisions(ListBiowning2Entity.class, o2_1_id)); - assertEquals(Arrays.asList(1, 4), getAuditReader().getRevisions(ListBiowning2Entity.class, o2_2_id)); - } + assertEquals( Arrays.asList( 1, 4 ), getAuditReader().getRevisions( ListBiowning2Entity.class, o2_1_id ) ); + assertEquals( Arrays.asList( 1, 4 ), getAuditReader().getRevisions( ListBiowning2Entity.class, o2_2_id ) ); + } - @Test - public void testHistoryOfO1_1() { - ListBiowning2Entity o2_1 = getEntityManager().find(ListBiowning2Entity.class, o2_1_id); - ListBiowning2Entity o2_2 = getEntityManager().find(ListBiowning2Entity.class, o2_2_id); + @Test + public void testHistoryOfO1_1() { + ListBiowning2Entity o2_1 = getEntityManager().find( ListBiowning2Entity.class, o2_1_id ); + ListBiowning2Entity o2_2 = getEntityManager().find( ListBiowning2Entity.class, o2_2_id ); - ListBiowning1Entity rev1 = getAuditReader().find(ListBiowning1Entity.class, o1_1_id, 1); - ListBiowning1Entity rev2 = getAuditReader().find(ListBiowning1Entity.class, o1_1_id, 2); - ListBiowning1Entity rev3 = getAuditReader().find(ListBiowning1Entity.class, o1_1_id, 3); - ListBiowning1Entity rev4 = getAuditReader().find(ListBiowning1Entity.class, o1_1_id, 4); - ListBiowning1Entity rev5 = getAuditReader().find(ListBiowning1Entity.class, o1_1_id, 5); + ListBiowning1Entity rev1 = getAuditReader().find( ListBiowning1Entity.class, o1_1_id, 1 ); + ListBiowning1Entity rev2 = getAuditReader().find( ListBiowning1Entity.class, o1_1_id, 2 ); + ListBiowning1Entity rev3 = getAuditReader().find( ListBiowning1Entity.class, o1_1_id, 3 ); + ListBiowning1Entity rev4 = getAuditReader().find( ListBiowning1Entity.class, o1_1_id, 4 ); + ListBiowning1Entity rev5 = getAuditReader().find( ListBiowning1Entity.class, o1_1_id, 5 ); - assert TestTools.checkList(rev1.getReferences()); - assert TestTools.checkList(rev2.getReferences(), o2_1); - assert TestTools.checkList(rev3.getReferences(), o2_1, o2_2); - assert TestTools.checkList(rev4.getReferences()); - assert TestTools.checkList(rev5.getReferences(), o2_2); - } + assert TestTools.checkList( rev1.getReferences() ); + assert TestTools.checkList( rev2.getReferences(), o2_1 ); + assert TestTools.checkList( rev3.getReferences(), o2_1, o2_2 ); + assert TestTools.checkList( rev4.getReferences() ); + assert TestTools.checkList( rev5.getReferences(), o2_2 ); + } - @Test - public void testHistoryOfO1_2() { - ListBiowning2Entity o2_1 = getEntityManager().find(ListBiowning2Entity.class, o2_1_id); - ListBiowning2Entity o2_2 = getEntityManager().find(ListBiowning2Entity.class, o2_2_id); + @Test + public void testHistoryOfO1_2() { + ListBiowning2Entity o2_1 = getEntityManager().find( ListBiowning2Entity.class, o2_1_id ); + ListBiowning2Entity o2_2 = getEntityManager().find( ListBiowning2Entity.class, o2_2_id ); - ListBiowning1Entity rev1 = getAuditReader().find(ListBiowning1Entity.class, o1_2_id, 1); - ListBiowning1Entity rev2 = getAuditReader().find(ListBiowning1Entity.class, o1_2_id, 2); - ListBiowning1Entity rev3 = getAuditReader().find(ListBiowning1Entity.class, o1_2_id, 3); - ListBiowning1Entity rev4 = getAuditReader().find(ListBiowning1Entity.class, o1_2_id, 4); - ListBiowning1Entity rev5 = getAuditReader().find(ListBiowning1Entity.class, o1_2_id, 5); + ListBiowning1Entity rev1 = getAuditReader().find( ListBiowning1Entity.class, o1_2_id, 1 ); + ListBiowning1Entity rev2 = getAuditReader().find( ListBiowning1Entity.class, o1_2_id, 2 ); + ListBiowning1Entity rev3 = getAuditReader().find( ListBiowning1Entity.class, o1_2_id, 3 ); + ListBiowning1Entity rev4 = getAuditReader().find( ListBiowning1Entity.class, o1_2_id, 4 ); + ListBiowning1Entity rev5 = getAuditReader().find( ListBiowning1Entity.class, o1_2_id, 5 ); - assert TestTools.checkList(rev1.getReferences()); - assert TestTools.checkList(rev2.getReferences(), o2_2); - assert TestTools.checkList(rev3.getReferences(), o2_2); - assert TestTools.checkList(rev4.getReferences(), o2_1, o2_2); - System.out.println("rev5.getReferences() = " + rev5.getReferences()); - assert TestTools.checkList(rev5.getReferences(), o2_2); - } + assert TestTools.checkList( rev1.getReferences() ); + assert TestTools.checkList( rev2.getReferences(), o2_2 ); + assert TestTools.checkList( rev3.getReferences(), o2_2 ); + assert TestTools.checkList( rev4.getReferences(), o2_1, o2_2 ); + System.out.println( "rev5.getReferences() = " + rev5.getReferences() ); + assert TestTools.checkList( rev5.getReferences(), o2_2 ); + } - @Test - public void testHistoryOfO2_1() { - ListBiowning1Entity o1_1 = getEntityManager().find(ListBiowning1Entity.class, o1_1_id); - ListBiowning1Entity o1_2 = getEntityManager().find(ListBiowning1Entity.class, o1_2_id); + @Test + public void testHistoryOfO2_1() { + ListBiowning1Entity o1_1 = getEntityManager().find( ListBiowning1Entity.class, o1_1_id ); + ListBiowning1Entity o1_2 = getEntityManager().find( ListBiowning1Entity.class, o1_2_id ); - ListBiowning2Entity rev1 = getAuditReader().find(ListBiowning2Entity.class, o2_1_id, 1); - ListBiowning2Entity rev2 = getAuditReader().find(ListBiowning2Entity.class, o2_1_id, 2); - ListBiowning2Entity rev3 = getAuditReader().find(ListBiowning2Entity.class, o2_1_id, 3); - ListBiowning2Entity rev4 = getAuditReader().find(ListBiowning2Entity.class, o2_1_id, 4); - ListBiowning2Entity rev5 = getAuditReader().find(ListBiowning2Entity.class, o2_1_id, 5); + ListBiowning2Entity rev1 = getAuditReader().find( ListBiowning2Entity.class, o2_1_id, 1 ); + ListBiowning2Entity rev2 = getAuditReader().find( ListBiowning2Entity.class, o2_1_id, 2 ); + ListBiowning2Entity rev3 = getAuditReader().find( ListBiowning2Entity.class, o2_1_id, 3 ); + ListBiowning2Entity rev4 = getAuditReader().find( ListBiowning2Entity.class, o2_1_id, 4 ); + ListBiowning2Entity rev5 = getAuditReader().find( ListBiowning2Entity.class, o2_1_id, 5 ); - assert TestTools.checkList(rev1.getReferences()); - assert TestTools.checkList(rev2.getReferences(), o1_1); - assert TestTools.checkList(rev3.getReferences(), o1_1); - assert TestTools.checkList(rev4.getReferences(), o1_2); - assert TestTools.checkList(rev5.getReferences()); - } + assert TestTools.checkList( rev1.getReferences() ); + assert TestTools.checkList( rev2.getReferences(), o1_1 ); + assert TestTools.checkList( rev3.getReferences(), o1_1 ); + assert TestTools.checkList( rev4.getReferences(), o1_2 ); + assert TestTools.checkList( rev5.getReferences() ); + } - @Test - public void testHistoryOfO2_2() { - ListBiowning1Entity o1_1 = getEntityManager().find(ListBiowning1Entity.class, o1_1_id); - ListBiowning1Entity o1_2 = getEntityManager().find(ListBiowning1Entity.class, o1_2_id); + @Test + public void testHistoryOfO2_2() { + ListBiowning1Entity o1_1 = getEntityManager().find( ListBiowning1Entity.class, o1_1_id ); + ListBiowning1Entity o1_2 = getEntityManager().find( ListBiowning1Entity.class, o1_2_id ); - ListBiowning2Entity rev1 = getAuditReader().find(ListBiowning2Entity.class, o2_2_id, 1); - ListBiowning2Entity rev2 = getAuditReader().find(ListBiowning2Entity.class, o2_2_id, 2); - ListBiowning2Entity rev3 = getAuditReader().find(ListBiowning2Entity.class, o2_2_id, 3); - ListBiowning2Entity rev4 = getAuditReader().find(ListBiowning2Entity.class, o2_2_id, 4); - ListBiowning2Entity rev5 = getAuditReader().find(ListBiowning2Entity.class, o2_2_id, 5); + ListBiowning2Entity rev1 = getAuditReader().find( ListBiowning2Entity.class, o2_2_id, 1 ); + ListBiowning2Entity rev2 = getAuditReader().find( ListBiowning2Entity.class, o2_2_id, 2 ); + ListBiowning2Entity rev3 = getAuditReader().find( ListBiowning2Entity.class, o2_2_id, 3 ); + ListBiowning2Entity rev4 = getAuditReader().find( ListBiowning2Entity.class, o2_2_id, 4 ); + ListBiowning2Entity rev5 = getAuditReader().find( ListBiowning2Entity.class, o2_2_id, 5 ); - assert TestTools.checkList(rev1.getReferences()); - assert TestTools.checkList(rev2.getReferences(), o1_2); - assert TestTools.checkList(rev3.getReferences(), o1_1, o1_2); - assert TestTools.checkList(rev4.getReferences(), o1_2); - assert TestTools.checkList(rev5.getReferences(), o1_1, o1_2); - } + assert TestTools.checkList( rev1.getReferences() ); + assert TestTools.checkList( rev2.getReferences(), o1_2 ); + assert TestTools.checkList( rev3.getReferences(), o1_1, o1_2 ); + assert TestTools.checkList( rev4.getReferences(), o1_2 ); + assert TestTools.checkList( rev5.getReferences(), o1_1, o1_2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/DetailSubclass.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/DetailSubclass.java index e211f4cd96..e9641d36a6 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/DetailSubclass.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/DetailSubclass.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.integration.manytomany.inverseToSuperclass; + import org.hibernate.envers.Audited; @Audited diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/DetailSubclass2.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/DetailSubclass2.java index e99efaf833..ffcef01c60 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/DetailSubclass2.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/DetailSubclass2.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.integration.manytomany.inverseToSuperclass; + import org.hibernate.envers.Audited; @Audited @@ -7,7 +8,7 @@ public class DetailSubclass2 extends DetailSubclass { private String str3; public DetailSubclass2() { - + } public String getStr3() { diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/DetailSuperclass.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/DetailSuperclass.java index f5697a74d4..2234676b44 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/DetailSuperclass.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/DetailSuperclass.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.integration.manytomany.inverseToSuperclass; + import java.util.List; import org.hibernate.envers.Audited; diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/ManyToManyInverseToSuperclassTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/ManyToManyInverseToSuperclassTest.java index 16deaf5b4f..4a0f2a4f71 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/ManyToManyInverseToSuperclassTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/ManyToManyInverseToSuperclassTest.java @@ -1,27 +1,26 @@ package org.hibernate.envers.test.integration.manytomany.inverseToSuperclass; -import java.util.ArrayList; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.ArrayList; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Hern�n Chanfreau - * */ -public class ManyToManyInverseToSuperclassTest extends BaseEnversJPAFunctionalTestCase { +public class ManyToManyInverseToSuperclassTest extends BaseEnversJPAFunctionalTestCase { private long m1_id; @Override protected String[] getMappings() { - return new String[] { "mappings/manyToMany/inverseToSuperclass/mappings.hbm.xml" }; + return new String[] {"mappings/manyToMany/inverseToSuperclass/mappings.hbm.xml"}; } @Test - @Priority(10) + @Priority(10) public void initData() { EntityManager em = getEntityManager(); @@ -31,16 +30,16 @@ public class ManyToManyInverseToSuperclassTest extends BaseEnversJPAFunctionalTe // Revision 1 em.getTransaction().begin(); - det1.setStr2("detail 1"); + det1.setStr2( "detail 1" ); - m1.setStr("master"); - m1.setItems(new ArrayList()); - m1.getItems().add(det1); + m1.setStr( "master" ); + m1.setItems( new ArrayList() ); + m1.getItems().add( det1 ); - det1.setMasters(new ArrayList()); - det1.getMasters().add(m1); + det1.setMasters( new ArrayList() ); + det1.getMasters().add( m1 ); - em.persist(m1); + em.persist( m1 ); em.getTransaction().commit(); m1_id = m1.getId(); @@ -89,10 +88,10 @@ public class ManyToManyInverseToSuperclassTest extends BaseEnversJPAFunctionalTe @Test public void testHistoryExists() { - Master rev1_1 = getAuditReader().find(Master.class, m1_id, 1); - Master rev1_2 = getAuditReader().find(Master.class, m1_id, 2); - Master rev1_3 = getAuditReader().find(Master.class, m1_id, 3); - Master rev1_4 = getAuditReader().find(Master.class, m1_id, 4); + Master rev1_1 = getAuditReader().find( Master.class, m1_id, 1 ); + Master rev1_2 = getAuditReader().find( Master.class, m1_id, 2 ); + Master rev1_3 = getAuditReader().find( Master.class, m1_id, 3 ); + Master rev1_4 = getAuditReader().find( Master.class, m1_id, 4 ); assert (rev1_1 != null); assert (rev1_2 != null); diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/Master.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/Master.java index 6a66ee44d2..b87834634c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/Master.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/inverseToSuperclass/Master.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.integration.manytomany.inverseToSuperclass; + import java.util.List; import org.hibernate.envers.Audited; diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/sametable/BasicSametable.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/sametable/BasicSametable.java index df91a972f9..d33b29fc0b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/sametable/BasicSametable.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/sametable/BasicSametable.java @@ -23,12 +23,9 @@ */ package org.hibernate.envers.test.integration.manytomany.sametable; +import javax.persistence.EntityManager; import java.sql.Types; import java.util.Arrays; -import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; import org.hibernate.Session; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -38,268 +35,276 @@ import org.hibernate.envers.test.entities.manytomany.sametable.Child2Entity; import org.hibernate.envers.test.entities.manytomany.sametable.ParentEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Assert; +import org.junit.Test; + /** * Test which checks that auditing entities which contain multiple mappings to same tables work. + * * @author Adam Warski (adam at warski dot org) */ -public class BasicSametable extends BaseEnversJPAFunctionalTestCase { - private Integer p1_id; - private Integer p2_id; - private Integer c1_1_id; - private Integer c1_2_id; - private Integer c2_1_id; - private Integer c2_2_id; +public class BasicSametable extends BaseEnversJPAFunctionalTestCase { + private Integer p1_id; + private Integer p2_id; + private Integer c1_1_id; + private Integer c1_2_id; + private Integer c2_1_id; + private Integer c2_2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ParentEntity.class, Child1Entity.class, Child2Entity.class }; - } + return new Class[] {ParentEntity.class, Child1Entity.class, Child2Entity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // We need first to modify the columns in the middle (join table) to allow null values. Hbm2ddl doesn't seem - // to allow this. - em.getTransaction().begin(); - Session session = (Session) em.getDelegate(); - session.createSQLQuery("DROP TABLE children").executeUpdate(); - session.createSQLQuery("CREATE TABLE children ( parent_id " + getDialect().getTypeName(Types.INTEGER) + - ", child1_id " + getDialect().getTypeName(Types.INTEGER) + " NULL" + - ", child2_id " + getDialect().getTypeName(Types.INTEGER) + " NULL )").executeUpdate(); - session.createSQLQuery("DROP TABLE children_AUD").executeUpdate(); - session.createSQLQuery("CREATE TABLE children_AUD ( REV " + getDialect().getTypeName(Types.INTEGER) + " NOT NULL" + - ", REVEND " + getDialect().getTypeName(Types.INTEGER) + - ", REVTYPE " + getDialect().getTypeName(Types.TINYINT) + - ", parent_id " + getDialect().getTypeName(Types.INTEGER) + - ", child1_id " + getDialect().getTypeName(Types.INTEGER) + " NULL" + - ", child2_id " + getDialect().getTypeName(Types.INTEGER) + " NULL )").executeUpdate(); - em.getTransaction().commit(); - em.clear(); + // We need first to modify the columns in the middle (join table) to allow null values. Hbm2ddl doesn't seem + // to allow this. + em.getTransaction().begin(); + Session session = (Session) em.getDelegate(); + session.createSQLQuery( "DROP TABLE children" ).executeUpdate(); + session.createSQLQuery( + "CREATE TABLE children ( parent_id " + getDialect().getTypeName( Types.INTEGER ) + + ", child1_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL" + + ", child2_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL )" + ).executeUpdate(); + session.createSQLQuery( "DROP TABLE children_AUD" ).executeUpdate(); + session.createSQLQuery( + "CREATE TABLE children_AUD ( REV " + getDialect().getTypeName( Types.INTEGER ) + " NOT NULL" + + ", REVEND " + getDialect().getTypeName( Types.INTEGER ) + + ", REVTYPE " + getDialect().getTypeName( Types.TINYINT ) + + ", parent_id " + getDialect().getTypeName( Types.INTEGER ) + + ", child1_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL" + + ", child2_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL )" + ).executeUpdate(); + em.getTransaction().commit(); + em.clear(); - ParentEntity p1 = new ParentEntity("parent_1"); - ParentEntity p2 = new ParentEntity("parent_2"); + ParentEntity p1 = new ParentEntity( "parent_1" ); + ParentEntity p2 = new ParentEntity( "parent_2" ); - Child1Entity c1_1 = new Child1Entity("child1_1"); - Child1Entity c1_2 = new Child1Entity("child1_2"); + Child1Entity c1_1 = new Child1Entity( "child1_1" ); + Child1Entity c1_2 = new Child1Entity( "child1_2" ); - Child2Entity c2_1 = new Child2Entity("child2_1"); - Child2Entity c2_2 = new Child2Entity("child2_2"); + Child2Entity c2_1 = new Child2Entity( "child2_1" ); + Child2Entity c2_2 = new Child2Entity( "child2_2" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(p1); - em.persist(p2); - em.persist(c1_1); - em.persist(c1_2); - em.persist(c2_1); - em.persist(c2_2); + em.persist( p1 ); + em.persist( p2 ); + em.persist( c1_1 ); + em.persist( c1_2 ); + em.persist( c2_1 ); + em.persist( c2_2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 2 - (p1: c1_1, p2: c2_1) + // Revision 2 - (p1: c1_1, p2: c2_1) - em.getTransaction().begin(); + em.getTransaction().begin(); - p1 = em.find(ParentEntity.class, p1.getId()); - p2 = em.find(ParentEntity.class, p2.getId()); - c1_1 = em.find(Child1Entity.class, c1_1.getId()); - c2_1 = em.find(Child2Entity.class, c2_1.getId()); + p1 = em.find( ParentEntity.class, p1.getId() ); + p2 = em.find( ParentEntity.class, p2.getId() ); + c1_1 = em.find( Child1Entity.class, c1_1.getId() ); + c2_1 = em.find( Child2Entity.class, c2_1.getId() ); - p1.getChildren1().add(c1_1); - p2.getChildren2().add(c2_1); + p1.getChildren1().add( c1_1 ); + p2.getChildren2().add( c2_1 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 3 - (p1: c1_1, c1_2, c2_2, p2: c1_1, c2_1) - em.getTransaction().begin(); + // Revision 3 - (p1: c1_1, c1_2, c2_2, p2: c1_1, c2_1) + em.getTransaction().begin(); - p1 = em.find(ParentEntity.class, p1.getId()); - p2 = em.find(ParentEntity.class, p2.getId()); - c1_1 = em.find(Child1Entity.class, c1_1.getId()); - c1_2 = em.find(Child1Entity.class, c1_2.getId()); - c2_2 = em.find(Child2Entity.class, c2_2.getId()); + p1 = em.find( ParentEntity.class, p1.getId() ); + p2 = em.find( ParentEntity.class, p2.getId() ); + c1_1 = em.find( Child1Entity.class, c1_1.getId() ); + c1_2 = em.find( Child1Entity.class, c1_2.getId() ); + c2_2 = em.find( Child2Entity.class, c2_2.getId() ); - p1.getChildren1().add(c1_2); - p1.getChildren2().add(c2_2); + p1.getChildren1().add( c1_2 ); + p1.getChildren2().add( c2_2 ); - p2.getChildren1().add(c1_1); + p2.getChildren1().add( c1_1 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 4 - (p1: c1_2, c2_2, p2: c1_1, c2_1, c2_2) - em.getTransaction().begin(); + // Revision 4 - (p1: c1_2, c2_2, p2: c1_1, c2_1, c2_2) + em.getTransaction().begin(); - p1 = em.find(ParentEntity.class, p1.getId()); - p2 = em.find(ParentEntity.class, p2.getId()); - c1_1 = em.find(Child1Entity.class, c1_1.getId()); - c2_2 = em.find(Child2Entity.class, c2_2.getId()); + p1 = em.find( ParentEntity.class, p1.getId() ); + p2 = em.find( ParentEntity.class, p2.getId() ); + c1_1 = em.find( Child1Entity.class, c1_1.getId() ); + c2_2 = em.find( Child2Entity.class, c2_2.getId() ); - p1.getChildren1().remove(c1_1); - p2.getChildren2().add(c2_2); + p1.getChildren1().remove( c1_1 ); + p2.getChildren2().add( c2_2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 5 - (p1: c2_2, p2: c1_1, c2_1) - em.getTransaction().begin(); + // Revision 5 - (p1: c2_2, p2: c1_1, c2_1) + em.getTransaction().begin(); - p1 = em.find(ParentEntity.class, p1.getId()); - p2 = em.find(ParentEntity.class, p2.getId()); - c1_2 = em.find(Child1Entity.class, c1_2.getId()); - c2_2 = em.find(Child2Entity.class, c2_2.getId()); + p1 = em.find( ParentEntity.class, p1.getId() ); + p2 = em.find( ParentEntity.class, p2.getId() ); + c1_2 = em.find( Child1Entity.class, c1_2.getId() ); + c2_2 = em.find( Child2Entity.class, c2_2.getId() ); - c2_2.getParents().remove(p2); - c1_2.getParents().remove(p1); + c2_2.getParents().remove( p2 ); + c1_2.getParents().remove( p1 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // + // - p1_id = p1.getId(); - p2_id = p2.getId(); - c1_1_id = c1_1.getId(); - c1_2_id = c1_2.getId(); - c2_1_id = c2_1.getId(); - c2_2_id = c2_2.getId(); - } + p1_id = p1.getId(); + p2_id = p2.getId(); + c1_1_id = c1_1.getId(); + c1_2_id = c1_2.getId(); + c2_1_id = c2_1.getId(); + c2_2_id = c2_2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3, 4).equals(getAuditReader().getRevisions(ParentEntity.class, p1_id)); - assert Arrays.asList(1, 2, 3, 4).equals(getAuditReader().getRevisions(ParentEntity.class, p2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3, 4 ).equals( getAuditReader().getRevisions( ParentEntity.class, p1_id ) ); + assert Arrays.asList( 1, 2, 3, 4 ).equals( getAuditReader().getRevisions( ParentEntity.class, p2_id ) ); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(Child1Entity.class, c1_1_id)); - assert Arrays.asList(1, 5).equals(getAuditReader().getRevisions(Child1Entity.class, c1_2_id)); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( Child1Entity.class, c1_1_id ) ); + assert Arrays.asList( 1, 5 ).equals( getAuditReader().getRevisions( Child1Entity.class, c1_2_id ) ); - Assert.assertEquals(Arrays.asList(1), getAuditReader().getRevisions(Child2Entity.class, c2_1_id)); - Assert.assertEquals(Arrays.asList(1, 5), getAuditReader().getRevisions(Child2Entity.class, c2_2_id)); - } + Assert.assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( Child2Entity.class, c2_1_id ) ); + Assert.assertEquals( Arrays.asList( 1, 5 ), getAuditReader().getRevisions( Child2Entity.class, c2_2_id ) ); + } - @Test - public void testHistoryOfParent1() { - Child1Entity c1_1 = getEntityManager().find(Child1Entity.class, c1_1_id); - Child1Entity c1_2 = getEntityManager().find(Child1Entity.class, c1_2_id); - Child2Entity c2_2 = getEntityManager().find(Child2Entity.class, c2_2_id); + @Test + public void testHistoryOfParent1() { + Child1Entity c1_1 = getEntityManager().find( Child1Entity.class, c1_1_id ); + Child1Entity c1_2 = getEntityManager().find( Child1Entity.class, c1_2_id ); + Child2Entity c2_2 = getEntityManager().find( Child2Entity.class, c2_2_id ); - ParentEntity rev1 = getAuditReader().find(ParentEntity.class, p1_id, 1); - ParentEntity rev2 = getAuditReader().find(ParentEntity.class, p1_id, 2); - ParentEntity rev3 = getAuditReader().find(ParentEntity.class, p1_id, 3); - ParentEntity rev4 = getAuditReader().find(ParentEntity.class, p1_id, 4); - ParentEntity rev5 = getAuditReader().find(ParentEntity.class, p1_id, 5); + ParentEntity rev1 = getAuditReader().find( ParentEntity.class, p1_id, 1 ); + ParentEntity rev2 = getAuditReader().find( ParentEntity.class, p1_id, 2 ); + ParentEntity rev3 = getAuditReader().find( ParentEntity.class, p1_id, 3 ); + ParentEntity rev4 = getAuditReader().find( ParentEntity.class, p1_id, 4 ); + ParentEntity rev5 = getAuditReader().find( ParentEntity.class, p1_id, 5 ); - assert TestTools.checkList(rev1.getChildren1()); - assert TestTools.checkList(rev2.getChildren1(), c1_1); - assert TestTools.checkList(rev3.getChildren1(), c1_1, c1_2); - assert TestTools.checkList(rev4.getChildren1(), c1_2); - assert TestTools.checkList(rev5.getChildren1()); + assert TestTools.checkList( rev1.getChildren1() ); + assert TestTools.checkList( rev2.getChildren1(), c1_1 ); + assert TestTools.checkList( rev3.getChildren1(), c1_1, c1_2 ); + assert TestTools.checkList( rev4.getChildren1(), c1_2 ); + assert TestTools.checkList( rev5.getChildren1() ); - assert TestTools.checkList(rev1.getChildren2()); - assert TestTools.checkList(rev2.getChildren2()); - assert TestTools.checkList(rev3.getChildren2(), c2_2); - assert TestTools.checkList(rev4.getChildren2(), c2_2); - assert TestTools.checkList(rev5.getChildren2(), c2_2); - } + assert TestTools.checkList( rev1.getChildren2() ); + assert TestTools.checkList( rev2.getChildren2() ); + assert TestTools.checkList( rev3.getChildren2(), c2_2 ); + assert TestTools.checkList( rev4.getChildren2(), c2_2 ); + assert TestTools.checkList( rev5.getChildren2(), c2_2 ); + } - @Test - public void testHistoryOfParent2() { - Child1Entity c1_1 = getEntityManager().find(Child1Entity.class, c1_1_id); - Child2Entity c2_1 = getEntityManager().find(Child2Entity.class, c2_1_id); - Child2Entity c2_2 = getEntityManager().find(Child2Entity.class, c2_2_id); + @Test + public void testHistoryOfParent2() { + Child1Entity c1_1 = getEntityManager().find( Child1Entity.class, c1_1_id ); + Child2Entity c2_1 = getEntityManager().find( Child2Entity.class, c2_1_id ); + Child2Entity c2_2 = getEntityManager().find( Child2Entity.class, c2_2_id ); - ParentEntity rev1 = getAuditReader().find(ParentEntity.class, p2_id, 1); - ParentEntity rev2 = getAuditReader().find(ParentEntity.class, p2_id, 2); - ParentEntity rev3 = getAuditReader().find(ParentEntity.class, p2_id, 3); - ParentEntity rev4 = getAuditReader().find(ParentEntity.class, p2_id, 4); - ParentEntity rev5 = getAuditReader().find(ParentEntity.class, p2_id, 5); + ParentEntity rev1 = getAuditReader().find( ParentEntity.class, p2_id, 1 ); + ParentEntity rev2 = getAuditReader().find( ParentEntity.class, p2_id, 2 ); + ParentEntity rev3 = getAuditReader().find( ParentEntity.class, p2_id, 3 ); + ParentEntity rev4 = getAuditReader().find( ParentEntity.class, p2_id, 4 ); + ParentEntity rev5 = getAuditReader().find( ParentEntity.class, p2_id, 5 ); - assert TestTools.checkList(rev1.getChildren1()); - assert TestTools.checkList(rev2.getChildren1()); - assert TestTools.checkList(rev3.getChildren1(), c1_1); - assert TestTools.checkList(rev4.getChildren1(), c1_1); - assert TestTools.checkList(rev5.getChildren1(), c1_1); + assert TestTools.checkList( rev1.getChildren1() ); + assert TestTools.checkList( rev2.getChildren1() ); + assert TestTools.checkList( rev3.getChildren1(), c1_1 ); + assert TestTools.checkList( rev4.getChildren1(), c1_1 ); + assert TestTools.checkList( rev5.getChildren1(), c1_1 ); - assert TestTools.checkList(rev1.getChildren2()); - assert TestTools.checkList(rev2.getChildren2(), c2_1); - assert TestTools.checkList(rev3.getChildren2(), c2_1); - assert TestTools.checkList(rev4.getChildren2(), c2_1, c2_2); - assert TestTools.checkList(rev5.getChildren2(), c2_1); - } + assert TestTools.checkList( rev1.getChildren2() ); + assert TestTools.checkList( rev2.getChildren2(), c2_1 ); + assert TestTools.checkList( rev3.getChildren2(), c2_1 ); + assert TestTools.checkList( rev4.getChildren2(), c2_1, c2_2 ); + assert TestTools.checkList( rev5.getChildren2(), c2_1 ); + } - @Test - public void testHistoryOfChild1_1() { - ParentEntity p1 = getEntityManager().find(ParentEntity.class, p1_id); - ParentEntity p2 = getEntityManager().find(ParentEntity.class, p2_id); + @Test + public void testHistoryOfChild1_1() { + ParentEntity p1 = getEntityManager().find( ParentEntity.class, p1_id ); + ParentEntity p2 = getEntityManager().find( ParentEntity.class, p2_id ); - Child1Entity rev1 = getAuditReader().find(Child1Entity.class, c1_1_id, 1); - Child1Entity rev2 = getAuditReader().find(Child1Entity.class, c1_1_id, 2); - Child1Entity rev3 = getAuditReader().find(Child1Entity.class, c1_1_id, 3); - Child1Entity rev4 = getAuditReader().find(Child1Entity.class, c1_1_id, 4); - Child1Entity rev5 = getAuditReader().find(Child1Entity.class, c1_1_id, 5); + Child1Entity rev1 = getAuditReader().find( Child1Entity.class, c1_1_id, 1 ); + Child1Entity rev2 = getAuditReader().find( Child1Entity.class, c1_1_id, 2 ); + Child1Entity rev3 = getAuditReader().find( Child1Entity.class, c1_1_id, 3 ); + Child1Entity rev4 = getAuditReader().find( Child1Entity.class, c1_1_id, 4 ); + Child1Entity rev5 = getAuditReader().find( Child1Entity.class, c1_1_id, 5 ); - assert TestTools.checkList(rev1.getParents()); - assert TestTools.checkList(rev2.getParents(), p1); - assert TestTools.checkList(rev3.getParents(), p1, p2); - assert TestTools.checkList(rev4.getParents(), p2); - assert TestTools.checkList(rev5.getParents(), p2); - } + assert TestTools.checkList( rev1.getParents() ); + assert TestTools.checkList( rev2.getParents(), p1 ); + assert TestTools.checkList( rev3.getParents(), p1, p2 ); + assert TestTools.checkList( rev4.getParents(), p2 ); + assert TestTools.checkList( rev5.getParents(), p2 ); + } - // TODO: was disabled? - @Test - public void testHistoryOfChild1_2() { - ParentEntity p1 = getEntityManager().find(ParentEntity.class, p1_id); + // TODO: was disabled? + @Test + public void testHistoryOfChild1_2() { + ParentEntity p1 = getEntityManager().find( ParentEntity.class, p1_id ); - Child1Entity rev1 = getAuditReader().find(Child1Entity.class, c1_2_id, 1); - Child1Entity rev2 = getAuditReader().find(Child1Entity.class, c1_2_id, 2); - Child1Entity rev3 = getAuditReader().find(Child1Entity.class, c1_2_id, 3); - Child1Entity rev4 = getAuditReader().find(Child1Entity.class, c1_2_id, 4); - Child1Entity rev5 = getAuditReader().find(Child1Entity.class, c1_2_id, 5); + Child1Entity rev1 = getAuditReader().find( Child1Entity.class, c1_2_id, 1 ); + Child1Entity rev2 = getAuditReader().find( Child1Entity.class, c1_2_id, 2 ); + Child1Entity rev3 = getAuditReader().find( Child1Entity.class, c1_2_id, 3 ); + Child1Entity rev4 = getAuditReader().find( Child1Entity.class, c1_2_id, 4 ); + Child1Entity rev5 = getAuditReader().find( Child1Entity.class, c1_2_id, 5 ); - assert TestTools.checkList(rev1.getParents()); - assert TestTools.checkList(rev2.getParents()); - assert TestTools.checkList(rev3.getParents(), p1); - assert TestTools.checkList(rev4.getParents(), p1); - assert TestTools.checkList(rev5.getParents()); - } + assert TestTools.checkList( rev1.getParents() ); + assert TestTools.checkList( rev2.getParents() ); + assert TestTools.checkList( rev3.getParents(), p1 ); + assert TestTools.checkList( rev4.getParents(), p1 ); + assert TestTools.checkList( rev5.getParents() ); + } - @Test - public void testHistoryOfChild2_1() { - ParentEntity p2 = getEntityManager().find(ParentEntity.class, p2_id); + @Test + public void testHistoryOfChild2_1() { + ParentEntity p2 = getEntityManager().find( ParentEntity.class, p2_id ); - Child2Entity rev1 = getAuditReader().find(Child2Entity.class, c2_1_id, 1); - Child2Entity rev2 = getAuditReader().find(Child2Entity.class, c2_1_id, 2); - Child2Entity rev3 = getAuditReader().find(Child2Entity.class, c2_1_id, 3); - Child2Entity rev4 = getAuditReader().find(Child2Entity.class, c2_1_id, 4); - Child2Entity rev5 = getAuditReader().find(Child2Entity.class, c2_1_id, 5); + Child2Entity rev1 = getAuditReader().find( Child2Entity.class, c2_1_id, 1 ); + Child2Entity rev2 = getAuditReader().find( Child2Entity.class, c2_1_id, 2 ); + Child2Entity rev3 = getAuditReader().find( Child2Entity.class, c2_1_id, 3 ); + Child2Entity rev4 = getAuditReader().find( Child2Entity.class, c2_1_id, 4 ); + Child2Entity rev5 = getAuditReader().find( Child2Entity.class, c2_1_id, 5 ); - assert TestTools.checkList(rev1.getParents()); - assert TestTools.checkList(rev2.getParents(), p2); - assert TestTools.checkList(rev3.getParents(), p2); - assert TestTools.checkList(rev4.getParents(), p2); - assert TestTools.checkList(rev5.getParents(), p2); - } + assert TestTools.checkList( rev1.getParents() ); + assert TestTools.checkList( rev2.getParents(), p2 ); + assert TestTools.checkList( rev3.getParents(), p2 ); + assert TestTools.checkList( rev4.getParents(), p2 ); + assert TestTools.checkList( rev5.getParents(), p2 ); + } - @Test - public void testHistoryOfChild2_2() { - ParentEntity p1 = getEntityManager().find(ParentEntity.class, p1_id); - ParentEntity p2 = getEntityManager().find(ParentEntity.class, p2_id); + @Test + public void testHistoryOfChild2_2() { + ParentEntity p1 = getEntityManager().find( ParentEntity.class, p1_id ); + ParentEntity p2 = getEntityManager().find( ParentEntity.class, p2_id ); - Child2Entity rev1 = getAuditReader().find(Child2Entity.class, c2_2_id, 1); - Child2Entity rev2 = getAuditReader().find(Child2Entity.class, c2_2_id, 2); - Child2Entity rev3 = getAuditReader().find(Child2Entity.class, c2_2_id, 3); - Child2Entity rev4 = getAuditReader().find(Child2Entity.class, c2_2_id, 4); - Child2Entity rev5 = getAuditReader().find(Child2Entity.class, c2_2_id, 5); + Child2Entity rev1 = getAuditReader().find( Child2Entity.class, c2_2_id, 1 ); + Child2Entity rev2 = getAuditReader().find( Child2Entity.class, c2_2_id, 2 ); + Child2Entity rev3 = getAuditReader().find( Child2Entity.class, c2_2_id, 3 ); + Child2Entity rev4 = getAuditReader().find( Child2Entity.class, c2_2_id, 4 ); + Child2Entity rev5 = getAuditReader().find( Child2Entity.class, c2_2_id, 5 ); - assert TestTools.checkList(rev1.getParents()); - assert TestTools.checkList(rev2.getParents()); - assert TestTools.checkList(rev3.getParents(), p1); - assert TestTools.checkList(rev4.getParents(), p1, p2); - assert TestTools.checkList(rev5.getParents(), p1); - } + assert TestTools.checkList( rev1.getParents() ); + assert TestTools.checkList( rev2.getParents() ); + assert TestTools.checkList( rev3.getParents(), p1 ); + assert TestTools.checkList( rev4.getParents(), p1, p2 ); + assert TestTools.checkList( rev5.getParents(), p1 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/ternary/TernaryMap.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/ternary/TernaryMap.java index 4fcb435dfb..f527070643 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/ternary/TernaryMap.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/ternary/TernaryMap.java @@ -23,11 +23,8 @@ */ package org.hibernate.envers.test.integration.manytomany.ternary; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -35,166 +32,169 @@ import org.hibernate.envers.test.entities.IntTestPrivSeqEntity; import org.hibernate.envers.test.entities.StrTestPrivSeqEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Assert; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class TernaryMap extends BaseEnversJPAFunctionalTestCase { - private Integer str1_id; - private Integer str2_id; + private Integer str1_id; + private Integer str2_id; - private Integer int1_id; - private Integer int2_id; + private Integer int1_id; + private Integer int2_id; - private Integer map1_id; - private Integer map2_id; + private Integer map1_id; + private Integer map2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { TernaryMapEntity.class, StrTestPrivSeqEntity.class, IntTestPrivSeqEntity.class }; - } + return new Class[] {TernaryMapEntity.class, StrTestPrivSeqEntity.class, IntTestPrivSeqEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - StrTestPrivSeqEntity str1 = new StrTestPrivSeqEntity("a"); - StrTestPrivSeqEntity str2 = new StrTestPrivSeqEntity("b"); + StrTestPrivSeqEntity str1 = new StrTestPrivSeqEntity( "a" ); + StrTestPrivSeqEntity str2 = new StrTestPrivSeqEntity( "b" ); - IntTestPrivSeqEntity int1 = new IntTestPrivSeqEntity(1); - IntTestPrivSeqEntity int2 = new IntTestPrivSeqEntity(2); + IntTestPrivSeqEntity int1 = new IntTestPrivSeqEntity( 1 ); + IntTestPrivSeqEntity int2 = new IntTestPrivSeqEntity( 2 ); - TernaryMapEntity map1 = new TernaryMapEntity(); - TernaryMapEntity map2 = new TernaryMapEntity(); + TernaryMapEntity map1 = new TernaryMapEntity(); + TernaryMapEntity map2 = new TernaryMapEntity(); - // Revision 1 (map1: initialy one mapping int1 -> str1, map2: empty) - em.getTransaction().begin(); + // Revision 1 (map1: initialy one mapping int1 -> str1, map2: empty) + em.getTransaction().begin(); - em.persist(str1); - em.persist(str2); - em.persist(int1); - em.persist(int2); + em.persist( str1 ); + em.persist( str2 ); + em.persist( int1 ); + em.persist( int2 ); - map1.getMap().put(int1, str1); + map1.getMap().put( int1, str1 ); - em.persist(map1); - em.persist(map2); + em.persist( map1 ); + em.persist( map2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (map1: replacing the mapping, map2: adding two mappings) + // Revision 2 (map1: replacing the mapping, map2: adding two mappings) - em.getTransaction().begin(); + em.getTransaction().begin(); - map1 = em.find(TernaryMapEntity.class, map1.getId()); - map2 = em.find(TernaryMapEntity.class, map2.getId()); + map1 = em.find( TernaryMapEntity.class, map1.getId() ); + map2 = em.find( TernaryMapEntity.class, map2.getId() ); - str1 = em.find(StrTestPrivSeqEntity.class, str1.getId()); - str2 = em.find(StrTestPrivSeqEntity.class, str2.getId()); + str1 = em.find( StrTestPrivSeqEntity.class, str1.getId() ); + str2 = em.find( StrTestPrivSeqEntity.class, str2.getId() ); - int1 = em.find(IntTestPrivSeqEntity.class, int1.getId()); - int2 = em.find(IntTestPrivSeqEntity.class, int2.getId()); + int1 = em.find( IntTestPrivSeqEntity.class, int1.getId() ); + int2 = em.find( IntTestPrivSeqEntity.class, int2.getId() ); - map1.getMap().put(int1, str2); + map1.getMap().put( int1, str2 ); - map2.getMap().put(int1, str1); - map2.getMap().put(int2, str1); + map2.getMap().put( int1, str1 ); + map2.getMap().put( int2, str1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 (map1: removing a non-existing mapping, adding an existing mapping - no changes, map2: removing a mapping) - em.getTransaction().begin(); + // Revision 3 (map1: removing a non-existing mapping, adding an existing mapping - no changes, map2: removing a mapping) + em.getTransaction().begin(); - map1 = em.find(TernaryMapEntity.class, map1.getId()); - map2 = em.find(TernaryMapEntity.class, map2.getId()); + map1 = em.find( TernaryMapEntity.class, map1.getId() ); + map2 = em.find( TernaryMapEntity.class, map2.getId() ); - str2 = em.find(StrTestPrivSeqEntity.class, str2.getId()); + str2 = em.find( StrTestPrivSeqEntity.class, str2.getId() ); - int1 = em.find(IntTestPrivSeqEntity.class, int1.getId()); - int2 = em.find(IntTestPrivSeqEntity.class, int2.getId()); + int1 = em.find( IntTestPrivSeqEntity.class, int1.getId() ); + int2 = em.find( IntTestPrivSeqEntity.class, int2.getId() ); - map1.getMap().remove(int2); - map1.getMap().put(int1, str2); + map1.getMap().remove( int2 ); + map1.getMap().put( int1, str2 ); - map2.getMap().remove(int1); + map2.getMap().remove( int1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 (map1: adding a mapping, map2: adding a mapping) - em.getTransaction().begin(); + // Revision 4 (map1: adding a mapping, map2: adding a mapping) + em.getTransaction().begin(); - map1 = em.find(TernaryMapEntity.class, map1.getId()); - map2 = em.find(TernaryMapEntity.class, map2.getId()); + map1 = em.find( TernaryMapEntity.class, map1.getId() ); + map2 = em.find( TernaryMapEntity.class, map2.getId() ); - str2 = em.find(StrTestPrivSeqEntity.class, str2.getId()); + str2 = em.find( StrTestPrivSeqEntity.class, str2.getId() ); - int1 = em.find(IntTestPrivSeqEntity.class, int1.getId()); - int2 = em.find(IntTestPrivSeqEntity.class, int2.getId()); + int1 = em.find( IntTestPrivSeqEntity.class, int1.getId() ); + int2 = em.find( IntTestPrivSeqEntity.class, int2.getId() ); - map1.getMap().put(int2, str2); + map1.getMap().put( int2, str2 ); - map2.getMap().put(int1, str2); + map2.getMap().put( int1, str2 ); - em.getTransaction().commit(); - // + em.getTransaction().commit(); + // - map1_id = map1.getId(); - map2_id = map2.getId(); + map1_id = map1.getId(); + map2_id = map2.getId(); - str1_id = str1.getId(); - str2_id = str2.getId(); + str1_id = str1.getId(); + str2_id = str2.getId(); - int1_id = int1.getId(); - int2_id = int2.getId(); - } + int1_id = int1.getId(); + int2_id = int2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 4).equals(getAuditReader().getRevisions(TernaryMapEntity.class, map1_id)); - assert Arrays.asList(1, 2, 3, 4).equals(getAuditReader().getRevisions(TernaryMapEntity.class, map2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 4 ).equals( getAuditReader().getRevisions( TernaryMapEntity.class, map1_id ) ); + assert Arrays.asList( 1, 2, 3, 4 ).equals( getAuditReader().getRevisions( TernaryMapEntity.class, map2_id ) ); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestPrivSeqEntity.class, str1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestPrivSeqEntity.class, str2_id)); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestPrivSeqEntity.class, str1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestPrivSeqEntity.class, str2_id ) ); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(IntTestPrivSeqEntity.class, int1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(IntTestPrivSeqEntity.class, int2_id)); - } + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( IntTestPrivSeqEntity.class, int1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( IntTestPrivSeqEntity.class, int2_id ) ); + } - @Test - public void testHistoryOfMap1() { - StrTestPrivSeqEntity str1 = getEntityManager().find(StrTestPrivSeqEntity.class, str1_id); - StrTestPrivSeqEntity str2 = getEntityManager().find(StrTestPrivSeqEntity.class, str2_id); + @Test + public void testHistoryOfMap1() { + StrTestPrivSeqEntity str1 = getEntityManager().find( StrTestPrivSeqEntity.class, str1_id ); + StrTestPrivSeqEntity str2 = getEntityManager().find( StrTestPrivSeqEntity.class, str2_id ); - IntTestPrivSeqEntity int1 = getEntityManager().find(IntTestPrivSeqEntity.class, int1_id); - IntTestPrivSeqEntity int2 = getEntityManager().find(IntTestPrivSeqEntity.class, int2_id); + IntTestPrivSeqEntity int1 = getEntityManager().find( IntTestPrivSeqEntity.class, int1_id ); + IntTestPrivSeqEntity int2 = getEntityManager().find( IntTestPrivSeqEntity.class, int2_id ); - TernaryMapEntity rev1 = getAuditReader().find(TernaryMapEntity.class, map1_id, 1); - TernaryMapEntity rev2 = getAuditReader().find(TernaryMapEntity.class, map1_id, 2); - TernaryMapEntity rev3 = getAuditReader().find(TernaryMapEntity.class, map1_id, 3); - TernaryMapEntity rev4 = getAuditReader().find(TernaryMapEntity.class, map1_id, 4); + TernaryMapEntity rev1 = getAuditReader().find( TernaryMapEntity.class, map1_id, 1 ); + TernaryMapEntity rev2 = getAuditReader().find( TernaryMapEntity.class, map1_id, 2 ); + TernaryMapEntity rev3 = getAuditReader().find( TernaryMapEntity.class, map1_id, 3 ); + TernaryMapEntity rev4 = getAuditReader().find( TernaryMapEntity.class, map1_id, 4 ); - Assert.assertEquals(TestTools.makeMap(int1, str1), rev1.getMap()); - Assert.assertEquals(TestTools.makeMap(int1, str2), rev2.getMap()); - Assert.assertEquals(TestTools.makeMap(int1, str2), rev3.getMap()); - Assert.assertEquals(TestTools.makeMap(int1, str2, int2, str2), rev4.getMap()); - } + Assert.assertEquals( TestTools.makeMap( int1, str1 ), rev1.getMap() ); + Assert.assertEquals( TestTools.makeMap( int1, str2 ), rev2.getMap() ); + Assert.assertEquals( TestTools.makeMap( int1, str2 ), rev3.getMap() ); + Assert.assertEquals( TestTools.makeMap( int1, str2, int2, str2 ), rev4.getMap() ); + } - @Test - public void testHistoryOfMap2() { - StrTestPrivSeqEntity str1 = getEntityManager().find(StrTestPrivSeqEntity.class, str1_id); - StrTestPrivSeqEntity str2 = getEntityManager().find(StrTestPrivSeqEntity.class, str2_id); + @Test + public void testHistoryOfMap2() { + StrTestPrivSeqEntity str1 = getEntityManager().find( StrTestPrivSeqEntity.class, str1_id ); + StrTestPrivSeqEntity str2 = getEntityManager().find( StrTestPrivSeqEntity.class, str2_id ); - IntTestPrivSeqEntity int1 = getEntityManager().find(IntTestPrivSeqEntity.class, int1_id); - IntTestPrivSeqEntity int2 = getEntityManager().find(IntTestPrivSeqEntity.class, int2_id); + IntTestPrivSeqEntity int1 = getEntityManager().find( IntTestPrivSeqEntity.class, int1_id ); + IntTestPrivSeqEntity int2 = getEntityManager().find( IntTestPrivSeqEntity.class, int2_id ); - TernaryMapEntity rev1 = getAuditReader().find(TernaryMapEntity.class, map2_id, 1); - TernaryMapEntity rev2 = getAuditReader().find(TernaryMapEntity.class, map2_id, 2); - TernaryMapEntity rev3 = getAuditReader().find(TernaryMapEntity.class, map2_id, 3); - TernaryMapEntity rev4 = getAuditReader().find(TernaryMapEntity.class, map2_id, 4); + TernaryMapEntity rev1 = getAuditReader().find( TernaryMapEntity.class, map2_id, 1 ); + TernaryMapEntity rev2 = getAuditReader().find( TernaryMapEntity.class, map2_id, 2 ); + TernaryMapEntity rev3 = getAuditReader().find( TernaryMapEntity.class, map2_id, 3 ); + TernaryMapEntity rev4 = getAuditReader().find( TernaryMapEntity.class, map2_id, 4 ); - assert rev1.getMap().equals(TestTools.makeMap()); - assert rev2.getMap().equals(TestTools.makeMap(int1, str1, int2, str1)); - assert rev3.getMap().equals(TestTools.makeMap(int2, str1)); - assert rev4.getMap().equals(TestTools.makeMap(int1, str2, int2, str1)); - } + assert rev1.getMap().equals( TestTools.makeMap() ); + assert rev2.getMap().equals( TestTools.makeMap( int1, str1, int2, str1 ) ); + assert rev3.getMap().equals( TestTools.makeMap( int2, str1 ) ); + assert rev4.getMap().equals( TestTools.makeMap( int1, str2, int2, str1 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/ternary/TernaryMapEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/ternary/TernaryMapEntity.java index 24a7789b5d..3313be249a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/ternary/TernaryMapEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/ternary/TernaryMapEntity.java @@ -22,12 +22,13 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.manytomany.ternary; -import java.util.HashMap; -import java.util.Map; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; +import java.util.HashMap; +import java.util.Map; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.IntTestPrivSeqEntity; @@ -38,51 +39,57 @@ import org.hibernate.envers.test.entities.StrTestPrivSeqEntity; */ @Entity public class TernaryMapEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - @ManyToMany - @javax.persistence.MapKeyJoinColumn - private Map map; + @Audited + @ManyToMany + @javax.persistence.MapKeyJoinColumn + private Map map; - public TernaryMapEntity() { - map = new HashMap(); - } + public TernaryMapEntity() { + map = new HashMap(); + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Map getMap() { - return map; - } + public Map getMap() { + return map; + } - public void setMap(Map map) { - this.map = map; - } + public void setMap(Map map) { + this.map = map; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof TernaryMapEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof TernaryMapEntity) ) { + return false; + } - TernaryMapEntity that = (TernaryMapEntity) o; + TernaryMapEntity that = (TernaryMapEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - return (id != null ? id.hashCode() : 0); - } + public int hashCode() { + return (id != null ? id.hashCode() : 0); + } - public String toString() { - return "TME(id = " + id + ", map = " + map + ")"; - } + public String toString() { + return "TME(id = " + id + ", map = " + map + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/ternary/TernaryMapFlush.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/ternary/TernaryMapFlush.java index 0a7fb128c2..e072ec36b7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/ternary/TernaryMapFlush.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/ternary/TernaryMapFlush.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.manytomany.ternary; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.HashMap; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -35,112 +33,114 @@ import org.hibernate.envers.test.entities.IntTestPrivSeqEntity; import org.hibernate.envers.test.entities.StrTestPrivSeqEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + import static org.junit.Assert.assertEquals; /** * @author Adam Warski (adam at warski dot org) */ public class TernaryMapFlush extends BaseEnversJPAFunctionalTestCase { - private Integer str1_id; - private Integer str2_id; - private Integer int1_id; - private Integer int2_id; - private Integer map1_id; + private Integer str1_id; + private Integer str2_id; + private Integer int1_id; + private Integer int2_id; + private Integer map1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { TernaryMapEntity.class, StrTestPrivSeqEntity.class, IntTestPrivSeqEntity.class }; - } + return new Class[] {TernaryMapEntity.class, StrTestPrivSeqEntity.class, IntTestPrivSeqEntity.class}; + } - @Test - @Priority(10) - public void createData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void createData() { + EntityManager em = getEntityManager(); - StrTestPrivSeqEntity str1 = new StrTestPrivSeqEntity("a"); - StrTestPrivSeqEntity str2 = new StrTestPrivSeqEntity("b"); - IntTestPrivSeqEntity int1 = new IntTestPrivSeqEntity(1); - IntTestPrivSeqEntity int2 = new IntTestPrivSeqEntity(2); - TernaryMapEntity map1 = new TernaryMapEntity(); + StrTestPrivSeqEntity str1 = new StrTestPrivSeqEntity( "a" ); + StrTestPrivSeqEntity str2 = new StrTestPrivSeqEntity( "b" ); + IntTestPrivSeqEntity int1 = new IntTestPrivSeqEntity( 1 ); + IntTestPrivSeqEntity int2 = new IntTestPrivSeqEntity( 2 ); + TernaryMapEntity map1 = new TernaryMapEntity(); - // Revision 1 (int1 -> str1) - em.getTransaction().begin(); + // Revision 1 (int1 -> str1) + em.getTransaction().begin(); - em.persist(str1); - em.persist(str2); - em.persist(int1); - em.persist(int2); + em.persist( str1 ); + em.persist( str2 ); + em.persist( int1 ); + em.persist( int2 ); - map1.getMap().put(int1, str1); + map1.getMap().put( int1, str1 ); - em.persist(map1); + em.persist( map1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (removing int1->str1, flushing, adding int1->str1 again and a new int2->str2 mapping to force a change) + // Revision 2 (removing int1->str1, flushing, adding int1->str1 again and a new int2->str2 mapping to force a change) - em.getTransaction().begin(); + em.getTransaction().begin(); - map1 = em.find(TernaryMapEntity.class, map1.getId()); - str1 = em.find(StrTestPrivSeqEntity.class, str1.getId()); - int1 = em.find(IntTestPrivSeqEntity.class, int1.getId()); + map1 = em.find( TernaryMapEntity.class, map1.getId() ); + str1 = em.find( StrTestPrivSeqEntity.class, str1.getId() ); + int1 = em.find( IntTestPrivSeqEntity.class, int1.getId() ); - map1.setMap(new HashMap()); - - em.flush(); + map1.setMap( new HashMap() ); - map1.getMap().put(int1, str1); - map1.getMap().put(int2, str2); + em.flush(); - em.getTransaction().commit(); + map1.getMap().put( int1, str1 ); + map1.getMap().put( int2, str2 ); - // Revision 3 (removing int1->str1, flushing, overwriting int2->str1) + em.getTransaction().commit(); - em.getTransaction().begin(); + // Revision 3 (removing int1->str1, flushing, overwriting int2->str1) - map1 = em.find(TernaryMapEntity.class, map1.getId()); - str1 = em.find(StrTestPrivSeqEntity.class, str1.getId()); - int1 = em.find(IntTestPrivSeqEntity.class, int1.getId()); + em.getTransaction().begin(); - map1.getMap().remove(int1); + map1 = em.find( TernaryMapEntity.class, map1.getId() ); + str1 = em.find( StrTestPrivSeqEntity.class, str1.getId() ); + int1 = em.find( IntTestPrivSeqEntity.class, int1.getId() ); - em.flush(); + map1.getMap().remove( int1 ); - map1.getMap().put(int2, str1); + em.flush(); - em.getTransaction().commit(); + map1.getMap().put( int2, str1 ); - // + em.getTransaction().commit(); - map1_id = map1.getId(); - str1_id = str1.getId(); - str2_id = str2.getId(); - int1_id = int1.getId(); - int2_id = int2.getId(); - } + // - @Test - public void testRevisionsCounts() { - assertEquals(Arrays.asList(1, 2, 3), getAuditReader().getRevisions(TernaryMapEntity.class, map1_id)); - assertEquals(Arrays.asList(1), getAuditReader().getRevisions(StrTestPrivSeqEntity.class, str1_id)); - assertEquals(Arrays.asList(1), getAuditReader().getRevisions(StrTestPrivSeqEntity.class, str2_id)); - assertEquals(Arrays.asList(1) ,getAuditReader().getRevisions(IntTestPrivSeqEntity.class, int1_id)); - assertEquals(Arrays.asList(1) ,getAuditReader().getRevisions(IntTestPrivSeqEntity.class, int2_id)); - } + map1_id = map1.getId(); + str1_id = str1.getId(); + str2_id = str2.getId(); + int1_id = int1.getId(); + int2_id = int2.getId(); + } - @Test - public void testHistoryOfMap1() { - StrTestPrivSeqEntity str1 = getEntityManager().find(StrTestPrivSeqEntity.class, str1_id); - StrTestPrivSeqEntity str2 = getEntityManager().find(StrTestPrivSeqEntity.class, str2_id); - IntTestPrivSeqEntity int1 = getEntityManager().find(IntTestPrivSeqEntity.class, int1_id); - IntTestPrivSeqEntity int2 = getEntityManager().find(IntTestPrivSeqEntity.class, int2_id); + @Test + public void testRevisionsCounts() { + assertEquals( Arrays.asList( 1, 2, 3 ), getAuditReader().getRevisions( TernaryMapEntity.class, map1_id ) ); + assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( StrTestPrivSeqEntity.class, str1_id ) ); + assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( StrTestPrivSeqEntity.class, str2_id ) ); + assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( IntTestPrivSeqEntity.class, int1_id ) ); + assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( IntTestPrivSeqEntity.class, int2_id ) ); + } - TernaryMapEntity rev1 = getAuditReader().find(TernaryMapEntity.class, map1_id, 1); - TernaryMapEntity rev2 = getAuditReader().find(TernaryMapEntity.class, map1_id, 2); - TernaryMapEntity rev3 = getAuditReader().find(TernaryMapEntity.class, map1_id, 3); + @Test + public void testHistoryOfMap1() { + StrTestPrivSeqEntity str1 = getEntityManager().find( StrTestPrivSeqEntity.class, str1_id ); + StrTestPrivSeqEntity str2 = getEntityManager().find( StrTestPrivSeqEntity.class, str2_id ); + IntTestPrivSeqEntity int1 = getEntityManager().find( IntTestPrivSeqEntity.class, int1_id ); + IntTestPrivSeqEntity int2 = getEntityManager().find( IntTestPrivSeqEntity.class, int2_id ); - assertEquals(rev1.getMap(), TestTools.makeMap(int1, str1)); - assertEquals(rev2.getMap(), TestTools.makeMap(int1, str1, int2, str2)); - assertEquals(rev3.getMap(), TestTools.makeMap(int2, str1)); - } + TernaryMapEntity rev1 = getAuditReader().find( TernaryMapEntity.class, map1_id, 1 ); + TernaryMapEntity rev2 = getAuditReader().find( TernaryMapEntity.class, map1_id, 2 ); + TernaryMapEntity rev3 = getAuditReader().find( TernaryMapEntity.class, map1_id, 3 ); + + assertEquals( rev1.getMap(), TestTools.makeMap( int1, str1 ) ); + assertEquals( rev2.getMap(), TestTools.makeMap( int1, str1, int2, str2 ) ); + assertEquals( rev3.getMap(), TestTools.makeMap( int2, str1 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/BasicUniList.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/BasicUniList.java index 31971c684f..04654084bc 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/BasicUniList.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/BasicUniList.java @@ -23,12 +23,10 @@ */ package org.hibernate.envers.test.integration.manytomany.unidirectional; +import javax.persistence.EntityManager; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -36,142 +34,144 @@ import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.manytomany.unidirectional.ListUniEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BasicUniList extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ListUniEntity.class, StrTestEntity.class }; - } + return new Class[] {ListUniEntity.class, StrTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - StrTestEntity ed1 = new StrTestEntity("data_ed_1"); - StrTestEntity ed2 = new StrTestEntity("data_ed_2"); + StrTestEntity ed1 = new StrTestEntity( "data_ed_1" ); + StrTestEntity ed2 = new StrTestEntity( "data_ed_2" ); - ListUniEntity ing1 = new ListUniEntity(3, "data_ing_1"); - ListUniEntity ing2 = new ListUniEntity(4, "data_ing_2"); + ListUniEntity ing1 = new ListUniEntity( 3, "data_ing_1" ); + ListUniEntity ing2 = new ListUniEntity( 4, "data_ing_2" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); - em.persist(ing1); - em.persist(ing2); + em.persist( ed1 ); + em.persist( ed2 ); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 + // Revision 2 - em.getTransaction().begin(); + em.getTransaction().begin(); - ing1 = em.find(ListUniEntity.class, ing1.getId()); - ing2 = em.find(ListUniEntity.class, ing2.getId()); - ed1 = em.find(StrTestEntity.class, ed1.getId()); - ed2 = em.find(StrTestEntity.class, ed2.getId()); + ing1 = em.find( ListUniEntity.class, ing1.getId() ); + ing2 = em.find( ListUniEntity.class, ing2.getId() ); + ed1 = em.find( StrTestEntity.class, ed1.getId() ); + ed2 = em.find( StrTestEntity.class, ed2.getId() ); - ing1.setReferences(new ArrayList()); - ing1.getReferences().add(ed1); + ing1.setReferences( new ArrayList() ); + ing1.getReferences().add( ed1 ); - ing2.setReferences(new ArrayList()); - ing2.getReferences().add(ed1); - ing2.getReferences().add(ed2); + ing2.setReferences( new ArrayList() ); + ing2.getReferences().add( ed1 ); + ing2.getReferences().add( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - ing1 = em.find(ListUniEntity.class, ing1.getId()); - ed2 = em.find(StrTestEntity.class, ed2.getId()); - ed1 = em.find(StrTestEntity.class, ed1.getId()); + ing1 = em.find( ListUniEntity.class, ing1.getId() ); + ed2 = em.find( StrTestEntity.class, ed2.getId() ); + ed1 = em.find( StrTestEntity.class, ed1.getId() ); - ing1.getReferences().add(ed2); + ing1.getReferences().add( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); + // Revision 4 + em.getTransaction().begin(); - ing1 = em.find(ListUniEntity.class, ing1.getId()); - ed2 = em.find(StrTestEntity.class, ed2.getId()); - ed1 = em.find(StrTestEntity.class, ed1.getId()); + ing1 = em.find( ListUniEntity.class, ing1.getId() ); + ed2 = em.find( StrTestEntity.class, ed2.getId() ); + ed1 = em.find( StrTestEntity.class, ed1.getId() ); - ing1.getReferences().remove(ed1); + ing1.getReferences().remove( ed1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 5 - em.getTransaction().begin(); + // Revision 5 + em.getTransaction().begin(); - ing1 = em.find(ListUniEntity.class, ing1.getId()); + ing1 = em.find( ListUniEntity.class, ing1.getId() ); - ing1.setReferences(null); + ing1.setReferences( null ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); - } + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestEntity.class, ed1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestEntity.class, ed1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestEntity.class, ed2_id ) ); - assert Arrays.asList(1, 2, 3, 4, 5).equals(getAuditReader().getRevisions(ListUniEntity.class, ing1_id)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(ListUniEntity.class, ing2_id)); - } + assert Arrays.asList( 1, 2, 3, 4, 5 ).equals( getAuditReader().getRevisions( ListUniEntity.class, ing1_id ) ); + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( ListUniEntity.class, ing2_id ) ); + } - @Test - public void testHistoryOfEdIng1() { - StrTestEntity ed1 = getEntityManager().find(StrTestEntity.class, ed1_id); - StrTestEntity ed2 = getEntityManager().find(StrTestEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng1() { + StrTestEntity ed1 = getEntityManager().find( StrTestEntity.class, ed1_id ); + StrTestEntity ed2 = getEntityManager().find( StrTestEntity.class, ed2_id ); - ListUniEntity rev1 = getAuditReader().find(ListUniEntity.class, ing1_id, 1); - ListUniEntity rev2 = getAuditReader().find(ListUniEntity.class, ing1_id, 2); - ListUniEntity rev3 = getAuditReader().find(ListUniEntity.class, ing1_id, 3); - ListUniEntity rev4 = getAuditReader().find(ListUniEntity.class, ing1_id, 4); - ListUniEntity rev5 = getAuditReader().find(ListUniEntity.class, ing1_id, 5); + ListUniEntity rev1 = getAuditReader().find( ListUniEntity.class, ing1_id, 1 ); + ListUniEntity rev2 = getAuditReader().find( ListUniEntity.class, ing1_id, 2 ); + ListUniEntity rev3 = getAuditReader().find( ListUniEntity.class, ing1_id, 3 ); + ListUniEntity rev4 = getAuditReader().find( ListUniEntity.class, ing1_id, 4 ); + ListUniEntity rev5 = getAuditReader().find( ListUniEntity.class, ing1_id, 5 ); - assert rev1.getReferences().equals(Collections.EMPTY_LIST); - assert TestTools.checkList(rev2.getReferences(), ed1); - assert TestTools.checkList(rev3.getReferences(), ed1, ed2); - assert TestTools.checkList(rev4.getReferences(), ed2); - assert rev5.getReferences().equals(Collections.EMPTY_LIST); - } + assert rev1.getReferences().equals( Collections.EMPTY_LIST ); + assert TestTools.checkList( rev2.getReferences(), ed1 ); + assert TestTools.checkList( rev3.getReferences(), ed1, ed2 ); + assert TestTools.checkList( rev4.getReferences(), ed2 ); + assert rev5.getReferences().equals( Collections.EMPTY_LIST ); + } - @Test - public void testHistoryOfEdIng2() { - StrTestEntity ed1 = getEntityManager().find(StrTestEntity.class, ed1_id); - StrTestEntity ed2 = getEntityManager().find(StrTestEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng2() { + StrTestEntity ed1 = getEntityManager().find( StrTestEntity.class, ed1_id ); + StrTestEntity ed2 = getEntityManager().find( StrTestEntity.class, ed2_id ); - ListUniEntity rev1 = getAuditReader().find(ListUniEntity.class, ing2_id, 1); - ListUniEntity rev2 = getAuditReader().find(ListUniEntity.class, ing2_id, 2); - ListUniEntity rev3 = getAuditReader().find(ListUniEntity.class, ing2_id, 3); - ListUniEntity rev4 = getAuditReader().find(ListUniEntity.class, ing2_id, 4); - ListUniEntity rev5 = getAuditReader().find(ListUniEntity.class, ing2_id, 5); + ListUniEntity rev1 = getAuditReader().find( ListUniEntity.class, ing2_id, 1 ); + ListUniEntity rev2 = getAuditReader().find( ListUniEntity.class, ing2_id, 2 ); + ListUniEntity rev3 = getAuditReader().find( ListUniEntity.class, ing2_id, 3 ); + ListUniEntity rev4 = getAuditReader().find( ListUniEntity.class, ing2_id, 4 ); + ListUniEntity rev5 = getAuditReader().find( ListUniEntity.class, ing2_id, 5 ); - assert rev1.getReferences().equals(Collections.EMPTY_LIST); - assert TestTools.checkList(rev2.getReferences(), ed1, ed2); - assert TestTools.checkList(rev3.getReferences(), ed1, ed2); - assert TestTools.checkList(rev4.getReferences(), ed1, ed2); - assert TestTools.checkList(rev5.getReferences(), ed1, ed2); - } + assert rev1.getReferences().equals( Collections.EMPTY_LIST ); + assert TestTools.checkList( rev2.getReferences(), ed1, ed2 ); + assert TestTools.checkList( rev3.getReferences(), ed1, ed2 ); + assert TestTools.checkList( rev4.getReferences(), ed1, ed2 ); + assert TestTools.checkList( rev5.getReferences(), ed1, ed2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/BasicUniMap.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/BasicUniMap.java index 61ac0a98f5..b92ff275df 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/BasicUniMap.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/BasicUniMap.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.manytomany.unidirectional; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.HashMap; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -35,105 +33,107 @@ import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.manytomany.unidirectional.MapUniEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BasicUniMap extends BaseEnversJPAFunctionalTestCase { - private Integer str1_id; - private Integer str2_id; + private Integer str1_id; + private Integer str2_id; - private Integer coll1_id; + private Integer coll1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class, MapUniEntity.class }; - } + return new Class[] {StrTestEntity.class, MapUniEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - StrTestEntity str1 = new StrTestEntity("str1"); - StrTestEntity str2 = new StrTestEntity("str2"); + StrTestEntity str1 = new StrTestEntity( "str1" ); + StrTestEntity str2 = new StrTestEntity( "str2" ); - MapUniEntity coll1 = new MapUniEntity(3, "coll1"); + MapUniEntity coll1 = new MapUniEntity( 3, "coll1" ); - // Revision 1 (coll1: initialy one mapping) - em.getTransaction().begin(); + // Revision 1 (coll1: initialy one mapping) + em.getTransaction().begin(); - em.persist(str1); - em.persist(str2); + em.persist( str1 ); + em.persist( str2 ); - coll1.setMap(new HashMap()); - coll1.getMap().put("1", str1); - em.persist(coll1); + coll1.setMap( new HashMap() ); + coll1.getMap().put( "1", str1 ); + em.persist( coll1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (coll1: adding one mapping) - em.getTransaction().begin(); + // Revision 2 (coll1: adding one mapping) + em.getTransaction().begin(); - str2 = em.find(StrTestEntity.class, str2.getId()); - coll1 = em.find(MapUniEntity.class, coll1.getId()); + str2 = em.find( StrTestEntity.class, str2.getId() ); + coll1 = em.find( MapUniEntity.class, coll1.getId() ); - coll1.getMap().put("2", str2); + coll1.getMap().put( "2", str2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 (coll1: replacing one mapping) - em.getTransaction().begin(); + // Revision 3 (coll1: replacing one mapping) + em.getTransaction().begin(); - str1 = em.find(StrTestEntity.class, str1.getId()); - coll1 = em.find(MapUniEntity.class, coll1.getId()); + str1 = em.find( StrTestEntity.class, str1.getId() ); + coll1 = em.find( MapUniEntity.class, coll1.getId() ); - coll1.getMap().put("2", str1); + coll1.getMap().put( "2", str1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 (coll1: removing one mapping) - em.getTransaction().begin(); + // Revision 4 (coll1: removing one mapping) + em.getTransaction().begin(); - coll1 = em.find(MapUniEntity.class, coll1.getId()); + coll1 = em.find( MapUniEntity.class, coll1.getId() ); - coll1.getMap().remove("1"); + coll1.getMap().remove( "1" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - str1_id = str1.getId(); - str2_id = str2.getId(); + str1_id = str1.getId(); + str2_id = str2.getId(); - coll1_id = coll1.getId(); - } + coll1_id = coll1.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3, 4).equals(getAuditReader().getRevisions(MapUniEntity.class, coll1_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3, 4 ).equals( getAuditReader().getRevisions( MapUniEntity.class, coll1_id ) ); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestEntity.class, str1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestEntity.class, str2_id)); - } + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestEntity.class, str1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestEntity.class, str2_id ) ); + } - @Test - public void testHistoryOfColl1() { - StrTestEntity str1 = getEntityManager().find(StrTestEntity.class, str1_id); - StrTestEntity str2 = getEntityManager().find(StrTestEntity.class, str2_id); + @Test + public void testHistoryOfColl1() { + StrTestEntity str1 = getEntityManager().find( StrTestEntity.class, str1_id ); + StrTestEntity str2 = getEntityManager().find( StrTestEntity.class, str2_id ); - MapUniEntity rev1 = getAuditReader().find(MapUniEntity.class, coll1_id, 1); - MapUniEntity rev2 = getAuditReader().find(MapUniEntity.class, coll1_id, 2); - MapUniEntity rev3 = getAuditReader().find(MapUniEntity.class, coll1_id, 3); - MapUniEntity rev4 = getAuditReader().find(MapUniEntity.class, coll1_id, 4); + MapUniEntity rev1 = getAuditReader().find( MapUniEntity.class, coll1_id, 1 ); + MapUniEntity rev2 = getAuditReader().find( MapUniEntity.class, coll1_id, 2 ); + MapUniEntity rev3 = getAuditReader().find( MapUniEntity.class, coll1_id, 3 ); + MapUniEntity rev4 = getAuditReader().find( MapUniEntity.class, coll1_id, 4 ); - assert rev1.getMap().equals(TestTools.makeMap("1", str1)); - assert rev2.getMap().equals(TestTools.makeMap("1", str1, "2", str2)); - assert rev3.getMap().equals(TestTools.makeMap("1", str1, "2", str1)); - assert rev4.getMap().equals(TestTools.makeMap("2", str1)); + assert rev1.getMap().equals( TestTools.makeMap( "1", str1 ) ); + assert rev2.getMap().equals( TestTools.makeMap( "1", str1, "2", str2 ) ); + assert rev3.getMap().equals( TestTools.makeMap( "1", str1, "2", str1 ) ); + assert rev4.getMap().equals( TestTools.makeMap( "2", str1 ) ); - assert "coll1".equals(rev1.getData()); - assert "coll1".equals(rev2.getData()); - assert "coll1".equals(rev3.getData()); - assert "coll1".equals(rev4.getData()); - } + assert "coll1".equals( rev1.getData() ); + assert "coll1".equals( rev2.getData() ); + assert "coll1".equals( rev3.getData() ); + assert "coll1".equals( rev4.getData() ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/BasicUniSet.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/BasicUniSet.java index f2e734f06c..77d00ec9e0 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/BasicUniSet.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/BasicUniSet.java @@ -23,12 +23,10 @@ */ package org.hibernate.envers.test.integration.manytomany.unidirectional; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -36,142 +34,144 @@ import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.manytomany.unidirectional.SetUniEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BasicUniSet extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SetUniEntity.class, StrTestEntity.class }; - } + return new Class[] {SetUniEntity.class, StrTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - StrTestEntity ed1 = new StrTestEntity("data_ed_1"); - StrTestEntity ed2 = new StrTestEntity("data_ed_2"); + StrTestEntity ed1 = new StrTestEntity( "data_ed_1" ); + StrTestEntity ed2 = new StrTestEntity( "data_ed_2" ); - SetUniEntity ing1 = new SetUniEntity(3, "data_ing_1"); - SetUniEntity ing2 = new SetUniEntity(4, "data_ing_2"); + SetUniEntity ing1 = new SetUniEntity( 3, "data_ing_1" ); + SetUniEntity ing2 = new SetUniEntity( 4, "data_ing_2" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); - em.persist(ing1); - em.persist(ing2); + em.persist( ed1 ); + em.persist( ed2 ); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 + // Revision 2 - em.getTransaction().begin(); + em.getTransaction().begin(); - ing1 = em.find(SetUniEntity.class, ing1.getId()); - ing2 = em.find(SetUniEntity.class, ing2.getId()); - ed1 = em.find(StrTestEntity.class, ed1.getId()); - ed2 = em.find(StrTestEntity.class, ed2.getId()); + ing1 = em.find( SetUniEntity.class, ing1.getId() ); + ing2 = em.find( SetUniEntity.class, ing2.getId() ); + ed1 = em.find( StrTestEntity.class, ed1.getId() ); + ed2 = em.find( StrTestEntity.class, ed2.getId() ); - ing1.setReferences(new HashSet()); - ing1.getReferences().add(ed1); + ing1.setReferences( new HashSet() ); + ing1.getReferences().add( ed1 ); - ing2.setReferences(new HashSet()); - ing2.getReferences().add(ed1); - ing2.getReferences().add(ed2); + ing2.setReferences( new HashSet() ); + ing2.getReferences().add( ed1 ); + ing2.getReferences().add( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - ing1 = em.find(SetUniEntity.class, ing1.getId()); - ed2 = em.find(StrTestEntity.class, ed2.getId()); - ed1 = em.find(StrTestEntity.class, ed1.getId()); + ing1 = em.find( SetUniEntity.class, ing1.getId() ); + ed2 = em.find( StrTestEntity.class, ed2.getId() ); + ed1 = em.find( StrTestEntity.class, ed1.getId() ); - ing1.getReferences().add(ed2); + ing1.getReferences().add( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); + // Revision 4 + em.getTransaction().begin(); - ing1 = em.find(SetUniEntity.class, ing1.getId()); - ed2 = em.find(StrTestEntity.class, ed2.getId()); - ed1 = em.find(StrTestEntity.class, ed1.getId()); + ing1 = em.find( SetUniEntity.class, ing1.getId() ); + ed2 = em.find( StrTestEntity.class, ed2.getId() ); + ed1 = em.find( StrTestEntity.class, ed1.getId() ); - ing1.getReferences().remove(ed1); + ing1.getReferences().remove( ed1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 5 - em.getTransaction().begin(); + // Revision 5 + em.getTransaction().begin(); - ing1 = em.find(SetUniEntity.class, ing1.getId()); + ing1 = em.find( SetUniEntity.class, ing1.getId() ); - ing1.setReferences(null); + ing1.setReferences( null ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); - } + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestEntity.class, ed1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestEntity.class, ed1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestEntity.class, ed2_id ) ); - assert Arrays.asList(1, 2, 3, 4, 5).equals(getAuditReader().getRevisions(SetUniEntity.class, ing1_id)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(SetUniEntity.class, ing2_id)); - } + assert Arrays.asList( 1, 2, 3, 4, 5 ).equals( getAuditReader().getRevisions( SetUniEntity.class, ing1_id ) ); + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( SetUniEntity.class, ing2_id ) ); + } - @Test - public void testHistoryOfEdIng1() { - StrTestEntity ed1 = getEntityManager().find(StrTestEntity.class, ed1_id); - StrTestEntity ed2 = getEntityManager().find(StrTestEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng1() { + StrTestEntity ed1 = getEntityManager().find( StrTestEntity.class, ed1_id ); + StrTestEntity ed2 = getEntityManager().find( StrTestEntity.class, ed2_id ); - SetUniEntity rev1 = getAuditReader().find(SetUniEntity.class, ing1_id, 1); - SetUniEntity rev2 = getAuditReader().find(SetUniEntity.class, ing1_id, 2); - SetUniEntity rev3 = getAuditReader().find(SetUniEntity.class, ing1_id, 3); - SetUniEntity rev4 = getAuditReader().find(SetUniEntity.class, ing1_id, 4); - SetUniEntity rev5 = getAuditReader().find(SetUniEntity.class, ing1_id, 5); + SetUniEntity rev1 = getAuditReader().find( SetUniEntity.class, ing1_id, 1 ); + SetUniEntity rev2 = getAuditReader().find( SetUniEntity.class, ing1_id, 2 ); + SetUniEntity rev3 = getAuditReader().find( SetUniEntity.class, ing1_id, 3 ); + SetUniEntity rev4 = getAuditReader().find( SetUniEntity.class, ing1_id, 4 ); + SetUniEntity rev5 = getAuditReader().find( SetUniEntity.class, ing1_id, 5 ); - assert rev1.getReferences().equals(Collections.EMPTY_SET); - assert rev2.getReferences().equals(TestTools.makeSet(ed1)); - assert rev3.getReferences().equals(TestTools.makeSet(ed1, ed2)); - assert rev4.getReferences().equals(TestTools.makeSet(ed2)); - assert rev5.getReferences().equals(Collections.EMPTY_SET); - } + assert rev1.getReferences().equals( Collections.EMPTY_SET ); + assert rev2.getReferences().equals( TestTools.makeSet( ed1 ) ); + assert rev3.getReferences().equals( TestTools.makeSet( ed1, ed2 ) ); + assert rev4.getReferences().equals( TestTools.makeSet( ed2 ) ); + assert rev5.getReferences().equals( Collections.EMPTY_SET ); + } - @Test - public void testHistoryOfEdIng2() { - StrTestEntity ed1 = getEntityManager().find(StrTestEntity.class, ed1_id); - StrTestEntity ed2 = getEntityManager().find(StrTestEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng2() { + StrTestEntity ed1 = getEntityManager().find( StrTestEntity.class, ed1_id ); + StrTestEntity ed2 = getEntityManager().find( StrTestEntity.class, ed2_id ); - SetUniEntity rev1 = getAuditReader().find(SetUniEntity.class, ing2_id, 1); - SetUniEntity rev2 = getAuditReader().find(SetUniEntity.class, ing2_id, 2); - SetUniEntity rev3 = getAuditReader().find(SetUniEntity.class, ing2_id, 3); - SetUniEntity rev4 = getAuditReader().find(SetUniEntity.class, ing2_id, 4); - SetUniEntity rev5 = getAuditReader().find(SetUniEntity.class, ing2_id, 5); + SetUniEntity rev1 = getAuditReader().find( SetUniEntity.class, ing2_id, 1 ); + SetUniEntity rev2 = getAuditReader().find( SetUniEntity.class, ing2_id, 2 ); + SetUniEntity rev3 = getAuditReader().find( SetUniEntity.class, ing2_id, 3 ); + SetUniEntity rev4 = getAuditReader().find( SetUniEntity.class, ing2_id, 4 ); + SetUniEntity rev5 = getAuditReader().find( SetUniEntity.class, ing2_id, 5 ); - assert rev1.getReferences().equals(Collections.EMPTY_SET); - assert rev2.getReferences().equals(TestTools.makeSet(ed1, ed2)); - assert rev3.getReferences().equals(TestTools.makeSet(ed1, ed2)); - assert rev4.getReferences().equals(TestTools.makeSet(ed1, ed2)); - assert rev5.getReferences().equals(TestTools.makeSet(ed1, ed2)); - } + assert rev1.getReferences().equals( Collections.EMPTY_SET ); + assert rev2.getReferences().equals( TestTools.makeSet( ed1, ed2 ) ); + assert rev3.getReferences().equals( TestTools.makeSet( ed1, ed2 ) ); + assert rev4.getReferences().equals( TestTools.makeSet( ed1, ed2 ) ); + assert rev5.getReferences().equals( TestTools.makeSet( ed1, ed2 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/JoinTableDetachedTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/JoinTableDetachedTest.java index 78b6a86d72..2eeb3dcaba 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/JoinTableDetachedTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/JoinTableDetachedTest.java @@ -1,22 +1,23 @@ package org.hibernate.envers.test.integration.manytomany.unidirectional; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.HashSet; -import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.manytomany.unidirectional.JoinTableEntity; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ -@TestForIssue( jiraKey = "HHH-8087" ) +@TestForIssue(jiraKey = "HHH-8087") public class JoinTableDetachedTest extends BaseEnversJPAFunctionalTestCase { private Long collectionEntityId = null; private Integer element1Id = null; @@ -24,7 +25,7 @@ public class JoinTableDetachedTest extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { JoinTableEntity.class, StrTestEntity.class }; + return new Class[] {JoinTableEntity.class, StrTestEntity.class}; } @Test @@ -93,9 +94,14 @@ public class JoinTableDetachedTest extends BaseEnversJPAFunctionalTestCase { @Test public void testRevisionsCounts() { - Assert.assertEquals( Arrays.asList( 1, 2, 3, 4, 5 ), getAuditReader().getRevisions(JoinTableEntity.class, collectionEntityId ) ); - Assert.assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions(StrTestEntity.class, element1Id ) ); - Assert.assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions(StrTestEntity.class, element2Id ) ); + Assert.assertEquals( + Arrays.asList( 1, 2, 3, 4, 5 ), getAuditReader().getRevisions( + JoinTableEntity.class, + collectionEntityId + ) + ); + Assert.assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( StrTestEntity.class, element1Id ) ); + Assert.assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( StrTestEntity.class, element2Id ) ); } @Test diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/M2MIndexedListNotAuditedTarget.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/M2MIndexedListNotAuditedTarget.java index 0a0fdef23c..63c8c56c3d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/M2MIndexedListNotAuditedTarget.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/M2MIndexedListNotAuditedTarget.java @@ -1,16 +1,16 @@ package org.hibernate.envers.test.integration.manytomany.unidirectional; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.UnversionedStrTestEntity; import org.hibernate.envers.test.entities.manytomany.unidirectional.M2MIndexedListTargetNotAuditedEntity; +import org.junit.Test; + import static org.hibernate.envers.test.tools.TestTools.checkList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -23,98 +23,122 @@ import static org.junit.Assert.assertTrue; * @author Adam Warski */ public class M2MIndexedListNotAuditedTarget extends BaseEnversJPAFunctionalTestCase { - private Integer itnae1_id; - private Integer itnae2_id; + private Integer itnae1_id; + private Integer itnae2_id; - private UnversionedStrTestEntity uste1; - private UnversionedStrTestEntity uste2; + private UnversionedStrTestEntity uste1; + private UnversionedStrTestEntity uste2; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { UnversionedStrTestEntity.class, M2MIndexedListTargetNotAuditedEntity.class }; - } + return new Class[] {UnversionedStrTestEntity.class, M2MIndexedListTargetNotAuditedEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - uste1 = new UnversionedStrTestEntity("str1"); - uste2 = new UnversionedStrTestEntity("str2"); + uste1 = new UnversionedStrTestEntity( "str1" ); + uste2 = new UnversionedStrTestEntity( "str2" ); - // No revision - em.getTransaction().begin(); + // No revision + em.getTransaction().begin(); - em.persist(uste1); - em.persist(uste2); + em.persist( uste1 ); + em.persist( uste2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - uste1 = em.find(UnversionedStrTestEntity.class, uste1.getId()); - uste2 = em.find(UnversionedStrTestEntity.class, uste2.getId()); + uste1 = em.find( UnversionedStrTestEntity.class, uste1.getId() ); + uste2 = em.find( UnversionedStrTestEntity.class, uste2.getId() ); - M2MIndexedListTargetNotAuditedEntity itnae1 = new M2MIndexedListTargetNotAuditedEntity(1, "tnae1"); + M2MIndexedListTargetNotAuditedEntity itnae1 = new M2MIndexedListTargetNotAuditedEntity( 1, "tnae1" ); - itnae1.getReferences().add(uste1); - itnae1.getReferences().add(uste2); + itnae1.getReferences().add( uste1 ); + itnae1.getReferences().add( uste2 ); - em.persist(itnae1); + em.persist( itnae1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - M2MIndexedListTargetNotAuditedEntity itnae2 = new M2MIndexedListTargetNotAuditedEntity(2, "tnae2"); + M2MIndexedListTargetNotAuditedEntity itnae2 = new M2MIndexedListTargetNotAuditedEntity( 2, "tnae2" ); - itnae2.getReferences().add(uste2); + itnae2.getReferences().add( uste2 ); - em.persist(itnae2); + em.persist( itnae2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - itnae1.getReferences().set(0, uste2); - itnae1.getReferences().set(1, uste1); - em.getTransaction().commit(); + itnae1.getReferences().set( 0, uste2 ); + itnae1.getReferences().set( 1, uste1 ); + em.getTransaction().commit(); - itnae1_id = itnae1.getId(); - itnae2_id = itnae2.getId(); - } + itnae1_id = itnae1.getId(); + itnae2_id = itnae2.getId(); + } @Test public void testRevisionsCounts() { - List revisions = getAuditReader().getRevisions(M2MIndexedListTargetNotAuditedEntity.class, itnae1_id); - assertEquals(revisions, Arrays.asList(1, 3)); + List revisions = getAuditReader().getRevisions( M2MIndexedListTargetNotAuditedEntity.class, itnae1_id ); + assertEquals( revisions, Arrays.asList( 1, 3 ) ); - revisions = getAuditReader().getRevisions(M2MIndexedListTargetNotAuditedEntity.class, itnae2_id); - assertEquals(revisions, Arrays.asList(2)); + revisions = getAuditReader().getRevisions( M2MIndexedListTargetNotAuditedEntity.class, itnae2_id ); + assertEquals( revisions, Arrays.asList( 2 ) ); } - @Test - public void testHistory1() throws Exception { - M2MIndexedListTargetNotAuditedEntity rev1 = getAuditReader().find(M2MIndexedListTargetNotAuditedEntity.class, itnae1_id, 1); - M2MIndexedListTargetNotAuditedEntity rev2 = getAuditReader().find(M2MIndexedListTargetNotAuditedEntity.class, itnae1_id, 2); - M2MIndexedListTargetNotAuditedEntity rev3 = getAuditReader().find(M2MIndexedListTargetNotAuditedEntity.class, itnae1_id, 3); + @Test + public void testHistory1() throws Exception { + M2MIndexedListTargetNotAuditedEntity rev1 = getAuditReader().find( + M2MIndexedListTargetNotAuditedEntity.class, + itnae1_id, + 1 + ); + M2MIndexedListTargetNotAuditedEntity rev2 = getAuditReader().find( + M2MIndexedListTargetNotAuditedEntity.class, + itnae1_id, + 2 + ); + M2MIndexedListTargetNotAuditedEntity rev3 = getAuditReader().find( + M2MIndexedListTargetNotAuditedEntity.class, + itnae1_id, + 3 + ); - assertTrue(checkList(rev1.getReferences(), uste1, uste2)); - assertTrue(checkList(rev2.getReferences(), uste1, uste2)); - assertTrue(checkList(rev3.getReferences(), uste2, uste1)); - } + assertTrue( checkList( rev1.getReferences(), uste1, uste2 ) ); + assertTrue( checkList( rev2.getReferences(), uste1, uste2 ) ); + assertTrue( checkList( rev3.getReferences(), uste2, uste1 ) ); + } - @Test - public void testHistory2() throws Exception { - M2MIndexedListTargetNotAuditedEntity rev1 = getAuditReader().find(M2MIndexedListTargetNotAuditedEntity.class, itnae2_id, 1); - M2MIndexedListTargetNotAuditedEntity rev2 = getAuditReader().find(M2MIndexedListTargetNotAuditedEntity.class, itnae2_id, 2); - M2MIndexedListTargetNotAuditedEntity rev3 = getAuditReader().find(M2MIndexedListTargetNotAuditedEntity.class, itnae2_id, 3); + @Test + public void testHistory2() throws Exception { + M2MIndexedListTargetNotAuditedEntity rev1 = getAuditReader().find( + M2MIndexedListTargetNotAuditedEntity.class, + itnae2_id, + 1 + ); + M2MIndexedListTargetNotAuditedEntity rev2 = getAuditReader().find( + M2MIndexedListTargetNotAuditedEntity.class, + itnae2_id, + 2 + ); + M2MIndexedListTargetNotAuditedEntity rev3 = getAuditReader().find( + M2MIndexedListTargetNotAuditedEntity.class, + itnae2_id, + 3 + ); - assertNull(rev1); - assertTrue(checkList(rev2.getReferences(), uste2)); - assertTrue(checkList(rev3.getReferences(), uste2)); - } + assertNull( rev1 ); + assertTrue( checkList( rev2.getReferences(), uste2 ) ); + assertTrue( checkList( rev3.getReferences(), uste2 ) ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/M2MRelationNotAuditedTarget.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/M2MRelationNotAuditedTarget.java index 50594e2672..2e7d567128 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/M2MRelationNotAuditedTarget.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/unidirectional/M2MRelationNotAuditedTarget.java @@ -23,23 +23,24 @@ */ package org.hibernate.envers.test.integration.manytomany.unidirectional; +import javax.persistence.EntityManager; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.UnversionedStrTestEntity; import org.hibernate.envers.test.entities.manytomany.unidirectional.M2MTargetNotAuditedEntity; +import org.junit.Test; + import static org.hibernate.envers.test.tools.TestTools.checkList; import static org.junit.Assert.assertTrue; /** * A test for auditing a many-to-many relation where the target entity is not audited. + * * @author Adam Warski */ public class M2MRelationNotAuditedTarget extends BaseEnversJPAFunctionalTestCase { @@ -51,71 +52,79 @@ public class M2MRelationNotAuditedTarget extends BaseEnversJPAFunctionalTestCase @Override protected Class[] getAnnotatedClasses() { - return new Class[] { M2MTargetNotAuditedEntity.class, UnversionedStrTestEntity.class }; + return new Class[] {M2MTargetNotAuditedEntity.class, UnversionedStrTestEntity.class}; } @Test - @Priority(10) + @Priority(10) public void initData() { EntityManager em = getEntityManager(); - UnversionedStrTestEntity uste1 = new UnversionedStrTestEntity("str1"); - UnversionedStrTestEntity uste2 = new UnversionedStrTestEntity("str2"); + UnversionedStrTestEntity uste1 = new UnversionedStrTestEntity( "str1" ); + UnversionedStrTestEntity uste2 = new UnversionedStrTestEntity( "str2" ); // No revision em.getTransaction().begin(); - em.persist(uste1); - em.persist(uste2); + em.persist( uste1 ); + em.persist( uste2 ); em.getTransaction().commit(); // Revision 1 em.getTransaction().begin(); - uste1 = em.find(UnversionedStrTestEntity.class, uste1.getId()); - uste2 = em.find(UnversionedStrTestEntity.class, uste2.getId()); + uste1 = em.find( UnversionedStrTestEntity.class, uste1.getId() ); + uste2 = em.find( UnversionedStrTestEntity.class, uste2.getId() ); - M2MTargetNotAuditedEntity tnae1 = new M2MTargetNotAuditedEntity(1, "tnae1", new ArrayList()); - M2MTargetNotAuditedEntity tnae2 = new M2MTargetNotAuditedEntity(2, "tnae2", new ArrayList()); - tnae2.getReferences().add(uste1); - tnae2.getReferences().add(uste2); - em.persist(tnae1); - em.persist(tnae2); + M2MTargetNotAuditedEntity tnae1 = new M2MTargetNotAuditedEntity( + 1, + "tnae1", + new ArrayList() + ); + M2MTargetNotAuditedEntity tnae2 = new M2MTargetNotAuditedEntity( + 2, + "tnae2", + new ArrayList() + ); + tnae2.getReferences().add( uste1 ); + tnae2.getReferences().add( uste2 ); + em.persist( tnae1 ); + em.persist( tnae2 ); em.getTransaction().commit(); // Revision 2 em.getTransaction().begin(); - tnae1 = em.find(M2MTargetNotAuditedEntity.class, tnae1.getId()); - tnae2 = em.find(M2MTargetNotAuditedEntity.class, tnae2.getId()); + tnae1 = em.find( M2MTargetNotAuditedEntity.class, tnae1.getId() ); + tnae2 = em.find( M2MTargetNotAuditedEntity.class, tnae2.getId() ); - tnae1.getReferences().add(uste1); - tnae2.getReferences().remove(uste1); + tnae1.getReferences().add( uste1 ); + tnae2.getReferences().remove( uste1 ); em.getTransaction().commit(); // Revision 3 em.getTransaction().begin(); - tnae1 = em.find(M2MTargetNotAuditedEntity.class, tnae1.getId()); - tnae2 = em.find(M2MTargetNotAuditedEntity.class, tnae2.getId()); + tnae1 = em.find( M2MTargetNotAuditedEntity.class, tnae1.getId() ); + tnae2 = em.find( M2MTargetNotAuditedEntity.class, tnae2.getId() ); //field not changed!!! - tnae1.getReferences().add(uste1); - tnae2.getReferences().remove(uste2); + tnae1.getReferences().add( uste1 ); + tnae2.getReferences().remove( uste2 ); em.getTransaction().commit(); // Revision 4 em.getTransaction().begin(); - tnae1 = em.find(M2MTargetNotAuditedEntity.class, tnae1.getId()); - tnae2 = em.find(M2MTargetNotAuditedEntity.class, tnae2.getId()); + tnae1 = em.find( M2MTargetNotAuditedEntity.class, tnae1.getId() ); + tnae2 = em.find( M2MTargetNotAuditedEntity.class, tnae2.getId() ); - tnae1.getReferences().add(uste2); - tnae2.getReferences().add(uste1); + tnae1.getReferences().add( uste2 ); + tnae2.getReferences().add( uste1 ); em.getTransaction().commit(); @@ -128,41 +137,41 @@ public class M2MRelationNotAuditedTarget extends BaseEnversJPAFunctionalTestCase @Test public void testRevisionsCounts() { - List revisions = getAuditReader().getRevisions(M2MTargetNotAuditedEntity.class, tnae1_id); - assert Arrays.asList(1, 2, 4).equals(revisions); - revisions = getAuditReader().getRevisions(M2MTargetNotAuditedEntity.class, tnae2_id); - assert Arrays.asList(1, 2, 3, 4).equals(revisions); + List revisions = getAuditReader().getRevisions( M2MTargetNotAuditedEntity.class, tnae1_id ); + assert Arrays.asList( 1, 2, 4 ).equals( revisions ); + revisions = getAuditReader().getRevisions( M2MTargetNotAuditedEntity.class, tnae2_id ); + assert Arrays.asList( 1, 2, 3, 4 ).equals( revisions ); } @Test public void testHistoryOfTnae1_id() { - UnversionedStrTestEntity uste1 = getEntityManager().find(UnversionedStrTestEntity.class, uste1_id); - UnversionedStrTestEntity uste2 = getEntityManager().find(UnversionedStrTestEntity.class, uste2_id); + UnversionedStrTestEntity uste1 = getEntityManager().find( UnversionedStrTestEntity.class, uste1_id ); + UnversionedStrTestEntity uste2 = getEntityManager().find( UnversionedStrTestEntity.class, uste2_id ); - M2MTargetNotAuditedEntity rev1 = getAuditReader().find(M2MTargetNotAuditedEntity.class, tnae1_id, 1); - M2MTargetNotAuditedEntity rev2 = getAuditReader().find(M2MTargetNotAuditedEntity.class, tnae1_id, 2); - M2MTargetNotAuditedEntity rev3 = getAuditReader().find(M2MTargetNotAuditedEntity.class, tnae1_id, 3); - M2MTargetNotAuditedEntity rev4 = getAuditReader().find(M2MTargetNotAuditedEntity.class, tnae1_id, 4); + M2MTargetNotAuditedEntity rev1 = getAuditReader().find( M2MTargetNotAuditedEntity.class, tnae1_id, 1 ); + M2MTargetNotAuditedEntity rev2 = getAuditReader().find( M2MTargetNotAuditedEntity.class, tnae1_id, 2 ); + M2MTargetNotAuditedEntity rev3 = getAuditReader().find( M2MTargetNotAuditedEntity.class, tnae1_id, 3 ); + M2MTargetNotAuditedEntity rev4 = getAuditReader().find( M2MTargetNotAuditedEntity.class, tnae1_id, 4 ); - assertTrue(checkList(rev1.getReferences())); - assertTrue(checkList(rev2.getReferences(), uste1)); - assertTrue(checkList(rev3.getReferences(), uste1)); - assertTrue(checkList(rev4.getReferences(), uste1, uste2)); + assertTrue( checkList( rev1.getReferences() ) ); + assertTrue( checkList( rev2.getReferences(), uste1 ) ); + assertTrue( checkList( rev3.getReferences(), uste1 ) ); + assertTrue( checkList( rev4.getReferences(), uste1, uste2 ) ); } @Test public void testHistoryOfTnae2_id() { - UnversionedStrTestEntity uste1 = getEntityManager().find(UnversionedStrTestEntity.class, uste1_id); - UnversionedStrTestEntity uste2 = getEntityManager().find(UnversionedStrTestEntity.class, uste2_id); + UnversionedStrTestEntity uste1 = getEntityManager().find( UnversionedStrTestEntity.class, uste1_id ); + UnversionedStrTestEntity uste2 = getEntityManager().find( UnversionedStrTestEntity.class, uste2_id ); - M2MTargetNotAuditedEntity rev1 = getAuditReader().find(M2MTargetNotAuditedEntity.class, tnae2_id, 1); - M2MTargetNotAuditedEntity rev2 = getAuditReader().find(M2MTargetNotAuditedEntity.class, tnae2_id, 2); - M2MTargetNotAuditedEntity rev3 = getAuditReader().find(M2MTargetNotAuditedEntity.class, tnae2_id, 3); - M2MTargetNotAuditedEntity rev4 = getAuditReader().find(M2MTargetNotAuditedEntity.class, tnae2_id, 4); + M2MTargetNotAuditedEntity rev1 = getAuditReader().find( M2MTargetNotAuditedEntity.class, tnae2_id, 1 ); + M2MTargetNotAuditedEntity rev2 = getAuditReader().find( M2MTargetNotAuditedEntity.class, tnae2_id, 2 ); + M2MTargetNotAuditedEntity rev3 = getAuditReader().find( M2MTargetNotAuditedEntity.class, tnae2_id, 3 ); + M2MTargetNotAuditedEntity rev4 = getAuditReader().find( M2MTargetNotAuditedEntity.class, tnae2_id, 4 ); - assertTrue(checkList(rev1.getReferences(), uste1, uste2)); - assertTrue(checkList(rev2.getReferences(), uste2)); - assertTrue(checkList(rev3.getReferences())); - assertTrue(checkList(rev4.getReferences(), uste1)); + assertTrue( checkList( rev1.getReferences(), uste1, uste2 ) ); + assertTrue( checkList( rev2.getReferences(), uste2 ) ); + assertTrue( checkList( rev3.getReferences() ) ); + assertTrue( checkList( rev4.getReferences(), uste1 ) ); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/bidirectional/ImplicitMappedByTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/bidirectional/ImplicitMappedByTest.java index e1f5c2c8ab..d4b3bfc187 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/bidirectional/ImplicitMappedByTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/bidirectional/ImplicitMappedByTest.java @@ -1,16 +1,17 @@ package org.hibernate.envers.test.integration.manytoone.bidirectional; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.HashSet; import java.util.Set; -import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.tools.TestTools; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -18,93 +19,93 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-4962") public class ImplicitMappedByTest extends BaseEnversJPAFunctionalTestCase { - private Long ownedId = null; - private Long owning1Id = null; - private Long owning2Id = null; + private Long ownedId = null; + private Long owning1Id = null; + private Long owning2Id = null; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { OneToManyOwned.class, ManyToOneOwning.class }; - } + return new Class[] {OneToManyOwned.class, ManyToOneOwning.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - OneToManyOwned owned = new OneToManyOwned("data", null); - Set referencing = new HashSet(); - ManyToOneOwning owning1 = new ManyToOneOwning("data1", owned); - referencing.add(owning1); - ManyToOneOwning owning2 = new ManyToOneOwning("data2", owned); - referencing.add(owning2); - owned.setReferencing(referencing); + OneToManyOwned owned = new OneToManyOwned( "data", null ); + Set referencing = new HashSet(); + ManyToOneOwning owning1 = new ManyToOneOwning( "data1", owned ); + referencing.add( owning1 ); + ManyToOneOwning owning2 = new ManyToOneOwning( "data2", owned ); + referencing.add( owning2 ); + owned.setReferencing( referencing ); - // Revision 1 - em.getTransaction().begin(); - em.persist(owned); - em.persist(owning1); - em.persist(owning2); - em.getTransaction().commit(); + // Revision 1 + em.getTransaction().begin(); + em.persist( owned ); + em.persist( owning1 ); + em.persist( owning2 ); + em.getTransaction().commit(); - ownedId = owned.getId(); - owning1Id = owning1.getId(); - owning2Id = owning2.getId(); + ownedId = owned.getId(); + owning1Id = owning1.getId(); + owning2Id = owning2.getId(); - // Revision 2 - em.getTransaction().begin(); - owning1 = em.find(ManyToOneOwning.class, owning1.getId()); - em.remove(owning1); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + owning1 = em.find( ManyToOneOwning.class, owning1.getId() ); + em.remove( owning1 ); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); - owning2 = em.find(ManyToOneOwning.class, owning2.getId()); - owning2.setData("data2modified"); - em.merge(owning2); - em.getTransaction().commit(); - } + // Revision 3 + em.getTransaction().begin(); + owning2 = em.find( ManyToOneOwning.class, owning2.getId() ); + owning2.setData( "data2modified" ); + em.merge( owning2 ); + em.getTransaction().commit(); + } - @Test + @Test public void testRevisionsCounts() { - Assert.assertEquals(Arrays.asList(1, 2), getAuditReader().getRevisions(OneToManyOwned.class, ownedId)); - Assert.assertEquals(Arrays.asList(1, 2), getAuditReader().getRevisions(ManyToOneOwning.class, owning1Id)); - Assert.assertEquals(Arrays.asList(1, 3), getAuditReader().getRevisions(ManyToOneOwning.class, owning2Id)); - } + Assert.assertEquals( Arrays.asList( 1, 2 ), getAuditReader().getRevisions( OneToManyOwned.class, ownedId ) ); + Assert.assertEquals( Arrays.asList( 1, 2 ), getAuditReader().getRevisions( ManyToOneOwning.class, owning1Id ) ); + Assert.assertEquals( Arrays.asList( 1, 3 ), getAuditReader().getRevisions( ManyToOneOwning.class, owning2Id ) ); + } - @Test - public void testHistoryOfOwned() { - OneToManyOwned owned = new OneToManyOwned("data", null, ownedId); - ManyToOneOwning owning1 = new ManyToOneOwning("data1", owned, owning1Id); - ManyToOneOwning owning2 = new ManyToOneOwning("data2", owned, owning2Id); + @Test + public void testHistoryOfOwned() { + OneToManyOwned owned = new OneToManyOwned( "data", null, ownedId ); + ManyToOneOwning owning1 = new ManyToOneOwning( "data1", owned, owning1Id ); + ManyToOneOwning owning2 = new ManyToOneOwning( "data2", owned, owning2Id ); - OneToManyOwned ver1 = getAuditReader().find(OneToManyOwned.class, ownedId, 1); - Assert.assertEquals(owned, ver1); - Assert.assertEquals(TestTools.makeSet(owning1, owning2), ver1.getReferencing()); + OneToManyOwned ver1 = getAuditReader().find( OneToManyOwned.class, ownedId, 1 ); + Assert.assertEquals( owned, ver1 ); + Assert.assertEquals( TestTools.makeSet( owning1, owning2 ), ver1.getReferencing() ); - OneToManyOwned ver2 = getAuditReader().find(OneToManyOwned.class, ownedId, 2); - Assert.assertEquals(owned, ver2); - Assert.assertEquals(TestTools.makeSet(owning2), ver2.getReferencing()); - } + OneToManyOwned ver2 = getAuditReader().find( OneToManyOwned.class, ownedId, 2 ); + Assert.assertEquals( owned, ver2 ); + Assert.assertEquals( TestTools.makeSet( owning2 ), ver2.getReferencing() ); + } - @Test - public void testHistoryOfOwning1() { - ManyToOneOwning ver1 = new ManyToOneOwning("data1", null, owning1Id); - Assert.assertEquals(ver1, getAuditReader().find(ManyToOneOwning.class, owning1Id, 1)); - } + @Test + public void testHistoryOfOwning1() { + ManyToOneOwning ver1 = new ManyToOneOwning( "data1", null, owning1Id ); + Assert.assertEquals( ver1, getAuditReader().find( ManyToOneOwning.class, owning1Id, 1 ) ); + } - @Test - public void testHistoryOfOwning2() { - OneToManyOwned owned = new OneToManyOwned("data", null, ownedId); - ManyToOneOwning owning1 = new ManyToOneOwning("data2", owned, owning2Id); - ManyToOneOwning owning3 = new ManyToOneOwning("data2modified", owned, owning2Id); + @Test + public void testHistoryOfOwning2() { + OneToManyOwned owned = new OneToManyOwned( "data", null, ownedId ); + ManyToOneOwning owning1 = new ManyToOneOwning( "data2", owned, owning2Id ); + ManyToOneOwning owning3 = new ManyToOneOwning( "data2modified", owned, owning2Id ); - ManyToOneOwning ver1 = getAuditReader().find(ManyToOneOwning.class, owning2Id, 1); - ManyToOneOwning ver3 = getAuditReader().find(ManyToOneOwning.class, owning2Id, 3); + ManyToOneOwning ver1 = getAuditReader().find( ManyToOneOwning.class, owning2Id, 1 ); + ManyToOneOwning ver3 = getAuditReader().find( ManyToOneOwning.class, owning2Id, 3 ); - Assert.assertEquals(owning1, ver1); - Assert.assertEquals(owned.getId(), ver1.getReferences().getId()); - Assert.assertEquals(owning3, ver3); - Assert.assertEquals(owned.getId(), ver3.getReferences().getId()); - } + Assert.assertEquals( owning1, ver1 ); + Assert.assertEquals( owned.getId(), ver1.getReferences().getId() ); + Assert.assertEquals( owning3, ver3 ); + Assert.assertEquals( owned.getId(), ver3.getReferences().getId() ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/bidirectional/ManyToOneOwning.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/bidirectional/ManyToOneOwning.java index 36cc49aeb9..38536a9745 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/bidirectional/ManyToOneOwning.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/bidirectional/ManyToOneOwning.java @@ -1,12 +1,12 @@ package org.hibernate.envers.test.integration.manytoone.bidirectional; -import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToOne; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -16,77 +16,85 @@ import org.hibernate.envers.Audited; @Entity @Audited public class ManyToOneOwning implements Serializable { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String data; + private String data; - @ManyToOne - @JoinTable(name = "many_to_one_join_table", joinColumns = @JoinColumn(name = "owning_id"), - inverseJoinColumns = @JoinColumn(name = "owned_id")) - private OneToManyOwned references; + @ManyToOne + @JoinTable(name = "many_to_one_join_table", joinColumns = @JoinColumn(name = "owning_id"), + inverseJoinColumns = @JoinColumn(name = "owned_id")) + private OneToManyOwned references; - public ManyToOneOwning() { - } + public ManyToOneOwning() { + } - public ManyToOneOwning(String data, OneToManyOwned references) { - this.data = data; - this.references = references; - } + public ManyToOneOwning(String data, OneToManyOwned references) { + this.data = data; + this.references = references; + } - public ManyToOneOwning(String data, OneToManyOwned references, Long id) { - this.id = id; - this.data = data; - this.references = references; - } + public ManyToOneOwning(String data, OneToManyOwned references, Long id) { + this.id = id; + this.data = data; + this.references = references; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ManyToOneOwning)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ManyToOneOwning) ) { + return false; + } - ManyToOneOwning that = (ManyToOneOwning) o; + ManyToOneOwning that = (ManyToOneOwning) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "ManyToOneOwning(id = " + id + ", data = " + data + ")"; - } + @Override + public String toString() { + return "ManyToOneOwning(id = " + id + ", data = " + data + ")"; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public OneToManyOwned getReferences() { - return references; - } + public OneToManyOwned getReferences() { + return references; + } - public void setReferences(OneToManyOwned references) { - this.references = references; - } + public void setReferences(OneToManyOwned references) { + this.references = references; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/bidirectional/OneToManyOwned.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/bidirectional/OneToManyOwned.java index b91a373ec4..7f5d7b9147 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/bidirectional/OneToManyOwned.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/bidirectional/OneToManyOwned.java @@ -1,12 +1,12 @@ package org.hibernate.envers.test.integration.manytoone.bidirectional; -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; import org.hibernate.envers.Audited; @@ -16,75 +16,83 @@ import org.hibernate.envers.Audited; @Entity @Audited public class OneToManyOwned implements Serializable { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String data; + private String data; - @OneToMany(mappedBy="references") - private Set referencing = new HashSet(); + @OneToMany(mappedBy = "references") + private Set referencing = new HashSet(); - public OneToManyOwned() { - } + public OneToManyOwned() { + } - public OneToManyOwned(String data, Set referencing) { - this.data = data; - this.referencing = referencing; - } + public OneToManyOwned(String data, Set referencing) { + this.data = data; + this.referencing = referencing; + } - public OneToManyOwned(String data, Set referencing, Long id) { - this.id = id; - this.data = data; - this.referencing = referencing; - } + public OneToManyOwned(String data, Set referencing, Long id) { + this.id = id; + this.data = data; + this.referencing = referencing; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof OneToManyOwned)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof OneToManyOwned) ) { + return false; + } - OneToManyOwned that = (OneToManyOwned) o; + OneToManyOwned that = (OneToManyOwned) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "OneToManyOwned(id = " + id + ", data = " + data + ")"; - } + @Override + public String toString() { + return "OneToManyOwned(id = " + id + ", data = " + data + ")"; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Set getReferencing() { - return referencing; - } + public Set getReferencing() { + return referencing; + } - public void setReferencing(Set referencing) { - this.referencing = referencing; - } + public void setReferencing(Set referencing) { + this.referencing = referencing; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/unidirectional/RelationNotAuditedTarget.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/unidirectional/RelationNotAuditedTarget.java index a2f5592cc7..9b701d4da7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/unidirectional/RelationNotAuditedTarget.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytoone/unidirectional/RelationNotAuditedTarget.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.manytoone.unidirectional; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.Hibernate; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -37,6 +35,8 @@ import org.hibernate.envers.test.entities.manytoone.unidirectional.TargetNotAudi import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.HibernateProxyHelper; +import org.junit.Test; + /** * @author Tomasz Bech */ @@ -49,69 +49,69 @@ public class RelationNotAuditedTarget extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { TargetNotAuditedEntity.class, UnversionedStrTestEntity.class }; + return new Class[] {TargetNotAuditedEntity.class, UnversionedStrTestEntity.class}; } @Test - @Priority(10) + @Priority(10) public void initData() { EntityManager em = getEntityManager(); - UnversionedStrTestEntity uste1 = new UnversionedStrTestEntity("str1"); - UnversionedStrTestEntity uste2 = new UnversionedStrTestEntity("str2"); + UnversionedStrTestEntity uste1 = new UnversionedStrTestEntity( "str1" ); + UnversionedStrTestEntity uste2 = new UnversionedStrTestEntity( "str2" ); // No revision em.getTransaction().begin(); - em.persist(uste1); - em.persist(uste2); + em.persist( uste1 ); + em.persist( uste2 ); em.getTransaction().commit(); // Revision 1 em.getTransaction().begin(); - uste1 = em.find(UnversionedStrTestEntity.class, uste1.getId()); - uste2 = em.find(UnversionedStrTestEntity.class, uste2.getId()); + uste1 = em.find( UnversionedStrTestEntity.class, uste1.getId() ); + uste2 = em.find( UnversionedStrTestEntity.class, uste2.getId() ); - TargetNotAuditedEntity tnae1 = new TargetNotAuditedEntity(1, "tnae1", uste1); - TargetNotAuditedEntity tnae2 = new TargetNotAuditedEntity(2, "tnae2", uste2); - em.persist(tnae1); - em.persist(tnae2); + TargetNotAuditedEntity tnae1 = new TargetNotAuditedEntity( 1, "tnae1", uste1 ); + TargetNotAuditedEntity tnae2 = new TargetNotAuditedEntity( 2, "tnae2", uste2 ); + em.persist( tnae1 ); + em.persist( tnae2 ); em.getTransaction().commit(); // Revision 2 em.getTransaction().begin(); - tnae1 = em.find(TargetNotAuditedEntity.class, tnae1.getId()); - tnae2 = em.find(TargetNotAuditedEntity.class, tnae2.getId()); + tnae1 = em.find( TargetNotAuditedEntity.class, tnae1.getId() ); + tnae2 = em.find( TargetNotAuditedEntity.class, tnae2.getId() ); - tnae1.setReference(uste2); - tnae2.setReference(uste1); + tnae1.setReference( uste2 ); + tnae2.setReference( uste1 ); em.getTransaction().commit(); // Revision 3 em.getTransaction().begin(); - tnae1 = em.find(TargetNotAuditedEntity.class, tnae1.getId()); - tnae2 = em.find(TargetNotAuditedEntity.class, tnae2.getId()); + tnae1 = em.find( TargetNotAuditedEntity.class, tnae1.getId() ); + tnae2 = em.find( TargetNotAuditedEntity.class, tnae2.getId() ); //field not changed!!! - tnae1.setReference(uste2); - tnae2.setReference(uste2); + tnae1.setReference( uste2 ); + tnae2.setReference( uste2 ); em.getTransaction().commit(); // Revision 4 em.getTransaction().begin(); - tnae1 = em.find(TargetNotAuditedEntity.class, tnae1.getId()); - tnae2 = em.find(TargetNotAuditedEntity.class, tnae2.getId()); + tnae1 = em.find( TargetNotAuditedEntity.class, tnae1.getId() ); + tnae2 = em.find( TargetNotAuditedEntity.class, tnae2.getId() ); - tnae1.setReference(uste1); - tnae2.setReference(uste1); + tnae1.setReference( uste1 ); + tnae2.setReference( uste1 ); em.getTransaction().commit(); @@ -124,49 +124,49 @@ public class RelationNotAuditedTarget extends BaseEnversJPAFunctionalTestCase { @Test public void testRevisionsCounts() { - List revisions = getAuditReader().getRevisions(TargetNotAuditedEntity.class, tnae1_id); - assert Arrays.asList(1, 2, 4).equals(revisions); - revisions = getAuditReader().getRevisions(TargetNotAuditedEntity.class, tnae2_id); - assert Arrays.asList(1, 2, 3, 4).equals(revisions); + List revisions = getAuditReader().getRevisions( TargetNotAuditedEntity.class, tnae1_id ); + assert Arrays.asList( 1, 2, 4 ).equals( revisions ); + revisions = getAuditReader().getRevisions( TargetNotAuditedEntity.class, tnae2_id ); + assert Arrays.asList( 1, 2, 3, 4 ).equals( revisions ); } @Test public void testHistoryOfTnae1_id() { // load original "tnae1" TargetNotAuditedEntity to force load "str1" UnversionedStrTestEntity as Proxy - TargetNotAuditedEntity original = getEntityManager().find(TargetNotAuditedEntity.class, tnae1_id); + TargetNotAuditedEntity original = getEntityManager().find( TargetNotAuditedEntity.class, tnae1_id ); - UnversionedStrTestEntity uste1 = getEntityManager().find(UnversionedStrTestEntity.class, uste1_id); - UnversionedStrTestEntity uste2 = getEntityManager().find(UnversionedStrTestEntity.class, uste2_id); + UnversionedStrTestEntity uste1 = getEntityManager().find( UnversionedStrTestEntity.class, uste1_id ); + UnversionedStrTestEntity uste2 = getEntityManager().find( UnversionedStrTestEntity.class, uste2_id ); - TargetNotAuditedEntity rev1 = getAuditReader().find(TargetNotAuditedEntity.class, tnae1_id, 1); - TargetNotAuditedEntity rev2 = getAuditReader().find(TargetNotAuditedEntity.class, tnae1_id, 2); - TargetNotAuditedEntity rev3 = getAuditReader().find(TargetNotAuditedEntity.class, tnae1_id, 3); - TargetNotAuditedEntity rev4 = getAuditReader().find(TargetNotAuditedEntity.class, tnae1_id, 4); + TargetNotAuditedEntity rev1 = getAuditReader().find( TargetNotAuditedEntity.class, tnae1_id, 1 ); + TargetNotAuditedEntity rev2 = getAuditReader().find( TargetNotAuditedEntity.class, tnae1_id, 2 ); + TargetNotAuditedEntity rev3 = getAuditReader().find( TargetNotAuditedEntity.class, tnae1_id, 3 ); + TargetNotAuditedEntity rev4 = getAuditReader().find( TargetNotAuditedEntity.class, tnae1_id, 4 ); - assert rev1.getReference().equals(uste1); - assert rev2.getReference().equals(uste2); - assert rev3.getReference().equals(uste2); - assert rev4.getReference().equals(uste1); + assert rev1.getReference().equals( uste1 ); + assert rev2.getReference().equals( uste2 ); + assert rev3.getReference().equals( uste2 ); + assert rev4.getReference().equals( uste1 ); assert original.getReference() instanceof HibernateProxy; - assert UnversionedStrTestEntity.class.equals(Hibernate.getClass(original.getReference())); - assert UnversionedStrTestEntity.class.equals(HibernateProxyHelper.getClassWithoutInitializingProxy(rev1.getReference())); - assert UnversionedStrTestEntity.class.equals(Hibernate.getClass(rev1.getReference())); + assert UnversionedStrTestEntity.class.equals( Hibernate.getClass( original.getReference() ) ); + assert UnversionedStrTestEntity.class.equals( HibernateProxyHelper.getClassWithoutInitializingProxy( rev1.getReference() ) ); + assert UnversionedStrTestEntity.class.equals( Hibernate.getClass( rev1.getReference() ) ); } @Test public void testHistoryOfTnae2_id() { - UnversionedStrTestEntity uste1 = getEntityManager().find(UnversionedStrTestEntity.class, uste1_id); - UnversionedStrTestEntity uste2 = getEntityManager().find(UnversionedStrTestEntity.class, uste2_id); + UnversionedStrTestEntity uste1 = getEntityManager().find( UnversionedStrTestEntity.class, uste1_id ); + UnversionedStrTestEntity uste2 = getEntityManager().find( UnversionedStrTestEntity.class, uste2_id ); - TargetNotAuditedEntity rev1 = getAuditReader().find(TargetNotAuditedEntity.class, tnae2_id, 1); - TargetNotAuditedEntity rev2 = getAuditReader().find(TargetNotAuditedEntity.class, tnae2_id, 2); - TargetNotAuditedEntity rev3 = getAuditReader().find(TargetNotAuditedEntity.class, tnae2_id, 3); - TargetNotAuditedEntity rev4 = getAuditReader().find(TargetNotAuditedEntity.class, tnae2_id, 4); + TargetNotAuditedEntity rev1 = getAuditReader().find( TargetNotAuditedEntity.class, tnae2_id, 1 ); + TargetNotAuditedEntity rev2 = getAuditReader().find( TargetNotAuditedEntity.class, tnae2_id, 2 ); + TargetNotAuditedEntity rev3 = getAuditReader().find( TargetNotAuditedEntity.class, tnae2_id, 3 ); + TargetNotAuditedEntity rev4 = getAuditReader().find( TargetNotAuditedEntity.class, tnae2_id, 4 ); - assert rev1.getReference().equals(uste2); - assert rev2.getReference().equals(uste1); - assert rev3.getReference().equals(uste2); - assert rev4.getReference().equals(uste1); + assert rev1.getReference().equals( uste2 ); + assert rev2.getReference().equals( uste1 ); + assert rev3.getReference().equals( uste2 ); + assert rev4.getReference().equals( uste1 ); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/merge/AddDelTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/merge/AddDelTest.java index fc0530472e..b7afd264cb 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/merge/AddDelTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/merge/AddDelTest.java @@ -2,13 +2,14 @@ package org.hibernate.envers.test.integration.merge; import java.util.Arrays; -import org.junit.Assert; -import org.junit.Test; - import org.hibernate.Session; import org.hibernate.envers.test.BaseEnversFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -16,53 +17,59 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-6753") public class AddDelTest extends BaseEnversFunctionalTestCase { - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{StrTestEntity.class, GivenIdStrEntity.class}; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {StrTestEntity.class, GivenIdStrEntity.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - Session session = openSession(); - session.getTransaction().begin(); - GivenIdStrEntity entity = new GivenIdStrEntity(1, "data"); - session.persist(entity); - session.getTransaction().commit(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + Session session = openSession(); + session.getTransaction().begin(); + GivenIdStrEntity entity = new GivenIdStrEntity( 1, "data" ); + session.persist( entity ); + session.getTransaction().commit(); - // Revision 2 - session.getTransaction().begin(); - session.persist(new StrTestEntity("another data")); // Just to create second revision. - entity = (GivenIdStrEntity) session.get(GivenIdStrEntity.class, 1); - session.delete(entity); // First try to remove the entity. - session.save(entity); // Then save it. - session.getTransaction().commit(); + // Revision 2 + session.getTransaction().begin(); + session.persist( new StrTestEntity( "another data" ) ); // Just to create second revision. + entity = (GivenIdStrEntity) session.get( GivenIdStrEntity.class, 1 ); + session.delete( entity ); // First try to remove the entity. + session.save( entity ); // Then save it. + session.getTransaction().commit(); - // Revision 3 - session.getTransaction().begin(); - entity = (GivenIdStrEntity) session.get(GivenIdStrEntity.class, 1); - session.delete(entity); // First try to remove the entity. - entity.setData("modified data"); // Then change it's state. - session.save(entity); // Finally save it. - session.getTransaction().commit(); + // Revision 3 + session.getTransaction().begin(); + entity = (GivenIdStrEntity) session.get( GivenIdStrEntity.class, 1 ); + session.delete( entity ); // First try to remove the entity. + entity.setData( "modified data" ); // Then change it's state. + session.save( entity ); // Finally save it. + session.getTransaction().commit(); - session.close(); - } + session.close(); + } - @Test - public void testRevisionsCountOfGivenIdStrEntity() { - // Revision 2 has not changed entity's state. - Assert.assertEquals(Arrays.asList(1, 3), getAuditReader().getRevisions(GivenIdStrEntity.class, 1)); + @Test + public void testRevisionsCountOfGivenIdStrEntity() { + // Revision 2 has not changed entity's state. + Assert.assertEquals( Arrays.asList( 1, 3 ), getAuditReader().getRevisions( GivenIdStrEntity.class, 1 ) ); - getSession().close(); - } + getSession().close(); + } - @Test - public void testHistoryOfGivenIdStrEntity() { - Assert.assertEquals(new GivenIdStrEntity(1, "data"), getAuditReader().find(GivenIdStrEntity.class, 1, 1)); - Assert.assertEquals(new GivenIdStrEntity(1, "modified data"), getAuditReader().find(GivenIdStrEntity.class, 1, 3)); + @Test + public void testHistoryOfGivenIdStrEntity() { + Assert.assertEquals( new GivenIdStrEntity( 1, "data" ), getAuditReader().find( GivenIdStrEntity.class, 1, 1 ) ); + Assert.assertEquals( + new GivenIdStrEntity( 1, "modified data" ), getAuditReader().find( + GivenIdStrEntity.class, + 1, + 3 + ) + ); - getSession().close(); - } + getSession().close(); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/merge/GivenIdStrEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/merge/GivenIdStrEntity.java index 9981928b2d..4ce7415928 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/merge/GivenIdStrEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/merge/GivenIdStrEntity.java @@ -13,57 +13,65 @@ import org.hibernate.envers.Audited; @Audited @AuditTable("GIVENIDSTRENTITY_AUD") public class GivenIdStrEntity { - @Id - private Integer id; + @Id + private Integer id; - private String data; + private String data; - public GivenIdStrEntity() { - } + public GivenIdStrEntity() { + } - public GivenIdStrEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public GivenIdStrEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof GivenIdStrEntity)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof GivenIdStrEntity) ) { + return false; + } - GivenIdStrEntity that = (GivenIdStrEntity) o; + GivenIdStrEntity that = (GivenIdStrEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "GivenIdStrEntity(id = " + id + ", data = " + data + ")"; - } + @Override + public String toString() { + return "GivenIdStrEntity(id = " + id + ", data = " + data + ")"; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/AbstractModifiedFlagsEntityTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/AbstractModifiedFlagsEntityTest.java index 59998f8ad5..ad6ffe2c36 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/AbstractModifiedFlagsEntityTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/AbstractModifiedFlagsEntityTest.java @@ -33,15 +33,15 @@ import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; /** * Base test for modified flags feature - * + * * @author Michal Skowronek (mskowr at o2 dot pl) */ public abstract class AbstractModifiedFlagsEntityTest extends BaseEnversJPAFunctionalTestCase { @Override protected void addConfigOptions(Map options) { - super.addConfigOptions(options); - if (forceModifiedFlags()) { - options.put(EnversSettings.GLOBAL_WITH_MODIFIED_FLAG, "true"); + super.addConfigOptions( options ); + if ( forceModifiedFlags() ) { + options.put( EnversSettings.GLOBAL_WITH_MODIFIED_FLAG, "true" ); } } @@ -49,52 +49,58 @@ public abstract class AbstractModifiedFlagsEntityTest extends BaseEnversJPAFunct return true; } - protected List queryForPropertyHasChanged(Class clazz, Object id, - String... propertyNames) { - AuditQuery query = createForRevisionsQuery(clazz, id, false); - addHasChangedProperties(query, propertyNames); + protected List queryForPropertyHasChanged( + Class clazz, Object id, + String... propertyNames) { + AuditQuery query = createForRevisionsQuery( clazz, id, false ); + addHasChangedProperties( query, propertyNames ); return query.getResultList(); } - protected List queryForPropertyHasChangedWithDeleted(Class clazz, Object id, - String... propertyNames) { - AuditQuery query = createForRevisionsQuery(clazz, id, true); - addHasChangedProperties(query, propertyNames); + protected List queryForPropertyHasChangedWithDeleted( + Class clazz, Object id, + String... propertyNames) { + AuditQuery query = createForRevisionsQuery( clazz, id, true ); + addHasChangedProperties( query, propertyNames ); return query.getResultList(); } - protected List queryForPropertyHasNotChanged(Class clazz, Object id, - String... propertyNames) { - AuditQuery query = createForRevisionsQuery(clazz, id, false); - addHasNotChangedProperties(query, propertyNames); + protected List queryForPropertyHasNotChanged( + Class clazz, Object id, + String... propertyNames) { + AuditQuery query = createForRevisionsQuery( clazz, id, false ); + addHasNotChangedProperties( query, propertyNames ); return query.getResultList(); } - protected List queryForPropertyHasNotChangedWithDeleted(Class clazz, Object id, - String... propertyNames) { - AuditQuery query = createForRevisionsQuery(clazz, id, true); - addHasNotChangedProperties(query, propertyNames); + protected List queryForPropertyHasNotChangedWithDeleted( + Class clazz, Object id, + String... propertyNames) { + AuditQuery query = createForRevisionsQuery( clazz, id, true ); + addHasNotChangedProperties( query, propertyNames ); return query.getResultList(); } - private void addHasChangedProperties(AuditQuery query, - String[] propertyNames) { - for (String propertyName : propertyNames) { - query.add(AuditEntity.property(propertyName).hasChanged()); + private void addHasChangedProperties( + AuditQuery query, + String[] propertyNames) { + for ( String propertyName : propertyNames ) { + query.add( AuditEntity.property( propertyName ).hasChanged() ); } } - private void addHasNotChangedProperties(AuditQuery query, - String[] propertyNames) { - for (String propertyName : propertyNames) { - query.add(AuditEntity.property(propertyName).hasNotChanged()); + private void addHasNotChangedProperties( + AuditQuery query, + String[] propertyNames) { + for ( String propertyName : propertyNames ) { + query.add( AuditEntity.property( propertyName ).hasNotChanged() ); } } private AuditQuery createForRevisionsQuery(Class clazz, Object id, boolean withDeleted) { return getAuditReader().createQuery() - .forRevisionsOfEntity(clazz, false, withDeleted) - .add(AuditEntity.id().eq(id)); + .forRevisionsOfEntity( clazz, false, withDeleted ) + .add( AuditEntity.id().eq( id ) ); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/AbstractModifiedFlagsOneSessionTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/AbstractModifiedFlagsOneSessionTest.java index 48372fbead..dd605196f6 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/AbstractModifiedFlagsOneSessionTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/AbstractModifiedFlagsOneSessionTest.java @@ -29,17 +29,17 @@ import org.hibernate.envers.test.AbstractOneSessionTest; /** * Base test for modified flags feature - * + * * @author Michal Skowronek (mskowr at o2 dot pl) */ public abstract class AbstractModifiedFlagsOneSessionTest extends - AbstractOneSessionTest { + AbstractOneSessionTest { @Override protected void addProperties(Configuration configuration) { - super.addProperties(configuration); - if (forceModifiedFlags()) { - configuration.setProperty(EnversSettings.GLOBAL_WITH_MODIFIED_FLAG, "true"); + super.addProperties( configuration ); + if ( forceModifiedFlags() ) { + configuration.setProperty( EnversSettings.GLOBAL_WITH_MODIFIED_FLAG, "true" ); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedAPITest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedAPITest.java index c8653307c3..88dcc2bbae 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedAPITest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedAPITest.java @@ -23,63 +23,63 @@ */ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.query.AuditEntity; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.auditReader.AuditedTestEntity; import org.hibernate.envers.test.integration.auditReader.NotAuditedTestEntity; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; /** * A test which checks the correct behavior of AuditReader.isEntityClassAudited(Class entityClass). - * + * * @author Hernan Chanfreau * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedAPITest extends AbstractModifiedFlagsEntityTest { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { AuditedTestEntity.class, NotAuditedTestEntity.class }; - } + return new Class[] {AuditedTestEntity.class, NotAuditedTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - AuditedTestEntity ent1 = new AuditedTestEntity(1, "str1"); - NotAuditedTestEntity ent2 = new NotAuditedTestEntity(1, "str1"); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + AuditedTestEntity ent1 = new AuditedTestEntity( 1, "str1" ); + NotAuditedTestEntity ent2 = new NotAuditedTestEntity( 1, "str1" ); - em.persist(ent1); - em.persist(ent2); - em.getTransaction().commit(); + em.persist( ent1 ); + em.persist( ent2 ); + em.getTransaction().commit(); - em.getTransaction().begin(); + em.getTransaction().begin(); - ent1 = em.find(AuditedTestEntity.class, 1); - ent2 = em.find(NotAuditedTestEntity.class, 1); - ent1.setStr1("str2"); - ent2.setStr1("str2"); - em.getTransaction().commit(); - } + ent1 = em.find( AuditedTestEntity.class, 1 ); + ent2 = em.find( NotAuditedTestEntity.class, 1 ); + ent1.setStr1( "str2" ); + ent2.setStr1( "str2" ); + em.getTransaction().commit(); + } - @Test + @Test public void testHasChangedHasNotChangedCriteria() throws Exception { - List list = getAuditReader().createQuery().forRevisionsOfEntity(AuditedTestEntity.class, true, true) - .add(AuditEntity.property("str1").hasChanged()).getResultList(); - assertEquals(2, list.size()); - assertEquals("str1", ((AuditedTestEntity) list.get(0)).getStr1()); - assertEquals("str2", ((AuditedTestEntity) list.get(1)).getStr1()); + List list = getAuditReader().createQuery().forRevisionsOfEntity( AuditedTestEntity.class, true, true ) + .add( AuditEntity.property( "str1" ).hasChanged() ).getResultList(); + assertEquals( 2, list.size() ); + assertEquals( "str1", ((AuditedTestEntity) list.get( 0 )).getStr1() ); + assertEquals( "str2", ((AuditedTestEntity) list.get( 1 )).getStr1() ); - list = getAuditReader().createQuery().forRevisionsOfEntity(AuditedTestEntity.class, true, true) - .add(AuditEntity.property("str1").hasNotChanged()).getResultList(); - assertTrue(list.isEmpty()); + list = getAuditReader().createQuery().forRevisionsOfEntity( AuditedTestEntity.class, true, true ) + .add( AuditEntity.property( "str1" ).hasNotChanged() ).getResultList(); + assertTrue( list.isEmpty() ); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedAuditedManyToManyTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedAuditedManyToManyTest.java index 6cbda2db5a..3df9dd68db 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedAuditedManyToManyTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedAuditedManyToManyTest.java @@ -6,14 +6,14 @@ import java.net.URL; import java.util.ArrayList; import java.util.List; -import org.junit.Test; - import org.hibernate.MappingException; import org.hibernate.envers.query.AuditEntity; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.entityNames.manyToManyAudited.Car; import org.hibernate.envers.test.integration.entityNames.manyToManyAudited.Person; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -21,9 +21,8 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; /** * @author Hernán Chanfreau * @author Michal Skowronek (mskowr at o2 dot pl) - * */ -public class HasChangedAuditedManyToManyTest extends AbstractModifiedFlagsOneSessionTest{ +public class HasChangedAuditedManyToManyTest extends AbstractModifiedFlagsOneSessionTest { private long id_car1; @@ -31,96 +30,98 @@ public class HasChangedAuditedManyToManyTest extends AbstractModifiedFlagsOneSes private long id_pers2; protected void initMappings() throws MappingException, URISyntaxException { - URL url = Thread.currentThread().getContextClassLoader().getResource("mappings/entityNames/manyToManyAudited/mappings.hbm.xml"); - config.addFile(new File(url.toURI())); + URL url = Thread.currentThread().getContextClassLoader().getResource( + "mappings/entityNames/manyToManyAudited/mappings.hbm.xml" + ); + config.addFile( new File( url.toURI() ) ); } - @Test - @Priority(10) - public void initData() { - - initializeSession(); + @Test + @Priority(10) + public void initData() { - Person pers1 = new Person("Hernan", 28); - Person pers2 = new Person("Leandro", 29); - Person pers3 = new Person("Barba", 32); - Person pers4 = new Person("Camomo", 15); + initializeSession(); - //REV 1 - getSession().getTransaction().begin(); - List owners = new ArrayList(); - owners.add(pers1); - owners.add(pers2); - owners.add(pers3); - Car car1 = new Car(5, owners); + Person pers1 = new Person( "Hernan", 28 ); + Person pers2 = new Person( "Leandro", 29 ); + Person pers3 = new Person( "Barba", 32 ); + Person pers4 = new Person( "Camomo", 15 ); - getSession().persist(car1); - getSession().getTransaction().commit(); - id_pers1 = pers1.getId(); - id_car1 = car1.getId(); + //REV 1 + getSession().getTransaction().begin(); + List owners = new ArrayList(); + owners.add( pers1 ); + owners.add( pers2 ); + owners.add( pers3 ); + Car car1 = new Car( 5, owners ); + + getSession().persist( car1 ); + getSession().getTransaction().commit(); + id_pers1 = pers1.getId(); + id_car1 = car1.getId(); id_pers2 = pers2.getId(); - owners = new ArrayList(); - owners.add(pers2); - owners.add(pers3); - owners.add(pers4); - Car car2 = new Car(27, owners); - //REV 2 - getSession().getTransaction().begin(); - Person person1 = (Person)getSession().get("Personaje", id_pers1); - person1.setName("Hernan David"); - person1.setAge(40); - getSession().persist(car1); - getSession().persist(car2); - getSession().getTransaction().commit(); + owners = new ArrayList(); + owners.add( pers2 ); + owners.add( pers3 ); + owners.add( pers4 ); + Car car2 = new Car( 27, owners ); + //REV 2 + getSession().getTransaction().begin(); + Person person1 = (Person) getSession().get( "Personaje", id_pers1 ); + person1.setName( "Hernan David" ); + person1.setAge( 40 ); + getSession().persist( car1 ); + getSession().persist( car2 ); + getSession().getTransaction().commit(); } @Test public void testHasChangedPerson1() throws Exception { - List list = getAuditReader().createQuery().forRevisionsOfEntity(Person.class, "Personaje", false, false) - .add(AuditEntity.id().eq(id_pers1)) - .add(AuditEntity.property("cars").hasChanged()) + List list = getAuditReader().createQuery().forRevisionsOfEntity( Person.class, "Personaje", false, false ) + .add( AuditEntity.id().eq( id_pers1 ) ) + .add( AuditEntity.property( "cars" ).hasChanged() ) .getResultList(); - assertEquals(1, list.size()); - assertEquals(makeList(1), extractRevisionNumbers(list)); + assertEquals( 1, list.size() ); + assertEquals( makeList( 1 ), extractRevisionNumbers( list ) ); - list = getAuditReader().createQuery().forRevisionsOfEntity(Person.class, "Personaje", false, false) - .add(AuditEntity.id().eq(id_pers1)) - .add(AuditEntity.property("cars").hasNotChanged()) + list = getAuditReader().createQuery().forRevisionsOfEntity( Person.class, "Personaje", false, false ) + .add( AuditEntity.id().eq( id_pers1 ) ) + .add( AuditEntity.property( "cars" ).hasNotChanged() ) .getResultList(); - assertEquals(1, list.size()); - assertEquals(makeList(2), extractRevisionNumbers(list)); + assertEquals( 1, list.size() ); + assertEquals( makeList( 2 ), extractRevisionNumbers( list ) ); } @Test public void testHasChangedPerson2() throws Exception { - List list = getAuditReader().createQuery().forRevisionsOfEntity(Person.class, "Personaje", false, false) - .add(AuditEntity.id().eq(id_pers2)) - .add(AuditEntity.property("cars").hasChanged()) + List list = getAuditReader().createQuery().forRevisionsOfEntity( Person.class, "Personaje", false, false ) + .add( AuditEntity.id().eq( id_pers2 ) ) + .add( AuditEntity.property( "cars" ).hasChanged() ) .getResultList(); - assertEquals(2, list.size()); - assertEquals(makeList(1, 2), extractRevisionNumbers(list)); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) ); - list = getAuditReader().createQuery().forRevisionsOfEntity(Person.class, "Personaje", false, false) - .add(AuditEntity.id().eq(id_pers2)) - .add(AuditEntity.property("cars").hasNotChanged()) + list = getAuditReader().createQuery().forRevisionsOfEntity( Person.class, "Personaje", false, false ) + .add( AuditEntity.id().eq( id_pers2 ) ) + .add( AuditEntity.property( "cars" ).hasNotChanged() ) .getResultList(); - assertEquals(0, list.size()); + assertEquals( 0, list.size() ); } @Test public void testHasChangedCar1() throws Exception { - List list = getAuditReader().createQuery().forRevisionsOfEntity(Car.class, false, false) - .add(AuditEntity.id().eq(id_car1)) - .add(AuditEntity.property("owners").hasChanged()) + List list = getAuditReader().createQuery().forRevisionsOfEntity( Car.class, false, false ) + .add( AuditEntity.id().eq( id_car1 ) ) + .add( AuditEntity.property( "owners" ).hasChanged() ) .getResultList(); - assertEquals(1, list.size()); - assertEquals(makeList(1), extractRevisionNumbers(list)); + assertEquals( 1, list.size() ); + assertEquals( makeList( 1 ), extractRevisionNumbers( list ) ); - list = getAuditReader().createQuery().forRevisionsOfEntity(Car.class, false, false) - .add(AuditEntity.id().eq(id_car1)) - .add(AuditEntity.property("owners").hasNotChanged()) + list = getAuditReader().createQuery().forRevisionsOfEntity( Car.class, false, false ) + .add( AuditEntity.id().eq( id_car1 ) ) + .add( AuditEntity.property( "owners" ).hasNotChanged() ) .getResultList(); - assertEquals(0, list.size()); + assertEquals( 0, list.size() ); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedBidirectional2.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedBidirectional2.java index 5b9c8d9873..77e0ceab75 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedBidirectional2.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedBidirectional2.java @@ -23,15 +23,15 @@ */ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.onetoone.bidirectional.BiRefEdEntity; import org.hibernate.envers.test.integration.onetoone.bidirectional.BiRefIngEntity; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -41,85 +41,89 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedBidirectional2 extends AbstractModifiedFlagsEntityTest { - private Integer ed1_id; - private Integer ed2_id; + private Integer ed1_id; + private Integer ed2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BiRefEdEntity.class, BiRefIngEntity.class }; - } + return new Class[] {BiRefEdEntity.class, BiRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - BiRefEdEntity ed1 = new BiRefEdEntity(1, "data_ed_1"); - BiRefEdEntity ed2 = new BiRefEdEntity(2, "data_ed_2"); + @Test + @Priority(10) + public void initData() { + BiRefEdEntity ed1 = new BiRefEdEntity( 1, "data_ed_1" ); + BiRefEdEntity ed2 = new BiRefEdEntity( 2, "data_ed_2" ); - BiRefIngEntity ing1 = new BiRefIngEntity(3, "data_ing_1"); - BiRefIngEntity ing2 = new BiRefIngEntity(4, "data_ing_2"); + BiRefIngEntity ing1 = new BiRefIngEntity( 3, "data_ing_1" ); + BiRefIngEntity ing2 = new BiRefIngEntity( 4, "data_ing_2" ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); + em.persist( ed1 ); + em.persist( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ed1 = em.find(BiRefEdEntity.class, ed1.getId()); + ed1 = em.find( BiRefEdEntity.class, ed1.getId() ); - ing1.setReference(ed1); + ing1.setReference( ed1 ); - em.persist(ing1); - em.persist(ing2); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - ed1 = em.find(BiRefEdEntity.class, ed1.getId()); - ing1 = em.find(BiRefIngEntity.class, ing1.getId()); - ing2 = em.find(BiRefIngEntity.class, ing2.getId()); + ed1 = em.find( BiRefEdEntity.class, ed1.getId() ); + ing1 = em.find( BiRefIngEntity.class, ing1.getId() ); + ing2 = em.find( BiRefIngEntity.class, ing2.getId() ); - ing1.setReference(null); - ing2.setReference(ed1); + ing1.setReference( null ); + ing2.setReference( ed1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); + // Revision 4 + em.getTransaction().begin(); - ed2 = em.find(BiRefEdEntity.class, ed2.getId()); - ing1 = em.find(BiRefIngEntity.class, ing1.getId()); - ing2 = em.find(BiRefIngEntity.class, ing2.getId()); + ed2 = em.find( BiRefEdEntity.class, ed2.getId() ); + ing1 = em.find( BiRefIngEntity.class, ing1.getId() ); + ing2 = em.find( BiRefIngEntity.class, ing2.getId() ); - ing1.setReference(ed2); - ing2.setReference(null); + ing1.setReference( ed2 ); + ing2.setReference( null ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); } @Test public void testHasChanged() throws Exception { - List list = queryForPropertyHasChanged(BiRefEdEntity.class, ed1_id, - "referencing"); - assertEquals(3, list.size()); - assertEquals(makeList(2, 3, 4), extractRevisionNumbers(list)); + List list = queryForPropertyHasChanged( + BiRefEdEntity.class, ed1_id, + "referencing" + ); + assertEquals( 3, list.size() ); + assertEquals( makeList( 2, 3, 4 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasChanged(BiRefEdEntity.class, ed2_id, - "referencing"); - assertEquals(1, list.size()); - assertEquals(makeList(4), extractRevisionNumbers(list)); + list = queryForPropertyHasChanged( + BiRefEdEntity.class, ed2_id, + "referencing" + ); + assertEquals( 1, list.size() ); + assertEquals( makeList( 4 ), extractRevisionNumbers( list ) ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedChildAuditing.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedChildAuditing.java index f32e8d5068..63aba97d17 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedChildAuditing.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedChildAuditing.java @@ -24,15 +24,15 @@ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.inheritance.joined.ChildEntity; import org.hibernate.envers.test.integration.inheritance.joined.ParentEntity; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -42,58 +42,58 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedChildAuditing extends AbstractModifiedFlagsEntityTest { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ChildEntity.class, ParentEntity.class }; - } + return new Class[] {ChildEntity.class, ParentEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - id1 = 1; + id1 = 1; - // Rev 1 - em.getTransaction().begin(); - ChildEntity ce = new ChildEntity(id1, "x", 1l); - em.persist(ce); - em.getTransaction().commit(); + // Rev 1 + em.getTransaction().begin(); + ChildEntity ce = new ChildEntity( id1, "x", 1l ); + em.persist( ce ); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); - ce = em.find(ChildEntity.class, id1); - ce.setData("y"); - ce.setNumVal(2l); - em.getTransaction().commit(); - } + // Rev 2 + em.getTransaction().begin(); + ce = em.find( ChildEntity.class, id1 ); + ce.setData( "y" ); + ce.setNumVal( 2l ); + em.getTransaction().commit(); + } @Test public void testChildHasChanged() throws Exception { - List list = queryForPropertyHasChanged(ChildEntity.class, id1, "data"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 2), extractRevisionNumbers(list)); + List list = queryForPropertyHasChanged( ChildEntity.class, id1, "data" ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasChanged(ChildEntity.class, id1, "numVal"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 2), extractRevisionNumbers(list)); + list = queryForPropertyHasChanged( ChildEntity.class, id1, "numVal" ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasNotChanged(ChildEntity.class, id1, "data"); - assertEquals(0, list.size()); + list = queryForPropertyHasNotChanged( ChildEntity.class, id1, "data" ); + assertEquals( 0, list.size() ); - list = queryForPropertyHasNotChanged(ChildEntity.class, id1, "numVal"); - assertEquals(0, list.size()); + list = queryForPropertyHasNotChanged( ChildEntity.class, id1, "numVal" ); + assertEquals( 0, list.size() ); } @Test public void testParentHasChanged() throws Exception { - List list = queryForPropertyHasChanged(ParentEntity.class, id1, "data"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 2), extractRevisionNumbers(list)); + List list = queryForPropertyHasChanged( ParentEntity.class, id1, "data" ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasNotChanged(ParentEntity.class, id1, "data"); - assertEquals(0, list.size()); + list = queryForPropertyHasNotChanged( ParentEntity.class, id1, "data" ); + assertEquals( 0, list.size() ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedChildReferencing.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedChildReferencing.java index 97c11022ba..7f631613c2 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedChildReferencing.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedChildReferencing.java @@ -24,16 +24,16 @@ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.inheritance.joined.childrelation.ChildIngEntity; import org.hibernate.envers.test.integration.inheritance.joined.childrelation.ParentNotIngEntity; import org.hibernate.envers.test.integration.inheritance.joined.childrelation.ReferencedEntity; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -43,70 +43,70 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedChildReferencing extends AbstractModifiedFlagsEntityTest { - private Integer re_id1; - private Integer re_id2; + private Integer re_id1; + private Integer re_id2; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ChildIngEntity.class, ParentNotIngEntity.class, ReferencedEntity.class }; - } + return new Class[] {ChildIngEntity.class, ParentNotIngEntity.class, ReferencedEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - re_id1 = 1; - re_id2 = 10; + re_id1 = 1; + re_id2 = 10; Integer c_id = 100; - // Rev 1 - em.getTransaction().begin(); + // Rev 1 + em.getTransaction().begin(); - ReferencedEntity re1 = new ReferencedEntity(re_id1); - em.persist(re1); + ReferencedEntity re1 = new ReferencedEntity( re_id1 ); + em.persist( re1 ); - ReferencedEntity re2 = new ReferencedEntity(re_id2); - em.persist(re2); + ReferencedEntity re2 = new ReferencedEntity( re_id2 ); + em.persist( re2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); + // Rev 2 + em.getTransaction().begin(); - re1 = em.find(ReferencedEntity.class, re_id1); + re1 = em.find( ReferencedEntity.class, re_id1 ); - ChildIngEntity cie = new ChildIngEntity(c_id, "y", 1l); - cie.setReferenced(re1); - em.persist(cie); - c_id = cie.getId(); + ChildIngEntity cie = new ChildIngEntity( c_id, "y", 1l ); + cie.setReferenced( re1 ); + em.persist( cie ); + c_id = cie.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 3 - em.getTransaction().begin(); + // Rev 3 + em.getTransaction().begin(); - re2 = em.find(ReferencedEntity.class, re_id2); - cie = em.find(ChildIngEntity.class, c_id); + re2 = em.find( ReferencedEntity.class, re_id2 ); + cie = em.find( ChildIngEntity.class, c_id ); - cie.setReferenced(re2); + cie.setReferenced( re2 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } @Test public void testReferencedEntityHasChanged() throws Exception { - List list = queryForPropertyHasChanged(ReferencedEntity.class, re_id1, "referencing"); - assertEquals(2, list.size()); - assertEquals(makeList(2, 3), extractRevisionNumbers(list)); + List list = queryForPropertyHasChanged( ReferencedEntity.class, re_id1, "referencing" ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 2, 3 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasNotChanged(ReferencedEntity.class, re_id1, "referencing"); - assertEquals(1, list.size()); // initially referencing collection is null - assertEquals(makeList(1), extractRevisionNumbers(list)); + list = queryForPropertyHasNotChanged( ReferencedEntity.class, re_id1, "referencing" ); + assertEquals( 1, list.size() ); // initially referencing collection is null + assertEquals( makeList( 1 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasChanged(ReferencedEntity.class, re_id2, "referencing"); - assertEquals(1, list.size()); - assertEquals(makeList(3), extractRevisionNumbers(list)); + list = queryForPropertyHasChanged( ReferencedEntity.class, re_id2, "referencing" ); + assertEquals( 1, list.size() ); + assertEquals( makeList( 3 ), extractRevisionNumbers( list ) ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedComponentCollection.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedComponentCollection.java index 29de8400cd..49db29119a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedComponentCollection.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedComponentCollection.java @@ -1,14 +1,15 @@ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.collection.EmbeddableListEntity1; import org.hibernate.envers.test.entities.components.Component3; import org.hibernate.envers.test.entities.components.Component4; + +import org.junit.Test; + import org.hibernate.testing.TestForIssue; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; @@ -18,7 +19,7 @@ import static org.junit.Assert.assertEquals; /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ -@TestForIssue( jiraKey = "HHH-6613" ) +@TestForIssue(jiraKey = "HHH-6613") public class HasChangedComponentCollection extends AbstractModifiedFlagsEntityTest { private Integer ele1_id = null; @@ -29,7 +30,7 @@ public class HasChangedComponentCollection extends AbstractModifiedFlagsEntityTe @Override protected Class[] getAnnotatedClasses() { - return new Class[] { EmbeddableListEntity1.class }; + return new Class[] {EmbeddableListEntity1.class}; } @Test diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedComponentMapKey.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedComponentMapKey.java index d66f46b00e..54909f5ea0 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedComponentMapKey.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedComponentMapKey.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.components.Component1; @@ -34,6 +32,8 @@ import org.hibernate.envers.test.entities.components.Component2; import org.hibernate.envers.test.entities.components.ComponentTestEntity; import org.hibernate.envers.test.integration.collection.mapkey.ComponentMapKeyEntity; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -43,83 +43,99 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedComponentMapKey extends AbstractModifiedFlagsEntityTest { - private Integer cmke_id; + private Integer cmke_id; - private Integer cte1_id; - private Integer cte2_id; + private Integer cte1_id; + private Integer cte2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ComponentMapKeyEntity.class, ComponentTestEntity.class }; - } + return new Class[] {ComponentMapKeyEntity.class, ComponentTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - ComponentMapKeyEntity imke = new ComponentMapKeyEntity(); + ComponentMapKeyEntity imke = new ComponentMapKeyEntity(); - // Revision 1 (intialy 1 mapping) - em.getTransaction().begin(); + // Revision 1 (intialy 1 mapping) + em.getTransaction().begin(); - ComponentTestEntity cte1 = new ComponentTestEntity(new Component1("x1", "y2"), new Component2("a1", "b2")); - ComponentTestEntity cte2 = new ComponentTestEntity(new Component1("x1", "y2"), new Component2("a1", "b2")); + ComponentTestEntity cte1 = new ComponentTestEntity( + new Component1( "x1", "y2" ), new Component2( + "a1", + "b2" + ) + ); + ComponentTestEntity cte2 = new ComponentTestEntity( + new Component1( "x1", "y2" ), new Component2( + "a1", + "b2" + ) + ); - em.persist(cte1); - em.persist(cte2); + em.persist( cte1 ); + em.persist( cte2 ); - imke.getIdmap().put(cte1.getComp1(), cte1); + imke.getIdmap().put( cte1.getComp1(), cte1 ); - em.persist(imke); + em.persist( imke ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (sse1: adding 1 mapping) - em.getTransaction().begin(); + // Revision 2 (sse1: adding 1 mapping) + em.getTransaction().begin(); - cte2 = em.find(ComponentTestEntity.class, cte2.getId()); - imke = em.find(ComponentMapKeyEntity.class, imke.getId()); + cte2 = em.find( ComponentTestEntity.class, cte2.getId() ); + imke = em.find( ComponentMapKeyEntity.class, imke.getId() ); - imke.getIdmap().put(cte2.getComp1(), cte2); + imke.getIdmap().put( cte2.getComp1(), cte2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - cmke_id = imke.getId(); + cmke_id = imke.getId(); - cte1_id = cte1.getId(); - cte2_id = cte2.getId(); - } + cte1_id = cte1.getId(); + cte2_id = cte2.getId(); + } @Test public void testHasChangedMapEntity() throws Exception { - List list = queryForPropertyHasChanged(ComponentMapKeyEntity.class, cmke_id, "idmap"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 2), extractRevisionNumbers(list)); + List list = queryForPropertyHasChanged( ComponentMapKeyEntity.class, cmke_id, "idmap" ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasNotChanged(ComponentMapKeyEntity.class, - cmke_id, "idmap"); - assertEquals(0, list.size()); + list = queryForPropertyHasNotChanged( + ComponentMapKeyEntity.class, + cmke_id, "idmap" + ); + assertEquals( 0, list.size() ); } @Test public void testHasChangedComponentEntity() throws Exception { - List list = queryForPropertyHasChanged(ComponentTestEntity.class, - cte1_id, "comp1"); - assertEquals(1, list.size()); - assertEquals(makeList(1), extractRevisionNumbers(list)); + List list = queryForPropertyHasChanged( + ComponentTestEntity.class, + cte1_id, "comp1" + ); + assertEquals( 1, list.size() ); + assertEquals( makeList( 1 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasNotChanged(ComponentTestEntity.class, cte1_id, - "comp1"); - assertEquals(0, list.size()); + list = queryForPropertyHasNotChanged( + ComponentTestEntity.class, cte1_id, + "comp1" + ); + assertEquals( 0, list.size() ); - list = queryForPropertyHasChanged(ComponentTestEntity.class, cte2_id, "comp1"); - assertEquals(1, list.size()); - assertEquals(makeList(1), extractRevisionNumbers(list)); + list = queryForPropertyHasChanged( ComponentTestEntity.class, cte2_id, "comp1" ); + assertEquals( 1, list.size() ); + assertEquals( makeList( 1 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasNotChanged(ComponentTestEntity.class, cte2_id, "comp1"); - assertEquals(0, list.size()); + list = queryForPropertyHasNotChanged( ComponentTestEntity.class, cte2_id, "comp1" ); + assertEquals( 0, list.size() ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedComponents.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedComponents.java index b1d5ecbd0d..f39023c8cb 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedComponents.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedComponents.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.QueryException; import org.hibernate.envers.test.Priority; @@ -35,6 +33,8 @@ import org.hibernate.envers.test.entities.components.Component2; import org.hibernate.envers.test.entities.components.ComponentTestEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -44,136 +44,151 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedComponents extends AbstractModifiedFlagsEntityTest { - private Integer id1; - private Integer id2; - private Integer id3; - private Integer id4; + private Integer id1; + private Integer id2; + private Integer id3; + private Integer id4; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ComponentTestEntity.class }; - } - - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - - ComponentTestEntity cte1 = new ComponentTestEntity(new Component1("a", "b"), new Component2("x", "y")); - ComponentTestEntity cte2 = new ComponentTestEntity(new Component1("a2", "b2"), new Component2("x2", "y2")); - ComponentTestEntity cte3 = new ComponentTestEntity(new Component1("a3", "b3"), new Component2("x3", "y3")); - ComponentTestEntity cte4 = new ComponentTestEntity(null, null); - - em.persist(cte1); - em.persist(cte2); - em.persist(cte3); - em.persist(cte4); - - em.getTransaction().commit(); - - // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); - - cte1 = em.find(ComponentTestEntity.class, cte1.getId()); - cte2 = em.find(ComponentTestEntity.class, cte2.getId()); - cte3 = em.find(ComponentTestEntity.class, cte3.getId()); - cte4 = em.find(ComponentTestEntity.class, cte4.getId()); - - cte1.setComp1(new Component1("a'", "b'")); - cte2.getComp1().setStr1("a2'"); - cte3.getComp2().setStr6("y3'"); - cte4.setComp1(new Component1()); - cte4.getComp1().setStr1("n"); - cte4.setComp2(new Component2()); - cte4.getComp2().setStr5("m"); - - em.getTransaction().commit(); - - // Revision 3 - em = getEntityManager(); - em.getTransaction().begin(); - - cte1 = em.find(ComponentTestEntity.class, cte1.getId()); - cte2 = em.find(ComponentTestEntity.class, cte2.getId()); - cte3 = em.find(ComponentTestEntity.class, cte3.getId()); - cte4 = em.find(ComponentTestEntity.class, cte4.getId()); - - cte1.setComp2(new Component2("x'", "y'")); - cte3.getComp1().setStr2("b3'"); - cte4.setComp1(null); - cte4.setComp2(null); - - em.getTransaction().commit(); - - // Revision 4 - em = getEntityManager(); - em.getTransaction().begin(); - - cte2 = em.find(ComponentTestEntity.class, cte2.getId()); - - em.remove(cte2); - - em.getTransaction().commit(); - - id1 = cte1.getId(); - id2 = cte2.getId(); - id3 = cte3.getId(); - id4 = cte4.getId(); - } + return new Class[] {ComponentTestEntity.class}; + } @Test - public void testModFlagProperties() { - assertEquals(TestTools.makeSet("comp1_MOD"), - TestTools.extractModProperties(getCfg().getClassMapping( - "org.hibernate.envers.test.entities.components.ComponentTestEntity_AUD"))); + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + + ComponentTestEntity cte1 = new ComponentTestEntity( new Component1( "a", "b" ), new Component2( "x", "y" ) ); + ComponentTestEntity cte2 = new ComponentTestEntity( + new Component1( "a2", "b2" ), new Component2( + "x2", + "y2" + ) + ); + ComponentTestEntity cte3 = new ComponentTestEntity( + new Component1( "a3", "b3" ), new Component2( + "x3", + "y3" + ) + ); + ComponentTestEntity cte4 = new ComponentTestEntity( null, null ); + + em.persist( cte1 ); + em.persist( cte2 ); + em.persist( cte3 ); + em.persist( cte4 ); + + em.getTransaction().commit(); + + // Revision 2 + em = getEntityManager(); + em.getTransaction().begin(); + + cte1 = em.find( ComponentTestEntity.class, cte1.getId() ); + cte2 = em.find( ComponentTestEntity.class, cte2.getId() ); + cte3 = em.find( ComponentTestEntity.class, cte3.getId() ); + cte4 = em.find( ComponentTestEntity.class, cte4.getId() ); + + cte1.setComp1( new Component1( "a'", "b'" ) ); + cte2.getComp1().setStr1( "a2'" ); + cte3.getComp2().setStr6( "y3'" ); + cte4.setComp1( new Component1() ); + cte4.getComp1().setStr1( "n" ); + cte4.setComp2( new Component2() ); + cte4.getComp2().setStr5( "m" ); + + em.getTransaction().commit(); + + // Revision 3 + em = getEntityManager(); + em.getTransaction().begin(); + + cte1 = em.find( ComponentTestEntity.class, cte1.getId() ); + cte2 = em.find( ComponentTestEntity.class, cte2.getId() ); + cte3 = em.find( ComponentTestEntity.class, cte3.getId() ); + cte4 = em.find( ComponentTestEntity.class, cte4.getId() ); + + cte1.setComp2( new Component2( "x'", "y'" ) ); + cte3.getComp1().setStr2( "b3'" ); + cte4.setComp1( null ); + cte4.setComp2( null ); + + em.getTransaction().commit(); + + // Revision 4 + em = getEntityManager(); + em.getTransaction().begin(); + + cte2 = em.find( ComponentTestEntity.class, cte2.getId() ); + + em.remove( cte2 ); + + em.getTransaction().commit(); + + id1 = cte1.getId(); + id2 = cte2.getId(); + id3 = cte3.getId(); + id4 = cte4.getId(); + } + + @Test + public void testModFlagProperties() { + assertEquals( + TestTools.makeSet( "comp1_MOD" ), + TestTools.extractModProperties( + getCfg().getClassMapping( + "org.hibernate.envers.test.entities.components.ComponentTestEntity_AUD" + ) + ) + ); } @Test(expected = QueryException.class) public void testHasChangedNotAudited() throws Exception { - queryForPropertyHasChanged(ComponentTestEntity.class, id1, "comp2"); + queryForPropertyHasChanged( ComponentTestEntity.class, id1, "comp2" ); } @Test public void testHasChangedId1() throws Exception { - List list = queryForPropertyHasChanged(ComponentTestEntity.class, id1, "comp1"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 2), extractRevisionNumbers(list)); + List list = queryForPropertyHasChanged( ComponentTestEntity.class, id1, "comp1" ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasNotChanged(ComponentTestEntity.class, id1, "comp1"); - assertEquals(0, list.size()); + list = queryForPropertyHasNotChanged( ComponentTestEntity.class, id1, "comp1" ); + assertEquals( 0, list.size() ); } @Test public void testHasChangedId2() throws Exception { - List list = queryForPropertyHasChangedWithDeleted(ComponentTestEntity.class, id2, "comp1"); - assertEquals(3, list.size()); - assertEquals(makeList(1, 2, 4), extractRevisionNumbers(list)); + List list = queryForPropertyHasChangedWithDeleted( ComponentTestEntity.class, id2, "comp1" ); + assertEquals( 3, list.size() ); + assertEquals( makeList( 1, 2, 4 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasNotChangedWithDeleted(ComponentTestEntity.class, id2, "comp1"); - assertEquals(0, list.size()); + list = queryForPropertyHasNotChangedWithDeleted( ComponentTestEntity.class, id2, "comp1" ); + assertEquals( 0, list.size() ); } @Test public void testHasChangedId3() throws Exception { - List list = queryForPropertyHasChangedWithDeleted(ComponentTestEntity.class, id3, "comp1"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 3), extractRevisionNumbers(list)); + List list = queryForPropertyHasChangedWithDeleted( ComponentTestEntity.class, id3, "comp1" ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 3 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasNotChangedWithDeleted(ComponentTestEntity.class, id3, "comp1"); - assertEquals(0, list.size()); + list = queryForPropertyHasNotChangedWithDeleted( ComponentTestEntity.class, id3, "comp1" ); + assertEquals( 0, list.size() ); } @Test public void testHasChangedId4() throws Exception { - List list = queryForPropertyHasChangedWithDeleted(ComponentTestEntity.class, id4, "comp1"); - assertEquals(2, list.size()); - assertEquals(makeList(2, 3), extractRevisionNumbers(list)); + List list = queryForPropertyHasChangedWithDeleted( ComponentTestEntity.class, id4, "comp1" ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 2, 3 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasNotChangedWithDeleted(ComponentTestEntity.class, id4, "comp1"); - assertEquals(1, list.size()); - assertEquals(makeList(1), extractRevisionNumbers(list)); + list = queryForPropertyHasNotChangedWithDeleted( ComponentTestEntity.class, id4, "comp1" ); + assertEquals( 1, list.size() ); + assertEquals( makeList( 1 ), extractRevisionNumbers( list ) ); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedCompositeCustom.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedCompositeCustom.java index 5c58a93b54..902dfa1c5c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedCompositeCustom.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedCompositeCustom.java @@ -23,15 +23,15 @@ */ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.customtype.Component; import org.hibernate.envers.test.entities.customtype.CompositeCustomTypeEntity; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -41,59 +41,59 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedCompositeCustom extends AbstractModifiedFlagsEntityTest { - private Integer ccte_id; + private Integer ccte_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { CompositeCustomTypeEntity.class }; - } + return new Class[] {CompositeCustomTypeEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - CompositeCustomTypeEntity ccte = new CompositeCustomTypeEntity(); + CompositeCustomTypeEntity ccte = new CompositeCustomTypeEntity(); - // Revision 1 (persisting 1 entity) - em.getTransaction().begin(); + // Revision 1 (persisting 1 entity) + em.getTransaction().begin(); - ccte.setComponent(new Component("a", 1)); + ccte.setComponent( new Component( "a", 1 ) ); - em.persist(ccte); + em.persist( ccte ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (changing the component) - em.getTransaction().begin(); + // Revision 2 (changing the component) + em.getTransaction().begin(); - ccte = em.find(CompositeCustomTypeEntity.class, ccte.getId()); + ccte = em.find( CompositeCustomTypeEntity.class, ccte.getId() ); - ccte.getComponent().setProp1("b"); + ccte.getComponent().setProp1( "b" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 (replacing the component) - em.getTransaction().begin(); + // Revision 3 (replacing the component) + em.getTransaction().begin(); - ccte = em.find(CompositeCustomTypeEntity.class, ccte.getId()); + ccte = em.find( CompositeCustomTypeEntity.class, ccte.getId() ); - ccte.setComponent(new Component("c", 3)); + ccte.setComponent( new Component( "c", 3 ) ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ccte_id = ccte.getId(); - } + ccte_id = ccte.getId(); + } @Test public void testHasChanged() throws Exception { - List list = queryForPropertyHasChanged(CompositeCustomTypeEntity.class,ccte_id, "component"); - assertEquals(3, list.size()); - assertEquals(makeList(1, 2, 3), extractRevisionNumbers(list)); + List list = queryForPropertyHasChanged( CompositeCustomTypeEntity.class, ccte_id, "component" ); + assertEquals( 3, list.size() ); + assertEquals( makeList( 1, 2, 3 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasNotChanged(CompositeCustomTypeEntity.class,ccte_id, "component"); - assertEquals(0, list.size()); + list = queryForPropertyHasNotChanged( CompositeCustomTypeEntity.class, ccte_id, "component" ); + assertEquals( 0, list.size() ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedDetachedMultipleCollection.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedDetachedMultipleCollection.java index 7c6036b562..f0e3e3518b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedDetachedMultipleCollection.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedDetachedMultipleCollection.java @@ -1,16 +1,17 @@ package org.hibernate.envers.test.integration.modifiedflags; +import javax.persistence.EntityManager; import java.util.ArrayList; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.dialect.Oracle8iDialect; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.collection.MultipleCollectionEntity; import org.hibernate.envers.test.entities.collection.MultipleCollectionRefEntity1; import org.hibernate.envers.test.entities.collection.MultipleCollectionRefEntity2; + +import org.junit.Test; + import org.hibernate.testing.SkipForDialect; import org.hibernate.testing.TestForIssue; @@ -23,7 +24,7 @@ import static org.junit.Assert.assertEquals; */ @TestForIssue(jiraKey = "HHH-7437") @SkipForDialect(value = Oracle8iDialect.class, - comment = "Oracle does not support identity key generation") + comment = "Oracle does not support identity key generation") public class HasChangedDetachedMultipleCollection extends AbstractModifiedFlagsEntityTest { private Long mce1Id = null; private Long mce2Id = null; diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedDoubleJoinColumnBidirectionalList.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedDoubleJoinColumnBidirectionalList.java index 4bd2dca4d5..a37f6b98d2 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedDoubleJoinColumnBidirectionalList.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedDoubleJoinColumnBidirectionalList.java @@ -23,16 +23,16 @@ */ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.onetomany.detached.DoubleListJoinColumnBidirectionalRefEdEntity1; import org.hibernate.envers.test.entities.onetomany.detached.DoubleListJoinColumnBidirectionalRefEdEntity2; import org.hibernate.envers.test.entities.onetomany.detached.DoubleListJoinColumnBidirectionalRefIngEntity; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -40,17 +40,18 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; /** * Test for a double "fake" bidirectional mapping where one side uses @OneToMany+@JoinColumn * (and thus owns the relation), and the other uses a @ManyToOne(insertable=false, updatable=false). + * * @author Adam Warski (adam at warski dot org) * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedDoubleJoinColumnBidirectionalList extends AbstractModifiedFlagsEntityTest { - private Integer ed1_1_id; - private Integer ed2_1_id; - private Integer ed1_2_id; - private Integer ed2_2_id; + private Integer ed1_1_id; + private Integer ed2_1_id; + private Integer ed1_2_id; + private Integer ed2_2_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { @@ -59,205 +60,233 @@ public class HasChangedDoubleJoinColumnBidirectionalList extends AbstractModifie DoubleListJoinColumnBidirectionalRefEdEntity1.class, DoubleListJoinColumnBidirectionalRefEdEntity2.class }; - } + } - @Test - @Priority(10) - public void createData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void createData() { + EntityManager em = getEntityManager(); - DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_1 = new DoubleListJoinColumnBidirectionalRefEdEntity1("ed1_1", null); - DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_2 = new DoubleListJoinColumnBidirectionalRefEdEntity1("ed1_2", null); + DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_1 = new DoubleListJoinColumnBidirectionalRefEdEntity1( + "ed1_1", + null + ); + DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_2 = new DoubleListJoinColumnBidirectionalRefEdEntity1( + "ed1_2", + null + ); - DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_1 = new DoubleListJoinColumnBidirectionalRefEdEntity2("ed2_1", null); - DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_2 = new DoubleListJoinColumnBidirectionalRefEdEntity2("ed2_2", null); + DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_1 = new DoubleListJoinColumnBidirectionalRefEdEntity2( + "ed2_1", + null + ); + DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_2 = new DoubleListJoinColumnBidirectionalRefEdEntity2( + "ed2_2", + null + ); - DoubleListJoinColumnBidirectionalRefIngEntity ing1 = new DoubleListJoinColumnBidirectionalRefIngEntity("coll1"); - DoubleListJoinColumnBidirectionalRefIngEntity ing2 = new DoubleListJoinColumnBidirectionalRefIngEntity("coll2"); + DoubleListJoinColumnBidirectionalRefIngEntity ing1 = new DoubleListJoinColumnBidirectionalRefIngEntity( "coll1" ); + DoubleListJoinColumnBidirectionalRefIngEntity ing2 = new DoubleListJoinColumnBidirectionalRefIngEntity( "coll2" ); - // Revision 1 (ing1: ed1_1, ed2_1, ing2: ed1_2, ed2_2) - em.getTransaction().begin(); + // Revision 1 (ing1: ed1_1, ed2_1, ing2: ed1_2, ed2_2) + em.getTransaction().begin(); - ing1.getReferences1().add(ed1_1); - ing1.getReferences2().add(ed2_1); + ing1.getReferences1().add( ed1_1 ); + ing1.getReferences2().add( ed2_1 ); - ing2.getReferences1().add(ed1_2); - ing2.getReferences2().add(ed2_2); + ing2.getReferences1().add( ed1_2 ); + ing2.getReferences2().add( ed2_2 ); - em.persist(ed1_1); - em.persist(ed1_2); - em.persist(ed2_1); - em.persist(ed2_2); - em.persist(ing1); - em.persist(ing2); + em.persist( ed1_1 ); + em.persist( ed1_2 ); + em.persist( ed2_1 ); + em.persist( ed2_2 ); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (ing1: ed1_1, ed1_2, ed2_1, ed2_2) - em.getTransaction().begin(); + // Revision 2 (ing1: ed1_1, ed1_2, ed2_1, ed2_2) + em.getTransaction().begin(); - ing1 = em.find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1.getId()); - ing2 = em.find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2.getId()); - ed1_1 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1.getId()); - ed1_2 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2.getId()); - ed2_1 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1.getId()); - ed2_2 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2.getId()); + ing1 = em.find( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1.getId() ); + ing2 = em.find( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2.getId() ); + ed1_1 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1.getId() ); + ed1_2 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2.getId() ); + ed2_1 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1.getId() ); + ed2_2 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2.getId() ); - ing2.getReferences1().clear(); - ing2.getReferences2().clear(); + ing2.getReferences1().clear(); + ing2.getReferences2().clear(); - ing1.getReferences1().add(ed1_2); - ing1.getReferences2().add(ed2_2); + ing1.getReferences1().add( ed1_2 ); + ing1.getReferences2().add( ed2_2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 3 (ing1: ed1_1, ed1_2, ed2_1, ed2_2) - em.getTransaction().begin(); + // Revision 3 (ing1: ed1_1, ed1_2, ed2_1, ed2_2) + em.getTransaction().begin(); - ing1 = em.find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1.getId()); - ing2 = em.find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2.getId()); - ed1_1 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1.getId()); - ed1_2 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2.getId()); - ed2_1 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1.getId()); - ed2_2 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2.getId()); + ing1 = em.find( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1.getId() ); + ing2 = em.find( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2.getId() ); + ed1_1 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1.getId() ); + ed1_2 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2.getId() ); + ed2_1 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1.getId() ); + ed2_2 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2.getId() ); - ed1_1.setData("ed1_1 bis"); - ed2_2.setData("ed2_2 bis"); + ed1_1.setData( "ed1_1 bis" ); + ed2_2.setData( "ed2_2 bis" ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 4 (ing1: ed2_2, ing2: ed2_1, ed1_1, ed1_2) - em.getTransaction().begin(); + // Revision 4 (ing1: ed2_2, ing2: ed2_1, ed1_1, ed1_2) + em.getTransaction().begin(); - ing1 = em.find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1.getId()); - ing2 = em.find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2.getId()); - ed1_1 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1.getId()); - ed1_2 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2.getId()); - ed2_1 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1.getId()); - ed2_2 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2.getId()); + ing1 = em.find( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1.getId() ); + ing2 = em.find( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2.getId() ); + ed1_1 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1.getId() ); + ed1_2 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2.getId() ); + ed2_1 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1.getId() ); + ed2_2 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2.getId() ); - ing1.getReferences1().clear(); - ing2.getReferences1().add(ed1_1); - ing2.getReferences1().add(ed1_2); + ing1.getReferences1().clear(); + ing2.getReferences1().add( ed1_1 ); + ing2.getReferences1().add( ed1_2 ); - ing1.getReferences2().remove(ed2_1); - ing2.getReferences2().add(ed2_1); + ing1.getReferences2().remove( ed2_1 ); + ing2.getReferences2().add( ed2_1 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // + // - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); - ed1_1_id = ed1_1.getId(); - ed1_2_id = ed1_2.getId(); - ed2_1_id = ed2_1.getId(); - ed2_2_id = ed2_2.getId(); - } + ed1_1_id = ed1_1.getId(); + ed1_2_id = ed1_2.getId(); + ed2_1_id = ed2_1.getId(); + ed2_2_id = ed2_2.getId(); + } @Test public void testOwnerHasChanged() throws Exception { List list = queryForPropertyHasChanged( DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1_id, - "owner"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 4), extractRevisionNumbers(list)); + "owner" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 4 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasNotChanged( DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1_id, - "owner"); - assertEquals(1, list.size()); - assertEquals(makeList(3), extractRevisionNumbers(list)); + "owner" + ); + assertEquals( 1, list.size() ); + assertEquals( makeList( 3 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasChanged( DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2_id, - "owner"); - assertEquals(3, list.size()); - assertEquals(makeList(1, 2, 4), extractRevisionNumbers(list)); + "owner" + ); + assertEquals( 3, list.size() ); + assertEquals( makeList( 1, 2, 4 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasNotChanged( DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2_id, - "owner"); - assertEquals(0, list.size()); + "owner" + ); + assertEquals( 0, list.size() ); } @Test public void testOwnerSecEntityHasChanged() throws Exception { List list = queryForPropertyHasChanged( DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1_id, - "owner"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 4), extractRevisionNumbers(list)); + "owner" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 4 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasNotChanged( DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1_id, - "owner"); - assertEquals(0, list.size()); + "owner" + ); + assertEquals( 0, list.size() ); list = queryForPropertyHasChanged( DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2_id, - "owner"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 2), extractRevisionNumbers(list)); + "owner" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasNotChanged( DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2_id, - "owner"); - assertEquals(1, list.size()); - assertEquals(makeList(3), extractRevisionNumbers(list)); + "owner" + ); + assertEquals( 1, list.size() ); + assertEquals( makeList( 3 ), extractRevisionNumbers( list ) ); } @Test public void testReferences1HasChanged() throws Exception { List list = queryForPropertyHasChanged( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1_id, - "references1"); - assertEquals(3, list.size()); - assertEquals(makeList(1, 2, 4), extractRevisionNumbers(list)); + "references1" + ); + assertEquals( 3, list.size() ); + assertEquals( makeList( 1, 2, 4 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasChanged( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2_id, - "references1"); - assertEquals(3, list.size()); - assertEquals(makeList(1, 2, 4), extractRevisionNumbers(list)); + "references1" + ); + assertEquals( 3, list.size() ); + assertEquals( makeList( 1, 2, 4 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasNotChanged( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1_id, - "references1"); - assertEquals(0, list.size()); + "references1" + ); + assertEquals( 0, list.size() ); list = queryForPropertyHasNotChanged( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2_id, - "references1"); - assertEquals(0, list.size()); + "references1" + ); + assertEquals( 0, list.size() ); } @Test public void testReferences2HasChanged() throws Exception { List list = queryForPropertyHasChanged( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1_id, - "references2"); - assertEquals(3, list.size()); - assertEquals(makeList(1, 2, 4), extractRevisionNumbers(list)); + "references2" + ); + assertEquals( 3, list.size() ); + assertEquals( makeList( 1, 2, 4 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasChanged( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2_id, - "references2"); - assertEquals(3, list.size()); - assertEquals(makeList(1, 2, 4), extractRevisionNumbers(list)); + "references2" + ); + assertEquals( 3, list.size() ); + assertEquals( makeList( 1, 2, 4 ), extractRevisionNumbers( list ) ); list = queryForPropertyHasNotChanged( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1_id, - "references2"); - assertEquals(0, list.size()); + "references2" + ); + assertEquals( 0, list.size() ); list = queryForPropertyHasNotChanged( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2_id, - "references2"); - assertEquals(0, list.size()); + "references2" + ); + assertEquals( 0, list.size() ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedEnumSet.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedEnumSet.java index 56d73e839e..1a71085b58 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedEnumSet.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedEnumSet.java @@ -23,16 +23,16 @@ */ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.collection.EnumSetEntity; import org.hibernate.envers.test.entities.collection.EnumSetEntity.E1; import org.hibernate.envers.test.entities.collection.EnumSetEntity.E2; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -42,74 +42,82 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedEnumSet extends AbstractModifiedFlagsEntityTest { - private Integer sse1_id; + private Integer sse1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { EnumSetEntity.class }; - } + return new Class[] {EnumSetEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - EnumSetEntity sse1 = new EnumSetEntity(); + EnumSetEntity sse1 = new EnumSetEntity(); - // Revision 1 (sse1: initialy 1 element) - em.getTransaction().begin(); + // Revision 1 (sse1: initialy 1 element) + em.getTransaction().begin(); - sse1.getEnums1().add(E1.X); - sse1.getEnums2().add(E2.A); + sse1.getEnums1().add( E1.X ); + sse1.getEnums2().add( E2.A ); - em.persist(sse1); + em.persist( sse1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (sse1: adding 1 element/removing a non-existing element) - em.getTransaction().begin(); + // Revision 2 (sse1: adding 1 element/removing a non-existing element) + em.getTransaction().begin(); - sse1 = em.find(EnumSetEntity.class, sse1.getId()); + sse1 = em.find( EnumSetEntity.class, sse1.getId() ); - sse1.getEnums1().add(E1.Y); - sse1.getEnums2().remove(E2.B); + sse1.getEnums1().add( E1.Y ); + sse1.getEnums2().remove( E2.B ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 (sse1: removing 1 element/adding an exisiting element) - em.getTransaction().begin(); + // Revision 3 (sse1: removing 1 element/adding an exisiting element) + em.getTransaction().begin(); - sse1 = em.find(EnumSetEntity.class, sse1.getId()); + sse1 = em.find( EnumSetEntity.class, sse1.getId() ); - sse1.getEnums1().remove(E1.X); - sse1.getEnums2().add(E2.A); + sse1.getEnums1().remove( E1.X ); + sse1.getEnums2().add( E2.A ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - sse1_id = sse1.getId(); - } + sse1_id = sse1.getId(); + } @Test public void testHasChanged() throws Exception { - List list = queryForPropertyHasChanged(EnumSetEntity.class, sse1_id, - "enums1"); - assertEquals(3, list.size()); - assertEquals(makeList(1, 2, 3), extractRevisionNumbers(list)); + List list = queryForPropertyHasChanged( + EnumSetEntity.class, sse1_id, + "enums1" + ); + assertEquals( 3, list.size() ); + assertEquals( makeList( 1, 2, 3 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasChanged(EnumSetEntity.class, sse1_id, - "enums2"); - assertEquals(1, list.size()); - assertEquals(makeList(1), extractRevisionNumbers(list)); + list = queryForPropertyHasChanged( + EnumSetEntity.class, sse1_id, + "enums2" + ); + assertEquals( 1, list.size() ); + assertEquals( makeList( 1 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasNotChanged(EnumSetEntity.class, sse1_id, - "enums1"); - assertEquals(0, list.size()); + list = queryForPropertyHasNotChanged( + EnumSetEntity.class, sse1_id, + "enums1" + ); + assertEquals( 0, list.size() ); - list = queryForPropertyHasNotChanged(EnumSetEntity.class, sse1_id, - "enums2"); - assertEquals(2, list.size()); - assertEquals(makeList(2, 3), extractRevisionNumbers(list)); + list = queryForPropertyHasNotChanged( + EnumSetEntity.class, sse1_id, + "enums2" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 2, 3 ), extractRevisionNumbers( list ) ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedForDefaultNotUsing.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedForDefaultNotUsing.java index 0edee4e6ba..ce28305313 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedForDefaultNotUsing.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedForDefaultNotUsing.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.modifiedflags; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.QueryException; import org.hibernate.envers.test.Priority; @@ -37,6 +35,8 @@ import org.hibernate.envers.test.entities.components.Component2; import org.hibernate.envers.test.integration.modifiedflags.entities.PartialModifiedFlagsEntity; import org.hibernate.envers.test.integration.modifiedflags.entities.WithModifiedFlagReferencingEntity; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -55,219 +55,243 @@ public class HasChangedForDefaultNotUsing extends AbstractModifiedFlagsEntityTes @Override protected Class[] getAnnotatedClasses() { - return new Class[] { PartialModifiedFlagsEntity.class, WithModifiedFlagReferencingEntity.class, StrTestEntity.class }; - } + return new Class[] { + PartialModifiedFlagsEntity.class, + WithModifiedFlagReferencingEntity.class, + StrTestEntity.class + }; + } - @Test - @Priority(10) - public void initData() { + @Test + @Priority(10) + public void initData() { PartialModifiedFlagsEntity entity = - new PartialModifiedFlagsEntity(entityId); + new PartialModifiedFlagsEntity( entityId ); // Revision 1 EntityManager em = getEntityManager(); em.getTransaction().begin(); - em.persist(entity); + em.persist( entity ); em.getTransaction().commit(); // Revision 2 em.getTransaction().begin(); - entity.setData("data1"); - entity = em.merge(entity); + entity.setData( "data1" ); + entity = em.merge( entity ); em.getTransaction().commit(); // Revision 3 em.getTransaction().begin(); - entity.setComp1(new Component1("str1", "str2")); - entity = em.merge(entity); + entity.setComp1( new Component1( "str1", "str2" ) ); + entity = em.merge( entity ); em.getTransaction().commit(); // Revision 4 em.getTransaction().begin(); - entity.setComp2(new Component2("str1", "str2")); - entity = em.merge(entity); + entity.setComp2( new Component2( "str1", "str2" ) ); + entity = em.merge( entity ); em.getTransaction().commit(); // Revision 5 em.getTransaction().begin(); - WithModifiedFlagReferencingEntity withModifiedFlagReferencingEntity = new WithModifiedFlagReferencingEntity(refEntityId, "first"); - withModifiedFlagReferencingEntity.setReference(entity); - em.persist(withModifiedFlagReferencingEntity); + WithModifiedFlagReferencingEntity withModifiedFlagReferencingEntity = new WithModifiedFlagReferencingEntity( + refEntityId, + "first" + ); + withModifiedFlagReferencingEntity.setReference( entity ); + em.persist( withModifiedFlagReferencingEntity ); em.getTransaction().commit(); // Revision 6 em.getTransaction().begin(); - withModifiedFlagReferencingEntity = em.find(WithModifiedFlagReferencingEntity.class, refEntityId); - withModifiedFlagReferencingEntity.setReference(null); - withModifiedFlagReferencingEntity.setSecondReference(entity); - em.merge(withModifiedFlagReferencingEntity); + withModifiedFlagReferencingEntity = em.find( WithModifiedFlagReferencingEntity.class, refEntityId ); + withModifiedFlagReferencingEntity.setReference( null ); + withModifiedFlagReferencingEntity.setSecondReference( entity ); + em.merge( withModifiedFlagReferencingEntity ); em.getTransaction().commit(); // Revision 7 em.getTransaction().begin(); - entity.getStringSet().add("firstElement"); - entity.getStringSet().add("secondElement"); - entity = em.merge(entity); + entity.getStringSet().add( "firstElement" ); + entity.getStringSet().add( "secondElement" ); + entity = em.merge( entity ); em.getTransaction().commit(); // Revision 8 em.getTransaction().begin(); - entity.getStringSet().remove("secondElement"); - entity.getStringMap().put("someKey", "someValue"); - entity = em.merge(entity); + entity.getStringSet().remove( "secondElement" ); + entity.getStringMap().put( "someKey", "someValue" ); + entity = em.merge( entity ); em.getTransaction().commit(); // Revision 9 - main entity doesn't change em.getTransaction().begin(); - StrTestEntity strTestEntity = new StrTestEntity("first"); - em.persist(strTestEntity); + StrTestEntity strTestEntity = new StrTestEntity( "first" ); + em.persist( strTestEntity ); em.getTransaction().commit(); // Revision 10 em.getTransaction().begin(); - entity.getEntitiesSet().add(strTestEntity); - entity = em.merge(entity); + entity.getEntitiesSet().add( strTestEntity ); + entity = em.merge( entity ); em.getTransaction().commit(); // Revision 11 em.getTransaction().begin(); - entity.getEntitiesSet().remove(strTestEntity); - entity.getEntitiesMap().put("someKey", strTestEntity); - em.merge(entity); + entity.getEntitiesSet().remove( strTestEntity ); + entity.getEntitiesMap().put( "someKey", strTestEntity ); + em.merge( entity ); em.getTransaction().commit(); // Revision 12 - main entity doesn't change em.getTransaction().begin(); - strTestEntity.setStr("second"); - em.merge(strTestEntity); + strTestEntity.setStr( "second" ); + em.merge( strTestEntity ); em.getTransaction().commit(); } @Test - public void testRevisionsCounts() { - assertEquals(Arrays.asList((Number) 1, 2, 3, 4, 5, 6, 7, 8, 10, 11), + public void testRevisionsCounts() { + assertEquals( + Arrays.asList( (Number) 1, 2, 3, 4, 5, 6, 7, 8, 10, 11 ), getAuditReader() - .getRevisions(PartialModifiedFlagsEntity.class, - entityId)); - } + .getRevisions( + PartialModifiedFlagsEntity.class, + entityId + ) + ); + } @Test public void testHasChangedData() throws Exception { List list = queryForPropertyHasChanged( PartialModifiedFlagsEntity.class, - entityId, "data"); - assertEquals(1, list.size()); - assertEquals(makeList(2), extractRevisionNumbers(list)); + entityId, "data" + ); + assertEquals( 1, list.size() ); + assertEquals( makeList( 2 ), extractRevisionNumbers( list ) ); } @Test public void testHasChangedComp1() throws Exception { List list = queryForPropertyHasChanged( PartialModifiedFlagsEntity.class, - entityId, "comp1"); - assertEquals(1, list.size()); - assertEquals(makeList(3), extractRevisionNumbers(list)); + entityId, "comp1" + ); + assertEquals( 1, list.size() ); + assertEquals( makeList( 3 ), extractRevisionNumbers( list ) ); } @Test(expected = QueryException.class) public void testHasChangedComp2() throws Exception { - queryForPropertyHasChanged(PartialModifiedFlagsEntity.class, - entityId, "comp2"); + queryForPropertyHasChanged( + PartialModifiedFlagsEntity.class, + entityId, "comp2" + ); } @Test public void testHasChangedReferencing() throws Exception { List list = queryForPropertyHasChanged( PartialModifiedFlagsEntity.class, - entityId, "referencing"); - assertEquals(2, list.size()); - assertEquals(makeList(5, 6), extractRevisionNumbers(list)); + entityId, "referencing" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 5, 6 ), extractRevisionNumbers( list ) ); } @Test(expected = QueryException.class) public void testHasChangedReferencing2() throws Exception { - queryForPropertyHasChanged(PartialModifiedFlagsEntity.class, - entityId, "referencing2"); + queryForPropertyHasChanged( + PartialModifiedFlagsEntity.class, + entityId, "referencing2" + ); } @Test public void testHasChangedStringSet() throws Exception { List list = queryForPropertyHasChanged( PartialModifiedFlagsEntity.class, - entityId, "stringSet"); - assertEquals(3, list.size()); - assertEquals(makeList(1, 7, 8), extractRevisionNumbers(list)); + entityId, "stringSet" + ); + assertEquals( 3, list.size() ); + assertEquals( makeList( 1, 7, 8 ), extractRevisionNumbers( list ) ); } @Test public void testHasChangedStringMap() throws Exception { List list = queryForPropertyHasChanged( PartialModifiedFlagsEntity.class, - entityId, "stringMap"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 8), extractRevisionNumbers(list)); + entityId, "stringMap" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 8 ), extractRevisionNumbers( list ) ); } @Test public void testHasChangedStringSetAndMap() throws Exception { List list = queryForPropertyHasChanged( PartialModifiedFlagsEntity.class, - entityId, "stringSet", "stringMap"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 8), extractRevisionNumbers(list)); + entityId, "stringSet", "stringMap" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 8 ), extractRevisionNumbers( list ) ); } @Test public void testHasChangedEntitiesSet() throws Exception { List list = queryForPropertyHasChanged( PartialModifiedFlagsEntity.class, - entityId, "entitiesSet"); - assertEquals(3, list.size()); - assertEquals(makeList(1, 10, 11), extractRevisionNumbers(list)); + entityId, "entitiesSet" + ); + assertEquals( 3, list.size() ); + assertEquals( makeList( 1, 10, 11 ), extractRevisionNumbers( list ) ); } @Test public void testHasChangedEntitiesMap() throws Exception { List list = queryForPropertyHasChanged( PartialModifiedFlagsEntity.class, - entityId, "entitiesMap"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 11), extractRevisionNumbers(list)); + entityId, "entitiesMap" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 11 ), extractRevisionNumbers( list ) ); } @Test public void testHasChangedEntitiesSetAndMap() throws Exception { List list = queryForPropertyHasChanged( PartialModifiedFlagsEntity.class, - entityId, "entitiesSet", "entitiesMap"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 11), extractRevisionNumbers(list)); + entityId, "entitiesSet", "entitiesMap" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 11 ), extractRevisionNumbers( list ) ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedIdMapKey.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedIdMapKey.java index ba0dd857ba..1b8837dc7c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedIdMapKey.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedIdMapKey.java @@ -23,15 +23,15 @@ */ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.integration.collection.mapkey.IdMapKeyEntity; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -41,60 +41,64 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedIdMapKey extends AbstractModifiedFlagsEntityTest { - private Integer imke_id; + private Integer imke_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { IdMapKeyEntity.class, StrTestEntity.class }; - } + return new Class[] {IdMapKeyEntity.class, StrTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - IdMapKeyEntity imke = new IdMapKeyEntity(); + IdMapKeyEntity imke = new IdMapKeyEntity(); - // Revision 1 (intialy 1 mapping) - em.getTransaction().begin(); + // Revision 1 (intialy 1 mapping) + em.getTransaction().begin(); - StrTestEntity ste1 = new StrTestEntity("x"); - StrTestEntity ste2 = new StrTestEntity("y"); + StrTestEntity ste1 = new StrTestEntity( "x" ); + StrTestEntity ste2 = new StrTestEntity( "y" ); - em.persist(ste1); - em.persist(ste2); + em.persist( ste1 ); + em.persist( ste2 ); - imke.getIdmap().put(ste1.getId(), ste1); + imke.getIdmap().put( ste1.getId(), ste1 ); - em.persist(imke); + em.persist( imke ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (sse1: adding 1 mapping) - em.getTransaction().begin(); + // Revision 2 (sse1: adding 1 mapping) + em.getTransaction().begin(); - ste2 = em.find(StrTestEntity.class, ste2.getId()); - imke = em.find(IdMapKeyEntity.class, imke.getId()); + ste2 = em.find( StrTestEntity.class, ste2.getId() ); + imke = em.find( IdMapKeyEntity.class, imke.getId() ); - imke.getIdmap().put(ste2.getId(), ste2); + imke.getIdmap().put( ste2.getId(), ste2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - imke_id = imke.getId(); + imke_id = imke.getId(); } @Test public void testHasChanged() throws Exception { - List list = queryForPropertyHasChanged(IdMapKeyEntity.class, imke_id, - "idmap"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 2), extractRevisionNumbers(list)); + List list = queryForPropertyHasChanged( + IdMapKeyEntity.class, imke_id, + "idmap" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasNotChanged(IdMapKeyEntity.class, imke_id, - "idmap"); - assertEquals(0, list.size()); + list = queryForPropertyHasNotChanged( + IdMapKeyEntity.class, imke_id, + "idmap" + ); + assertEquals( 0, list.size() ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedManualFlush.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedManualFlush.java index b6d2630cad..153a7cef02 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedManualFlush.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedManualFlush.java @@ -1,12 +1,13 @@ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.basic.BasicTestEntity1; + +import org.junit.Test; + import org.hibernate.testing.TestForIssue; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; @@ -22,7 +23,7 @@ public class HasChangedManualFlush extends AbstractModifiedFlagsEntityTest { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BasicTestEntity1.class }; + return new Class[] {BasicTestEntity1.class}; } @Test diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedManyToOneInComponent.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedManyToOneInComponent.java index b0eeee997c..1a771185f9 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedManyToOneInComponent.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedManyToOneInComponent.java @@ -23,16 +23,16 @@ */ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.components.relations.ManyToOneComponent; import org.hibernate.envers.test.entities.components.relations.ManyToOneComponentTestEntity; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -42,63 +42,72 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedManyToOneInComponent extends AbstractModifiedFlagsEntityTest { - private Integer mtocte_id1; + private Integer mtocte_id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ManyToOneComponentTestEntity.class, StrTestEntity.class }; - } + return new Class[] {ManyToOneComponentTestEntity.class, StrTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); StrTestEntity ste1 = new StrTestEntity(); - ste1.setStr("str1"); + ste1.setStr( "str1" ); StrTestEntity ste2 = new StrTestEntity(); - ste2.setStr("str2"); + ste2.setStr( "str2" ); - em.persist(ste1); - em.persist(ste2); + em.persist( ste1 ); + em.persist( ste2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 2 + em = getEntityManager(); + em.getTransaction().begin(); - ManyToOneComponentTestEntity mtocte1 = new ManyToOneComponentTestEntity(new ManyToOneComponent(ste1, "data1")); + ManyToOneComponentTestEntity mtocte1 = new ManyToOneComponentTestEntity( + new ManyToOneComponent( + ste1, + "data1" + ) + ); - em.persist(mtocte1); + em.persist( mtocte1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 3 + em = getEntityManager(); + em.getTransaction().begin(); - mtocte1 = em.find(ManyToOneComponentTestEntity.class, mtocte1.getId()); - mtocte1.getComp1().setEntity(ste2); + mtocte1 = em.find( ManyToOneComponentTestEntity.class, mtocte1.getId() ); + mtocte1.getComp1().setEntity( ste2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - mtocte_id1 = mtocte1.getId(); + mtocte_id1 = mtocte1.getId(); } @Test public void testHasChangedId1() throws Exception { - List list = queryForPropertyHasChanged(ManyToOneComponentTestEntity.class, - mtocte_id1, "comp1"); - assertEquals(2, list.size()); - assertEquals(makeList(2, 3), extractRevisionNumbers(list)); + List list = queryForPropertyHasChanged( + ManyToOneComponentTestEntity.class, + mtocte_id1, "comp1" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 2, 3 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasNotChanged(ManyToOneComponentTestEntity.class, - mtocte_id1, "comp1"); - assertEquals(0, list.size()); + list = queryForPropertyHasNotChanged( + ManyToOneComponentTestEntity.class, + mtocte_id1, "comp1" + ); + assertEquals( 0, list.size() ); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedMergeTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedMergeTest.java index 6971ce9da4..5155eb5f5e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedMergeTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedMergeTest.java @@ -1,14 +1,15 @@ package org.hibernate.envers.test.integration.modifiedflags; +import javax.persistence.EntityManager; import java.util.ArrayList; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.onetomany.ListRefEdEntity; import org.hibernate.envers.test.entities.onetomany.ListRefIngEntity; + +import org.junit.Test; + import org.hibernate.testing.TestForIssue; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; @@ -27,7 +28,7 @@ public class HasChangedMergeTest extends AbstractModifiedFlagsEntityTest { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ListRefEdEntity.class, ListRefIngEntity.class }; + return new Class[] {ListRefEdEntity.class, ListRefIngEntity.class}; } @Test diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedNotOwnedBidirectional.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedNotOwnedBidirectional.java index 93d3c43962..1bb69c38a3 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedNotOwnedBidirectional.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedNotOwnedBidirectional.java @@ -24,16 +24,16 @@ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.inheritance.joined.notownedrelation.Address; import org.hibernate.envers.test.integration.inheritance.joined.notownedrelation.Contact; import org.hibernate.envers.test.integration.inheritance.joined.notownedrelation.PersonalContact; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -43,63 +43,65 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedNotOwnedBidirectional extends AbstractModifiedFlagsEntityTest { - private Long pc_id; - private Long a1_id; - private Long a2_id; + private Long pc_id; + private Long a1_id; + private Long a2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { Address.class, Contact.class, PersonalContact.class }; - } + return new Class[] {Address.class, Contact.class, PersonalContact.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - pc_id = 1l; - a1_id = 10l; - a2_id = 100l; + pc_id = 1l; + a1_id = 10l; + a2_id = 100l; - // Rev 1 - em.getTransaction().begin(); + // Rev 1 + em.getTransaction().begin(); - PersonalContact pc = new PersonalContact(pc_id, "e", "f"); + PersonalContact pc = new PersonalContact( pc_id, "e", "f" ); - Address a1 = new Address(a1_id, "a1"); - a1.setContact(pc); + Address a1 = new Address( a1_id, "a1" ); + a1.setContact( pc ); - em.persist(pc); - em.persist(a1); + em.persist( pc ); + em.persist( a1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); + // Rev 2 + em.getTransaction().begin(); - pc = em.find(PersonalContact.class, pc_id); + pc = em.find( PersonalContact.class, pc_id ); - Address a2 = new Address(a2_id, "a2"); - a2.setContact(pc); + Address a2 = new Address( a2_id, "a2" ); + a2.setContact( pc ); - em.persist(a2); + em.persist( a2 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } @Test public void testReferencedEntityHasChanged() throws Exception { - List list = queryForPropertyHasChanged(PersonalContact.class, pc_id, - "addresses"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 2), extractRevisionNumbers(list)); + List list = queryForPropertyHasChanged( + PersonalContact.class, pc_id, + "addresses" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasChanged(Address.class, a1_id, "contact"); - assertEquals(1, list.size()); - assertEquals(makeList(1), extractRevisionNumbers(list)); + list = queryForPropertyHasChanged( Address.class, a1_id, "contact" ); + assertEquals( 1, list.size() ); + assertEquals( makeList( 1 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasChanged(Address.class, a2_id, "contact"); - assertEquals(1, list.size()); - assertEquals(makeList(2), extractRevisionNumbers(list)); + list = queryForPropertyHasChanged( Address.class, a2_id, "contact" ); + assertEquals( 1, list.size() ); + assertEquals( makeList( 2 ), extractRevisionNumbers( list ) ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedNullProperties.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedNullProperties.java index a5b78bf811..341f48eed2 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedNullProperties.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedNullProperties.java @@ -23,15 +23,15 @@ */ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.query.AuditEntity; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.basic.BasicTestEntity1; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -41,71 +41,79 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedNullProperties extends AbstractModifiedFlagsEntityTest { - private Integer id1; - private Integer id2; + private Integer id1; + private Integer id2; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BasicTestEntity1.class }; - } + return new Class[] {BasicTestEntity1.class}; + } - private Integer addNewEntity(String str, long lng) { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - BasicTestEntity1 bte1 = new BasicTestEntity1(str, lng); - em.persist(bte1); - em.getTransaction().commit(); + private Integer addNewEntity(String str, long lng) { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + BasicTestEntity1 bte1 = new BasicTestEntity1( str, lng ); + em.persist( bte1 ); + em.getTransaction().commit(); - return bte1.getId(); - } + return bte1.getId(); + } - private void modifyEntity(Integer id, String str, long lng) { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - BasicTestEntity1 bte1 = em.find(BasicTestEntity1.class, id); - bte1.setLong1(lng); - bte1.setStr1(str); - em.getTransaction().commit(); - } + private void modifyEntity(Integer id, String str, long lng) { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + BasicTestEntity1 bte1 = em.find( BasicTestEntity1.class, id ); + bte1.setLong1( lng ); + bte1.setStr1( str ); + em.getTransaction().commit(); + } - @Test - @Priority(10) - public void initData() { - id1 = addNewEntity("x", 1); // rev 1 - id2 = addNewEntity(null, 20); // rev 2 + @Test + @Priority(10) + public void initData() { + id1 = addNewEntity( "x", 1 ); // rev 1 + id2 = addNewEntity( null, 20 ); // rev 2 - modifyEntity(id1, null, 1); // rev 3 - modifyEntity(id2, "y2", 20); // rev 4 - } + modifyEntity( id1, null, 1 ); // rev 3 + modifyEntity( id2, "y2", 20 ); // rev 4 + } @Test public void testHasChanged() throws Exception { - List list = queryForPropertyHasChangedWithDeleted(BasicTestEntity1.class, - id1, "str1"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 3), extractRevisionNumbers(list)); + List list = queryForPropertyHasChangedWithDeleted( + BasicTestEntity1.class, + id1, "str1" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 3 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasChangedWithDeleted(BasicTestEntity1.class, - id1, "long1"); - assertEquals(1, list.size()); - assertEquals(makeList(1), extractRevisionNumbers(list)); + list = queryForPropertyHasChangedWithDeleted( + BasicTestEntity1.class, + id1, "long1" + ); + assertEquals( 1, list.size() ); + assertEquals( makeList( 1 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasChangedWithDeleted(BasicTestEntity1.class, - id2, "str1"); + list = queryForPropertyHasChangedWithDeleted( + BasicTestEntity1.class, + id2, "str1" + ); // str1 property was null before insert and after insert so in a way it didn't change - is it a good way to go? - assertEquals(1, list.size()); - assertEquals(makeList(4), extractRevisionNumbers(list)); + assertEquals( 1, list.size() ); + assertEquals( makeList( 4 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasChangedWithDeleted(BasicTestEntity1.class, - id2, "long1"); - assertEquals(1, list.size()); - assertEquals(makeList(2), extractRevisionNumbers(list)); + list = queryForPropertyHasChangedWithDeleted( + BasicTestEntity1.class, + id2, "long1" + ); + assertEquals( 1, list.size() ); + assertEquals( makeList( 2 ), extractRevisionNumbers( list ) ); - list = getAuditReader().createQuery().forRevisionsOfEntity(BasicTestEntity1.class, false, true) - .add(AuditEntity.property("str1").hasChanged()) - .add(AuditEntity.property("long1").hasChanged()) + list = getAuditReader().createQuery().forRevisionsOfEntity( BasicTestEntity1.class, false, true ) + .add( AuditEntity.property( "str1" ).hasChanged() ) + .add( AuditEntity.property( "long1" ).hasChanged() ) .getResultList(); - assertEquals(1, list.size()); - assertEquals(makeList(1), extractRevisionNumbers(list)); + assertEquals( 1, list.size() ); + assertEquals( makeList( 1 ), extractRevisionNumbers( list ) ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedOneToManyInComponent.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedOneToManyInComponent.java index 9af0928020..e6453884f2 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedOneToManyInComponent.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedOneToManyInComponent.java @@ -23,16 +23,16 @@ */ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.components.relations.OneToManyComponent; import org.hibernate.envers.test.entities.components.relations.OneToManyComponentTestEntity; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -42,64 +42,68 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedOneToManyInComponent extends AbstractModifiedFlagsEntityTest { - private Integer otmcte_id1; + private Integer otmcte_id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { OneToManyComponentTestEntity.class, StrTestEntity.class }; - } + return new Class[] {OneToManyComponentTestEntity.class, StrTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); StrTestEntity ste1 = new StrTestEntity(); - ste1.setStr("str1"); + ste1.setStr( "str1" ); StrTestEntity ste2 = new StrTestEntity(); - ste2.setStr("str2"); + ste2.setStr( "str2" ); - em.persist(ste1); - em.persist(ste2); + em.persist( ste1 ); + em.persist( ste2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 2 + em = getEntityManager(); + em.getTransaction().begin(); - OneToManyComponentTestEntity otmcte1 = new OneToManyComponentTestEntity(new OneToManyComponent("data1")); - otmcte1.getComp1().getEntities().add(ste1); + OneToManyComponentTestEntity otmcte1 = new OneToManyComponentTestEntity( new OneToManyComponent( "data1" ) ); + otmcte1.getComp1().getEntities().add( ste1 ); - em.persist(otmcte1); + em.persist( otmcte1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 3 + em = getEntityManager(); + em.getTransaction().begin(); - otmcte1 = em.find(OneToManyComponentTestEntity.class, otmcte1.getId()); - otmcte1.getComp1().getEntities().add(ste2); + otmcte1 = em.find( OneToManyComponentTestEntity.class, otmcte1.getId() ); + otmcte1.getComp1().getEntities().add( ste2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - otmcte_id1 = otmcte1.getId(); + otmcte_id1 = otmcte1.getId(); } @Test public void testHasChangedId1() throws Exception { List list = - queryForPropertyHasChanged(OneToManyComponentTestEntity.class, - otmcte_id1, "comp1"); - assertEquals(2, list.size()); - assertEquals(makeList(2, 3), extractRevisionNumbers(list)); + queryForPropertyHasChanged( + OneToManyComponentTestEntity.class, + otmcte_id1, "comp1" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 2, 3 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasNotChanged(OneToManyComponentTestEntity.class, - otmcte_id1, "comp1"); - assertEquals(0, list.size()); + list = queryForPropertyHasNotChanged( + OneToManyComponentTestEntity.class, + otmcte_id1, "comp1" + ); + assertEquals( 0, list.size() ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedStringMap.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedStringMap.java index b5ef7f5a71..9eddbe9f84 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedStringMap.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedStringMap.java @@ -23,14 +23,14 @@ */ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.collection.StringMapEntity; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -40,89 +40,97 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedStringMap extends AbstractModifiedFlagsEntityTest { - private Integer sme1_id; - private Integer sme2_id; + private Integer sme1_id; + private Integer sme2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StringMapEntity.class }; - } + return new Class[] {StringMapEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - StringMapEntity sme1 = new StringMapEntity(); - StringMapEntity sme2 = new StringMapEntity(); + StringMapEntity sme1 = new StringMapEntity(); + StringMapEntity sme2 = new StringMapEntity(); - // Revision 1 (sme1: initialy empty, sme2: initialy 1 mapping) - em.getTransaction().begin(); + // Revision 1 (sme1: initialy empty, sme2: initialy 1 mapping) + em.getTransaction().begin(); - sme2.getStrings().put("1", "a"); + sme2.getStrings().put( "1", "a" ); - em.persist(sme1); - em.persist(sme2); + em.persist( sme1 ); + em.persist( sme2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (sme1: adding 2 mappings, sme2: no changes) - em.getTransaction().begin(); + // Revision 2 (sme1: adding 2 mappings, sme2: no changes) + em.getTransaction().begin(); - sme1 = em.find(StringMapEntity.class, sme1.getId()); - sme2 = em.find(StringMapEntity.class, sme2.getId()); + sme1 = em.find( StringMapEntity.class, sme1.getId() ); + sme2 = em.find( StringMapEntity.class, sme2.getId() ); - sme1.getStrings().put("1", "a"); - sme1.getStrings().put("2", "b"); + sme1.getStrings().put( "1", "a" ); + sme1.getStrings().put( "2", "b" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 (sme1: removing an existing mapping, sme2: replacing a value) - em.getTransaction().begin(); + // Revision 3 (sme1: removing an existing mapping, sme2: replacing a value) + em.getTransaction().begin(); - sme1 = em.find(StringMapEntity.class, sme1.getId()); - sme2 = em.find(StringMapEntity.class, sme2.getId()); + sme1 = em.find( StringMapEntity.class, sme1.getId() ); + sme2 = em.find( StringMapEntity.class, sme2.getId() ); - sme1.getStrings().remove("1"); - sme2.getStrings().put("1", "b"); - - em.getTransaction().commit(); + sme1.getStrings().remove( "1" ); + sme2.getStrings().put( "1", "b" ); - // No revision (sme1: removing a non-existing mapping, sme2: replacing with the same value) - em.getTransaction().begin(); + em.getTransaction().commit(); - sme1 = em.find(StringMapEntity.class, sme1.getId()); - sme2 = em.find(StringMapEntity.class, sme2.getId()); + // No revision (sme1: removing a non-existing mapping, sme2: replacing with the same value) + em.getTransaction().begin(); - sme1.getStrings().remove("3"); - sme2.getStrings().put("1", "b"); + sme1 = em.find( StringMapEntity.class, sme1.getId() ); + sme2 = em.find( StringMapEntity.class, sme2.getId() ); - em.getTransaction().commit(); + sme1.getStrings().remove( "3" ); + sme2.getStrings().put( "1", "b" ); - // + em.getTransaction().commit(); - sme1_id = sme1.getId(); - sme2_id = sme2.getId(); - } + // + + sme1_id = sme1.getId(); + sme2_id = sme2.getId(); + } @Test public void testHasChanged() throws Exception { - List list = queryForPropertyHasChanged(StringMapEntity.class, sme1_id, - "strings"); - assertEquals(3, list.size()); - assertEquals(makeList(1, 2, 3), extractRevisionNumbers(list)); + List list = queryForPropertyHasChanged( + StringMapEntity.class, sme1_id, + "strings" + ); + assertEquals( 3, list.size() ); + assertEquals( makeList( 1, 2, 3 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasChanged(StringMapEntity.class, sme2_id, - "strings"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 3), extractRevisionNumbers(list)); + list = queryForPropertyHasChanged( + StringMapEntity.class, sme2_id, + "strings" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 3 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasNotChanged(StringMapEntity.class, sme1_id, - "strings"); - assertEquals(0, list.size()); + list = queryForPropertyHasNotChanged( + StringMapEntity.class, sme1_id, + "strings" + ); + assertEquals( 0, list.size() ); - list = queryForPropertyHasNotChanged(StringMapEntity.class, sme2_id, - "strings"); - assertEquals(0, list.size()); // in rev 2 there was no version generated for sme2_id + list = queryForPropertyHasNotChanged( + StringMapEntity.class, sme2_id, + "strings" + ); + assertEquals( 0, list.size() ); // in rev 2 there was no version generated for sme2_id } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedStringSet.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedStringSet.java index 3ed5328f6d..af83adbf2c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedStringSet.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedStringSet.java @@ -23,14 +23,14 @@ */ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.collection.StringSetEntity; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -40,81 +40,89 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedStringSet extends AbstractModifiedFlagsEntityTest { - private Integer sse1_id; - private Integer sse2_id; + private Integer sse1_id; + private Integer sse2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StringSetEntity.class }; - } + return new Class[] {StringSetEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - StringSetEntity sse1 = new StringSetEntity(); - StringSetEntity sse2 = new StringSetEntity(); + StringSetEntity sse1 = new StringSetEntity(); + StringSetEntity sse2 = new StringSetEntity(); - // Revision 1 (sse1: initialy empty, sse2: initialy 2 elements) - em.getTransaction().begin(); + // Revision 1 (sse1: initialy empty, sse2: initialy 2 elements) + em.getTransaction().begin(); - sse2.getStrings().add("sse2_string1"); - sse2.getStrings().add("sse2_string2"); + sse2.getStrings().add( "sse2_string1" ); + sse2.getStrings().add( "sse2_string2" ); - em.persist(sse1); - em.persist(sse2); + em.persist( sse1 ); + em.persist( sse2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (sse1: adding 2 elements, sse2: adding an existing element) - em.getTransaction().begin(); + // Revision 2 (sse1: adding 2 elements, sse2: adding an existing element) + em.getTransaction().begin(); - sse1 = em.find(StringSetEntity.class, sse1.getId()); - sse2 = em.find(StringSetEntity.class, sse2.getId()); + sse1 = em.find( StringSetEntity.class, sse1.getId() ); + sse2 = em.find( StringSetEntity.class, sse2.getId() ); - sse1.getStrings().add("sse1_string1"); - sse1.getStrings().add("sse1_string2"); + sse1.getStrings().add( "sse1_string1" ); + sse1.getStrings().add( "sse1_string2" ); - sse2.getStrings().add("sse2_string1"); + sse2.getStrings().add( "sse2_string1" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 (sse1: removing a non-existing element, sse2: removing one element) - em.getTransaction().begin(); + // Revision 3 (sse1: removing a non-existing element, sse2: removing one element) + em.getTransaction().begin(); - sse1 = em.find(StringSetEntity.class, sse1.getId()); - sse2 = em.find(StringSetEntity.class, sse2.getId()); + sse1 = em.find( StringSetEntity.class, sse1.getId() ); + sse2 = em.find( StringSetEntity.class, sse2.getId() ); - sse1.getStrings().remove("sse1_string3"); - sse2.getStrings().remove("sse2_string1"); + sse1.getStrings().remove( "sse1_string3" ); + sse2.getStrings().remove( "sse2_string1" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - sse1_id = sse1.getId(); - sse2_id = sse2.getId(); - } + sse1_id = sse1.getId(); + sse2_id = sse2.getId(); + } @Test public void testHasChanged() throws Exception { - List list = queryForPropertyHasChanged(StringSetEntity.class, sse1_id, - "strings"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 2), extractRevisionNumbers(list)); + List list = queryForPropertyHasChanged( + StringSetEntity.class, sse1_id, + "strings" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasChanged(StringSetEntity.class, sse2_id, - "strings"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 3), extractRevisionNumbers(list)); + list = queryForPropertyHasChanged( + StringSetEntity.class, sse2_id, + "strings" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 3 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasNotChanged(StringSetEntity.class, sse1_id, - "strings"); - assertEquals(0, list.size()); + list = queryForPropertyHasNotChanged( + StringSetEntity.class, sse1_id, + "strings" + ); + assertEquals( 0, list.size() ); - list = queryForPropertyHasNotChanged(StringSetEntity.class, sse2_id, - "strings"); - assertEquals(0, list.size()); + list = queryForPropertyHasNotChanged( + StringSetEntity.class, sse2_id, + "strings" + ); + assertEquals( 0, list.size() ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedUnversionedProperties.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedUnversionedProperties.java index 6c3f430726..828c0eff4c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedUnversionedProperties.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/HasChangedUnversionedProperties.java @@ -23,15 +23,15 @@ */ package org.hibernate.envers.test.integration.modifiedflags; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.QueryException; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.basic.BasicTestEntity2; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -41,52 +41,56 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class HasChangedUnversionedProperties extends AbstractModifiedFlagsEntityTest { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BasicTestEntity2.class }; - } + return new Class[] {BasicTestEntity2.class}; + } - private Integer addNewEntity(String str1, String str2) { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - BasicTestEntity2 bte2 = new BasicTestEntity2(str1, str2); - em.persist(bte2); - em.getTransaction().commit(); + private Integer addNewEntity(String str1, String str2) { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + BasicTestEntity2 bte2 = new BasicTestEntity2( str1, str2 ); + em.persist( bte2 ); + em.getTransaction().commit(); - return bte2.getId(); - } + return bte2.getId(); + } - private void modifyEntity(Integer id, String str1, String str2) { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - BasicTestEntity2 bte2 = em.find(BasicTestEntity2.class, id); - bte2.setStr1(str1); - bte2.setStr2(str2); - em.getTransaction().commit(); - } + private void modifyEntity(Integer id, String str1, String str2) { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + BasicTestEntity2 bte2 = em.find( BasicTestEntity2.class, id ); + bte2.setStr1( str1 ); + bte2.setStr2( str2 ); + em.getTransaction().commit(); + } - @Test - @Priority(10) - public void initData() { - id1 = addNewEntity("x", "a"); // rev 1 - modifyEntity(id1, "x", "a"); // no rev - modifyEntity(id1, "y", "b"); // rev 2 - modifyEntity(id1, "y", "c"); // no rev - } + @Test + @Priority(10) + public void initData() { + id1 = addNewEntity( "x", "a" ); // rev 1 + modifyEntity( id1, "x", "a" ); // no rev + modifyEntity( id1, "y", "b" ); // rev 2 + modifyEntity( id1, "y", "c" ); // no rev + } @Test public void testHasChangedQuery() throws Exception { - List list = queryForPropertyHasChanged(BasicTestEntity2.class, - id1, "str1"); - assertEquals(2, list.size()); - assertEquals(makeList(1, 2), extractRevisionNumbers(list)); + List list = queryForPropertyHasChanged( + BasicTestEntity2.class, + id1, "str1" + ); + assertEquals( 2, list.size() ); + assertEquals( makeList( 1, 2 ), extractRevisionNumbers( list ) ); } @Test(expected = QueryException.class) public void testExceptionOnHasChangedQuery() throws Exception { - queryForPropertyHasChangedWithDeleted(BasicTestEntity2.class, - id1, "str2"); + queryForPropertyHasChangedWithDeleted( + BasicTestEntity2.class, + id1, "str2" + ); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/ModifiedFlagSuffix.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/ModifiedFlagSuffix.java index dcef9d8aa5..a88b79d180 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/ModifiedFlagSuffix.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/ModifiedFlagSuffix.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.modifiedflags; +import javax.persistence.EntityManager; import java.util.List; import java.util.Map; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.configuration.EnversSettings; import org.hibernate.envers.query.AuditEntity; @@ -35,6 +33,8 @@ import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.basic.BasicTestEntity1; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static org.hibernate.envers.test.tools.TestTools.extractRevisionNumbers; import static org.hibernate.envers.test.tools.TestTools.makeList; @@ -44,60 +44,69 @@ import static org.hibernate.envers.test.tools.TestTools.makeList; * @author Michal Skowronek (mskowr at o2 dot pl) */ public class ModifiedFlagSuffix extends AbstractModifiedFlagsEntityTest { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BasicTestEntity1.class }; - } + return new Class[] {BasicTestEntity1.class}; + } @Override protected void addConfigOptions(Map options) { - super.addConfigOptions(options); - options.put(EnversSettings.MODIFIED_FLAG_SUFFIX, "_CHANGED"); + super.addConfigOptions( options ); + options.put( EnversSettings.MODIFIED_FLAG_SUFFIX, "_CHANGED" ); } private Integer addNewEntity(String str, long lng) { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - BasicTestEntity1 bte1 = new BasicTestEntity1(str, lng); - em.persist(bte1); - em.getTransaction().commit(); + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + BasicTestEntity1 bte1 = new BasicTestEntity1( str, lng ); + em.persist( bte1 ); + em.getTransaction().commit(); - return bte1.getId(); - } + return bte1.getId(); + } - @Test - @Priority(10) - public void initData() { - id1 = addNewEntity("x", 1); // rev 1 - } + @Test + @Priority(10) + public void initData() { + id1 = addNewEntity( "x", 1 ); // rev 1 + } @Test public void testModFlagProperties() { - assertEquals(TestTools.makeSet("str1_CHANGED", "long1_CHANGED"), - TestTools.extractModProperties(getCfg().getClassMapping( - "org.hibernate.envers.test.integration.basic.BasicTestEntity1_AUD"), - "_CHANGED")); + assertEquals( + TestTools.makeSet( "str1_CHANGED", "long1_CHANGED" ), + TestTools.extractModProperties( + getCfg().getClassMapping( + "org.hibernate.envers.test.integration.basic.BasicTestEntity1_AUD" + ), + "_CHANGED" + ) + ); } @Test public void testHasChanged() throws Exception { - List list = queryForPropertyHasChangedWithDeleted(BasicTestEntity1.class, - id1, "str1"); - assertEquals(1, list.size()); - assertEquals(makeList(1), extractRevisionNumbers(list)); + List list = queryForPropertyHasChangedWithDeleted( + BasicTestEntity1.class, + id1, "str1" + ); + assertEquals( 1, list.size() ); + assertEquals( makeList( 1 ), extractRevisionNumbers( list ) ); - list = queryForPropertyHasChangedWithDeleted(BasicTestEntity1.class, - id1, "long1"); - assertEquals(1, list.size()); - assertEquals(makeList(1), extractRevisionNumbers(list)); + list = queryForPropertyHasChangedWithDeleted( + BasicTestEntity1.class, + id1, "long1" + ); + assertEquals( 1, list.size() ); + assertEquals( makeList( 1 ), extractRevisionNumbers( list ) ); - list = getAuditReader().createQuery().forRevisionsOfEntity(BasicTestEntity1.class, false, true) - .add(AuditEntity.property("str1").hasChanged()) - .add(AuditEntity.property("long1").hasChanged()) + list = getAuditReader().createQuery().forRevisionsOfEntity( BasicTestEntity1.class, false, true ) + .add( AuditEntity.property( "str1" ).hasChanged() ) + .add( AuditEntity.property( "long1" ).hasChanged() ) .getResultList(); - assertEquals(1, list.size()); - assertEquals(makeList(1), extractRevisionNumbers(list)); + assertEquals( 1, list.size() ); + assertEquals( makeList( 1 ), extractRevisionNumbers( list ) ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/entities/PartialModifiedFlagsEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/entities/PartialModifiedFlagsEntity.java index d06d16e5af..76e22e31b6 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/entities/PartialModifiedFlagsEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/entities/PartialModifiedFlagsEntity.java @@ -23,10 +23,6 @@ */ package org.hibernate.envers.test.integration.modifiedflags.entities; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; import javax.persistence.CollectionTable; import javax.persistence.ElementCollection; import javax.persistence.Embedded; @@ -37,6 +33,10 @@ import javax.persistence.ManyToMany; import javax.persistence.MapKeyColumn; import javax.persistence.OneToOne; import javax.persistence.Table; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; import org.hibernate.envers.AuditJoinTable; import org.hibernate.envers.Audited; @@ -51,51 +51,51 @@ import org.hibernate.envers.test.entities.components.Component2; @Table(name = "PartialModFlags") @Audited(withModifiedFlag = false) public class PartialModifiedFlagsEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited(withModifiedFlag = true) - private String data; + @Audited(withModifiedFlag = true) + private String data; @Audited(withModifiedFlag = true) @Embedded - private Component1 comp1; + private Component1 comp1; @Audited(withModifiedFlag = false) @Embedded - private Component2 comp2; + private Component2 comp2; - @Audited(withModifiedFlag = true) - @OneToOne(mappedBy="reference") - private WithModifiedFlagReferencingEntity referencing; + @Audited(withModifiedFlag = true) + @OneToOne(mappedBy = "reference") + private WithModifiedFlagReferencingEntity referencing; @Audited(withModifiedFlag = false) - @OneToOne(mappedBy="secondReference") - private WithModifiedFlagReferencingEntity referencing2; + @OneToOne(mappedBy = "secondReference") + private WithModifiedFlagReferencingEntity referencing2; - @Audited(withModifiedFlag = true) - @ElementCollection - @JoinTable(name = "PartialModFlags_StrSet") - @AuditJoinTable(name = "PartialModFlags_StrSet_AUD") - private Set stringSet = new HashSet(); + @Audited(withModifiedFlag = true) + @ElementCollection + @JoinTable(name = "PartialModFlags_StrSet") + @AuditJoinTable(name = "PartialModFlags_StrSet_AUD") + private Set stringSet = new HashSet(); @Audited(withModifiedFlag = true) @ManyToMany @CollectionTable(name = "ENTITIESSET") - private Set entitiesSet = new HashSet(); + private Set entitiesSet = new HashSet(); @Audited(withModifiedFlag = true) @ElementCollection - @MapKeyColumn(nullable=false) - @JoinTable(name = "PartialModFlags_StrMap") - @AuditJoinTable(name = "PartialModFlags_StrMap_AUD") - private Map stringMap = new HashMap(); + @MapKeyColumn(nullable = false) + @JoinTable(name = "PartialModFlags_StrMap") + @AuditJoinTable(name = "PartialModFlags_StrMap_AUD") + private Map stringMap = new HashMap(); @Audited(withModifiedFlag = true) - @ManyToMany - @CollectionTable(name = "ENTITIESMAP") - @MapKeyColumn(nullable = false) - private Map entitiesMap = + @ManyToMany + @CollectionTable(name = "ENTITIESMAP") + @MapKeyColumn(nullable = false) + private Map entitiesMap = new HashMap(); public PartialModifiedFlagsEntity() { @@ -106,36 +106,36 @@ public class PartialModifiedFlagsEntity { } public Integer getId() { - return id; - } + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public WithModifiedFlagReferencingEntity getReferencing() { - return referencing; - } + public WithModifiedFlagReferencingEntity getReferencing() { + return referencing; + } - public void setReferencing(WithModifiedFlagReferencingEntity referencing) { - this.referencing = referencing; - } + public void setReferencing(WithModifiedFlagReferencingEntity referencing) { + this.referencing = referencing; + } public WithModifiedFlagReferencingEntity getReferencing2() { - return referencing2; - } + return referencing2; + } - public void setReferencing2(WithModifiedFlagReferencingEntity referencing) { - this.referencing2 = referencing; - } + public void setReferencing2(WithModifiedFlagReferencingEntity referencing) { + this.referencing2 = referencing; + } public Component1 getComp1() { return comp1; @@ -186,21 +186,29 @@ public class PartialModifiedFlagsEntity { } public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof PartialModifiedFlagsEntity)) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof PartialModifiedFlagsEntity) ) { + return false; + } - PartialModifiedFlagsEntity that = (PartialModifiedFlagsEntity) o; + PartialModifiedFlagsEntity that = (PartialModifiedFlagsEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/entities/WithModifiedFlagReferencingEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/entities/WithModifiedFlagReferencingEntity.java index fcb799c54f..a0c8ca7ef7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/entities/WithModifiedFlagReferencingEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/modifiedflags/entities/WithModifiedFlagReferencingEntity.java @@ -37,73 +37,81 @@ import org.hibernate.envers.Audited; @Table(name = "WithModFlagRefIng") @Audited(withModifiedFlag = true) public class WithModifiedFlagReferencingEntity { - @Id - private Integer id; + @Id + private Integer id; - private String data; - - @OneToOne - private PartialModifiedFlagsEntity reference; + private String data; @OneToOne - private PartialModifiedFlagsEntity secondReference; + private PartialModifiedFlagsEntity reference; - public WithModifiedFlagReferencingEntity() { - } + @OneToOne + private PartialModifiedFlagsEntity secondReference; - public WithModifiedFlagReferencingEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public WithModifiedFlagReferencingEntity() { + } - public Integer getId() { - return id; - } + public WithModifiedFlagReferencingEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public void setId(Integer id) { - this.id = id; - } + public Integer getId() { + return id; + } - public String getData() { - return data; - } + public void setId(Integer id) { + this.id = id; + } - public void setData(String data) { - this.data = data; - } + public String getData() { + return data; + } - public PartialModifiedFlagsEntity getReference() { - return reference; - } + public void setData(String data) { + this.data = data; + } - public void setReference(PartialModifiedFlagsEntity reference) { - this.reference = reference; - } + public PartialModifiedFlagsEntity getReference() { + return reference; + } + + public void setReference(PartialModifiedFlagsEntity reference) { + this.reference = reference; + } public PartialModifiedFlagsEntity getSecondReference() { - return secondReference; - } + return secondReference; + } - public void setSecondReference(PartialModifiedFlagsEntity reference) { - this.secondReference = reference; - } + public void setSecondReference(PartialModifiedFlagsEntity reference) { + this.secondReference = reference; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof WithModifiedFlagReferencingEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof WithModifiedFlagReferencingEntity) ) { + return false; + } - WithModifiedFlagReferencingEntity that = (WithModifiedFlagReferencingEntity) o; + WithModifiedFlagReferencingEntity that = (WithModifiedFlagReferencingEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/multiplerelations/Address.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/multiplerelations/Address.java index 4517995d41..cc75fa807b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/multiplerelations/Address.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/multiplerelations/Address.java @@ -1,8 +1,5 @@ package org.hibernate.envers.test.integration.multiplerelations; -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -10,6 +7,9 @@ import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; import org.hibernate.envers.Audited; @@ -19,85 +19,93 @@ import org.hibernate.envers.Audited; @Entity @Audited public class Address implements Serializable { - @Id - @GeneratedValue - private long id; + @Id + @GeneratedValue + private long id; - private String city; + private String city; - @ManyToMany(cascade = {CascadeType.PERSIST}) - private Set tenants = new HashSet(); + @ManyToMany(cascade = {CascadeType.PERSIST}) + private Set tenants = new HashSet(); - @ManyToOne - @JoinColumn(nullable = false) - Person landlord; + @ManyToOne + @JoinColumn(nullable = false) + Person landlord; - public Address() { - } + public Address() { + } - public Address(String city) { - this.city = city; - } + public Address(String city) { + this.city = city; + } - public Address(String city, long id) { - this.id = id; - this.city = city; - } + public Address(String city, long id) { + this.id = id; + this.city = city; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Address)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Address) ) { + return false; + } - Address address = (Address) o; + Address address = (Address) o; - if (id != address.id) return false; - if (city != null ? !city.equals(address.city) : address.city != null) return false; + if ( id != address.id ) { + return false; + } + if ( city != null ? !city.equals( address.city ) : address.city != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = (int) (id ^ (id >>> 32)); - result = 31 * result + (city != null ? city.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = (int) (id ^ (id >>> 32)); + result = 31 * result + (city != null ? city.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "Address(id = " + id + ", city = " + city + ")"; - } + @Override + public String toString() { + return "Address(id = " + id + ", city = " + city + ")"; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(long id) { - this.id = id; - } + public void setId(long id) { + this.id = id; + } - public String getCity() { - return city; - } + public String getCity() { + return city; + } - public void setCity(String city) { - this.city = city; - } + public void setCity(String city) { + this.city = city; + } - public Set getTenants() { - return tenants; - } + public Set getTenants() { + return tenants; + } - public void setTenants(Set tenants) { - this.tenants = tenants; - } + public void setTenants(Set tenants) { + this.tenants = tenants; + } - public Person getLandlord() { - return landlord; - } + public Person getLandlord() { + return landlord; + } - public void setLandlord(Person landlord) { - this.landlord = landlord; - } + public void setLandlord(Person landlord) { + this.landlord = landlord; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/multiplerelations/MultipleAssociationsTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/multiplerelations/MultipleAssociationsTest.java index 7a9dad0ff2..52dcb42f5a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/multiplerelations/MultipleAssociationsTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/multiplerelations/MultipleAssociationsTest.java @@ -1,14 +1,15 @@ package org.hibernate.envers.test.integration.multiplerelations; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.tools.TestTools; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -16,175 +17,178 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-7073") public class MultipleAssociationsTest extends BaseEnversJPAFunctionalTestCase { - private long lukaszId = 0; - private long kingaId = 0; - private long warsawId = 0; - private long cracowId = 0; + private long lukaszId = 0; + private long kingaId = 0; + private long warsawId = 0; + private long cracowId = 0; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { Person.class, Address.class }; - } + return new Class[] {Person.class, Address.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 1 - em.getTransaction().begin(); - Person lukasz = new Person("Lukasz"); - Person kinga = new Person("Kinga"); - Address warsaw = new Address("Warsaw"); - warsaw.getTenants().add(lukasz); - warsaw.setLandlord(lukasz); - warsaw.getTenants().add(kinga); - lukasz.getAddresses().add(warsaw); - lukasz.getOwnedAddresses().add(warsaw); - kinga.getAddresses().add(warsaw); - em.persist(lukasz); - em.persist(kinga); - em.persist(warsaw); - em.getTransaction().commit(); + // Revision 1 + em.getTransaction().begin(); + Person lukasz = new Person( "Lukasz" ); + Person kinga = new Person( "Kinga" ); + Address warsaw = new Address( "Warsaw" ); + warsaw.getTenants().add( lukasz ); + warsaw.setLandlord( lukasz ); + warsaw.getTenants().add( kinga ); + lukasz.getAddresses().add( warsaw ); + lukasz.getOwnedAddresses().add( warsaw ); + kinga.getAddresses().add( warsaw ); + em.persist( lukasz ); + em.persist( kinga ); + em.persist( warsaw ); + em.getTransaction().commit(); - lukaszId = lukasz.getId(); - kingaId = kinga.getId(); - warsawId = warsaw.getId(); + lukaszId = lukasz.getId(); + kingaId = kinga.getId(); + warsawId = warsaw.getId(); - // Revision 2 - em.getTransaction().begin(); - kinga = em.find(Person.class, kinga.getId()); - Address cracow = new Address("Cracow"); - kinga.getAddresses().add(cracow); - cracow.getTenants().add(kinga); - cracow.setLandlord(kinga); - em.persist(cracow); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + kinga = em.find( Person.class, kinga.getId() ); + Address cracow = new Address( "Cracow" ); + kinga.getAddresses().add( cracow ); + cracow.getTenants().add( kinga ); + cracow.setLandlord( kinga ); + em.persist( cracow ); + em.getTransaction().commit(); - cracowId = cracow.getId(); + cracowId = cracow.getId(); - // Revision 3 - em.getTransaction().begin(); - cracow = em.find(Address.class, cracow.getId()); - cracow.setCity("Krakow"); - em.merge(cracow); - em.getTransaction().commit(); + // Revision 3 + em.getTransaction().begin(); + cracow = em.find( Address.class, cracow.getId() ); + cracow.setCity( "Krakow" ); + em.merge( cracow ); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); - lukasz = em.find(Person.class, lukasz.getId()); - lukasz.setName("Lucas"); - em.merge(lukasz); - em.getTransaction().commit(); + // Revision 4 + em.getTransaction().begin(); + lukasz = em.find( Person.class, lukasz.getId() ); + lukasz.setName( "Lucas" ); + em.merge( lukasz ); + em.getTransaction().commit(); - // Revision 5 - em.getTransaction().begin(); - warsaw = em.find(Address.class, warsaw.getId()); - lukasz = em.find(Person.class, lukasz.getId()); - kinga = em.find(Person.class, kinga.getId()); - warsaw.setLandlord(kinga); - kinga.getOwnedAddresses().add(warsaw); - lukasz.getOwnedAddresses().remove(warsaw); - em.merge(warsaw); - em.merge(lukasz); - em.merge(kinga); - em.getTransaction().commit(); - } + // Revision 5 + em.getTransaction().begin(); + warsaw = em.find( Address.class, warsaw.getId() ); + lukasz = em.find( Person.class, lukasz.getId() ); + kinga = em.find( Person.class, kinga.getId() ); + warsaw.setLandlord( kinga ); + kinga.getOwnedAddresses().add( warsaw ); + lukasz.getOwnedAddresses().remove( warsaw ); + em.merge( warsaw ); + em.merge( lukasz ); + em.merge( kinga ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - Assert.assertEquals(Arrays.asList(1, 4, 5), getAuditReader().getRevisions(Person.class, lukaszId)); - Assert.assertEquals(Arrays.asList(1, 2, 5), getAuditReader().getRevisions(Person.class, kingaId)); - Assert.assertEquals(Arrays.asList(1, 5), getAuditReader().getRevisions(Address.class, warsawId)); - Assert.assertEquals(Arrays.asList(2, 3), getAuditReader().getRevisions(Address.class, cracowId)); - } + @Test + public void testRevisionsCounts() { + Assert.assertEquals( Arrays.asList( 1, 4, 5 ), getAuditReader().getRevisions( Person.class, lukaszId ) ); + Assert.assertEquals( Arrays.asList( 1, 2, 5 ), getAuditReader().getRevisions( Person.class, kingaId ) ); + Assert.assertEquals( Arrays.asList( 1, 5 ), getAuditReader().getRevisions( Address.class, warsawId ) ); + Assert.assertEquals( Arrays.asList( 2, 3 ), getAuditReader().getRevisions( Address.class, cracowId ) ); + } - @Test - public void testHistoryOfLukasz() { - Person lukasz = new Person("Lukasz", lukaszId); - Address warsaw = new Address("Warsaw", warsawId); - lukasz.getAddresses().add(warsaw); - lukasz.getOwnedAddresses().add(warsaw); + @Test + public void testHistoryOfLukasz() { + Person lukasz = new Person( "Lukasz", lukaszId ); + Address warsaw = new Address( "Warsaw", warsawId ); + lukasz.getAddresses().add( warsaw ); + lukasz.getOwnedAddresses().add( warsaw ); - Person ver1 = getAuditReader().find(Person.class, lukaszId, 1); - Assert.assertEquals(lukasz, ver1); - Assert.assertEquals(lukasz.getAddresses(), ver1.getAddresses()); - Assert.assertEquals(lukasz.getOwnedAddresses(), ver1.getOwnedAddresses()); + Person ver1 = getAuditReader().find( Person.class, lukaszId, 1 ); + Assert.assertEquals( lukasz, ver1 ); + Assert.assertEquals( lukasz.getAddresses(), ver1.getAddresses() ); + Assert.assertEquals( lukasz.getOwnedAddresses(), ver1.getOwnedAddresses() ); - lukasz.setName("Lucas"); + lukasz.setName( "Lucas" ); - Person ver4 = getAuditReader().find(Person.class, lukaszId, 4); - Assert.assertEquals(lukasz, ver4); + Person ver4 = getAuditReader().find( Person.class, lukaszId, 4 ); + Assert.assertEquals( lukasz, ver4 ); - lukasz.getOwnedAddresses().remove(warsaw); + lukasz.getOwnedAddresses().remove( warsaw ); - Person ver5 = getAuditReader().find(Person.class, lukaszId, 5); - Assert.assertEquals(lukasz.getOwnedAddresses(), ver5.getOwnedAddresses()); - } + Person ver5 = getAuditReader().find( Person.class, lukaszId, 5 ); + Assert.assertEquals( lukasz.getOwnedAddresses(), ver5.getOwnedAddresses() ); + } - @Test - public void testHistoryOfKinga() { - Person kinga = new Person("Kinga", kingaId); - Address warsaw = new Address("Warsaw", warsawId); - kinga.getAddresses().add(warsaw); + @Test + public void testHistoryOfKinga() { + Person kinga = new Person( "Kinga", kingaId ); + Address warsaw = new Address( "Warsaw", warsawId ); + kinga.getAddresses().add( warsaw ); - Person ver1 = getAuditReader().find(Person.class, kingaId, 1); - Assert.assertEquals(kinga, ver1); - Assert.assertEquals(kinga.getAddresses(), ver1.getAddresses()); - Assert.assertEquals(kinga.getOwnedAddresses(), ver1.getOwnedAddresses()); + Person ver1 = getAuditReader().find( Person.class, kingaId, 1 ); + Assert.assertEquals( kinga, ver1 ); + Assert.assertEquals( kinga.getAddresses(), ver1.getAddresses() ); + Assert.assertEquals( kinga.getOwnedAddresses(), ver1.getOwnedAddresses() ); - Address cracow = new Address("Cracow", cracowId); - kinga.getOwnedAddresses().add(cracow); - kinga.getAddresses().add(cracow); + Address cracow = new Address( "Cracow", cracowId ); + kinga.getOwnedAddresses().add( cracow ); + kinga.getAddresses().add( cracow ); - Person ver2 = getAuditReader().find(Person.class, kingaId, 2); - Assert.assertEquals(kinga, ver2); - Assert.assertEquals(kinga.getAddresses(), ver2.getAddresses()); - Assert.assertEquals(kinga.getOwnedAddresses(), ver2.getOwnedAddresses()); + Person ver2 = getAuditReader().find( Person.class, kingaId, 2 ); + Assert.assertEquals( kinga, ver2 ); + Assert.assertEquals( kinga.getAddresses(), ver2.getAddresses() ); + Assert.assertEquals( kinga.getOwnedAddresses(), ver2.getOwnedAddresses() ); - kinga.getOwnedAddresses().add(warsaw); - cracow.setCity("Krakow"); + kinga.getOwnedAddresses().add( warsaw ); + cracow.setCity( "Krakow" ); - Person ver5 = getAuditReader().find(Person.class, kingaId, 5); - Assert.assertEquals(TestTools.makeSet(kinga.getAddresses()), TestTools.makeSet(ver5.getAddresses())); - Assert.assertEquals(TestTools.makeSet(kinga.getOwnedAddresses()), TestTools.makeSet(ver5.getOwnedAddresses())); - } + Person ver5 = getAuditReader().find( Person.class, kingaId, 5 ); + Assert.assertEquals( TestTools.makeSet( kinga.getAddresses() ), TestTools.makeSet( ver5.getAddresses() ) ); + Assert.assertEquals( + TestTools.makeSet( kinga.getOwnedAddresses() ), + TestTools.makeSet( ver5.getOwnedAddresses() ) + ); + } - @Test - public void testHistoryOfCracow() { - Address cracow = new Address("Cracow", cracowId); - Person kinga = new Person("Kinga", kingaId); - cracow.getTenants().add(kinga); - cracow.setLandlord(kinga); + @Test + public void testHistoryOfCracow() { + Address cracow = new Address( "Cracow", cracowId ); + Person kinga = new Person( "Kinga", kingaId ); + cracow.getTenants().add( kinga ); + cracow.setLandlord( kinga ); - Address ver2 = getAuditReader().find(Address.class, cracowId, 2); - Assert.assertEquals(cracow, ver2); - Assert.assertEquals(cracow.getTenants(), ver2.getTenants()); - Assert.assertEquals(cracow.getLandlord().getId(), ver2.getLandlord().getId()); + Address ver2 = getAuditReader().find( Address.class, cracowId, 2 ); + Assert.assertEquals( cracow, ver2 ); + Assert.assertEquals( cracow.getTenants(), ver2.getTenants() ); + Assert.assertEquals( cracow.getLandlord().getId(), ver2.getLandlord().getId() ); - cracow.setCity("Krakow"); + cracow.setCity( "Krakow" ); - Address ver3 = getAuditReader().find(Address.class, cracowId, 3); - Assert.assertEquals(cracow, ver3); - } + Address ver3 = getAuditReader().find( Address.class, cracowId, 3 ); + Assert.assertEquals( cracow, ver3 ); + } - @Test - public void testHistoryOfWarsaw() { - Address warsaw = new Address("Warsaw", warsawId); - Person kinga = new Person("Kinga", kingaId); - Person lukasz = new Person("Lukasz", lukaszId); - warsaw.getTenants().add(lukasz); - warsaw.getTenants().add(kinga); - warsaw.setLandlord(lukasz); + @Test + public void testHistoryOfWarsaw() { + Address warsaw = new Address( "Warsaw", warsawId ); + Person kinga = new Person( "Kinga", kingaId ); + Person lukasz = new Person( "Lukasz", lukaszId ); + warsaw.getTenants().add( lukasz ); + warsaw.getTenants().add( kinga ); + warsaw.setLandlord( lukasz ); - Address ver1 = getAuditReader().find(Address.class, warsawId, 1); - Assert.assertEquals(warsaw, ver1); - Assert.assertEquals(warsaw.getTenants(), ver1.getTenants()); - Assert.assertEquals(warsaw.getLandlord().getId(), ver1.getLandlord().getId()); + Address ver1 = getAuditReader().find( Address.class, warsawId, 1 ); + Assert.assertEquals( warsaw, ver1 ); + Assert.assertEquals( warsaw.getTenants(), ver1.getTenants() ); + Assert.assertEquals( warsaw.getLandlord().getId(), ver1.getLandlord().getId() ); - warsaw.setLandlord(kinga); + warsaw.setLandlord( kinga ); - Address ver5 = getAuditReader().find(Address.class, warsawId, 5); - Assert.assertEquals(warsaw.getLandlord().getId(), ver5.getLandlord().getId()); - } + Address ver5 = getAuditReader().find( Address.class, warsawId, 5 ); + Assert.assertEquals( warsaw.getLandlord().getId(), ver5.getLandlord().getId() ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/multiplerelations/Person.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/multiplerelations/Person.java index 4a44c5a452..3084762c5a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/multiplerelations/Person.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/multiplerelations/Person.java @@ -1,8 +1,5 @@ package org.hibernate.envers.test.integration.multiplerelations; -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -11,6 +8,9 @@ import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; import org.hibernate.envers.Audited; @@ -20,87 +20,95 @@ import org.hibernate.envers.Audited; @Entity @Audited public class Person implements Serializable { - @Id - @GeneratedValue - private long id; + @Id + @GeneratedValue + private long id; - private String name; + private String name; - @ManyToMany(cascade = {CascadeType.PERSIST}) - @JoinTable(name = "PERSON_ADDRESS", - joinColumns = {@JoinColumn(name = "personId", nullable = false)}, - inverseJoinColumns = {@JoinColumn(name = "addressId", nullable = false)}) - private Set
      addresses = new HashSet
      (); + @ManyToMany(cascade = {CascadeType.PERSIST}) + @JoinTable(name = "PERSON_ADDRESS", + joinColumns = {@JoinColumn(name = "personId", nullable = false)}, + inverseJoinColumns = {@JoinColumn(name = "addressId", nullable = false)}) + private Set
      addresses = new HashSet
      (); - @OneToMany(mappedBy = "landlord", cascade = {CascadeType.PERSIST}, orphanRemoval = true) - private Set
      ownedAddresses = new HashSet
      (); + @OneToMany(mappedBy = "landlord", cascade = {CascadeType.PERSIST}, orphanRemoval = true) + private Set
      ownedAddresses = new HashSet
      (); - public Person() { - } + public Person() { + } - public Person(String name) { - this.name = name; - } + public Person(String name) { + this.name = name; + } - public Person(String name, long id) { - this.id = id; - this.name = name; - } + public Person(String name, long id) { + this.id = id; + this.name = name; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Person)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Person) ) { + return false; + } - Person person = (Person) o; + Person person = (Person) o; - if (id != person.id) return false; - if (name != null ? !name.equals(person.name) : person.name != null) return false; + if ( id != person.id ) { + return false; + } + if ( name != null ? !name.equals( person.name ) : person.name != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = (int) (id ^ (id >>> 32)); - result = 31 * result + (name != null ? name.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = (int) (id ^ (id >>> 32)); + result = 31 * result + (name != null ? name.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "Person(id = " + id + ", name = " + name + ")"; - } + @Override + public String toString() { + return "Person(id = " + id + ", name = " + name + ")"; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(long id) { - this.id = id; - } + public void setId(long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Set
      getAddresses() { - return addresses; - } + public Set
      getAddresses() { + return addresses; + } - public void setAddresses(Set
      addresses) { - this.addresses = addresses; - } + public void setAddresses(Set
      addresses) { + this.addresses = addresses; + } - public Set
      getOwnedAddresses() { - return ownedAddresses; - } + public Set
      getOwnedAddresses() { + return ownedAddresses; + } - public void setOwnedAddresses(Set
      ownedAddresses) { - this.ownedAddresses = ownedAddresses; - } + public void setOwnedAddresses(Set
      ownedAddresses) { + this.ownedAddresses = ownedAddresses; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/BasicNaming.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/BasicNaming.java index ec1e229d0d..99711705d3 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/BasicNaming.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/BasicNaming.java @@ -23,94 +23,95 @@ */ package org.hibernate.envers.test.integration.naming; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BasicNaming extends BaseEnversJPAFunctionalTestCase { - private Integer id1; - private Integer id2; + private Integer id1; + private Integer id2; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { NamingTestEntity1.class }; - } + return new Class[] {NamingTestEntity1.class}; + } - @Test - @Priority(10) - public void initData() { - NamingTestEntity1 nte1 = new NamingTestEntity1("data1"); - NamingTestEntity1 nte2 = new NamingTestEntity1("data2"); + @Test + @Priority(10) + public void initData() { + NamingTestEntity1 nte1 = new NamingTestEntity1( "data1" ); + NamingTestEntity1 nte2 = new NamingTestEntity1( "data2" ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - em.persist(nte1); - em.persist(nte2); + em.persist( nte1 ); + em.persist( nte2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - nte1 = em.find(NamingTestEntity1.class, nte1.getId()); - nte1.setData("data1'"); + nte1 = em.find( NamingTestEntity1.class, nte1.getId() ); + nte1.setData( "data1'" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - nte2 = em.find(NamingTestEntity1.class, nte2.getId()); - nte2.setData("data2'"); + nte2 = em.find( NamingTestEntity1.class, nte2.getId() ); + nte2.setData( "data2'" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - id1 = nte1.getId(); - id2 = nte2.getId(); - } + id1 = nte1.getId(); + id2 = nte2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(NamingTestEntity1.class, id1)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( NamingTestEntity1.class, id1 ) ); - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(NamingTestEntity1.class, id2)); - } + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( NamingTestEntity1.class, id2 ) ); + } - @Test - public void testHistoryOfId1() { - NamingTestEntity1 ver1 = new NamingTestEntity1(id1, "data1"); - NamingTestEntity1 ver2 = new NamingTestEntity1(id1, "data1'"); + @Test + public void testHistoryOfId1() { + NamingTestEntity1 ver1 = new NamingTestEntity1( id1, "data1" ); + NamingTestEntity1 ver2 = new NamingTestEntity1( id1, "data1'" ); - assert getAuditReader().find(NamingTestEntity1.class, id1, 1).equals(ver1); - assert getAuditReader().find(NamingTestEntity1.class, id1, 2).equals(ver2); - assert getAuditReader().find(NamingTestEntity1.class, id1, 3).equals(ver2); - } + assert getAuditReader().find( NamingTestEntity1.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( NamingTestEntity1.class, id1, 2 ).equals( ver2 ); + assert getAuditReader().find( NamingTestEntity1.class, id1, 3 ).equals( ver2 ); + } - @Test - public void testHistoryOfId2() { - NamingTestEntity1 ver1 = new NamingTestEntity1(id2, "data2"); - NamingTestEntity1 ver2 = new NamingTestEntity1(id2, "data2'"); + @Test + public void testHistoryOfId2() { + NamingTestEntity1 ver1 = new NamingTestEntity1( id2, "data2" ); + NamingTestEntity1 ver2 = new NamingTestEntity1( id2, "data2'" ); - assert getAuditReader().find(NamingTestEntity1.class, id2, 1).equals(ver1); - assert getAuditReader().find(NamingTestEntity1.class, id2, 2).equals(ver1); - assert getAuditReader().find(NamingTestEntity1.class, id2, 3).equals(ver2); - } + assert getAuditReader().find( NamingTestEntity1.class, id2, 1 ).equals( ver1 ); + assert getAuditReader().find( NamingTestEntity1.class, id2, 2 ).equals( ver1 ); + assert getAuditReader().find( NamingTestEntity1.class, id2, 3 ).equals( ver2 ); + } - @Test - public void testTableName() { - assert "naming_test_entity_1_versions".equals( - getCfg().getClassMapping("org.hibernate.envers.test.integration.naming.NamingTestEntity1_AUD") - .getTable().getName()); - } + @Test + public void testTableName() { + assert "naming_test_entity_1_versions".equals( + getCfg().getClassMapping( "org.hibernate.envers.test.integration.naming.NamingTestEntity1_AUD" ) + .getTable().getName() + ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/DetachedNamingTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/DetachedNamingTestEntity.java index eafec7f691..8c7dbf3a3d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/DetachedNamingTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/DetachedNamingTestEntity.java @@ -22,12 +22,13 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.naming; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.OneToMany; +import java.util.Set; import org.hibernate.envers.Audited; import org.hibernate.envers.test.entities.StrTestEntity; @@ -37,75 +38,83 @@ import org.hibernate.envers.test.entities.StrTestEntity; */ @Entity public class DetachedNamingTestEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToMany - @JoinTable(name = "UNI_NAMING_TEST", - joinColumns = @JoinColumn(name = "ID_1"), - inverseJoinColumns = @JoinColumn(name = "ID_2")) - private Set collection; + @Audited + @OneToMany + @JoinTable(name = "UNI_NAMING_TEST", + joinColumns = @JoinColumn(name = "ID_1"), + inverseJoinColumns = @JoinColumn(name = "ID_2")) + private Set collection; - public DetachedNamingTestEntity() { - } + public DetachedNamingTestEntity() { + } - public DetachedNamingTestEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public DetachedNamingTestEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public DetachedNamingTestEntity(String data) { - this.data = data; - } + public DetachedNamingTestEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Set getCollection() { - return collection; - } + public Set getCollection() { + return collection; + } - public void setCollection(Set collection) { - this.collection = collection; - } + public void setCollection(Set collection) { + this.collection = collection; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof DetachedNamingTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof DetachedNamingTestEntity) ) { + return false; + } - DetachedNamingTestEntity that = (DetachedNamingTestEntity) o; + DetachedNamingTestEntity that = (DetachedNamingTestEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "DetachedNamingTestEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "DetachedNamingTestEntity(id = " + id + ", data = " + data + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/EstonianTableAlias.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/EstonianTableAlias.java index 4ca09d9a1d..14aa4ebaf7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/EstonianTableAlias.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/EstonianTableAlias.java @@ -4,12 +4,14 @@ import javax.persistence.EntityManager; import ee.estonia.entities.Child; import ee.estonia.entities.Parent; -import org.junit.Assert; -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.tools.TestTools; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -17,40 +19,40 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-6738") public class EstonianTableAlias extends BaseEnversJPAFunctionalTestCase { - private Long parentId = null; - private Long childId = null; + private Long parentId = null; + private Long childId = null; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { Parent.class, Child.class }; - } + return new Class[] {Parent.class, Child.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 1 - em.getTransaction().begin(); - Parent parent = new Parent("parent"); - Child child = new Child("child"); - parent.getCollection().add(child); - em.persist(child); - em.persist(parent); - em.getTransaction().commit(); + // Revision 1 + em.getTransaction().begin(); + Parent parent = new Parent( "parent" ); + Child child = new Child( "child" ); + parent.getCollection().add( child ); + em.persist( child ); + em.persist( parent ); + em.getTransaction().commit(); - parentId = parent.getId(); - childId = child.getId(); - } + parentId = parent.getId(); + childId = child.getId(); + } - @Test - public void testAuditChildTableAlias() { - Parent parent = new Parent("parent", parentId); - Child child = new Child("child", childId); + @Test + public void testAuditChildTableAlias() { + Parent parent = new Parent( "parent", parentId ); + Child child = new Child( "child", childId ); - Parent ver1 = getAuditReader().find(Parent.class, parentId, 1); + Parent ver1 = getAuditReader().find( Parent.class, parentId, 1 ); - Assert.assertEquals(parent, ver1); - Assert.assertEquals(TestTools.makeSet(child), ver1.getCollection()); - } + Assert.assertEquals( parent, ver1 ); + Assert.assertEquals( TestTools.makeSet( child ), ver1.getCollection() ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/JoinNaming.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/JoinNaming.java index fcc6b7ddd1..166635d22c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/JoinNaming.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/JoinNaming.java @@ -23,16 +23,16 @@ */ package org.hibernate.envers.test.integration.naming; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Iterator; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.mapping.Column; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; @@ -41,96 +41,98 @@ import static junit.framework.Assert.assertTrue; * @author Adam Warski (adam at warski dot org) */ public class JoinNaming extends BaseEnversJPAFunctionalTestCase { - private Integer ed_id1; - private Integer ed_id2; - private Integer ing_id1; + private Integer ed_id1; + private Integer ed_id2; + private Integer ing_id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { JoinNamingRefEdEntity.class, JoinNamingRefIngEntity.class }; - } + return new Class[] {JoinNamingRefEdEntity.class, JoinNamingRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - JoinNamingRefEdEntity ed1 = new JoinNamingRefEdEntity("data1"); - JoinNamingRefEdEntity ed2 = new JoinNamingRefEdEntity("data2"); + @Test + @Priority(10) + public void initData() { + JoinNamingRefEdEntity ed1 = new JoinNamingRefEdEntity( "data1" ); + JoinNamingRefEdEntity ed2 = new JoinNamingRefEdEntity( "data2" ); - JoinNamingRefIngEntity ing1 = new JoinNamingRefIngEntity("x", ed1); + JoinNamingRefIngEntity ing1 = new JoinNamingRefIngEntity( "x", ed1 ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); - em.persist(ing1); + em.persist( ed1 ); + em.persist( ed2 ); + em.persist( ing1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ed2 = em.find(JoinNamingRefEdEntity.class, ed2.getId()); + ed2 = em.find( JoinNamingRefEdEntity.class, ed2.getId() ); - ing1 = em.find(JoinNamingRefIngEntity.class, ing1.getId()); - ing1.setData("y"); - ing1.setReference(ed2); + ing1 = em.find( JoinNamingRefIngEntity.class, ing1.getId() ); + ing1.setData( "y" ); + ing1.setReference( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed_id1 = ed1.getId(); - ed_id2 = ed2.getId(); - ing_id1 = ing1.getId(); - } + ed_id1 = ed1.getId(); + ed_id2 = ed2.getId(); + ing_id1 = ing1.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(JoinNamingRefEdEntity.class, ed_id1)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(JoinNamingRefEdEntity.class, ed_id2)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(JoinNamingRefIngEntity.class, ing_id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( JoinNamingRefEdEntity.class, ed_id1 ) ); + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( JoinNamingRefEdEntity.class, ed_id2 ) ); + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( JoinNamingRefIngEntity.class, ing_id1 ) ); + } - @Test - public void testHistoryOfEdId1() { - JoinNamingRefEdEntity ver1 = new JoinNamingRefEdEntity(ed_id1, "data1"); + @Test + public void testHistoryOfEdId1() { + JoinNamingRefEdEntity ver1 = new JoinNamingRefEdEntity( ed_id1, "data1" ); - assert getAuditReader().find(JoinNamingRefEdEntity.class, ed_id1, 1).equals(ver1); - assert getAuditReader().find(JoinNamingRefEdEntity.class, ed_id1, 2).equals(ver1); - } + assert getAuditReader().find( JoinNamingRefEdEntity.class, ed_id1, 1 ).equals( ver1 ); + assert getAuditReader().find( JoinNamingRefEdEntity.class, ed_id1, 2 ).equals( ver1 ); + } - @Test - public void testHistoryOfEdId2() { - JoinNamingRefEdEntity ver1 = new JoinNamingRefEdEntity(ed_id2, "data2"); + @Test + public void testHistoryOfEdId2() { + JoinNamingRefEdEntity ver1 = new JoinNamingRefEdEntity( ed_id2, "data2" ); - assert getAuditReader().find(JoinNamingRefEdEntity.class, ed_id2, 1).equals(ver1); - assert getAuditReader().find(JoinNamingRefEdEntity.class, ed_id2, 2).equals(ver1); - } + assert getAuditReader().find( JoinNamingRefEdEntity.class, ed_id2, 1 ).equals( ver1 ); + assert getAuditReader().find( JoinNamingRefEdEntity.class, ed_id2, 2 ).equals( ver1 ); + } - @Test - public void testHistoryOfIngId1() { - JoinNamingRefIngEntity ver1 = new JoinNamingRefIngEntity(ing_id1, "x", null); - JoinNamingRefIngEntity ver2 = new JoinNamingRefIngEntity(ing_id1, "y", null); + @Test + public void testHistoryOfIngId1() { + JoinNamingRefIngEntity ver1 = new JoinNamingRefIngEntity( ing_id1, "x", null ); + JoinNamingRefIngEntity ver2 = new JoinNamingRefIngEntity( ing_id1, "y", null ); - assert getAuditReader().find(JoinNamingRefIngEntity.class, ing_id1, 1).equals(ver1); - assert getAuditReader().find(JoinNamingRefIngEntity.class, ing_id1, 2).equals(ver2); + assert getAuditReader().find( JoinNamingRefIngEntity.class, ing_id1, 1 ).equals( ver1 ); + assert getAuditReader().find( JoinNamingRefIngEntity.class, ing_id1, 2 ).equals( ver2 ); - assert getAuditReader().find(JoinNamingRefIngEntity.class, ing_id1, 1).getReference().equals( - new JoinNamingRefEdEntity(ed_id1, "data1")); - assert getAuditReader().find(JoinNamingRefIngEntity.class, ing_id1, 2).getReference().equals( - new JoinNamingRefEdEntity(ed_id2, "data2")); - } + assert getAuditReader().find( JoinNamingRefIngEntity.class, ing_id1, 1 ).getReference().equals( + new JoinNamingRefEdEntity( ed_id1, "data1" ) + ); + assert getAuditReader().find( JoinNamingRefIngEntity.class, ing_id1, 2 ).getReference().equals( + new JoinNamingRefEdEntity( ed_id2, "data2" ) + ); + } - @SuppressWarnings({"unchecked"}) - @Test - public void testJoinColumnName() { + @SuppressWarnings({"unchecked"}) + @Test + public void testJoinColumnName() { Iterator columns = - getCfg().getClassMapping("org.hibernate.envers.test.integration.naming.JoinNamingRefIngEntity_AUD") - .getProperty("reference_id").getColumnIterator(); - assertTrue(columns.hasNext()); - assertEquals("jnree_column_reference", columns.next().getName()); - assertFalse(columns.hasNext()); + getCfg().getClassMapping( "org.hibernate.envers.test.integration.naming.JoinNamingRefIngEntity_AUD" ) + .getProperty( "reference_id" ).getColumnIterator(); + assertTrue( columns.hasNext() ); + assertEquals( "jnree_column_reference", columns.next().getName() ); + assertFalse( columns.hasNext() ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/JoinNamingRefEdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/JoinNamingRefEdEntity.java index 78da95d41e..0ef8f74a1d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/JoinNamingRefEdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/JoinNamingRefEdEntity.java @@ -22,89 +22,99 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.naming; -import java.util.List; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.util.List; import org.hibernate.envers.Audited; /** * ReferencEd entity + * * @author Adam Warski (adam at warski dot org) */ @Entity public class JoinNamingRefEdEntity { - @Id - @GeneratedValue - @Column(name = "jnree_id") - private Integer id; + @Id + @GeneratedValue + @Column(name = "jnree_id") + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToMany(mappedBy="reference") - private List reffering; + @Audited + @OneToMany(mappedBy = "reference") + private List reffering; - public JoinNamingRefEdEntity() { - } + public JoinNamingRefEdEntity() { + } - public JoinNamingRefEdEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public JoinNamingRefEdEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public JoinNamingRefEdEntity(String data) { - this.data = data; - } + public JoinNamingRefEdEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public List getReffering() { - return reffering; - } + public List getReffering() { + return reffering; + } - public void setReffering(List reffering) { - this.reffering = reffering; - } + public void setReffering(List reffering) { + this.reffering = reffering; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof JoinNamingRefEdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof JoinNamingRefEdEntity) ) { + return false; + } - JoinNamingRefEdEntity that = (JoinNamingRefEdEntity) o; + JoinNamingRefEdEntity that = (JoinNamingRefEdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "JoinNamingRefEdEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "JoinNamingRefEdEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/JoinNamingRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/JoinNamingRefIngEntity.java index 269894d40e..680e3b756e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/JoinNamingRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/JoinNamingRefIngEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.naming; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -33,80 +34,90 @@ import org.hibernate.envers.Audited; /** * ReferencIng entity + * * @author Adam Warski (adam at warski dot org) */ @Entity public class JoinNamingRefIngEntity { - @Id - @GeneratedValue - @Column(name = "jnrie_id") - private Integer id; + @Id + @GeneratedValue + @Column(name = "jnrie_id") + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToOne - @JoinColumn(name = "jnree_column_reference") - private JoinNamingRefEdEntity reference; + @Audited + @ManyToOne + @JoinColumn(name = "jnree_column_reference") + private JoinNamingRefEdEntity reference; - public JoinNamingRefIngEntity() { } + public JoinNamingRefIngEntity() { + } - public JoinNamingRefIngEntity(Integer id, String data, JoinNamingRefEdEntity reference) { - this.id = id; - this.data = data; - this.reference = reference; - } + public JoinNamingRefIngEntity(Integer id, String data, JoinNamingRefEdEntity reference) { + this.id = id; + this.data = data; + this.reference = reference; + } - public JoinNamingRefIngEntity(String data, JoinNamingRefEdEntity reference) { - this.data = data; - this.reference = reference; - } + public JoinNamingRefIngEntity(String data, JoinNamingRefEdEntity reference) { + this.data = data; + this.reference = reference; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public JoinNamingRefEdEntity getReference() { - return reference; - } + public JoinNamingRefEdEntity getReference() { + return reference; + } - public void setReference(JoinNamingRefEdEntity reference) { - this.reference = reference; - } + public void setReference(JoinNamingRefEdEntity reference) { + this.reference = reference; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof JoinNamingRefIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof JoinNamingRefIngEntity) ) { + return false; + } - JoinNamingRefIngEntity that = (JoinNamingRefIngEntity) o; + JoinNamingRefIngEntity that = (JoinNamingRefIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "JoinNamingRefIngEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "JoinNamingRefIngEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/NamingTestEntity1.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/NamingTestEntity1.java index a5d3b7df74..0be00ef816 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/NamingTestEntity1.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/NamingTestEntity1.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.naming; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -35,62 +36,70 @@ import org.hibernate.envers.Audited; * @author Adam Warski (adam at warski dot org) */ @Entity -@Table(name="naming_test_entity_1") +@Table(name = "naming_test_entity_1") @AuditTable("naming_test_entity_1_versions") public class NamingTestEntity1 { - @Id - @GeneratedValue - @Column(name = "nte_id") - private Integer id; + @Id + @GeneratedValue + @Column(name = "nte_id") + private Integer id; - @Column(name = "nte_data") - @Audited - private String data; + @Column(name = "nte_data") + @Audited + private String data; - public NamingTestEntity1() { - } + public NamingTestEntity1() { + } - public NamingTestEntity1(String data) { - this.data = data; - } + public NamingTestEntity1(String data) { + this.data = data; + } - public NamingTestEntity1(Integer id, String data) { - this.id = id; - this.data = data; - } + public NamingTestEntity1(Integer id, String data) { + this.id = id; + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof NamingTestEntity1)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof NamingTestEntity1) ) { + return false; + } - NamingTestEntity1 that = (NamingTestEntity1) o; + NamingTestEntity1 that = (NamingTestEntity1) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/OneToManyUnidirectionalNaming.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/OneToManyUnidirectionalNaming.java index cada8de416..cb52a4abbf 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/OneToManyUnidirectionalNaming.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/OneToManyUnidirectionalNaming.java @@ -23,12 +23,10 @@ */ package org.hibernate.envers.test.integration.naming; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -36,96 +34,100 @@ import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.tools.TestTools; import org.hibernate.mapping.Column; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class OneToManyUnidirectionalNaming extends BaseEnversJPAFunctionalTestCase { - private Integer uni1_id; - private Integer str1_id; + private Integer uni1_id; + private Integer str1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { DetachedNamingTestEntity.class, StrTestEntity.class }; - } + return new Class[] {DetachedNamingTestEntity.class, StrTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - DetachedNamingTestEntity uni1 = new DetachedNamingTestEntity(1, "data1"); - StrTestEntity str1 = new StrTestEntity("str1"); + @Test + @Priority(10) + public void initData() { + DetachedNamingTestEntity uni1 = new DetachedNamingTestEntity( 1, "data1" ); + StrTestEntity str1 = new StrTestEntity( "str1" ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - uni1.setCollection(new HashSet()); - em.persist(uni1); - em.persist(str1); + uni1.setCollection( new HashSet() ); + em.persist( uni1 ); + em.persist( str1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - uni1 = em.find(DetachedNamingTestEntity.class, uni1.getId()); - str1 = em.find(StrTestEntity.class, str1.getId()); - uni1.getCollection().add(str1); + uni1 = em.find( DetachedNamingTestEntity.class, uni1.getId() ); + str1 = em.find( StrTestEntity.class, str1.getId() ); + uni1.getCollection().add( str1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - uni1_id = uni1.getId(); - str1_id = str1.getId(); - } + uni1_id = uni1.getId(); + str1_id = str1.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(DetachedNamingTestEntity.class, uni1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestEntity.class, str1_id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( DetachedNamingTestEntity.class, uni1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestEntity.class, str1_id ) ); + } - @Test - public void testHistoryOfUniId1() { - StrTestEntity str1 = getEntityManager().find(StrTestEntity.class, str1_id); + @Test + public void testHistoryOfUniId1() { + StrTestEntity str1 = getEntityManager().find( StrTestEntity.class, str1_id ); - DetachedNamingTestEntity rev1 = getAuditReader().find(DetachedNamingTestEntity.class, uni1_id, 1); - DetachedNamingTestEntity rev2 = getAuditReader().find(DetachedNamingTestEntity.class, uni1_id, 2); + DetachedNamingTestEntity rev1 = getAuditReader().find( DetachedNamingTestEntity.class, uni1_id, 1 ); + DetachedNamingTestEntity rev2 = getAuditReader().find( DetachedNamingTestEntity.class, uni1_id, 2 ); - assert rev1.getCollection().equals(TestTools.makeSet()); - assert rev2.getCollection().equals(TestTools.makeSet(str1)); + assert rev1.getCollection().equals( TestTools.makeSet() ); + assert rev2.getCollection().equals( TestTools.makeSet( str1 ) ); - assert "data1".equals(rev1.getData()); - assert "data1".equals(rev2.getData()); - } + assert "data1".equals( rev1.getData() ); + assert "data1".equals( rev2.getData() ); + } - private final static String MIDDLE_VERSIONS_ENTITY_NAME = "UNI_NAMING_TEST_AUD"; - @Test - public void testTableName() { - assert MIDDLE_VERSIONS_ENTITY_NAME.equals( - getCfg().getClassMapping(MIDDLE_VERSIONS_ENTITY_NAME).getTable().getName()); - } + private final static String MIDDLE_VERSIONS_ENTITY_NAME = "UNI_NAMING_TEST_AUD"; - @SuppressWarnings({"unchecked"}) - @Test - public void testJoinColumnName() { - Iterator columns = - getCfg().getClassMapping(MIDDLE_VERSIONS_ENTITY_NAME).getTable().getColumnIterator(); + @Test + public void testTableName() { + assert MIDDLE_VERSIONS_ENTITY_NAME.equals( + getCfg().getClassMapping( MIDDLE_VERSIONS_ENTITY_NAME ).getTable().getName() + ); + } - boolean id1Found = false; - boolean id2Found = false; + @SuppressWarnings({"unchecked"}) + @Test + public void testJoinColumnName() { + Iterator columns = + getCfg().getClassMapping( MIDDLE_VERSIONS_ENTITY_NAME ).getTable().getColumnIterator(); - while (columns.hasNext()) { - Column column = columns.next(); - if ("ID_1".equals(column.getName())) { - id1Found = true; - } + boolean id1Found = false; + boolean id2Found = false; - if ("ID_2".equals(column.getName())) { - id2Found = true; - } - } + while ( columns.hasNext() ) { + Column column = columns.next(); + if ( "ID_1".equals( column.getName() ) ) { + id1Found = true; + } - assert id1Found && id2Found; - } + if ( "ID_2".equals( column.getName() ) ) { + id2Found = true; + } + } + + assert id1Found && id2Found; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableNaming.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableNaming.java index 26b2eef8ce..70d410d043 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableNaming.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableNaming.java @@ -23,12 +23,10 @@ */ package org.hibernate.envers.test.integration.naming; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -36,97 +34,105 @@ import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.tools.TestTools; import org.hibernate.mapping.Column; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class VersionsJoinTableNaming extends BaseEnversJPAFunctionalTestCase { - private Integer uni1_id; - private Integer str1_id; + private Integer uni1_id; + private Integer str1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { VersionsJoinTableTestEntity.class, StrTestEntity.class }; - } + return new Class[] {VersionsJoinTableTestEntity.class, StrTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - VersionsJoinTableTestEntity uni1 = new VersionsJoinTableTestEntity(1, "data1"); - StrTestEntity str1 = new StrTestEntity("str1"); + @Test + @Priority(10) + public void initData() { + VersionsJoinTableTestEntity uni1 = new VersionsJoinTableTestEntity( 1, "data1" ); + StrTestEntity str1 = new StrTestEntity( "str1" ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - uni1.setCollection(new HashSet()); - em.persist(uni1); - em.persist(str1); + uni1.setCollection( new HashSet() ); + em.persist( uni1 ); + em.persist( str1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - uni1 = em.find(VersionsJoinTableTestEntity.class, uni1.getId()); - str1 = em.find(StrTestEntity.class, str1.getId()); - uni1.getCollection().add(str1); + uni1 = em.find( VersionsJoinTableTestEntity.class, uni1.getId() ); + str1 = em.find( StrTestEntity.class, str1.getId() ); + uni1.getCollection().add( str1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - uni1_id = uni1.getId(); - str1_id = str1.getId(); - } + uni1_id = uni1.getId(); + str1_id = str1.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(VersionsJoinTableTestEntity.class, uni1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestEntity.class, str1_id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( + VersionsJoinTableTestEntity.class, + uni1_id + ) + ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestEntity.class, str1_id ) ); + } - @Test - public void testHistoryOfUniId1() { - StrTestEntity str1 = getEntityManager().find(StrTestEntity.class, str1_id); + @Test + public void testHistoryOfUniId1() { + StrTestEntity str1 = getEntityManager().find( StrTestEntity.class, str1_id ); - VersionsJoinTableTestEntity rev1 = getAuditReader().find(VersionsJoinTableTestEntity.class, uni1_id, 1); - VersionsJoinTableTestEntity rev2 = getAuditReader().find(VersionsJoinTableTestEntity.class, uni1_id, 2); + VersionsJoinTableTestEntity rev1 = getAuditReader().find( VersionsJoinTableTestEntity.class, uni1_id, 1 ); + VersionsJoinTableTestEntity rev2 = getAuditReader().find( VersionsJoinTableTestEntity.class, uni1_id, 2 ); - assert rev1.getCollection().equals(TestTools.makeSet()); - assert rev2.getCollection().equals(TestTools.makeSet(str1)); + assert rev1.getCollection().equals( TestTools.makeSet() ); + assert rev2.getCollection().equals( TestTools.makeSet( str1 ) ); - assert "data1".equals(rev1.getData()); - assert "data1".equals(rev2.getData()); - } + assert "data1".equals( rev1.getData() ); + assert "data1".equals( rev2.getData() ); + } - private final static String MIDDLE_VERSIONS_ENTITY_NAME = "VERSIONS_JOIN_TABLE_TEST"; - - @Test - public void testTableName() { - assert MIDDLE_VERSIONS_ENTITY_NAME.equals( - getCfg().getClassMapping(MIDDLE_VERSIONS_ENTITY_NAME).getTable().getName()); - } + private final static String MIDDLE_VERSIONS_ENTITY_NAME = "VERSIONS_JOIN_TABLE_TEST"; - @SuppressWarnings({"unchecked"}) - @Test - public void testJoinColumnName() { - Iterator columns = - getCfg().getClassMapping(MIDDLE_VERSIONS_ENTITY_NAME).getTable().getColumnIterator(); + @Test + public void testTableName() { + assert MIDDLE_VERSIONS_ENTITY_NAME.equals( + getCfg().getClassMapping( MIDDLE_VERSIONS_ENTITY_NAME ).getTable().getName() + ); + } - boolean id1Found = false; - boolean id2Found = false; + @SuppressWarnings({"unchecked"}) + @Test + public void testJoinColumnName() { + Iterator columns = + getCfg().getClassMapping( MIDDLE_VERSIONS_ENTITY_NAME ).getTable().getColumnIterator(); - while (columns.hasNext()) { - Column column = columns.next(); - if ("VJT_ID".equals(column.getName())) { - id1Found = true; - } + boolean id1Found = false; + boolean id2Found = false; - if ("STR_ID".equals(column.getName())) { - id2Found = true; - } - } + while ( columns.hasNext() ) { + Column column = columns.next(); + if ( "VJT_ID".equals( column.getName() ) ) { + id1Found = true; + } - assert id1Found && id2Found; - } + if ( "STR_ID".equals( column.getName() ) ) { + id2Found = true; + } + } + + assert id1Found && id2Found; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeComponent.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeComponent.java index f7b16ce402..a1d0641ab9 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeComponent.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeComponent.java @@ -1,32 +1,35 @@ package org.hibernate.envers.test.integration.naming; -import java.util.ArrayList; -import java.util.List; + import javax.persistence.CascadeType; import javax.persistence.Embeddable; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; +import java.util.ArrayList; +import java.util.List; import org.hibernate.annotations.FetchMode; /** * An embeddable component containing a list of * {@link VersionsJoinTableRangeTestEntitySuperClass}-instances - * - * @author Erik-Berndt Scheper + * * @param + * + * @author Erik-Berndt Scheper */ @Embeddable public final class VersionsJoinTableRangeComponent { @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) - @org.hibernate.annotations.Fetch(value = FetchMode.SUBSELECT) + @org.hibernate.annotations.Fetch(value = FetchMode.SUBSELECT) @org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN) @JoinColumn(name = "VJTRCTE_ID", insertable = true, updatable = false, nullable = false) // Note: If this is processed without override annotation, then we should get a // org.hibernate.DuplicateMappingException: // Duplicate class/entity mapping JOIN_TABLE_COMPONENT_1_AUD - @org.hibernate.envers.AuditJoinTable(name = "JOIN_TABLE_COMPONENT_1_AUD", inverseJoinColumns = @JoinColumn(name = "VJTRTE_ID")) + @org.hibernate.envers.AuditJoinTable(name = "JOIN_TABLE_COMPONENT_1_AUD", + inverseJoinColumns = @JoinColumn(name = "VJTRTE_ID")) private List range = new ArrayList(); // ********************** Accessor Methods ********************** // @@ -47,18 +50,24 @@ public final class VersionsJoinTableRangeComponent other = (VersionsJoinTableRangeComponent) obj; - if (range == null) { - if (other.range != null) + if ( range == null ) { + if ( other.range != null ) { return false; - } else if (!range.equals(other.range)) + } + } + else if ( !range.equals( other.range ) ) { return false; + } return true; } @@ -66,12 +75,12 @@ public final class VersionsJoinTableRangeComponent ent1List = vjrcte .getComponent1().getRange(); assert ent1List.size() == 1; - assert vjtrte.equals(ent1List.get(0)); + assert vjtrte.equals( ent1List.get( 0 ) ); List ent2List = vjrcte .getComponent2().getRange(); assert ent2List.size() == 1; - assert vjtrtae1.equals(ent2List.get(0)); + assert vjtrtae1.equals( ent2List.get( 0 ) ); em.getTransaction().commit(); @@ -136,39 +142,50 @@ public class VersionsJoinTableRangeComponentNamingTest extends @Test public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals( + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( VersionsJoinTableRangeComponentTestEntity.class, - vjrcte_id)); - assert Arrays.asList(2).equals( + vjrcte_id + ) + ); + assert Arrays.asList( 2 ).equals( getAuditReader().getRevisions( - VersionsJoinTableRangeTestEntity.class, vjtrte_id)); - assert Arrays.asList(2).equals( + VersionsJoinTableRangeTestEntity.class, vjtrte_id + ) + ); + assert Arrays.asList( 2 ).equals( getAuditReader().getRevisions( VersionsJoinTableRangeTestAlternateEntity.class, - vjtrtae_id1)); + vjtrtae_id1 + ) + ); } @Test public void testHistoryOfUniId1() { VersionsJoinTableRangeTestEntity vjtrte = getEntityManager().find( - VersionsJoinTableRangeTestEntity.class, vjtrte_id); + VersionsJoinTableRangeTestEntity.class, vjtrte_id + ); VersionsJoinTableRangeTestAlternateEntity vjtrtae = getEntityManager() - .find(VersionsJoinTableRangeTestAlternateEntity.class, - vjtrtae_id1); + .find( + VersionsJoinTableRangeTestAlternateEntity.class, + vjtrtae_id1 + ); VersionsJoinTableRangeComponentTestEntity rev1 = getAuditReader().find( - VersionsJoinTableRangeComponentTestEntity.class, vjrcte_id, 1); + VersionsJoinTableRangeComponentTestEntity.class, vjrcte_id, 1 + ); VersionsJoinTableRangeComponentTestEntity rev2 = getAuditReader().find( - VersionsJoinTableRangeComponentTestEntity.class, vjrcte_id, 2); + VersionsJoinTableRangeComponentTestEntity.class, vjrcte_id, 2 + ); assert rev1.getComponent1().getRange().size() == 0; assert rev1.getComponent2().getRange().size() == 0; assert rev2.getComponent1().getRange().size() == 1; - assert rev2.getComponent1().getRange().get(0).equals(vjtrte); + assert rev2.getComponent1().getRange().get( 0 ).equals( vjtrte ); assert rev2.getComponent2().getRange().size() == 1; - assert rev2.getComponent2().getRange().get(0).equals(vjtrtae); + assert rev2.getComponent2().getRange().get( 0 ).equals( vjtrtae ); } /* The Audit join tables we expect */ @@ -182,54 +199,63 @@ public class VersionsJoinTableRangeComponentNamingTest extends @Test public void testExpectedTableNameComponent1() { PersistentClass auditClass = getCfg().getClassMapping( - COMPONENT_1_AUDIT_JOIN_TABLE_NAME); + COMPONENT_1_AUDIT_JOIN_TABLE_NAME + ); assert auditClass != null; - assert COMPONENT_1_AUDIT_JOIN_TABLE_NAME.equals(auditClass.getTable() - .getName()); + assert COMPONENT_1_AUDIT_JOIN_TABLE_NAME.equals( + auditClass.getTable() + .getName() + ); } @Test public void testExpectedTableNameComponent2() { PersistentClass auditClass = getCfg().getClassMapping( - COMPONENT_2_AUDIT_JOIN_TABLE_NAME); + COMPONENT_2_AUDIT_JOIN_TABLE_NAME + ); assert auditClass != null; - assert COMPONENT_2_AUDIT_JOIN_TABLE_NAME.equals(auditClass.getTable() - .getName()); + assert COMPONENT_2_AUDIT_JOIN_TABLE_NAME.equals( + auditClass.getTable() + .getName() + ); } @Test public void testWrongTableNameComponent1() { PersistentClass auditClass = getCfg().getClassMapping( - UNMODIFIED_COMPONENT_1_AUDIT_JOIN_TABLE_NAME); + UNMODIFIED_COMPONENT_1_AUDIT_JOIN_TABLE_NAME + ); assert auditClass == null; } @Test public void testWrongTableNameComponent2() { PersistentClass auditClass = getCfg().getClassMapping( - UNMODIFIED_COMPONENT_2_AUDIT_JOIN_TABLE_NAME); + UNMODIFIED_COMPONENT_2_AUDIT_JOIN_TABLE_NAME + ); assert auditClass == null; } @Test public void testJoinColumnNamesComponent1() { PersistentClass auditClass = getCfg().getClassMapping( - COMPONENT_1_AUDIT_JOIN_TABLE_NAME); + COMPONENT_1_AUDIT_JOIN_TABLE_NAME + ); assert auditClass != null; - @SuppressWarnings( { "unchecked" }) + @SuppressWarnings({"unchecked"}) Iterator columns = auditClass.getTable().getColumnIterator(); boolean id1Found = false; boolean id2Found = false; - while (columns.hasNext()) { + while ( columns.hasNext() ) { Column column = columns.next(); - if ("VJTRCTE1_ID".equals(column.getName())) { + if ( "VJTRCTE1_ID".equals( column.getName() ) ) { id1Found = true; } - if ("VJTRTE_ID".equals(column.getName())) { + if ( "VJTRTE_ID".equals( column.getName() ) ) { id2Found = true; } } @@ -240,22 +266,23 @@ public class VersionsJoinTableRangeComponentNamingTest extends @Test public void testJoinColumnNamesComponent2() { PersistentClass auditClass = getCfg().getClassMapping( - COMPONENT_2_AUDIT_JOIN_TABLE_NAME); + COMPONENT_2_AUDIT_JOIN_TABLE_NAME + ); assert auditClass != null; - @SuppressWarnings( { "unchecked" }) + @SuppressWarnings({"unchecked"}) Iterator columns = auditClass.getTable().getColumnIterator(); boolean id1Found = false; boolean id2Found = false; - while (columns.hasNext()) { + while ( columns.hasNext() ) { Column column = columns.next(); - if ("VJTRCTE2_ID".equals(column.getName())) { + if ( "VJTRCTE2_ID".equals( column.getName() ) ) { id1Found = true; } - if ("VJTRTAE_ID".equals(column.getName())) { + if ( "VJTRTAE_ID".equals( column.getName() ) ) { id2Found = true; } } @@ -272,22 +299,23 @@ public class VersionsJoinTableRangeComponentNamingTest extends public void testOverrideNotAudited() { PersistentClass auditClass = getCfg().getClassMapping( VersionsJoinTableRangeComponentTestEntity.class.getName() - + "_AUD"); + + "_AUD" + ); assert auditClass != null; - @SuppressWarnings( { "unchecked" }) + @SuppressWarnings({"unchecked"}) Iterator columns = auditClass.getTable().getColumnIterator(); boolean auditColumn1Found = false; boolean auditColumn2Found = false; - while (columns.hasNext()) { + while ( columns.hasNext() ) { Column column = columns.next(); - if ("STR1".equals(column.getName())) { + if ( "STR1".equals( column.getName() ) ) { auditColumn1Found = true; } - if ("STR2".equals(column.getName())) { + if ( "STR2".equals( column.getName() ) ) { auditColumn2Found = true; } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeComponentTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeComponentTestEntity.java index a78ee7ba8e..40c7025a11 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeComponentTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeComponentTestEntity.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.integration.naming; + import javax.persistence.AssociationOverride; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; @@ -17,7 +18,7 @@ import org.hibernate.envers.test.entities.components.Component1; /** * Test entity, containing two embedded components, which each contain a list of * {@link VersionsJoinTableRangeTestEntitySuperClass}-instances - * + * * @author Erik-Berndt Scheper */ @Entity @@ -33,9 +34,17 @@ public class VersionsJoinTableRangeComponentTestEntity { * {@link VersionsJoinTableRangeTestEntity}-instances. */ @Embedded - @AssociationOverride(name = "range", joinColumns = { @JoinColumn(name = "VJTRCTE1_ID", insertable = true, updatable = false, nullable = false) }) + @AssociationOverride(name = "range", + joinColumns = { + @JoinColumn(name = "VJTRCTE1_ID", + insertable = true, + updatable = false, + nullable = false) + }) @org.hibernate.envers.Audited - @AuditOverride(name = "range", auditJoinTable = @org.hibernate.envers.AuditJoinTable(name = "JOIN_TABLE_COMPONENT_1_AUD", inverseJoinColumns = @JoinColumn(name = "VJTRTE_ID"))) + @AuditOverride(name = "range", + auditJoinTable = @org.hibernate.envers.AuditJoinTable(name = "JOIN_TABLE_COMPONENT_1_AUD", + inverseJoinColumns = @JoinColumn(name = "VJTRTE_ID"))) private VersionsJoinTableRangeComponent component1 = new VersionsJoinTableRangeComponent(); /** @@ -43,20 +52,33 @@ public class VersionsJoinTableRangeComponentTestEntity { * {@link VersionsJoinTableRangeTestAlternateEntity}-instances. */ @Embedded - @AssociationOverride(name = "range", joinColumns = { @JoinColumn(name = "VJTRCTE2_ID", insertable = true, updatable = false, nullable = false) }) + @AssociationOverride(name = "range", + joinColumns = { + @JoinColumn(name = "VJTRCTE2_ID", + insertable = true, + updatable = false, + nullable = false) + }) @org.hibernate.envers.Audited - @AuditOverrides(value = { @AuditOverride(name = "range", auditJoinTable = @org.hibernate.envers.AuditJoinTable(name = "JOIN_TABLE_COMPONENT_2_AUD", inverseJoinColumns = @JoinColumn(name = "VJTRTAE_ID"))) }) + @AuditOverrides(value = { + @AuditOverride(name = "range", + auditJoinTable = @org.hibernate.envers.AuditJoinTable(name = "JOIN_TABLE_COMPONENT_2_AUD", + inverseJoinColumns = @JoinColumn(name = "VJTRTAE_ID"))) + }) private VersionsJoinTableRangeComponent component2 = new VersionsJoinTableRangeComponent(); /** * An embedded component, containing a list of NOT AUDITED * {@link VersionsJoinTableRangeTestAlternateEntity}-instances. */ - @Embedded - @AttributeOverrides(value={@AttributeOverride(name="str1", column=@Column(name="STR1")), @AttributeOverride(name="str2", column=@Column(name="STR2"))}) + @Embedded + @AttributeOverrides(value = { + @AttributeOverride(name = "str1", column = @Column(name = "STR1")), + @AttributeOverride(name = "str2", column = @Column(name = "STR2")) + }) @org.hibernate.envers.Audited - @AuditOverrides(value={@AuditOverride(name="str2", isAudited = false)}) - private Component1 component3; + @AuditOverrides(value = {@AuditOverride(name = "str2", isAudited = false)}) + private Component1 component3; /** * Default constructor @@ -73,8 +95,7 @@ public class VersionsJoinTableRangeComponentTestEntity { } /** - * @param id - * the id to set + * @param id the id to set */ protected void setId(Integer id) { this.id = id; @@ -88,8 +109,7 @@ public class VersionsJoinTableRangeComponentTestEntity { } /** - * @param component1 - * the component1 to set + * @param component1 the component1 to set */ public void setComponent1( VersionsJoinTableRangeComponent component1) { @@ -104,8 +124,7 @@ public class VersionsJoinTableRangeComponentTestEntity { } /** - * @param component2 - * the component2 to set + * @param component2 the component2 to set */ public void setComponent2( VersionsJoinTableRangeComponent component2) { @@ -120,8 +139,7 @@ public class VersionsJoinTableRangeComponentTestEntity { } /** - * @param component3 - * the component3 to set + * @param component3 the component3 to set */ public void setComponent3(Component1 component3) { this.component3 = component3; @@ -143,33 +161,48 @@ public class VersionsJoinTableRangeComponentTestEntity { @Override public boolean equals(Object obj) { - if (this == obj) + if ( this == obj ) { return true; - if (obj == null) + } + if ( obj == null ) { return false; - if (getClass() != obj.getClass()) + } + if ( getClass() != obj.getClass() ) { return false; + } VersionsJoinTableRangeComponentTestEntity other = (VersionsJoinTableRangeComponentTestEntity) obj; - if (component1 == null) { - if (other.component1 != null) + if ( component1 == null ) { + if ( other.component1 != null ) { return false; - } else if (!component1.equals(other.component1)) + } + } + else if ( !component1.equals( other.component1 ) ) { return false; - if (component2 == null) { - if (other.component2 != null) + } + if ( component2 == null ) { + if ( other.component2 != null ) { return false; - } else if (!component2.equals(other.component2)) + } + } + else if ( !component2.equals( other.component2 ) ) { return false; - if (component3 == null) { - if (other.component3 != null) + } + if ( component3 == null ) { + if ( other.component3 != null ) { return false; - } else if (!component3.equals(other.component3)) + } + } + else if ( !component3.equals( other.component3 ) ) { return false; - if (id == null) { - if (other.id != null) + } + if ( id == null ) { + if ( other.id != null ) { return false; - } else if (!id.equals(other.id)) + } + } + else if ( !id.equals( other.id ) ) { return false; + } return true; } @@ -177,12 +210,12 @@ public class VersionsJoinTableRangeComponentTestEntity { public String toString() { StringBuilder output = new StringBuilder(); - output.append("VersionsJoinTableRangeComponentTestEntity {"); - output.append(" id = \"").append(this.getId()).append("\","); - output.append(" component1 = \"").append(this.component1) - .append("\", "); - output.append(" component2 = \"").append(this.component2).append("\"}"); - output.append(" component3 = \"").append(this.component3).append("\"}"); + output.append( "VersionsJoinTableRangeComponentTestEntity {" ); + output.append( " id = \"" ).append( this.getId() ).append( "\"," ); + output.append( " component1 = \"" ).append( this.component1 ) + .append( "\", " ); + output.append( " component2 = \"" ).append( this.component2 ).append( "\"}" ); + output.append( " component3 = \"" ).append( this.component3 ).append( "\"}" ); return output.toString(); } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeTestAlternateEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeTestAlternateEntity.java index 94470bb4be..eb7f608359 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeTestAlternateEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeTestAlternateEntity.java @@ -1,10 +1,11 @@ package org.hibernate.envers.test.integration.naming; + import javax.persistence.Entity; import javax.persistence.Table; /** * Alternate implementation of mapped superclass for Audit join table test. - * + * * @author Erik-Berndt Scheper * @see VersionsJoinTableRangeTestEntity * @see VersionsJoinTableRangeTestEntitySuperClass @@ -13,7 +14,7 @@ import javax.persistence.Table; @Table(name = "RANGE_TEST_ALTERNATE_ENT") @org.hibernate.envers.Audited public class VersionsJoinTableRangeTestAlternateEntity extends - VersionsJoinTableRangeTestEntitySuperClass { + VersionsJoinTableRangeTestEntitySuperClass { private String alternateValue; @@ -32,8 +33,7 @@ public class VersionsJoinTableRangeTestAlternateEntity extends } /** - * @param alternateValue - * the alternateValue to set + * @param alternateValue the alternateValue to set */ public void setAlternateValue(String alternateValue) { this.alternateValue = alternateValue; @@ -50,18 +50,24 @@ public class VersionsJoinTableRangeTestAlternateEntity extends @Override public boolean equals(Object obj) { - if (this == obj) + if ( this == obj ) { return true; - if (!super.equals(obj)) + } + if ( !super.equals( obj ) ) { return false; - if (getClass() != obj.getClass()) + } + if ( getClass() != obj.getClass() ) { return false; + } VersionsJoinTableRangeTestAlternateEntity other = (VersionsJoinTableRangeTestAlternateEntity) obj; - if (alternateValue == null) { - if (other.alternateValue != null) + if ( alternateValue == null ) { + if ( other.alternateValue != null ) { return false; - } else if (!alternateValue.equals(other.alternateValue)) + } + } + else if ( !alternateValue.equals( other.alternateValue ) ) { return false; + } return true; } @@ -69,12 +75,13 @@ public class VersionsJoinTableRangeTestAlternateEntity extends public String toString() { StringBuilder output = new StringBuilder(); - output.append("VersionsJoinTableRangeComponentTestEntity {"); - output.append(" id = \"").append(getId()).append("\", "); - output.append(" genericValue = \"").append(getGenericValue()).append( - "\", "); - output.append(" alternateValue = \"").append(this.alternateValue) - .append("\"}"); + output.append( "VersionsJoinTableRangeComponentTestEntity {" ); + output.append( " id = \"" ).append( getId() ).append( "\", " ); + output.append( " genericValue = \"" ).append( getGenericValue() ).append( + "\", " + ); + output.append( " alternateValue = \"" ).append( this.alternateValue ) + .append( "\"}" ); return output.toString(); } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeTestEntity.java index a0c9ccfa4c..ec943a7aaf 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeTestEntity.java @@ -1,10 +1,11 @@ package org.hibernate.envers.test.integration.naming; + import javax.persistence.Entity; import javax.persistence.Table; /** * Concrete implementation of mapped superclass for Audit join table test. - * + * * @author Erik-Berndt Scheper * @see VersionsJoinTableRangeTestAlternateEntity * @see VersionsJoinTableRangeTestEntitySuperClass @@ -13,7 +14,7 @@ import javax.persistence.Table; @Table(name = "RANGE_TEST_ENTITY") @org.hibernate.envers.Audited public class VersionsJoinTableRangeTestEntity extends - VersionsJoinTableRangeTestEntitySuperClass { + VersionsJoinTableRangeTestEntitySuperClass { private String value; @@ -32,8 +33,7 @@ public class VersionsJoinTableRangeTestEntity extends } /** - * @param value - * the value to set + * @param value the value to set */ public void setValue(String value) { this.value = value; @@ -49,18 +49,24 @@ public class VersionsJoinTableRangeTestEntity extends @Override public boolean equals(Object obj) { - if (this == obj) + if ( this == obj ) { return true; - if (!super.equals(obj)) + } + if ( !super.equals( obj ) ) { return false; - if (getClass() != obj.getClass()) + } + if ( getClass() != obj.getClass() ) { return false; + } VersionsJoinTableRangeTestEntity other = (VersionsJoinTableRangeTestEntity) obj; - if (value == null) { - if (other.value != null) + if ( value == null ) { + if ( other.value != null ) { return false; - } else if (!value.equals(other.value)) + } + } + else if ( !value.equals( other.value ) ) { return false; + } return true; } @@ -68,11 +74,12 @@ public class VersionsJoinTableRangeTestEntity extends public String toString() { StringBuilder output = new StringBuilder(); - output.append("VersionsJoinTableRangeComponentTestEntity {"); - output.append(" id = \"").append(getId()).append("\", "); - output.append(" genericValue = \"").append(getGenericValue()).append( - "\", "); - output.append(" value = \"").append(this.value).append("\"}"); + output.append( "VersionsJoinTableRangeComponentTestEntity {" ); + output.append( " id = \"" ).append( getId() ).append( "\", " ); + output.append( " genericValue = \"" ).append( getGenericValue() ).append( + "\", " + ); + output.append( " value = \"" ).append( this.value ).append( "\"}" ); return output.toString(); } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeTestEntitySuperClass.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeTestEntitySuperClass.java index a93a901185..bd770f95cf 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeTestEntitySuperClass.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableRangeTestEntitySuperClass.java @@ -1,11 +1,12 @@ package org.hibernate.envers.test.integration.naming; + import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.MappedSuperclass; /** * Mapped superclass for Audit join table test. - * + * * @author Erik-Berndt Scheper */ @MappedSuperclass @@ -26,8 +27,7 @@ public abstract class VersionsJoinTableRangeTestEntitySuperClass { } /** - * @param id - * the id to set + * @param id the id to set */ protected void setId(Integer id) { this.id = id; @@ -41,8 +41,7 @@ public abstract class VersionsJoinTableRangeTestEntitySuperClass { } /** - * @param genericValue - * the genericValue to set + * @param genericValue the genericValue to set */ public void setGenericValue(String genericValue) { this.genericValue = genericValue; @@ -60,23 +59,32 @@ public abstract class VersionsJoinTableRangeTestEntitySuperClass { @Override public boolean equals(Object obj) { - if (this == obj) + if ( this == obj ) { return true; - if (obj == null) + } + if ( obj == null ) { return false; - if (getClass() != obj.getClass()) + } + if ( getClass() != obj.getClass() ) { return false; + } VersionsJoinTableRangeTestEntitySuperClass other = (VersionsJoinTableRangeTestEntitySuperClass) obj; - if (genericValue == null) { - if (other.genericValue != null) + if ( genericValue == null ) { + if ( other.genericValue != null ) { return false; - } else if (!genericValue.equals(other.genericValue)) + } + } + else if ( !genericValue.equals( other.genericValue ) ) { return false; - if (id == null) { - if (other.id != null) + } + if ( id == null ) { + if ( other.id != null ) { return false; - } else if (!id.equals(other.id)) + } + } + else if ( !id.equals( other.id ) ) { return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableTestEntity.java index a1eca35046..cbfce2348d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/VersionsJoinTableTestEntity.java @@ -22,12 +22,13 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.naming; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; +import java.util.Set; import org.hibernate.envers.AuditJoinTable; import org.hibernate.envers.Audited; @@ -39,74 +40,82 @@ import org.hibernate.envers.test.entities.StrTestEntity; @Entity @Table(name = "VersionsJoinTable") public class VersionsJoinTableTestEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToMany - @JoinColumn(name = "VJT_ID") - @AuditJoinTable(name = "VERSIONS_JOIN_TABLE_TEST", inverseJoinColumns = @JoinColumn(name = "STR_ID")) - private Set collection; + @Audited + @OneToMany + @JoinColumn(name = "VJT_ID") + @AuditJoinTable(name = "VERSIONS_JOIN_TABLE_TEST", inverseJoinColumns = @JoinColumn(name = "STR_ID")) + private Set collection; - public VersionsJoinTableTestEntity() { - } + public VersionsJoinTableTestEntity() { + } - public VersionsJoinTableTestEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public VersionsJoinTableTestEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public VersionsJoinTableTestEntity(String data) { - this.data = data; - } + public VersionsJoinTableTestEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Set getCollection() { - return collection; - } + public Set getCollection() { + return collection; + } - public void setCollection(Set collection) { - this.collection = collection; - } + public void setCollection(Set collection) { + this.collection = collection; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof VersionsJoinTableTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof VersionsJoinTableTestEntity) ) { + return false; + } - VersionsJoinTableTestEntity that = (VersionsJoinTableTestEntity) o; + VersionsJoinTableTestEntity that = (VersionsJoinTableTestEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "VersionsJoinTableTestEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "VersionsJoinTableTestEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/EmbIdNaming.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/EmbIdNaming.java index bf0ea35f7b..33189ad0bb 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/EmbIdNaming.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/EmbIdNaming.java @@ -22,65 +22,74 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.naming.ids; -import java.io.Serializable; + import javax.persistence.Column; import javax.persistence.Embeddable; +import java.io.Serializable; /** * @author Adam Warski (adam at warski dot org) */ @Embeddable public class EmbIdNaming implements Serializable { - @Column(name = "XX") - private Integer x; + @Column(name = "XX") + private Integer x; - @Column(name = "YY") - private Integer y; + @Column(name = "YY") + private Integer y; - public EmbIdNaming() { - } + public EmbIdNaming() { + } - public EmbIdNaming(Integer x, Integer y) { - this.x = x; - this.y = y; - } + public EmbIdNaming(Integer x, Integer y) { + this.x = x; + this.y = y; + } - public Integer getX() { - return x; - } + public Integer getX() { + return x; + } - public void setX(Integer x) { - this.x = x; - } + public void setX(Integer x) { + this.x = x; + } - public Integer getY() { - return y; - } + public Integer getY() { + return y; + } - public void setY(Integer y) { - this.y = y; - } + public void setY(Integer y) { + this.y = y; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof EmbIdNaming)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof EmbIdNaming) ) { + return false; + } - EmbIdNaming embId = (EmbIdNaming) o; + EmbIdNaming embId = (EmbIdNaming) o; - if (x != null ? !x.equals(embId.x) : embId.x != null) return false; - if (y != null ? !y.equals(embId.y) : embId.y != null) return false; + if ( x != null ? !x.equals( embId.x ) : embId.x != null ) { + return false; + } + if ( y != null ? !y.equals( embId.y ) : embId.y != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (x != null ? x.hashCode() : 0); - result = 31 * result + (y != null ? y.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (x != null ? x.hashCode() : 0); + result = 31 * result + (y != null ? y.hashCode() : 0); + return result; + } - public String toString() { - return "EmbIdNaming(" + x + ", " + y + ")"; - } + public String toString() { + return "EmbIdNaming(" + x + ", " + y + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinEmbIdNaming.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinEmbIdNaming.java index 2825cbe802..cbb4ac50c8 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinEmbIdNaming.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinEmbIdNaming.java @@ -23,16 +23,16 @@ */ package org.hibernate.envers.test.integration.naming.ids; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Iterator; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.mapping.Column; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; @@ -41,101 +41,122 @@ import static junit.framework.Assert.assertTrue; * @author Adam Warski (adam at warski dot org) */ public class JoinEmbIdNaming extends BaseEnversJPAFunctionalTestCase { - private EmbIdNaming ed_id1; - private EmbIdNaming ed_id2; - private EmbIdNaming ing_id1; + private EmbIdNaming ed_id1; + private EmbIdNaming ed_id2; + private EmbIdNaming ing_id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { JoinEmbIdNamingRefEdEntity.class, JoinEmbIdNamingRefIngEntity.class }; - } + return new Class[] {JoinEmbIdNamingRefEdEntity.class, JoinEmbIdNamingRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - ed_id1 = new EmbIdNaming(10, 20); - ed_id2 = new EmbIdNaming(11, 21); - ing_id1 = new EmbIdNaming(12, 22); + @Test + @Priority(10) + public void initData() { + ed_id1 = new EmbIdNaming( 10, 20 ); + ed_id2 = new EmbIdNaming( 11, 21 ); + ing_id1 = new EmbIdNaming( 12, 22 ); - JoinEmbIdNamingRefEdEntity ed1 = new JoinEmbIdNamingRefEdEntity(ed_id1, "data1"); - JoinEmbIdNamingRefEdEntity ed2 = new JoinEmbIdNamingRefEdEntity(ed_id2, "data2"); + JoinEmbIdNamingRefEdEntity ed1 = new JoinEmbIdNamingRefEdEntity( ed_id1, "data1" ); + JoinEmbIdNamingRefEdEntity ed2 = new JoinEmbIdNamingRefEdEntity( ed_id2, "data2" ); - JoinEmbIdNamingRefIngEntity ing1 = new JoinEmbIdNamingRefIngEntity(ing_id1, "x", ed1); + JoinEmbIdNamingRefIngEntity ing1 = new JoinEmbIdNamingRefIngEntity( ing_id1, "x", ed1 ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); - em.persist(ing1); + em.persist( ed1 ); + em.persist( ed2 ); + em.persist( ing1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ed2 = em.find(JoinEmbIdNamingRefEdEntity.class, ed2.getId()); + ed2 = em.find( JoinEmbIdNamingRefEdEntity.class, ed2.getId() ); - ing1 = em.find(JoinEmbIdNamingRefIngEntity.class, ing1.getId()); - ing1.setData("y"); - ing1.setReference(ed2); + ing1 = em.find( JoinEmbIdNamingRefIngEntity.class, ing1.getId() ); + ing1.setData( "y" ); + ing1.setReference( ed2 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(JoinEmbIdNamingRefEdEntity.class, ed_id1)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(JoinEmbIdNamingRefEdEntity.class, ed_id2)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(JoinEmbIdNamingRefIngEntity.class, ing_id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( + JoinEmbIdNamingRefEdEntity.class, + ed_id1 + ) + ); + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( + JoinEmbIdNamingRefEdEntity.class, + ed_id2 + ) + ); + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( + JoinEmbIdNamingRefIngEntity.class, + ing_id1 + ) + ); + } - @Test - public void testHistoryOfEdId1() { - JoinEmbIdNamingRefEdEntity ver1 = new JoinEmbIdNamingRefEdEntity(ed_id1, "data1"); + @Test + public void testHistoryOfEdId1() { + JoinEmbIdNamingRefEdEntity ver1 = new JoinEmbIdNamingRefEdEntity( ed_id1, "data1" ); - assert getAuditReader().find(JoinEmbIdNamingRefEdEntity.class, ed_id1, 1).equals(ver1); - assert getAuditReader().find(JoinEmbIdNamingRefEdEntity.class, ed_id1, 2).equals(ver1); - } + assert getAuditReader().find( JoinEmbIdNamingRefEdEntity.class, ed_id1, 1 ).equals( ver1 ); + assert getAuditReader().find( JoinEmbIdNamingRefEdEntity.class, ed_id1, 2 ).equals( ver1 ); + } - @Test - public void testHistoryOfEdId2() { - JoinEmbIdNamingRefEdEntity ver1 = new JoinEmbIdNamingRefEdEntity(ed_id2, "data2"); + @Test + public void testHistoryOfEdId2() { + JoinEmbIdNamingRefEdEntity ver1 = new JoinEmbIdNamingRefEdEntity( ed_id2, "data2" ); - assert getAuditReader().find(JoinEmbIdNamingRefEdEntity.class, ed_id2, 1).equals(ver1); - assert getAuditReader().find(JoinEmbIdNamingRefEdEntity.class, ed_id2, 2).equals(ver1); - } + assert getAuditReader().find( JoinEmbIdNamingRefEdEntity.class, ed_id2, 1 ).equals( ver1 ); + assert getAuditReader().find( JoinEmbIdNamingRefEdEntity.class, ed_id2, 2 ).equals( ver1 ); + } - @Test - public void testHistoryOfIngId1() { - JoinEmbIdNamingRefIngEntity ver1 = new JoinEmbIdNamingRefIngEntity(ing_id1, "x", null); - JoinEmbIdNamingRefIngEntity ver2 = new JoinEmbIdNamingRefIngEntity(ing_id1, "y", null); + @Test + public void testHistoryOfIngId1() { + JoinEmbIdNamingRefIngEntity ver1 = new JoinEmbIdNamingRefIngEntity( ing_id1, "x", null ); + JoinEmbIdNamingRefIngEntity ver2 = new JoinEmbIdNamingRefIngEntity( ing_id1, "y", null ); - assert getAuditReader().find(JoinEmbIdNamingRefIngEntity.class, ing_id1, 1).equals(ver1); - assert getAuditReader().find(JoinEmbIdNamingRefIngEntity.class, ing_id1, 2).equals(ver2); + assert getAuditReader().find( JoinEmbIdNamingRefIngEntity.class, ing_id1, 1 ).equals( ver1 ); + assert getAuditReader().find( JoinEmbIdNamingRefIngEntity.class, ing_id1, 2 ).equals( ver2 ); - assert getAuditReader().find(JoinEmbIdNamingRefIngEntity.class, ing_id1, 1).getReference().equals( - new JoinEmbIdNamingRefEdEntity(ed_id1, "data1")); - assert getAuditReader().find(JoinEmbIdNamingRefIngEntity.class, ing_id1, 2).getReference().equals( - new JoinEmbIdNamingRefEdEntity(ed_id2, "data2")); - } + assert getAuditReader().find( JoinEmbIdNamingRefIngEntity.class, ing_id1, 1 ).getReference().equals( + new JoinEmbIdNamingRefEdEntity( ed_id1, "data1" ) + ); + assert getAuditReader().find( JoinEmbIdNamingRefIngEntity.class, ing_id1, 2 ).getReference().equals( + new JoinEmbIdNamingRefEdEntity( ed_id2, "data2" ) + ); + } - @SuppressWarnings({"unchecked"}) - @Test - public void testJoinColumnNames() { + @SuppressWarnings({"unchecked"}) + @Test + public void testJoinColumnNames() { Iterator columns = - getCfg().getClassMapping("org.hibernate.envers.test.integration.naming.ids.JoinEmbIdNamingRefIngEntity_AUD") - .getProperty("reference_x").getColumnIterator(); - assertTrue(columns.hasNext()); - assertEquals("XX_reference", columns.next().getName()); - assertFalse(columns.hasNext()); + getCfg().getClassMapping( + "org.hibernate.envers.test.integration.naming.ids.JoinEmbIdNamingRefIngEntity_AUD" + ) + .getProperty( "reference_x" ).getColumnIterator(); + assertTrue( columns.hasNext() ); + assertEquals( "XX_reference", columns.next().getName() ); + assertFalse( columns.hasNext() ); - columns = getCfg().getClassMapping("org.hibernate.envers.test.integration.naming.ids.JoinEmbIdNamingRefIngEntity_AUD") - .getProperty("reference_y").getColumnIterator(); + columns = getCfg().getClassMapping( + "org.hibernate.envers.test.integration.naming.ids.JoinEmbIdNamingRefIngEntity_AUD" + ) + .getProperty( "reference_y" ).getColumnIterator(); - assertTrue(columns.hasNext()); - assertEquals("YY_reference", columns.next().getName()); - assertFalse(columns.hasNext()); + assertTrue( columns.hasNext() ); + assertEquals( "YY_reference", columns.next().getName() ); + assertFalse( columns.hasNext() ); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinEmbIdNamingRefEdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinEmbIdNamingRefEdEntity.java index af87776956..af8bd17527 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinEmbIdNamingRefEdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinEmbIdNamingRefEdEntity.java @@ -22,89 +22,99 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.naming.ids; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; +import java.util.List; import org.hibernate.envers.Audited; /** * ReferencEd entity + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "JoinEmbIdRefEd") public class JoinEmbIdNamingRefEdEntity { - @Id - @GeneratedValue - private EmbIdNaming id; + @Id + @GeneratedValue + private EmbIdNaming id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToMany(mappedBy="reference") - private List reffering; + @Audited + @OneToMany(mappedBy = "reference") + private List reffering; - public JoinEmbIdNamingRefEdEntity() { - } + public JoinEmbIdNamingRefEdEntity() { + } - public JoinEmbIdNamingRefEdEntity(EmbIdNaming id, String data) { - this.id = id; - this.data = data; - } + public JoinEmbIdNamingRefEdEntity(EmbIdNaming id, String data) { + this.id = id; + this.data = data; + } - public JoinEmbIdNamingRefEdEntity(String data) { - this.data = data; - } + public JoinEmbIdNamingRefEdEntity(String data) { + this.data = data; + } - public EmbIdNaming getId() { - return id; - } + public EmbIdNaming getId() { + return id; + } - public void setId(EmbIdNaming id) { - this.id = id; - } + public void setId(EmbIdNaming id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public List getReffering() { - return reffering; - } + public List getReffering() { + return reffering; + } - public void setReffering(List reffering) { - this.reffering = reffering; - } + public void setReffering(List reffering) { + this.reffering = reffering; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof JoinEmbIdNamingRefEdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof JoinEmbIdNamingRefEdEntity) ) { + return false; + } - JoinEmbIdNamingRefEdEntity that = (JoinEmbIdNamingRefEdEntity) o; + JoinEmbIdNamingRefEdEntity that = (JoinEmbIdNamingRefEdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "JoinEmbIdNamingRefEdEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "JoinEmbIdNamingRefEdEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinEmbIdNamingRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinEmbIdNamingRefIngEntity.java index ef563ad7b1..4ff6573840 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinEmbIdNamingRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinEmbIdNamingRefIngEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.naming.ids; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -34,81 +35,93 @@ import org.hibernate.envers.Audited; /** * ReferencIng entity + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "JoinEmbIdRefIng") public class JoinEmbIdNamingRefIngEntity { - @Id - @GeneratedValue - private EmbIdNaming id; + @Id + @GeneratedValue + private EmbIdNaming id; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToOne - @JoinColumns({@JoinColumn(name = "XX_reference", referencedColumnName = "XX"), - @JoinColumn(name = "YY_reference", referencedColumnName = "YY")}) - private JoinEmbIdNamingRefEdEntity reference; + @Audited + @ManyToOne + @JoinColumns({ + @JoinColumn(name = "XX_reference", referencedColumnName = "XX"), + @JoinColumn(name = "YY_reference", referencedColumnName = "YY") + }) + private JoinEmbIdNamingRefEdEntity reference; - public JoinEmbIdNamingRefIngEntity() { } + public JoinEmbIdNamingRefIngEntity() { + } - public JoinEmbIdNamingRefIngEntity(EmbIdNaming id, String data, JoinEmbIdNamingRefEdEntity reference) { - this.id = id; - this.data = data; - this.reference = reference; - } + public JoinEmbIdNamingRefIngEntity(EmbIdNaming id, String data, JoinEmbIdNamingRefEdEntity reference) { + this.id = id; + this.data = data; + this.reference = reference; + } - public JoinEmbIdNamingRefIngEntity(String data, JoinEmbIdNamingRefEdEntity reference) { - this.data = data; - this.reference = reference; - } + public JoinEmbIdNamingRefIngEntity(String data, JoinEmbIdNamingRefEdEntity reference) { + this.data = data; + this.reference = reference; + } - public EmbIdNaming getId() { - return id; - } + public EmbIdNaming getId() { + return id; + } - public void setId(EmbIdNaming id) { - this.id = id; - } + public void setId(EmbIdNaming id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public JoinEmbIdNamingRefEdEntity getReference() { - return reference; - } + public JoinEmbIdNamingRefEdEntity getReference() { + return reference; + } - public void setReference(JoinEmbIdNamingRefEdEntity reference) { - this.reference = reference; - } + public void setReference(JoinEmbIdNamingRefEdEntity reference) { + this.reference = reference; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof JoinEmbIdNamingRefIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof JoinEmbIdNamingRefIngEntity) ) { + return false; + } - JoinEmbIdNamingRefIngEntity that = (JoinEmbIdNamingRefIngEntity) o; + JoinEmbIdNamingRefIngEntity that = (JoinEmbIdNamingRefIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "JoinEmbIdNamingRefIngEntity(id = " + id + ", data = " + data + ")"; - } + public String toString() { + return "JoinEmbIdNamingRefIngEntity(id = " + id + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinMulIdNaming.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinMulIdNaming.java index 84f96a30b6..9d3a050172 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinMulIdNaming.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinMulIdNaming.java @@ -23,16 +23,16 @@ */ package org.hibernate.envers.test.integration.naming.ids; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Iterator; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.mapping.Column; +import org.junit.Test; + import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; @@ -41,100 +41,121 @@ import static junit.framework.Assert.assertTrue; * @author Adam Warski (adam at warski dot org) */ public class JoinMulIdNaming extends BaseEnversJPAFunctionalTestCase { - private MulIdNaming ed_id1; - private MulIdNaming ed_id2; - private MulIdNaming ing_id1; + private MulIdNaming ed_id1; + private MulIdNaming ed_id2; + private MulIdNaming ing_id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { JoinMulIdNamingRefEdEntity.class, JoinMulIdNamingRefIngEntity.class }; - } + return new Class[] {JoinMulIdNamingRefEdEntity.class, JoinMulIdNamingRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - ed_id1 = new MulIdNaming(10, 20); - ed_id2 = new MulIdNaming(11, 21); - ing_id1 = new MulIdNaming(12, 22); + @Test + @Priority(10) + public void initData() { + ed_id1 = new MulIdNaming( 10, 20 ); + ed_id2 = new MulIdNaming( 11, 21 ); + ing_id1 = new MulIdNaming( 12, 22 ); - JoinMulIdNamingRefEdEntity ed1 = new JoinMulIdNamingRefEdEntity(ed_id1, "data1"); - JoinMulIdNamingRefEdEntity ed2 = new JoinMulIdNamingRefEdEntity(ed_id2, "data2"); + JoinMulIdNamingRefEdEntity ed1 = new JoinMulIdNamingRefEdEntity( ed_id1, "data1" ); + JoinMulIdNamingRefEdEntity ed2 = new JoinMulIdNamingRefEdEntity( ed_id2, "data2" ); - JoinMulIdNamingRefIngEntity ing1 = new JoinMulIdNamingRefIngEntity(ing_id1, "x", ed1); + JoinMulIdNamingRefIngEntity ing1 = new JoinMulIdNamingRefIngEntity( ing_id1, "x", ed1 ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); - em.persist(ing1); + em.persist( ed1 ); + em.persist( ed2 ); + em.persist( ing1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ed2 = em.find(JoinMulIdNamingRefEdEntity.class, ed_id2); + ed2 = em.find( JoinMulIdNamingRefEdEntity.class, ed_id2 ); - ing1 = em.find(JoinMulIdNamingRefIngEntity.class, ing_id1); - ing1.setData("y"); - ing1.setReference(ed2); + ing1 = em.find( JoinMulIdNamingRefIngEntity.class, ing_id1 ); + ing1.setData( "y" ); + ing1.setReference( ed2 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(JoinMulIdNamingRefEdEntity.class, ed_id1)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(JoinMulIdNamingRefEdEntity.class, ed_id2)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(JoinMulIdNamingRefIngEntity.class, ing_id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( + JoinMulIdNamingRefEdEntity.class, + ed_id1 + ) + ); + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( + JoinMulIdNamingRefEdEntity.class, + ed_id2 + ) + ); + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( + JoinMulIdNamingRefIngEntity.class, + ing_id1 + ) + ); + } - @Test - public void testHistoryOfEdId1() { - JoinMulIdNamingRefEdEntity ver1 = new JoinMulIdNamingRefEdEntity(ed_id1, "data1"); + @Test + public void testHistoryOfEdId1() { + JoinMulIdNamingRefEdEntity ver1 = new JoinMulIdNamingRefEdEntity( ed_id1, "data1" ); - assert getAuditReader().find(JoinMulIdNamingRefEdEntity.class, ed_id1, 1).equals(ver1); - assert getAuditReader().find(JoinMulIdNamingRefEdEntity.class, ed_id1, 2).equals(ver1); - } + assert getAuditReader().find( JoinMulIdNamingRefEdEntity.class, ed_id1, 1 ).equals( ver1 ); + assert getAuditReader().find( JoinMulIdNamingRefEdEntity.class, ed_id1, 2 ).equals( ver1 ); + } - @Test - public void testHistoryOfEdId2() { - JoinMulIdNamingRefEdEntity ver1 = new JoinMulIdNamingRefEdEntity(ed_id2, "data2"); + @Test + public void testHistoryOfEdId2() { + JoinMulIdNamingRefEdEntity ver1 = new JoinMulIdNamingRefEdEntity( ed_id2, "data2" ); - assert getAuditReader().find(JoinMulIdNamingRefEdEntity.class, ed_id2, 1).equals(ver1); - assert getAuditReader().find(JoinMulIdNamingRefEdEntity.class, ed_id2, 2).equals(ver1); - } + assert getAuditReader().find( JoinMulIdNamingRefEdEntity.class, ed_id2, 1 ).equals( ver1 ); + assert getAuditReader().find( JoinMulIdNamingRefEdEntity.class, ed_id2, 2 ).equals( ver1 ); + } - @Test - public void testHistoryOfIngId1() { - JoinMulIdNamingRefIngEntity ver1 = new JoinMulIdNamingRefIngEntity(ing_id1, "x", null); - JoinMulIdNamingRefIngEntity ver2 = new JoinMulIdNamingRefIngEntity(ing_id1, "y", null); + @Test + public void testHistoryOfIngId1() { + JoinMulIdNamingRefIngEntity ver1 = new JoinMulIdNamingRefIngEntity( ing_id1, "x", null ); + JoinMulIdNamingRefIngEntity ver2 = new JoinMulIdNamingRefIngEntity( ing_id1, "y", null ); - assert getAuditReader().find(JoinMulIdNamingRefIngEntity.class, ing_id1, 1).equals(ver1); - assert getAuditReader().find(JoinMulIdNamingRefIngEntity.class, ing_id1, 2).equals(ver2); + assert getAuditReader().find( JoinMulIdNamingRefIngEntity.class, ing_id1, 1 ).equals( ver1 ); + assert getAuditReader().find( JoinMulIdNamingRefIngEntity.class, ing_id1, 2 ).equals( ver2 ); - assert getAuditReader().find(JoinMulIdNamingRefIngEntity.class, ing_id1, 1).getReference().equals( - new JoinMulIdNamingRefEdEntity(ed_id1, "data1")); - assert getAuditReader().find(JoinMulIdNamingRefIngEntity.class, ing_id1, 2).getReference().equals( - new JoinMulIdNamingRefEdEntity(ed_id2, "data2")); - } + assert getAuditReader().find( JoinMulIdNamingRefIngEntity.class, ing_id1, 1 ).getReference().equals( + new JoinMulIdNamingRefEdEntity( ed_id1, "data1" ) + ); + assert getAuditReader().find( JoinMulIdNamingRefIngEntity.class, ing_id1, 2 ).getReference().equals( + new JoinMulIdNamingRefEdEntity( ed_id2, "data2" ) + ); + } - @SuppressWarnings({"unchecked"}) - @Test - public void testJoinColumnNames() { + @SuppressWarnings({"unchecked"}) + @Test + public void testJoinColumnNames() { Iterator columns = - getCfg().getClassMapping("org.hibernate.envers.test.integration.naming.ids.JoinMulIdNamingRefIngEntity_AUD") - .getProperty("reference_id1").getColumnIterator(); - assertTrue(columns.hasNext()); - assertEquals("ID1_reference", columns.next().getName()); - assertFalse(columns.hasNext()); + getCfg().getClassMapping( + "org.hibernate.envers.test.integration.naming.ids.JoinMulIdNamingRefIngEntity_AUD" + ) + .getProperty( "reference_id1" ).getColumnIterator(); + assertTrue( columns.hasNext() ); + assertEquals( "ID1_reference", columns.next().getName() ); + assertFalse( columns.hasNext() ); - columns = getCfg().getClassMapping("org.hibernate.envers.test.integration.naming.ids.JoinMulIdNamingRefIngEntity_AUD") - .getProperty("reference_id2").getColumnIterator(); - assertTrue(columns.hasNext()); - assertEquals("ID2_reference", columns.next().getName()); - assertFalse(columns.hasNext()); + columns = getCfg().getClassMapping( + "org.hibernate.envers.test.integration.naming.ids.JoinMulIdNamingRefIngEntity_AUD" + ) + .getProperty( "reference_id2" ).getColumnIterator(); + assertTrue( columns.hasNext() ); + assertEquals( "ID2_reference", columns.next().getName() ); + assertFalse( columns.hasNext() ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinMulIdNamingRefEdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinMulIdNamingRefEdEntity.java index 08c0f93147..38b2830947 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinMulIdNamingRefEdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinMulIdNamingRefEdEntity.java @@ -22,103 +22,115 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.naming.ids; -import java.util.List; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; import javax.persistence.OneToMany; import javax.persistence.Table; +import java.util.List; import org.hibernate.envers.Audited; /** * ReferencEd entity + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "JoinMulIdRefEd") @IdClass(MulIdNaming.class) public class JoinMulIdNamingRefEdEntity { - @Id - private Integer id1; + @Id + private Integer id1; - @Id - private Integer id2; + @Id + private Integer id2; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToMany(mappedBy="reference") - private List reffering; + @Audited + @OneToMany(mappedBy = "reference") + private List reffering; - public JoinMulIdNamingRefEdEntity() { - } + public JoinMulIdNamingRefEdEntity() { + } - public JoinMulIdNamingRefEdEntity(MulIdNaming id, String data) { - this.id1 = id.getId1(); - this.id2 = id.getId2(); - this.data = data; - } + public JoinMulIdNamingRefEdEntity(MulIdNaming id, String data) { + this.id1 = id.getId1(); + this.id2 = id.getId2(); + this.data = data; + } - public JoinMulIdNamingRefEdEntity(String data) { - this.data = data; - } + public JoinMulIdNamingRefEdEntity(String data) { + this.data = data; + } - public Integer getId1() { - return id1; - } + public Integer getId1() { + return id1; + } - public void setId1(Integer id1) { - this.id1 = id1; - } + public void setId1(Integer id1) { + this.id1 = id1; + } - public Integer getId2() { - return id2; - } + public Integer getId2() { + return id2; + } - public void setId2(Integer id2) { - this.id2 = id2; - } + public void setId2(Integer id2) { + this.id2 = id2; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public List getReffering() { - return reffering; - } + public List getReffering() { + return reffering; + } - public void setReffering(List reffering) { - this.reffering = reffering; - } + public void setReffering(List reffering) { + this.reffering = reffering; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof JoinMulIdNamingRefEdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof JoinMulIdNamingRefEdEntity) ) { + return false; + } - JoinMulIdNamingRefEdEntity that = (JoinMulIdNamingRefEdEntity) o; + JoinMulIdNamingRefEdEntity that = (JoinMulIdNamingRefEdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id1 != null ? !id1.equals(that.id1) : that.id1 != null) return false; - if (id2 != null ? !id2.equals(that.id2) : that.id2 != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id1 != null ? !id1.equals( that.id1 ) : that.id1 != null ) { + return false; + } + if ( id2 != null ? !id2.equals( that.id2 ) : that.id2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id1 != null ? id1.hashCode() : 0); - result = 31 * result + (id2 != null ? id2.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id1 != null ? id1.hashCode() : 0); + result = 31 * result + (id2 != null ? id2.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "JoinMulIdNamingRefEdEntity(id1 = " + id1 + ", id2 = " + id2 + ", data = " + data + ")"; - } + public String toString() { + return "JoinMulIdNamingRefEdEntity(id1 = " + id1 + ", id2 = " + id2 + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinMulIdNamingRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinMulIdNamingRefIngEntity.java index a211b42ba5..3ea8273a83 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinMulIdNamingRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/JoinMulIdNamingRefIngEntity.java @@ -35,87 +35,101 @@ import org.hibernate.envers.Audited; /** * ReferencIng entity + * * @author Adam Warski (adam at warski dot org) */ @Entity @Table(name = "JoinMulIdRefIng") @IdClass(MulIdNaming.class) -public class JoinMulIdNamingRefIngEntity { - @Id - private Integer id1; +public class JoinMulIdNamingRefIngEntity { + @Id + private Integer id1; - @Id - private Integer id2; + @Id + private Integer id2; - @Audited - private String data; + @Audited + private String data; - @Audited - @ManyToOne - @JoinColumns({@JoinColumn(name = "ID2_reference", referencedColumnName = "ID_2"), - @JoinColumn(name = "ID1_reference", referencedColumnName = "ID_1")}) - private JoinMulIdNamingRefEdEntity reference; + @Audited + @ManyToOne + @JoinColumns({ + @JoinColumn(name = "ID2_reference", referencedColumnName = "ID_2"), + @JoinColumn(name = "ID1_reference", referencedColumnName = "ID_1") + }) + private JoinMulIdNamingRefEdEntity reference; - public JoinMulIdNamingRefIngEntity() { } + public JoinMulIdNamingRefIngEntity() { + } - public JoinMulIdNamingRefIngEntity(MulIdNaming id, String data, JoinMulIdNamingRefEdEntity reference) { - this.id1 = id.getId1(); - this.id2 = id.getId2(); - this.data = data; - this.reference = reference; - } + public JoinMulIdNamingRefIngEntity(MulIdNaming id, String data, JoinMulIdNamingRefEdEntity reference) { + this.id1 = id.getId1(); + this.id2 = id.getId2(); + this.data = data; + this.reference = reference; + } - public JoinMulIdNamingRefIngEntity(String data, JoinMulIdNamingRefEdEntity reference) { - this.data = data; - this.reference = reference; - } + public JoinMulIdNamingRefIngEntity(String data, JoinMulIdNamingRefEdEntity reference) { + this.data = data; + this.reference = reference; + } - public void setId1(Integer id1) { - this.id1 = id1; - } + public void setId1(Integer id1) { + this.id1 = id1; + } - public void setId2(Integer id2) { - this.id2 = id2; - } + public void setId2(Integer id2) { + this.id2 = id2; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public JoinMulIdNamingRefEdEntity getReference() { - return reference; - } + public JoinMulIdNamingRefEdEntity getReference() { + return reference; + } - public void setReference(JoinMulIdNamingRefEdEntity reference) { - this.reference = reference; - } + public void setReference(JoinMulIdNamingRefEdEntity reference) { + this.reference = reference; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof JoinMulIdNamingRefIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof JoinMulIdNamingRefIngEntity) ) { + return false; + } - JoinMulIdNamingRefIngEntity that = (JoinMulIdNamingRefIngEntity) o; + JoinMulIdNamingRefIngEntity that = (JoinMulIdNamingRefIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id1 != null ? !id1.equals(that.id1) : that.id1 != null) return false; - if (id2 != null ? !id2.equals(that.id2) : that.id2 != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id1 != null ? !id1.equals( that.id1 ) : that.id1 != null ) { + return false; + } + if ( id2 != null ? !id2.equals( that.id2 ) : that.id2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id1 != null ? id1.hashCode() : 0); - result = 31 * result + (id2 != null ? id2.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id1 != null ? id1.hashCode() : 0); + result = 31 * result + (id2 != null ? id2.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - public String toString() { - return "JoinMulIdNamingRefIngEntity(id1 = " + id1 + ", id2 = " + id2 + ", data = " + data + ")"; - } + public String toString() { + return "JoinMulIdNamingRefIngEntity(id1 = " + id1 + ", id2 = " + id2 + ", data = " + data + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/MulIdNaming.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/MulIdNaming.java index f52caa845d..4a4d3928b7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/MulIdNaming.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/ids/MulIdNaming.java @@ -22,63 +22,72 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.naming.ids; -import java.io.Serializable; + import javax.persistence.Column; +import java.io.Serializable; /** * @author Adam Warski (adam at warski dot org) */ public class MulIdNaming implements Serializable { - @Column(name = "ID_1") - private Integer id1; + @Column(name = "ID_1") + private Integer id1; - @Column(name = "ID_2") - private Integer id2; + @Column(name = "ID_2") + private Integer id2; - public MulIdNaming() { - } + public MulIdNaming() { + } - public MulIdNaming(Integer id1, Integer id2) { - this.id1 = id1; - this.id2 = id2; - } + public MulIdNaming(Integer id1, Integer id2) { + this.id1 = id1; + this.id2 = id2; + } - public Integer getId1() { - return id1; - } + public Integer getId1() { + return id1; + } - public void setId1(Integer id1) { - this.id1 = id1; - } + public void setId1(Integer id1) { + this.id1 = id1; + } - public Integer getId2() { - return id2; - } + public Integer getId2() { + return id2; + } - public void setId2(Integer id2) { - this.id2 = id2; - } + public void setId2(Integer id2) { + this.id2 = id2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof MulIdNaming)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof MulIdNaming) ) { + return false; + } - MulIdNaming mulId = (MulIdNaming) o; + MulIdNaming mulId = (MulIdNaming) o; - if (id1 != null ? !id1.equals(mulId.id1) : mulId.id1 != null) return false; - if (id2 != null ? !id2.equals(mulId.id2) : mulId.id2 != null) return false; + if ( id1 != null ? !id1.equals( mulId.id1 ) : mulId.id1 != null ) { + return false; + } + if ( id2 != null ? !id2.equals( mulId.id2 ) : mulId.id2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id1 != null ? id1.hashCode() : 0); - result = 31 * result + (id2 != null ? id2.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id1 != null ? id1.hashCode() : 0); + result = 31 * result + (id2 != null ? id2.hashCode() : 0); + return result; + } - public String toString() { - return "MulIdNaming(" + id1 + ", " + id2 + ")"; - } + public String toString() { + return "MulIdNaming(" + id1 + ", " + id2 + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/quotation/QuotedFieldsEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/quotation/QuotedFieldsEntity.java index d6013f25dc..c4ffc34207 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/quotation/QuotedFieldsEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/quotation/QuotedFieldsEntity.java @@ -12,84 +12,94 @@ import org.hibernate.envers.Audited; */ @Entity public class QuotedFieldsEntity { - @Id - @GeneratedValue - @Column(name = "`id`") - private Long id; + @Id + @GeneratedValue + @Column(name = "`id`") + private Long id; - @Column(name = "`data1`") - @Audited - private String data1; + @Column(name = "`data1`") + @Audited + private String data1; - @Column(name = "`data2`") - @Audited - private Integer data2; + @Column(name = "`data2`") + @Audited + private Integer data2; - public QuotedFieldsEntity() { - } + public QuotedFieldsEntity() { + } - public QuotedFieldsEntity(String data1, Integer data2) { - this.data1 = data1; - this.data2 = data2; - } + public QuotedFieldsEntity(String data1, Integer data2) { + this.data1 = data1; + this.data2 = data2; + } - public QuotedFieldsEntity(Long id, String data1, Integer data2) { - this.id = id; - this.data1 = data1; - this.data2 = data2; - } + public QuotedFieldsEntity(Long id, String data1, Integer data2) { + this.id = id; + this.data1 = data1; + this.data2 = data2; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getData1() { - return data1; - } + public String getData1() { + return data1; + } - public void setData1(String data1) { - this.data1 = data1; - } + public void setData1(String data1) { + this.data1 = data1; + } - public Integer getData2() { - return data2; - } + public Integer getData2() { + return data2; + } - public void setData2(Integer data2) { - this.data2 = data2; - } + public void setData2(Integer data2) { + this.data2 = data2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof QuotedFieldsEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof QuotedFieldsEntity) ) { + return false; + } - QuotedFieldsEntity that = (QuotedFieldsEntity) o; + QuotedFieldsEntity that = (QuotedFieldsEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (data1 != null ? !data1.equals(that.data1) : that.data1 != null) return false; - if (data2 != null ? !data2.equals(that.data2) : that.data2 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( data1 != null ? !data1.equals( that.data1 ) : that.data1 != null ) { + return false; + } + if ( data2 != null ? !data2.equals( that.data2 ) : that.data2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data1 != null ? data1.hashCode() : 0); - result = 31 * result + (data2 != null ? data2.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data1 != null ? data1.hashCode() : 0); + result = 31 * result + (data2 != null ? data2.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "QuotedFieldsEntity{" + - "id=" + id + - ", data1='" + data1 + '\'' + - ", data2=" + data2 + - '}'; - } + @Override + public String toString() { + return "QuotedFieldsEntity{" + + "id=" + id + + ", data1='" + data1 + '\'' + + ", data2=" + data2 + + '}'; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/quotation/QuotedFieldsTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/quotation/QuotedFieldsTest.java index 1e32f31edf..8ba87cdf0c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/quotation/QuotedFieldsTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/naming/quotation/QuotedFieldsTest.java @@ -1,105 +1,107 @@ package org.hibernate.envers.test.integration.naming.quotation; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Iterator; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.mapping.Column; import org.hibernate.mapping.Table; +import org.junit.Test; + /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class QuotedFieldsTest extends BaseEnversJPAFunctionalTestCase { - private Long qfeId1 = null; - private Long qfeId2 = null; + private Long qfeId1 = null; + private Long qfeId2 = null; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { QuotedFieldsEntity.class }; - } + return new Class[] {QuotedFieldsEntity.class}; + } - @Test - @Priority(10) - public void initData() { - QuotedFieldsEntity qfe1 = new QuotedFieldsEntity("data1", 1); - QuotedFieldsEntity qfe2 = new QuotedFieldsEntity("data2", 2); + @Test + @Priority(10) + public void initData() { + QuotedFieldsEntity qfe1 = new QuotedFieldsEntity( "data1", 1 ); + QuotedFieldsEntity qfe2 = new QuotedFieldsEntity( "data2", 2 ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - em.persist(qfe1); - em.persist(qfe2); - em.getTransaction().commit(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + em.persist( qfe1 ); + em.persist( qfe2 ); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); - qfe1 = em.find(QuotedFieldsEntity.class, qfe1.getId()); - qfe1.setData1("data1 changed"); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + qfe1 = em.find( QuotedFieldsEntity.class, qfe1.getId() ); + qfe1.setData1( "data1 changed" ); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); - qfe2 = em.find(QuotedFieldsEntity.class, qfe2.getId()); - qfe2.setData2(3); - em.getTransaction().commit(); + // Revision 3 + em.getTransaction().begin(); + qfe2 = em.find( QuotedFieldsEntity.class, qfe2.getId() ); + qfe2.setData2( 3 ); + em.getTransaction().commit(); - qfeId1 = qfe1.getId(); - qfeId2 = qfe2.getId(); - } + qfeId1 = qfe1.getId(); + qfeId2 = qfe2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(QuotedFieldsEntity.class, qfeId1)); - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(QuotedFieldsEntity.class, qfeId2)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( QuotedFieldsEntity.class, qfeId1 ) ); + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( QuotedFieldsEntity.class, qfeId2 ) ); + } - @Test - public void testHistoryOfId1() { - QuotedFieldsEntity ver1 = new QuotedFieldsEntity(qfeId1, "data1", 1); - QuotedFieldsEntity ver2 = new QuotedFieldsEntity(qfeId1, "data1 changed", 1); + @Test + public void testHistoryOfId1() { + QuotedFieldsEntity ver1 = new QuotedFieldsEntity( qfeId1, "data1", 1 ); + QuotedFieldsEntity ver2 = new QuotedFieldsEntity( qfeId1, "data1 changed", 1 ); - assert getAuditReader().find(QuotedFieldsEntity.class, qfeId1, 1).equals(ver1); - assert getAuditReader().find(QuotedFieldsEntity.class, qfeId1, 2).equals(ver2); - assert getAuditReader().find(QuotedFieldsEntity.class, qfeId1, 3).equals(ver2); - } + assert getAuditReader().find( QuotedFieldsEntity.class, qfeId1, 1 ).equals( ver1 ); + assert getAuditReader().find( QuotedFieldsEntity.class, qfeId1, 2 ).equals( ver2 ); + assert getAuditReader().find( QuotedFieldsEntity.class, qfeId1, 3 ).equals( ver2 ); + } - @Test - public void testHistoryOfId2() { - QuotedFieldsEntity ver1 = new QuotedFieldsEntity(qfeId2, "data2", 2); - QuotedFieldsEntity ver2 = new QuotedFieldsEntity(qfeId2, "data2", 3); + @Test + public void testHistoryOfId2() { + QuotedFieldsEntity ver1 = new QuotedFieldsEntity( qfeId2, "data2", 2 ); + QuotedFieldsEntity ver2 = new QuotedFieldsEntity( qfeId2, "data2", 3 ); - assert getAuditReader().find(QuotedFieldsEntity.class, qfeId2, 1).equals(ver1); - assert getAuditReader().find(QuotedFieldsEntity.class, qfeId2, 2).equals(ver1); - assert getAuditReader().find(QuotedFieldsEntity.class, qfeId2, 3).equals(ver2); - } + assert getAuditReader().find( QuotedFieldsEntity.class, qfeId2, 1 ).equals( ver1 ); + assert getAuditReader().find( QuotedFieldsEntity.class, qfeId2, 2 ).equals( ver1 ); + assert getAuditReader().find( QuotedFieldsEntity.class, qfeId2, 3 ).equals( ver2 ); + } - @Test - public void testEscapeEntityField() { - Table table = getCfg().getClassMapping("org.hibernate.envers.test.integration.naming.quotation.QuotedFieldsEntity_AUD").getTable(); - Column column1 = getColumnByName(table, "id"); - Column column2 = getColumnByName(table, "data1"); - Column column3 = getColumnByName(table, "data2"); - assert column1 != null; - assert column2 != null; - assert column3 != null; - assert column1.isQuoted(); - assert column2.isQuoted(); - assert column3.isQuoted(); - } + @Test + public void testEscapeEntityField() { + Table table = getCfg().getClassMapping( + "org.hibernate.envers.test.integration.naming.quotation.QuotedFieldsEntity_AUD" + ).getTable(); + Column column1 = getColumnByName( table, "id" ); + Column column2 = getColumnByName( table, "data1" ); + Column column3 = getColumnByName( table, "data2" ); + assert column1 != null; + assert column2 != null; + assert column3 != null; + assert column1.isQuoted(); + assert column2.isQuoted(); + assert column3.isQuoted(); + } - private Column getColumnByName(Table table, String columnName) { - Iterator columnIterator = table.getColumnIterator(); - while (columnIterator.hasNext()) { - Column column = columnIterator.next(); - if (columnName.equals(column.getName())) { - return column; - } - } - return null; - } + private Column getColumnByName(Table table, String columnName) { + Iterator columnIterator = table.getColumnIterator(); + while ( columnIterator.hasNext() ) { + Column column = columnIterator.next(); + if ( columnName.equals( column.getName() ) ) { + return column; + } + } + return null; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/NotInsertable.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/NotInsertable.java index 4e7e0fa426..36faba5fd0 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/NotInsertable.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/NotInsertable.java @@ -23,52 +23,52 @@ */ package org.hibernate.envers.test.integration.notinsertable; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class NotInsertable extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { NotInsertableTestEntity.class }; - } + return new Class[] {NotInsertableTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - NotInsertableTestEntity dte = new NotInsertableTestEntity("data1"); - em.persist(dte); - id1 = dte.getId(); - em.getTransaction().commit(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + NotInsertableTestEntity dte = new NotInsertableTestEntity( "data1" ); + em.persist( dte ); + id1 = dte.getId(); + em.getTransaction().commit(); - em.getTransaction().begin(); - dte = em.find(NotInsertableTestEntity.class, id1); - dte.setData("data2"); - em.getTransaction().commit(); - } + em.getTransaction().begin(); + dte = em.find( NotInsertableTestEntity.class, id1 ); + dte.setData( "data2" ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(NotInsertableTestEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( NotInsertableTestEntity.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - NotInsertableTestEntity ver1 = new NotInsertableTestEntity(id1, "data1", "data1"); - NotInsertableTestEntity ver2 = new NotInsertableTestEntity(id1, "data2", "data2"); + @Test + public void testHistoryOfId1() { + NotInsertableTestEntity ver1 = new NotInsertableTestEntity( id1, "data1", "data1" ); + NotInsertableTestEntity ver2 = new NotInsertableTestEntity( id1, "data2", "data2" ); - assert getAuditReader().find(NotInsertableTestEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(NotInsertableTestEntity.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( NotInsertableTestEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( NotInsertableTestEntity.class, id1, 2 ).equals( ver2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/NotInsertableTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/NotInsertableTestEntity.java index 24adfcc32d..b1e83f070f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/NotInsertableTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/NotInsertableTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.notinsertable; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -35,71 +36,81 @@ import org.hibernate.envers.Audited; @Entity @Audited public class NotInsertableTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Column(name = "data") - private String data; + @Column(name = "data") + private String data; - @Column(name = "data", insertable = false, updatable = false) - private String dataCopy; + @Column(name = "data", insertable = false, updatable = false) + private String dataCopy; - public NotInsertableTestEntity() { - } + public NotInsertableTestEntity() { + } - public NotInsertableTestEntity(Integer id, String data, String dataCopy) { - this.id = id; - this.data = data; - this.dataCopy = dataCopy; - } + public NotInsertableTestEntity(Integer id, String data, String dataCopy) { + this.id = id; + this.data = data; + this.dataCopy = dataCopy; + } - public NotInsertableTestEntity(String data) { - this.data = data; - } + public NotInsertableTestEntity(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public String getDataCopy() { - return dataCopy; - } + public String getDataCopy() { + return dataCopy; + } - public void setDataCopy(String dataCopy) { - this.dataCopy = dataCopy; - } + public void setDataCopy(String dataCopy) { + this.dataCopy = dataCopy; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof NotInsertableTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof NotInsertableTestEntity) ) { + return false; + } - NotInsertableTestEntity that = (NotInsertableTestEntity) o; + NotInsertableTestEntity that = (NotInsertableTestEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (dataCopy != null ? !dataCopy.equals(that.dataCopy) : that.dataCopy != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( dataCopy != null ? !dataCopy.equals( that.dataCopy ) : that.dataCopy != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - result = 31 * result + (dataCopy != null ? dataCopy.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + result = 31 * result + (dataCopy != null ? dataCopy.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/manytoone/ManyToOneNotInsertable.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/manytoone/ManyToOneNotInsertable.java index f22e3977c9..d8842cfae1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/manytoone/ManyToOneNotInsertable.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/manytoone/ManyToOneNotInsertable.java @@ -1,80 +1,85 @@ package org.hibernate.envers.test.integration.notinsertable.manytoone; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + public class ManyToOneNotInsertable extends BaseEnversJPAFunctionalTestCase { - private Integer mto_id1; - private Integer type_id1; - private Integer type_id2; + private Integer mto_id1; + private Integer type_id1; + private Integer type_id2; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ManyToOneNotInsertableEntity.class, NotInsertableEntityType.class }; - } + return new Class[] {ManyToOneNotInsertableEntity.class, NotInsertableEntityType.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - mto_id1 = 1; - type_id1 = 2; - type_id2 = 3; + mto_id1 = 1; + type_id1 = 2; + type_id2 = 3; // Rev 1 // Preparing the types em.getTransaction().begin(); - NotInsertableEntityType type1 = new NotInsertableEntityType(type_id1, "type1"); - NotInsertableEntityType type2 = new NotInsertableEntityType(type_id2, "type2"); + NotInsertableEntityType type1 = new NotInsertableEntityType( type_id1, "type1" ); + NotInsertableEntityType type2 = new NotInsertableEntityType( type_id2, "type2" ); - em.persist(type1); - em.persist(type2); + em.persist( type1 ); + em.persist( type2 ); em.getTransaction().commit(); - // Rev 2 - em.getTransaction().begin(); + // Rev 2 + em.getTransaction().begin(); - ManyToOneNotInsertableEntity master = new ManyToOneNotInsertableEntity(mto_id1, type_id1, type1); - em.persist(master); + ManyToOneNotInsertableEntity master = new ManyToOneNotInsertableEntity( mto_id1, type_id1, type1 ); + em.persist( master ); - em.getTransaction().commit(); + em.getTransaction().commit(); // Rev 2 - em.getTransaction().begin(); + em.getTransaction().begin(); - master = em.find(ManyToOneNotInsertableEntity.class, mto_id1); - master.setNumber(type_id2); + master = em.find( ManyToOneNotInsertableEntity.class, mto_id1 ); + master.setNumber( type_id2 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionCounts() { - assert Arrays.asList(1).equals(getAuditReader().getRevisions(NotInsertableEntityType.class, type_id1)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(NotInsertableEntityType.class, type_id2)); + @Test + public void testRevisionCounts() { + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( NotInsertableEntityType.class, type_id1 ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( NotInsertableEntityType.class, type_id2 ) ); - assert Arrays.asList(2, 3).equals(getAuditReader().getRevisions(ManyToOneNotInsertableEntity.class, mto_id1)); - } + assert Arrays.asList( 2, 3 ).equals( + getAuditReader().getRevisions( + ManyToOneNotInsertableEntity.class, + mto_id1 + ) + ); + } - @Test - public void testNotInsertableEntity() { - ManyToOneNotInsertableEntity ver1 = getAuditReader().find(ManyToOneNotInsertableEntity.class, mto_id1, 1); - ManyToOneNotInsertableEntity ver2 = getAuditReader().find(ManyToOneNotInsertableEntity.class, mto_id1, 2); - ManyToOneNotInsertableEntity ver3 = getAuditReader().find(ManyToOneNotInsertableEntity.class, mto_id1, 3); + @Test + public void testNotInsertableEntity() { + ManyToOneNotInsertableEntity ver1 = getAuditReader().find( ManyToOneNotInsertableEntity.class, mto_id1, 1 ); + ManyToOneNotInsertableEntity ver2 = getAuditReader().find( ManyToOneNotInsertableEntity.class, mto_id1, 2 ); + ManyToOneNotInsertableEntity ver3 = getAuditReader().find( ManyToOneNotInsertableEntity.class, mto_id1, 3 ); - NotInsertableEntityType type1 = getEntityManager().find(NotInsertableEntityType.class, type_id1); - NotInsertableEntityType type2 = getEntityManager().find(NotInsertableEntityType.class, type_id2); + NotInsertableEntityType type1 = getEntityManager().find( NotInsertableEntityType.class, type_id1 ); + NotInsertableEntityType type2 = getEntityManager().find( NotInsertableEntityType.class, type_id2 ); assert ver1 == null; - assert ver2.getType().equals(type1); - assert ver3.getType().equals(type2); - } + assert ver2.getType().equals( type1 ); + assert ver3.getType().equals( type2 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/manytoone/ManyToOneNotInsertableEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/manytoone/ManyToOneNotInsertableEntity.java index b46086c412..9ff826149c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/manytoone/ManyToOneNotInsertableEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/manytoone/ManyToOneNotInsertableEntity.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.integration.notinsertable.manytoone; + import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; @@ -13,18 +14,19 @@ import org.hibernate.envers.Audited; @Table(name = "ManyToOneNotIns") @Audited public class ManyToOneNotInsertableEntity { - @Id - private Integer id; + @Id + private Integer id; - @Basic + @Basic @Column(name = "numVal") - private Integer number; + private Integer number; @ManyToOne @JoinColumn(name = "numVal", insertable = false, updatable = false) private NotInsertableEntityType type; - public ManyToOneNotInsertableEntity() { } + public ManyToOneNotInsertableEntity() { + } public ManyToOneNotInsertableEntity(Integer id, Integer number, NotInsertableEntityType type) { this.id = id; diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/manytoone/NotInsertableEntityType.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/manytoone/NotInsertableEntityType.java index 31be0e82b2..faae5ab6fb 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/manytoone/NotInsertableEntityType.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notinsertable/manytoone/NotInsertableEntityType.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.integration.notinsertable.manytoone; + import javax.persistence.Basic; import javax.persistence.Entity; import javax.persistence.Id; @@ -8,18 +9,19 @@ import org.hibernate.envers.Audited; @Entity @Audited public class NotInsertableEntityType { - public NotInsertableEntityType(Integer typeId, String type) { - this.typeId = typeId; - this.type = type; - } + public NotInsertableEntityType(Integer typeId, String type) { + this.typeId = typeId; + this.type = type; + } - public NotInsertableEntityType() { } + public NotInsertableEntityType() { + } - @Id - private Integer typeId; + @Id + private Integer typeId; - @Basic - private String type; + @Basic + private String type; public Integer getTypeId() { return typeId; @@ -39,13 +41,21 @@ public class NotInsertableEntityType { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if ( this == o ) { + return true; + } + if ( o == null || getClass() != o.getClass() ) { + return false; + } NotInsertableEntityType that = (NotInsertableEntityType) o; - if (type != null ? !type.equals(that.type) : that.type != null) return false; - if (typeId != null ? !typeId.equals(that.typeId) : that.typeId != null) return false; + if ( type != null ? !type.equals( that.type ) : that.type != null ) { + return false; + } + if ( typeId != null ? !typeId.equals( that.typeId ) : that.typeId != null ) { + return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notupdatable/PropertyNotUpdatableEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notupdatable/PropertyNotUpdatableEntity.java index a2518649cb..b62af259f6 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notupdatable/PropertyNotUpdatableEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notupdatable/PropertyNotUpdatableEntity.java @@ -1,10 +1,10 @@ package org.hibernate.envers.test.integration.notupdatable; -import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -14,92 +14,104 @@ import org.hibernate.envers.Audited; @Entity @Audited public class PropertyNotUpdatableEntity implements Serializable { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String data; + private String data; - @Column(updatable = false) - private String constantData1; + @Column(updatable = false) + private String constantData1; - @Column(updatable = false) - private String constantData2; + @Column(updatable = false) + private String constantData2; - public PropertyNotUpdatableEntity() { - } + public PropertyNotUpdatableEntity() { + } - public PropertyNotUpdatableEntity(String data, String constantData1, String constantData2) { - this.constantData1 = constantData1; - this.constantData2 = constantData2; - this.data = data; - } + public PropertyNotUpdatableEntity(String data, String constantData1, String constantData2) { + this.constantData1 = constantData1; + this.constantData2 = constantData2; + this.data = data; + } - public PropertyNotUpdatableEntity(String data, String constantData1, String constantData2, Long id) { - this.data = data; - this.id = id; - this.constantData1 = constantData1; - this.constantData2 = constantData2; - } + public PropertyNotUpdatableEntity(String data, String constantData1, String constantData2, Long id) { + this.data = data; + this.id = id; + this.constantData1 = constantData1; + this.constantData2 = constantData2; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof PropertyNotUpdatableEntity)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof PropertyNotUpdatableEntity) ) { + return false; + } - PropertyNotUpdatableEntity that = (PropertyNotUpdatableEntity) o; + PropertyNotUpdatableEntity that = (PropertyNotUpdatableEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (constantData1 != null ? !constantData1.equals(that.constantData1) : that.constantData1 != null) return false; - if (constantData2 != null ? !constantData2.equals(that.constantData2) : that.constantData2 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( constantData1 != null ? !constantData1.equals( that.constantData1 ) : that.constantData1 != null ) { + return false; + } + if ( constantData2 != null ? !constantData2.equals( that.constantData2 ) : that.constantData2 != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (data != null ? data.hashCode() : 0); - result = 31 * result + (constantData1 != null ? constantData1.hashCode() : 0); - result = 31 * result + (constantData2 != null ? constantData2.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (data != null ? data.hashCode() : 0); + result = 31 * result + (constantData1 != null ? constantData1.hashCode() : 0); + result = 31 * result + (constantData2 != null ? constantData2.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "PropertyNotUpdatableEntity(id = " + id + ", data = " + data + ", constantData1 = " + constantData1 + ", constantData2 = " + constantData2 + ")"; - } + @Override + public String toString() { + return "PropertyNotUpdatableEntity(id = " + id + ", data = " + data + ", constantData1 = " + constantData1 + ", constantData2 = " + constantData2 + ")"; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getConstantData1() { - return constantData1; - } + public String getConstantData1() { + return constantData1; + } - public void setConstantData1(String constantData1) { - this.constantData1 = constantData1; - } + public void setConstantData1(String constantData1) { + this.constantData1 = constantData1; + } - public String getConstantData2() { - return constantData2; - } + public String getConstantData2() { + return constantData2; + } - public void setConstantData2(String constantData2) { - this.constantData2 = constantData2; - } + public void setConstantData2(String constantData2) { + this.constantData2 = constantData2; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notupdatable/PropertyNotUpdatableTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notupdatable/PropertyNotUpdatableTest.java index e9abc7425c..6d450c2bd8 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notupdatable/PropertyNotUpdatableTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/notupdatable/PropertyNotUpdatableTest.java @@ -1,16 +1,17 @@ package org.hibernate.envers.test.integration.notupdatable; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.List; import java.util.Map; -import javax.persistence.EntityManager; - -import junit.framework.Assert; -import org.junit.Test; import org.hibernate.envers.configuration.EnversSettings; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; + +import org.junit.Test; +import junit.framework.Assert; + import org.hibernate.testing.TestForIssue; /** @@ -18,79 +19,110 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-5411") public class PropertyNotUpdatableTest extends BaseEnversJPAFunctionalTestCase { - private Long id = null; + private Long id = null; - @Override - protected void addConfigOptions(Map options) { - options.put(EnversSettings.STORE_DATA_AT_DELETE, "true"); - } + @Override + protected void addConfigOptions(Map options) { + options.put( EnversSettings.STORE_DATA_AT_DELETE, "true" ); + } - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] { PropertyNotUpdatableEntity.class }; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {PropertyNotUpdatableEntity.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - PropertyNotUpdatableEntity entity = new PropertyNotUpdatableEntity("data", "constant data 1", "constant data 2"); - em.persist(entity); - em.getTransaction().commit(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + PropertyNotUpdatableEntity entity = new PropertyNotUpdatableEntity( + "data", + "constant data 1", + "constant data 2" + ); + em.persist( entity ); + em.getTransaction().commit(); - id = entity.getId(); + id = entity.getId(); - // Revision 2 - em.getTransaction().begin(); - entity = em.find(PropertyNotUpdatableEntity.class, entity.getId()); - entity.setData("modified data"); - entity.setConstantData1(null); - em.merge(entity); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + entity = em.find( PropertyNotUpdatableEntity.class, entity.getId() ); + entity.setData( "modified data" ); + entity.setConstantData1( null ); + em.merge( entity ); + em.getTransaction().commit(); - em.close(); - em = getEntityManager(); // Re-opening entity manager to re-initialize non-updatable fields - // with database values. Otherwise PostUpdateEvent#getOldState() returns previous - // memory state. This can be achieved using EntityManager#refresh(Object) method as well. + em.close(); + em = getEntityManager(); // Re-opening entity manager to re-initialize non-updatable fields + // with database values. Otherwise PostUpdateEvent#getOldState() returns previous + // memory state. This can be achieved using EntityManager#refresh(Object) method as well. - // Revision 3 - em.getTransaction().begin(); - entity = em.find(PropertyNotUpdatableEntity.class, entity.getId()); - entity.setData("another modified data"); - entity.setConstantData2("invalid data"); - em.merge(entity); - em.getTransaction().commit(); + // Revision 3 + em.getTransaction().begin(); + entity = em.find( PropertyNotUpdatableEntity.class, entity.getId() ); + entity.setData( "another modified data" ); + entity.setConstantData2( "invalid data" ); + em.merge( entity ); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); - em.refresh(entity); - em.remove(entity); - em.getTransaction().commit(); - } + // Revision 4 + em.getTransaction().begin(); + em.refresh( entity ); + em.remove( entity ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - Assert.assertEquals(Arrays.asList(1, 2, 3, 4), getAuditReader().getRevisions(PropertyNotUpdatableEntity.class, id)); - } + @Test + public void testRevisionsCounts() { + Assert.assertEquals( + Arrays.asList( 1, 2, 3, 4 ), + getAuditReader().getRevisions( PropertyNotUpdatableEntity.class, id ) + ); + } - @Test - public void testHistoryOfId() { - PropertyNotUpdatableEntity ver1 = new PropertyNotUpdatableEntity("data", "constant data 1", "constant data 2", id); - Assert.assertEquals(ver1, getAuditReader().find(PropertyNotUpdatableEntity.class, id, 1)); + @Test + public void testHistoryOfId() { + PropertyNotUpdatableEntity ver1 = new PropertyNotUpdatableEntity( + "data", + "constant data 1", + "constant data 2", + id + ); + Assert.assertEquals( ver1, getAuditReader().find( PropertyNotUpdatableEntity.class, id, 1 ) ); - PropertyNotUpdatableEntity ver2 = new PropertyNotUpdatableEntity("modified data", "constant data 1", "constant data 2", id); - Assert.assertEquals(ver2, getAuditReader().find(PropertyNotUpdatableEntity.class, id, 2)); + PropertyNotUpdatableEntity ver2 = new PropertyNotUpdatableEntity( + "modified data", + "constant data 1", + "constant data 2", + id + ); + Assert.assertEquals( ver2, getAuditReader().find( PropertyNotUpdatableEntity.class, id, 2 ) ); - PropertyNotUpdatableEntity ver3 = new PropertyNotUpdatableEntity("another modified data", "constant data 1", "constant data 2", id); - Assert.assertEquals(ver3, getAuditReader().find(PropertyNotUpdatableEntity.class, id, 3)); - } + PropertyNotUpdatableEntity ver3 = new PropertyNotUpdatableEntity( + "another modified data", + "constant data 1", + "constant data 2", + id + ); + Assert.assertEquals( ver3, getAuditReader().find( PropertyNotUpdatableEntity.class, id, 3 ) ); + } - @Test - public void testDeleteState() { - PropertyNotUpdatableEntity delete = new PropertyNotUpdatableEntity("another modified data", "constant data 1", "constant data 2", id); - List results = getAuditReader().createQuery().forRevisionsOfEntity(PropertyNotUpdatableEntity.class, true, true).getResultList(); - Assert.assertEquals(delete, results.get(3)); - } + @Test + public void testDeleteState() { + PropertyNotUpdatableEntity delete = new PropertyNotUpdatableEntity( + "another modified data", + "constant data 1", + "constant data 2", + id + ); + List results = getAuditReader().createQuery().forRevisionsOfEntity( + PropertyNotUpdatableEntity.class, + true, + true + ).getResultList(); + Assert.assertEquals( delete, results.get( 3 ) ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicCollection.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicCollection.java index ccb0c7a57f..85d2b8efc2 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicCollection.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicCollection.java @@ -23,165 +23,167 @@ */ package org.hibernate.envers.test.integration.onetomany; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.onetomany.CollectionRefEdEntity; import org.hibernate.envers.test.entities.onetomany.CollectionRefIngEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BasicCollection extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { CollectionRefEdEntity.class, CollectionRefIngEntity.class }; - } + return new Class[] {CollectionRefEdEntity.class, CollectionRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - CollectionRefEdEntity ed1 = new CollectionRefEdEntity(1, "data_ed_1"); - CollectionRefEdEntity ed2 = new CollectionRefEdEntity(2, "data_ed_2"); + CollectionRefEdEntity ed1 = new CollectionRefEdEntity( 1, "data_ed_1" ); + CollectionRefEdEntity ed2 = new CollectionRefEdEntity( 2, "data_ed_2" ); - CollectionRefIngEntity ing1 = new CollectionRefIngEntity(3, "data_ing_1", ed1); - CollectionRefIngEntity ing2 = new CollectionRefIngEntity(4, "data_ing_2", ed1); + CollectionRefIngEntity ing1 = new CollectionRefIngEntity( 3, "data_ing_1", ed1 ); + CollectionRefIngEntity ing2 = new CollectionRefIngEntity( 4, "data_ing_2", ed1 ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); + em.persist( ed1 ); + em.persist( ed2 ); - em.persist(ing1); - em.persist(ing2); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ing1 = em.find(CollectionRefIngEntity.class, ing1.getId()); - ed2 = em.find(CollectionRefEdEntity.class, ed2.getId()); + ing1 = em.find( CollectionRefIngEntity.class, ing1.getId() ); + ed2 = em.find( CollectionRefEdEntity.class, ed2.getId() ); - ing1.setReference(ed2); + ing1.setReference( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - ing2 = em.find(CollectionRefIngEntity.class, ing2.getId()); - ed2 = em.find(CollectionRefEdEntity.class, ed2.getId()); + ing2 = em.find( CollectionRefIngEntity.class, ing2.getId() ); + ed2 = em.find( CollectionRefEdEntity.class, ed2.getId() ); - ing2.setReference(ed2); + ing2.setReference( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); - } + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(CollectionRefEdEntity.class, ed1_id)); - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(CollectionRefEdEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( CollectionRefEdEntity.class, ed1_id ) ); + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( CollectionRefEdEntity.class, ed2_id ) ); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(CollectionRefIngEntity.class, ing1_id)); - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(CollectionRefIngEntity.class, ing2_id)); - } + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( CollectionRefIngEntity.class, ing1_id ) ); + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( CollectionRefIngEntity.class, ing2_id ) ); + } - private Set makeSet(T... objects) { - Set ret = new HashSet(); - //noinspection ManualArrayToCollectionCopy - for (T obj : objects) { ret.add(obj); } - return ret; - } + private Set makeSet(T... objects) { + Set ret = new HashSet(); + //noinspection ManualArrayToCollectionCopy + for ( T obj : objects ) { + ret.add( obj ); + } + return ret; + } - @Test - public void testHistoryOfEdId1() { - CollectionRefIngEntity ing1 = getEntityManager().find(CollectionRefIngEntity.class, ing1_id); - CollectionRefIngEntity ing2 = getEntityManager().find(CollectionRefIngEntity.class, ing2_id); + @Test + public void testHistoryOfEdId1() { + CollectionRefIngEntity ing1 = getEntityManager().find( CollectionRefIngEntity.class, ing1_id ); + CollectionRefIngEntity ing2 = getEntityManager().find( CollectionRefIngEntity.class, ing2_id ); - CollectionRefEdEntity rev1 = getAuditReader().find(CollectionRefEdEntity.class, ed1_id, 1); - CollectionRefEdEntity rev2 = getAuditReader().find(CollectionRefEdEntity.class, ed1_id, 2); - CollectionRefEdEntity rev3 = getAuditReader().find(CollectionRefEdEntity.class, ed1_id, 3); + CollectionRefEdEntity rev1 = getAuditReader().find( CollectionRefEdEntity.class, ed1_id, 1 ); + CollectionRefEdEntity rev2 = getAuditReader().find( CollectionRefEdEntity.class, ed1_id, 2 ); + CollectionRefEdEntity rev3 = getAuditReader().find( CollectionRefEdEntity.class, ed1_id, 3 ); - assert rev1.getReffering().containsAll(makeSet(ing1, ing2)); - assert rev1.getReffering().size() == 2; + assert rev1.getReffering().containsAll( makeSet( ing1, ing2 ) ); + assert rev1.getReffering().size() == 2; - assert rev2.getReffering().containsAll(makeSet(ing2)); - assert rev2.getReffering().size() == 1; + assert rev2.getReffering().containsAll( makeSet( ing2 ) ); + assert rev2.getReffering().size() == 1; - assert rev3.getReffering().containsAll(Collections.EMPTY_SET); - assert rev3.getReffering().size() == 0; - } + assert rev3.getReffering().containsAll( Collections.EMPTY_SET ); + assert rev3.getReffering().size() == 0; + } - @Test - public void testHistoryOfEdId2() { - CollectionRefIngEntity ing1 = getEntityManager().find(CollectionRefIngEntity.class, ing1_id); - CollectionRefIngEntity ing2 = getEntityManager().find(CollectionRefIngEntity.class, ing2_id); + @Test + public void testHistoryOfEdId2() { + CollectionRefIngEntity ing1 = getEntityManager().find( CollectionRefIngEntity.class, ing1_id ); + CollectionRefIngEntity ing2 = getEntityManager().find( CollectionRefIngEntity.class, ing2_id ); - CollectionRefEdEntity rev1 = getAuditReader().find(CollectionRefEdEntity.class, ed2_id, 1); - CollectionRefEdEntity rev2 = getAuditReader().find(CollectionRefEdEntity.class, ed2_id, 2); - CollectionRefEdEntity rev3 = getAuditReader().find(CollectionRefEdEntity.class, ed2_id, 3); + CollectionRefEdEntity rev1 = getAuditReader().find( CollectionRefEdEntity.class, ed2_id, 1 ); + CollectionRefEdEntity rev2 = getAuditReader().find( CollectionRefEdEntity.class, ed2_id, 2 ); + CollectionRefEdEntity rev3 = getAuditReader().find( CollectionRefEdEntity.class, ed2_id, 3 ); - assert rev1.getReffering().containsAll(Collections.EMPTY_SET); - assert rev1.getReffering().size() == 0; + assert rev1.getReffering().containsAll( Collections.EMPTY_SET ); + assert rev1.getReffering().size() == 0; - assert rev2.getReffering().containsAll(makeSet(ing1)); - assert rev2.getReffering().size() == 1; + assert rev2.getReffering().containsAll( makeSet( ing1 ) ); + assert rev2.getReffering().size() == 1; - assert rev3.getReffering().containsAll(makeSet(ing1, ing2)); - assert rev3.getReffering().size() == 2; + assert rev3.getReffering().containsAll( makeSet( ing1, ing2 ) ); + assert rev3.getReffering().size() == 2; - } + } - @Test - public void testHistoryOfEdIng1() { - CollectionRefEdEntity ed1 = getEntityManager().find(CollectionRefEdEntity.class, ed1_id); - CollectionRefEdEntity ed2 = getEntityManager().find(CollectionRefEdEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng1() { + CollectionRefEdEntity ed1 = getEntityManager().find( CollectionRefEdEntity.class, ed1_id ); + CollectionRefEdEntity ed2 = getEntityManager().find( CollectionRefEdEntity.class, ed2_id ); - CollectionRefIngEntity rev1 = getAuditReader().find(CollectionRefIngEntity.class, ing1_id, 1); - CollectionRefIngEntity rev2 = getAuditReader().find(CollectionRefIngEntity.class, ing1_id, 2); - CollectionRefIngEntity rev3 = getAuditReader().find(CollectionRefIngEntity.class, ing1_id, 3); + CollectionRefIngEntity rev1 = getAuditReader().find( CollectionRefIngEntity.class, ing1_id, 1 ); + CollectionRefIngEntity rev2 = getAuditReader().find( CollectionRefIngEntity.class, ing1_id, 2 ); + CollectionRefIngEntity rev3 = getAuditReader().find( CollectionRefIngEntity.class, ing1_id, 3 ); - assert rev1.getReference().equals(ed1); - assert rev2.getReference().equals(ed2); - assert rev3.getReference().equals(ed2); - } + assert rev1.getReference().equals( ed1 ); + assert rev2.getReference().equals( ed2 ); + assert rev3.getReference().equals( ed2 ); + } - @Test - public void testHistoryOfEdIng2() { - CollectionRefEdEntity ed1 = getEntityManager().find(CollectionRefEdEntity.class, ed1_id); - CollectionRefEdEntity ed2 = getEntityManager().find(CollectionRefEdEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng2() { + CollectionRefEdEntity ed1 = getEntityManager().find( CollectionRefEdEntity.class, ed1_id ); + CollectionRefEdEntity ed2 = getEntityManager().find( CollectionRefEdEntity.class, ed2_id ); - CollectionRefIngEntity rev1 = getAuditReader().find(CollectionRefIngEntity.class, ing2_id, 1); - CollectionRefIngEntity rev2 = getAuditReader().find(CollectionRefIngEntity.class, ing2_id, 2); - CollectionRefIngEntity rev3 = getAuditReader().find(CollectionRefIngEntity.class, ing2_id, 3); + CollectionRefIngEntity rev1 = getAuditReader().find( CollectionRefIngEntity.class, ing2_id, 1 ); + CollectionRefIngEntity rev2 = getAuditReader().find( CollectionRefIngEntity.class, ing2_id, 2 ); + CollectionRefIngEntity rev3 = getAuditReader().find( CollectionRefIngEntity.class, ing2_id, 3 ); - assert rev1.getReference().equals(ed1); - assert rev2.getReference().equals(ed1); - assert rev3.getReference().equals(ed2); - } + assert rev1.getReference().equals( ed1 ); + assert rev2.getReference().equals( ed1 ); + assert rev3.getReference().equals( ed2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicList.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicList.java index e2ae66a345..267e5e191e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicList.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicList.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.onetomany; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -34,133 +32,136 @@ import org.hibernate.envers.test.entities.onetomany.ListRefEdEntity; import org.hibernate.envers.test.entities.onetomany.ListRefIngEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ -public class BasicList extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; +public class BasicList extends BaseEnversJPAFunctionalTestCase { + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ListRefEdEntity.class, ListRefIngEntity.class }; - } + return new Class[] {ListRefEdEntity.class, ListRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - ListRefEdEntity ed1 = new ListRefEdEntity(1, "data_ed_1"); - ListRefEdEntity ed2 = new ListRefEdEntity(2, "data_ed_2"); + ListRefEdEntity ed1 = new ListRefEdEntity( 1, "data_ed_1" ); + ListRefEdEntity ed2 = new ListRefEdEntity( 2, "data_ed_2" ); - ListRefIngEntity ing1 = new ListRefIngEntity(3, "data_ing_1", ed1); - ListRefIngEntity ing2 = new ListRefIngEntity(4, "data_ing_2", ed1); + ListRefIngEntity ing1 = new ListRefIngEntity( 3, "data_ing_1", ed1 ); + ListRefIngEntity ing2 = new ListRefIngEntity( 4, "data_ing_2", ed1 ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); + em.persist( ed1 ); + em.persist( ed2 ); - em.persist(ing1); - em.persist(ing2); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ing1 = em.find(ListRefIngEntity.class, ing1.getId()); - ed2 = em.find(ListRefEdEntity.class, ed2.getId()); + ing1 = em.find( ListRefIngEntity.class, ing1.getId() ); + ed2 = em.find( ListRefEdEntity.class, ed2.getId() ); - ing1.setReference(ed2); + ing1.setReference( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - ing2 = em.find(ListRefIngEntity.class, ing2.getId()); - ed2 = em.find(ListRefEdEntity.class, ed2.getId()); + ing2 = em.find( ListRefIngEntity.class, ing2.getId() ); + ed2 = em.find( ListRefEdEntity.class, ed2.getId() ); - ing2.setReference(ed2); + ing2.setReference( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); - } + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(ListRefEdEntity.class, ed1_id)); - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(ListRefEdEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( ListRefEdEntity.class, ed1_id ) ); + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( ListRefEdEntity.class, ed2_id ) ); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(ListRefIngEntity.class, ing1_id)); - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(ListRefIngEntity.class, ing2_id)); - } - @Test - public void testHistoryOfEdId1() { - ListRefIngEntity ing1 = getEntityManager().find(ListRefIngEntity.class, ing1_id); - ListRefIngEntity ing2 = getEntityManager().find(ListRefIngEntity.class, ing2_id); + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( ListRefIngEntity.class, ing1_id ) ); + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( ListRefIngEntity.class, ing2_id ) ); + } - ListRefEdEntity rev1 = getAuditReader().find(ListRefEdEntity.class, ed1_id, 1); - ListRefEdEntity rev2 = getAuditReader().find(ListRefEdEntity.class, ed1_id, 2); - ListRefEdEntity rev3 = getAuditReader().find(ListRefEdEntity.class, ed1_id, 3); + @Test + public void testHistoryOfEdId1() { + ListRefIngEntity ing1 = getEntityManager().find( ListRefIngEntity.class, ing1_id ); + ListRefIngEntity ing2 = getEntityManager().find( ListRefIngEntity.class, ing2_id ); - assert TestTools.checkList(rev1.getReffering(), ing1, ing2); - assert TestTools.checkList(rev2.getReffering(), ing2); - assert TestTools.checkList(rev3.getReffering()); - } + ListRefEdEntity rev1 = getAuditReader().find( ListRefEdEntity.class, ed1_id, 1 ); + ListRefEdEntity rev2 = getAuditReader().find( ListRefEdEntity.class, ed1_id, 2 ); + ListRefEdEntity rev3 = getAuditReader().find( ListRefEdEntity.class, ed1_id, 3 ); - @Test - public void testHistoryOfEdId2() { - ListRefIngEntity ing1 = getEntityManager().find(ListRefIngEntity.class, ing1_id); - ListRefIngEntity ing2 = getEntityManager().find(ListRefIngEntity.class, ing2_id); + assert TestTools.checkList( rev1.getReffering(), ing1, ing2 ); + assert TestTools.checkList( rev2.getReffering(), ing2 ); + assert TestTools.checkList( rev3.getReffering() ); + } - ListRefEdEntity rev1 = getAuditReader().find(ListRefEdEntity.class, ed2_id, 1); - ListRefEdEntity rev2 = getAuditReader().find(ListRefEdEntity.class, ed2_id, 2); - ListRefEdEntity rev3 = getAuditReader().find(ListRefEdEntity.class, ed2_id, 3); + @Test + public void testHistoryOfEdId2() { + ListRefIngEntity ing1 = getEntityManager().find( ListRefIngEntity.class, ing1_id ); + ListRefIngEntity ing2 = getEntityManager().find( ListRefIngEntity.class, ing2_id ); - assert TestTools.checkList(rev1.getReffering()); - assert TestTools.checkList(rev2.getReffering(), ing1); - assert TestTools.checkList(rev3.getReffering(), ing1, ing2); - } + ListRefEdEntity rev1 = getAuditReader().find( ListRefEdEntity.class, ed2_id, 1 ); + ListRefEdEntity rev2 = getAuditReader().find( ListRefEdEntity.class, ed2_id, 2 ); + ListRefEdEntity rev3 = getAuditReader().find( ListRefEdEntity.class, ed2_id, 3 ); - @Test - public void testHistoryOfEdIng1() { - ListRefEdEntity ed1 = getEntityManager().find(ListRefEdEntity.class, ed1_id); - ListRefEdEntity ed2 = getEntityManager().find(ListRefEdEntity.class, ed2_id); + assert TestTools.checkList( rev1.getReffering() ); + assert TestTools.checkList( rev2.getReffering(), ing1 ); + assert TestTools.checkList( rev3.getReffering(), ing1, ing2 ); + } - ListRefIngEntity rev1 = getAuditReader().find(ListRefIngEntity.class, ing1_id, 1); - ListRefIngEntity rev2 = getAuditReader().find(ListRefIngEntity.class, ing1_id, 2); - ListRefIngEntity rev3 = getAuditReader().find(ListRefIngEntity.class, ing1_id, 3); + @Test + public void testHistoryOfEdIng1() { + ListRefEdEntity ed1 = getEntityManager().find( ListRefEdEntity.class, ed1_id ); + ListRefEdEntity ed2 = getEntityManager().find( ListRefEdEntity.class, ed2_id ); - assert rev1.getReference().equals(ed1); - assert rev2.getReference().equals(ed2); - assert rev3.getReference().equals(ed2); - } + ListRefIngEntity rev1 = getAuditReader().find( ListRefIngEntity.class, ing1_id, 1 ); + ListRefIngEntity rev2 = getAuditReader().find( ListRefIngEntity.class, ing1_id, 2 ); + ListRefIngEntity rev3 = getAuditReader().find( ListRefIngEntity.class, ing1_id, 3 ); - @Test - public void testHistoryOfEdIng2() { - ListRefEdEntity ed1 = getEntityManager().find(ListRefEdEntity.class, ed1_id); - ListRefEdEntity ed2 = getEntityManager().find(ListRefEdEntity.class, ed2_id); + assert rev1.getReference().equals( ed1 ); + assert rev2.getReference().equals( ed2 ); + assert rev3.getReference().equals( ed2 ); + } - ListRefIngEntity rev1 = getAuditReader().find(ListRefIngEntity.class, ing2_id, 1); - ListRefIngEntity rev2 = getAuditReader().find(ListRefIngEntity.class, ing2_id, 2); - ListRefIngEntity rev3 = getAuditReader().find(ListRefIngEntity.class, ing2_id, 3); + @Test + public void testHistoryOfEdIng2() { + ListRefEdEntity ed1 = getEntityManager().find( ListRefEdEntity.class, ed1_id ); + ListRefEdEntity ed2 = getEntityManager().find( ListRefEdEntity.class, ed2_id ); - assert rev1.getReference().equals(ed1); - assert rev2.getReference().equals(ed1); - assert rev3.getReference().equals(ed2); - } + ListRefIngEntity rev1 = getAuditReader().find( ListRefIngEntity.class, ing2_id, 1 ); + ListRefIngEntity rev2 = getAuditReader().find( ListRefIngEntity.class, ing2_id, 2 ); + ListRefIngEntity rev3 = getAuditReader().find( ListRefIngEntity.class, ing2_id, 3 ); + + assert rev1.getReference().equals( ed1 ); + assert rev2.getReference().equals( ed1 ); + assert rev3.getReference().equals( ed2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicSet.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicSet.java index fe0d1e52d4..2c7a7ebfba 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicSet.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicSet.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.onetomany; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Collections; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -35,153 +33,155 @@ import org.hibernate.envers.test.entities.onetomany.SetRefEdEntity; import org.hibernate.envers.test.entities.onetomany.SetRefIngEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BasicSet extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SetRefEdEntity.class, SetRefIngEntity.class }; - } + return new Class[] {SetRefEdEntity.class, SetRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - SetRefEdEntity ed1 = new SetRefEdEntity(1, "data_ed_1"); - SetRefEdEntity ed2 = new SetRefEdEntity(2, "data_ed_2"); + SetRefEdEntity ed1 = new SetRefEdEntity( 1, "data_ed_1" ); + SetRefEdEntity ed2 = new SetRefEdEntity( 2, "data_ed_2" ); - SetRefIngEntity ing1 = new SetRefIngEntity(3, "data_ing_1"); - SetRefIngEntity ing2 = new SetRefIngEntity(4, "data_ing_2"); + SetRefIngEntity ing1 = new SetRefIngEntity( 3, "data_ing_1" ); + SetRefIngEntity ing2 = new SetRefIngEntity( 4, "data_ing_2" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); + em.persist( ed1 ); + em.persist( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 + // Revision 2 - em.getTransaction().begin(); + em.getTransaction().begin(); - ed1 = em.find(SetRefEdEntity.class, ed1.getId()); + ed1 = em.find( SetRefEdEntity.class, ed1.getId() ); - ing1.setReference(ed1); - ing2.setReference(ed1); + ing1.setReference( ed1 ); + ing2.setReference( ed1 ); - em.persist(ing1); - em.persist(ing2); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - ing1 = em.find(SetRefIngEntity.class, ing1.getId()); - ed2 = em.find(SetRefEdEntity.class, ed2.getId()); + ing1 = em.find( SetRefIngEntity.class, ing1.getId() ); + ed2 = em.find( SetRefEdEntity.class, ed2.getId() ); - ing1.setReference(ed2); + ing1.setReference( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); + // Revision 4 + em.getTransaction().begin(); - ing2 = em.find(SetRefIngEntity.class, ing2.getId()); - ed2 = em.find(SetRefEdEntity.class, ed2.getId()); + ing2 = em.find( SetRefIngEntity.class, ing2.getId() ); + ed2 = em.find( SetRefEdEntity.class, ed2.getId() ); - ing2.setReference(ed2); + ing2.setReference( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); - } + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3, 4).equals(getAuditReader().getRevisions(SetRefEdEntity.class, ed1_id)); - assert Arrays.asList(1, 3, 4).equals(getAuditReader().getRevisions(SetRefEdEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3, 4 ).equals( getAuditReader().getRevisions( SetRefEdEntity.class, ed1_id ) ); + assert Arrays.asList( 1, 3, 4 ).equals( getAuditReader().getRevisions( SetRefEdEntity.class, ed2_id ) ); - assert Arrays.asList(2, 3).equals(getAuditReader().getRevisions(SetRefIngEntity.class, ing1_id)); - assert Arrays.asList(2, 4).equals(getAuditReader().getRevisions(SetRefIngEntity.class, ing2_id)); - } + assert Arrays.asList( 2, 3 ).equals( getAuditReader().getRevisions( SetRefIngEntity.class, ing1_id ) ); + assert Arrays.asList( 2, 4 ).equals( getAuditReader().getRevisions( SetRefIngEntity.class, ing2_id ) ); + } - @Test - public void testHistoryOfEdId1() { - SetRefIngEntity ing1 = getEntityManager().find(SetRefIngEntity.class, ing1_id); - SetRefIngEntity ing2 = getEntityManager().find(SetRefIngEntity.class, ing2_id); + @Test + public void testHistoryOfEdId1() { + SetRefIngEntity ing1 = getEntityManager().find( SetRefIngEntity.class, ing1_id ); + SetRefIngEntity ing2 = getEntityManager().find( SetRefIngEntity.class, ing2_id ); - SetRefEdEntity rev1 = getAuditReader().find(SetRefEdEntity.class, ed1_id, 1); - SetRefEdEntity rev2 = getAuditReader().find(SetRefEdEntity.class, ed1_id, 2); - SetRefEdEntity rev3 = getAuditReader().find(SetRefEdEntity.class, ed1_id, 3); - SetRefEdEntity rev4 = getAuditReader().find(SetRefEdEntity.class, ed1_id, 4); + SetRefEdEntity rev1 = getAuditReader().find( SetRefEdEntity.class, ed1_id, 1 ); + SetRefEdEntity rev2 = getAuditReader().find( SetRefEdEntity.class, ed1_id, 2 ); + SetRefEdEntity rev3 = getAuditReader().find( SetRefEdEntity.class, ed1_id, 3 ); + SetRefEdEntity rev4 = getAuditReader().find( SetRefEdEntity.class, ed1_id, 4 ); - assert rev1.getReffering().equals(Collections.EMPTY_SET); - assert rev2.getReffering().equals(TestTools.makeSet(ing1, ing2)); - assert rev3.getReffering().equals(TestTools.makeSet(ing2)); - assert rev4.getReffering().equals(Collections.EMPTY_SET); - } + assert rev1.getReffering().equals( Collections.EMPTY_SET ); + assert rev2.getReffering().equals( TestTools.makeSet( ing1, ing2 ) ); + assert rev3.getReffering().equals( TestTools.makeSet( ing2 ) ); + assert rev4.getReffering().equals( Collections.EMPTY_SET ); + } - @Test - public void testHistoryOfEdId2() { - SetRefIngEntity ing1 = getEntityManager().find(SetRefIngEntity.class, ing1_id); - SetRefIngEntity ing2 = getEntityManager().find(SetRefIngEntity.class, ing2_id); + @Test + public void testHistoryOfEdId2() { + SetRefIngEntity ing1 = getEntityManager().find( SetRefIngEntity.class, ing1_id ); + SetRefIngEntity ing2 = getEntityManager().find( SetRefIngEntity.class, ing2_id ); - SetRefEdEntity rev1 = getAuditReader().find(SetRefEdEntity.class, ed2_id, 1); - SetRefEdEntity rev2 = getAuditReader().find(SetRefEdEntity.class, ed2_id, 2); - SetRefEdEntity rev3 = getAuditReader().find(SetRefEdEntity.class, ed2_id, 3); - SetRefEdEntity rev4 = getAuditReader().find(SetRefEdEntity.class, ed2_id, 4); + SetRefEdEntity rev1 = getAuditReader().find( SetRefEdEntity.class, ed2_id, 1 ); + SetRefEdEntity rev2 = getAuditReader().find( SetRefEdEntity.class, ed2_id, 2 ); + SetRefEdEntity rev3 = getAuditReader().find( SetRefEdEntity.class, ed2_id, 3 ); + SetRefEdEntity rev4 = getAuditReader().find( SetRefEdEntity.class, ed2_id, 4 ); - assert rev1.getReffering().equals(Collections.EMPTY_SET); - assert rev2.getReffering().equals(Collections.EMPTY_SET); - assert rev3.getReffering().equals(TestTools.makeSet(ing1)); - assert rev4.getReffering().equals(TestTools.makeSet(ing1, ing2)); - } + assert rev1.getReffering().equals( Collections.EMPTY_SET ); + assert rev2.getReffering().equals( Collections.EMPTY_SET ); + assert rev3.getReffering().equals( TestTools.makeSet( ing1 ) ); + assert rev4.getReffering().equals( TestTools.makeSet( ing1, ing2 ) ); + } - @Test - public void testHistoryOfEdIng1() { - SetRefEdEntity ed1 = getEntityManager().find(SetRefEdEntity.class, ed1_id); - SetRefEdEntity ed2 = getEntityManager().find(SetRefEdEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng1() { + SetRefEdEntity ed1 = getEntityManager().find( SetRefEdEntity.class, ed1_id ); + SetRefEdEntity ed2 = getEntityManager().find( SetRefEdEntity.class, ed2_id ); - SetRefIngEntity rev1 = getAuditReader().find(SetRefIngEntity.class, ing1_id, 1); - SetRefIngEntity rev2 = getAuditReader().find(SetRefIngEntity.class, ing1_id, 2); - SetRefIngEntity rev3 = getAuditReader().find(SetRefIngEntity.class, ing1_id, 3); - SetRefIngEntity rev4 = getAuditReader().find(SetRefIngEntity.class, ing1_id, 4); + SetRefIngEntity rev1 = getAuditReader().find( SetRefIngEntity.class, ing1_id, 1 ); + SetRefIngEntity rev2 = getAuditReader().find( SetRefIngEntity.class, ing1_id, 2 ); + SetRefIngEntity rev3 = getAuditReader().find( SetRefIngEntity.class, ing1_id, 3 ); + SetRefIngEntity rev4 = getAuditReader().find( SetRefIngEntity.class, ing1_id, 4 ); - assert rev1 == null; - assert rev2.getReference().equals(ed1); - assert rev3.getReference().equals(ed2); - assert rev4.getReference().equals(ed2); - } + assert rev1 == null; + assert rev2.getReference().equals( ed1 ); + assert rev3.getReference().equals( ed2 ); + assert rev4.getReference().equals( ed2 ); + } - @Test - public void testHistoryOfEdIng2() { - SetRefEdEntity ed1 = getEntityManager().find(SetRefEdEntity.class, ed1_id); - SetRefEdEntity ed2 = getEntityManager().find(SetRefEdEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng2() { + SetRefEdEntity ed1 = getEntityManager().find( SetRefEdEntity.class, ed1_id ); + SetRefEdEntity ed2 = getEntityManager().find( SetRefEdEntity.class, ed2_id ); - SetRefIngEntity rev1 = getAuditReader().find(SetRefIngEntity.class, ing2_id, 1); - SetRefIngEntity rev2 = getAuditReader().find(SetRefIngEntity.class, ing2_id, 2); - SetRefIngEntity rev3 = getAuditReader().find(SetRefIngEntity.class, ing2_id, 3); - SetRefIngEntity rev4 = getAuditReader().find(SetRefIngEntity.class, ing2_id, 4); + SetRefIngEntity rev1 = getAuditReader().find( SetRefIngEntity.class, ing2_id, 1 ); + SetRefIngEntity rev2 = getAuditReader().find( SetRefIngEntity.class, ing2_id, 2 ); + SetRefIngEntity rev3 = getAuditReader().find( SetRefIngEntity.class, ing2_id, 3 ); + SetRefIngEntity rev4 = getAuditReader().find( SetRefIngEntity.class, ing2_id, 4 ); - assert rev1 == null; - assert rev2.getReference().equals(ed1); - assert rev3.getReference().equals(ed1); - assert rev4.getReference().equals(ed2); - } + assert rev1 == null; + assert rev2.getReference().equals( ed1 ); + assert rev3.getReference().equals( ed1 ); + assert rev4.getReference().equals( ed2 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicSetWithEmbId.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicSetWithEmbId.java index 375b69afed..af713707f4 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicSetWithEmbId.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicSetWithEmbId.java @@ -23,13 +23,11 @@ */ package org.hibernate.envers.test.integration.onetomany; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -37,139 +35,143 @@ import org.hibernate.envers.test.entities.ids.EmbId; import org.hibernate.envers.test.entities.onetomany.ids.SetRefEdEmbIdEntity; import org.hibernate.envers.test.entities.onetomany.ids.SetRefIngEmbIdEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BasicSetWithEmbId extends BaseEnversJPAFunctionalTestCase { - private EmbId ed1_id; - private EmbId ed2_id; + private EmbId ed1_id; + private EmbId ed2_id; - private EmbId ing1_id; - private EmbId ing2_id; + private EmbId ing1_id; + private EmbId ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SetRefEdEmbIdEntity.class, SetRefIngEmbIdEntity.class }; - } + return new Class[] {SetRefEdEmbIdEntity.class, SetRefIngEmbIdEntity.class}; + } - @Test - @Priority(10) - public void initData() { - ed1_id = new EmbId(0, 1); - ed2_id = new EmbId(2, 3); + @Test + @Priority(10) + public void initData() { + ed1_id = new EmbId( 0, 1 ); + ed2_id = new EmbId( 2, 3 ); - ing2_id = new EmbId(4, 5); - ing1_id = new EmbId(6, 7); + ing2_id = new EmbId( 4, 5 ); + ing1_id = new EmbId( 6, 7 ); - EntityManager em = getEntityManager(); + EntityManager em = getEntityManager(); - SetRefEdEmbIdEntity ed1 = new SetRefEdEmbIdEntity(ed1_id, "data_ed_1"); - SetRefEdEmbIdEntity ed2 = new SetRefEdEmbIdEntity(ed2_id, "data_ed_2"); + SetRefEdEmbIdEntity ed1 = new SetRefEdEmbIdEntity( ed1_id, "data_ed_1" ); + SetRefEdEmbIdEntity ed2 = new SetRefEdEmbIdEntity( ed2_id, "data_ed_2" ); - SetRefIngEmbIdEntity ing1 = new SetRefIngEmbIdEntity(ing1_id, "data_ing_1", ed1); - SetRefIngEmbIdEntity ing2 = new SetRefIngEmbIdEntity(ing2_id, "data_ing_2", ed1); + SetRefIngEmbIdEntity ing1 = new SetRefIngEmbIdEntity( ing1_id, "data_ing_1", ed1 ); + SetRefIngEmbIdEntity ing2 = new SetRefIngEmbIdEntity( ing2_id, "data_ing_2", ed1 ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); + em.persist( ed1 ); + em.persist( ed2 ); - em.persist(ing1); - em.persist(ing2); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ing1 = em.find(SetRefIngEmbIdEntity.class, ing1.getId()); - ed2 = em.find(SetRefEdEmbIdEntity.class, ed2.getId()); + ing1 = em.find( SetRefIngEmbIdEntity.class, ing1.getId() ); + ed2 = em.find( SetRefEdEmbIdEntity.class, ed2.getId() ); - ing1.setReference(ed2); + ing1.setReference( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - ing2 = em.find(SetRefIngEmbIdEntity.class, ing2.getId()); - ed2 = em.find(SetRefEdEmbIdEntity.class, ed2.getId()); + ing2 = em.find( SetRefIngEmbIdEntity.class, ing2.getId() ); + ed2 = em.find( SetRefEdEmbIdEntity.class, ed2.getId() ); - ing2.setReference(ed2); + ing2.setReference( ed2 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(SetRefEdEmbIdEntity.class, ed1_id)); - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(SetRefEdEmbIdEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( SetRefEdEmbIdEntity.class, ed1_id ) ); + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( SetRefEdEmbIdEntity.class, ed2_id ) ); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(SetRefIngEmbIdEntity.class, ing1_id)); - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(SetRefIngEmbIdEntity.class, ing2_id)); - } + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( SetRefIngEmbIdEntity.class, ing1_id ) ); + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( SetRefIngEmbIdEntity.class, ing2_id ) ); + } - private Set makeSet(T... objects) { - Set ret = new HashSet(); - //noinspection ManualArrayToCollectionCopy - for (T obj : objects) { ret.add(obj); } - return ret; - } + private Set makeSet(T... objects) { + Set ret = new HashSet(); + //noinspection ManualArrayToCollectionCopy + for ( T obj : objects ) { + ret.add( obj ); + } + return ret; + } - @Test - public void testHistoryOfEdId1() { - SetRefIngEmbIdEntity ing1 = getEntityManager().find(SetRefIngEmbIdEntity.class, ing1_id); - SetRefIngEmbIdEntity ing2 = getEntityManager().find(SetRefIngEmbIdEntity.class, ing2_id); + @Test + public void testHistoryOfEdId1() { + SetRefIngEmbIdEntity ing1 = getEntityManager().find( SetRefIngEmbIdEntity.class, ing1_id ); + SetRefIngEmbIdEntity ing2 = getEntityManager().find( SetRefIngEmbIdEntity.class, ing2_id ); - SetRefEdEmbIdEntity rev1 = getAuditReader().find(SetRefEdEmbIdEntity.class, ed1_id, 1); - SetRefEdEmbIdEntity rev2 = getAuditReader().find(SetRefEdEmbIdEntity.class, ed1_id, 2); - SetRefEdEmbIdEntity rev3 = getAuditReader().find(SetRefEdEmbIdEntity.class, ed1_id, 3); + SetRefEdEmbIdEntity rev1 = getAuditReader().find( SetRefEdEmbIdEntity.class, ed1_id, 1 ); + SetRefEdEmbIdEntity rev2 = getAuditReader().find( SetRefEdEmbIdEntity.class, ed1_id, 2 ); + SetRefEdEmbIdEntity rev3 = getAuditReader().find( SetRefEdEmbIdEntity.class, ed1_id, 3 ); - assert rev1.getReffering().equals(makeSet(ing1, ing2)); - assert rev2.getReffering().equals(makeSet(ing2)); - assert rev3.getReffering().equals(Collections.EMPTY_SET); - } + assert rev1.getReffering().equals( makeSet( ing1, ing2 ) ); + assert rev2.getReffering().equals( makeSet( ing2 ) ); + assert rev3.getReffering().equals( Collections.EMPTY_SET ); + } - @Test - public void testHistoryOfEdId2() { - SetRefIngEmbIdEntity ing1 = getEntityManager().find(SetRefIngEmbIdEntity.class, ing1_id); - SetRefIngEmbIdEntity ing2 = getEntityManager().find(SetRefIngEmbIdEntity.class, ing2_id); + @Test + public void testHistoryOfEdId2() { + SetRefIngEmbIdEntity ing1 = getEntityManager().find( SetRefIngEmbIdEntity.class, ing1_id ); + SetRefIngEmbIdEntity ing2 = getEntityManager().find( SetRefIngEmbIdEntity.class, ing2_id ); - SetRefEdEmbIdEntity rev1 = getAuditReader().find(SetRefEdEmbIdEntity.class, ed2_id, 1); - SetRefEdEmbIdEntity rev2 = getAuditReader().find(SetRefEdEmbIdEntity.class, ed2_id, 2); - SetRefEdEmbIdEntity rev3 = getAuditReader().find(SetRefEdEmbIdEntity.class, ed2_id, 3); + SetRefEdEmbIdEntity rev1 = getAuditReader().find( SetRefEdEmbIdEntity.class, ed2_id, 1 ); + SetRefEdEmbIdEntity rev2 = getAuditReader().find( SetRefEdEmbIdEntity.class, ed2_id, 2 ); + SetRefEdEmbIdEntity rev3 = getAuditReader().find( SetRefEdEmbIdEntity.class, ed2_id, 3 ); - assert rev1.getReffering().equals(Collections.EMPTY_SET); - assert rev2.getReffering().equals(makeSet(ing1)); - assert rev3.getReffering().equals(makeSet(ing1, ing2)); - } + assert rev1.getReffering().equals( Collections.EMPTY_SET ); + assert rev2.getReffering().equals( makeSet( ing1 ) ); + assert rev3.getReffering().equals( makeSet( ing1, ing2 ) ); + } - @Test - public void testHistoryOfEdIng1() { - SetRefEdEmbIdEntity ed1 = getEntityManager().find(SetRefEdEmbIdEntity.class, ed1_id); - SetRefEdEmbIdEntity ed2 = getEntityManager().find(SetRefEdEmbIdEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng1() { + SetRefEdEmbIdEntity ed1 = getEntityManager().find( SetRefEdEmbIdEntity.class, ed1_id ); + SetRefEdEmbIdEntity ed2 = getEntityManager().find( SetRefEdEmbIdEntity.class, ed2_id ); - SetRefIngEmbIdEntity rev1 = getAuditReader().find(SetRefIngEmbIdEntity.class, ing1_id, 1); - SetRefIngEmbIdEntity rev2 = getAuditReader().find(SetRefIngEmbIdEntity.class, ing1_id, 2); - SetRefIngEmbIdEntity rev3 = getAuditReader().find(SetRefIngEmbIdEntity.class, ing1_id, 3); + SetRefIngEmbIdEntity rev1 = getAuditReader().find( SetRefIngEmbIdEntity.class, ing1_id, 1 ); + SetRefIngEmbIdEntity rev2 = getAuditReader().find( SetRefIngEmbIdEntity.class, ing1_id, 2 ); + SetRefIngEmbIdEntity rev3 = getAuditReader().find( SetRefIngEmbIdEntity.class, ing1_id, 3 ); - assert rev1.getReference().equals(ed1); - assert rev2.getReference().equals(ed2); - assert rev3.getReference().equals(ed2); - } + assert rev1.getReference().equals( ed1 ); + assert rev2.getReference().equals( ed2 ); + assert rev3.getReference().equals( ed2 ); + } - @Test - public void testHistoryOfEdIng2() { - SetRefEdEmbIdEntity ed1 = getEntityManager().find(SetRefEdEmbIdEntity.class, ed1_id); - SetRefEdEmbIdEntity ed2 = getEntityManager().find(SetRefEdEmbIdEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng2() { + SetRefEdEmbIdEntity ed1 = getEntityManager().find( SetRefEdEmbIdEntity.class, ed1_id ); + SetRefEdEmbIdEntity ed2 = getEntityManager().find( SetRefEdEmbIdEntity.class, ed2_id ); - SetRefIngEmbIdEntity rev1 = getAuditReader().find(SetRefIngEmbIdEntity.class, ing2_id, 1); - SetRefIngEmbIdEntity rev2 = getAuditReader().find(SetRefIngEmbIdEntity.class, ing2_id, 2); - SetRefIngEmbIdEntity rev3 = getAuditReader().find(SetRefIngEmbIdEntity.class, ing2_id, 3); + SetRefIngEmbIdEntity rev1 = getAuditReader().find( SetRefIngEmbIdEntity.class, ing2_id, 1 ); + SetRefIngEmbIdEntity rev2 = getAuditReader().find( SetRefIngEmbIdEntity.class, ing2_id, 2 ); + SetRefIngEmbIdEntity rev3 = getAuditReader().find( SetRefIngEmbIdEntity.class, ing2_id, 3 ); - assert rev1.getReference().equals(ed1); - assert rev2.getReference().equals(ed1); - assert rev3.getReference().equals(ed2); - } + assert rev1.getReference().equals( ed1 ); + assert rev2.getReference().equals( ed1 ); + assert rev3.getReference().equals( ed2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicSetWithMulId.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicSetWithMulId.java index 61d1456f48..c2adab7ad1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicSetWithMulId.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicSetWithMulId.java @@ -23,13 +23,11 @@ */ package org.hibernate.envers.test.integration.onetomany; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -37,139 +35,143 @@ import org.hibernate.envers.test.entities.ids.MulId; import org.hibernate.envers.test.entities.onetomany.ids.SetRefEdMulIdEntity; import org.hibernate.envers.test.entities.onetomany.ids.SetRefIngMulIdEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BasicSetWithMulId extends BaseEnversJPAFunctionalTestCase { - private MulId ed1_id; - private MulId ed2_id; + private MulId ed1_id; + private MulId ed2_id; - private MulId ing1_id; - private MulId ing2_id; + private MulId ing1_id; + private MulId ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SetRefEdMulIdEntity.class, SetRefIngMulIdEntity.class }; - } + return new Class[] {SetRefEdMulIdEntity.class, SetRefIngMulIdEntity.class}; + } - @Test - @Priority(10) - public void initData() { - ed1_id = new MulId(0, 1); - ed2_id = new MulId(2, 3); + @Test + @Priority(10) + public void initData() { + ed1_id = new MulId( 0, 1 ); + ed2_id = new MulId( 2, 3 ); - ing2_id = new MulId(4, 5); - ing1_id = new MulId(6, 7); + ing2_id = new MulId( 4, 5 ); + ing1_id = new MulId( 6, 7 ); - EntityManager em = getEntityManager(); + EntityManager em = getEntityManager(); - SetRefEdMulIdEntity ed1 = new SetRefEdMulIdEntity(ed1_id.getId1(), ed1_id.getId2(), "data_ed_1"); - SetRefEdMulIdEntity ed2 = new SetRefEdMulIdEntity(ed2_id.getId1(), ed2_id.getId2(), "data_ed_2"); + SetRefEdMulIdEntity ed1 = new SetRefEdMulIdEntity( ed1_id.getId1(), ed1_id.getId2(), "data_ed_1" ); + SetRefEdMulIdEntity ed2 = new SetRefEdMulIdEntity( ed2_id.getId1(), ed2_id.getId2(), "data_ed_2" ); - SetRefIngMulIdEntity ing1 = new SetRefIngMulIdEntity(ing1_id.getId1(), ing1_id.getId2(), "data_ing_1", ed1); - SetRefIngMulIdEntity ing2 = new SetRefIngMulIdEntity(ing2_id.getId1(), ing2_id.getId2(), "data_ing_2", ed1); + SetRefIngMulIdEntity ing1 = new SetRefIngMulIdEntity( ing1_id.getId1(), ing1_id.getId2(), "data_ing_1", ed1 ); + SetRefIngMulIdEntity ing2 = new SetRefIngMulIdEntity( ing2_id.getId1(), ing2_id.getId2(), "data_ing_2", ed1 ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); + em.persist( ed1 ); + em.persist( ed2 ); - em.persist(ing1); - em.persist(ing2); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ing1 = em.find(SetRefIngMulIdEntity.class, ing1_id); - ed2 = em.find(SetRefEdMulIdEntity.class, ed2_id); + ing1 = em.find( SetRefIngMulIdEntity.class, ing1_id ); + ed2 = em.find( SetRefEdMulIdEntity.class, ed2_id ); - ing1.setReference(ed2); + ing1.setReference( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - ing2 = em.find(SetRefIngMulIdEntity.class, ing2_id); - ed2 = em.find(SetRefEdMulIdEntity.class, ed2_id); + ing2 = em.find( SetRefIngMulIdEntity.class, ing2_id ); + ed2 = em.find( SetRefEdMulIdEntity.class, ed2_id ); - ing2.setReference(ed2); + ing2.setReference( ed2 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(SetRefEdMulIdEntity.class, ed1_id)); - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(SetRefEdMulIdEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( SetRefEdMulIdEntity.class, ed1_id ) ); + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( SetRefEdMulIdEntity.class, ed2_id ) ); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(SetRefIngMulIdEntity.class, ing1_id)); - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(SetRefIngMulIdEntity.class, ing2_id)); - } + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( SetRefIngMulIdEntity.class, ing1_id ) ); + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( SetRefIngMulIdEntity.class, ing2_id ) ); + } - private Set makeSet(T... objects) { - Set ret = new HashSet(); - //noinspection ManualArrayToCollectionCopy - for (T obj : objects) { ret.add(obj); } - return ret; - } + private Set makeSet(T... objects) { + Set ret = new HashSet(); + //noinspection ManualArrayToCollectionCopy + for ( T obj : objects ) { + ret.add( obj ); + } + return ret; + } - @Test - public void testHistoryOfEdId1() { - SetRefIngMulIdEntity ing1 = getEntityManager().find(SetRefIngMulIdEntity.class, ing1_id); - SetRefIngMulIdEntity ing2 = getEntityManager().find(SetRefIngMulIdEntity.class, ing2_id); + @Test + public void testHistoryOfEdId1() { + SetRefIngMulIdEntity ing1 = getEntityManager().find( SetRefIngMulIdEntity.class, ing1_id ); + SetRefIngMulIdEntity ing2 = getEntityManager().find( SetRefIngMulIdEntity.class, ing2_id ); - SetRefEdMulIdEntity rev1 = getAuditReader().find(SetRefEdMulIdEntity.class, ed1_id, 1); - SetRefEdMulIdEntity rev2 = getAuditReader().find(SetRefEdMulIdEntity.class, ed1_id, 2); - SetRefEdMulIdEntity rev3 = getAuditReader().find(SetRefEdMulIdEntity.class, ed1_id, 3); + SetRefEdMulIdEntity rev1 = getAuditReader().find( SetRefEdMulIdEntity.class, ed1_id, 1 ); + SetRefEdMulIdEntity rev2 = getAuditReader().find( SetRefEdMulIdEntity.class, ed1_id, 2 ); + SetRefEdMulIdEntity rev3 = getAuditReader().find( SetRefEdMulIdEntity.class, ed1_id, 3 ); - assert rev1.getReffering().equals(makeSet(ing1, ing2)); - assert rev2.getReffering().equals(makeSet(ing2)); - assert rev3.getReffering().equals(Collections.EMPTY_SET); - } + assert rev1.getReffering().equals( makeSet( ing1, ing2 ) ); + assert rev2.getReffering().equals( makeSet( ing2 ) ); + assert rev3.getReffering().equals( Collections.EMPTY_SET ); + } - @Test - public void testHistoryOfEdId2() { - SetRefIngMulIdEntity ing1 = getEntityManager().find(SetRefIngMulIdEntity.class, ing1_id); - SetRefIngMulIdEntity ing2 = getEntityManager().find(SetRefIngMulIdEntity.class, ing2_id); + @Test + public void testHistoryOfEdId2() { + SetRefIngMulIdEntity ing1 = getEntityManager().find( SetRefIngMulIdEntity.class, ing1_id ); + SetRefIngMulIdEntity ing2 = getEntityManager().find( SetRefIngMulIdEntity.class, ing2_id ); - SetRefEdMulIdEntity rev1 = getAuditReader().find(SetRefEdMulIdEntity.class, ed2_id, 1); - SetRefEdMulIdEntity rev2 = getAuditReader().find(SetRefEdMulIdEntity.class, ed2_id, 2); - SetRefEdMulIdEntity rev3 = getAuditReader().find(SetRefEdMulIdEntity.class, ed2_id, 3); + SetRefEdMulIdEntity rev1 = getAuditReader().find( SetRefEdMulIdEntity.class, ed2_id, 1 ); + SetRefEdMulIdEntity rev2 = getAuditReader().find( SetRefEdMulIdEntity.class, ed2_id, 2 ); + SetRefEdMulIdEntity rev3 = getAuditReader().find( SetRefEdMulIdEntity.class, ed2_id, 3 ); - assert rev1.getReffering().equals(Collections.EMPTY_SET); - assert rev2.getReffering().equals(makeSet(ing1)); - assert rev3.getReffering().equals(makeSet(ing1, ing2)); - } + assert rev1.getReffering().equals( Collections.EMPTY_SET ); + assert rev2.getReffering().equals( makeSet( ing1 ) ); + assert rev3.getReffering().equals( makeSet( ing1, ing2 ) ); + } - @Test - public void testHistoryOfEdIng1() { - SetRefEdMulIdEntity ed1 = getEntityManager().find(SetRefEdMulIdEntity.class, ed1_id); - SetRefEdMulIdEntity ed2 = getEntityManager().find(SetRefEdMulIdEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng1() { + SetRefEdMulIdEntity ed1 = getEntityManager().find( SetRefEdMulIdEntity.class, ed1_id ); + SetRefEdMulIdEntity ed2 = getEntityManager().find( SetRefEdMulIdEntity.class, ed2_id ); - SetRefIngMulIdEntity rev1 = getAuditReader().find(SetRefIngMulIdEntity.class, ing1_id, 1); - SetRefIngMulIdEntity rev2 = getAuditReader().find(SetRefIngMulIdEntity.class, ing1_id, 2); - SetRefIngMulIdEntity rev3 = getAuditReader().find(SetRefIngMulIdEntity.class, ing1_id, 3); + SetRefIngMulIdEntity rev1 = getAuditReader().find( SetRefIngMulIdEntity.class, ing1_id, 1 ); + SetRefIngMulIdEntity rev2 = getAuditReader().find( SetRefIngMulIdEntity.class, ing1_id, 2 ); + SetRefIngMulIdEntity rev3 = getAuditReader().find( SetRefIngMulIdEntity.class, ing1_id, 3 ); - assert rev1.getReference().equals(ed1); - assert rev2.getReference().equals(ed2); - assert rev3.getReference().equals(ed2); - } + assert rev1.getReference().equals( ed1 ); + assert rev2.getReference().equals( ed2 ); + assert rev3.getReference().equals( ed2 ); + } - @Test - public void testHistoryOfEdIng2() { - SetRefEdMulIdEntity ed1 = getEntityManager().find(SetRefEdMulIdEntity.class, ed1_id); - SetRefEdMulIdEntity ed2 = getEntityManager().find(SetRefEdMulIdEntity.class, ed2_id); + @Test + public void testHistoryOfEdIng2() { + SetRefEdMulIdEntity ed1 = getEntityManager().find( SetRefEdMulIdEntity.class, ed1_id ); + SetRefEdMulIdEntity ed2 = getEntityManager().find( SetRefEdMulIdEntity.class, ed2_id ); - SetRefIngMulIdEntity rev1 = getAuditReader().find(SetRefIngMulIdEntity.class, ing2_id, 1); - SetRefIngMulIdEntity rev2 = getAuditReader().find(SetRefIngMulIdEntity.class, ing2_id, 2); - SetRefIngMulIdEntity rev3 = getAuditReader().find(SetRefIngMulIdEntity.class, ing2_id, 3); + SetRefIngMulIdEntity rev1 = getAuditReader().find( SetRefIngMulIdEntity.class, ing2_id, 1 ); + SetRefIngMulIdEntity rev2 = getAuditReader().find( SetRefIngMulIdEntity.class, ing2_id, 2 ); + SetRefIngMulIdEntity rev3 = getAuditReader().find( SetRefIngMulIdEntity.class, ing2_id, 3 ); - assert rev1.getReference().equals(ed1); - assert rev2.getReference().equals(ed1); - assert rev3.getReference().equals(ed2); - } + assert rev1.getReference().equals( ed1 ); + assert rev2.getReference().equals( ed1 ); + assert rev3.getReference().equals( ed2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicSetWithNullsDelete.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicSetWithNullsDelete.java index d71ef643eb..c1aa3dc541 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicSetWithNullsDelete.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BasicSetWithNullsDelete.java @@ -23,229 +23,231 @@ */ package org.hibernate.envers.test.integration.onetomany; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.onetomany.SetRefEdEntity; import org.hibernate.envers.test.entities.onetomany.SetRefIngEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BasicSetWithNullsDelete extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; - private Integer ing2_id; - private Integer ing3_id; - private Integer ing4_id; + private Integer ing1_id; + private Integer ing2_id; + private Integer ing3_id; + private Integer ing4_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SetRefEdEntity.class, SetRefIngEntity.class }; - } + return new Class[] {SetRefEdEntity.class, SetRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - SetRefEdEntity ed1 = new SetRefEdEntity(1, "data_ed_1"); - SetRefEdEntity ed2 = new SetRefEdEntity(2, "data_ed_2"); + SetRefEdEntity ed1 = new SetRefEdEntity( 1, "data_ed_1" ); + SetRefEdEntity ed2 = new SetRefEdEntity( 2, "data_ed_2" ); - SetRefIngEntity ing1 = new SetRefIngEntity(3, "data_ing_1", ed1); - SetRefIngEntity ing2 = new SetRefIngEntity(4, "data_ing_2", ed1); - SetRefIngEntity ing3 = new SetRefIngEntity(5, "data_ing_3", ed1); - SetRefIngEntity ing4 = new SetRefIngEntity(6, "data_ing_4", ed1); + SetRefIngEntity ing1 = new SetRefIngEntity( 3, "data_ing_1", ed1 ); + SetRefIngEntity ing2 = new SetRefIngEntity( 4, "data_ing_2", ed1 ); + SetRefIngEntity ing3 = new SetRefIngEntity( 5, "data_ing_3", ed1 ); + SetRefIngEntity ing4 = new SetRefIngEntity( 6, "data_ing_4", ed1 ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); + em.persist( ed1 ); + em.persist( ed2 ); - em.persist(ing1); - em.persist(ing2); - em.persist(ing3); - em.persist(ing4); + em.persist( ing1 ); + em.persist( ing2 ); + em.persist( ing3 ); + em.persist( ing4 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ing1 = em.find(SetRefIngEntity.class, ing1.getId()); + ing1 = em.find( SetRefIngEntity.class, ing1.getId() ); - ing1.setReference(null); + ing1.setReference( null ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - ing2 = em.find(SetRefIngEntity.class, ing2.getId()); - em.remove(ing2); + ing2 = em.find( SetRefIngEntity.class, ing2.getId() ); + em.remove( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); + // Revision 4 + em.getTransaction().begin(); - ing3 = em.find(SetRefIngEntity.class, ing3.getId()); - ed2 = em.find(SetRefEdEntity.class, ed2.getId()); - ing3.setReference(ed2); + ing3 = em.find( SetRefIngEntity.class, ing3.getId() ); + ed2 = em.find( SetRefEdEntity.class, ed2.getId() ); + ing3.setReference( ed2 ); - em.getTransaction().commit(); - // Revision 5 - em.getTransaction().begin(); + em.getTransaction().commit(); + // Revision 5 + em.getTransaction().begin(); - ing4 = em.find(SetRefIngEntity.class, ing4.getId()); - ed1 = em.find(SetRefEdEntity.class, ed1.getId()); - em.remove(ed1); - ing4.setReference(null); + ing4 = em.find( SetRefIngEntity.class, ing4.getId() ); + ed1 = em.find( SetRefEdEntity.class, ed1.getId() ); + em.remove( ed1 ); + ing4.setReference( null ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); - ing3_id = ing3.getId(); - ing4_id = ing4.getId(); - } + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); + ing3_id = ing3.getId(); + ing4_id = ing4.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3, 4, 5).equals(getAuditReader().getRevisions(SetRefEdEntity.class, ed1_id)); - assert Arrays.asList(1, 4).equals(getAuditReader().getRevisions(SetRefEdEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3, 4, 5 ).equals( getAuditReader().getRevisions( SetRefEdEntity.class, ed1_id ) ); + assert Arrays.asList( 1, 4 ).equals( getAuditReader().getRevisions( SetRefEdEntity.class, ed2_id ) ); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(SetRefIngEntity.class, ing1_id)); - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(SetRefIngEntity.class, ing2_id)); - assert Arrays.asList(1, 4).equals(getAuditReader().getRevisions(SetRefIngEntity.class, ing3_id)); - assert Arrays.asList(1, 5).equals(getAuditReader().getRevisions(SetRefIngEntity.class, ing4_id)); - } + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( SetRefIngEntity.class, ing1_id ) ); + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( SetRefIngEntity.class, ing2_id ) ); + assert Arrays.asList( 1, 4 ).equals( getAuditReader().getRevisions( SetRefIngEntity.class, ing3_id ) ); + assert Arrays.asList( 1, 5 ).equals( getAuditReader().getRevisions( SetRefIngEntity.class, ing4_id ) ); + } - private Set makeSet(T... objects) { - Set ret = new HashSet(); - //noinspection ManualArrayToCollectionCopy - for (T obj : objects) { ret.add(obj); } - return ret; - } + private Set makeSet(T... objects) { + Set ret = new HashSet(); + //noinspection ManualArrayToCollectionCopy + for ( T obj : objects ) { + ret.add( obj ); + } + return ret; + } - @Test - public void testHistoryOfEdId1() { - SetRefIngEntity ing1 = getEntityManager().find(SetRefIngEntity.class, ing1_id); - SetRefIngEntity ing2 = new SetRefIngEntity(4, "data_ing_2", new SetRefEdEntity(1, "data_ed_1")); - SetRefIngEntity ing3 = getEntityManager().find(SetRefIngEntity.class, ing3_id); - SetRefIngEntity ing4 = getEntityManager().find(SetRefIngEntity.class, ing4_id); + @Test + public void testHistoryOfEdId1() { + SetRefIngEntity ing1 = getEntityManager().find( SetRefIngEntity.class, ing1_id ); + SetRefIngEntity ing2 = new SetRefIngEntity( 4, "data_ing_2", new SetRefEdEntity( 1, "data_ed_1" ) ); + SetRefIngEntity ing3 = getEntityManager().find( SetRefIngEntity.class, ing3_id ); + SetRefIngEntity ing4 = getEntityManager().find( SetRefIngEntity.class, ing4_id ); - SetRefEdEntity rev1 = getAuditReader().find(SetRefEdEntity.class, ed1_id, 1); - SetRefEdEntity rev2 = getAuditReader().find(SetRefEdEntity.class, ed1_id, 2); - SetRefEdEntity rev3 = getAuditReader().find(SetRefEdEntity.class, ed1_id, 3); - SetRefEdEntity rev4 = getAuditReader().find(SetRefEdEntity.class, ed1_id, 4); - SetRefEdEntity rev5 = getAuditReader().find(SetRefEdEntity.class, ed1_id, 5); + SetRefEdEntity rev1 = getAuditReader().find( SetRefEdEntity.class, ed1_id, 1 ); + SetRefEdEntity rev2 = getAuditReader().find( SetRefEdEntity.class, ed1_id, 2 ); + SetRefEdEntity rev3 = getAuditReader().find( SetRefEdEntity.class, ed1_id, 3 ); + SetRefEdEntity rev4 = getAuditReader().find( SetRefEdEntity.class, ed1_id, 4 ); + SetRefEdEntity rev5 = getAuditReader().find( SetRefEdEntity.class, ed1_id, 5 ); - assert rev1.getReffering().equals(makeSet(ing1, ing2, ing3, ing4)); - assert rev2.getReffering().equals(makeSet(ing2, ing3, ing4)); - assert rev3.getReffering().equals(makeSet(ing3, ing4)); - assert rev4.getReffering().equals(makeSet(ing4)); - assert rev5 == null; - } + assert rev1.getReffering().equals( makeSet( ing1, ing2, ing3, ing4 ) ); + assert rev2.getReffering().equals( makeSet( ing2, ing3, ing4 ) ); + assert rev3.getReffering().equals( makeSet( ing3, ing4 ) ); + assert rev4.getReffering().equals( makeSet( ing4 ) ); + assert rev5 == null; + } - @Test - public void testHistoryOfEdId2() { - SetRefIngEntity ing3 = getEntityManager().find(SetRefIngEntity.class, ing3_id); + @Test + public void testHistoryOfEdId2() { + SetRefIngEntity ing3 = getEntityManager().find( SetRefIngEntity.class, ing3_id ); - SetRefEdEntity rev1 = getAuditReader().find(SetRefEdEntity.class, ed2_id, 1); - SetRefEdEntity rev2 = getAuditReader().find(SetRefEdEntity.class, ed2_id, 2); - SetRefEdEntity rev3 = getAuditReader().find(SetRefEdEntity.class, ed2_id, 3); - SetRefEdEntity rev4 = getAuditReader().find(SetRefEdEntity.class, ed2_id, 4); - SetRefEdEntity rev5 = getAuditReader().find(SetRefEdEntity.class, ed2_id, 5); + SetRefEdEntity rev1 = getAuditReader().find( SetRefEdEntity.class, ed2_id, 1 ); + SetRefEdEntity rev2 = getAuditReader().find( SetRefEdEntity.class, ed2_id, 2 ); + SetRefEdEntity rev3 = getAuditReader().find( SetRefEdEntity.class, ed2_id, 3 ); + SetRefEdEntity rev4 = getAuditReader().find( SetRefEdEntity.class, ed2_id, 4 ); + SetRefEdEntity rev5 = getAuditReader().find( SetRefEdEntity.class, ed2_id, 5 ); - assert rev1.getReffering().equals(Collections.EMPTY_SET); - assert rev2.getReffering().equals(Collections.EMPTY_SET); - assert rev3.getReffering().equals(Collections.EMPTY_SET); - assert rev4.getReffering().equals(makeSet(ing3)); - assert rev5.getReffering().equals(makeSet(ing3)); - } + assert rev1.getReffering().equals( Collections.EMPTY_SET ); + assert rev2.getReffering().equals( Collections.EMPTY_SET ); + assert rev3.getReffering().equals( Collections.EMPTY_SET ); + assert rev4.getReffering().equals( makeSet( ing3 ) ); + assert rev5.getReffering().equals( makeSet( ing3 ) ); + } - @Test - public void testHistoryOfEdIng1() { - SetRefEdEntity ed1 = new SetRefEdEntity(1, "data_ed_1"); + @Test + public void testHistoryOfEdIng1() { + SetRefEdEntity ed1 = new SetRefEdEntity( 1, "data_ed_1" ); - SetRefIngEntity rev1 = getAuditReader().find(SetRefIngEntity.class, ing1_id, 1); - SetRefIngEntity rev2 = getAuditReader().find(SetRefIngEntity.class, ing1_id, 2); - SetRefIngEntity rev3 = getAuditReader().find(SetRefIngEntity.class, ing1_id, 3); - SetRefIngEntity rev4 = getAuditReader().find(SetRefIngEntity.class, ing1_id, 4); - SetRefIngEntity rev5 = getAuditReader().find(SetRefIngEntity.class, ing1_id, 5); + SetRefIngEntity rev1 = getAuditReader().find( SetRefIngEntity.class, ing1_id, 1 ); + SetRefIngEntity rev2 = getAuditReader().find( SetRefIngEntity.class, ing1_id, 2 ); + SetRefIngEntity rev3 = getAuditReader().find( SetRefIngEntity.class, ing1_id, 3 ); + SetRefIngEntity rev4 = getAuditReader().find( SetRefIngEntity.class, ing1_id, 4 ); + SetRefIngEntity rev5 = getAuditReader().find( SetRefIngEntity.class, ing1_id, 5 ); - assert rev1.getReference().equals(ed1); - assert rev2.getReference() == null; - assert rev3.getReference() == null; - assert rev4.getReference() == null; - assert rev5.getReference() == null; - } + assert rev1.getReference().equals( ed1 ); + assert rev2.getReference() == null; + assert rev3.getReference() == null; + assert rev4.getReference() == null; + assert rev5.getReference() == null; + } - @Test - public void testHistoryOfEdIng2() { - SetRefEdEntity ed1 = new SetRefEdEntity(1, "data_ed_1"); + @Test + public void testHistoryOfEdIng2() { + SetRefEdEntity ed1 = new SetRefEdEntity( 1, "data_ed_1" ); - SetRefIngEntity rev1 = getAuditReader().find(SetRefIngEntity.class, ing2_id, 1); - SetRefIngEntity rev2 = getAuditReader().find(SetRefIngEntity.class, ing2_id, 2); - SetRefIngEntity rev3 = getAuditReader().find(SetRefIngEntity.class, ing2_id, 3); - SetRefIngEntity rev4 = getAuditReader().find(SetRefIngEntity.class, ing2_id, 4); - SetRefIngEntity rev5 = getAuditReader().find(SetRefIngEntity.class, ing2_id, 5); + SetRefIngEntity rev1 = getAuditReader().find( SetRefIngEntity.class, ing2_id, 1 ); + SetRefIngEntity rev2 = getAuditReader().find( SetRefIngEntity.class, ing2_id, 2 ); + SetRefIngEntity rev3 = getAuditReader().find( SetRefIngEntity.class, ing2_id, 3 ); + SetRefIngEntity rev4 = getAuditReader().find( SetRefIngEntity.class, ing2_id, 4 ); + SetRefIngEntity rev5 = getAuditReader().find( SetRefIngEntity.class, ing2_id, 5 ); - assert rev1.getReference().equals(ed1); - assert rev2.getReference().equals(ed1); - assert rev3 == null; - assert rev4 == null; - assert rev5 == null; - } + assert rev1.getReference().equals( ed1 ); + assert rev2.getReference().equals( ed1 ); + assert rev3 == null; + assert rev4 == null; + assert rev5 == null; + } - @Test - public void testHistoryOfEdIng3() { - SetRefEdEntity ed1 = new SetRefEdEntity(1, "data_ed_1"); - SetRefEdEntity ed2 = new SetRefEdEntity(2, "data_ed_2"); - - SetRefIngEntity rev1 = getAuditReader().find(SetRefIngEntity.class, ing3_id, 1); - SetRefIngEntity rev2 = getAuditReader().find(SetRefIngEntity.class, ing3_id, 2); - SetRefIngEntity rev3 = getAuditReader().find(SetRefIngEntity.class, ing3_id, 3); - SetRefIngEntity rev4 = getAuditReader().find(SetRefIngEntity.class, ing3_id, 4); - SetRefIngEntity rev5 = getAuditReader().find(SetRefIngEntity.class, ing3_id, 5); + @Test + public void testHistoryOfEdIng3() { + SetRefEdEntity ed1 = new SetRefEdEntity( 1, "data_ed_1" ); + SetRefEdEntity ed2 = new SetRefEdEntity( 2, "data_ed_2" ); - assert rev1.getReference().equals(ed1); - assert rev2.getReference().equals(ed1); - assert rev3.getReference().equals(ed1); - assert rev4.getReference().equals(ed2); - assert rev5.getReference().equals(ed2); - } + SetRefIngEntity rev1 = getAuditReader().find( SetRefIngEntity.class, ing3_id, 1 ); + SetRefIngEntity rev2 = getAuditReader().find( SetRefIngEntity.class, ing3_id, 2 ); + SetRefIngEntity rev3 = getAuditReader().find( SetRefIngEntity.class, ing3_id, 3 ); + SetRefIngEntity rev4 = getAuditReader().find( SetRefIngEntity.class, ing3_id, 4 ); + SetRefIngEntity rev5 = getAuditReader().find( SetRefIngEntity.class, ing3_id, 5 ); - @Test - public void testHistoryOfEdIng4() { - SetRefEdEntity ed1 = new SetRefEdEntity(1, "data_ed_1"); + assert rev1.getReference().equals( ed1 ); + assert rev2.getReference().equals( ed1 ); + assert rev3.getReference().equals( ed1 ); + assert rev4.getReference().equals( ed2 ); + assert rev5.getReference().equals( ed2 ); + } - SetRefIngEntity rev1 = getAuditReader().find(SetRefIngEntity.class, ing4_id, 1); - SetRefIngEntity rev2 = getAuditReader().find(SetRefIngEntity.class, ing4_id, 2); - SetRefIngEntity rev3 = getAuditReader().find(SetRefIngEntity.class, ing4_id, 3); - SetRefIngEntity rev4 = getAuditReader().find(SetRefIngEntity.class, ing4_id, 4); - SetRefIngEntity rev5 = getAuditReader().find(SetRefIngEntity.class, ing4_id, 5); + @Test + public void testHistoryOfEdIng4() { + SetRefEdEntity ed1 = new SetRefEdEntity( 1, "data_ed_1" ); - assert rev1.getReference().equals(ed1); - assert rev2.getReference().equals(ed1); - assert rev3.getReference().equals(ed1); - assert rev4.getReference().equals(ed1); - assert rev5.getReference() == null; - } + SetRefIngEntity rev1 = getAuditReader().find( SetRefIngEntity.class, ing4_id, 1 ); + SetRefIngEntity rev2 = getAuditReader().find( SetRefIngEntity.class, ing4_id, 2 ); + SetRefIngEntity rev3 = getAuditReader().find( SetRefIngEntity.class, ing4_id, 3 ); + SetRefIngEntity rev4 = getAuditReader().find( SetRefIngEntity.class, ing4_id, 4 ); + SetRefIngEntity rev5 = getAuditReader().find( SetRefIngEntity.class, ing4_id, 5 ); + + assert rev1.getReference().equals( ed1 ); + assert rev2.getReference().equals( ed1 ); + assert rev3.getReference().equals( ed1 ); + assert rev4.getReference().equals( ed1 ); + assert rev5.getReference() == null; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BidirectionalMapKey.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BidirectionalMapKey.java index 843b617e33..494c4cc0ed 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BidirectionalMapKey.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/BidirectionalMapKey.java @@ -23,88 +23,88 @@ */ package org.hibernate.envers.test.integration.onetomany; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BidirectionalMapKey extends BaseEnversJPAFunctionalTestCase { - private Integer ed_id; + private Integer ed_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { RefIngMapKeyEntity.class, RefEdMapKeyEntity.class }; - } + return new Class[] {RefIngMapKeyEntity.class, RefEdMapKeyEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 1 (intialy 1 relation: ing1 -> ed) - em.getTransaction().begin(); + // Revision 1 (intialy 1 relation: ing1 -> ed) + em.getTransaction().begin(); - RefEdMapKeyEntity ed = new RefEdMapKeyEntity(); + RefEdMapKeyEntity ed = new RefEdMapKeyEntity(); - em.persist(ed); + em.persist( ed ); - RefIngMapKeyEntity ing1 = new RefIngMapKeyEntity(); - ing1.setData("a"); - ing1.setReference(ed); + RefIngMapKeyEntity ing1 = new RefIngMapKeyEntity(); + ing1.setData( "a" ); + ing1.setReference( ed ); - RefIngMapKeyEntity ing2 = new RefIngMapKeyEntity(); - ing2.setData("b"); + RefIngMapKeyEntity ing2 = new RefIngMapKeyEntity(); + ing2.setData( "b" ); - em.persist(ing1); - em.persist(ing2); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (adding second relation: ing2 -> ed) - em.getTransaction().begin(); + // Revision 2 (adding second relation: ing2 -> ed) + em.getTransaction().begin(); - ed = em.find(RefEdMapKeyEntity.class, ed.getId()); - ing2 = em.find(RefIngMapKeyEntity.class, ing2.getId()); + ed = em.find( RefEdMapKeyEntity.class, ed.getId() ); + ing2 = em.find( RefIngMapKeyEntity.class, ing2.getId() ); - ing2.setReference(ed); + ing2.setReference( ed ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed_id = ed.getId(); + ed_id = ed.getId(); - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); - } + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(RefEdMapKeyEntity.class, ed_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( RefEdMapKeyEntity.class, ed_id ) ); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(RefIngMapKeyEntity.class, ing1_id)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(RefIngMapKeyEntity.class, ing2_id)); - } + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( RefIngMapKeyEntity.class, ing1_id ) ); + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( RefIngMapKeyEntity.class, ing2_id ) ); + } - @Test - public void testHistoryOfEd() { - RefIngMapKeyEntity ing1 = getEntityManager().find(RefIngMapKeyEntity.class, ing1_id); - RefIngMapKeyEntity ing2 = getEntityManager().find(RefIngMapKeyEntity.class, ing2_id); + @Test + public void testHistoryOfEd() { + RefIngMapKeyEntity ing1 = getEntityManager().find( RefIngMapKeyEntity.class, ing1_id ); + RefIngMapKeyEntity ing2 = getEntityManager().find( RefIngMapKeyEntity.class, ing2_id ); - RefEdMapKeyEntity rev1 = getAuditReader().find(RefEdMapKeyEntity.class, ed_id, 1); - RefEdMapKeyEntity rev2 = getAuditReader().find(RefEdMapKeyEntity.class, ed_id, 2); + RefEdMapKeyEntity rev1 = getAuditReader().find( RefEdMapKeyEntity.class, ed_id, 1 ); + RefEdMapKeyEntity rev2 = getAuditReader().find( RefEdMapKeyEntity.class, ed_id, 2 ); - assert rev1.getIdmap().equals(TestTools.makeMap("a", ing1)); - assert rev2.getIdmap().equals(TestTools.makeMap("a", ing1, "b", ing2)); - } + assert rev1.getIdmap().equals( TestTools.makeMap( "a", ing1 ) ); + assert rev2.getIdmap().equals( TestTools.makeMap( "a", ing1, "b", ing2 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/InverseSideChanges.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/InverseSideChanges.java index ec652dd7e3..79eeb5d789 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/InverseSideChanges.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/InverseSideChanges.java @@ -24,85 +24,85 @@ package org.hibernate.envers.test.integration.onetomany; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.onetomany.SetRefEdEntity; import org.hibernate.envers.test.entities.onetomany.SetRefIngEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class InverseSideChanges extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; + private Integer ed1_id; - private Integer ing1_id; + private Integer ing1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SetRefEdEntity.class, SetRefIngEntity.class }; - } + return new Class[] {SetRefEdEntity.class, SetRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - SetRefEdEntity ed1 = new SetRefEdEntity(1, "data_ed_1"); + SetRefEdEntity ed1 = new SetRefEdEntity( 1, "data_ed_1" ); - SetRefIngEntity ing1 = new SetRefIngEntity(3, "data_ing_1"); + SetRefIngEntity ing1 = new SetRefIngEntity( 3, "data_ing_1" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(ed1); + em.persist( ed1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 + // Revision 2 - em.getTransaction().begin(); + em.getTransaction().begin(); - ed1 = em.find(SetRefEdEntity.class, ed1.getId()); - - em.persist(ing1); + ed1 = em.find( SetRefEdEntity.class, ed1.getId() ); - ed1.setReffering(new HashSet()); - ed1.getReffering().add(ing1); + em.persist( ing1 ); - em.getTransaction().commit(); + ed1.setReffering( new HashSet() ); + ed1.getReffering().add( ing1 ); - // + em.getTransaction().commit(); - ed1_id = ed1.getId(); + // - ing1_id = ing1.getId(); - } + ed1_id = ed1.getId(); - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1).equals(getAuditReader().getRevisions(SetRefEdEntity.class, ed1_id)); + ing1_id = ing1.getId(); + } - assert Arrays.asList(2).equals(getAuditReader().getRevisions(SetRefIngEntity.class, ing1_id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( SetRefEdEntity.class, ed1_id ) ); - @Test - public void testHistoryOfEdId1() { - SetRefEdEntity rev1 = getAuditReader().find(SetRefEdEntity.class, ed1_id, 1); + assert Arrays.asList( 2 ).equals( getAuditReader().getRevisions( SetRefIngEntity.class, ing1_id ) ); + } - assert rev1.getReffering().equals(Collections.EMPTY_SET); - } + @Test + public void testHistoryOfEdId1() { + SetRefEdEntity rev1 = getAuditReader().find( SetRefEdEntity.class, ed1_id, 1 ); - @Test - public void testHistoryOfEdIng1() { - SetRefIngEntity rev2 = getAuditReader().find(SetRefIngEntity.class, ing1_id, 2); + assert rev1.getReffering().equals( Collections.EMPTY_SET ); + } - assert rev2.getReference() == null; - } + @Test + public void testHistoryOfEdIng1() { + SetRefIngEntity rev2 = getAuditReader().find( SetRefIngEntity.class, ing1_id, 2 ); + + assert rev2.getReference() == null; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/RefEdMapKeyEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/RefEdMapKeyEntity.java index 1c63c61674..6abbb75fc9 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/RefEdMapKeyEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/RefEdMapKeyEntity.java @@ -22,13 +22,14 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.onetomany; -import java.util.HashMap; -import java.util.Map; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.MapKey; import javax.persistence.OneToMany; +import java.util.HashMap; +import java.util.Map; import org.hibernate.envers.Audited; @@ -37,51 +38,57 @@ import org.hibernate.envers.Audited; */ @Entity public class RefEdMapKeyEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - @OneToMany(mappedBy="reference") - @MapKey(name = "data") - private Map idmap; + @Audited + @OneToMany(mappedBy = "reference") + @MapKey(name = "data") + private Map idmap; - public RefEdMapKeyEntity() { - idmap = new HashMap(); - } + public RefEdMapKeyEntity() { + idmap = new HashMap(); + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public Map getIdmap() { - return idmap; - } + public Map getIdmap() { + return idmap; + } - public void setIdmap(Map idmap) { - this.idmap = idmap; - } + public void setIdmap(Map idmap) { + this.idmap = idmap; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof RefEdMapKeyEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof RefEdMapKeyEntity) ) { + return false; + } - RefEdMapKeyEntity that = (RefEdMapKeyEntity) o; + RefEdMapKeyEntity that = (RefEdMapKeyEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - return (id != null ? id.hashCode() : 0); - } + public int hashCode() { + return (id != null ? id.hashCode() : 0); + } - public String toString() { - return "RedMKE(id = " + id + ", idmap = " + idmap + ")"; - } + public String toString() { + return "RedMKE(id = " + id + ", idmap = " + idmap + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/RefIngMapKeyEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/RefIngMapKeyEntity.java index a674bac718..e337700d63 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/RefIngMapKeyEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/RefIngMapKeyEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.onetomany; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -34,57 +35,63 @@ import org.hibernate.envers.Audited; */ @Entity public class RefIngMapKeyEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - @ManyToOne - private RefEdMapKeyEntity reference; + @Audited + @ManyToOne + private RefEdMapKeyEntity reference; - @Audited - private String data; + @Audited + private String data; - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public RefEdMapKeyEntity getReference() { - return reference; - } + public RefEdMapKeyEntity getReference() { + return reference; + } - public void setReference(RefEdMapKeyEntity reference) { - this.reference = reference; - } + public void setReference(RefEdMapKeyEntity reference) { + this.reference = reference; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof RefIngMapKeyEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof RefIngMapKeyEntity) ) { + return false; + } - RefIngMapKeyEntity that = (RefIngMapKeyEntity) o; + RefIngMapKeyEntity that = (RefIngMapKeyEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - return (id != null ? id.hashCode() : 0); - } + public int hashCode() { + return (id != null ? id.hashCode() : 0); + } - public String toString() { - return "RingMKE(id = " + id + ", data = " + data + ", reference = " + reference + ")"; - } + public String toString() { + return "RingMKE(id = " + id + ", data = " + data + ", reference = " + reference + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicDetachedList.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicDetachedList.java index 81bd37bb80..682b52ed63 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicDetachedList.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicDetachedList.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.onetomany.detached; +import javax.persistence.EntityManager; import java.util.ArrayList; import java.util.Arrays; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -35,105 +33,107 @@ import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.onetomany.detached.ListRefCollEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BasicDetachedList extends BaseEnversJPAFunctionalTestCase { - private Integer str1_id; - private Integer str2_id; + private Integer str1_id; + private Integer str2_id; - private Integer coll1_id; + private Integer coll1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class, ListRefCollEntity.class }; - } + return new Class[] {StrTestEntity.class, ListRefCollEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - StrTestEntity str1 = new StrTestEntity("str1"); - StrTestEntity str2 = new StrTestEntity("str2"); + StrTestEntity str1 = new StrTestEntity( "str1" ); + StrTestEntity str2 = new StrTestEntity( "str2" ); - ListRefCollEntity coll1 = new ListRefCollEntity(3, "coll1"); + ListRefCollEntity coll1 = new ListRefCollEntity( 3, "coll1" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(str1); - em.persist(str2); + em.persist( str1 ); + em.persist( str2 ); - coll1.setCollection(new ArrayList()); - coll1.getCollection().add(str1); - em.persist(coll1); + coll1.setCollection( new ArrayList() ); + coll1.getCollection().add( str1 ); + em.persist( coll1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - str2 = em.find(StrTestEntity.class, str2.getId()); - coll1 = em.find(ListRefCollEntity.class, coll1.getId()); + str2 = em.find( StrTestEntity.class, str2.getId() ); + coll1 = em.find( ListRefCollEntity.class, coll1.getId() ); - coll1.getCollection().add(str2); + coll1.getCollection().add( str2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - str1 = em.find(StrTestEntity.class, str1.getId()); - coll1 = em.find(ListRefCollEntity.class, coll1.getId()); + str1 = em.find( StrTestEntity.class, str1.getId() ); + coll1 = em.find( ListRefCollEntity.class, coll1.getId() ); - coll1.getCollection().remove(str1); + coll1.getCollection().remove( str1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); + // Revision 4 + em.getTransaction().begin(); - coll1 = em.find(ListRefCollEntity.class, coll1.getId()); + coll1 = em.find( ListRefCollEntity.class, coll1.getId() ); - coll1.getCollection().clear(); + coll1.getCollection().clear(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - str1_id = str1.getId(); - str2_id = str2.getId(); + str1_id = str1.getId(); + str2_id = str2.getId(); - coll1_id = coll1.getId(); - } + coll1_id = coll1.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3, 4).equals(getAuditReader().getRevisions(ListRefCollEntity.class, coll1_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3, 4 ).equals( getAuditReader().getRevisions( ListRefCollEntity.class, coll1_id ) ); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestEntity.class, str1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestEntity.class, str2_id)); - } + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestEntity.class, str1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestEntity.class, str2_id ) ); + } - @Test - public void testHistoryOfColl1() { - StrTestEntity str1 = getEntityManager().find(StrTestEntity.class, str1_id); - StrTestEntity str2 = getEntityManager().find(StrTestEntity.class, str2_id); + @Test + public void testHistoryOfColl1() { + StrTestEntity str1 = getEntityManager().find( StrTestEntity.class, str1_id ); + StrTestEntity str2 = getEntityManager().find( StrTestEntity.class, str2_id ); - ListRefCollEntity rev1 = getAuditReader().find(ListRefCollEntity.class, coll1_id, 1); - ListRefCollEntity rev2 = getAuditReader().find(ListRefCollEntity.class, coll1_id, 2); - ListRefCollEntity rev3 = getAuditReader().find(ListRefCollEntity.class, coll1_id, 3); - ListRefCollEntity rev4 = getAuditReader().find(ListRefCollEntity.class, coll1_id, 4); + ListRefCollEntity rev1 = getAuditReader().find( ListRefCollEntity.class, coll1_id, 1 ); + ListRefCollEntity rev2 = getAuditReader().find( ListRefCollEntity.class, coll1_id, 2 ); + ListRefCollEntity rev3 = getAuditReader().find( ListRefCollEntity.class, coll1_id, 3 ); + ListRefCollEntity rev4 = getAuditReader().find( ListRefCollEntity.class, coll1_id, 4 ); - assert TestTools.checkList(rev1.getCollection(), str1); - assert TestTools.checkList(rev2.getCollection(), str1, str2); - assert TestTools.checkList(rev3.getCollection(), str2); - assert TestTools.checkList(rev4.getCollection()); - - assert "coll1".equals(rev1.getData()); - assert "coll1".equals(rev2.getData()); - assert "coll1".equals(rev3.getData()); - assert "coll1".equals(rev4.getData()); - } + assert TestTools.checkList( rev1.getCollection(), str1 ); + assert TestTools.checkList( rev2.getCollection(), str1, str2 ); + assert TestTools.checkList( rev3.getCollection(), str2 ); + assert TestTools.checkList( rev4.getCollection() ); + + assert "coll1".equals( rev1.getData() ); + assert "coll1".equals( rev2.getData() ); + assert "coll1".equals( rev3.getData() ); + assert "coll1".equals( rev4.getData() ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicDetachedSet.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicDetachedSet.java index 8e1f763e96..e19e18aedd 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicDetachedSet.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicDetachedSet.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.onetomany.detached; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.HashSet; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -35,105 +33,107 @@ import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.onetomany.detached.SetRefCollEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BasicDetachedSet extends BaseEnversJPAFunctionalTestCase { - private Integer str1_id; - private Integer str2_id; + private Integer str1_id; + private Integer str2_id; - private Integer coll1_id; + private Integer coll1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class, SetRefCollEntity.class }; - } + return new Class[] {StrTestEntity.class, SetRefCollEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - StrTestEntity str1 = new StrTestEntity("str1"); - StrTestEntity str2 = new StrTestEntity("str2"); + StrTestEntity str1 = new StrTestEntity( "str1" ); + StrTestEntity str2 = new StrTestEntity( "str2" ); - SetRefCollEntity coll1 = new SetRefCollEntity(3, "coll1"); + SetRefCollEntity coll1 = new SetRefCollEntity( 3, "coll1" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(str1); - em.persist(str2); + em.persist( str1 ); + em.persist( str2 ); - coll1.setCollection(new HashSet()); - coll1.getCollection().add(str1); - em.persist(coll1); + coll1.setCollection( new HashSet() ); + coll1.getCollection().add( str1 ); + em.persist( coll1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - str2 = em.find(StrTestEntity.class, str2.getId()); - coll1 = em.find(SetRefCollEntity.class, coll1.getId()); + str2 = em.find( StrTestEntity.class, str2.getId() ); + coll1 = em.find( SetRefCollEntity.class, coll1.getId() ); - coll1.getCollection().add(str2); + coll1.getCollection().add( str2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - str1 = em.find(StrTestEntity.class, str1.getId()); - coll1 = em.find(SetRefCollEntity.class, coll1.getId()); + str1 = em.find( StrTestEntity.class, str1.getId() ); + coll1 = em.find( SetRefCollEntity.class, coll1.getId() ); - coll1.getCollection().remove(str1); + coll1.getCollection().remove( str1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); + // Revision 4 + em.getTransaction().begin(); - coll1 = em.find(SetRefCollEntity.class, coll1.getId()); + coll1 = em.find( SetRefCollEntity.class, coll1.getId() ); - coll1.getCollection().clear(); + coll1.getCollection().clear(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - str1_id = str1.getId(); - str2_id = str2.getId(); + str1_id = str1.getId(); + str2_id = str2.getId(); - coll1_id = coll1.getId(); - } + coll1_id = coll1.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3, 4).equals(getAuditReader().getRevisions(SetRefCollEntity.class, coll1_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3, 4 ).equals( getAuditReader().getRevisions( SetRefCollEntity.class, coll1_id ) ); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestEntity.class, str1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestEntity.class, str2_id)); - } + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestEntity.class, str1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestEntity.class, str2_id ) ); + } - @Test - public void testHistoryOfColl1() { - StrTestEntity str1 = getEntityManager().find(StrTestEntity.class, str1_id); - StrTestEntity str2 = getEntityManager().find(StrTestEntity.class, str2_id); + @Test + public void testHistoryOfColl1() { + StrTestEntity str1 = getEntityManager().find( StrTestEntity.class, str1_id ); + StrTestEntity str2 = getEntityManager().find( StrTestEntity.class, str2_id ); - SetRefCollEntity rev1 = getAuditReader().find(SetRefCollEntity.class, coll1_id, 1); - SetRefCollEntity rev2 = getAuditReader().find(SetRefCollEntity.class, coll1_id, 2); - SetRefCollEntity rev3 = getAuditReader().find(SetRefCollEntity.class, coll1_id, 3); - SetRefCollEntity rev4 = getAuditReader().find(SetRefCollEntity.class, coll1_id, 4); + SetRefCollEntity rev1 = getAuditReader().find( SetRefCollEntity.class, coll1_id, 1 ); + SetRefCollEntity rev2 = getAuditReader().find( SetRefCollEntity.class, coll1_id, 2 ); + SetRefCollEntity rev3 = getAuditReader().find( SetRefCollEntity.class, coll1_id, 3 ); + SetRefCollEntity rev4 = getAuditReader().find( SetRefCollEntity.class, coll1_id, 4 ); - assert rev1.getCollection().equals(TestTools.makeSet(str1)); - assert rev2.getCollection().equals(TestTools.makeSet(str1, str2)); - assert rev3.getCollection().equals(TestTools.makeSet(str2)); - assert rev4.getCollection().equals(TestTools.makeSet()); + assert rev1.getCollection().equals( TestTools.makeSet( str1 ) ); + assert rev2.getCollection().equals( TestTools.makeSet( str1, str2 ) ); + assert rev3.getCollection().equals( TestTools.makeSet( str2 ) ); + assert rev4.getCollection().equals( TestTools.makeSet() ); - assert "coll1".equals(rev1.getData()); - assert "coll1".equals(rev2.getData()); - assert "coll1".equals(rev3.getData()); - assert "coll1".equals(rev4.getData()); - } + assert "coll1".equals( rev1.getData() ); + assert "coll1".equals( rev2.getData() ); + assert "coll1".equals( rev3.getData() ); + assert "coll1".equals( rev4.getData() ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicDetachedSetWithEmbId.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicDetachedSetWithEmbId.java index e60a949091..2b3e9bad8a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicDetachedSetWithEmbId.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicDetachedSetWithEmbId.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.onetomany.detached; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.HashSet; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -36,103 +34,110 @@ import org.hibernate.envers.test.entities.ids.EmbIdTestEntity; import org.hibernate.envers.test.entities.onetomany.detached.ids.SetRefCollEntityEmbId; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BasicDetachedSetWithEmbId extends BaseEnversJPAFunctionalTestCase { - private EmbId str1_id; - private EmbId str2_id; + private EmbId str1_id; + private EmbId str2_id; - private EmbId coll1_id; + private EmbId coll1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { EmbIdTestEntity.class, SetRefCollEntityEmbId.class }; - } + return new Class[] {EmbIdTestEntity.class, SetRefCollEntityEmbId.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - str1_id = new EmbId(1, 2); - str2_id = new EmbId(3, 4); + str1_id = new EmbId( 1, 2 ); + str2_id = new EmbId( 3, 4 ); - coll1_id = new EmbId(5, 6); + coll1_id = new EmbId( 5, 6 ); - EmbIdTestEntity str1 = new EmbIdTestEntity(str1_id, "str1"); - EmbIdTestEntity str2 = new EmbIdTestEntity(str2_id, "str2"); + EmbIdTestEntity str1 = new EmbIdTestEntity( str1_id, "str1" ); + EmbIdTestEntity str2 = new EmbIdTestEntity( str2_id, "str2" ); - SetRefCollEntityEmbId coll1 = new SetRefCollEntityEmbId(coll1_id, "coll1"); + SetRefCollEntityEmbId coll1 = new SetRefCollEntityEmbId( coll1_id, "coll1" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(str1); - em.persist(str2); + em.persist( str1 ); + em.persist( str2 ); - coll1.setCollection(new HashSet()); - coll1.getCollection().add(str1); - em.persist(coll1); + coll1.setCollection( new HashSet() ); + coll1.getCollection().add( str1 ); + em.persist( coll1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - str2 = em.find(EmbIdTestEntity.class, str2.getId()); - coll1 = em.find(SetRefCollEntityEmbId.class, coll1.getId()); + str2 = em.find( EmbIdTestEntity.class, str2.getId() ); + coll1 = em.find( SetRefCollEntityEmbId.class, coll1.getId() ); - coll1.getCollection().add(str2); + coll1.getCollection().add( str2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - str1 = em.find(EmbIdTestEntity.class, str1.getId()); - coll1 = em.find(SetRefCollEntityEmbId.class, coll1.getId()); + str1 = em.find( EmbIdTestEntity.class, str1.getId() ); + coll1 = em.find( SetRefCollEntityEmbId.class, coll1.getId() ); - coll1.getCollection().remove(str1); + coll1.getCollection().remove( str1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); + // Revision 4 + em.getTransaction().begin(); - coll1 = em.find(SetRefCollEntityEmbId.class, coll1.getId()); + coll1 = em.find( SetRefCollEntityEmbId.class, coll1.getId() ); - coll1.getCollection().clear(); + coll1.getCollection().clear(); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3, 4).equals(getAuditReader().getRevisions(SetRefCollEntityEmbId.class, coll1_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3, 4 ).equals( + getAuditReader().getRevisions( + SetRefCollEntityEmbId.class, + coll1_id + ) + ); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(EmbIdTestEntity.class, str1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(EmbIdTestEntity.class, str2_id)); - } + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( EmbIdTestEntity.class, str1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( EmbIdTestEntity.class, str2_id ) ); + } - @Test - public void testHistoryOfColl1() { - EmbIdTestEntity str1 = getEntityManager().find(EmbIdTestEntity.class, str1_id); - EmbIdTestEntity str2 = getEntityManager().find(EmbIdTestEntity.class, str2_id); + @Test + public void testHistoryOfColl1() { + EmbIdTestEntity str1 = getEntityManager().find( EmbIdTestEntity.class, str1_id ); + EmbIdTestEntity str2 = getEntityManager().find( EmbIdTestEntity.class, str2_id ); - SetRefCollEntityEmbId rev1 = getAuditReader().find(SetRefCollEntityEmbId.class, coll1_id, 1); - SetRefCollEntityEmbId rev2 = getAuditReader().find(SetRefCollEntityEmbId.class, coll1_id, 2); - SetRefCollEntityEmbId rev3 = getAuditReader().find(SetRefCollEntityEmbId.class, coll1_id, 3); - SetRefCollEntityEmbId rev4 = getAuditReader().find(SetRefCollEntityEmbId.class, coll1_id, 4); + SetRefCollEntityEmbId rev1 = getAuditReader().find( SetRefCollEntityEmbId.class, coll1_id, 1 ); + SetRefCollEntityEmbId rev2 = getAuditReader().find( SetRefCollEntityEmbId.class, coll1_id, 2 ); + SetRefCollEntityEmbId rev3 = getAuditReader().find( SetRefCollEntityEmbId.class, coll1_id, 3 ); + SetRefCollEntityEmbId rev4 = getAuditReader().find( SetRefCollEntityEmbId.class, coll1_id, 4 ); - assert rev1.getCollection().equals(TestTools.makeSet(str1)); - assert rev2.getCollection().equals(TestTools.makeSet(str1, str2)); - assert rev3.getCollection().equals(TestTools.makeSet(str2)); - assert rev4.getCollection().equals(TestTools.makeSet()); + assert rev1.getCollection().equals( TestTools.makeSet( str1 ) ); + assert rev2.getCollection().equals( TestTools.makeSet( str1, str2 ) ); + assert rev3.getCollection().equals( TestTools.makeSet( str2 ) ); + assert rev4.getCollection().equals( TestTools.makeSet() ); - assert "coll1".equals(rev1.getData()); - assert "coll1".equals(rev2.getData()); - assert "coll1".equals(rev3.getData()); - assert "coll1".equals(rev4.getData()); - } + assert "coll1".equals( rev1.getData() ); + assert "coll1".equals( rev2.getData() ); + assert "coll1".equals( rev3.getData() ); + assert "coll1".equals( rev4.getData() ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicDetachedSetWithMulId.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicDetachedSetWithMulId.java index 21507b8442..3403a7538e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicDetachedSetWithMulId.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicDetachedSetWithMulId.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.onetomany.detached; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.HashSet; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -36,103 +34,110 @@ import org.hibernate.envers.test.entities.ids.MulIdTestEntity; import org.hibernate.envers.test.entities.onetomany.detached.ids.SetRefCollEntityMulId; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BasicDetachedSetWithMulId extends BaseEnversJPAFunctionalTestCase { - private MulId str1_id; - private MulId str2_id; + private MulId str1_id; + private MulId str2_id; - private MulId coll1_id; + private MulId coll1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { MulIdTestEntity.class, SetRefCollEntityMulId.class }; - } + return new Class[] {MulIdTestEntity.class, SetRefCollEntityMulId.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - str1_id = new MulId(1, 2); - str2_id = new MulId(3, 4); + str1_id = new MulId( 1, 2 ); + str2_id = new MulId( 3, 4 ); - coll1_id = new MulId(5, 6); + coll1_id = new MulId( 5, 6 ); - MulIdTestEntity str1 = new MulIdTestEntity(str1_id.getId1(), str1_id.getId2(), "str1"); - MulIdTestEntity str2 = new MulIdTestEntity(str2_id.getId1(), str2_id.getId2(), "str2"); + MulIdTestEntity str1 = new MulIdTestEntity( str1_id.getId1(), str1_id.getId2(), "str1" ); + MulIdTestEntity str2 = new MulIdTestEntity( str2_id.getId1(), str2_id.getId2(), "str2" ); - SetRefCollEntityMulId coll1 = new SetRefCollEntityMulId(coll1_id.getId1(), coll1_id.getId2(), "coll1"); + SetRefCollEntityMulId coll1 = new SetRefCollEntityMulId( coll1_id.getId1(), coll1_id.getId2(), "coll1" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(str1); - em.persist(str2); + em.persist( str1 ); + em.persist( str2 ); - coll1.setCollection(new HashSet()); - coll1.getCollection().add(str1); - em.persist(coll1); + coll1.setCollection( new HashSet() ); + coll1.getCollection().add( str1 ); + em.persist( coll1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - str2 = em.find(MulIdTestEntity.class, str2_id); - coll1 = em.find(SetRefCollEntityMulId.class, coll1_id); + str2 = em.find( MulIdTestEntity.class, str2_id ); + coll1 = em.find( SetRefCollEntityMulId.class, coll1_id ); - coll1.getCollection().add(str2); + coll1.getCollection().add( str2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - str1 = em.find(MulIdTestEntity.class, str1_id); - coll1 = em.find(SetRefCollEntityMulId.class, coll1_id); + str1 = em.find( MulIdTestEntity.class, str1_id ); + coll1 = em.find( SetRefCollEntityMulId.class, coll1_id ); - coll1.getCollection().remove(str1); + coll1.getCollection().remove( str1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); + // Revision 4 + em.getTransaction().begin(); - coll1 = em.find(SetRefCollEntityMulId.class, coll1_id); + coll1 = em.find( SetRefCollEntityMulId.class, coll1_id ); - coll1.getCollection().clear(); + coll1.getCollection().clear(); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3, 4).equals(getAuditReader().getRevisions(SetRefCollEntityMulId.class, coll1_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3, 4 ).equals( + getAuditReader().getRevisions( + SetRefCollEntityMulId.class, + coll1_id + ) + ); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(MulIdTestEntity.class, str1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(MulIdTestEntity.class, str2_id)); - } + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( MulIdTestEntity.class, str1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( MulIdTestEntity.class, str2_id ) ); + } - @Test - public void testHistoryOfColl1() { - MulIdTestEntity str1 = getEntityManager().find(MulIdTestEntity.class, str1_id); - MulIdTestEntity str2 = getEntityManager().find(MulIdTestEntity.class, str2_id); + @Test + public void testHistoryOfColl1() { + MulIdTestEntity str1 = getEntityManager().find( MulIdTestEntity.class, str1_id ); + MulIdTestEntity str2 = getEntityManager().find( MulIdTestEntity.class, str2_id ); - SetRefCollEntityMulId rev1 = getAuditReader().find(SetRefCollEntityMulId.class, coll1_id, 1); - SetRefCollEntityMulId rev2 = getAuditReader().find(SetRefCollEntityMulId.class, coll1_id, 2); - SetRefCollEntityMulId rev3 = getAuditReader().find(SetRefCollEntityMulId.class, coll1_id, 3); - SetRefCollEntityMulId rev4 = getAuditReader().find(SetRefCollEntityMulId.class, coll1_id, 4); + SetRefCollEntityMulId rev1 = getAuditReader().find( SetRefCollEntityMulId.class, coll1_id, 1 ); + SetRefCollEntityMulId rev2 = getAuditReader().find( SetRefCollEntityMulId.class, coll1_id, 2 ); + SetRefCollEntityMulId rev3 = getAuditReader().find( SetRefCollEntityMulId.class, coll1_id, 3 ); + SetRefCollEntityMulId rev4 = getAuditReader().find( SetRefCollEntityMulId.class, coll1_id, 4 ); - assert rev1.getCollection().equals(TestTools.makeSet(str1)); - assert rev2.getCollection().equals(TestTools.makeSet(str1, str2)); - assert rev3.getCollection().equals(TestTools.makeSet(str2)); - assert rev4.getCollection().equals(TestTools.makeSet()); + assert rev1.getCollection().equals( TestTools.makeSet( str1 ) ); + assert rev2.getCollection().equals( TestTools.makeSet( str1, str2 ) ); + assert rev3.getCollection().equals( TestTools.makeSet( str2 ) ); + assert rev4.getCollection().equals( TestTools.makeSet() ); - assert "coll1".equals(rev1.getData()); - assert "coll1".equals(rev2.getData()); - assert "coll1".equals(rev3.getData()); - assert "coll1".equals(rev4.getData()); - } + assert "coll1".equals( rev1.getData() ); + assert "coll1".equals( rev2.getData() ); + assert "coll1".equals( rev3.getData() ); + assert "coll1".equals( rev4.getData() ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicJoinColumnSet.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicJoinColumnSet.java index 6864cc4a82..e2edb32eb7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicJoinColumnSet.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/BasicJoinColumnSet.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.onetomany.detached; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.HashSet; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -35,105 +33,112 @@ import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.onetomany.detached.SetJoinColumnRefCollEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BasicJoinColumnSet extends BaseEnversJPAFunctionalTestCase { - private Integer str1_id; - private Integer str2_id; + private Integer str1_id; + private Integer str2_id; - private Integer coll1_id; + private Integer coll1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class, SetJoinColumnRefCollEntity.class }; - } + return new Class[] {StrTestEntity.class, SetJoinColumnRefCollEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - StrTestEntity str1 = new StrTestEntity("str1"); - StrTestEntity str2 = new StrTestEntity("str2"); + StrTestEntity str1 = new StrTestEntity( "str1" ); + StrTestEntity str2 = new StrTestEntity( "str2" ); - SetJoinColumnRefCollEntity coll1 = new SetJoinColumnRefCollEntity(3, "coll1"); + SetJoinColumnRefCollEntity coll1 = new SetJoinColumnRefCollEntity( 3, "coll1" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(str1); - em.persist(str2); + em.persist( str1 ); + em.persist( str2 ); - coll1.setCollection(new HashSet()); - coll1.getCollection().add(str1); - em.persist(coll1); + coll1.setCollection( new HashSet() ); + coll1.getCollection().add( str1 ); + em.persist( coll1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - str2 = em.find(StrTestEntity.class, str2.getId()); - coll1 = em.find(SetJoinColumnRefCollEntity.class, coll1.getId()); + str2 = em.find( StrTestEntity.class, str2.getId() ); + coll1 = em.find( SetJoinColumnRefCollEntity.class, coll1.getId() ); - coll1.getCollection().add(str2); + coll1.getCollection().add( str2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - str1 = em.find(StrTestEntity.class, str1.getId()); - coll1 = em.find(SetJoinColumnRefCollEntity.class, coll1.getId()); + str1 = em.find( StrTestEntity.class, str1.getId() ); + coll1 = em.find( SetJoinColumnRefCollEntity.class, coll1.getId() ); - coll1.getCollection().remove(str1); + coll1.getCollection().remove( str1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); + // Revision 4 + em.getTransaction().begin(); - coll1 = em.find(SetJoinColumnRefCollEntity.class, coll1.getId()); + coll1 = em.find( SetJoinColumnRefCollEntity.class, coll1.getId() ); - coll1.getCollection().clear(); + coll1.getCollection().clear(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - str1_id = str1.getId(); - str2_id = str2.getId(); + str1_id = str1.getId(); + str2_id = str2.getId(); - coll1_id = coll1.getId(); - } + coll1_id = coll1.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3, 4).equals(getAuditReader().getRevisions(SetJoinColumnRefCollEntity.class, coll1_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3, 4 ).equals( + getAuditReader().getRevisions( + SetJoinColumnRefCollEntity.class, + coll1_id + ) + ); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestEntity.class, str1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestEntity.class, str2_id)); - } + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestEntity.class, str1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestEntity.class, str2_id ) ); + } - @Test - public void testHistoryOfColl1() { - StrTestEntity str1 = getEntityManager().find(StrTestEntity.class, str1_id); - StrTestEntity str2 = getEntityManager().find(StrTestEntity.class, str2_id); + @Test + public void testHistoryOfColl1() { + StrTestEntity str1 = getEntityManager().find( StrTestEntity.class, str1_id ); + StrTestEntity str2 = getEntityManager().find( StrTestEntity.class, str2_id ); - SetJoinColumnRefCollEntity rev1 = getAuditReader().find(SetJoinColumnRefCollEntity.class, coll1_id, 1); - SetJoinColumnRefCollEntity rev2 = getAuditReader().find(SetJoinColumnRefCollEntity.class, coll1_id, 2); - SetJoinColumnRefCollEntity rev3 = getAuditReader().find(SetJoinColumnRefCollEntity.class, coll1_id, 3); - SetJoinColumnRefCollEntity rev4 = getAuditReader().find(SetJoinColumnRefCollEntity.class, coll1_id, 4); + SetJoinColumnRefCollEntity rev1 = getAuditReader().find( SetJoinColumnRefCollEntity.class, coll1_id, 1 ); + SetJoinColumnRefCollEntity rev2 = getAuditReader().find( SetJoinColumnRefCollEntity.class, coll1_id, 2 ); + SetJoinColumnRefCollEntity rev3 = getAuditReader().find( SetJoinColumnRefCollEntity.class, coll1_id, 3 ); + SetJoinColumnRefCollEntity rev4 = getAuditReader().find( SetJoinColumnRefCollEntity.class, coll1_id, 4 ); - assert rev1.getCollection().equals(TestTools.makeSet(str1)); - assert rev2.getCollection().equals(TestTools.makeSet(str1, str2)); - assert rev3.getCollection().equals(TestTools.makeSet(str2)); - assert rev4.getCollection().equals(TestTools.makeSet()); + assert rev1.getCollection().equals( TestTools.makeSet( str1 ) ); + assert rev2.getCollection().equals( TestTools.makeSet( str1, str2 ) ); + assert rev3.getCollection().equals( TestTools.makeSet( str2 ) ); + assert rev4.getCollection().equals( TestTools.makeSet() ); - assert "coll1".equals(rev1.getData()); - assert "coll1".equals(rev2.getData()); - assert "coll1".equals(rev3.getData()); - assert "coll1".equals(rev4.getData()); - } + assert "coll1".equals( rev1.getData() ); + assert "coll1".equals( rev2.getData() ); + assert "coll1".equals( rev3.getData() ); + assert "coll1".equals( rev4.getData() ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/DataChangesDetachedSet.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/DataChangesDetachedSet.java index 0f7645de26..6b1ddccf32 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/DataChangesDetachedSet.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/DataChangesDetachedSet.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.onetomany.detached; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.HashSet; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -35,74 +33,76 @@ import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.onetomany.detached.SetRefCollEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ -public class DataChangesDetachedSet extends BaseEnversJPAFunctionalTestCase { - private Integer str1_id; +public class DataChangesDetachedSet extends BaseEnversJPAFunctionalTestCase { + private Integer str1_id; - private Integer coll1_id; + private Integer coll1_id; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{StrTestEntity.class, SetRefCollEntity.class}; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {StrTestEntity.class, SetRefCollEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - StrTestEntity str1 = new StrTestEntity("str1"); + StrTestEntity str1 = new StrTestEntity( "str1" ); - SetRefCollEntity coll1 = new SetRefCollEntity(3, "coll1"); + SetRefCollEntity coll1 = new SetRefCollEntity( 3, "coll1" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(str1); + em.persist( str1 ); - coll1.setCollection(new HashSet()); - em.persist(coll1); + coll1.setCollection( new HashSet() ); + em.persist( coll1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - str1 = em.find(StrTestEntity.class, str1.getId()); - coll1 = em.find(SetRefCollEntity.class, coll1.getId()); + str1 = em.find( StrTestEntity.class, str1.getId() ); + coll1 = em.find( SetRefCollEntity.class, coll1.getId() ); - coll1.getCollection().add(str1); - coll1.setData("coll2"); + coll1.getCollection().add( str1 ); + coll1.setData( "coll2" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - str1_id = str1.getId(); + str1_id = str1.getId(); - coll1_id = coll1.getId(); - } + coll1_id = coll1.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(SetRefCollEntity.class, coll1_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( SetRefCollEntity.class, coll1_id ) ); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestEntity.class, str1_id)); - } + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestEntity.class, str1_id ) ); + } - @Test - public void testHistoryOfColl1() { - StrTestEntity str1 = getEntityManager().find(StrTestEntity.class, str1_id); + @Test + public void testHistoryOfColl1() { + StrTestEntity str1 = getEntityManager().find( StrTestEntity.class, str1_id ); - SetRefCollEntity rev1 = getAuditReader().find(SetRefCollEntity.class, coll1_id, 1); - SetRefCollEntity rev2 = getAuditReader().find(SetRefCollEntity.class, coll1_id, 2); + SetRefCollEntity rev1 = getAuditReader().find( SetRefCollEntity.class, coll1_id, 1 ); + SetRefCollEntity rev2 = getAuditReader().find( SetRefCollEntity.class, coll1_id, 2 ); - assert rev1.getCollection().equals(TestTools.makeSet()); - assert rev2.getCollection().equals(TestTools.makeSet(str1)); + assert rev1.getCollection().equals( TestTools.makeSet() ); + assert rev2.getCollection().equals( TestTools.makeSet( str1 ) ); - assert "coll1".equals(rev1.getData()); - assert "coll2".equals(rev2.getData()); - } + assert "coll1".equals( rev1.getData() ); + assert "coll2".equals( rev2.getData() ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/DetachedTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/DetachedTest.java index 10e7c65af7..e8d508ef1e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/DetachedTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/DetachedTest.java @@ -2,14 +2,15 @@ package org.hibernate.envers.test.integration.onetomany.detached; import java.util.Arrays; -import junit.framework.Assert; -import org.junit.Test; - import org.hibernate.Session; import org.hibernate.envers.test.BaseEnversFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.onetomany.detached.ListRefCollEntity; + +import org.junit.Test; +import junit.framework.Assert; + import org.hibernate.testing.TestForIssue; /** @@ -21,7 +22,7 @@ public class DetachedTest extends BaseEnversFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ListRefCollEntity.class, StrTestEntity.class }; + return new Class[] {ListRefCollEntity.class, StrTestEntity.class}; } @Test @@ -56,7 +57,12 @@ public class DetachedTest extends BaseEnversFunctionalTestCase { @Test public void testRevisionsCounts() { - Assert.assertEquals( Arrays.asList( 1, 2 ), getAuditReader().getRevisions( ListRefCollEntity.class, parentId ) ); + Assert.assertEquals( + Arrays.asList( 1, 2 ), getAuditReader().getRevisions( + ListRefCollEntity.class, + parentId + ) + ); Assert.assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( StrTestEntity.class, childId ) ); } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/DoubleDetachedSet.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/DoubleDetachedSet.java index f3e8a324cd..f819ca2094 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/DoubleDetachedSet.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/DoubleDetachedSet.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.onetomany.detached; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.HashSet; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -35,98 +33,105 @@ import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.onetomany.detached.DoubleSetRefCollEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class DoubleDetachedSet extends BaseEnversJPAFunctionalTestCase { - private Integer str1_id; - private Integer str2_id; + private Integer str1_id; + private Integer str2_id; - private Integer coll1_id; + private Integer coll1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class, DoubleSetRefCollEntity.class }; - } + return new Class[] {StrTestEntity.class, DoubleSetRefCollEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - StrTestEntity str1 = new StrTestEntity("str1"); - StrTestEntity str2 = new StrTestEntity("str2"); + StrTestEntity str1 = new StrTestEntity( "str1" ); + StrTestEntity str2 = new StrTestEntity( "str2" ); - DoubleSetRefCollEntity coll1 = new DoubleSetRefCollEntity(3, "coll1"); + DoubleSetRefCollEntity coll1 = new DoubleSetRefCollEntity( 3, "coll1" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(str1); - em.persist(str2); + em.persist( str1 ); + em.persist( str2 ); - coll1.setCollection(new HashSet()); - coll1.getCollection().add(str1); - em.persist(coll1); + coll1.setCollection( new HashSet() ); + coll1.getCollection().add( str1 ); + em.persist( coll1 ); - coll1.setCollection2(new HashSet()); - coll1.getCollection2().add(str2); - em.persist(coll1); + coll1.setCollection2( new HashSet() ); + coll1.getCollection2().add( str2 ); + em.persist( coll1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - str2 = em.find(StrTestEntity.class, str2.getId()); - coll1 = em.find(DoubleSetRefCollEntity.class, coll1.getId()); + str2 = em.find( StrTestEntity.class, str2.getId() ); + coll1 = em.find( DoubleSetRefCollEntity.class, coll1.getId() ); - coll1.getCollection().add(str2); + coll1.getCollection().add( str2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - str1 = em.find(StrTestEntity.class, str1.getId()); - coll1 = em.find(DoubleSetRefCollEntity.class, coll1.getId()); + str1 = em.find( StrTestEntity.class, str1.getId() ); + coll1 = em.find( DoubleSetRefCollEntity.class, coll1.getId() ); - coll1.getCollection().remove(str1); - coll1.getCollection2().add(str1); + coll1.getCollection().remove( str1 ); + coll1.getCollection2().add( str1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - str1_id = str1.getId(); - str2_id = str2.getId(); + str1_id = str1.getId(); + str2_id = str2.getId(); - coll1_id = coll1.getId(); - } + coll1_id = coll1.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(DoubleSetRefCollEntity.class, coll1_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( + getAuditReader().getRevisions( + DoubleSetRefCollEntity.class, + coll1_id + ) + ); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestEntity.class, str1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(StrTestEntity.class, str2_id)); - } + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestEntity.class, str1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( StrTestEntity.class, str2_id ) ); + } - @Test - public void testHistoryOfColl1() { - StrTestEntity str1 = getEntityManager().find(StrTestEntity.class, str1_id); - StrTestEntity str2 = getEntityManager().find(StrTestEntity.class, str2_id); + @Test + public void testHistoryOfColl1() { + StrTestEntity str1 = getEntityManager().find( StrTestEntity.class, str1_id ); + StrTestEntity str2 = getEntityManager().find( StrTestEntity.class, str2_id ); - DoubleSetRefCollEntity rev1 = getAuditReader().find(DoubleSetRefCollEntity.class, coll1_id, 1); - DoubleSetRefCollEntity rev2 = getAuditReader().find(DoubleSetRefCollEntity.class, coll1_id, 2); - DoubleSetRefCollEntity rev3 = getAuditReader().find(DoubleSetRefCollEntity.class, coll1_id, 3); + DoubleSetRefCollEntity rev1 = getAuditReader().find( DoubleSetRefCollEntity.class, coll1_id, 1 ); + DoubleSetRefCollEntity rev2 = getAuditReader().find( DoubleSetRefCollEntity.class, coll1_id, 2 ); + DoubleSetRefCollEntity rev3 = getAuditReader().find( DoubleSetRefCollEntity.class, coll1_id, 3 ); - assert rev1.getCollection().equals(TestTools.makeSet(str1)); - assert rev2.getCollection().equals(TestTools.makeSet(str1, str2)); - assert rev3.getCollection().equals(TestTools.makeSet(str2)); + assert rev1.getCollection().equals( TestTools.makeSet( str1 ) ); + assert rev2.getCollection().equals( TestTools.makeSet( str1, str2 ) ); + assert rev3.getCollection().equals( TestTools.makeSet( str2 ) ); - assert rev1.getCollection2().equals(TestTools.makeSet(str2)); - assert rev2.getCollection2().equals(TestTools.makeSet(str2)); - assert rev3.getCollection2().equals(TestTools.makeSet(str1, str2)); - } + assert rev1.getCollection2().equals( TestTools.makeSet( str2 ) ); + assert rev2.getCollection2().equals( TestTools.makeSet( str2 ) ); + assert rev3.getCollection2().equals( TestTools.makeSet( str1, str2 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/DoubleJoinColumnBidirectionalList.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/DoubleJoinColumnBidirectionalList.java index ce923fdfbd..a25e76827b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/DoubleJoinColumnBidirectionalList.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/DoubleJoinColumnBidirectionalList.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.onetomany.detached; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -34,6 +32,8 @@ import org.hibernate.envers.test.entities.onetomany.detached.DoubleListJoinColum import org.hibernate.envers.test.entities.onetomany.detached.DoubleListJoinColumnBidirectionalRefEdEntity2; import org.hibernate.envers.test.entities.onetomany.detached.DoubleListJoinColumnBidirectionalRefIngEntity; +import org.junit.Test; + import static org.hibernate.envers.test.tools.TestTools.checkList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -41,16 +41,17 @@ import static org.junit.Assert.assertTrue; /** * Test for a double "fake" bidirectional mapping where one side uses @OneToMany+@JoinColumn * (and thus owns the relation), and the other uses a @ManyToOne(insertable=false, updatable=false). + * * @author Adam Warski (adam at warski dot org) */ public class DoubleJoinColumnBidirectionalList extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_1_id; - private Integer ed2_1_id; - private Integer ed1_2_id; - private Integer ed2_2_id; + private Integer ed1_1_id; + private Integer ed2_1_id; + private Integer ed1_2_id; + private Integer ed2_2_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { @@ -59,247 +60,445 @@ public class DoubleJoinColumnBidirectionalList extends BaseEnversJPAFunctionalTe DoubleListJoinColumnBidirectionalRefEdEntity1.class, DoubleListJoinColumnBidirectionalRefEdEntity2.class }; - } + } - @Test - @Priority(10) - public void createData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void createData() { + EntityManager em = getEntityManager(); - DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_1 = new DoubleListJoinColumnBidirectionalRefEdEntity1("ed1_1", null); - DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_2 = new DoubleListJoinColumnBidirectionalRefEdEntity1("ed1_2", null); + DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_1 = new DoubleListJoinColumnBidirectionalRefEdEntity1( + "ed1_1", + null + ); + DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_2 = new DoubleListJoinColumnBidirectionalRefEdEntity1( + "ed1_2", + null + ); - DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_1 = new DoubleListJoinColumnBidirectionalRefEdEntity2("ed2_1", null); - DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_2 = new DoubleListJoinColumnBidirectionalRefEdEntity2("ed2_2", null); + DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_1 = new DoubleListJoinColumnBidirectionalRefEdEntity2( + "ed2_1", + null + ); + DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_2 = new DoubleListJoinColumnBidirectionalRefEdEntity2( + "ed2_2", + null + ); - DoubleListJoinColumnBidirectionalRefIngEntity ing1 = new DoubleListJoinColumnBidirectionalRefIngEntity("coll1"); - DoubleListJoinColumnBidirectionalRefIngEntity ing2 = new DoubleListJoinColumnBidirectionalRefIngEntity("coll2"); + DoubleListJoinColumnBidirectionalRefIngEntity ing1 = new DoubleListJoinColumnBidirectionalRefIngEntity( "coll1" ); + DoubleListJoinColumnBidirectionalRefIngEntity ing2 = new DoubleListJoinColumnBidirectionalRefIngEntity( "coll2" ); - // Revision 1 (ing1: ed1_1, ed2_1, ing2: ed1_2, ed2_2) - em.getTransaction().begin(); + // Revision 1 (ing1: ed1_1, ed2_1, ing2: ed1_2, ed2_2) + em.getTransaction().begin(); - ing1.getReferences1().add(ed1_1); - ing1.getReferences2().add(ed2_1); + ing1.getReferences1().add( ed1_1 ); + ing1.getReferences2().add( ed2_1 ); - ing2.getReferences1().add(ed1_2); - ing2.getReferences2().add(ed2_2); + ing2.getReferences1().add( ed1_2 ); + ing2.getReferences2().add( ed2_2 ); - em.persist(ed1_1); - em.persist(ed1_2); - em.persist(ed2_1); - em.persist(ed2_2); - em.persist(ing1); - em.persist(ing2); + em.persist( ed1_1 ); + em.persist( ed1_2 ); + em.persist( ed2_1 ); + em.persist( ed2_2 ); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (ing1: ed1_1, ed1_2, ed2_1, ed2_2) - em.getTransaction().begin(); + // Revision 2 (ing1: ed1_1, ed1_2, ed2_1, ed2_2) + em.getTransaction().begin(); - ing1 = em.find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1.getId()); - ing2 = em.find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2.getId()); - ed1_1 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1.getId()); - ed1_2 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2.getId()); - ed2_1 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1.getId()); - ed2_2 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2.getId()); + ing1 = em.find( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1.getId() ); + ing2 = em.find( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2.getId() ); + ed1_1 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1.getId() ); + ed1_2 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2.getId() ); + ed2_1 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1.getId() ); + ed2_2 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2.getId() ); - ing2.getReferences1().clear(); - ing2.getReferences2().clear(); + ing2.getReferences1().clear(); + ing2.getReferences2().clear(); - ing1.getReferences1().add(ed1_2); - ing1.getReferences2().add(ed2_2); + ing1.getReferences1().add( ed1_2 ); + ing1.getReferences2().add( ed2_2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 3 (ing1: ed1_1, ed1_2, ed2_1, ed2_2) - em.getTransaction().begin(); + // Revision 3 (ing1: ed1_1, ed1_2, ed2_1, ed2_2) + em.getTransaction().begin(); - ing1 = em.find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1.getId()); - ing2 = em.find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2.getId()); - ed1_1 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1.getId()); - ed1_2 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2.getId()); - ed2_1 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1.getId()); - ed2_2 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2.getId()); + ing1 = em.find( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1.getId() ); + ing2 = em.find( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2.getId() ); + ed1_1 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1.getId() ); + ed1_2 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2.getId() ); + ed2_1 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1.getId() ); + ed2_2 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2.getId() ); - ed1_1.setData("ed1_1 bis"); - ed2_2.setData("ed2_2 bis"); + ed1_1.setData( "ed1_1 bis" ); + ed2_2.setData( "ed2_2 bis" ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 4 (ing1: ed2_2, ing2: ed2_1, ed1_1, ed1_2) - em.getTransaction().begin(); + // Revision 4 (ing1: ed2_2, ing2: ed2_1, ed1_1, ed1_2) + em.getTransaction().begin(); - ing1 = em.find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1.getId()); - ing2 = em.find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2.getId()); - ed1_1 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1.getId()); - ed1_2 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2.getId()); - ed2_1 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1.getId()); - ed2_2 = em.find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2.getId()); + ing1 = em.find( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1.getId() ); + ing2 = em.find( DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2.getId() ); + ed1_1 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1.getId() ); + ed1_2 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2.getId() ); + ed2_1 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1.getId() ); + ed2_2 = em.find( DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2.getId() ); - ing1.getReferences1().clear(); - ing2.getReferences1().add(ed1_1); - ing2.getReferences1().add(ed1_2); + ing1.getReferences1().clear(); + ing2.getReferences1().add( ed1_1 ); + ing2.getReferences1().add( ed1_2 ); - ing1.getReferences2().remove(ed2_1); - ing2.getReferences2().add(ed2_1); + ing1.getReferences2().remove( ed2_1 ); + ing2.getReferences2().add( ed2_1 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // + // - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); - ed1_1_id = ed1_1.getId(); - ed1_2_id = ed1_2.getId(); - ed2_1_id = ed2_1.getId(); - ed2_2_id = ed2_2.getId(); - } + ed1_1_id = ed1_1.getId(); + ed1_2_id = ed1_2.getId(); + ed2_1_id = ed2_1.getId(); + ed2_2_id = ed2_2.getId(); + } - @Test - public void testRevisionsCounts() { - assertEquals(Arrays.asList(1, 2, 4), getAuditReader().getRevisions(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1_id)); - assertEquals(Arrays.asList(1, 2, 4), getAuditReader().getRevisions(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2_id)); + @Test + public void testRevisionsCounts() { + assertEquals( + Arrays.asList( 1, 2, 4 ), getAuditReader().getRevisions( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing1_id + ) + ); + assertEquals( + Arrays.asList( 1, 2, 4 ), getAuditReader().getRevisions( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing2_id + ) + ); - assertEquals(Arrays.asList(1, 3, 4), getAuditReader().getRevisions(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1_id)); - assertEquals(Arrays.asList(1, 2, 4), getAuditReader().getRevisions(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2_id)); + assertEquals( + Arrays.asList( 1, 3, 4 ), getAuditReader().getRevisions( + DoubleListJoinColumnBidirectionalRefEdEntity1.class, + ed1_1_id + ) + ); + assertEquals( + Arrays.asList( 1, 2, 4 ), getAuditReader().getRevisions( + DoubleListJoinColumnBidirectionalRefEdEntity1.class, + ed1_2_id + ) + ); - assertEquals(Arrays.asList(1, 4), getAuditReader().getRevisions(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1_id)); - assertEquals(Arrays.asList(1, 2, 3), getAuditReader().getRevisions(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2_id)); - } + assertEquals( + Arrays.asList( 1, 4 ), getAuditReader().getRevisions( + DoubleListJoinColumnBidirectionalRefEdEntity2.class, + ed2_1_id + ) + ); + assertEquals( + Arrays.asList( 1, 2, 3 ), getAuditReader().getRevisions( + DoubleListJoinColumnBidirectionalRefEdEntity2.class, + ed2_2_id + ) + ); + } - @Test - public void testHistoryOfIng1() { - DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_1_fromRev1 = new DoubleListJoinColumnBidirectionalRefEdEntity1(ed1_1_id, "ed1_1", null); - DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_1_fromRev3 = new DoubleListJoinColumnBidirectionalRefEdEntity1(ed1_1_id, "ed1_1 bis", null); - DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_2 = getEntityManager().find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2_id); - DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_1 = getEntityManager().find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1_id); - DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_2_fromRev1 = new DoubleListJoinColumnBidirectionalRefEdEntity2(ed2_2_id, "ed2_2", null); - DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_2_fromRev3 = new DoubleListJoinColumnBidirectionalRefEdEntity2(ed2_2_id, "ed2_2 bis", null); + @Test + public void testHistoryOfIng1() { + DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_1_fromRev1 = new DoubleListJoinColumnBidirectionalRefEdEntity1( + ed1_1_id, + "ed1_1", + null + ); + DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_1_fromRev3 = new DoubleListJoinColumnBidirectionalRefEdEntity1( + ed1_1_id, + "ed1_1 bis", + null + ); + DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_2 = getEntityManager().find( + DoubleListJoinColumnBidirectionalRefEdEntity1.class, + ed1_2_id + ); + DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_1 = getEntityManager().find( + DoubleListJoinColumnBidirectionalRefEdEntity2.class, + ed2_1_id + ); + DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_2_fromRev1 = new DoubleListJoinColumnBidirectionalRefEdEntity2( + ed2_2_id, + "ed2_2", + null + ); + DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_2_fromRev3 = new DoubleListJoinColumnBidirectionalRefEdEntity2( + ed2_2_id, + "ed2_2 bis", + null + ); - DoubleListJoinColumnBidirectionalRefIngEntity rev1 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1_id, 1); - DoubleListJoinColumnBidirectionalRefIngEntity rev2 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1_id, 2); - DoubleListJoinColumnBidirectionalRefIngEntity rev3 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1_id, 3); - DoubleListJoinColumnBidirectionalRefIngEntity rev4 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1_id, 4); + DoubleListJoinColumnBidirectionalRefIngEntity rev1 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing1_id, + 1 + ); + DoubleListJoinColumnBidirectionalRefIngEntity rev2 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing1_id, + 2 + ); + DoubleListJoinColumnBidirectionalRefIngEntity rev3 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing1_id, + 3 + ); + DoubleListJoinColumnBidirectionalRefIngEntity rev4 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing1_id, + 4 + ); - assertTrue(checkList(rev1.getReferences1(), ed1_1_fromRev1)); - assertTrue(checkList(rev2.getReferences1(), ed1_1_fromRev1, ed1_2)); - assertTrue(checkList(rev3.getReferences1(), ed1_1_fromRev3, ed1_2)); - assertTrue(checkList(rev4.getReferences1())); + assertTrue( checkList( rev1.getReferences1(), ed1_1_fromRev1 ) ); + assertTrue( checkList( rev2.getReferences1(), ed1_1_fromRev1, ed1_2 ) ); + assertTrue( checkList( rev3.getReferences1(), ed1_1_fromRev3, ed1_2 ) ); + assertTrue( checkList( rev4.getReferences1() ) ); - assertTrue(checkList(rev1.getReferences2(), ed2_1)); - assertTrue(checkList(rev2.getReferences2(), ed2_1, ed2_2_fromRev1)); - assertTrue(checkList(rev3.getReferences2(), ed2_1, ed2_2_fromRev3)); - assertTrue(checkList(rev4.getReferences2(), ed2_2_fromRev3)); - } + assertTrue( checkList( rev1.getReferences2(), ed2_1 ) ); + assertTrue( checkList( rev2.getReferences2(), ed2_1, ed2_2_fromRev1 ) ); + assertTrue( checkList( rev3.getReferences2(), ed2_1, ed2_2_fromRev3 ) ); + assertTrue( checkList( rev4.getReferences2(), ed2_2_fromRev3 ) ); + } - @Test - public void testHistoryOfIng2() { - DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_1_fromRev3 = new DoubleListJoinColumnBidirectionalRefEdEntity1(ed1_1_id, "ed1_1 bis", null); - DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_2 = getEntityManager().find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2_id); - DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_1 = getEntityManager().find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1_id); - DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_2_fromRev1 = new DoubleListJoinColumnBidirectionalRefEdEntity2(ed2_2_id, "ed2_2", null); + @Test + public void testHistoryOfIng2() { + DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_1_fromRev3 = new DoubleListJoinColumnBidirectionalRefEdEntity1( + ed1_1_id, + "ed1_1 bis", + null + ); + DoubleListJoinColumnBidirectionalRefEdEntity1 ed1_2 = getEntityManager().find( + DoubleListJoinColumnBidirectionalRefEdEntity1.class, + ed1_2_id + ); + DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_1 = getEntityManager().find( + DoubleListJoinColumnBidirectionalRefEdEntity2.class, + ed2_1_id + ); + DoubleListJoinColumnBidirectionalRefEdEntity2 ed2_2_fromRev1 = new DoubleListJoinColumnBidirectionalRefEdEntity2( + ed2_2_id, + "ed2_2", + null + ); - DoubleListJoinColumnBidirectionalRefIngEntity rev1 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2_id, 1); - DoubleListJoinColumnBidirectionalRefIngEntity rev2 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2_id, 2); - DoubleListJoinColumnBidirectionalRefIngEntity rev3 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2_id, 3); - DoubleListJoinColumnBidirectionalRefIngEntity rev4 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2_id, 4); + DoubleListJoinColumnBidirectionalRefIngEntity rev1 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing2_id, + 1 + ); + DoubleListJoinColumnBidirectionalRefIngEntity rev2 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing2_id, + 2 + ); + DoubleListJoinColumnBidirectionalRefIngEntity rev3 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing2_id, + 3 + ); + DoubleListJoinColumnBidirectionalRefIngEntity rev4 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing2_id, + 4 + ); - assertTrue(checkList(rev1.getReferences1(), ed1_2)); - assertTrue(checkList(rev2.getReferences1())); - assertTrue(checkList(rev3.getReferences1())); - assertTrue(checkList(rev4.getReferences1(), ed1_1_fromRev3, ed1_2)); + assertTrue( checkList( rev1.getReferences1(), ed1_2 ) ); + assertTrue( checkList( rev2.getReferences1() ) ); + assertTrue( checkList( rev3.getReferences1() ) ); + assertTrue( checkList( rev4.getReferences1(), ed1_1_fromRev3, ed1_2 ) ); - assertTrue(checkList(rev1.getReferences2(), ed2_2_fromRev1)); - assertTrue(checkList(rev2.getReferences2())); - assertTrue(checkList(rev3.getReferences2())); - assertTrue(checkList(rev4.getReferences2(), ed2_1)); - } + assertTrue( checkList( rev1.getReferences2(), ed2_2_fromRev1 ) ); + assertTrue( checkList( rev2.getReferences2() ) ); + assertTrue( checkList( rev3.getReferences2() ) ); + assertTrue( checkList( rev4.getReferences2(), ed2_1 ) ); + } - @Test - public void testHistoryOfEd1_1() { - DoubleListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1_id); - DoubleListJoinColumnBidirectionalRefIngEntity ing2 = getEntityManager().find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2_id); + @Test + public void testHistoryOfEd1_1() { + DoubleListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing1_id + ); + DoubleListJoinColumnBidirectionalRefIngEntity ing2 = getEntityManager().find( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing2_id + ); - DoubleListJoinColumnBidirectionalRefEdEntity1 rev1 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1_id, 1); - DoubleListJoinColumnBidirectionalRefEdEntity1 rev2 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1_id, 2); - DoubleListJoinColumnBidirectionalRefEdEntity1 rev3 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1_id, 3); - DoubleListJoinColumnBidirectionalRefEdEntity1 rev4 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_1_id, 4); + DoubleListJoinColumnBidirectionalRefEdEntity1 rev1 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefEdEntity1.class, + ed1_1_id, + 1 + ); + DoubleListJoinColumnBidirectionalRefEdEntity1 rev2 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefEdEntity1.class, + ed1_1_id, + 2 + ); + DoubleListJoinColumnBidirectionalRefEdEntity1 rev3 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefEdEntity1.class, + ed1_1_id, + 3 + ); + DoubleListJoinColumnBidirectionalRefEdEntity1 rev4 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefEdEntity1.class, + ed1_1_id, + 4 + ); - assertTrue(rev1.getOwner().equals(ing1)); - assertTrue(rev2.getOwner().equals(ing1)); - assertTrue(rev3.getOwner().equals(ing1)); - assertTrue(rev4.getOwner().equals(ing2)); + assertTrue( rev1.getOwner().equals( ing1 ) ); + assertTrue( rev2.getOwner().equals( ing1 ) ); + assertTrue( rev3.getOwner().equals( ing1 ) ); + assertTrue( rev4.getOwner().equals( ing2 ) ); - assertEquals(rev1.getData(), "ed1_1"); - assertEquals(rev2.getData(), "ed1_1"); - assertEquals(rev3.getData(), "ed1_1 bis"); - assertEquals(rev4.getData(), "ed1_1 bis"); - } + assertEquals( rev1.getData(), "ed1_1" ); + assertEquals( rev2.getData(), "ed1_1" ); + assertEquals( rev3.getData(), "ed1_1 bis" ); + assertEquals( rev4.getData(), "ed1_1 bis" ); + } - @Test - public void testHistoryOfEd1_2() { - DoubleListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1_id); - DoubleListJoinColumnBidirectionalRefIngEntity ing2 = getEntityManager().find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2_id); + @Test + public void testHistoryOfEd1_2() { + DoubleListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing1_id + ); + DoubleListJoinColumnBidirectionalRefIngEntity ing2 = getEntityManager().find( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing2_id + ); - DoubleListJoinColumnBidirectionalRefEdEntity1 rev1 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2_id, 1); - DoubleListJoinColumnBidirectionalRefEdEntity1 rev2 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2_id, 2); - DoubleListJoinColumnBidirectionalRefEdEntity1 rev3 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2_id, 3); - DoubleListJoinColumnBidirectionalRefEdEntity1 rev4 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefEdEntity1.class, ed1_2_id, 4); + DoubleListJoinColumnBidirectionalRefEdEntity1 rev1 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefEdEntity1.class, + ed1_2_id, + 1 + ); + DoubleListJoinColumnBidirectionalRefEdEntity1 rev2 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefEdEntity1.class, + ed1_2_id, + 2 + ); + DoubleListJoinColumnBidirectionalRefEdEntity1 rev3 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefEdEntity1.class, + ed1_2_id, + 3 + ); + DoubleListJoinColumnBidirectionalRefEdEntity1 rev4 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefEdEntity1.class, + ed1_2_id, + 4 + ); - assertTrue(rev1.getOwner().equals(ing2)); - assertTrue(rev2.getOwner().equals(ing1)); - assertTrue(rev3.getOwner().equals(ing1)); - assertTrue(rev4.getOwner().equals(ing2)); + assertTrue( rev1.getOwner().equals( ing2 ) ); + assertTrue( rev2.getOwner().equals( ing1 ) ); + assertTrue( rev3.getOwner().equals( ing1 ) ); + assertTrue( rev4.getOwner().equals( ing2 ) ); - assertEquals(rev1.getData(), "ed1_2"); - assertEquals(rev2.getData(), "ed1_2"); - assertEquals(rev3.getData(), "ed1_2"); - assertEquals(rev4.getData(), "ed1_2"); - } + assertEquals( rev1.getData(), "ed1_2" ); + assertEquals( rev2.getData(), "ed1_2" ); + assertEquals( rev3.getData(), "ed1_2" ); + assertEquals( rev4.getData(), "ed1_2" ); + } - @Test - public void testHistoryOfEd2_1() { - DoubleListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1_id); - DoubleListJoinColumnBidirectionalRefIngEntity ing2 = getEntityManager().find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2_id); + @Test + public void testHistoryOfEd2_1() { + DoubleListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing1_id + ); + DoubleListJoinColumnBidirectionalRefIngEntity ing2 = getEntityManager().find( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing2_id + ); - DoubleListJoinColumnBidirectionalRefEdEntity2 rev1 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1_id, 1); - DoubleListJoinColumnBidirectionalRefEdEntity2 rev2 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1_id, 2); - DoubleListJoinColumnBidirectionalRefEdEntity2 rev3 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1_id, 3); - DoubleListJoinColumnBidirectionalRefEdEntity2 rev4 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_1_id, 4); + DoubleListJoinColumnBidirectionalRefEdEntity2 rev1 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefEdEntity2.class, + ed2_1_id, + 1 + ); + DoubleListJoinColumnBidirectionalRefEdEntity2 rev2 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefEdEntity2.class, + ed2_1_id, + 2 + ); + DoubleListJoinColumnBidirectionalRefEdEntity2 rev3 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefEdEntity2.class, + ed2_1_id, + 3 + ); + DoubleListJoinColumnBidirectionalRefEdEntity2 rev4 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefEdEntity2.class, + ed2_1_id, + 4 + ); - assertTrue(rev1.getOwner().equals(ing1)); - assertTrue(rev2.getOwner().equals(ing1)); - assertTrue(rev3.getOwner().equals(ing1)); - assertTrue(rev4.getOwner().equals(ing2)); + assertTrue( rev1.getOwner().equals( ing1 ) ); + assertTrue( rev2.getOwner().equals( ing1 ) ); + assertTrue( rev3.getOwner().equals( ing1 ) ); + assertTrue( rev4.getOwner().equals( ing2 ) ); - assertEquals(rev1.getData(), "ed2_1"); - assertEquals(rev2.getData(), "ed2_1"); - assertEquals(rev3.getData(), "ed2_1"); - assertEquals(rev4.getData(), "ed2_1"); - } + assertEquals( rev1.getData(), "ed2_1" ); + assertEquals( rev2.getData(), "ed2_1" ); + assertEquals( rev3.getData(), "ed2_1" ); + assertEquals( rev4.getData(), "ed2_1" ); + } - @Test - public void testHistoryOfEd2_2() { - DoubleListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing1_id); - DoubleListJoinColumnBidirectionalRefIngEntity ing2 = getEntityManager().find(DoubleListJoinColumnBidirectionalRefIngEntity.class, ing2_id); + @Test + public void testHistoryOfEd2_2() { + DoubleListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing1_id + ); + DoubleListJoinColumnBidirectionalRefIngEntity ing2 = getEntityManager().find( + DoubleListJoinColumnBidirectionalRefIngEntity.class, + ing2_id + ); - DoubleListJoinColumnBidirectionalRefEdEntity2 rev1 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2_id, 1); - DoubleListJoinColumnBidirectionalRefEdEntity2 rev2 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2_id, 2); - DoubleListJoinColumnBidirectionalRefEdEntity2 rev3 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2_id, 3); - DoubleListJoinColumnBidirectionalRefEdEntity2 rev4 = getAuditReader().find(DoubleListJoinColumnBidirectionalRefEdEntity2.class, ed2_2_id, 4); + DoubleListJoinColumnBidirectionalRefEdEntity2 rev1 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefEdEntity2.class, + ed2_2_id, + 1 + ); + DoubleListJoinColumnBidirectionalRefEdEntity2 rev2 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefEdEntity2.class, + ed2_2_id, + 2 + ); + DoubleListJoinColumnBidirectionalRefEdEntity2 rev3 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefEdEntity2.class, + ed2_2_id, + 3 + ); + DoubleListJoinColumnBidirectionalRefEdEntity2 rev4 = getAuditReader().find( + DoubleListJoinColumnBidirectionalRefEdEntity2.class, + ed2_2_id, + 4 + ); - assertTrue(rev1.getOwner().equals(ing2)); - assertTrue(rev2.getOwner().equals(ing1)); - assertTrue(rev3.getOwner().equals(ing1)); - assertTrue(rev4.getOwner().equals(ing1)); + assertTrue( rev1.getOwner().equals( ing2 ) ); + assertTrue( rev2.getOwner().equals( ing1 ) ); + assertTrue( rev3.getOwner().equals( ing1 ) ); + assertTrue( rev4.getOwner().equals( ing1 ) ); - assertEquals(rev1.getData(), "ed2_2"); - assertEquals(rev2.getData(), "ed2_2"); - assertEquals(rev3.getData(), "ed2_2 bis"); - assertEquals(rev4.getData(), "ed2_2 bis"); - } + assertEquals( rev1.getData(), "ed2_2" ); + assertEquals( rev2.getData(), "ed2_2" ); + assertEquals( rev3.getData(), "ed2_2 bis" ); + assertEquals( rev4.getData(), "ed2_2 bis" ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/IndexedJoinColumnBidirectionalList.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/IndexedJoinColumnBidirectionalList.java index ea186da718..970415b94d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/IndexedJoinColumnBidirectionalList.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/IndexedJoinColumnBidirectionalList.java @@ -23,231 +23,380 @@ */ package org.hibernate.envers.test.integration.onetomany.detached; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.onetomany.detached.IndexedListJoinColumnBidirectionalRefEdEntity; import org.hibernate.envers.test.entities.onetomany.detached.IndexedListJoinColumnBidirectionalRefIngEntity; +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Test for a "fake" bidirectional mapping where one side uses @OneToMany+@JoinColumn (and thus owns the relatin), * and the other uses a @ManyToOne(insertable=false, updatable=false). + * * @author Adam Warski (adam at warski dot org) */ public class IndexedJoinColumnBidirectionalList extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; - private Integer ed3_id; + private Integer ed1_id; + private Integer ed2_id; + private Integer ed3_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { IndexedListJoinColumnBidirectionalRefIngEntity.class, IndexedListJoinColumnBidirectionalRefEdEntity.class }; - } + return new Class[] { + IndexedListJoinColumnBidirectionalRefIngEntity.class, + IndexedListJoinColumnBidirectionalRefEdEntity.class + }; + } - @Test - @Priority(10) - public void createData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void createData() { + EntityManager em = getEntityManager(); - IndexedListJoinColumnBidirectionalRefEdEntity ed1 = new IndexedListJoinColumnBidirectionalRefEdEntity("ed1", null); - IndexedListJoinColumnBidirectionalRefEdEntity ed2 = new IndexedListJoinColumnBidirectionalRefEdEntity("ed2", null); - IndexedListJoinColumnBidirectionalRefEdEntity ed3 = new IndexedListJoinColumnBidirectionalRefEdEntity("ed3", null); + IndexedListJoinColumnBidirectionalRefEdEntity ed1 = new IndexedListJoinColumnBidirectionalRefEdEntity( + "ed1", + null + ); + IndexedListJoinColumnBidirectionalRefEdEntity ed2 = new IndexedListJoinColumnBidirectionalRefEdEntity( + "ed2", + null + ); + IndexedListJoinColumnBidirectionalRefEdEntity ed3 = new IndexedListJoinColumnBidirectionalRefEdEntity( + "ed3", + null + ); - IndexedListJoinColumnBidirectionalRefIngEntity ing1 = new IndexedListJoinColumnBidirectionalRefIngEntity("coll1", ed1, ed2, ed3); - IndexedListJoinColumnBidirectionalRefIngEntity ing2 = new IndexedListJoinColumnBidirectionalRefIngEntity("coll1"); + IndexedListJoinColumnBidirectionalRefIngEntity ing1 = new IndexedListJoinColumnBidirectionalRefIngEntity( + "coll1", + ed1, + ed2, + ed3 + ); + IndexedListJoinColumnBidirectionalRefIngEntity ing2 = new IndexedListJoinColumnBidirectionalRefIngEntity( + "coll1" + ); - // Revision 1 (ing1: ed1, ed2, ed3) - em.getTransaction().begin(); + // Revision 1 (ing1: ed1, ed2, ed3) + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); - em.persist(ed3); - em.persist(ing1); - em.persist(ing2); + em.persist( ed1 ); + em.persist( ed2 ); + em.persist( ed3 ); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (ing1: ed1, ed3, ing2: ed2) - em.getTransaction().begin(); + // Revision 2 (ing1: ed1, ed3, ing2: ed2) + em.getTransaction().begin(); - ing1 = em.find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing1.getId()); - ing2 = em.find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing2.getId()); - ed2 = em.find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed2.getId()); + ing1 = em.find( IndexedListJoinColumnBidirectionalRefIngEntity.class, ing1.getId() ); + ing2 = em.find( IndexedListJoinColumnBidirectionalRefIngEntity.class, ing2.getId() ); + ed2 = em.find( IndexedListJoinColumnBidirectionalRefEdEntity.class, ed2.getId() ); - ing1.getReferences().remove(ed2); - ing2.getReferences().add(ed2); + ing1.getReferences().remove( ed2 ); + ing2.getReferences().add( ed2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 3 (ing1: ed3, ed1, ing2: ed2) - em.getTransaction().begin(); + // Revision 3 (ing1: ed3, ed1, ing2: ed2) + em.getTransaction().begin(); - ing1 = em.find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing1.getId()); - ing2 = em.find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing2.getId()); - ed1 = em.find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed1.getId()); - ed2 = em.find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed2.getId()); - ed3 = em.find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed3.getId()); + ing1 = em.find( IndexedListJoinColumnBidirectionalRefIngEntity.class, ing1.getId() ); + ing2 = em.find( IndexedListJoinColumnBidirectionalRefIngEntity.class, ing2.getId() ); + ed1 = em.find( IndexedListJoinColumnBidirectionalRefEdEntity.class, ed1.getId() ); + ed2 = em.find( IndexedListJoinColumnBidirectionalRefEdEntity.class, ed2.getId() ); + ed3 = em.find( IndexedListJoinColumnBidirectionalRefEdEntity.class, ed3.getId() ); - ing1.getReferences().remove(ed3); - ing1.getReferences().add(0, ed3); + ing1.getReferences().remove( ed3 ); + ing1.getReferences().add( 0, ed3 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 4 (ing1: ed2, ed3, ed1) - em.getTransaction().begin(); + // Revision 4 (ing1: ed2, ed3, ed1) + em.getTransaction().begin(); - ing1 = em.find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing1.getId()); - ing2 = em.find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing2.getId()); - ed1 = em.find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed1.getId()); - ed2 = em.find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed2.getId()); - ed3 = em.find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed3.getId()); + ing1 = em.find( IndexedListJoinColumnBidirectionalRefIngEntity.class, ing1.getId() ); + ing2 = em.find( IndexedListJoinColumnBidirectionalRefIngEntity.class, ing2.getId() ); + ed1 = em.find( IndexedListJoinColumnBidirectionalRefEdEntity.class, ed1.getId() ); + ed2 = em.find( IndexedListJoinColumnBidirectionalRefEdEntity.class, ed2.getId() ); + ed3 = em.find( IndexedListJoinColumnBidirectionalRefEdEntity.class, ed3.getId() ); - ing2.getReferences().remove(ed2); - ing1.getReferences().add(0, ed2); + ing2.getReferences().remove( ed2 ); + ing1.getReferences().add( 0, ed2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // + // - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); - ed3_id = ed3.getId(); - } + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); + ed3_id = ed3.getId(); + } - @Test - public void testRevisionsCounts() { - assertEquals(Arrays.asList(1, 2, 3, 4), getAuditReader().getRevisions(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing1_id)); - assertEquals(Arrays.asList(1, 2, 4), getAuditReader().getRevisions(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing2_id)); + @Test + public void testRevisionsCounts() { + assertEquals( + Arrays.asList( 1, 2, 3, 4 ), getAuditReader().getRevisions( + IndexedListJoinColumnBidirectionalRefIngEntity.class, + ing1_id + ) + ); + assertEquals( + Arrays.asList( 1, 2, 4 ), getAuditReader().getRevisions( + IndexedListJoinColumnBidirectionalRefIngEntity.class, + ing2_id + ) + ); - assertEquals(Arrays.asList(1, 3, 4), getAuditReader().getRevisions(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed1_id)); - assertEquals(Arrays.asList(1, 2, 4), getAuditReader().getRevisions(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed2_id)); - assertEquals(Arrays.asList(1, 2, 3, 4), getAuditReader().getRevisions(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed3_id)); - } + assertEquals( + Arrays.asList( 1, 3, 4 ), getAuditReader().getRevisions( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed1_id + ) + ); + assertEquals( + Arrays.asList( 1, 2, 4 ), getAuditReader().getRevisions( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed2_id + ) + ); + assertEquals( + Arrays.asList( 1, 2, 3, 4 ), getAuditReader().getRevisions( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed3_id + ) + ); + } - @Test - public void testHistoryOfIng1() { - IndexedListJoinColumnBidirectionalRefEdEntity ed1 = getEntityManager().find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed1_id); - IndexedListJoinColumnBidirectionalRefEdEntity ed2 = getEntityManager().find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed2_id); - IndexedListJoinColumnBidirectionalRefEdEntity ed3 = getEntityManager().find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed3_id); + @Test + public void testHistoryOfIng1() { + IndexedListJoinColumnBidirectionalRefEdEntity ed1 = getEntityManager().find( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed1_id + ); + IndexedListJoinColumnBidirectionalRefEdEntity ed2 = getEntityManager().find( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed2_id + ); + IndexedListJoinColumnBidirectionalRefEdEntity ed3 = getEntityManager().find( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed3_id + ); - IndexedListJoinColumnBidirectionalRefIngEntity rev1 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing1_id, 1); - IndexedListJoinColumnBidirectionalRefIngEntity rev2 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing1_id, 2); - IndexedListJoinColumnBidirectionalRefIngEntity rev3 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing1_id, 3); - IndexedListJoinColumnBidirectionalRefIngEntity rev4 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing1_id, 4); + IndexedListJoinColumnBidirectionalRefIngEntity rev1 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefIngEntity.class, + ing1_id, + 1 + ); + IndexedListJoinColumnBidirectionalRefIngEntity rev2 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefIngEntity.class, + ing1_id, + 2 + ); + IndexedListJoinColumnBidirectionalRefIngEntity rev3 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefIngEntity.class, + ing1_id, + 3 + ); + IndexedListJoinColumnBidirectionalRefIngEntity rev4 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefIngEntity.class, + ing1_id, + 4 + ); - assertEquals(rev1.getReferences().size(), 3); - assertEquals(rev1.getReferences().get(0), ed1); - assertEquals(rev1.getReferences().get(1), ed2); - assertEquals(rev1.getReferences().get(2), ed3); + assertEquals( rev1.getReferences().size(), 3 ); + assertEquals( rev1.getReferences().get( 0 ), ed1 ); + assertEquals( rev1.getReferences().get( 1 ), ed2 ); + assertEquals( rev1.getReferences().get( 2 ), ed3 ); - assertEquals(rev2.getReferences().size(), 2); - assertEquals(rev2.getReferences().get(0), ed1); - assertEquals(rev2.getReferences().get(1), ed3); + assertEquals( rev2.getReferences().size(), 2 ); + assertEquals( rev2.getReferences().get( 0 ), ed1 ); + assertEquals( rev2.getReferences().get( 1 ), ed3 ); - assertEquals(rev3.getReferences().size(), 2); - assertEquals(rev3.getReferences().get(0), ed3); - assertEquals(rev3.getReferences().get(1), ed1); + assertEquals( rev3.getReferences().size(), 2 ); + assertEquals( rev3.getReferences().get( 0 ), ed3 ); + assertEquals( rev3.getReferences().get( 1 ), ed1 ); - assertEquals(rev4.getReferences().size(), 3); - assertEquals(rev4.getReferences().get(0), ed2); - assertEquals(rev4.getReferences().get(1), ed3); - assertEquals(rev4.getReferences().get(2), ed1); - } + assertEquals( rev4.getReferences().size(), 3 ); + assertEquals( rev4.getReferences().get( 0 ), ed2 ); + assertEquals( rev4.getReferences().get( 1 ), ed3 ); + assertEquals( rev4.getReferences().get( 2 ), ed1 ); + } - @Test - public void testHistoryOfIng2() { - IndexedListJoinColumnBidirectionalRefEdEntity ed2 = getEntityManager().find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed2_id); + @Test + public void testHistoryOfIng2() { + IndexedListJoinColumnBidirectionalRefEdEntity ed2 = getEntityManager().find( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed2_id + ); - IndexedListJoinColumnBidirectionalRefIngEntity rev1 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing2_id, 1); - IndexedListJoinColumnBidirectionalRefIngEntity rev2 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing2_id, 2); - IndexedListJoinColumnBidirectionalRefIngEntity rev3 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing2_id, 3); - IndexedListJoinColumnBidirectionalRefIngEntity rev4 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing2_id, 4); + IndexedListJoinColumnBidirectionalRefIngEntity rev1 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefIngEntity.class, + ing2_id, + 1 + ); + IndexedListJoinColumnBidirectionalRefIngEntity rev2 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefIngEntity.class, + ing2_id, + 2 + ); + IndexedListJoinColumnBidirectionalRefIngEntity rev3 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefIngEntity.class, + ing2_id, + 3 + ); + IndexedListJoinColumnBidirectionalRefIngEntity rev4 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefIngEntity.class, + ing2_id, + 4 + ); - assertEquals(rev1.getReferences().size(), 0); + assertEquals( rev1.getReferences().size(), 0 ); - assertEquals(rev2.getReferences().size(), 1); - assertEquals(rev2.getReferences().get(0), ed2); + assertEquals( rev2.getReferences().size(), 1 ); + assertEquals( rev2.getReferences().get( 0 ), ed2 ); - assertEquals(rev3.getReferences().size(), 1); - assertEquals(rev3.getReferences().get(0), ed2); + assertEquals( rev3.getReferences().size(), 1 ); + assertEquals( rev3.getReferences().get( 0 ), ed2 ); - assertEquals(rev4.getReferences().size(), 0); - } + assertEquals( rev4.getReferences().size(), 0 ); + } - @Test - public void testHistoryOfEd1() { - IndexedListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing1_id); + @Test + public void testHistoryOfEd1() { + IndexedListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find( + IndexedListJoinColumnBidirectionalRefIngEntity.class, + ing1_id + ); - IndexedListJoinColumnBidirectionalRefEdEntity rev1 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed1_id, 1); - IndexedListJoinColumnBidirectionalRefEdEntity rev2 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed1_id, 2); - IndexedListJoinColumnBidirectionalRefEdEntity rev3 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed1_id, 3); - IndexedListJoinColumnBidirectionalRefEdEntity rev4 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed1_id, 4); + IndexedListJoinColumnBidirectionalRefEdEntity rev1 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed1_id, + 1 + ); + IndexedListJoinColumnBidirectionalRefEdEntity rev2 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed1_id, + 2 + ); + IndexedListJoinColumnBidirectionalRefEdEntity rev3 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed1_id, + 3 + ); + IndexedListJoinColumnBidirectionalRefEdEntity rev4 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed1_id, + 4 + ); - assertTrue(rev1.getOwner().equals(ing1)); - assertTrue(rev2.getOwner().equals(ing1)); - assertTrue(rev3.getOwner().equals(ing1)); - assertTrue(rev4.getOwner().equals(ing1)); + assertTrue( rev1.getOwner().equals( ing1 ) ); + assertTrue( rev2.getOwner().equals( ing1 ) ); + assertTrue( rev3.getOwner().equals( ing1 ) ); + assertTrue( rev4.getOwner().equals( ing1 ) ); - assertEquals( rev1.getPosition(), Integer.valueOf( 0 ) ); - assertEquals( rev2.getPosition(), Integer.valueOf( 0 ) ); - assertEquals( rev3.getPosition(), Integer.valueOf( 1 ) ); - assertEquals( rev4.getPosition(), Integer.valueOf( 2 ) ); - } + assertEquals( rev1.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev2.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev3.getPosition(), Integer.valueOf( 1 ) ); + assertEquals( rev4.getPosition(), Integer.valueOf( 2 ) ); + } - @Test - public void testHistoryOfEd2() { - IndexedListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing1_id); - IndexedListJoinColumnBidirectionalRefIngEntity ing2 = getEntityManager().find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing2_id); + @Test + public void testHistoryOfEd2() { + IndexedListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find( + IndexedListJoinColumnBidirectionalRefIngEntity.class, + ing1_id + ); + IndexedListJoinColumnBidirectionalRefIngEntity ing2 = getEntityManager().find( + IndexedListJoinColumnBidirectionalRefIngEntity.class, + ing2_id + ); - IndexedListJoinColumnBidirectionalRefEdEntity rev1 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed2_id, 1); - IndexedListJoinColumnBidirectionalRefEdEntity rev2 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed2_id, 2); - IndexedListJoinColumnBidirectionalRefEdEntity rev3 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed2_id, 3); - IndexedListJoinColumnBidirectionalRefEdEntity rev4 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed2_id, 4); + IndexedListJoinColumnBidirectionalRefEdEntity rev1 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed2_id, + 1 + ); + IndexedListJoinColumnBidirectionalRefEdEntity rev2 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed2_id, + 2 + ); + IndexedListJoinColumnBidirectionalRefEdEntity rev3 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed2_id, + 3 + ); + IndexedListJoinColumnBidirectionalRefEdEntity rev4 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed2_id, + 4 + ); - assertTrue(rev1.getOwner().equals(ing1)); - assertTrue(rev2.getOwner().equals(ing2)); - assertTrue(rev3.getOwner().equals(ing2)); - assertTrue(rev4.getOwner().equals(ing1)); + assertTrue( rev1.getOwner().equals( ing1 ) ); + assertTrue( rev2.getOwner().equals( ing2 ) ); + assertTrue( rev3.getOwner().equals( ing2 ) ); + assertTrue( rev4.getOwner().equals( ing1 ) ); - assertEquals( rev1.getPosition(), Integer.valueOf( 1 ) ); - assertEquals( rev2.getPosition(), Integer.valueOf( 0 ) ); - assertEquals( rev3.getPosition(), Integer.valueOf( 0 ) ); - assertEquals( rev4.getPosition(), Integer.valueOf( 0 ) ); - } + assertEquals( rev1.getPosition(), Integer.valueOf( 1 ) ); + assertEquals( rev2.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev3.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev4.getPosition(), Integer.valueOf( 0 ) ); + } - @Test - public void testHistoryOfEd3() { - IndexedListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find(IndexedListJoinColumnBidirectionalRefIngEntity.class, ing1_id); + @Test + public void testHistoryOfEd3() { + IndexedListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find( + IndexedListJoinColumnBidirectionalRefIngEntity.class, + ing1_id + ); - IndexedListJoinColumnBidirectionalRefEdEntity rev1 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed3_id, 1); - IndexedListJoinColumnBidirectionalRefEdEntity rev2 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed3_id, 2); - IndexedListJoinColumnBidirectionalRefEdEntity rev3 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed3_id, 3); - IndexedListJoinColumnBidirectionalRefEdEntity rev4 = getAuditReader().find(IndexedListJoinColumnBidirectionalRefEdEntity.class, ed3_id, 4); + IndexedListJoinColumnBidirectionalRefEdEntity rev1 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed3_id, + 1 + ); + IndexedListJoinColumnBidirectionalRefEdEntity rev2 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed3_id, + 2 + ); + IndexedListJoinColumnBidirectionalRefEdEntity rev3 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed3_id, + 3 + ); + IndexedListJoinColumnBidirectionalRefEdEntity rev4 = getAuditReader().find( + IndexedListJoinColumnBidirectionalRefEdEntity.class, + ed3_id, + 4 + ); - assertTrue(rev1.getOwner().equals(ing1)); - assertTrue(rev2.getOwner().equals(ing1)); - assertTrue(rev3.getOwner().equals(ing1)); - assertTrue(rev4.getOwner().equals(ing1)); + assertTrue( rev1.getOwner().equals( ing1 ) ); + assertTrue( rev2.getOwner().equals( ing1 ) ); + assertTrue( rev3.getOwner().equals( ing1 ) ); + assertTrue( rev4.getOwner().equals( ing1 ) ); - assertEquals( rev1.getPosition(), Integer.valueOf( 2 ) ); - assertEquals( rev2.getPosition(), Integer.valueOf( 1 ) ); - assertEquals( rev3.getPosition(), Integer.valueOf( 0 ) ); - assertEquals( rev4.getPosition(), Integer.valueOf( 1 ) ); - } + assertEquals( rev1.getPosition(), Integer.valueOf( 2 ) ); + assertEquals( rev2.getPosition(), Integer.valueOf( 1 ) ); + assertEquals( rev3.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev4.getPosition(), Integer.valueOf( 1 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/InheritanceIndexedJoinColumnBidirectionalList.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/InheritanceIndexedJoinColumnBidirectionalList.java index a9845ad1f1..5439ce127f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/InheritanceIndexedJoinColumnBidirectionalList.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/InheritanceIndexedJoinColumnBidirectionalList.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.onetomany.detached; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -34,21 +32,24 @@ import org.hibernate.envers.test.entities.onetomany.detached.inheritance.ChildIn import org.hibernate.envers.test.entities.onetomany.detached.inheritance.ParentIndexedListJoinColumnBidirectionalRefIngEntity; import org.hibernate.envers.test.entities.onetomany.detached.inheritance.ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity; +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Test for a "fake" bidirectional mapping where one side uses @OneToMany+@JoinColumn (and thus owns the relation), * in the parent entity, and the other uses a @ManyToOne(insertable=false, updatable=false). + * * @author Adam Warski (adam at warski dot org) */ public class InheritanceIndexedJoinColumnBidirectionalList extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; - private Integer ed3_id; + private Integer ed1_id; + private Integer ed2_id; + private Integer ed3_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { @@ -57,202 +58,349 @@ public class InheritanceIndexedJoinColumnBidirectionalList extends BaseEnversJPA ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class }; - } + } - @Test - @Priority(10) - public void createData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void createData() { + EntityManager em = getEntityManager(); - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity ed1 = new ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity("ed1", null); - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity ed2 = new ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity("ed2", null); - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity ed3 = new ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity("ed3", null); + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity ed1 = new ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity( + "ed1", + null + ); + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity ed2 = new ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity( + "ed2", + null + ); + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity ed3 = new ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity( + "ed3", + null + ); - ChildIndexedListJoinColumnBidirectionalRefIngEntity ing1 = new ChildIndexedListJoinColumnBidirectionalRefIngEntity("coll1", "coll1bis", ed1, ed2, ed3); - ChildIndexedListJoinColumnBidirectionalRefIngEntity ing2 = new ChildIndexedListJoinColumnBidirectionalRefIngEntity("coll1", "coll1bis"); + ChildIndexedListJoinColumnBidirectionalRefIngEntity ing1 = new ChildIndexedListJoinColumnBidirectionalRefIngEntity( + "coll1", + "coll1bis", + ed1, + ed2, + ed3 + ); + ChildIndexedListJoinColumnBidirectionalRefIngEntity ing2 = new ChildIndexedListJoinColumnBidirectionalRefIngEntity( + "coll1", + "coll1bis" + ); - // Revision 1 (ing1: ed1, ed2, ed3) - em.getTransaction().begin(); + // Revision 1 (ing1: ed1, ed2, ed3) + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); - em.persist(ed3); - em.persist(ing1); - em.persist(ing2); + em.persist( ed1 ); + em.persist( ed2 ); + em.persist( ed3 ); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (ing1: ed1, ed3, ing2: ed2) - em.getTransaction().begin(); + // Revision 2 (ing1: ed1, ed3, ing2: ed2) + em.getTransaction().begin(); - ing1 = em.find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing1.getId()); - ing2 = em.find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing2.getId()); - ed2 = em.find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed2.getId()); + ing1 = em.find( ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing1.getId() ); + ing2 = em.find( ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing2.getId() ); + ed2 = em.find( ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed2.getId() ); - ing1.getReferences().remove(ed2); - ing2.getReferences().add(ed2); + ing1.getReferences().remove( ed2 ); + ing2.getReferences().add( ed2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 3 (ing1: ed3, ed1, ing2: ed2) - em.getTransaction().begin(); + // Revision 3 (ing1: ed3, ed1, ing2: ed2) + em.getTransaction().begin(); - ing1 = em.find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing1.getId()); - ing2 = em.find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing2.getId()); - ed1 = em.find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed1.getId()); - ed2 = em.find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed2.getId()); - ed3 = em.find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed3.getId()); + ing1 = em.find( ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing1.getId() ); + ing2 = em.find( ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing2.getId() ); + ed1 = em.find( ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed1.getId() ); + ed2 = em.find( ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed2.getId() ); + ed3 = em.find( ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed3.getId() ); - ing1.getReferences().remove(ed3); - ing1.getReferences().add(0, ed3); + ing1.getReferences().remove( ed3 ); + ing1.getReferences().add( 0, ed3 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 4 (ing1: ed2, ed3, ed1) - em.getTransaction().begin(); + // Revision 4 (ing1: ed2, ed3, ed1) + em.getTransaction().begin(); - ing1 = em.find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing1.getId()); - ing2 = em.find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing2.getId()); - ed1 = em.find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed1.getId()); - ed2 = em.find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed2.getId()); - ed3 = em.find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed3.getId()); + ing1 = em.find( ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing1.getId() ); + ing2 = em.find( ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing2.getId() ); + ed1 = em.find( ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed1.getId() ); + ed2 = em.find( ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed2.getId() ); + ed3 = em.find( ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed3.getId() ); - ing2.getReferences().remove(ed2); - ing1.getReferences().add(0, ed2); + ing2.getReferences().remove( ed2 ); + ing1.getReferences().add( 0, ed2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // + // - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); - ed3_id = ed3.getId(); - } + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); + ed3_id = ed3.getId(); + } - @Test - public void testRevisionsCounts() { - assertEquals(Arrays.asList(1, 2, 3, 4), getAuditReader().getRevisions(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing1_id)); - assertEquals(Arrays.asList(1, 2, 4), getAuditReader().getRevisions(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing2_id)); + @Test + public void testRevisionsCounts() { + assertEquals( + Arrays.asList( 1, 2, 3, 4 ), getAuditReader().getRevisions( + ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, + ing1_id + ) + ); + assertEquals( + Arrays.asList( 1, 2, 4 ), getAuditReader().getRevisions( + ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, + ing2_id + ) + ); - assertEquals(Arrays.asList(1, 3, 4), getAuditReader().getRevisions(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed1_id)); - assertEquals(Arrays.asList(1, 2, 4), getAuditReader().getRevisions(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed2_id)); - assertEquals(Arrays.asList(1, 2, 3, 4), getAuditReader().getRevisions(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed3_id)); - } + assertEquals( + Arrays.asList( 1, 3, 4 ), getAuditReader().getRevisions( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed1_id + ) + ); + assertEquals( + Arrays.asList( 1, 2, 4 ), getAuditReader().getRevisions( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed2_id + ) + ); + assertEquals( + Arrays.asList( 1, 2, 3, 4 ), getAuditReader().getRevisions( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed3_id + ) + ); + } - @Test - public void testHistoryOfIng1() { - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity ed1 = getEntityManager().find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed1_id); - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity ed2 = getEntityManager().find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed2_id); - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity ed3 = getEntityManager().find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed3_id); + @Test + public void testHistoryOfIng1() { + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity ed1 = getEntityManager().find( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed1_id + ); + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity ed2 = getEntityManager().find( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed2_id + ); + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity ed3 = getEntityManager().find( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed3_id + ); - ChildIndexedListJoinColumnBidirectionalRefIngEntity rev1 = getAuditReader().find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing1_id, 1); - ChildIndexedListJoinColumnBidirectionalRefIngEntity rev2 = getAuditReader().find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing1_id, 2); - ChildIndexedListJoinColumnBidirectionalRefIngEntity rev3 = getAuditReader().find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing1_id, 3); - ChildIndexedListJoinColumnBidirectionalRefIngEntity rev4 = getAuditReader().find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing1_id, 4); + ChildIndexedListJoinColumnBidirectionalRefIngEntity rev1 = getAuditReader().find( + ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, + ing1_id, + 1 + ); + ChildIndexedListJoinColumnBidirectionalRefIngEntity rev2 = getAuditReader().find( + ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, + ing1_id, + 2 + ); + ChildIndexedListJoinColumnBidirectionalRefIngEntity rev3 = getAuditReader().find( + ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, + ing1_id, + 3 + ); + ChildIndexedListJoinColumnBidirectionalRefIngEntity rev4 = getAuditReader().find( + ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, + ing1_id, + 4 + ); - assertEquals(rev1.getReferences().size(), 3); - assertEquals(rev1.getReferences().get(0), ed1); - assertEquals(rev1.getReferences().get(1), ed2); - assertEquals(rev1.getReferences().get(2), ed3); + assertEquals( rev1.getReferences().size(), 3 ); + assertEquals( rev1.getReferences().get( 0 ), ed1 ); + assertEquals( rev1.getReferences().get( 1 ), ed2 ); + assertEquals( rev1.getReferences().get( 2 ), ed3 ); - assertEquals(rev2.getReferences().size(), 2); - assertEquals(rev2.getReferences().get(0), ed1); - assertEquals(rev2.getReferences().get(1), ed3); + assertEquals( rev2.getReferences().size(), 2 ); + assertEquals( rev2.getReferences().get( 0 ), ed1 ); + assertEquals( rev2.getReferences().get( 1 ), ed3 ); - assertEquals(rev3.getReferences().size(), 2); - assertEquals(rev3.getReferences().get(0), ed3); - assertEquals(rev3.getReferences().get(1), ed1); + assertEquals( rev3.getReferences().size(), 2 ); + assertEquals( rev3.getReferences().get( 0 ), ed3 ); + assertEquals( rev3.getReferences().get( 1 ), ed1 ); - assertEquals(rev4.getReferences().size(), 3); - assertEquals(rev4.getReferences().get(0), ed2); - assertEquals(rev4.getReferences().get(1), ed3); - assertEquals(rev4.getReferences().get(2), ed1); - } + assertEquals( rev4.getReferences().size(), 3 ); + assertEquals( rev4.getReferences().get( 0 ), ed2 ); + assertEquals( rev4.getReferences().get( 1 ), ed3 ); + assertEquals( rev4.getReferences().get( 2 ), ed1 ); + } - @Test - public void testHistoryOfIng2() { - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity ed2 = getEntityManager().find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed2_id); + @Test + public void testHistoryOfIng2() { + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity ed2 = getEntityManager().find( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed2_id + ); - ChildIndexedListJoinColumnBidirectionalRefIngEntity rev1 = getAuditReader().find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing2_id, 1); - ChildIndexedListJoinColumnBidirectionalRefIngEntity rev2 = getAuditReader().find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing2_id, 2); - ChildIndexedListJoinColumnBidirectionalRefIngEntity rev3 = getAuditReader().find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing2_id, 3); - ChildIndexedListJoinColumnBidirectionalRefIngEntity rev4 = getAuditReader().find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing2_id, 4); + ChildIndexedListJoinColumnBidirectionalRefIngEntity rev1 = getAuditReader().find( + ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, + ing2_id, + 1 + ); + ChildIndexedListJoinColumnBidirectionalRefIngEntity rev2 = getAuditReader().find( + ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, + ing2_id, + 2 + ); + ChildIndexedListJoinColumnBidirectionalRefIngEntity rev3 = getAuditReader().find( + ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, + ing2_id, + 3 + ); + ChildIndexedListJoinColumnBidirectionalRefIngEntity rev4 = getAuditReader().find( + ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, + ing2_id, + 4 + ); - assertEquals(rev1.getReferences().size(), 0); + assertEquals( rev1.getReferences().size(), 0 ); - assertEquals(rev2.getReferences().size(), 1); - assertEquals(rev2.getReferences().get(0), ed2); + assertEquals( rev2.getReferences().size(), 1 ); + assertEquals( rev2.getReferences().get( 0 ), ed2 ); - assertEquals(rev3.getReferences().size(), 1); - assertEquals(rev3.getReferences().get(0), ed2); + assertEquals( rev3.getReferences().size(), 1 ); + assertEquals( rev3.getReferences().get( 0 ), ed2 ); - assertEquals(rev4.getReferences().size(), 0); - } + assertEquals( rev4.getReferences().size(), 0 ); + } - @Test - public void testHistoryOfEd1() { - ChildIndexedListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing1_id); + @Test + public void testHistoryOfEd1() { + ChildIndexedListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find( + ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, + ing1_id + ); - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev1 = getAuditReader().find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed1_id, 1); - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev2 = getAuditReader().find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed1_id, 2); - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev3 = getAuditReader().find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed1_id, 3); - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev4 = getAuditReader().find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed1_id, 4); + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev1 = getAuditReader().find( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed1_id, + 1 + ); + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev2 = getAuditReader().find( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed1_id, + 2 + ); + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev3 = getAuditReader().find( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed1_id, + 3 + ); + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev4 = getAuditReader().find( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed1_id, + 4 + ); - assertTrue(rev1.getOwner().equals(ing1)); - assertTrue(rev2.getOwner().equals(ing1)); - assertTrue(rev3.getOwner().equals(ing1)); - assertTrue(rev4.getOwner().equals(ing1)); + assertTrue( rev1.getOwner().equals( ing1 ) ); + assertTrue( rev2.getOwner().equals( ing1 ) ); + assertTrue( rev3.getOwner().equals( ing1 ) ); + assertTrue( rev4.getOwner().equals( ing1 ) ); - assertEquals( rev1.getPosition(), Integer.valueOf( 0 ) ); - assertEquals( rev2.getPosition(), Integer.valueOf( 0 ) ); - assertEquals( rev3.getPosition(), Integer.valueOf( 1 ) ); - assertEquals( rev4.getPosition(), Integer.valueOf( 2 ) ); - } + assertEquals( rev1.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev2.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev3.getPosition(), Integer.valueOf( 1 ) ); + assertEquals( rev4.getPosition(), Integer.valueOf( 2 ) ); + } - @Test - public void testHistoryOfEd2() { - ChildIndexedListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing1_id); - ChildIndexedListJoinColumnBidirectionalRefIngEntity ing2 = getEntityManager().find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing2_id); + @Test + public void testHistoryOfEd2() { + ChildIndexedListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find( + ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, + ing1_id + ); + ChildIndexedListJoinColumnBidirectionalRefIngEntity ing2 = getEntityManager().find( + ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, + ing2_id + ); - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev1 = getAuditReader().find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed2_id, 1); - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev2 = getAuditReader().find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed2_id, 2); - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev3 = getAuditReader().find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed2_id, 3); - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev4 = getAuditReader().find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed2_id, 4); + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev1 = getAuditReader().find( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed2_id, + 1 + ); + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev2 = getAuditReader().find( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed2_id, + 2 + ); + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev3 = getAuditReader().find( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed2_id, + 3 + ); + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev4 = getAuditReader().find( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed2_id, + 4 + ); - assertTrue(rev1.getOwner().equals(ing1)); - assertTrue(rev2.getOwner().equals(ing2)); - assertTrue(rev3.getOwner().equals(ing2)); - assertTrue(rev4.getOwner().equals(ing1)); + assertTrue( rev1.getOwner().equals( ing1 ) ); + assertTrue( rev2.getOwner().equals( ing2 ) ); + assertTrue( rev3.getOwner().equals( ing2 ) ); + assertTrue( rev4.getOwner().equals( ing1 ) ); - assertEquals( rev1.getPosition(), Integer.valueOf( 1 ) ); - assertEquals( rev2.getPosition(), Integer.valueOf( 0 ) ); - assertEquals( rev3.getPosition(), Integer.valueOf( 0 ) ); - assertEquals( rev4.getPosition(), Integer.valueOf( 0 ) ); - } + assertEquals( rev1.getPosition(), Integer.valueOf( 1 ) ); + assertEquals( rev2.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev3.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev4.getPosition(), Integer.valueOf( 0 ) ); + } - @Test - public void testHistoryOfEd3() { - ChildIndexedListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find(ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, ing1_id); + @Test + public void testHistoryOfEd3() { + ChildIndexedListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find( + ChildIndexedListJoinColumnBidirectionalRefIngEntity.class, + ing1_id + ); - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev1 = getAuditReader().find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed3_id, 1); - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev2 = getAuditReader().find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed3_id, 2); - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev3 = getAuditReader().find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed3_id, 3); - ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev4 = getAuditReader().find(ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, ed3_id, 4); + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev1 = getAuditReader().find( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed3_id, + 1 + ); + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev2 = getAuditReader().find( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed3_id, + 2 + ); + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev3 = getAuditReader().find( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed3_id, + 3 + ); + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity rev4 = getAuditReader().find( + ParentOwnedIndexedListJoinColumnBidirectionalRefEdEntity.class, + ed3_id, + 4 + ); - assertTrue(rev1.getOwner().equals(ing1)); - assertTrue(rev2.getOwner().equals(ing1)); - assertTrue(rev3.getOwner().equals(ing1)); - assertTrue(rev4.getOwner().equals(ing1)); + assertTrue( rev1.getOwner().equals( ing1 ) ); + assertTrue( rev2.getOwner().equals( ing1 ) ); + assertTrue( rev3.getOwner().equals( ing1 ) ); + assertTrue( rev4.getOwner().equals( ing1 ) ); - assertEquals( rev1.getPosition(), Integer.valueOf( 2 ) ); - assertEquals( rev2.getPosition(), Integer.valueOf( 1 ) ); - assertEquals( rev3.getPosition(), Integer.valueOf( 0 ) ); - assertEquals( rev4.getPosition(), Integer.valueOf( 1 ) ); - } + assertEquals( rev1.getPosition(), Integer.valueOf( 2 ) ); + assertEquals( rev2.getPosition(), Integer.valueOf( 1 ) ); + assertEquals( rev3.getPosition(), Integer.valueOf( 0 ) ); + assertEquals( rev4.getPosition(), Integer.valueOf( 1 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/JoinColumnBidirectionalList.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/JoinColumnBidirectionalList.java index 27221556a5..173fc57639 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/JoinColumnBidirectionalList.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/JoinColumnBidirectionalList.java @@ -23,16 +23,16 @@ */ package org.hibernate.envers.test.integration.onetomany.detached; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.onetomany.detached.ListJoinColumnBidirectionalRefEdEntity; import org.hibernate.envers.test.entities.onetomany.detached.ListJoinColumnBidirectionalRefIngEntity; +import org.junit.Test; + import static org.hibernate.envers.test.tools.TestTools.checkList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -40,183 +40,292 @@ import static org.junit.Assert.assertTrue; /** * Test for a "fake" bidirectional mapping where one side uses @OneToMany+@JoinColumn (and thus owns the relatin), * and the other uses a @ManyToOne(insertable=false, updatable=false). + * * @author Adam Warski (adam at warski dot org) */ public class JoinColumnBidirectionalList extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ListJoinColumnBidirectionalRefIngEntity.class, ListJoinColumnBidirectionalRefEdEntity.class }; - } + return new Class[] { + ListJoinColumnBidirectionalRefIngEntity.class, + ListJoinColumnBidirectionalRefEdEntity.class + }; + } - @Test - @Priority(10) - public void createData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void createData() { + EntityManager em = getEntityManager(); - ListJoinColumnBidirectionalRefEdEntity ed1 = new ListJoinColumnBidirectionalRefEdEntity("ed1", null); - ListJoinColumnBidirectionalRefEdEntity ed2 = new ListJoinColumnBidirectionalRefEdEntity("ed2", null); + ListJoinColumnBidirectionalRefEdEntity ed1 = new ListJoinColumnBidirectionalRefEdEntity( "ed1", null ); + ListJoinColumnBidirectionalRefEdEntity ed2 = new ListJoinColumnBidirectionalRefEdEntity( "ed2", null ); - ListJoinColumnBidirectionalRefIngEntity ing1 = new ListJoinColumnBidirectionalRefIngEntity("coll1", ed1); - ListJoinColumnBidirectionalRefIngEntity ing2 = new ListJoinColumnBidirectionalRefIngEntity("coll1", ed2); + ListJoinColumnBidirectionalRefIngEntity ing1 = new ListJoinColumnBidirectionalRefIngEntity( "coll1", ed1 ); + ListJoinColumnBidirectionalRefIngEntity ing2 = new ListJoinColumnBidirectionalRefIngEntity( "coll1", ed2 ); - // Revision 1 (ing1: ed1, ing2: ed2) - em.getTransaction().begin(); + // Revision 1 (ing1: ed1, ing2: ed2) + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); - em.persist(ing1); - em.persist(ing2); + em.persist( ed1 ); + em.persist( ed2 ); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (ing1: ed1, ed2) - em.getTransaction().begin(); + // Revision 2 (ing1: ed1, ed2) + em.getTransaction().begin(); - ing1 = em.find(ListJoinColumnBidirectionalRefIngEntity.class, ing1.getId()); - ing2 = em.find(ListJoinColumnBidirectionalRefIngEntity.class, ing2.getId()); - ed1 = em.find(ListJoinColumnBidirectionalRefEdEntity.class, ed1.getId()); - ed2 = em.find(ListJoinColumnBidirectionalRefEdEntity.class, ed2.getId()); + ing1 = em.find( ListJoinColumnBidirectionalRefIngEntity.class, ing1.getId() ); + ing2 = em.find( ListJoinColumnBidirectionalRefIngEntity.class, ing2.getId() ); + ed1 = em.find( ListJoinColumnBidirectionalRefEdEntity.class, ed1.getId() ); + ed2 = em.find( ListJoinColumnBidirectionalRefEdEntity.class, ed2.getId() ); - ing2.getReferences().remove(ed2); - ing1.getReferences().add(ed2); + ing2.getReferences().remove( ed2 ); + ing1.getReferences().add( ed2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // No revision - no changes - em.getTransaction().begin(); + // No revision - no changes + em.getTransaction().begin(); - ing1 = em.find(ListJoinColumnBidirectionalRefIngEntity.class, ing1.getId()); - ing2 = em.find(ListJoinColumnBidirectionalRefIngEntity.class, ing2.getId()); - ed1 = em.find(ListJoinColumnBidirectionalRefEdEntity.class, ed1.getId()); - ed2 = em.find(ListJoinColumnBidirectionalRefEdEntity.class, ed2.getId()); + ing1 = em.find( ListJoinColumnBidirectionalRefIngEntity.class, ing1.getId() ); + ing2 = em.find( ListJoinColumnBidirectionalRefIngEntity.class, ing2.getId() ); + ed1 = em.find( ListJoinColumnBidirectionalRefEdEntity.class, ed1.getId() ); + ed2 = em.find( ListJoinColumnBidirectionalRefEdEntity.class, ed2.getId() ); - ed2.setOwner(ing2); + ed2.setOwner( ing2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 3 (ing1: ed1, ed2) - em.getTransaction().begin(); + // Revision 3 (ing1: ed1, ed2) + em.getTransaction().begin(); - ed1 = em.find(ListJoinColumnBidirectionalRefEdEntity.class, ed1.getId()); + ed1 = em.find( ListJoinColumnBidirectionalRefEdEntity.class, ed1.getId() ); - ed1.setData("ed1 bis"); - // Shouldn't get written - ed1.setOwner(ing2); + ed1.setData( "ed1 bis" ); + // Shouldn't get written + ed1.setOwner( ing2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 4 (ing2: ed1, ed2) - em.getTransaction().begin(); + // Revision 4 (ing2: ed1, ed2) + em.getTransaction().begin(); - ing1 = em.find(ListJoinColumnBidirectionalRefIngEntity.class, ing1.getId()); - ing2 = em.find(ListJoinColumnBidirectionalRefIngEntity.class, ing2.getId()); + ing1 = em.find( ListJoinColumnBidirectionalRefIngEntity.class, ing1.getId() ); + ing2 = em.find( ListJoinColumnBidirectionalRefIngEntity.class, ing2.getId() ); - ing1.getReferences().clear(); - ing2.getReferences().add(ed1); - ing2.getReferences().add(ed2); + ing1.getReferences().clear(); + ing2.getReferences().add( ed1 ); + ing2.getReferences().add( ed2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // + // - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); - } + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); + } - @Test - public void testRevisionsCounts() { - assertEquals(Arrays.asList(1, 2, 4), getAuditReader().getRevisions(ListJoinColumnBidirectionalRefIngEntity.class, ing1_id)); - assertEquals(Arrays.asList(1, 2, 4), getAuditReader().getRevisions(ListJoinColumnBidirectionalRefIngEntity.class, ing2_id)); + @Test + public void testRevisionsCounts() { + assertEquals( + Arrays.asList( 1, 2, 4 ), + getAuditReader().getRevisions( ListJoinColumnBidirectionalRefIngEntity.class, ing1_id ) + ); + assertEquals( + Arrays.asList( 1, 2, 4 ), + getAuditReader().getRevisions( ListJoinColumnBidirectionalRefIngEntity.class, ing2_id ) + ); - assertEquals(Arrays.asList(1, 3, 4), getAuditReader().getRevisions(ListJoinColumnBidirectionalRefEdEntity.class, ed1_id)); - assertEquals(Arrays.asList(1, 2, 4), getAuditReader().getRevisions(ListJoinColumnBidirectionalRefEdEntity.class, ed2_id)); - } + assertEquals( + Arrays.asList( 1, 3, 4 ), + getAuditReader().getRevisions( ListJoinColumnBidirectionalRefEdEntity.class, ed1_id ) + ); + assertEquals( + Arrays.asList( 1, 2, 4 ), + getAuditReader().getRevisions( ListJoinColumnBidirectionalRefEdEntity.class, ed2_id ) + ); + } - @Test - public void testHistoryOfIng1() { - ListJoinColumnBidirectionalRefEdEntity ed1_fromRev1 = new ListJoinColumnBidirectionalRefEdEntity(ed1_id, "ed1", null); - ListJoinColumnBidirectionalRefEdEntity ed1_fromRev3 = new ListJoinColumnBidirectionalRefEdEntity(ed1_id, "ed1 bis", null); - ListJoinColumnBidirectionalRefEdEntity ed2 = getEntityManager().find(ListJoinColumnBidirectionalRefEdEntity.class, ed2_id); + @Test + public void testHistoryOfIng1() { + ListJoinColumnBidirectionalRefEdEntity ed1_fromRev1 = new ListJoinColumnBidirectionalRefEdEntity( + ed1_id, + "ed1", + null + ); + ListJoinColumnBidirectionalRefEdEntity ed1_fromRev3 = new ListJoinColumnBidirectionalRefEdEntity( + ed1_id, + "ed1 bis", + null + ); + ListJoinColumnBidirectionalRefEdEntity ed2 = getEntityManager().find( + ListJoinColumnBidirectionalRefEdEntity.class, + ed2_id + ); - ListJoinColumnBidirectionalRefIngEntity rev1 = getAuditReader().find(ListJoinColumnBidirectionalRefIngEntity.class, ing1_id, 1); - ListJoinColumnBidirectionalRefIngEntity rev2 = getAuditReader().find(ListJoinColumnBidirectionalRefIngEntity.class, ing1_id, 2); - ListJoinColumnBidirectionalRefIngEntity rev3 = getAuditReader().find(ListJoinColumnBidirectionalRefIngEntity.class, ing1_id, 3); - ListJoinColumnBidirectionalRefIngEntity rev4 = getAuditReader().find(ListJoinColumnBidirectionalRefIngEntity.class, ing1_id, 4); + ListJoinColumnBidirectionalRefIngEntity rev1 = getAuditReader().find( + ListJoinColumnBidirectionalRefIngEntity.class, + ing1_id, + 1 + ); + ListJoinColumnBidirectionalRefIngEntity rev2 = getAuditReader().find( + ListJoinColumnBidirectionalRefIngEntity.class, + ing1_id, + 2 + ); + ListJoinColumnBidirectionalRefIngEntity rev3 = getAuditReader().find( + ListJoinColumnBidirectionalRefIngEntity.class, + ing1_id, + 3 + ); + ListJoinColumnBidirectionalRefIngEntity rev4 = getAuditReader().find( + ListJoinColumnBidirectionalRefIngEntity.class, + ing1_id, + 4 + ); - assertTrue(checkList(rev1.getReferences(), ed1_fromRev1)); - assertTrue(checkList(rev2.getReferences(), ed1_fromRev1, ed2)); - assertTrue(checkList(rev3.getReferences(), ed1_fromRev3, ed2)); - assertTrue(checkList(rev4.getReferences())); - } + assertTrue( checkList( rev1.getReferences(), ed1_fromRev1 ) ); + assertTrue( checkList( rev2.getReferences(), ed1_fromRev1, ed2 ) ); + assertTrue( checkList( rev3.getReferences(), ed1_fromRev3, ed2 ) ); + assertTrue( checkList( rev4.getReferences() ) ); + } - @Test - public void testHistoryOfIng2() { - ListJoinColumnBidirectionalRefEdEntity ed1 = getEntityManager().find(ListJoinColumnBidirectionalRefEdEntity.class, ed1_id); - ListJoinColumnBidirectionalRefEdEntity ed2 = getEntityManager().find(ListJoinColumnBidirectionalRefEdEntity.class, ed2_id); + @Test + public void testHistoryOfIng2() { + ListJoinColumnBidirectionalRefEdEntity ed1 = getEntityManager().find( + ListJoinColumnBidirectionalRefEdEntity.class, + ed1_id + ); + ListJoinColumnBidirectionalRefEdEntity ed2 = getEntityManager().find( + ListJoinColumnBidirectionalRefEdEntity.class, + ed2_id + ); - ListJoinColumnBidirectionalRefIngEntity rev1 = getAuditReader().find(ListJoinColumnBidirectionalRefIngEntity.class, ing2_id, 1); - ListJoinColumnBidirectionalRefIngEntity rev2 = getAuditReader().find(ListJoinColumnBidirectionalRefIngEntity.class, ing2_id, 2); - ListJoinColumnBidirectionalRefIngEntity rev3 = getAuditReader().find(ListJoinColumnBidirectionalRefIngEntity.class, ing2_id, 3); - ListJoinColumnBidirectionalRefIngEntity rev4 = getAuditReader().find(ListJoinColumnBidirectionalRefIngEntity.class, ing2_id, 4); + ListJoinColumnBidirectionalRefIngEntity rev1 = getAuditReader().find( + ListJoinColumnBidirectionalRefIngEntity.class, + ing2_id, + 1 + ); + ListJoinColumnBidirectionalRefIngEntity rev2 = getAuditReader().find( + ListJoinColumnBidirectionalRefIngEntity.class, + ing2_id, + 2 + ); + ListJoinColumnBidirectionalRefIngEntity rev3 = getAuditReader().find( + ListJoinColumnBidirectionalRefIngEntity.class, + ing2_id, + 3 + ); + ListJoinColumnBidirectionalRefIngEntity rev4 = getAuditReader().find( + ListJoinColumnBidirectionalRefIngEntity.class, + ing2_id, + 4 + ); - assertTrue(checkList(rev1.getReferences(), ed2)); - assertTrue(checkList(rev2.getReferences())); - assertTrue(checkList(rev3.getReferences())); - assertTrue(checkList(rev4.getReferences(), ed1, ed2)); - } + assertTrue( checkList( rev1.getReferences(), ed2 ) ); + assertTrue( checkList( rev2.getReferences() ) ); + assertTrue( checkList( rev3.getReferences() ) ); + assertTrue( checkList( rev4.getReferences(), ed1, ed2 ) ); + } - @Test - public void testHistoryOfEd1() { - ListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find(ListJoinColumnBidirectionalRefIngEntity.class, ing1_id); - ListJoinColumnBidirectionalRefIngEntity ing2 = getEntityManager().find(ListJoinColumnBidirectionalRefIngEntity.class, ing2_id); + @Test + public void testHistoryOfEd1() { + ListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find( + ListJoinColumnBidirectionalRefIngEntity.class, + ing1_id + ); + ListJoinColumnBidirectionalRefIngEntity ing2 = getEntityManager().find( + ListJoinColumnBidirectionalRefIngEntity.class, + ing2_id + ); - ListJoinColumnBidirectionalRefEdEntity rev1 = getAuditReader().find(ListJoinColumnBidirectionalRefEdEntity.class, ed1_id, 1); - ListJoinColumnBidirectionalRefEdEntity rev2 = getAuditReader().find(ListJoinColumnBidirectionalRefEdEntity.class, ed1_id, 2); - ListJoinColumnBidirectionalRefEdEntity rev3 = getAuditReader().find(ListJoinColumnBidirectionalRefEdEntity.class, ed1_id, 3); - ListJoinColumnBidirectionalRefEdEntity rev4 = getAuditReader().find(ListJoinColumnBidirectionalRefEdEntity.class, ed1_id, 4); + ListJoinColumnBidirectionalRefEdEntity rev1 = getAuditReader().find( + ListJoinColumnBidirectionalRefEdEntity.class, + ed1_id, + 1 + ); + ListJoinColumnBidirectionalRefEdEntity rev2 = getAuditReader().find( + ListJoinColumnBidirectionalRefEdEntity.class, + ed1_id, + 2 + ); + ListJoinColumnBidirectionalRefEdEntity rev3 = getAuditReader().find( + ListJoinColumnBidirectionalRefEdEntity.class, + ed1_id, + 3 + ); + ListJoinColumnBidirectionalRefEdEntity rev4 = getAuditReader().find( + ListJoinColumnBidirectionalRefEdEntity.class, + ed1_id, + 4 + ); - assertTrue(rev1.getOwner().equals(ing1)); - assertTrue(rev2.getOwner().equals(ing1)); - assertTrue(rev3.getOwner().equals(ing1)); - assertTrue(rev4.getOwner().equals(ing2)); + assertTrue( rev1.getOwner().equals( ing1 ) ); + assertTrue( rev2.getOwner().equals( ing1 ) ); + assertTrue( rev3.getOwner().equals( ing1 ) ); + assertTrue( rev4.getOwner().equals( ing2 ) ); - assertEquals(rev1.getData(), "ed1"); - assertEquals(rev2.getData(), "ed1"); - assertEquals(rev3.getData(), "ed1 bis"); - assertEquals(rev4.getData(), "ed1 bis"); - } + assertEquals( rev1.getData(), "ed1" ); + assertEquals( rev2.getData(), "ed1" ); + assertEquals( rev3.getData(), "ed1 bis" ); + assertEquals( rev4.getData(), "ed1 bis" ); + } - @Test - public void testHistoryOfEd2() { - ListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find(ListJoinColumnBidirectionalRefIngEntity.class, ing1_id); - ListJoinColumnBidirectionalRefIngEntity ing2 = getEntityManager().find(ListJoinColumnBidirectionalRefIngEntity.class, ing2_id); + @Test + public void testHistoryOfEd2() { + ListJoinColumnBidirectionalRefIngEntity ing1 = getEntityManager().find( + ListJoinColumnBidirectionalRefIngEntity.class, + ing1_id + ); + ListJoinColumnBidirectionalRefIngEntity ing2 = getEntityManager().find( + ListJoinColumnBidirectionalRefIngEntity.class, + ing2_id + ); - ListJoinColumnBidirectionalRefEdEntity rev1 = getAuditReader().find(ListJoinColumnBidirectionalRefEdEntity.class, ed2_id, 1); - ListJoinColumnBidirectionalRefEdEntity rev2 = getAuditReader().find(ListJoinColumnBidirectionalRefEdEntity.class, ed2_id, 2); - ListJoinColumnBidirectionalRefEdEntity rev3 = getAuditReader().find(ListJoinColumnBidirectionalRefEdEntity.class, ed2_id, 3); - ListJoinColumnBidirectionalRefEdEntity rev4 = getAuditReader().find(ListJoinColumnBidirectionalRefEdEntity.class, ed2_id, 4); + ListJoinColumnBidirectionalRefEdEntity rev1 = getAuditReader().find( + ListJoinColumnBidirectionalRefEdEntity.class, + ed2_id, + 1 + ); + ListJoinColumnBidirectionalRefEdEntity rev2 = getAuditReader().find( + ListJoinColumnBidirectionalRefEdEntity.class, + ed2_id, + 2 + ); + ListJoinColumnBidirectionalRefEdEntity rev3 = getAuditReader().find( + ListJoinColumnBidirectionalRefEdEntity.class, + ed2_id, + 3 + ); + ListJoinColumnBidirectionalRefEdEntity rev4 = getAuditReader().find( + ListJoinColumnBidirectionalRefEdEntity.class, + ed2_id, + 4 + ); - assertTrue(rev1.getOwner().equals(ing2)); - assertTrue(rev2.getOwner().equals(ing1)); - assertTrue(rev3.getOwner().equals(ing1)); - assertTrue(rev4.getOwner().equals(ing2)); + assertTrue( rev1.getOwner().equals( ing2 ) ); + assertTrue( rev2.getOwner().equals( ing1 ) ); + assertTrue( rev3.getOwner().equals( ing1 ) ); + assertTrue( rev4.getOwner().equals( ing2 ) ); - assertEquals(rev1.getData(), "ed2"); - assertEquals(rev2.getData(), "ed2"); - assertEquals(rev3.getData(), "ed2"); - assertEquals(rev4.getData(), "ed2"); - } + assertEquals( rev1.getData(), "ed2" ); + assertEquals( rev2.getData(), "ed2" ); + assertEquals( rev3.getData(), "ed2" ); + assertEquals( rev4.getData(), "ed2" ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/JoinColumnBidirectionalListWithInheritance.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/JoinColumnBidirectionalListWithInheritance.java index 25914b9dcc..f592416a19 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/JoinColumnBidirectionalListWithInheritance.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/detached/JoinColumnBidirectionalListWithInheritance.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.onetomany.detached; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -34,6 +32,8 @@ import org.hibernate.envers.test.entities.onetomany.detached.ListJoinColumnBidir import org.hibernate.envers.test.entities.onetomany.detached.ListJoinColumnBidirectionalInheritanceRefEdParentEntity; import org.hibernate.envers.test.entities.onetomany.detached.ListJoinColumnBidirectionalInheritanceRefIngEntity; +import org.junit.Test; + import static org.hibernate.envers.test.tools.TestTools.checkList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -41,14 +41,15 @@ import static org.junit.Assert.assertTrue; /** * Test for a "fake" bidirectional mapping where one side uses @OneToMany+@JoinColumn (and thus owns the relatin), * and the other uses a @ManyToOne(insertable=false, updatable=false). + * * @author Adam Warski (adam at warski dot org) */ public class JoinColumnBidirectionalListWithInheritance extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { @@ -57,105 +58,189 @@ public class JoinColumnBidirectionalListWithInheritance extends BaseEnversJPAFun ListJoinColumnBidirectionalInheritanceRefEdChildEntity.class, ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class }; - } + } - @Test - @Priority(10) - public void createData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void createData() { + EntityManager em = getEntityManager(); - ListJoinColumnBidirectionalInheritanceRefEdParentEntity ed1 = new ListJoinColumnBidirectionalInheritanceRefEdChildEntity("ed1", null, "ed1 child"); - ListJoinColumnBidirectionalInheritanceRefEdParentEntity ed2 = new ListJoinColumnBidirectionalInheritanceRefEdChildEntity("ed2", null, "ed2 child"); + ListJoinColumnBidirectionalInheritanceRefEdParentEntity ed1 = new ListJoinColumnBidirectionalInheritanceRefEdChildEntity( + "ed1", + null, + "ed1 child" + ); + ListJoinColumnBidirectionalInheritanceRefEdParentEntity ed2 = new ListJoinColumnBidirectionalInheritanceRefEdChildEntity( + "ed2", + null, + "ed2 child" + ); - ListJoinColumnBidirectionalInheritanceRefIngEntity ing1 = new ListJoinColumnBidirectionalInheritanceRefIngEntity("coll1", ed1); - ListJoinColumnBidirectionalInheritanceRefIngEntity ing2 = new ListJoinColumnBidirectionalInheritanceRefIngEntity("coll1", ed2); + ListJoinColumnBidirectionalInheritanceRefIngEntity ing1 = new ListJoinColumnBidirectionalInheritanceRefIngEntity( + "coll1", + ed1 + ); + ListJoinColumnBidirectionalInheritanceRefIngEntity ing2 = new ListJoinColumnBidirectionalInheritanceRefIngEntity( + "coll1", + ed2 + ); - // Revision 1 (ing1: ed1, ing2: ed2) - em.getTransaction().begin(); + // Revision 1 (ing1: ed1, ing2: ed2) + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); - em.persist(ing1); - em.persist(ing2); + em.persist( ed1 ); + em.persist( ed2 ); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 (ing1: ed1, ed2) - em.getTransaction().begin(); + // Revision 2 (ing1: ed1, ed2) + em.getTransaction().begin(); - ing1 = em.find(ListJoinColumnBidirectionalInheritanceRefIngEntity.class, ing1.getId()); - ing2 = em.find(ListJoinColumnBidirectionalInheritanceRefIngEntity.class, ing2.getId()); - ed1 = em.find(ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, ed1.getId()); - ed2 = em.find(ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, ed2.getId()); + ing1 = em.find( ListJoinColumnBidirectionalInheritanceRefIngEntity.class, ing1.getId() ); + ing2 = em.find( ListJoinColumnBidirectionalInheritanceRefIngEntity.class, ing2.getId() ); + ed1 = em.find( ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, ed1.getId() ); + ed2 = em.find( ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, ed2.getId() ); - ing2.getReferences().remove(ed2); - ing1.getReferences().add(ed2); + ing2.getReferences().remove( ed2 ); + ing1.getReferences().add( ed2 ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // + // - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); - } + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); + } - @Test - public void testRevisionsCounts() { - assertEquals(Arrays.asList(1, 2), getAuditReader().getRevisions(ListJoinColumnBidirectionalInheritanceRefIngEntity.class, ing1_id)); - assertEquals(Arrays.asList(1, 2), getAuditReader().getRevisions(ListJoinColumnBidirectionalInheritanceRefIngEntity.class, ing2_id)); + @Test + public void testRevisionsCounts() { + assertEquals( + Arrays.asList( 1, 2 ), getAuditReader().getRevisions( + ListJoinColumnBidirectionalInheritanceRefIngEntity.class, + ing1_id + ) + ); + assertEquals( + Arrays.asList( 1, 2 ), getAuditReader().getRevisions( + ListJoinColumnBidirectionalInheritanceRefIngEntity.class, + ing2_id + ) + ); - assertEquals(Arrays.asList(1), getAuditReader().getRevisions(ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, ed1_id)); - assertEquals(Arrays.asList(1, 2), getAuditReader().getRevisions(ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, ed2_id)); - } + assertEquals( + Arrays.asList( 1 ), getAuditReader().getRevisions( + ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, + ed1_id + ) + ); + assertEquals( + Arrays.asList( 1, 2 ), getAuditReader().getRevisions( + ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, + ed2_id + ) + ); + } - @Test - public void testHistoryOfIng1() { - ListJoinColumnBidirectionalInheritanceRefEdParentEntity ed1 = getEntityManager().find(ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, ed1_id); - ListJoinColumnBidirectionalInheritanceRefEdParentEntity ed2 = getEntityManager().find(ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, ed2_id); + @Test + public void testHistoryOfIng1() { + ListJoinColumnBidirectionalInheritanceRefEdParentEntity ed1 = getEntityManager().find( + ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, + ed1_id + ); + ListJoinColumnBidirectionalInheritanceRefEdParentEntity ed2 = getEntityManager().find( + ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, + ed2_id + ); - ListJoinColumnBidirectionalInheritanceRefIngEntity rev1 = getAuditReader().find(ListJoinColumnBidirectionalInheritanceRefIngEntity.class, ing1_id, 1); - ListJoinColumnBidirectionalInheritanceRefIngEntity rev2 = getAuditReader().find(ListJoinColumnBidirectionalInheritanceRefIngEntity.class, ing1_id, 2); + ListJoinColumnBidirectionalInheritanceRefIngEntity rev1 = getAuditReader().find( + ListJoinColumnBidirectionalInheritanceRefIngEntity.class, + ing1_id, + 1 + ); + ListJoinColumnBidirectionalInheritanceRefIngEntity rev2 = getAuditReader().find( + ListJoinColumnBidirectionalInheritanceRefIngEntity.class, + ing1_id, + 2 + ); - assertTrue(checkList(rev1.getReferences(), ed1)); - assertTrue(checkList(rev2.getReferences(), ed1, ed2)); - } + assertTrue( checkList( rev1.getReferences(), ed1 ) ); + assertTrue( checkList( rev2.getReferences(), ed1, ed2 ) ); + } - @Test - public void testHistoryOfIng2() { - ListJoinColumnBidirectionalInheritanceRefEdParentEntity ed2 = getEntityManager().find(ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, ed2_id); + @Test + public void testHistoryOfIng2() { + ListJoinColumnBidirectionalInheritanceRefEdParentEntity ed2 = getEntityManager().find( + ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, + ed2_id + ); - ListJoinColumnBidirectionalInheritanceRefIngEntity rev1 = getAuditReader().find(ListJoinColumnBidirectionalInheritanceRefIngEntity.class, ing2_id, 1); - ListJoinColumnBidirectionalInheritanceRefIngEntity rev2 = getAuditReader().find(ListJoinColumnBidirectionalInheritanceRefIngEntity.class, ing2_id, 2); + ListJoinColumnBidirectionalInheritanceRefIngEntity rev1 = getAuditReader().find( + ListJoinColumnBidirectionalInheritanceRefIngEntity.class, + ing2_id, + 1 + ); + ListJoinColumnBidirectionalInheritanceRefIngEntity rev2 = getAuditReader().find( + ListJoinColumnBidirectionalInheritanceRefIngEntity.class, + ing2_id, + 2 + ); - assertTrue(checkList(rev1.getReferences(), ed2)); - assertTrue(checkList(rev2.getReferences())); - } + assertTrue( checkList( rev1.getReferences(), ed2 ) ); + assertTrue( checkList( rev2.getReferences() ) ); + } - @Test - public void testHistoryOfEd1() { - ListJoinColumnBidirectionalInheritanceRefIngEntity ing1 = getEntityManager().find(ListJoinColumnBidirectionalInheritanceRefIngEntity.class, ing1_id); + @Test + public void testHistoryOfEd1() { + ListJoinColumnBidirectionalInheritanceRefIngEntity ing1 = getEntityManager().find( + ListJoinColumnBidirectionalInheritanceRefIngEntity.class, + ing1_id + ); - ListJoinColumnBidirectionalInheritanceRefEdParentEntity rev1 = getAuditReader().find(ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, ed1_id, 1); - ListJoinColumnBidirectionalInheritanceRefEdParentEntity rev2 = getAuditReader().find(ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, ed1_id, 2); + ListJoinColumnBidirectionalInheritanceRefEdParentEntity rev1 = getAuditReader().find( + ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, + ed1_id, + 1 + ); + ListJoinColumnBidirectionalInheritanceRefEdParentEntity rev2 = getAuditReader().find( + ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, + ed1_id, + 2 + ); - assertTrue(rev1.getOwner().equals(ing1)); - assertTrue(rev2.getOwner().equals(ing1)); - } + assertTrue( rev1.getOwner().equals( ing1 ) ); + assertTrue( rev2.getOwner().equals( ing1 ) ); + } - @Test - public void testHistoryOfEd2() { - ListJoinColumnBidirectionalInheritanceRefIngEntity ing1 = getEntityManager().find(ListJoinColumnBidirectionalInheritanceRefIngEntity.class, ing1_id); - ListJoinColumnBidirectionalInheritanceRefIngEntity ing2 = getEntityManager().find(ListJoinColumnBidirectionalInheritanceRefIngEntity.class, ing2_id); + @Test + public void testHistoryOfEd2() { + ListJoinColumnBidirectionalInheritanceRefIngEntity ing1 = getEntityManager().find( + ListJoinColumnBidirectionalInheritanceRefIngEntity.class, + ing1_id + ); + ListJoinColumnBidirectionalInheritanceRefIngEntity ing2 = getEntityManager().find( + ListJoinColumnBidirectionalInheritanceRefIngEntity.class, + ing2_id + ); - ListJoinColumnBidirectionalInheritanceRefEdParentEntity rev1 = getAuditReader().find(ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, ed2_id, 1); - ListJoinColumnBidirectionalInheritanceRefEdParentEntity rev2 = getAuditReader().find(ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, ed2_id, 2); + ListJoinColumnBidirectionalInheritanceRefEdParentEntity rev1 = getAuditReader().find( + ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, + ed2_id, + 1 + ); + ListJoinColumnBidirectionalInheritanceRefEdParentEntity rev2 = getAuditReader().find( + ListJoinColumnBidirectionalInheritanceRefEdParentEntity.class, + ed2_id, + 2 + ); - assertTrue(rev1.getOwner().equals(ing2)); - assertTrue(rev2.getOwner().equals(ing1)); - } + assertTrue( rev1.getOwner().equals( ing2 ) ); + assertTrue( rev2.getOwner().equals( ing1 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/embeddedid/Constant.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/embeddedid/Constant.java index 9db330a594..678c9486a3 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/embeddedid/Constant.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/embeddedid/Constant.java @@ -1,9 +1,9 @@ package org.hibernate.envers.test.integration.onetomany.embeddedid; -import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -13,58 +13,66 @@ import org.hibernate.envers.Audited; @Entity @Audited public class Constant implements Serializable { - @Id - @Column(length = 3) - private String id; + @Id + @Column(length = 3) + private String id; - private String name; + private String name; - public Constant() { - } + public Constant() { + } - public Constant(String id, String name) { - this.id = id; - this.name = name; - } + public Constant(String id, String name) { + this.id = id; + this.name = name; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Constant)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Constant) ) { + return false; + } - Constant constant = (Constant) o; + Constant constant = (Constant) o; - if (id != null ? !id.equals(constant.id) : constant.id != null) return false; - if (name != null ? !name.equals(constant.name) : constant.name != null) return false; + if ( id != null ? !id.equals( constant.id ) : constant.id != null ) { + return false; + } + if ( name != null ? !name.equals( constant.name ) : constant.name != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (name != null ? name.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (name != null ? name.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "Constant(id = " + id + ", name = " + name + ")"; - } + @Override + public String toString() { + return "Constant(id = " + id + ", name = " + name + ")"; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/embeddedid/MapsIdTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/embeddedid/MapsIdTest.java index a785b53263..115d61b1c9 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/embeddedid/MapsIdTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/embeddedid/MapsIdTest.java @@ -1,13 +1,14 @@ package org.hibernate.envers.test.integration.onetomany.embeddedid; -import java.util.Arrays; import javax.persistence.EntityManager; +import java.util.Arrays; + +import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; +import org.hibernate.envers.test.Priority; import org.junit.Assert; import org.junit.Test; -import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; -import org.hibernate.envers.test.Priority; import org.hibernate.testing.TestForIssue; /** @@ -15,115 +16,145 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-7157") public class MapsIdTest extends BaseEnversJPAFunctionalTestCase { - private PersonTuple tuple1Ver1 = null; - private PersonTuple tuple2Ver1 = null; - private PersonTuple tuple2Ver2 = null; - private Person personCVer1 = null; - private Person personCVer2 = null; + private PersonTuple tuple1Ver1 = null; + private PersonTuple tuple2Ver1 = null; + private PersonTuple tuple2Ver2 = null; + private Person personCVer1 = null; + private Person personCVer2 = null; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{Person.class, PersonTuple.class, Constant.class}; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {Person.class, PersonTuple.class, Constant.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 1 - em.getTransaction().begin(); - Person personA = new Person("Peter"); - Person personB = new Person("Mary"); - em.persist(personA); - em.persist(personB); - Constant cons = new Constant("USD", "US Dollar"); - em.persist(cons); - PersonTuple tuple1 = new PersonTuple(true, personA, personB, cons); - em.persist(tuple1); - em.getTransaction().commit(); + // Revision 1 + em.getTransaction().begin(); + Person personA = new Person( "Peter" ); + Person personB = new Person( "Mary" ); + em.persist( personA ); + em.persist( personB ); + Constant cons = new Constant( "USD", "US Dollar" ); + em.persist( cons ); + PersonTuple tuple1 = new PersonTuple( true, personA, personB, cons ); + em.persist( tuple1 ); + em.getTransaction().commit(); - tuple1Ver1 = new PersonTuple(tuple1.isHelloWorld(), tuple1.getPersonA(), tuple1.getPersonB(), tuple1.getConstant()); + tuple1Ver1 = new PersonTuple( + tuple1.isHelloWorld(), + tuple1.getPersonA(), + tuple1.getPersonB(), + tuple1.getConstant() + ); - // Revision 2 - em.getTransaction().begin(); - cons = em.find(Constant.class, cons.getId()); - Person personC1 = new Person("Lukasz"); - em.persist(personC1); - PersonTuple tuple2 = new PersonTuple(true, personA, personC1, cons); - em.persist(tuple2); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + cons = em.find( Constant.class, cons.getId() ); + Person personC1 = new Person( "Lukasz" ); + em.persist( personC1 ); + PersonTuple tuple2 = new PersonTuple( true, personA, personC1, cons ); + em.persist( tuple2 ); + em.getTransaction().commit(); - tuple2Ver1 = new PersonTuple(tuple2.isHelloWorld(), tuple2.getPersonA(), tuple2.getPersonB(), tuple2.getConstant()); - personCVer1 = new Person(personC1.getId(), personC1.getName()); - personCVer1.getPersonBTuples().add(tuple2Ver1); + tuple2Ver1 = new PersonTuple( + tuple2.isHelloWorld(), + tuple2.getPersonA(), + tuple2.getPersonB(), + tuple2.getConstant() + ); + personCVer1 = new Person( personC1.getId(), personC1.getName() ); + personCVer1.getPersonBTuples().add( tuple2Ver1 ); - // Revision 3 - em.getTransaction().begin(); - tuple2 = em.find(PersonTuple.class, tuple2.getPersonTupleId()); - tuple2.setHelloWorld(false); - em.merge(tuple2); - em.getTransaction().commit(); + // Revision 3 + em.getTransaction().begin(); + tuple2 = em.find( PersonTuple.class, tuple2.getPersonTupleId() ); + tuple2.setHelloWorld( false ); + em.merge( tuple2 ); + em.getTransaction().commit(); - tuple2Ver2 = new PersonTuple(tuple2.isHelloWorld(), tuple2.getPersonA(), tuple2.getPersonB(), tuple2.getConstant()); + tuple2Ver2 = new PersonTuple( + tuple2.isHelloWorld(), + tuple2.getPersonA(), + tuple2.getPersonB(), + tuple2.getConstant() + ); - // Revision 4 - em.getTransaction().begin(); - Person personC2 = em.find(Person.class, personC1.getId()); - personC2.setName("Robert"); - em.merge(personC2); - em.getTransaction().commit(); + // Revision 4 + em.getTransaction().begin(); + Person personC2 = em.find( Person.class, personC1.getId() ); + personC2.setName( "Robert" ); + em.merge( personC2 ); + em.getTransaction().commit(); - personCVer2 = new Person(personC2.getId(), personC2.getName()); - personCVer2.getPersonBTuples().add(tuple2Ver1); + personCVer2 = new Person( personC2.getId(), personC2.getName() ); + personCVer2.getPersonBTuples().add( tuple2Ver1 ); - em.close(); - } + em.close(); + } - @Test - public void testRevisionsCounts() { - Assert.assertEquals(Arrays.asList(1), getAuditReader().getRevisions(PersonTuple.class, tuple1Ver1.getPersonTupleId())); - Assert.assertEquals(Arrays.asList(2, 3), getAuditReader().getRevisions(PersonTuple.class, tuple2Ver1.getPersonTupleId())); - Assert.assertEquals(Arrays.asList(2, 4), getAuditReader().getRevisions(Person.class, personCVer1.getId())); - } + @Test + public void testRevisionsCounts() { + Assert.assertEquals( + Arrays.asList( 1 ), getAuditReader().getRevisions( + PersonTuple.class, + tuple1Ver1.getPersonTupleId() + ) + ); + Assert.assertEquals( + Arrays.asList( 2, 3 ), getAuditReader().getRevisions( + PersonTuple.class, + tuple2Ver1.getPersonTupleId() + ) + ); + Assert.assertEquals( + Arrays.asList( 2, 4 ), getAuditReader().getRevisions( + Person.class, + personCVer1.getId() + ) + ); + } - @Test - public void testHistoryOfTuple1() { - PersonTuple tuple = getAuditReader().find(PersonTuple.class, tuple1Ver1.getPersonTupleId(), 1); + @Test + public void testHistoryOfTuple1() { + PersonTuple tuple = getAuditReader().find( PersonTuple.class, tuple1Ver1.getPersonTupleId(), 1 ); - Assert.assertEquals(tuple1Ver1, tuple); - Assert.assertEquals(tuple1Ver1.isHelloWorld(), tuple.isHelloWorld()); - Assert.assertEquals(tuple1Ver1.getPersonA().getId(), tuple.getPersonA().getId()); - Assert.assertEquals(tuple1Ver1.getPersonB().getId(), tuple.getPersonB().getId()); - } + Assert.assertEquals( tuple1Ver1, tuple ); + Assert.assertEquals( tuple1Ver1.isHelloWorld(), tuple.isHelloWorld() ); + Assert.assertEquals( tuple1Ver1.getPersonA().getId(), tuple.getPersonA().getId() ); + Assert.assertEquals( tuple1Ver1.getPersonB().getId(), tuple.getPersonB().getId() ); + } - @Test - public void testHistoryOfTuple2() { - PersonTuple tuple = getAuditReader().find(PersonTuple.class, tuple2Ver2.getPersonTupleId(), 2); + @Test + public void testHistoryOfTuple2() { + PersonTuple tuple = getAuditReader().find( PersonTuple.class, tuple2Ver2.getPersonTupleId(), 2 ); - Assert.assertEquals(tuple2Ver1, tuple); - Assert.assertEquals(tuple2Ver1.isHelloWorld(), tuple.isHelloWorld()); - Assert.assertEquals(tuple2Ver1.getPersonA().getId(), tuple.getPersonA().getId()); - Assert.assertEquals(tuple2Ver1.getPersonB().getId(), tuple.getPersonB().getId()); + Assert.assertEquals( tuple2Ver1, tuple ); + Assert.assertEquals( tuple2Ver1.isHelloWorld(), tuple.isHelloWorld() ); + Assert.assertEquals( tuple2Ver1.getPersonA().getId(), tuple.getPersonA().getId() ); + Assert.assertEquals( tuple2Ver1.getPersonB().getId(), tuple.getPersonB().getId() ); - tuple = getAuditReader().find(PersonTuple.class, tuple2Ver2.getPersonTupleId(), 3); + tuple = getAuditReader().find( PersonTuple.class, tuple2Ver2.getPersonTupleId(), 3 ); - Assert.assertEquals(tuple2Ver2, tuple); - Assert.assertEquals(tuple2Ver2.isHelloWorld(), tuple.isHelloWorld()); - Assert.assertEquals(tuple2Ver2.getPersonA().getId(), tuple.getPersonA().getId()); - Assert.assertEquals(tuple2Ver2.getPersonB().getId(), tuple.getPersonB().getId()); - } + Assert.assertEquals( tuple2Ver2, tuple ); + Assert.assertEquals( tuple2Ver2.isHelloWorld(), tuple.isHelloWorld() ); + Assert.assertEquals( tuple2Ver2.getPersonA().getId(), tuple.getPersonA().getId() ); + Assert.assertEquals( tuple2Ver2.getPersonB().getId(), tuple.getPersonB().getId() ); + } - @Test - public void testHistoryOfPersonC() { - Person person = getAuditReader().find(Person.class, personCVer1.getId(), 2); + @Test + public void testHistoryOfPersonC() { + Person person = getAuditReader().find( Person.class, personCVer1.getId(), 2 ); - Assert.assertEquals(personCVer1, person); - Assert.assertEquals(personCVer1.getPersonATuples(), person.getPersonATuples()); - Assert.assertEquals(personCVer1.getPersonBTuples(), person.getPersonBTuples()); + Assert.assertEquals( personCVer1, person ); + Assert.assertEquals( personCVer1.getPersonATuples(), person.getPersonATuples() ); + Assert.assertEquals( personCVer1.getPersonBTuples(), person.getPersonBTuples() ); - person = getAuditReader().find(Person.class, personCVer2.getId(), 4); + person = getAuditReader().find( Person.class, personCVer2.getId(), 4 ); - Assert.assertEquals(personCVer2, person); - } + Assert.assertEquals( personCVer2, person ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/embeddedid/Person.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/embeddedid/Person.java index 5c834a651d..bb71de9a43 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/embeddedid/Person.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/embeddedid/Person.java @@ -1,12 +1,12 @@ package org.hibernate.envers.test.integration.onetomany.embeddedid; -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; import org.hibernate.envers.Audited; @@ -16,84 +16,92 @@ import org.hibernate.envers.Audited; @Entity @Audited public class Person implements Serializable { - @Id - @GeneratedValue - private long id; + @Id + @GeneratedValue + private long id; - private String name; + private String name; - @OneToMany(mappedBy = "personA") - private Set personATuples = new HashSet(); + @OneToMany(mappedBy = "personA") + private Set personATuples = new HashSet(); - @OneToMany(mappedBy = "personB") - private Set personBTuples = new HashSet(); + @OneToMany(mappedBy = "personB") + private Set personBTuples = new HashSet(); - public Person() { - } + public Person() { + } - public Person(String name) { - this.name = name; - } + public Person(String name) { + this.name = name; + } - public Person(long id, String name) { - this.id = id; - this.name = name; - } + public Person(long id, String name) { + this.id = id; + this.name = name; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Person)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Person) ) { + return false; + } - Person person = (Person) o; + Person person = (Person) o; - if (id != person.id) return false; - if (name != null ? !name.equals(person.name) : person.name != null) return false; + if ( id != person.id ) { + return false; + } + if ( name != null ? !name.equals( person.name ) : person.name != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = (int) (id ^ (id >>> 32)); - result = 31 * result + (name != null ? name.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = (int) (id ^ (id >>> 32)); + result = 31 * result + (name != null ? name.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "Person(id = " + id + ", name = " + name + ")"; - } + @Override + public String toString() { + return "Person(id = " + id + ", name = " + name + ")"; + } - public long getId() { - return id; - } + public long getId() { + return id; + } - public void setId(long id) { - this.id = id; - } + public void setId(long id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Set getPersonBTuples() { - return personBTuples; - } + public Set getPersonBTuples() { + return personBTuples; + } - public void setPersonBTuples(Set personBTuples) { - this.personBTuples = personBTuples; - } + public void setPersonBTuples(Set personBTuples) { + this.personBTuples = personBTuples; + } - public Set getPersonATuples() { - return personATuples; - } + public Set getPersonATuples() { + return personATuples; + } - public void setPersonATuples(Set personATuples) { - this.personATuples = personATuples; - } + public void setPersonATuples(Set personATuples) { + this.personATuples = personATuples; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/embeddedid/PersonTuple.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/embeddedid/PersonTuple.java index 0767999040..4a452ad679 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/embeddedid/PersonTuple.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/embeddedid/PersonTuple.java @@ -1,6 +1,5 @@ package org.hibernate.envers.test.integration.onetomany.embeddedid; -import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.EmbeddedId; @@ -8,6 +7,7 @@ import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.MapsId; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -17,164 +17,178 @@ import org.hibernate.envers.Audited; @Entity @Audited public class PersonTuple implements Serializable { - @Embeddable - public static class PersonTupleId implements Serializable { - @Column(nullable = false) - private long personAId; + @Embeddable + public static class PersonTupleId implements Serializable { + @Column(nullable = false) + private long personAId; - @Column(nullable = false) - private long personBId; + @Column(nullable = false) + private long personBId; - @Column(nullable = false) - private String constantId; + @Column(nullable = false) + private String constantId; - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof PersonTupleId)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof PersonTupleId) ) { + return false; + } - PersonTupleId that = (PersonTupleId) o; + PersonTupleId that = (PersonTupleId) o; - if (personAId != that.personAId) return false; - if (personBId != that.personBId) return false; - if (constantId != null ? !constantId.equals(that.constantId) : that.constantId != null) return false; + if ( personAId != that.personAId ) { + return false; + } + if ( personBId != that.personBId ) { + return false; + } + if ( constantId != null ? !constantId.equals( that.constantId ) : that.constantId != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = (int) (personAId ^ (personAId >>> 32)); - result = 31 * result + (int) (personBId ^ (personBId >>> 32)); - result = 31 * result + (constantId != null ? constantId.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = (int) (personAId ^ (personAId >>> 32)); + result = 31 * result + (int) (personBId ^ (personBId >>> 32)); + result = 31 * result + (constantId != null ? constantId.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "PersonTupleId(personAId = " + personAId + ", personBId = " + personBId + ", constantId = " + constantId + ")"; - } + @Override + public String toString() { + return "PersonTupleId(personAId = " + personAId + ", personBId = " + personBId + ", constantId = " + constantId + ")"; + } - public long getPersonAId() { - return personAId; - } + public long getPersonAId() { + return personAId; + } - public void setPersonAId(long personAId) { - this.personAId = personAId; - } + public void setPersonAId(long personAId) { + this.personAId = personAId; + } - public long getPersonBId() { - return personBId; - } + public long getPersonBId() { + return personBId; + } - public void setPersonBId(long personBId) { - this.personBId = personBId; - } + public void setPersonBId(long personBId) { + this.personBId = personBId; + } - public String getConstantId() { - return constantId; - } + public String getConstantId() { + return constantId; + } - public void setConstantId(String constantId) { - this.constantId = constantId; - } - } + public void setConstantId(String constantId) { + this.constantId = constantId; + } + } - @EmbeddedId - private PersonTupleId personTupleId = new PersonTupleId(); + @EmbeddedId + private PersonTupleId personTupleId = new PersonTupleId(); - @MapsId("personAId") - @ManyToOne(optional = false) - @JoinColumn(insertable = false, updatable = false, nullable=false) - private Person personA; + @MapsId("personAId") + @ManyToOne(optional = false) + @JoinColumn(insertable = false, updatable = false, nullable = false) + private Person personA; - @MapsId("personBId") - @ManyToOne(optional = false) - @JoinColumn(insertable = false, updatable = false, nullable=false) - private Person personB; + @MapsId("personBId") + @ManyToOne(optional = false) + @JoinColumn(insertable = false, updatable = false, nullable = false) + private Person personB; - @MapsId("constantId") - @ManyToOne(optional = false) - @JoinColumn(insertable = false, updatable = false, nullable=false) - private Constant constant; + @MapsId("constantId") + @ManyToOne(optional = false) + @JoinColumn(insertable = false, updatable = false, nullable = false) + private Constant constant; - @Column(nullable = false) - private boolean helloWorld = false; + @Column(nullable = false) + private boolean helloWorld = false; - public PersonTuple() { - } + public PersonTuple() { + } - public PersonTuple(boolean helloWorld, Person personA, Person personB, Constant constant) { - this.helloWorld = helloWorld; - this.personA = personA; - this.personB = personB; - this.constant = constant; + public PersonTuple(boolean helloWorld, Person personA, Person personB, Constant constant) { + this.helloWorld = helloWorld; + this.personA = personA; + this.personB = personB; + this.constant = constant; - this.personTupleId.personAId = personA.getId(); - this.personTupleId.personBId = personB.getId(); - this.personTupleId.constantId = constant.getId(); + this.personTupleId.personAId = personA.getId(); + this.personTupleId.personBId = personB.getId(); + this.personTupleId.constantId = constant.getId(); - personA.getPersonATuples().add(this); - personB.getPersonBTuples().add(this); - } + personA.getPersonATuples().add( this ); + personB.getPersonBTuples().add( this ); + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof PersonTuple)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof PersonTuple) ) { + return false; + } - PersonTuple that = (PersonTuple) o; + PersonTuple that = (PersonTuple) o; - return personTupleId.equals(that.personTupleId); - } + return personTupleId.equals( that.personTupleId ); + } - @Override - public int hashCode() { - return personTupleId.hashCode(); - } + @Override + public int hashCode() { + return personTupleId.hashCode(); + } - @Override - public String toString() { - return "PersonTuple(id = " + personTupleId + ", helloWorld = " + helloWorld + ")"; - } + @Override + public String toString() { + return "PersonTuple(id = " + personTupleId + ", helloWorld = " + helloWorld + ")"; + } - public PersonTupleId getPersonTupleId() { - return personTupleId; - } + public PersonTupleId getPersonTupleId() { + return personTupleId; + } - public void setPersonTupleId(PersonTupleId personTupleId) { - this.personTupleId = personTupleId; - } + public void setPersonTupleId(PersonTupleId personTupleId) { + this.personTupleId = personTupleId; + } - public Person getPersonA() { - return personA; - } + public Person getPersonA() { + return personA; + } - public void setPersonA(Person personA) { - this.personA = personA; - } + public void setPersonA(Person personA) { + this.personA = personA; + } - public Person getPersonB() { - return personB; - } + public Person getPersonB() { + return personB; + } - public void setPersonB(Person personB) { - this.personB = personB; - } + public void setPersonB(Person personB) { + this.personB = personB; + } - public Constant getConstant() { - return constant; - } + public Constant getConstant() { + return constant; + } - public void setConstant(Constant constant) { - this.constant = constant; - } + public void setConstant(Constant constant) { + this.constant = constant; + } - public boolean isHelloWorld() { - return helloWorld; - } + public boolean isHelloWorld() { + return helloWorld; + } - public void setHelloWorld(boolean helloWorld) { - this.helloWorld = helloWorld; - } + public void setHelloWorld(boolean helloWorld) { + this.helloWorld = helloWorld; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/hierarchy/HierarchyTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/hierarchy/HierarchyTest.java index ea7cef8db2..d9dbd07e60 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/hierarchy/HierarchyTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/hierarchy/HierarchyTest.java @@ -1,14 +1,15 @@ package org.hibernate.envers.test.integration.onetomany.hierarchy; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.tools.TestTools; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -16,92 +17,92 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-6661") public class HierarchyTest extends BaseEnversJPAFunctionalTestCase { - private Long parentId = null; - private Long child1Id = null; - private Long child2Id = null; + private Long parentId = null; + private Long child1Id = null; + private Long child2Id = null; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { Node.class }; - } + return new Class[] {Node.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 1 - em.getTransaction().begin(); - Node parent = new Node("parent", (Node)null); - Node child1 = new Node("child1", parent); - Node child2 = new Node("child2", parent); - parent.getChildren().add(child1); - parent.getChildren().add(child2); - em.persist(parent); - em.persist(child1); - em.persist(child2); - em.getTransaction().commit(); + // Revision 1 + em.getTransaction().begin(); + Node parent = new Node( "parent", (Node) null ); + Node child1 = new Node( "child1", parent ); + Node child2 = new Node( "child2", parent ); + parent.getChildren().add( child1 ); + parent.getChildren().add( child2 ); + em.persist( parent ); + em.persist( child1 ); + em.persist( child2 ); + em.getTransaction().commit(); - parentId = parent.getId(); - child1Id = child1.getId(); - child2Id = child2.getId(); + parentId = parent.getId(); + child1Id = child1.getId(); + child2Id = child2.getId(); - // Revision 2 - em.getTransaction().begin(); - parent = em.find(Node.class, parent.getId()); - parent.getChildren().get(0).setData("child1 modified"); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + parent = em.find( Node.class, parent.getId() ); + parent.getChildren().get( 0 ).setData( "child1 modified" ); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); - child2 = em.find(Node.class, child2.getId()); - em.remove(child2); - em.getTransaction().commit(); - } + // Revision 3 + em.getTransaction().begin(); + child2 = em.find( Node.class, child2.getId() ); + em.remove( child2 ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - Assert.assertEquals(Arrays.asList(1, 3), getAuditReader().getRevisions(Node.class, parentId)); - Assert.assertEquals(Arrays.asList(1, 2), getAuditReader().getRevisions(Node.class, child1Id)); - Assert.assertEquals(Arrays.asList(1, 3), getAuditReader().getRevisions(Node.class, child2Id)); - } + @Test + public void testRevisionsCounts() { + Assert.assertEquals( Arrays.asList( 1, 3 ), getAuditReader().getRevisions( Node.class, parentId ) ); + Assert.assertEquals( Arrays.asList( 1, 2 ), getAuditReader().getRevisions( Node.class, child1Id ) ); + Assert.assertEquals( Arrays.asList( 1, 3 ), getAuditReader().getRevisions( Node.class, child2Id ) ); + } - @Test - public void testHistoryOfParentNode() { - Node parent = new Node("parent", parentId); - Node child1 = new Node("child1", child1Id); - Node child2 = new Node("child2", child2Id); + @Test + public void testHistoryOfParentNode() { + Node parent = new Node( "parent", parentId ); + Node child1 = new Node( "child1", child1Id ); + Node child2 = new Node( "child2", child2Id ); - Node ver1 = getAuditReader().find(Node.class, parentId, 1); - Assert.assertEquals(parent, ver1); - Assert.assertTrue(TestTools.checkList(ver1.getChildren(), child1, child2)); + Node ver1 = getAuditReader().find( Node.class, parentId, 1 ); + Assert.assertEquals( parent, ver1 ); + Assert.assertTrue( TestTools.checkList( ver1.getChildren(), child1, child2 ) ); - child1.setData("child1 modified"); + child1.setData( "child1 modified" ); - Node ver2 = getAuditReader().find(Node.class, parentId, 2); - Assert.assertEquals(parent, ver2); - Assert.assertTrue(TestTools.checkList(ver2.getChildren(), child1, child2)); + Node ver2 = getAuditReader().find( Node.class, parentId, 2 ); + Assert.assertEquals( parent, ver2 ); + Assert.assertTrue( TestTools.checkList( ver2.getChildren(), child1, child2 ) ); - Node ver3 = getAuditReader().find(Node.class, parentId, 3); - Assert.assertEquals(parent, ver3); - Assert.assertTrue(TestTools.checkList(ver3.getChildren(), child1)); - } + Node ver3 = getAuditReader().find( Node.class, parentId, 3 ); + Assert.assertEquals( parent, ver3 ); + Assert.assertTrue( TestTools.checkList( ver3.getChildren(), child1 ) ); + } - @Test - public void testHistoryOfChild1Node() { - Node parent = new Node("parent", parentId); - Node child1 = new Node("child1", child1Id); + @Test + public void testHistoryOfChild1Node() { + Node parent = new Node( "parent", parentId ); + Node child1 = new Node( "child1", child1Id ); - Node ver1 = getAuditReader().find(Node.class, child1Id, 1); - Assert.assertEquals(child1, ver1); - Assert.assertEquals(parent.getId(), ver1.getParent().getId()); - Assert.assertEquals(parent.getData(), ver1.getParent().getData()); + Node ver1 = getAuditReader().find( Node.class, child1Id, 1 ); + Assert.assertEquals( child1, ver1 ); + Assert.assertEquals( parent.getId(), ver1.getParent().getId() ); + Assert.assertEquals( parent.getData(), ver1.getParent().getData() ); - child1.setData("child1 modified"); + child1.setData( "child1 modified" ); - Node ver2 = getAuditReader().find(Node.class, child1Id, 2); - Assert.assertEquals(child1, ver2); - Assert.assertEquals(parent.getId(), ver2.getParent().getId()); - Assert.assertEquals(parent.getData(), ver2.getParent().getData()); - } + Node ver2 = getAuditReader().find( Node.class, child1Id, 2 ); + Assert.assertEquals( child1, ver2 ); + Assert.assertEquals( parent.getId(), ver2.getParent().getId() ); + Assert.assertEquals( parent.getData(), ver2.getParent().getData() ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/hierarchy/Node.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/hierarchy/Node.java index c8265cb50c..e936e19b06 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/hierarchy/Node.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/hierarchy/Node.java @@ -1,8 +1,5 @@ package org.hibernate.envers.test.integration.onetomany.hierarchy; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; @@ -12,6 +9,9 @@ import javax.persistence.JoinTable; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; import org.hibernate.envers.AuditJoinTable; import org.hibernate.envers.Audited; @@ -23,90 +23,98 @@ import org.hibernate.envers.Audited; @Table(name = "NODES") @Audited public class Node implements Serializable { - @Id - @GeneratedValue - private Long id; + @Id + @GeneratedValue + private Long id; - private String data; + private String data; - @ManyToOne(fetch = FetchType.LAZY, optional = true) - @AuditJoinTable(name = "NODES_JOIN_TABLE_AUD", - inverseJoinColumns = {@JoinColumn(name = "PARENT_ID", nullable = true, updatable = false)}) - @JoinTable(name = "NODES_JOIN_TABLE", - joinColumns = {@JoinColumn(name = "CHILD_ID", nullable = true, updatable = false)}, - inverseJoinColumns = {@JoinColumn(name = "PARENT_ID", nullable = true, updatable = false)}) - private Node parent; + @ManyToOne(fetch = FetchType.LAZY, optional = true) + @AuditJoinTable(name = "NODES_JOIN_TABLE_AUD", + inverseJoinColumns = {@JoinColumn(name = "PARENT_ID", nullable = true, updatable = false)}) + @JoinTable(name = "NODES_JOIN_TABLE", + joinColumns = {@JoinColumn(name = "CHILD_ID", nullable = true, updatable = false)}, + inverseJoinColumns = {@JoinColumn(name = "PARENT_ID", nullable = true, updatable = false)}) + private Node parent; - @OneToMany(mappedBy = "parent") - private List children = new ArrayList(); + @OneToMany(mappedBy = "parent") + private List children = new ArrayList(); - public Node() { - } + public Node() { + } - public Node(String data, Node parent) { - this.data = data; - this.parent = parent; - } + public Node(String data, Node parent) { + this.data = data; + this.parent = parent; + } - public Node(String data, Long id) { - this.id = id; - this.data = data; - } + public Node(String data, Long id) { + this.id = id; + this.data = data; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Node)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Node) ) { + return false; + } - Node node = (Node) o; + Node node = (Node) o; - if (data != null ? !data.equals(node.data) : node.data != null) return false; - if (id != null ? !id.equals(node.id) : node.id != null) return false; + if ( data != null ? !data.equals( node.data ) : node.data != null ) { + return false; + } + if ( id != null ? !id.equals( node.id ) : node.id != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = id != null ? id.hashCode() : 0; - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = id != null ? id.hashCode() : 0; + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "Node(id = " + id + ", data = " + data + ")"; - } + @Override + public String toString() { + return "Node(id = " + id + ", data = " + data + ")"; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Node getParent() { - return parent; - } + public Node getParent() { + return parent; + } - public void setParent(Node parent) { - this.parent = parent; - } + public void setParent(Node parent) { + this.parent = parent; + } - public List getChildren() { - return children; - } + public List getChildren() { + return children; + } - public void setChildren(List children) { - this.children = children; - } + public void setChildren(List children) { + this.children = children; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/DetailSubclass.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/DetailSubclass.java index 5216b11333..0ba21bef2a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/DetailSubclass.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/DetailSubclass.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.integration.onetomany.inverseToSuperclass; + import org.hibernate.envers.Audited; @Audited diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/DetailSubclass2.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/DetailSubclass2.java index ec3c111e34..fc453ad97c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/DetailSubclass2.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/DetailSubclass2.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.integration.onetomany.inverseToSuperclass; + import org.hibernate.envers.Audited; @Audited @@ -7,7 +8,7 @@ public class DetailSubclass2 extends DetailSubclass { private String str3; public DetailSubclass2() { - + } public String getStr3() { diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/DetailSuperclass.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/DetailSuperclass.java index 11de49656f..bfcf346250 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/DetailSuperclass.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/DetailSuperclass.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.integration.onetomany.inverseToSuperclass; + import org.hibernate.envers.Audited; @Audited diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/Master.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/Master.java index ba6dccb7a1..bf3a87dc67 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/Master.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/Master.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.integration.onetomany.inverseToSuperclass; + import java.util.List; import org.hibernate.envers.Audited; diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/OneToManyInverseToSuperclassTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/OneToManyInverseToSuperclassTest.java index 0097db671b..68daa68379 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/OneToManyInverseToSuperclassTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetomany/inverseToSuperclass/OneToManyInverseToSuperclassTest.java @@ -1,16 +1,15 @@ package org.hibernate.envers.test.integration.onetomany.inverseToSuperclass; -import java.util.ArrayList; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.ArrayList; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Hern�n Chanfreau - * */ public class OneToManyInverseToSuperclassTest extends BaseEnversJPAFunctionalTestCase { @@ -19,11 +18,11 @@ public class OneToManyInverseToSuperclassTest extends BaseEnversJPAFunctionalTes @Override protected String[] getMappings() { - return new String[] { "mappings/oneToMany/inverseToSuperclass/mappings.hbm.xml" }; + return new String[] {"mappings/oneToMany/inverseToSuperclass/mappings.hbm.xml"}; } @Test - @Priority(10) + @Priority(10) public void initData() { EntityManager em = getEntityManager(); @@ -34,66 +33,66 @@ public class OneToManyInverseToSuperclassTest extends BaseEnversJPAFunctionalTes // Revision 1 em.getTransaction().begin(); - det1.setStr2("detail 1"); + det1.setStr2( "detail 1" ); - m1.setStr("master"); - m1.setItems(new ArrayList()); - m1.getItems().add(det1); - det1.setParent(m1); + m1.setStr( "master" ); + m1.setItems( new ArrayList() ); + m1.getItems().add( det1 ); + det1.setParent( m1 ); - em.persist(m1); + em.persist( m1 ); em.getTransaction().commit(); m1_id = m1.getId(); // Revision 2 em.getTransaction().begin(); - m1 = em.find(Master.class, m1_id); + m1 = em.find( Master.class, m1_id ); - det2.setStr2("detail 2"); - det2.setParent(m1); - m1.getItems().add(det2); + det2.setStr2( "detail 2" ); + det2.setParent( m1 ); + m1.getItems().add( det2 ); em.getTransaction().commit(); // Revision 3 em.getTransaction().begin(); - m1 = em.find(Master.class, m1_id); - m1.setStr("new master"); + m1 = em.find( Master.class, m1_id ); + m1.setStr( "new master" ); - det1 = m1.getItems().get(0); - det1.setStr2("new detail"); + det1 = m1.getItems().get( 0 ); + det1.setStr2( "new detail" ); DetailSubclass det3 = new DetailSubclass2(); - det3.setStr2("detail 3"); - det3.setParent(m1); + det3.setStr2( "detail 3" ); + det3.setParent( m1 ); - m1.getItems().get(1).setParent(null); + m1.getItems().get( 1 ).setParent( null ); // m1.getItems().remove(1); - m1.getItems().add(det3); + m1.getItems().add( det3 ); - em.persist(m1); + em.persist( m1 ); em.getTransaction().commit(); // Revision 4 em.getTransaction().begin(); - m1 = em.find(Master.class, m1_id); + m1 = em.find( Master.class, m1_id ); - det1 = m1.getItems().get(0); - det1.setParent(null); + det1 = m1.getItems().get( 0 ); + det1.setParent( null ); // m1.getItems().remove(det1); - em.persist(m1); + em.persist( m1 ); em.getTransaction().commit(); } @Test public void testHistoryExists() { - Master rev1_1 = getAuditReader().find(Master.class, m1_id, 1); - Master rev1_2 = getAuditReader().find(Master.class, m1_id, 2); - Master rev1_3 = getAuditReader().find(Master.class, m1_id, 3); - Master rev1_4 = getAuditReader().find(Master.class, m1_id, 4); + Master rev1_1 = getAuditReader().find( Master.class, m1_id, 1 ); + Master rev1_2 = getAuditReader().find( Master.class, m1_id, 2 ); + Master rev1_3 = getAuditReader().find( Master.class, m1_id, 3 ); + Master rev1_4 = getAuditReader().find( Master.class, m1_id, 4 ); assert (rev1_1 != null); assert (rev1_2 != null); diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BiRefEdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BiRefEdEntity.java index 068c178af9..6cb675f524 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BiRefEdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BiRefEdEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.onetoone.bidirectional; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToOne; @@ -33,70 +34,78 @@ import org.hibernate.envers.Audited; */ @Entity public class BiRefEdEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToOne(mappedBy="reference") - private BiRefIngEntity referencing; + @Audited + @OneToOne(mappedBy = "reference") + private BiRefIngEntity referencing; - public BiRefEdEntity() { - } + public BiRefEdEntity() { + } - public BiRefEdEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public BiRefEdEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public BiRefEdEntity(Integer id, String data, BiRefIngEntity referencing) { - this.id = id; - this.data = data; - this.referencing = referencing; - } + public BiRefEdEntity(Integer id, String data, BiRefIngEntity referencing) { + this.id = id; + this.data = data; + this.referencing = referencing; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public BiRefIngEntity getReferencing() { - return referencing; - } + public BiRefIngEntity getReferencing() { + return referencing; + } - public void setReferencing(BiRefIngEntity referencing) { - this.referencing = referencing; - } + public void setReferencing(BiRefIngEntity referencing) { + this.referencing = referencing; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof BiRefEdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof BiRefEdEntity) ) { + return false; + } - BiRefEdEntity that = (BiRefEdEntity) o; + BiRefEdEntity that = (BiRefEdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BiRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BiRefIngEntity.java index b7ef5a7863..dabc358929 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BiRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BiRefIngEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.onetoone.bidirectional; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToOne; @@ -33,70 +34,78 @@ import org.hibernate.envers.Audited; */ @Entity public class BiRefIngEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToOne - private BiRefEdEntity reference; + @Audited + @OneToOne + private BiRefEdEntity reference; - public BiRefIngEntity() { - } + public BiRefIngEntity() { + } - public BiRefIngEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public BiRefIngEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public BiRefIngEntity(Integer id, String data, BiRefEdEntity reference) { - this.id = id; - this.data = data; - this.reference = reference; - } + public BiRefIngEntity(Integer id, String data, BiRefEdEntity reference) { + this.id = id; + this.data = data; + this.reference = reference; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public BiRefEdEntity getReference() { - return reference; - } + public BiRefEdEntity getReference() { + return reference; + } - public void setReference(BiRefEdEntity reference) { - this.reference = reference; - } + public void setReference(BiRefEdEntity reference) { + this.reference = reference; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof BiRefIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof BiRefIngEntity) ) { + return false; + } - BiRefIngEntity that = (BiRefIngEntity) o; + BiRefIngEntity that = (BiRefIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/Bidirectional.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/Bidirectional.java index b83e565367..bc5086049f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/Bidirectional.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/Bidirectional.java @@ -23,94 +23,94 @@ */ package org.hibernate.envers.test.integration.onetoone.bidirectional; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class Bidirectional extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; + private Integer ing1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BiRefEdEntity.class, BiRefIngEntity.class }; - } + return new Class[] {BiRefEdEntity.class, BiRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - BiRefEdEntity ed1 = new BiRefEdEntity(1, "data_ed_1"); - BiRefEdEntity ed2 = new BiRefEdEntity(2, "data_ed_2"); + @Test + @Priority(10) + public void initData() { + BiRefEdEntity ed1 = new BiRefEdEntity( 1, "data_ed_1" ); + BiRefEdEntity ed2 = new BiRefEdEntity( 2, "data_ed_2" ); - BiRefIngEntity ing1 = new BiRefIngEntity(3, "data_ing_1"); + BiRefIngEntity ing1 = new BiRefIngEntity( 3, "data_ing_1" ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - ing1.setReference(ed1); + ing1.setReference( ed1 ); - em.persist(ed1); - em.persist(ed2); + em.persist( ed1 ); + em.persist( ed2 ); - em.persist(ing1); + em.persist( ing1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ing1 = em.find(BiRefIngEntity.class, ing1.getId()); - ed2 = em.find(BiRefEdEntity.class, ed2.getId()); + ing1 = em.find( BiRefIngEntity.class, ing1.getId() ); + ed2 = em.find( BiRefEdEntity.class, ed2.getId() ); - ing1.setReference(ed2); + ing1.setReference( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); - ing1_id = ing1.getId(); - } + ing1_id = ing1.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(BiRefEdEntity.class, ed1_id)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(BiRefEdEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( BiRefEdEntity.class, ed1_id ) ); + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( BiRefEdEntity.class, ed2_id ) ); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(BiRefIngEntity.class, ing1_id)); - } + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( BiRefIngEntity.class, ing1_id ) ); + } - @Test - public void testHistoryOfEdId1() { - BiRefIngEntity ing1 = getEntityManager().find(BiRefIngEntity.class, ing1_id); + @Test + public void testHistoryOfEdId1() { + BiRefIngEntity ing1 = getEntityManager().find( BiRefIngEntity.class, ing1_id ); - BiRefEdEntity rev1 = getAuditReader().find(BiRefEdEntity.class, ed1_id, 1); - BiRefEdEntity rev2 = getAuditReader().find(BiRefEdEntity.class, ed1_id, 2); + BiRefEdEntity rev1 = getAuditReader().find( BiRefEdEntity.class, ed1_id, 1 ); + BiRefEdEntity rev2 = getAuditReader().find( BiRefEdEntity.class, ed1_id, 2 ); - assert rev1.getReferencing().equals(ing1); - assert rev2.getReferencing() == null; - } + assert rev1.getReferencing().equals( ing1 ); + assert rev2.getReferencing() == null; + } - @Test - public void testHistoryOfEdId2() { - BiRefIngEntity ing1 = getEntityManager().find(BiRefIngEntity.class, ing1_id); + @Test + public void testHistoryOfEdId2() { + BiRefIngEntity ing1 = getEntityManager().find( BiRefIngEntity.class, ing1_id ); - BiRefEdEntity rev1 = getAuditReader().find(BiRefEdEntity.class, ed2_id, 1); - BiRefEdEntity rev2 = getAuditReader().find(BiRefEdEntity.class, ed2_id, 2); - - assert rev1.getReferencing() == null; - assert rev2.getReferencing().equals(ing1); - } + BiRefEdEntity rev1 = getAuditReader().find( BiRefEdEntity.class, ed2_id, 1 ); + BiRefEdEntity rev2 = getAuditReader().find( BiRefEdEntity.class, ed2_id, 2 ); + + assert rev1.getReferencing() == null; + assert rev2.getReferencing().equals( ing1 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/Bidirectional2.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/Bidirectional2.java index 6ddfcc0084..20bd984779 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/Bidirectional2.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/Bidirectional2.java @@ -23,129 +23,129 @@ */ package org.hibernate.envers.test.integration.onetoone.bidirectional; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class Bidirectional2 extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BiRefEdEntity.class, BiRefIngEntity.class }; - } + return new Class[] {BiRefEdEntity.class, BiRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - BiRefEdEntity ed1 = new BiRefEdEntity(1, "data_ed_1"); - BiRefEdEntity ed2 = new BiRefEdEntity(2, "data_ed_2"); + @Test + @Priority(10) + public void initData() { + BiRefEdEntity ed1 = new BiRefEdEntity( 1, "data_ed_1" ); + BiRefEdEntity ed2 = new BiRefEdEntity( 2, "data_ed_2" ); - BiRefIngEntity ing1 = new BiRefIngEntity(3, "data_ing_1"); - BiRefIngEntity ing2 = new BiRefIngEntity(4, "data_ing_2"); + BiRefIngEntity ing1 = new BiRefIngEntity( 3, "data_ing_1" ); + BiRefIngEntity ing2 = new BiRefIngEntity( 4, "data_ing_2" ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); + em.persist( ed1 ); + em.persist( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ed1 = em.find(BiRefEdEntity.class, ed1.getId()); + ed1 = em.find( BiRefEdEntity.class, ed1.getId() ); - ing1.setReference(ed1); + ing1.setReference( ed1 ); - em.persist(ing1); - em.persist(ing2); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - ed1 = em.find(BiRefEdEntity.class, ed1.getId()); - ing1 = em.find(BiRefIngEntity.class, ing1.getId()); - ing2 = em.find(BiRefIngEntity.class, ing2.getId()); + ed1 = em.find( BiRefEdEntity.class, ed1.getId() ); + ing1 = em.find( BiRefIngEntity.class, ing1.getId() ); + ing2 = em.find( BiRefIngEntity.class, ing2.getId() ); - ing1.setReference(null); - ing2.setReference(ed1); + ing1.setReference( null ); + ing2.setReference( ed1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); + // Revision 4 + em.getTransaction().begin(); - ed2 = em.find(BiRefEdEntity.class, ed2.getId()); - ing1 = em.find(BiRefIngEntity.class, ing1.getId()); - ing2 = em.find(BiRefIngEntity.class, ing2.getId()); + ed2 = em.find( BiRefEdEntity.class, ed2.getId() ); + ing1 = em.find( BiRefIngEntity.class, ing1.getId() ); + ing2 = em.find( BiRefIngEntity.class, ing2.getId() ); - ing1.setReference(ed2); - ing2.setReference(null); + ing1.setReference( ed2 ); + ing2.setReference( null ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); - } + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3, 4).equals(getAuditReader().getRevisions(BiRefEdEntity.class, ed1_id)); - assert Arrays.asList(1, 4).equals(getAuditReader().getRevisions(BiRefEdEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3, 4 ).equals( getAuditReader().getRevisions( BiRefEdEntity.class, ed1_id ) ); + assert Arrays.asList( 1, 4 ).equals( getAuditReader().getRevisions( BiRefEdEntity.class, ed2_id ) ); - assert Arrays.asList(2, 3, 4).equals(getAuditReader().getRevisions(BiRefIngEntity.class, ing1_id)); - assert Arrays.asList(2, 3, 4).equals(getAuditReader().getRevisions(BiRefIngEntity.class, ing2_id)); - } + assert Arrays.asList( 2, 3, 4 ).equals( getAuditReader().getRevisions( BiRefIngEntity.class, ing1_id ) ); + assert Arrays.asList( 2, 3, 4 ).equals( getAuditReader().getRevisions( BiRefIngEntity.class, ing2_id ) ); + } - @Test - public void testHistoryOfEdId1() { - BiRefIngEntity ing1 = getEntityManager().find(BiRefIngEntity.class, ing1_id); - BiRefIngEntity ing2 = getEntityManager().find(BiRefIngEntity.class, ing2_id); + @Test + public void testHistoryOfEdId1() { + BiRefIngEntity ing1 = getEntityManager().find( BiRefIngEntity.class, ing1_id ); + BiRefIngEntity ing2 = getEntityManager().find( BiRefIngEntity.class, ing2_id ); - BiRefEdEntity rev1 = getAuditReader().find(BiRefEdEntity.class, ed1_id, 1); - BiRefEdEntity rev2 = getAuditReader().find(BiRefEdEntity.class, ed1_id, 2); - BiRefEdEntity rev3 = getAuditReader().find(BiRefEdEntity.class, ed1_id, 3); - BiRefEdEntity rev4 = getAuditReader().find(BiRefEdEntity.class, ed1_id, 4); + BiRefEdEntity rev1 = getAuditReader().find( BiRefEdEntity.class, ed1_id, 1 ); + BiRefEdEntity rev2 = getAuditReader().find( BiRefEdEntity.class, ed1_id, 2 ); + BiRefEdEntity rev3 = getAuditReader().find( BiRefEdEntity.class, ed1_id, 3 ); + BiRefEdEntity rev4 = getAuditReader().find( BiRefEdEntity.class, ed1_id, 4 ); - assert rev1.getReferencing() == null; - assert rev2.getReferencing().equals(ing1); - assert rev3.getReferencing().equals(ing2); - assert rev4.getReferencing() == null; - } + assert rev1.getReferencing() == null; + assert rev2.getReferencing().equals( ing1 ); + assert rev3.getReferencing().equals( ing2 ); + assert rev4.getReferencing() == null; + } - @Test - public void testHistoryOfEdId2() { - BiRefIngEntity ing1 = getEntityManager().find(BiRefIngEntity.class, ing1_id); + @Test + public void testHistoryOfEdId2() { + BiRefIngEntity ing1 = getEntityManager().find( BiRefIngEntity.class, ing1_id ); - BiRefEdEntity rev1 = getAuditReader().find(BiRefEdEntity.class, ed2_id, 1); - BiRefEdEntity rev2 = getAuditReader().find(BiRefEdEntity.class, ed2_id, 2); - BiRefEdEntity rev3 = getAuditReader().find(BiRefEdEntity.class, ed2_id, 3); - BiRefEdEntity rev4 = getAuditReader().find(BiRefEdEntity.class, ed2_id, 4); + BiRefEdEntity rev1 = getAuditReader().find( BiRefEdEntity.class, ed2_id, 1 ); + BiRefEdEntity rev2 = getAuditReader().find( BiRefEdEntity.class, ed2_id, 2 ); + BiRefEdEntity rev3 = getAuditReader().find( BiRefEdEntity.class, ed2_id, 3 ); + BiRefEdEntity rev4 = getAuditReader().find( BiRefEdEntity.class, ed2_id, 4 ); - assert rev1.getReferencing() == null; - assert rev2.getReferencing() == null; - assert rev3.getReferencing() == null; - assert rev4.getReferencing().equals(ing1); - } + assert rev1.getReferencing() == null; + assert rev2.getReferencing() == null; + assert rev3.getReferencing() == null; + assert rev4.getReferencing().equals( ing1 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BidirectionalEagerAnnotationTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BidirectionalEagerAnnotationTest.java index b64b7f4e1b..50daacec93 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BidirectionalEagerAnnotationTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BidirectionalEagerAnnotationTest.java @@ -25,12 +25,13 @@ package org.hibernate.envers.test.integration.onetoone.bidirectional; import javax.persistence.EntityManager; -import org.junit.Test; - import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.onetoone.BidirectionalEagerAnnotationRefEdOneToOne; import org.hibernate.envers.test.entities.onetoone.BidirectionalEagerAnnotationRefIngOneToOne; + +import org.junit.Test; + import org.hibernate.testing.TestForIssue; import static org.junit.Assert.assertNotNull; diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BidirectionalEagerHbmTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BidirectionalEagerHbmTest.java index 75c5baf28e..1b5d29d381 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BidirectionalEagerHbmTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BidirectionalEagerHbmTest.java @@ -25,12 +25,13 @@ package org.hibernate.envers.test.integration.onetoone.bidirectional; import javax.persistence.EntityManager; -import org.junit.Test; - import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.onetoone.BidirectionalEagerHbmRefEdPK; import org.hibernate.envers.test.entities.onetoone.BidirectionalEagerHbmRefIngPK; + +import org.junit.Test; + import org.hibernate.testing.TestForIssue; import static org.junit.Assert.assertNotNull; @@ -44,7 +45,7 @@ public class BidirectionalEagerHbmTest extends BaseEnversJPAFunctionalTestCase { @Override protected String[] getMappings() { - return new String[] { "mappings/oneToOne/bidirectional/eagerLoading.hbm.xml" }; + return new String[] {"mappings/oneToOne/bidirectional/eagerLoading.hbm.xml"}; } @Test diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BidirectionalNoNulls.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BidirectionalNoNulls.java index 9f59dda26f..0621c7d925 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BidirectionalNoNulls.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/BidirectionalNoNulls.java @@ -23,107 +23,107 @@ */ package org.hibernate.envers.test.integration.onetoone.bidirectional; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BidirectionalNoNulls extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BiRefEdEntity.class, BiRefIngEntity.class }; - } + return new Class[] {BiRefEdEntity.class, BiRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - BiRefEdEntity ed1 = new BiRefEdEntity(1, "data_ed_1"); - BiRefEdEntity ed2 = new BiRefEdEntity(2, "data_ed_2"); + @Test + @Priority(10) + public void initData() { + BiRefEdEntity ed1 = new BiRefEdEntity( 1, "data_ed_1" ); + BiRefEdEntity ed2 = new BiRefEdEntity( 2, "data_ed_2" ); - BiRefIngEntity ing1 = new BiRefIngEntity(3, "data_ing_1"); - BiRefIngEntity ing2 = new BiRefIngEntity(4, "data_ing_2"); + BiRefIngEntity ing1 = new BiRefIngEntity( 3, "data_ing_1" ); + BiRefIngEntity ing2 = new BiRefIngEntity( 4, "data_ing_2" ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - ing1.setReference(ed1); - ing2.setReference(ed2); + ing1.setReference( ed1 ); + ing2.setReference( ed2 ); - em.persist(ed1); - em.persist(ed2); + em.persist( ed1 ); + em.persist( ed2 ); - em.persist(ing1); - em.persist(ing2); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); + // Revision 2 + em = getEntityManager(); + em.getTransaction().begin(); - ing1 = em.find(BiRefIngEntity.class, ing1.getId()); - ing2 = em.find(BiRefIngEntity.class, ing2.getId()); + ing1 = em.find( BiRefIngEntity.class, ing1.getId() ); + ing2 = em.find( BiRefIngEntity.class, ing2.getId() ); - ed1 = em.find(BiRefEdEntity.class, ed1.getId()); - ed2 = em.find(BiRefEdEntity.class, ed2.getId()); + ed1 = em.find( BiRefEdEntity.class, ed1.getId() ); + ed2 = em.find( BiRefEdEntity.class, ed2.getId() ); - ing1.setReference(ed2); - ing2.setReference(ed1); + ing1.setReference( ed2 ); + ing2.setReference( ed1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); - } + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(BiRefEdEntity.class, ed1_id)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(BiRefEdEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( BiRefEdEntity.class, ed1_id ) ); + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( BiRefEdEntity.class, ed2_id ) ); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(BiRefIngEntity.class, ing1_id)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(BiRefIngEntity.class, ing2_id)); - } + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( BiRefIngEntity.class, ing1_id ) ); + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( BiRefIngEntity.class, ing2_id ) ); + } - @Test - public void testHistoryOfEdId1() { - BiRefIngEntity ing1 = getEntityManager().find(BiRefIngEntity.class, ing1_id); - BiRefIngEntity ing2 = getEntityManager().find(BiRefIngEntity.class, ing2_id); + @Test + public void testHistoryOfEdId1() { + BiRefIngEntity ing1 = getEntityManager().find( BiRefIngEntity.class, ing1_id ); + BiRefIngEntity ing2 = getEntityManager().find( BiRefIngEntity.class, ing2_id ); - BiRefEdEntity rev1 = getAuditReader().find(BiRefEdEntity.class, ed1_id, 1); - BiRefEdEntity rev2 = getAuditReader().find(BiRefEdEntity.class, ed1_id, 2); + BiRefEdEntity rev1 = getAuditReader().find( BiRefEdEntity.class, ed1_id, 1 ); + BiRefEdEntity rev2 = getAuditReader().find( BiRefEdEntity.class, ed1_id, 2 ); - assert rev1.getReferencing().equals(ing1); - assert rev2.getReferencing().equals(ing2); - } + assert rev1.getReferencing().equals( ing1 ); + assert rev2.getReferencing().equals( ing2 ); + } - @Test - public void testHistoryOfEdId2() { - BiRefIngEntity ing1 = getEntityManager().find(BiRefIngEntity.class, ing1_id); - BiRefIngEntity ing2 = getEntityManager().find(BiRefIngEntity.class, ing2_id); + @Test + public void testHistoryOfEdId2() { + BiRefIngEntity ing1 = getEntityManager().find( BiRefIngEntity.class, ing1_id ); + BiRefIngEntity ing2 = getEntityManager().find( BiRefIngEntity.class, ing2_id ); - BiRefEdEntity rev1 = getAuditReader().find(BiRefEdEntity.class, ed2_id, 1); - BiRefEdEntity rev2 = getAuditReader().find(BiRefEdEntity.class, ed2_id, 2); + BiRefEdEntity rev1 = getAuditReader().find( BiRefEdEntity.class, ed2_id, 1 ); + BiRefEdEntity rev2 = getAuditReader().find( BiRefEdEntity.class, ed2_id, 2 ); - assert rev1.getReferencing().equals(ing2); - assert rev2.getReferencing().equals(ing1); - } + assert rev1.getReferencing().equals( ing2 ); + assert rev2.getReferencing().equals( ing1 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/BiEmbIdRefEdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/BiEmbIdRefEdEntity.java index 481406872e..bf6b803054 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/BiEmbIdRefEdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/BiEmbIdRefEdEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.onetoone.bidirectional.ids; + import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.OneToOne; @@ -34,70 +35,78 @@ import org.hibernate.envers.test.entities.ids.EmbId; */ @Entity public class BiEmbIdRefEdEntity { - @EmbeddedId - private EmbId id; + @EmbeddedId + private EmbId id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToOne(mappedBy="reference") - private BiEmbIdRefIngEntity referencing; + @Audited + @OneToOne(mappedBy = "reference") + private BiEmbIdRefIngEntity referencing; - public BiEmbIdRefEdEntity() { - } + public BiEmbIdRefEdEntity() { + } - public BiEmbIdRefEdEntity(EmbId id, String data) { - this.id = id; - this.data = data; - } + public BiEmbIdRefEdEntity(EmbId id, String data) { + this.id = id; + this.data = data; + } - public BiEmbIdRefEdEntity(EmbId id, String data, BiEmbIdRefIngEntity referencing) { - this.id = id; - this.data = data; - this.referencing = referencing; - } + public BiEmbIdRefEdEntity(EmbId id, String data, BiEmbIdRefIngEntity referencing) { + this.id = id; + this.data = data; + this.referencing = referencing; + } - public EmbId getId() { - return id; - } + public EmbId getId() { + return id; + } - public void setId(EmbId id) { - this.id = id; - } + public void setId(EmbId id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public BiEmbIdRefIngEntity getReferencing() { - return referencing; - } + public BiEmbIdRefIngEntity getReferencing() { + return referencing; + } - public void setReferencing(BiEmbIdRefIngEntity referencing) { - this.referencing = referencing; - } + public void setReferencing(BiEmbIdRefIngEntity referencing) { + this.referencing = referencing; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof BiEmbIdRefEdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof BiEmbIdRefEdEntity) ) { + return false; + } - BiEmbIdRefEdEntity that = (BiEmbIdRefEdEntity) o; + BiEmbIdRefEdEntity that = (BiEmbIdRefEdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/BiEmbIdRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/BiEmbIdRefIngEntity.java index 7eb93dedf8..e36bf5b991 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/BiEmbIdRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/BiEmbIdRefIngEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.onetoone.bidirectional.ids; + import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.OneToOne; @@ -34,70 +35,78 @@ import org.hibernate.envers.test.entities.ids.EmbId; */ @Entity public class BiEmbIdRefIngEntity { - @EmbeddedId - private EmbId id; + @EmbeddedId + private EmbId id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToOne - private BiEmbIdRefEdEntity reference; + @Audited + @OneToOne + private BiEmbIdRefEdEntity reference; - public BiEmbIdRefIngEntity() { - } + public BiEmbIdRefIngEntity() { + } - public BiEmbIdRefIngEntity(EmbId id, String data) { - this.id = id; - this.data = data; - } + public BiEmbIdRefIngEntity(EmbId id, String data) { + this.id = id; + this.data = data; + } - public BiEmbIdRefIngEntity(EmbId id, String data, BiEmbIdRefEdEntity reference) { - this.id = id; - this.data = data; - this.reference = reference; - } + public BiEmbIdRefIngEntity(EmbId id, String data, BiEmbIdRefEdEntity reference) { + this.id = id; + this.data = data; + this.reference = reference; + } - public EmbId getId() { - return id; - } + public EmbId getId() { + return id; + } - public void setId(EmbId id) { - this.id = id; - } + public void setId(EmbId id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public BiEmbIdRefEdEntity getReference() { - return reference; - } + public BiEmbIdRefEdEntity getReference() { + return reference; + } - public void setReference(BiEmbIdRefEdEntity reference) { - this.reference = reference; - } + public void setReference(BiEmbIdRefEdEntity reference) { + this.reference = reference; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof BiEmbIdRefIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof BiEmbIdRefIngEntity) ) { + return false; + } - BiEmbIdRefIngEntity that = (BiEmbIdRefIngEntity) o; + BiEmbIdRefIngEntity that = (BiEmbIdRefIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/BiMulIdRefEdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/BiMulIdRefEdEntity.java index 7ee7ee2419..49cb2cefac 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/BiMulIdRefEdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/BiMulIdRefEdEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.onetoone.bidirectional.ids; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; @@ -36,78 +37,88 @@ import org.hibernate.envers.test.entities.ids.MulId; @Entity @IdClass(MulId.class) public class BiMulIdRefEdEntity { - @Id - private Integer id1; + @Id + private Integer id1; - @Id - private Integer id2; + @Id + private Integer id2; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToOne(mappedBy="reference") - private BiMulIdRefIngEntity referencing; + @Audited + @OneToOne(mappedBy = "reference") + private BiMulIdRefIngEntity referencing; - public BiMulIdRefEdEntity() { - } + public BiMulIdRefEdEntity() { + } - public BiMulIdRefEdEntity(Integer id1, Integer id2, String data) { - this.id1 = id1; - this.id2 = id2; - this.data = data; - } + public BiMulIdRefEdEntity(Integer id1, Integer id2, String data) { + this.id1 = id1; + this.id2 = id2; + this.data = data; + } - public Integer getId1() { - return id1; - } + public Integer getId1() { + return id1; + } - public void setId1(Integer id1) { - this.id1 = id1; - } + public void setId1(Integer id1) { + this.id1 = id1; + } - public Integer getId2() { - return id2; - } + public Integer getId2() { + return id2; + } - public void setId2(Integer id2) { - this.id2 = id2; - } + public void setId2(Integer id2) { + this.id2 = id2; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public BiMulIdRefIngEntity getReferencing() { - return referencing; - } + public BiMulIdRefIngEntity getReferencing() { + return referencing; + } - public void setReferencing(BiMulIdRefIngEntity referencing) { - this.referencing = referencing; - } + public void setReferencing(BiMulIdRefIngEntity referencing) { + this.referencing = referencing; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof BiMulIdRefEdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof BiMulIdRefEdEntity) ) { + return false; + } - BiMulIdRefEdEntity that = (BiMulIdRefEdEntity) o; + BiMulIdRefEdEntity that = (BiMulIdRefEdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id1 != null ? !id1.equals(that.id1) : that.id1 != null) return false; - if (id2 != null ? !id2.equals(that.id2) : that.id2 != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id1 != null ? !id1.equals( that.id1 ) : that.id1 != null ) { + return false; + } + if ( id2 != null ? !id2.equals( that.id2 ) : that.id2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id1 != null ? id1.hashCode() : 0); - result = 31 * result + (id2 != null ? id2.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id1 != null ? id1.hashCode() : 0); + result = 31 * result + (id2 != null ? id2.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/BiMulIdRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/BiMulIdRefIngEntity.java index 5973d93f29..a83bad0f28 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/BiMulIdRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/BiMulIdRefIngEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.onetoone.bidirectional.ids; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.IdClass; @@ -36,78 +37,88 @@ import org.hibernate.envers.test.entities.ids.MulId; @Entity @IdClass(MulId.class) public class BiMulIdRefIngEntity { - @Id - private Integer id1; + @Id + private Integer id1; - @Id - private Integer id2; + @Id + private Integer id2; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToOne - private BiMulIdRefEdEntity reference; + @Audited + @OneToOne + private BiMulIdRefEdEntity reference; - public BiMulIdRefIngEntity() { - } + public BiMulIdRefIngEntity() { + } - public BiMulIdRefIngEntity(Integer id1, Integer id2, String data) { - this.id1 = id1; - this.id2 = id2; - this.data = data; - } + public BiMulIdRefIngEntity(Integer id1, Integer id2, String data) { + this.id1 = id1; + this.id2 = id2; + this.data = data; + } - public Integer getId1() { - return id1; - } + public Integer getId1() { + return id1; + } - public void setId1(Integer id1) { - this.id1 = id1; - } + public void setId1(Integer id1) { + this.id1 = id1; + } - public Integer getId2() { - return id2; - } + public Integer getId2() { + return id2; + } - public void setId2(Integer id2) { - this.id2 = id2; - } + public void setId2(Integer id2) { + this.id2 = id2; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public BiMulIdRefEdEntity getReference() { - return reference; - } + public BiMulIdRefEdEntity getReference() { + return reference; + } - public void setReference(BiMulIdRefEdEntity reference) { - this.reference = reference; - } + public void setReference(BiMulIdRefEdEntity reference) { + this.reference = reference; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof BiMulIdRefIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof BiMulIdRefIngEntity) ) { + return false; + } - BiMulIdRefIngEntity that = (BiMulIdRefIngEntity) o; + BiMulIdRefIngEntity that = (BiMulIdRefIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id1 != null ? !id1.equals(that.id1) : that.id1 != null) return false; - if (id2 != null ? !id2.equals(that.id2) : that.id2 != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id1 != null ? !id1.equals( that.id1 ) : that.id1 != null ) { + return false; + } + if ( id2 != null ? !id2.equals( that.id2 ) : that.id2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id1 != null ? id1.hashCode() : 0); - result = 31 * result + (id2 != null ? id2.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id1 != null ? id1.hashCode() : 0); + result = 31 * result + (id2 != null ? id2.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/EmbIdBidirectional.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/EmbIdBidirectional.java index 6fd81ef659..b713c87056 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/EmbIdBidirectional.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/EmbIdBidirectional.java @@ -23,105 +23,105 @@ */ package org.hibernate.envers.test.integration.onetoone.bidirectional.ids; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.ids.EmbId; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class EmbIdBidirectional extends BaseEnversJPAFunctionalTestCase { - private EmbId ed1_id; - private EmbId ed2_id; + private EmbId ed1_id; + private EmbId ed2_id; - private EmbId ing1_id; + private EmbId ing1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BiEmbIdRefEdEntity.class, BiEmbIdRefIngEntity.class }; - } + return new Class[] {BiEmbIdRefEdEntity.class, BiEmbIdRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - ed1_id = new EmbId(1, 2); - ed2_id = new EmbId(3, 4); + @Test + @Priority(10) + public void initData() { + ed1_id = new EmbId( 1, 2 ); + ed2_id = new EmbId( 3, 4 ); - ing1_id = new EmbId(5, 6); + ing1_id = new EmbId( 5, 6 ); - BiEmbIdRefEdEntity ed1 = new BiEmbIdRefEdEntity(ed1_id, "data_ed_1"); - BiEmbIdRefEdEntity ed2 = new BiEmbIdRefEdEntity(ed2_id, "data_ed_2"); + BiEmbIdRefEdEntity ed1 = new BiEmbIdRefEdEntity( ed1_id, "data_ed_1" ); + BiEmbIdRefEdEntity ed2 = new BiEmbIdRefEdEntity( ed2_id, "data_ed_2" ); - BiEmbIdRefIngEntity ing1 = new BiEmbIdRefIngEntity(ing1_id, "data_ing_1"); + BiEmbIdRefIngEntity ing1 = new BiEmbIdRefIngEntity( ing1_id, "data_ing_1" ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - ing1.setReference(ed1); + ing1.setReference( ed1 ); - em.persist(ed1); - em.persist(ed2); + em.persist( ed1 ); + em.persist( ed2 ); - em.persist(ing1); + em.persist( ing1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ing1 = em.find(BiEmbIdRefIngEntity.class, ing1.getId()); - ed2 = em.find(BiEmbIdRefEdEntity.class, ed2.getId()); + ing1 = em.find( BiEmbIdRefIngEntity.class, ing1.getId() ); + ed2 = em.find( BiEmbIdRefEdEntity.class, ed2.getId() ); - ing1.setReference(ed2); + ing1.setReference( ed2 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(BiEmbIdRefEdEntity.class, ed1_id)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(BiEmbIdRefEdEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( BiEmbIdRefEdEntity.class, ed1_id ) ); + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( BiEmbIdRefEdEntity.class, ed2_id ) ); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(BiEmbIdRefIngEntity.class, ing1_id)); - } + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( BiEmbIdRefIngEntity.class, ing1_id ) ); + } - @Test - public void testHistoryOfEdId1() { - BiEmbIdRefIngEntity ing1 = getEntityManager().find(BiEmbIdRefIngEntity.class, ing1_id); + @Test + public void testHistoryOfEdId1() { + BiEmbIdRefIngEntity ing1 = getEntityManager().find( BiEmbIdRefIngEntity.class, ing1_id ); - BiEmbIdRefEdEntity rev1 = getAuditReader().find(BiEmbIdRefEdEntity.class, ed1_id, 1); - BiEmbIdRefEdEntity rev2 = getAuditReader().find(BiEmbIdRefEdEntity.class, ed1_id, 2); + BiEmbIdRefEdEntity rev1 = getAuditReader().find( BiEmbIdRefEdEntity.class, ed1_id, 1 ); + BiEmbIdRefEdEntity rev2 = getAuditReader().find( BiEmbIdRefEdEntity.class, ed1_id, 2 ); - assert rev1.getReferencing().equals(ing1); - assert rev2.getReferencing() == null; - } + assert rev1.getReferencing().equals( ing1 ); + assert rev2.getReferencing() == null; + } - @Test - public void testHistoryOfEdId2() { - BiEmbIdRefIngEntity ing1 = getEntityManager().find(BiEmbIdRefIngEntity.class, ing1_id); + @Test + public void testHistoryOfEdId2() { + BiEmbIdRefIngEntity ing1 = getEntityManager().find( BiEmbIdRefIngEntity.class, ing1_id ); - BiEmbIdRefEdEntity rev1 = getAuditReader().find(BiEmbIdRefEdEntity.class, ed2_id, 1); - BiEmbIdRefEdEntity rev2 = getAuditReader().find(BiEmbIdRefEdEntity.class, ed2_id, 2); + BiEmbIdRefEdEntity rev1 = getAuditReader().find( BiEmbIdRefEdEntity.class, ed2_id, 1 ); + BiEmbIdRefEdEntity rev2 = getAuditReader().find( BiEmbIdRefEdEntity.class, ed2_id, 2 ); - assert rev1.getReferencing() == null; - assert rev2.getReferencing().equals(ing1); - } + assert rev1.getReferencing() == null; + assert rev2.getReferencing().equals( ing1 ); + } - @Test - public void testHistoryOfIngId1() { - BiEmbIdRefEdEntity ed1 = getEntityManager().find(BiEmbIdRefEdEntity.class, ed1_id); - BiEmbIdRefEdEntity ed2 = getEntityManager().find(BiEmbIdRefEdEntity.class, ed2_id); + @Test + public void testHistoryOfIngId1() { + BiEmbIdRefEdEntity ed1 = getEntityManager().find( BiEmbIdRefEdEntity.class, ed1_id ); + BiEmbIdRefEdEntity ed2 = getEntityManager().find( BiEmbIdRefEdEntity.class, ed2_id ); - BiEmbIdRefIngEntity rev1 = getAuditReader().find(BiEmbIdRefIngEntity.class, ing1_id, 1); - BiEmbIdRefIngEntity rev2 = getAuditReader().find(BiEmbIdRefIngEntity.class, ing1_id, 2); + BiEmbIdRefIngEntity rev1 = getAuditReader().find( BiEmbIdRefIngEntity.class, ing1_id, 1 ); + BiEmbIdRefIngEntity rev2 = getAuditReader().find( BiEmbIdRefIngEntity.class, ing1_id, 2 ); - assert rev1.getReference().equals(ed1); - assert rev2.getReference().equals(ed2); - } + assert rev1.getReference().equals( ed1 ); + assert rev2.getReference().equals( ed2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/MulIdBidirectional.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/MulIdBidirectional.java index 19ee468b4a..da1087c79c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/MulIdBidirectional.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/ids/MulIdBidirectional.java @@ -23,105 +23,105 @@ */ package org.hibernate.envers.test.integration.onetoone.bidirectional.ids; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.ids.MulId; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class MulIdBidirectional extends BaseEnversJPAFunctionalTestCase { - private MulId ed1_id; - private MulId ed2_id; + private MulId ed1_id; + private MulId ed2_id; - private MulId ing1_id; + private MulId ing1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { BiMulIdRefEdEntity.class, BiMulIdRefIngEntity.class }; - } + return new Class[] {BiMulIdRefEdEntity.class, BiMulIdRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - ed1_id = new MulId(1, 2); - ed2_id = new MulId(3, 4); + @Test + @Priority(10) + public void initData() { + ed1_id = new MulId( 1, 2 ); + ed2_id = new MulId( 3, 4 ); - ing1_id = new MulId(5, 6); + ing1_id = new MulId( 5, 6 ); - BiMulIdRefEdEntity ed1 = new BiMulIdRefEdEntity(ed1_id.getId1(), ed1_id.getId2(), "data_ed_1"); - BiMulIdRefEdEntity ed2 = new BiMulIdRefEdEntity(ed2_id.getId1(), ed2_id.getId2(), "data_ed_2"); + BiMulIdRefEdEntity ed1 = new BiMulIdRefEdEntity( ed1_id.getId1(), ed1_id.getId2(), "data_ed_1" ); + BiMulIdRefEdEntity ed2 = new BiMulIdRefEdEntity( ed2_id.getId1(), ed2_id.getId2(), "data_ed_2" ); - BiMulIdRefIngEntity ing1 = new BiMulIdRefIngEntity(ing1_id.getId1(), ing1_id.getId2(), "data_ing_1"); + BiMulIdRefIngEntity ing1 = new BiMulIdRefIngEntity( ing1_id.getId1(), ing1_id.getId2(), "data_ing_1" ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - ing1.setReference(ed1); + ing1.setReference( ed1 ); - em.persist(ed1); - em.persist(ed2); + em.persist( ed1 ); + em.persist( ed2 ); - em.persist(ing1); + em.persist( ing1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ing1 = em.find(BiMulIdRefIngEntity.class, ing1_id); - ed2 = em.find(BiMulIdRefEdEntity.class, ed2_id); + ing1 = em.find( BiMulIdRefIngEntity.class, ing1_id ); + ed2 = em.find( BiMulIdRefEdEntity.class, ed2_id ); - ing1.setReference(ed2); + ing1.setReference( ed2 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(BiMulIdRefEdEntity.class, ed1_id)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(BiMulIdRefEdEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( BiMulIdRefEdEntity.class, ed1_id ) ); + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( BiMulIdRefEdEntity.class, ed2_id ) ); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(BiMulIdRefIngEntity.class, ing1_id)); - } + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( BiMulIdRefIngEntity.class, ing1_id ) ); + } - @Test - public void testHistoryOfEdId1() { - BiMulIdRefIngEntity ing1 = getEntityManager().find(BiMulIdRefIngEntity.class, ing1_id); + @Test + public void testHistoryOfEdId1() { + BiMulIdRefIngEntity ing1 = getEntityManager().find( BiMulIdRefIngEntity.class, ing1_id ); - BiMulIdRefEdEntity rev1 = getAuditReader().find(BiMulIdRefEdEntity.class, ed1_id, 1); - BiMulIdRefEdEntity rev2 = getAuditReader().find(BiMulIdRefEdEntity.class, ed1_id, 2); + BiMulIdRefEdEntity rev1 = getAuditReader().find( BiMulIdRefEdEntity.class, ed1_id, 1 ); + BiMulIdRefEdEntity rev2 = getAuditReader().find( BiMulIdRefEdEntity.class, ed1_id, 2 ); - assert rev1.getReferencing().equals(ing1); - assert rev2.getReferencing() == null; - } + assert rev1.getReferencing().equals( ing1 ); + assert rev2.getReferencing() == null; + } - @Test - public void testHistoryOfEdId2() { - BiMulIdRefIngEntity ing1 = getEntityManager().find(BiMulIdRefIngEntity.class, ing1_id); + @Test + public void testHistoryOfEdId2() { + BiMulIdRefIngEntity ing1 = getEntityManager().find( BiMulIdRefIngEntity.class, ing1_id ); - BiMulIdRefEdEntity rev1 = getAuditReader().find(BiMulIdRefEdEntity.class, ed2_id, 1); - BiMulIdRefEdEntity rev2 = getAuditReader().find(BiMulIdRefEdEntity.class, ed2_id, 2); + BiMulIdRefEdEntity rev1 = getAuditReader().find( BiMulIdRefEdEntity.class, ed2_id, 1 ); + BiMulIdRefEdEntity rev2 = getAuditReader().find( BiMulIdRefEdEntity.class, ed2_id, 2 ); - assert rev1.getReferencing() == null; - assert rev2.getReferencing().equals(ing1); - } + assert rev1.getReferencing() == null; + assert rev2.getReferencing().equals( ing1 ); + } - @Test - public void testHistoryOfIngId1() { - BiMulIdRefEdEntity ed1 = getEntityManager().find(BiMulIdRefEdEntity.class, ed1_id); - BiMulIdRefEdEntity ed2 = getEntityManager().find(BiMulIdRefEdEntity.class, ed2_id); + @Test + public void testHistoryOfIngId1() { + BiMulIdRefEdEntity ed1 = getEntityManager().find( BiMulIdRefEdEntity.class, ed1_id ); + BiMulIdRefEdEntity ed2 = getEntityManager().find( BiMulIdRefEdEntity.class, ed2_id ); - BiMulIdRefIngEntity rev1 = getAuditReader().find(BiMulIdRefIngEntity.class, ing1_id, 1); - BiMulIdRefIngEntity rev2 = getAuditReader().find(BiMulIdRefIngEntity.class, ing1_id, 2); + BiMulIdRefIngEntity rev1 = getAuditReader().find( BiMulIdRefIngEntity.class, ing1_id, 1 ); + BiMulIdRefIngEntity rev2 = getAuditReader().find( BiMulIdRefIngEntity.class, ing1_id, 2 ); - assert rev1.getReference().equals(ed1); - assert rev2.getReference().equals(ed2); - } + assert rev1.getReference().equals( ed1 ); + assert rev2.getReference().equals( ed2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/Account.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/Account.java index 6c011e6584..b2eaa31820 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/Account.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/Account.java @@ -1,12 +1,12 @@ package org.hibernate.envers.test.integration.onetoone.bidirectional.primarykeyjoincolumn; -import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; +import java.io.Serializable; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @@ -18,77 +18,85 @@ import org.hibernate.envers.Audited; @Entity @Audited public class Account implements Serializable { - @Id - @Column(name = "ACCOUNT_ID") - @GeneratedValue(generator = "AccountForeignKeyGenerator") - @GenericGenerator(name = "AccountForeignKeyGenerator", strategy = "foreign", - parameters = {@Parameter(name = "property", value = "owner")}) - private Long accountId; + @Id + @Column(name = "ACCOUNT_ID") + @GeneratedValue(generator = "AccountForeignKeyGenerator") + @GenericGenerator(name = "AccountForeignKeyGenerator", strategy = "foreign", + parameters = {@Parameter(name = "property", value = "owner")}) + private Long accountId; - private String type; + private String type; - @OneToOne(optional = false) - @PrimaryKeyJoinColumn(name = "ACCOUNT_ID", referencedColumnName = "PERSON_ID") - private Person owner; + @OneToOne(optional = false) + @PrimaryKeyJoinColumn(name = "ACCOUNT_ID", referencedColumnName = "PERSON_ID") + private Person owner; - public Account() { - } + public Account() { + } - public Account(String type) { - this.type = type; - } + public Account(String type) { + this.type = type; + } - public Account(Long accountId, String type) { - this.accountId = accountId; - this.type = type; - } + public Account(Long accountId, String type) { + this.accountId = accountId; + this.type = type; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Account)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Account) ) { + return false; + } - Account account = (Account) o; + Account account = (Account) o; - if (accountId != null ? !accountId.equals(account.accountId) : account.accountId != null) return false; - if (type != null ? !type.equals(account.type) : account.type != null) return false; + if ( accountId != null ? !accountId.equals( account.accountId ) : account.accountId != null ) { + return false; + } + if ( type != null ? !type.equals( account.type ) : account.type != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = accountId != null ? accountId.hashCode() : 0; - result = 31 * result + (type != null ? type.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = accountId != null ? accountId.hashCode() : 0; + result = 31 * result + (type != null ? type.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "Account(accountId = " + accountId + ", type = " + type + ")"; - } + @Override + public String toString() { + return "Account(accountId = " + accountId + ", type = " + type + ")"; + } - public Long getAccountId() { - return accountId; - } + public Long getAccountId() { + return accountId; + } - public void setAccountId(Long accountId) { - this.accountId = accountId; - } + public void setAccountId(Long accountId) { + this.accountId = accountId; + } - public Person getOwner() { - return owner; - } + public Person getOwner() { + return owner; + } - public void setOwner(Person owner) { - this.owner = owner; - } + public void setOwner(Person owner) { + this.owner = owner; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/AccountNotAuditedOwners.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/AccountNotAuditedOwners.java index 6a11954bb7..8f9a97d2eb 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/AccountNotAuditedOwners.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/AccountNotAuditedOwners.java @@ -1,12 +1,12 @@ package org.hibernate.envers.test.integration.onetoone.bidirectional.primarykeyjoincolumn; -import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; +import java.io.Serializable; import org.hibernate.envers.Audited; import org.hibernate.envers.RelationTargetAuditMode; @@ -17,87 +17,95 @@ import org.hibernate.envers.RelationTargetAuditMode; @Entity @Audited public class AccountNotAuditedOwners implements Serializable { - @Id - @Column(name = "ACCOUNT_ID") - @GeneratedValue - private Long accountId; + @Id + @Column(name = "ACCOUNT_ID") + @GeneratedValue + private Long accountId; - private String type; + private String type; - @OneToOne(mappedBy = "account", optional = false) - @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) - private NotAuditedNoProxyPerson owner; + @OneToOne(mappedBy = "account", optional = false) + @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) + private NotAuditedNoProxyPerson owner; - @OneToOne(mappedBy = "account", optional = false, fetch = FetchType.LAZY) - @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) - private NotAuditedProxyPerson coOwner; + @OneToOne(mappedBy = "account", optional = false, fetch = FetchType.LAZY) + @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) + private NotAuditedProxyPerson coOwner; - public AccountNotAuditedOwners() { - } + public AccountNotAuditedOwners() { + } - public AccountNotAuditedOwners(String type) { - this.type = type; - } + public AccountNotAuditedOwners(String type) { + this.type = type; + } - public AccountNotAuditedOwners(Long accountId, String type) { - this.accountId = accountId; - this.type = type; - } + public AccountNotAuditedOwners(Long accountId, String type) { + this.accountId = accountId; + this.type = type; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof AccountNotAuditedOwners)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof AccountNotAuditedOwners) ) { + return false; + } - AccountNotAuditedOwners account = (AccountNotAuditedOwners) o; + AccountNotAuditedOwners account = (AccountNotAuditedOwners) o; - if (accountId != null ? !accountId.equals(account.accountId) : account.accountId != null) return false; - if (type != null ? !type.equals(account.type) : account.type != null) return false; + if ( accountId != null ? !accountId.equals( account.accountId ) : account.accountId != null ) { + return false; + } + if ( type != null ? !type.equals( account.type ) : account.type != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = accountId != null ? accountId.hashCode() : 0; - result = 31 * result + (type != null ? type.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = accountId != null ? accountId.hashCode() : 0; + result = 31 * result + (type != null ? type.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "AccountNotAuditedOwners(accountId = " + accountId + ", type = " + type + ")"; - } + @Override + public String toString() { + return "AccountNotAuditedOwners(accountId = " + accountId + ", type = " + type + ")"; + } - public Long getAccountId() { - return accountId; - } + public Long getAccountId() { + return accountId; + } - public void setAccountId(Long accountId) { - this.accountId = accountId; - } + public void setAccountId(Long accountId) { + this.accountId = accountId; + } - public NotAuditedNoProxyPerson getOwner() { - return owner; - } + public NotAuditedNoProxyPerson getOwner() { + return owner; + } - public void setOwner(NotAuditedNoProxyPerson owner) { - this.owner = owner; - } + public void setOwner(NotAuditedNoProxyPerson owner) { + this.owner = owner; + } - public NotAuditedProxyPerson getCoOwner() { - return coOwner; - } + public NotAuditedProxyPerson getCoOwner() { + return coOwner; + } - public void setCoOwner(NotAuditedProxyPerson coOwner) { - this.coOwner = coOwner; - } + public void setCoOwner(NotAuditedProxyPerson coOwner) { + this.coOwner = coOwner; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/NotAuditedNoProxyPerson.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/NotAuditedNoProxyPerson.java index c249c556e2..857a6d693a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/NotAuditedNoProxyPerson.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/NotAuditedNoProxyPerson.java @@ -1,12 +1,12 @@ package org.hibernate.envers.test.integration.onetoone.bidirectional.primarykeyjoincolumn; -import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; +import java.io.Serializable; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @@ -18,77 +18,85 @@ import org.hibernate.annotations.Proxy; @Entity @Proxy(lazy = false) public class NotAuditedNoProxyPerson implements Serializable { - @Id - @Column(name = "PERSON_ID") - @GeneratedValue(generator = "NotAuditedNoProxyKeyGenerator") - @GenericGenerator(name = "NotAuditedNoProxyKeyGenerator", strategy = "foreign", - parameters = {@Parameter(name = "property", value = "account")}) - private Long personId; + @Id + @Column(name = "PERSON_ID") + @GeneratedValue(generator = "NotAuditedNoProxyKeyGenerator") + @GenericGenerator(name = "NotAuditedNoProxyKeyGenerator", strategy = "foreign", + parameters = {@Parameter(name = "property", value = "account")}) + private Long personId; - private String name; + private String name; - @OneToOne(optional = false) - @PrimaryKeyJoinColumn(name = "PERSON_ID", referencedColumnName = "ACCOUNT_ID") - private AccountNotAuditedOwners account; + @OneToOne(optional = false) + @PrimaryKeyJoinColumn(name = "PERSON_ID", referencedColumnName = "ACCOUNT_ID") + private AccountNotAuditedOwners account; - public NotAuditedNoProxyPerson() { - } + public NotAuditedNoProxyPerson() { + } - public NotAuditedNoProxyPerson(String name) { - this.name = name; - } + public NotAuditedNoProxyPerson(String name) { + this.name = name; + } - public NotAuditedNoProxyPerson(Long personId, String name) { - this.personId = personId; - this.name = name; - } + public NotAuditedNoProxyPerson(Long personId, String name) { + this.personId = personId; + this.name = name; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof NotAuditedNoProxyPerson)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof NotAuditedNoProxyPerson) ) { + return false; + } - NotAuditedNoProxyPerson person = (NotAuditedNoProxyPerson) o; + NotAuditedNoProxyPerson person = (NotAuditedNoProxyPerson) o; - if (personId != null ? !personId.equals(person.personId) : person.personId != null) return false; - if (name != null ? !name.equals(person.name) : person.name != null) return false; + if ( personId != null ? !personId.equals( person.personId ) : person.personId != null ) { + return false; + } + if ( name != null ? !name.equals( person.name ) : person.name != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = personId != null ? personId.hashCode() : 0; - result = 31 * result + (name != null ? name.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = personId != null ? personId.hashCode() : 0; + result = 31 * result + (name != null ? name.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "NotAuditedNoProxyPerson(personId = " + personId + ", name = " + name + ")"; - } + @Override + public String toString() { + return "NotAuditedNoProxyPerson(personId = " + personId + ", name = " + name + ")"; + } - public Long getPersonId() { - return personId; - } + public Long getPersonId() { + return personId; + } - public void setPersonId(Long personId) { - this.personId = personId; - } + public void setPersonId(Long personId) { + this.personId = personId; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public AccountNotAuditedOwners getAccount() { - return account; - } + public AccountNotAuditedOwners getAccount() { + return account; + } - public void setAccount(AccountNotAuditedOwners account) { - this.account = account; - } + public void setAccount(AccountNotAuditedOwners account) { + this.account = account; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/NotAuditedProxyPerson.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/NotAuditedProxyPerson.java index ae7c88e151..a19a60d5c9 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/NotAuditedProxyPerson.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/NotAuditedProxyPerson.java @@ -1,6 +1,5 @@ package org.hibernate.envers.test.integration.onetoone.bidirectional.primarykeyjoincolumn; -import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; @@ -8,6 +7,7 @@ import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; +import java.io.Serializable; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @@ -19,77 +19,85 @@ import org.hibernate.annotations.Proxy; @Entity @Proxy(lazy = true) public class NotAuditedProxyPerson implements Serializable { - @Id - @Column(name = "PERSON_ID") - @GeneratedValue(generator = "NotAuditedProxyKeyGenerator") - @GenericGenerator(name = "NotAuditedProxyKeyGenerator", strategy = "foreign", - parameters = {@Parameter(name = "property", value = "account")}) - private Long personId; + @Id + @Column(name = "PERSON_ID") + @GeneratedValue(generator = "NotAuditedProxyKeyGenerator") + @GenericGenerator(name = "NotAuditedProxyKeyGenerator", strategy = "foreign", + parameters = {@Parameter(name = "property", value = "account")}) + private Long personId; - private String name; + private String name; - @OneToOne(optional = false, fetch = FetchType.LAZY) - @PrimaryKeyJoinColumn(name = "PERSON_ID", referencedColumnName = "ACCOUNT_ID") - private AccountNotAuditedOwners account; + @OneToOne(optional = false, fetch = FetchType.LAZY) + @PrimaryKeyJoinColumn(name = "PERSON_ID", referencedColumnName = "ACCOUNT_ID") + private AccountNotAuditedOwners account; - public NotAuditedProxyPerson() { - } + public NotAuditedProxyPerson() { + } - public NotAuditedProxyPerson(String name) { - this.name = name; - } + public NotAuditedProxyPerson(String name) { + this.name = name; + } - public NotAuditedProxyPerson(Long personId, String name) { - this.personId = personId; - this.name = name; - } + public NotAuditedProxyPerson(Long personId, String name) { + this.personId = personId; + this.name = name; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof NotAuditedProxyPerson)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof NotAuditedProxyPerson) ) { + return false; + } - NotAuditedProxyPerson person = (NotAuditedProxyPerson) o; + NotAuditedProxyPerson person = (NotAuditedProxyPerson) o; - if (personId != null ? !personId.equals(person.personId) : person.personId != null) return false; - if (name != null ? !name.equals(person.name) : person.name != null) return false; + if ( personId != null ? !personId.equals( person.personId ) : person.personId != null ) { + return false; + } + if ( name != null ? !name.equals( person.name ) : person.name != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = personId != null ? personId.hashCode() : 0; - result = 31 * result + (name != null ? name.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = personId != null ? personId.hashCode() : 0; + result = 31 * result + (name != null ? name.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "NotAuditedProxyPerson(personId = " + personId + ", name = " + name + ")"; - } + @Override + public String toString() { + return "NotAuditedProxyPerson(personId = " + personId + ", name = " + name + ")"; + } - public Long getPersonId() { - return personId; - } + public Long getPersonId() { + return personId; + } - public void setPersonId(Long personId) { - this.personId = personId; - } + public void setPersonId(Long personId) { + this.personId = personId; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public AccountNotAuditedOwners getAccount() { - return account; - } + public AccountNotAuditedOwners getAccount() { + return account; + } - public void setAccount(AccountNotAuditedOwners account) { - this.account = account; - } + public void setAccount(AccountNotAuditedOwners account) { + this.account = account; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/OneToOneWithPrimaryKeyJoinTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/OneToOneWithPrimaryKeyJoinTest.java index 53a49d44b3..7aea79eb2b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/OneToOneWithPrimaryKeyJoinTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/OneToOneWithPrimaryKeyJoinTest.java @@ -1,16 +1,17 @@ package org.hibernate.envers.test.integration.onetoone.bidirectional.primarykeyjoincolumn; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.RevisionType; import org.hibernate.envers.query.AuditEntity; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.proxy.HibernateProxy; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -18,11 +19,11 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-6825") public class OneToOneWithPrimaryKeyJoinTest extends BaseEnversJPAFunctionalTestCase { - private Long personId = null; - private Long accountId = null; - private Long proxyPersonId = null; - private Long noProxyPersonId = null; - private Long accountNotAuditedOwnersId = null; + private Long personId = null; + private Long accountId = null; + private Long proxyPersonId = null; + private Long noProxyPersonId = null; + private Long accountNotAuditedOwnersId = null; @Override protected Class[] getAnnotatedClasses() { @@ -33,109 +34,128 @@ public class OneToOneWithPrimaryKeyJoinTest extends BaseEnversJPAFunctionalTestC NotAuditedNoProxyPerson.class, NotAuditedProxyPerson.class }; - } + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 1 - em.getTransaction().begin(); - Person person = new Person("Robert"); - Account account = new Account("Saving"); - person.setAccount(account); - account.setOwner(person); - em.persist(person); - em.persist(account); - em.getTransaction().commit(); + // Revision 1 + em.getTransaction().begin(); + Person person = new Person( "Robert" ); + Account account = new Account( "Saving" ); + person.setAccount( account ); + account.setOwner( person ); + em.persist( person ); + em.persist( account ); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); - NotAuditedNoProxyPerson noProxyPerson = new NotAuditedNoProxyPerson("Kinga"); - NotAuditedProxyPerson proxyPerson = new NotAuditedProxyPerson("Lukasz"); - AccountNotAuditedOwners accountNotAuditedOwners = new AccountNotAuditedOwners("Standard"); - noProxyPerson.setAccount(accountNotAuditedOwners); - proxyPerson.setAccount(accountNotAuditedOwners); - accountNotAuditedOwners.setOwner(noProxyPerson); - accountNotAuditedOwners.setCoOwner(proxyPerson); - em.persist(accountNotAuditedOwners); - em.persist(noProxyPerson); - em.persist(proxyPerson); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + NotAuditedNoProxyPerson noProxyPerson = new NotAuditedNoProxyPerson( "Kinga" ); + NotAuditedProxyPerson proxyPerson = new NotAuditedProxyPerson( "Lukasz" ); + AccountNotAuditedOwners accountNotAuditedOwners = new AccountNotAuditedOwners( "Standard" ); + noProxyPerson.setAccount( accountNotAuditedOwners ); + proxyPerson.setAccount( accountNotAuditedOwners ); + accountNotAuditedOwners.setOwner( noProxyPerson ); + accountNotAuditedOwners.setCoOwner( proxyPerson ); + em.persist( accountNotAuditedOwners ); + em.persist( noProxyPerson ); + em.persist( proxyPerson ); + em.getTransaction().commit(); - personId = person.getPersonId(); - accountId = account.getAccountId(); - accountNotAuditedOwnersId = accountNotAuditedOwners.getAccountId(); - proxyPersonId = proxyPerson.getPersonId(); - noProxyPersonId = noProxyPerson.getPersonId(); - } + personId = person.getPersonId(); + accountId = account.getAccountId(); + accountNotAuditedOwnersId = accountNotAuditedOwners.getAccountId(); + proxyPersonId = proxyPerson.getPersonId(); + noProxyPersonId = noProxyPerson.getPersonId(); + } - @Test - public void testRevisionsCounts() { - Assert.assertEquals(Arrays.asList(1), getAuditReader().getRevisions(Person.class, personId)); - Assert.assertEquals(Arrays.asList(1), getAuditReader().getRevisions(Account.class, accountId)); - Assert.assertEquals(Arrays.asList(2), getAuditReader().getRevisions(AccountNotAuditedOwners.class, accountNotAuditedOwnersId)); - } + @Test + public void testRevisionsCounts() { + Assert.assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( Person.class, personId ) ); + Assert.assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( Account.class, accountId ) ); + Assert.assertEquals( + Arrays.asList( 2 ), getAuditReader().getRevisions( + AccountNotAuditedOwners.class, + accountNotAuditedOwnersId + ) + ); + } - @Test - public void testHistoryOfPerson() { - Person personVer1 = new Person(personId, "Robert"); - Account accountVer1 = new Account(accountId, "Saving"); - personVer1.setAccount(accountVer1); - accountVer1.setOwner(personVer1); + @Test + public void testHistoryOfPerson() { + Person personVer1 = new Person( personId, "Robert" ); + Account accountVer1 = new Account( accountId, "Saving" ); + personVer1.setAccount( accountVer1 ); + accountVer1.setOwner( personVer1 ); - Object[] result = ((Object[]) getAuditReader().createQuery().forRevisionsOfEntity(Person.class, false, true) - .add(AuditEntity.id().eq(personId)) - .getResultList().get(0)); + Object[] result = ((Object[]) getAuditReader().createQuery().forRevisionsOfEntity( Person.class, false, true ) + .add( AuditEntity.id().eq( personId ) ) + .getResultList().get( 0 )); - Assert.assertEquals(personVer1, result[0]); - Assert.assertEquals(personVer1.getAccount(), ((Person)result[0]).getAccount()); - Assert.assertEquals(RevisionType.ADD, result[2]); + Assert.assertEquals( personVer1, result[0] ); + Assert.assertEquals( personVer1.getAccount(), ((Person) result[0]).getAccount() ); + Assert.assertEquals( RevisionType.ADD, result[2] ); - Assert.assertEquals(personVer1, getAuditReader().find(Person.class, personId, 1)); - } + Assert.assertEquals( personVer1, getAuditReader().find( Person.class, personId, 1 ) ); + } - @Test - public void testHistoryOfAccount() { - Person personVer1 = new Person(personId, "Robert"); - Account accountVer1 = new Account(accountId, "Saving"); - personVer1.setAccount(accountVer1); - accountVer1.setOwner(personVer1); + @Test + public void testHistoryOfAccount() { + Person personVer1 = new Person( personId, "Robert" ); + Account accountVer1 = new Account( accountId, "Saving" ); + personVer1.setAccount( accountVer1 ); + accountVer1.setOwner( personVer1 ); - Object[] result = ((Object[]) getAuditReader().createQuery().forRevisionsOfEntity(Account.class, false, true) - .add(AuditEntity.id().eq(accountId)) - .getResultList().get(0)); + Object[] result = ((Object[]) getAuditReader().createQuery().forRevisionsOfEntity( Account.class, false, true ) + .add( AuditEntity.id().eq( accountId ) ) + .getResultList().get( 0 )); - Assert.assertEquals(accountVer1, result[0]); - Assert.assertEquals(accountVer1.getOwner(), ((Account)result[0]).getOwner()); - Assert.assertEquals(RevisionType.ADD, result[2]); + Assert.assertEquals( accountVer1, result[0] ); + Assert.assertEquals( accountVer1.getOwner(), ((Account) result[0]).getOwner() ); + Assert.assertEquals( RevisionType.ADD, result[2] ); - Assert.assertEquals(accountVer1, getAuditReader().find(Account.class, accountId, 1)); - } + Assert.assertEquals( accountVer1, getAuditReader().find( Account.class, accountId, 1 ) ); + } - @Test - public void testHistoryOfAccountNotAuditedOwners() { - NotAuditedNoProxyPerson noProxyPersonVer1 = new NotAuditedNoProxyPerson(noProxyPersonId, "Kinga"); - NotAuditedProxyPerson proxyPersonVer1 = new NotAuditedProxyPerson(proxyPersonId, "Lukasz"); - AccountNotAuditedOwners accountNotAuditedOwnersVer1 = new AccountNotAuditedOwners(accountNotAuditedOwnersId, "Standard"); - noProxyPersonVer1.setAccount(accountNotAuditedOwnersVer1); - proxyPersonVer1.setAccount(accountNotAuditedOwnersVer1); - accountNotAuditedOwnersVer1.setOwner(noProxyPersonVer1); - accountNotAuditedOwnersVer1.setCoOwner(proxyPersonVer1); + @Test + public void testHistoryOfAccountNotAuditedOwners() { + NotAuditedNoProxyPerson noProxyPersonVer1 = new NotAuditedNoProxyPerson( noProxyPersonId, "Kinga" ); + NotAuditedProxyPerson proxyPersonVer1 = new NotAuditedProxyPerson( proxyPersonId, "Lukasz" ); + AccountNotAuditedOwners accountNotAuditedOwnersVer1 = new AccountNotAuditedOwners( + accountNotAuditedOwnersId, + "Standard" + ); + noProxyPersonVer1.setAccount( accountNotAuditedOwnersVer1 ); + proxyPersonVer1.setAccount( accountNotAuditedOwnersVer1 ); + accountNotAuditedOwnersVer1.setOwner( noProxyPersonVer1 ); + accountNotAuditedOwnersVer1.setCoOwner( proxyPersonVer1 ); - Object[] result = ((Object[]) getAuditReader().createQuery().forRevisionsOfEntity(AccountNotAuditedOwners.class, false, true) - .add(AuditEntity.id().eq(accountNotAuditedOwnersId)) - .getResultList().get(0)); + Object[] result = ((Object[]) getAuditReader().createQuery() + .forRevisionsOfEntity( AccountNotAuditedOwners.class, false, true ) + .add( AuditEntity.id().eq( accountNotAuditedOwnersId ) ) + .getResultList() + .get( 0 )); - Assert.assertEquals(accountNotAuditedOwnersVer1, result[0]); - Assert.assertEquals(RevisionType.ADD, result[2]); - // Checking non-proxy reference - Assert.assertEquals(accountNotAuditedOwnersVer1.getOwner(), ((AccountNotAuditedOwners)result[0]).getOwner()); - // Checking proxy reference - Assert.assertTrue(((AccountNotAuditedOwners)result[0]).getCoOwner() instanceof HibernateProxy); - Assert.assertEquals(proxyPersonVer1.getPersonId(), ((AccountNotAuditedOwners)result[0]).getCoOwner().getPersonId()); + Assert.assertEquals( accountNotAuditedOwnersVer1, result[0] ); + Assert.assertEquals( RevisionType.ADD, result[2] ); + // Checking non-proxy reference + Assert.assertEquals( accountNotAuditedOwnersVer1.getOwner(), ((AccountNotAuditedOwners) result[0]).getOwner() ); + // Checking proxy reference + Assert.assertTrue( ((AccountNotAuditedOwners) result[0]).getCoOwner() instanceof HibernateProxy ); + Assert.assertEquals( + proxyPersonVer1.getPersonId(), + ((AccountNotAuditedOwners) result[0]).getCoOwner().getPersonId() + ); - Assert.assertEquals(accountNotAuditedOwnersVer1, getAuditReader().find(AccountNotAuditedOwners.class, accountNotAuditedOwnersId, 2)); - } + Assert.assertEquals( + accountNotAuditedOwnersVer1, getAuditReader().find( + AccountNotAuditedOwners.class, + accountNotAuditedOwnersId, + 2 + ) + ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/Person.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/Person.java index 963e62afe8..ca75a1dc81 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/Person.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/bidirectional/primarykeyjoincolumn/Person.java @@ -1,11 +1,11 @@ package org.hibernate.envers.test.integration.onetoone.bidirectional.primarykeyjoincolumn; -import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -15,74 +15,82 @@ import org.hibernate.envers.Audited; @Entity @Audited public class Person implements Serializable { - @Id - @Column(name = "PERSON_ID") - @GeneratedValue - private Long personId; + @Id + @Column(name = "PERSON_ID") + @GeneratedValue + private Long personId; - private String name; + private String name; - @OneToOne(mappedBy = "owner") - private Account account; + @OneToOne(mappedBy = "owner") + private Account account; - public Person() { - } + public Person() { + } - public Person(String name) { - this.name = name; - } + public Person(String name) { + this.name = name; + } - public Person(Long personId, String name) { - this.personId = personId; - this.name = name; - } + public Person(Long personId, String name) { + this.personId = personId; + this.name = name; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Person)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Person) ) { + return false; + } - Person person = (Person) o; + Person person = (Person) o; - if (personId != null ? !personId.equals(person.personId) : person.personId != null) return false; - if (name != null ? !name.equals(person.name) : person.name != null) return false; + if ( personId != null ? !personId.equals( person.personId ) : person.personId != null ) { + return false; + } + if ( name != null ? !name.equals( person.name ) : person.name != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = personId != null ? personId.hashCode() : 0; - result = 31 * result + (name != null ? name.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = personId != null ? personId.hashCode() : 0; + result = 31 * result + (name != null ? name.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "Person(personId = " + personId + ", name = " + name + ")"; - } + @Override + public String toString() { + return "Person(personId = " + personId + ", name = " + name + ")"; + } - public Long getPersonId() { - return personId; - } + public Long getPersonId() { + return personId; + } - public void setPersonId(Long personId) { - this.personId = personId; - } + public void setPersonId(Long personId) { + this.personId = personId; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public Account getAccount() { - return account; - } + public Account getAccount() { + return account; + } - public void setAccount(Account account) { - this.account = account; - } + public void setAccount(Account account) { + this.account = account; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UniRefEdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UniRefEdEntity.java index bf17d6cdd4..35bb8df464 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UniRefEdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UniRefEdEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.onetoone.unidirectional; + import javax.persistence.Entity; import javax.persistence.Id; @@ -29,56 +30,65 @@ import org.hibernate.envers.Audited; /** * Unidirectional ReferencEd Entity + * * @author Adam Warski (adam at warski dot org) */ @Entity public class UniRefEdEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - public UniRefEdEntity() { - } + public UniRefEdEntity() { + } - public UniRefEdEntity(Integer id, String data) { - this.id = id; - this.data = data; - } + public UniRefEdEntity(Integer id, String data) { + this.id = id; + this.data = data; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof UniRefEdEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof UniRefEdEntity) ) { + return false; + } - UniRefEdEntity that = (UniRefEdEntity) o; + UniRefEdEntity that = (UniRefEdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UniRefIngEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UniRefIngEntity.java index 0d1365a57c..ddd9186ca5 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UniRefIngEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UniRefIngEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.onetoone.unidirectional; + import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToOne; @@ -30,69 +31,78 @@ import org.hibernate.envers.Audited; /** * Unidirectional ReferencIng Entity + * * @author Adam Warski (adam at warski dot org) */ @Entity public class UniRefIngEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToOne - private UniRefEdEntity reference; + @Audited + @OneToOne + private UniRefEdEntity reference; - public UniRefIngEntity() { - } + public UniRefIngEntity() { + } - public UniRefIngEntity(Integer id, String data, UniRefEdEntity reference) { - this.id = id; - this.data = data; - this.reference = reference; - } + public UniRefIngEntity(Integer id, String data, UniRefEdEntity reference) { + this.id = id; + this.data = data; + this.reference = reference; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public UniRefEdEntity getReference() { - return reference; - } + public UniRefEdEntity getReference() { + return reference; + } - public void setReference(UniRefEdEntity reference) { - this.reference = reference; - } + public void setReference(UniRefEdEntity reference) { + this.reference = reference; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof UniRefIngEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof UniRefIngEntity) ) { + return false; + } - UniRefIngEntity that = (UniRefIngEntity) o; + UniRefIngEntity that = (UniRefIngEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UniRefIngMulIdEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UniRefIngMulIdEntity.java index 1040cf5b69..a6dd5e7d7c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UniRefIngMulIdEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UniRefIngMulIdEntity.java @@ -12,71 +12,79 @@ import org.hibernate.envers.test.entities.ids.EmbIdTestEntity; */ @Entity public class UniRefIngMulIdEntity { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String data; + @Audited + private String data; - @Audited - @OneToOne - private EmbIdTestEntity reference; + @Audited + @OneToOne + private EmbIdTestEntity reference; - public UniRefIngMulIdEntity() { - } + public UniRefIngMulIdEntity() { + } - public UniRefIngMulIdEntity(Integer id, String data, EmbIdTestEntity reference) { - this.id = id; - this.data = data; - this.reference = reference; - } + public UniRefIngMulIdEntity(Integer id, String data, EmbIdTestEntity reference) { + this.id = id; + this.data = data; + this.reference = reference; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public EmbIdTestEntity getReference() { - return reference; - } + public EmbIdTestEntity getReference() { + return reference; + } - public void setReference(EmbIdTestEntity reference) { - this.reference = reference; - } + public void setReference(EmbIdTestEntity reference) { + this.reference = reference; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof UniRefIngMulIdEntity)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof UniRefIngMulIdEntity) ) { + return false; + } - UniRefIngMulIdEntity that = (UniRefIngMulIdEntity) o; + UniRefIngMulIdEntity that = (UniRefIngMulIdEntity) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "UniRefIngMulIdEntity[id = " + id + ", data = " + data + "]"; - } + @Override + public String toString() { + return "UniRefIngMulIdEntity[id = " + id + ", data = " + data + "]"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/Unidirectional.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/Unidirectional.java index a53fe71f42..464538edb3 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/Unidirectional.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/Unidirectional.java @@ -23,127 +23,127 @@ */ package org.hibernate.envers.test.integration.onetoone.unidirectional; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class Unidirectional extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; - private Integer ed3_id; - private Integer ed4_id; + private Integer ed1_id; + private Integer ed2_id; + private Integer ed3_id; + private Integer ed4_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { UniRefEdEntity.class, UniRefIngEntity.class }; - } + return new Class[] {UniRefEdEntity.class, UniRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - UniRefEdEntity ed1 = new UniRefEdEntity(1, "data_ed_1"); - UniRefEdEntity ed2 = new UniRefEdEntity(2, "data_ed_2"); - UniRefEdEntity ed3 = new UniRefEdEntity(3, "data_ed_2"); - UniRefEdEntity ed4 = new UniRefEdEntity(4, "data_ed_2"); + @Test + @Priority(10) + public void initData() { + UniRefEdEntity ed1 = new UniRefEdEntity( 1, "data_ed_1" ); + UniRefEdEntity ed2 = new UniRefEdEntity( 2, "data_ed_2" ); + UniRefEdEntity ed3 = new UniRefEdEntity( 3, "data_ed_2" ); + UniRefEdEntity ed4 = new UniRefEdEntity( 4, "data_ed_2" ); - UniRefIngEntity ing1 = new UniRefIngEntity(5, "data_ing_1", ed1); - UniRefIngEntity ing2 = new UniRefIngEntity(6, "data_ing_2", ed3); + UniRefIngEntity ing1 = new UniRefIngEntity( 5, "data_ing_1", ed1 ); + UniRefIngEntity ing2 = new UniRefIngEntity( 6, "data_ing_2", ed3 ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); - em.persist(ed3); - em.persist(ed4); + em.persist( ed1 ); + em.persist( ed2 ); + em.persist( ed3 ); + em.persist( ed4 ); - em.persist(ing1); - em.persist(ing2); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 + // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); + em = getEntityManager(); + em.getTransaction().begin(); - ing1 = em.find(UniRefIngEntity.class, ing1.getId()); - ed2 = em.find(UniRefEdEntity.class, ed2.getId()); + ing1 = em.find( UniRefIngEntity.class, ing1.getId() ); + ed2 = em.find( UniRefEdEntity.class, ed2.getId() ); - ing1.setReference(ed2); + ing1.setReference( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 + // Revision 3 - em = getEntityManager(); - em.getTransaction().begin(); + em = getEntityManager(); + em.getTransaction().begin(); - ing2 = em.find(UniRefIngEntity.class, ing2.getId()); - ed3 = em.find(UniRefEdEntity.class, ed3.getId()); + ing2 = em.find( UniRefIngEntity.class, ing2.getId() ); + ed3 = em.find( UniRefEdEntity.class, ed3.getId() ); - ing2.setReference(ed4); + ing2.setReference( ed4 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); - ed3_id = ed3.getId(); - ed4_id = ed4.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); + ed3_id = ed3.getId(); + ed4_id = ed4.getId(); - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); - } + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1).equals(getAuditReader().getRevisions(UniRefEdEntity.class, ed1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(UniRefEdEntity.class, ed2_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(UniRefEdEntity.class, ed3_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(UniRefEdEntity.class, ed4_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( UniRefEdEntity.class, ed1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( UniRefEdEntity.class, ed2_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( UniRefEdEntity.class, ed3_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( UniRefEdEntity.class, ed4_id ) ); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(UniRefIngEntity.class, ing1_id)); - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(UniRefIngEntity.class, ing2_id)); - } + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( UniRefIngEntity.class, ing1_id ) ); + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( UniRefIngEntity.class, ing2_id ) ); + } - @Test - public void testHistoryOfIngId1() { - UniRefEdEntity ed1 = getEntityManager().find(UniRefEdEntity.class, ed1_id); - UniRefEdEntity ed2 = getEntityManager().find(UniRefEdEntity.class, ed2_id); + @Test + public void testHistoryOfIngId1() { + UniRefEdEntity ed1 = getEntityManager().find( UniRefEdEntity.class, ed1_id ); + UniRefEdEntity ed2 = getEntityManager().find( UniRefEdEntity.class, ed2_id ); - UniRefIngEntity rev1 = getAuditReader().find(UniRefIngEntity.class, ing1_id, 1); - UniRefIngEntity rev2 = getAuditReader().find(UniRefIngEntity.class, ing1_id, 2); - UniRefIngEntity rev3 = getAuditReader().find(UniRefIngEntity.class, ing1_id, 3); + UniRefIngEntity rev1 = getAuditReader().find( UniRefIngEntity.class, ing1_id, 1 ); + UniRefIngEntity rev2 = getAuditReader().find( UniRefIngEntity.class, ing1_id, 2 ); + UniRefIngEntity rev3 = getAuditReader().find( UniRefIngEntity.class, ing1_id, 3 ); - assert rev1.getReference().equals(ed1); - assert rev2.getReference().equals(ed2); - assert rev3.getReference().equals(ed2); - } + assert rev1.getReference().equals( ed1 ); + assert rev2.getReference().equals( ed2 ); + assert rev3.getReference().equals( ed2 ); + } - @Test - public void testHistoryOfIngId2() { - UniRefEdEntity ed3 = getEntityManager().find(UniRefEdEntity.class, ed3_id); - UniRefEdEntity ed4 = getEntityManager().find(UniRefEdEntity.class, ed4_id); + @Test + public void testHistoryOfIngId2() { + UniRefEdEntity ed3 = getEntityManager().find( UniRefEdEntity.class, ed3_id ); + UniRefEdEntity ed4 = getEntityManager().find( UniRefEdEntity.class, ed4_id ); - UniRefIngEntity rev1 = getAuditReader().find(UniRefIngEntity.class, ing2_id, 1); - UniRefIngEntity rev2 = getAuditReader().find(UniRefIngEntity.class, ing2_id, 2); - UniRefIngEntity rev3 = getAuditReader().find(UniRefIngEntity.class, ing2_id, 3); + UniRefIngEntity rev1 = getAuditReader().find( UniRefIngEntity.class, ing2_id, 1 ); + UniRefIngEntity rev2 = getAuditReader().find( UniRefIngEntity.class, ing2_id, 2 ); + UniRefIngEntity rev3 = getAuditReader().find( UniRefIngEntity.class, ing2_id, 3 ); - assert rev1.getReference().equals(ed3); - assert rev2.getReference().equals(ed3); - assert rev3.getReference().equals(ed4); - } + assert rev1.getReference().equals( ed3 ); + assert rev2.getReference().equals( ed3 ); + assert rev3.getReference().equals( ed4 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UnidirectionalMulIdWithNulls.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UnidirectionalMulIdWithNulls.java index df5be2c0e2..8d6bb63ca8 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UnidirectionalMulIdWithNulls.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UnidirectionalMulIdWithNulls.java @@ -2,13 +2,13 @@ package org.hibernate.envers.test.integration.onetoone.unidirectional; import javax.persistence.EntityManager; -import org.junit.Test; - import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.ids.EmbId; import org.hibernate.envers.test.entities.ids.EmbIdTestEntity; +import org.junit.Test; + import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -17,43 +17,43 @@ import static org.junit.Assert.assertNull; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class UnidirectionalMulIdWithNulls extends BaseEnversJPAFunctionalTestCase { - private EmbId ei; + private EmbId ei; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { EmbIdTestEntity.class, UniRefIngMulIdEntity.class }; - } + return new Class[] {EmbIdTestEntity.class, UniRefIngMulIdEntity.class}; + } - @Test - @Priority(10) - public void initData() { - ei = new EmbId(1, 2); + @Test + @Priority(10) + public void initData() { + ei = new EmbId( 1, 2 ); - EntityManager em = getEntityManager(); - - // Revision 1 - EmbIdTestEntity eite = new EmbIdTestEntity(ei, "data"); - UniRefIngMulIdEntity notNullRef = new UniRefIngMulIdEntity(1, "data 1", eite); - UniRefIngMulIdEntity nullRef = new UniRefIngMulIdEntity(2, "data 2", null); + EntityManager em = getEntityManager(); - em.getTransaction().begin(); - em.persist(eite); - em.persist(notNullRef); - em.persist(nullRef); - em.getTransaction().commit(); - } + // Revision 1 + EmbIdTestEntity eite = new EmbIdTestEntity( ei, "data" ); + UniRefIngMulIdEntity notNullRef = new UniRefIngMulIdEntity( 1, "data 1", eite ); + UniRefIngMulIdEntity nullRef = new UniRefIngMulIdEntity( 2, "data 2", null ); - @Test - public void testNullReference() { - UniRefIngMulIdEntity nullRef = getAuditReader().find(UniRefIngMulIdEntity.class, 2, 1); - assertNull(nullRef.getReference()); - } + em.getTransaction().begin(); + em.persist( eite ); + em.persist( notNullRef ); + em.persist( nullRef ); + em.getTransaction().commit(); + } - @Test - public void testNotNullReference() { - EmbIdTestEntity eite = getAuditReader().find(EmbIdTestEntity.class, ei, 1); - UniRefIngMulIdEntity notNullRef = getAuditReader().find(UniRefIngMulIdEntity.class, 1, 1); - assertNotNull(notNullRef.getReference()); - assertEquals(notNullRef.getReference(), eite); - } + @Test + public void testNullReference() { + UniRefIngMulIdEntity nullRef = getAuditReader().find( UniRefIngMulIdEntity.class, 2, 1 ); + assertNull( nullRef.getReference() ); + } + + @Test + public void testNotNullReference() { + EmbIdTestEntity eite = getAuditReader().find( EmbIdTestEntity.class, ei, 1 ); + UniRefIngMulIdEntity notNullRef = getAuditReader().find( UniRefIngMulIdEntity.class, 1, 1 ); + assertNotNull( notNullRef.getReference() ); + assertEquals( notNullRef.getReference(), eite ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UnidirectionalWithNulls.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UnidirectionalWithNulls.java index 9b4135359e..86844395bf 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UnidirectionalWithNulls.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/onetoone/unidirectional/UnidirectionalWithNulls.java @@ -23,114 +23,114 @@ */ package org.hibernate.envers.test.integration.onetoone.unidirectional; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class UnidirectionalWithNulls extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ed2_id; + private Integer ed1_id; + private Integer ed2_id; - private Integer ing1_id; - private Integer ing2_id; + private Integer ing1_id; + private Integer ing2_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { UniRefEdEntity.class, UniRefIngEntity.class }; - } + return new Class[] {UniRefEdEntity.class, UniRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - UniRefEdEntity ed1 = new UniRefEdEntity(1, "data_ed_1"); - UniRefEdEntity ed2 = new UniRefEdEntity(2, "data_ed_2"); + @Test + @Priority(10) + public void initData() { + UniRefEdEntity ed1 = new UniRefEdEntity( 1, "data_ed_1" ); + UniRefEdEntity ed2 = new UniRefEdEntity( 2, "data_ed_2" ); - UniRefIngEntity ing1 = new UniRefIngEntity(3, "data_ing_1", ed1); - UniRefIngEntity ing2 = new UniRefIngEntity(4, "data_ing_2", null); + UniRefIngEntity ing1 = new UniRefIngEntity( 3, "data_ing_1", ed1 ); + UniRefIngEntity ing2 = new UniRefIngEntity( 4, "data_ing_2", null ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ed2); + em.persist( ed1 ); + em.persist( ed2 ); - em.persist(ing1); - em.persist(ing2); + em.persist( ing1 ); + em.persist( ing2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 + // Revision 2 - em = getEntityManager(); - em.getTransaction().begin(); + em = getEntityManager(); + em.getTransaction().begin(); - ing1 = em.find(UniRefIngEntity.class, ing1.getId()); + ing1 = em.find( UniRefIngEntity.class, ing1.getId() ); - ing1.setReference(null); + ing1.setReference( null ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 + // Revision 3 - em = getEntityManager(); - em.getTransaction().begin(); + em = getEntityManager(); + em.getTransaction().begin(); - ing2 = em.find(UniRefIngEntity.class, ing2.getId()); - ed2 = em.find(UniRefEdEntity.class, ed2.getId()); + ing2 = em.find( UniRefIngEntity.class, ing2.getId() ); + ed2 = em.find( UniRefEdEntity.class, ed2.getId() ); - ing2.setReference(ed2); + ing2.setReference( ed2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed1_id = ed1.getId(); - ed2_id = ed2.getId(); + ed1_id = ed1.getId(); + ed2_id = ed2.getId(); - ing1_id = ing1.getId(); - ing2_id = ing2.getId(); - } + ing1_id = ing1.getId(); + ing2_id = ing2.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1).equals(getAuditReader().getRevisions(UniRefEdEntity.class, ed1_id)); - assert Arrays.asList(1).equals(getAuditReader().getRevisions(UniRefEdEntity.class, ed2_id)); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( UniRefEdEntity.class, ed1_id ) ); + assert Arrays.asList( 1 ).equals( getAuditReader().getRevisions( UniRefEdEntity.class, ed2_id ) ); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(UniRefIngEntity.class, ing1_id)); - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(UniRefIngEntity.class, ing2_id)); - } + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( UniRefIngEntity.class, ing1_id ) ); + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( UniRefIngEntity.class, ing2_id ) ); + } - @Test - public void testHistoryOfIngId1() { - UniRefEdEntity ed1 = getEntityManager().find(UniRefEdEntity.class, ed1_id); + @Test + public void testHistoryOfIngId1() { + UniRefEdEntity ed1 = getEntityManager().find( UniRefEdEntity.class, ed1_id ); - UniRefIngEntity rev1 = getAuditReader().find(UniRefIngEntity.class, ing1_id, 1); - UniRefIngEntity rev2 = getAuditReader().find(UniRefIngEntity.class, ing1_id, 2); - UniRefIngEntity rev3 = getAuditReader().find(UniRefIngEntity.class, ing1_id, 3); + UniRefIngEntity rev1 = getAuditReader().find( UniRefIngEntity.class, ing1_id, 1 ); + UniRefIngEntity rev2 = getAuditReader().find( UniRefIngEntity.class, ing1_id, 2 ); + UniRefIngEntity rev3 = getAuditReader().find( UniRefIngEntity.class, ing1_id, 3 ); - assert rev1.getReference().equals(ed1); - assert rev2.getReference() == null; - assert rev3.getReference() == null; - } + assert rev1.getReference().equals( ed1 ); + assert rev2.getReference() == null; + assert rev3.getReference() == null; + } - @Test - public void testHistoryOfIngId2() { - UniRefEdEntity ed2 = getEntityManager().find(UniRefEdEntity.class, ed2_id); + @Test + public void testHistoryOfIngId2() { + UniRefEdEntity ed2 = getEntityManager().find( UniRefEdEntity.class, ed2_id ); - UniRefIngEntity rev1 = getAuditReader().find(UniRefIngEntity.class, ing2_id, 1); - UniRefIngEntity rev2 = getAuditReader().find(UniRefIngEntity.class, ing2_id, 2); - UniRefIngEntity rev3 = getAuditReader().find(UniRefIngEntity.class, ing2_id, 3); + UniRefIngEntity rev1 = getAuditReader().find( UniRefIngEntity.class, ing2_id, 1 ); + UniRefIngEntity rev2 = getAuditReader().find( UniRefIngEntity.class, ing2_id, 2 ); + UniRefIngEntity rev3 = getAuditReader().find( UniRefIngEntity.class, ing2_id, 3 ); - assert rev1.getReference() == null; - assert rev2.getReference() == null; - assert rev3.getReference().equals(ed2); - } + assert rev1.getReference() == null; + assert rev2.getReference() == null; + assert rev3.getReference().equals( ed2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/primitive/PrimitiveAddDelete.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/primitive/PrimitiveAddDelete.java index 13c051cf3c..6d79e1bbff 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/primitive/PrimitiveAddDelete.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/primitive/PrimitiveAddDelete.java @@ -23,77 +23,77 @@ */ package org.hibernate.envers.test.integration.primitive; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.PrimitiveTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class PrimitiveAddDelete extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{PrimitiveTestEntity.class}; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {PrimitiveTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); // Revision 1 - em.getTransaction().begin(); - PrimitiveTestEntity pte = new PrimitiveTestEntity(10, 11); - em.persist(pte); - id1 = pte.getId(); - em.getTransaction().commit(); + em.getTransaction().begin(); + PrimitiveTestEntity pte = new PrimitiveTestEntity( 10, 11 ); + em.persist( pte ); + id1 = pte.getId(); + em.getTransaction().commit(); // Revision 2 - em.getTransaction().begin(); - pte = em.find(PrimitiveTestEntity.class, id1); - pte.setNumVal1(20); - pte.setNumVal2(21); - em.getTransaction().commit(); + em.getTransaction().begin(); + pte = em.find( PrimitiveTestEntity.class, id1 ); + pte.setNumVal1( 20 ); + pte.setNumVal2( 21 ); + em.getTransaction().commit(); // Revision 3 - em.getTransaction().begin(); - pte = em.find(PrimitiveTestEntity.class, id1); - em.remove(pte); - em.getTransaction().commit(); - } + em.getTransaction().begin(); + pte = em.find( PrimitiveTestEntity.class, id1 ); + em.remove( pte ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(PrimitiveTestEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( PrimitiveTestEntity.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - PrimitiveTestEntity ver1 = new PrimitiveTestEntity(id1, 10, 0); - PrimitiveTestEntity ver2 = new PrimitiveTestEntity(id1, 20, 0); + @Test + public void testHistoryOfId1() { + PrimitiveTestEntity ver1 = new PrimitiveTestEntity( id1, 10, 0 ); + PrimitiveTestEntity ver2 = new PrimitiveTestEntity( id1, 20, 0 ); - assert getAuditReader().find(PrimitiveTestEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(PrimitiveTestEntity.class, id1, 2).equals(ver2); - assert getAuditReader().find(PrimitiveTestEntity.class, id1, 3) == null; - } + assert getAuditReader().find( PrimitiveTestEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( PrimitiveTestEntity.class, id1, 2 ).equals( ver2 ); + assert getAuditReader().find( PrimitiveTestEntity.class, id1, 3 ) == null; + } @Test public void testQueryWithDeleted() { // Selecting all entities, also the deleted ones - List entities = getAuditReader().createQuery().forRevisionsOfEntity(PrimitiveTestEntity.class, true, true) + List entities = getAuditReader().createQuery().forRevisionsOfEntity( PrimitiveTestEntity.class, true, true ) .getResultList(); assert entities.size() == 3; - assert entities.get(0).equals(new PrimitiveTestEntity(id1, 10, 0)); - assert entities.get(1).equals(new PrimitiveTestEntity(id1, 20, 0)); - assert entities.get(2).equals(new PrimitiveTestEntity(id1, 0, 0)); + assert entities.get( 0 ).equals( new PrimitiveTestEntity( id1, 10, 0 ) ); + assert entities.get( 1 ).equals( new PrimitiveTestEntity( id1, 20, 0 ) ); + assert entities.get( 2 ).equals( new PrimitiveTestEntity( id1, 0, 0 ) ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/properties/PropertiesTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/properties/PropertiesTestEntity.java index 6b0849e11f..b35991b088 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/properties/PropertiesTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/properties/PropertiesTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.properties; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -33,57 +34,65 @@ import org.hibernate.envers.Audited; */ @Entity public class PropertiesTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - private String str; + @Audited + private String str; - public PropertiesTestEntity() { - } + public PropertiesTestEntity() { + } - public PropertiesTestEntity(String str) { - this.str = str; - } + public PropertiesTestEntity(String str) { + this.str = str; + } - public PropertiesTestEntity(Integer id, String str) { - this.id = id; - this.str = str; - } + public PropertiesTestEntity(Integer id, String str) { + this.id = id; + this.str = str; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStr() { - return str; -} + public String getStr() { + return str; + } - public void setStr(String str) { - this.str = str; - } + public void setStr(String str) { + this.str = str; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof PropertiesTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof PropertiesTestEntity) ) { + return false; + } - PropertiesTestEntity that = (PropertiesTestEntity) o; + PropertiesTestEntity that = (PropertiesTestEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (str != null ? !str.equals(that.str) : that.str != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str != null ? !str.equals( that.str ) : that.str != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str != null ? str.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str != null ? str.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/properties/UnversionedOptimisticLockingField.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/properties/UnversionedOptimisticLockingField.java index eef446a43d..655d1f2dc0 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/properties/UnversionedOptimisticLockingField.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/properties/UnversionedOptimisticLockingField.java @@ -23,12 +23,10 @@ */ package org.hibernate.envers.test.integration.properties; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Iterator; import java.util.Map; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.configuration.EnversSettings; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -36,6 +34,8 @@ import org.hibernate.envers.test.Priority; import org.hibernate.mapping.PersistentClass; import org.hibernate.mapping.Property; +import org.junit.Test; + /** * @author Nicolas Doroskevich */ @@ -44,56 +44,59 @@ public class UnversionedOptimisticLockingField extends BaseEnversJPAFunctionalTe @Override protected Class[] getAnnotatedClasses() { - return new Class[] { UnversionedOptimisticLockingFieldEntity.class }; + return new Class[] {UnversionedOptimisticLockingFieldEntity.class}; } @Override public void addConfigOptions(Map configuration) { super.addConfigOptions( configuration ); - configuration.put(EnversSettings.DO_NOT_AUDIT_OPTIMISTIC_LOCKING_FIELD, "true"); + configuration.put( EnversSettings.DO_NOT_AUDIT_OPTIMISTIC_LOCKING_FIELD, "true" ); } @Test - @Priority(10) + @Priority(10) public void initData() { EntityManager em = getEntityManager(); em.getTransaction().begin(); - UnversionedOptimisticLockingFieldEntity olfe = new UnversionedOptimisticLockingFieldEntity("x"); - em.persist(olfe); + UnversionedOptimisticLockingFieldEntity olfe = new UnversionedOptimisticLockingFieldEntity( "x" ); + em.persist( olfe ); id1 = olfe.getId(); em.getTransaction().commit(); em.getTransaction().begin(); - olfe = em.find(UnversionedOptimisticLockingFieldEntity.class, id1); - olfe.setStr("y"); + olfe = em.find( UnversionedOptimisticLockingFieldEntity.class, id1 ); + olfe.setStr( "y" ); em.getTransaction().commit(); } @Test public void testRevisionCounts() { - assert Arrays.asList(1, 2).equals( - getAuditReader().getRevisions(UnversionedOptimisticLockingFieldEntity.class, - id1)); + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( + UnversionedOptimisticLockingFieldEntity.class, + id1 + ) + ); } @Test public void testHistoryOfId1() { - UnversionedOptimisticLockingFieldEntity ver1 = new UnversionedOptimisticLockingFieldEntity(id1, "x"); - UnversionedOptimisticLockingFieldEntity ver2 = new UnversionedOptimisticLockingFieldEntity(id1, "y"); - - assert getAuditReader().find(UnversionedOptimisticLockingFieldEntity.class, id1, 1) - .equals(ver1); - assert getAuditReader().find(UnversionedOptimisticLockingFieldEntity.class, id1, 2) - .equals(ver2); + UnversionedOptimisticLockingFieldEntity ver1 = new UnversionedOptimisticLockingFieldEntity( id1, "x" ); + UnversionedOptimisticLockingFieldEntity ver2 = new UnversionedOptimisticLockingFieldEntity( id1, "y" ); + + assert getAuditReader().find( UnversionedOptimisticLockingFieldEntity.class, id1, 1 ) + .equals( ver1 ); + assert getAuditReader().find( UnversionedOptimisticLockingFieldEntity.class, id1, 2 ) + .equals( ver2 ); } - + @Test public void testMapping() { - PersistentClass pc = getCfg().getClassMapping(UnversionedOptimisticLockingFieldEntity.class.getName() + "_AUD"); + PersistentClass pc = getCfg().getClassMapping( UnversionedOptimisticLockingFieldEntity.class.getName() + "_AUD" ); Iterator pi = pc.getPropertyIterator(); - while(pi.hasNext()) { + while ( pi.hasNext() ) { Property p = (Property) pi.next(); - assert !"optLocking".equals(p.getName()); + assert !"optLocking".equals( p.getName() ); } } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/properties/UnversionedOptimisticLockingFieldEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/properties/UnversionedOptimisticLockingFieldEntity.java index 2835bbe160..28a95924f0 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/properties/UnversionedOptimisticLockingFieldEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/properties/UnversionedOptimisticLockingFieldEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.properties; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -37,29 +38,29 @@ import org.hibernate.envers.Audited; @Table(name = "UnverOptimLockField") @Entity public class UnversionedOptimisticLockingFieldEntity { - - @Id - @GeneratedValue - private Integer id; - - private String str; - - @Version - private int optLocking; - - public UnversionedOptimisticLockingFieldEntity() { - } - - public UnversionedOptimisticLockingFieldEntity(String str) { - this.str = str; - } - - public UnversionedOptimisticLockingFieldEntity(Integer id, String str) { - this.id = id; - this.str = str; - } - - public Integer getId() { + + @Id + @GeneratedValue + private Integer id; + + private String str; + + @Version + private int optLocking; + + public UnversionedOptimisticLockingFieldEntity() { + } + + public UnversionedOptimisticLockingFieldEntity(String str) { + this.str = str; + } + + public UnversionedOptimisticLockingFieldEntity(Integer id, String str) { + this.id = id; + this.str = str; + } + + public Integer getId() { return id; } @@ -74,7 +75,7 @@ public class UnversionedOptimisticLockingFieldEntity { public void setStr(String str) { this.str = str; } - + public int getOptLocking() { return optLocking; } @@ -82,24 +83,32 @@ public class UnversionedOptimisticLockingFieldEntity { public void setOptLocking(int optLocking) { this.optLocking = optLocking; } - + public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof UnversionedOptimisticLockingFieldEntity)) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof UnversionedOptimisticLockingFieldEntity) ) { + return false; + } - UnversionedOptimisticLockingFieldEntity that = (UnversionedOptimisticLockingFieldEntity) o; + UnversionedOptimisticLockingFieldEntity that = (UnversionedOptimisticLockingFieldEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (str != null ? !str.equals(that.str) : that.str != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str != null ? !str.equals( that.str ) : that.str != null ) { + return false; + } - return true; - } + return true; + } + + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str != null ? str.hashCode() : 0); + return result; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str != null ? str.hashCode() : 0); - return result; - } - } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/properties/VersionsProperties.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/properties/VersionsProperties.java index 92c51d991a..6d98af0ec7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/properties/VersionsProperties.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/properties/VersionsProperties.java @@ -23,63 +23,63 @@ */ package org.hibernate.envers.test.integration.properties; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Map; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.configuration.EnversSettings; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class VersionsProperties extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { PropertiesTestEntity.class }; + return new Class[] {PropertiesTestEntity.class}; } @Override protected void addConfigOptions(Map options) { super.addConfigOptions( options ); - options.put(EnversSettings.AUDIT_TABLE_PREFIX, "VP_"); - options.put(EnversSettings.AUDIT_TABLE_SUFFIX, "_VS"); - options.put(EnversSettings.REVISION_FIELD_NAME, "ver_rev"); - options.put(EnversSettings.REVISION_TYPE_FIELD_NAME, "ver_rev_type"); + options.put( EnversSettings.AUDIT_TABLE_PREFIX, "VP_" ); + options.put( EnversSettings.AUDIT_TABLE_SUFFIX, "_VS" ); + options.put( EnversSettings.REVISION_FIELD_NAME, "ver_rev" ); + options.put( EnversSettings.REVISION_TYPE_FIELD_NAME, "ver_rev_type" ); } @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - PropertiesTestEntity pte = new PropertiesTestEntity("x"); - em.persist(pte); - id1 = pte.getId(); - em.getTransaction().commit(); + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + PropertiesTestEntity pte = new PropertiesTestEntity( "x" ); + em.persist( pte ); + id1 = pte.getId(); + em.getTransaction().commit(); - em.getTransaction().begin(); - pte = em.find(PropertiesTestEntity.class, id1); - pte.setStr("y"); - em.getTransaction().commit(); - } + em.getTransaction().begin(); + pte = em.find( PropertiesTestEntity.class, id1 ); + pte.setStr( "y" ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(PropertiesTestEntity.class, id1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( PropertiesTestEntity.class, id1 ) ); + } - @Test - public void testHistoryOfId1() { - PropertiesTestEntity ver1 = new PropertiesTestEntity(id1, "x"); - PropertiesTestEntity ver2 = new PropertiesTestEntity(id1, "y"); + @Test + public void testHistoryOfId1() { + PropertiesTestEntity ver1 = new PropertiesTestEntity( id1, "x" ); + PropertiesTestEntity ver2 = new PropertiesTestEntity( id1, "y" ); - assert getAuditReader().find(PropertiesTestEntity.class, id1, 1).equals(ver1); - assert getAuditReader().find(PropertiesTestEntity.class, id1, 2).equals(ver2); - } + assert getAuditReader().find( PropertiesTestEntity.class, id1, 1 ).equals( ver1 ); + assert getAuditReader().find( PropertiesTestEntity.class, id1, 2 ).equals( ver2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/proxy/AuditedCollectionProxyTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/proxy/AuditedCollectionProxyTest.java index 12149056ec..c29f86cf80 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/proxy/AuditedCollectionProxyTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/proxy/AuditedCollectionProxyTest.java @@ -25,76 +25,80 @@ package org.hibernate.envers.test.integration.proxy; import javax.persistence.EntityManager; -import org.junit.Test; - import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.onetomany.ListRefEdEntity; import org.hibernate.envers.test.entities.onetomany.ListRefIngEntity; import org.hibernate.proxy.HibernateProxy; +import org.junit.Test; + /** * Test case for HHH-5750: Proxied objects lose the temporary session used to * initialize them. - * + * * @author Erik-Berndt Scheper - * */ public class AuditedCollectionProxyTest extends BaseEnversJPAFunctionalTestCase { - Integer id_ListRefEdEntity1; + Integer id_ListRefEdEntity1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ListRefEdEntity.class, ListRefIngEntity.class }; - } + return new Class[] {ListRefEdEntity.class, ListRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - ListRefEdEntity listReferencedEntity1 = new ListRefEdEntity( - Integer.valueOf(1), "str1"); - ListRefIngEntity refingEntity1 = new ListRefIngEntity( - Integer.valueOf(1), "refing1", listReferencedEntity1); + ListRefEdEntity listReferencedEntity1 = new ListRefEdEntity( + Integer.valueOf( 1 ), "str1" + ); + ListRefIngEntity refingEntity1 = new ListRefIngEntity( + Integer.valueOf( 1 ), "refing1", listReferencedEntity1 + ); - // Revision 1 - em.getTransaction().begin(); - em.persist(listReferencedEntity1); - em.persist(refingEntity1); - em.getTransaction().commit(); + // Revision 1 + em.getTransaction().begin(); + em.persist( listReferencedEntity1 ); + em.persist( refingEntity1 ); + em.getTransaction().commit(); - id_ListRefEdEntity1 = listReferencedEntity1.getId(); + id_ListRefEdEntity1 = listReferencedEntity1.getId(); - // Revision 2 - ListRefIngEntity refingEntity2 = new ListRefIngEntity( - Integer.valueOf(2), "refing2", listReferencedEntity1); + // Revision 2 + ListRefIngEntity refingEntity2 = new ListRefIngEntity( + Integer.valueOf( 2 ), "refing2", listReferencedEntity1 + ); - em.getTransaction().begin(); - em.persist(refingEntity2); - em.getTransaction().commit(); - } + em.getTransaction().begin(); + em.persist( refingEntity2 ); + em.getTransaction().commit(); + } - @Test - public void testProxyIdentifier() { - EntityManager em = getEntityManager(); + @Test + public void testProxyIdentifier() { + EntityManager em = getEntityManager(); - ListRefEdEntity listReferencedEntity1 = em.getReference( - ListRefEdEntity.class, id_ListRefEdEntity1); + ListRefEdEntity listReferencedEntity1 = em.getReference( + ListRefEdEntity.class, id_ListRefEdEntity1 + ); - assert listReferencedEntity1 instanceof HibernateProxy; + assert listReferencedEntity1 instanceof HibernateProxy; - // Revision 3 - ListRefIngEntity refingEntity3 = new ListRefIngEntity( - Integer.valueOf(3), "refing3", listReferencedEntity1); + // Revision 3 + ListRefIngEntity refingEntity3 = new ListRefIngEntity( + Integer.valueOf( 3 ), "refing3", listReferencedEntity1 + ); - em.getTransaction().begin(); - em.persist(refingEntity3); - em.getTransaction().commit(); + em.getTransaction().begin(); + em.persist( refingEntity3 ); + em.getTransaction().commit(); - listReferencedEntity1.getReffering().size(); + listReferencedEntity1.getReffering().size(); - } + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/proxy/ProxyIdentifier.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/proxy/ProxyIdentifier.java index fb08cb875c..95b010430d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/proxy/ProxyIdentifier.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/proxy/ProxyIdentifier.java @@ -25,8 +25,6 @@ package org.hibernate.envers.test.integration.proxy; import javax.persistence.EntityManager; -import org.junit.Test; - import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.UnversionedStrTestEntity; @@ -34,55 +32,57 @@ import org.hibernate.envers.test.entities.manytoone.unidirectional.TargetNotAudi import org.hibernate.proxy.HibernateProxy; import org.hibernate.proxy.LazyInitializer; +import org.junit.Test; + /** * @author Eugene Goroschenya */ public class ProxyIdentifier extends BaseEnversJPAFunctionalTestCase { - private TargetNotAuditedEntity tnae1; - private UnversionedStrTestEntity uste1; + private TargetNotAuditedEntity tnae1; + private UnversionedStrTestEntity uste1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { TargetNotAuditedEntity.class, UnversionedStrTestEntity.class }; - } + return new Class[] {TargetNotAuditedEntity.class, UnversionedStrTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - uste1 = new UnversionedStrTestEntity("str1"); + uste1 = new UnversionedStrTestEntity( "str1" ); - // No revision - em.getTransaction().begin(); - em.persist(uste1); - em.getTransaction().commit(); + // No revision + em.getTransaction().begin(); + em.persist( uste1 ); + em.getTransaction().commit(); - // Revision 1 - em.getTransaction().begin(); - uste1 = em.find(UnversionedStrTestEntity.class, uste1.getId()); - tnae1 = new TargetNotAuditedEntity(1, "tnae1", uste1); - em.persist(tnae1); - em.getTransaction().commit(); - } + // Revision 1 + em.getTransaction().begin(); + uste1 = em.find( UnversionedStrTestEntity.class, uste1.getId() ); + tnae1 = new TargetNotAuditedEntity( 1, "tnae1", uste1 ); + em.persist( tnae1 ); + em.getTransaction().commit(); + } - @Test - public void testProxyIdentifier() { - TargetNotAuditedEntity rev1 = getAuditReader().find(TargetNotAuditedEntity.class, tnae1.getId(), 1); + @Test + public void testProxyIdentifier() { + TargetNotAuditedEntity rev1 = getAuditReader().find( TargetNotAuditedEntity.class, tnae1.getId(), 1 ); - assert rev1.getReference() instanceof HibernateProxy; + assert rev1.getReference() instanceof HibernateProxy; - HibernateProxy proxyCreateByEnvers = (HibernateProxy) rev1.getReference(); - LazyInitializer lazyInitializer = proxyCreateByEnvers.getHibernateLazyInitializer(); + HibernateProxy proxyCreateByEnvers = (HibernateProxy) rev1.getReference(); + LazyInitializer lazyInitializer = proxyCreateByEnvers.getHibernateLazyInitializer(); - assert lazyInitializer.isUninitialized(); - assert lazyInitializer.getIdentifier() != null; - assert lazyInitializer.getIdentifier().equals(tnae1.getId()); - assert lazyInitializer.isUninitialized(); + assert lazyInitializer.isUninitialized(); + assert lazyInitializer.getIdentifier() != null; + assert lazyInitializer.getIdentifier().equals( tnae1.getId() ); + assert lazyInitializer.isUninitialized(); - assert rev1.getReference().getId().equals(uste1.getId()); - assert rev1.getReference().getStr().equals(uste1.getStr()); - assert !lazyInitializer.isUninitialized(); - } + assert rev1.getReference().getId().equals( uste1.getId() ); + assert rev1.getReference().getStr().equals( uste1.getStr() ); + assert !lazyInitializer.isUninitialized(); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/proxy/QueryingWithProxyObjectTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/proxy/QueryingWithProxyObjectTest.java index effb0f3958..c411e82256 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/proxy/QueryingWithProxyObjectTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/proxy/QueryingWithProxyObjectTest.java @@ -3,62 +3,69 @@ package org.hibernate.envers.test.integration.proxy; import java.util.Arrays; import java.util.List; -import org.junit.Assert; -import org.junit.Test; - import org.hibernate.envers.test.BaseEnversFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class QueryingWithProxyObjectTest extends BaseEnversFunctionalTestCase { - private Integer id = null; + private Integer id = null; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{ StrTestEntity.class}; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {StrTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - getSession().getTransaction().begin(); - StrTestEntity ste = new StrTestEntity("data"); - getSession().persist(ste); - getSession().getTransaction().commit(); - id = ste.getId(); - getSession().close(); - } + @Test + @Priority(10) + public void initData() { + // Revision 1 + getSession().getTransaction().begin(); + StrTestEntity ste = new StrTestEntity( "data" ); + getSession().persist( ste ); + getSession().getTransaction().commit(); + id = ste.getId(); + getSession().close(); + } - @Test - @TestForIssue(jiraKey="HHH-4760") - @SuppressWarnings("unchecked") - public void testQueryingWithProxyObject() { - StrTestEntity originalSte = new StrTestEntity("data", id); - // Load the proxy instance - StrTestEntity proxySte = (StrTestEntity) getSession().load(StrTestEntity.class, id); + @Test + @TestForIssue(jiraKey = "HHH-4760") + @SuppressWarnings("unchecked") + public void testQueryingWithProxyObject() { + StrTestEntity originalSte = new StrTestEntity( "data", id ); + // Load the proxy instance + StrTestEntity proxySte = (StrTestEntity) getSession().load( StrTestEntity.class, id ); - Assert.assertTrue(getAuditReader().isEntityClassAudited(proxySte.getClass())); + Assert.assertTrue( getAuditReader().isEntityClassAudited( proxySte.getClass() ) ); - StrTestEntity ste = getAuditReader().find(proxySte.getClass(), proxySte.getId(), 1); - Assert.assertEquals(originalSte, ste); + StrTestEntity ste = getAuditReader().find( proxySte.getClass(), proxySte.getId(), 1 ); + Assert.assertEquals( originalSte, ste ); - List revisions = getAuditReader().getRevisions(proxySte.getClass(), proxySte.getId()); - Assert.assertEquals(Arrays.asList(1), revisions); + List revisions = getAuditReader().getRevisions( proxySte.getClass(), proxySte.getId() ); + Assert.assertEquals( Arrays.asList( 1 ), revisions ); - List entities = getAuditReader().createQuery().forEntitiesAtRevision(proxySte.getClass(), 1).getResultList(); - Assert.assertEquals(Arrays.asList(originalSte), entities); + List entities = getAuditReader().createQuery() + .forEntitiesAtRevision( proxySte.getClass(), 1 ) + .getResultList(); + Assert.assertEquals( Arrays.asList( originalSte ), entities ); - ste = (StrTestEntity) getAuditReader().createQuery().forRevisionsOfEntity(proxySte.getClass(), true, false).getSingleResult(); - Assert.assertEquals(originalSte, ste); + ste = (StrTestEntity) getAuditReader().createQuery() + .forRevisionsOfEntity( proxySte.getClass(), true, false ) + .getSingleResult(); + Assert.assertEquals( originalSte, ste ); - ste = (StrTestEntity) getAuditReader().createQuery().forEntitiesModifiedAtRevision(proxySte.getClass(), 1).getSingleResult(); - Assert.assertEquals(originalSte, ste); + ste = (StrTestEntity) getAuditReader().createQuery() + .forEntitiesModifiedAtRevision( proxySte.getClass(), 1 ) + .getSingleResult(); + Assert.assertEquals( originalSte, ste ); - getSession().close(); - } + getSession().close(); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/proxy/RemovedObjectQueryTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/proxy/RemovedObjectQueryTest.java index 7f56a97947..5fb9cc8d3d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/proxy/RemovedObjectQueryTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/proxy/RemovedObjectQueryTest.java @@ -1,13 +1,10 @@ package org.hibernate.envers.test.integration.proxy; +import javax.persistence.EntityManager; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; import org.hibernate.Hibernate; import org.hibernate.envers.RevisionType; @@ -27,6 +24,10 @@ import org.hibernate.envers.test.entities.onetomany.SetRefEdEntity; import org.hibernate.envers.test.entities.onetomany.SetRefIngEntity; import org.hibernate.envers.test.integration.manytomany.ternary.TernaryMapEntity; import org.hibernate.envers.test.tools.TestTools; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -172,7 +173,10 @@ public class RemovedObjectQueryTest extends BaseEnversJPAFunctionalTestCase { em.getTransaction().begin(); unversionedEntity1 = new UnversionedStrTestEntity( "string 1" ); unversionedEntity2 = new UnversionedStrTestEntity( "string 2" ); - M2MIndexedListTargetNotAuditedEntity relationNotAuditedEntity = new M2MIndexedListTargetNotAuditedEntity( 1, "Parent" ); + M2MIndexedListTargetNotAuditedEntity relationNotAuditedEntity = new M2MIndexedListTargetNotAuditedEntity( + 1, + "Parent" + ); relationNotAuditedEntity.getReferences().add( unversionedEntity1 ); relationNotAuditedEntity.getReferences().add( unversionedEntity2 ); em.persist( unversionedEntity1 ); @@ -182,7 +186,10 @@ public class RemovedObjectQueryTest extends BaseEnversJPAFunctionalTestCase { // Revision 14 - removing entity with unversioned relation em.getTransaction().begin(); - relationNotAuditedEntity = em.find( M2MIndexedListTargetNotAuditedEntity.class, relationNotAuditedEntity.getId() ); + relationNotAuditedEntity = em.find( + M2MIndexedListTargetNotAuditedEntity.class, + relationNotAuditedEntity.getId() + ); em.remove( relationNotAuditedEntity ); em.getTransaction().commit(); @@ -225,12 +232,16 @@ public class RemovedObjectQueryTest extends BaseEnversJPAFunctionalTestCase { Assert.assertEquals( 16, getRevisionNumber( objArray[1] ) ); TernaryMapEntity mapEntity = (TernaryMapEntity) objArray[0]; - Assert.assertEquals( TestTools.makeMap( intEntity1, stringEntity1, intEntity2, stringEntity2 ), mapEntity.getMap() ); + Assert.assertEquals( + TestTools.makeMap( intEntity1, stringEntity1, intEntity2, stringEntity2 ), + mapEntity.getMap() + ); } @Test public void testUnversionedRelation() { - List queryResult = getAuditReader().createQuery().forRevisionsOfEntity( M2MIndexedListTargetNotAuditedEntity.class, false, true ) + List queryResult = getAuditReader().createQuery() + .forRevisionsOfEntity( M2MIndexedListTargetNotAuditedEntity.class, false, true ) .add( AuditEntity.id().eq( 1 ) ) .add( AuditEntity.revisionType().eq( RevisionType.DEL ) ) .getResultList(); @@ -440,6 +451,6 @@ public class RemovedObjectQueryTest extends BaseEnversJPAFunctionalTestCase { } private Number getRevisionNumber(Object revisionEntity) { - return ( (SequenceIdRevisionEntity) revisionEntity ).getId(); + return ((SequenceIdRevisionEntity) revisionEntity).getId(); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/AggregateQuery.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/AggregateQuery.java index 5f04155a06..d0a2c04295 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/AggregateQuery.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/AggregateQuery.java @@ -23,12 +23,9 @@ */ package org.hibernate.envers.test.integration.query; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; import org.hibernate.envers.query.AuditEntity; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -36,6 +33,10 @@ import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.IntTestEntity; import org.hibernate.envers.test.entities.ids.UnusualIdNamingEntity; import org.hibernate.envers.test.tools.TestTools; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -45,75 +46,75 @@ import org.hibernate.testing.TestForIssue; public class AggregateQuery extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { IntTestEntity.class, UnusualIdNamingEntity.class }; + return new Class[] {IntTestEntity.class, UnusualIdNamingEntity.class}; } @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); // Revision 1 - em.getTransaction().begin(); - IntTestEntity ite1 = new IntTestEntity(2); - IntTestEntity ite2 = new IntTestEntity(10); - em.persist(ite1); - em.persist(ite2); - Integer id1 = ite1.getId(); - Integer id2 = ite2.getId(); - em.getTransaction().commit(); + em.getTransaction().begin(); + IntTestEntity ite1 = new IntTestEntity( 2 ); + IntTestEntity ite2 = new IntTestEntity( 10 ); + em.persist( ite1 ); + em.persist( ite2 ); + Integer id1 = ite1.getId(); + Integer id2 = ite2.getId(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); - IntTestEntity ite3 = new IntTestEntity(8); + // Revision 2 + em.getTransaction().begin(); + IntTestEntity ite3 = new IntTestEntity( 8 ); UnusualIdNamingEntity uine1 = new UnusualIdNamingEntity( "id1", "data1" ); em.persist( uine1 ); - em.persist(ite3); - ite1 = em.find(IntTestEntity.class, id1); - ite1.setNumber(0); - em.getTransaction().commit(); + em.persist( ite3 ); + ite1 = em.find( IntTestEntity.class, id1 ); + ite1.setNumber( 0 ); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); - ite2 = em.find(IntTestEntity.class, id2); - ite2.setNumber(52); - em.getTransaction().commit(); + // Revision 3 + em.getTransaction().begin(); + ite2 = em.find( IntTestEntity.class, id2 ); + ite2.setNumber( 52 ); + em.getTransaction().commit(); em.close(); - } - - @Test - public void testEntitiesAvgMaxQuery() { - Object[] ver1 = (Object[]) getAuditReader().createQuery() - .forEntitiesAtRevision(IntTestEntity.class, 1) - .addProjection(AuditEntity.property("number").max()) - .addProjection(AuditEntity.property("number").function("avg")) - .getSingleResult(); - - Object[] ver2 = (Object[]) getAuditReader().createQuery() - .forEntitiesAtRevision(IntTestEntity.class, 2) - .addProjection(AuditEntity.property("number").max()) - .addProjection(AuditEntity.property("number").function("avg")) - .getSingleResult(); - - Object[] ver3 = (Object[]) getAuditReader().createQuery() - .forEntitiesAtRevision(IntTestEntity.class, 3) - .addProjection(AuditEntity.property("number").max()) - .addProjection(AuditEntity.property("number").function("avg")) - .getSingleResult(); - - assert (Integer) ver1[0] == 10; - assert (Double) ver1[1] == 6.0; - - assert (Integer) ver2[0] == 10; - assert (Double) ver2[1] == 6.0; - - assert (Integer) ver3[0] == 52; - assert (Double) ver3[1] == 20.0; - } + } @Test - @TestForIssue( jiraKey = "HHH-8036" ) + public void testEntitiesAvgMaxQuery() { + Object[] ver1 = (Object[]) getAuditReader().createQuery() + .forEntitiesAtRevision( IntTestEntity.class, 1 ) + .addProjection( AuditEntity.property( "number" ).max() ) + .addProjection( AuditEntity.property( "number" ).function( "avg" ) ) + .getSingleResult(); + + Object[] ver2 = (Object[]) getAuditReader().createQuery() + .forEntitiesAtRevision( IntTestEntity.class, 2 ) + .addProjection( AuditEntity.property( "number" ).max() ) + .addProjection( AuditEntity.property( "number" ).function( "avg" ) ) + .getSingleResult(); + + Object[] ver3 = (Object[]) getAuditReader().createQuery() + .forEntitiesAtRevision( IntTestEntity.class, 3 ) + .addProjection( AuditEntity.property( "number" ).max() ) + .addProjection( AuditEntity.property( "number" ).function( "avg" ) ) + .getSingleResult(); + + assert (Integer) ver1[0] == 10; + assert (Double) ver1[1] == 6.0; + + assert (Integer) ver2[0] == 10; + assert (Double) ver2[1] == 6.0; + + assert (Integer) ver3[0] == 52; + assert (Double) ver3[1] == 20.0; + } + + @Test + @TestForIssue(jiraKey = "HHH-8036") public void testEntityIdProjection() { Integer maxId = (Integer) getAuditReader().createQuery().forRevisionsOfEntity( IntTestEntity.class, true, true ) .addProjection( AuditEntity.id().max() ) @@ -123,22 +124,31 @@ public class AggregateQuery extends BaseEnversJPAFunctionalTestCase { } @Test - @TestForIssue( jiraKey = "HHH-8036" ) + @TestForIssue(jiraKey = "HHH-8036") public void testEntityIdRestriction() { - List list = getAuditReader().createQuery().forRevisionsOfEntity( IntTestEntity.class, true, true ) + List list = getAuditReader().createQuery().forRevisionsOfEntity( + IntTestEntity.class, + true, + true + ) .add( AuditEntity.id().between( 2, 3 ) ) .getResultList(); Assert.assertTrue( - TestTools.checkList( list, + TestTools.checkList( + list, new IntTestEntity( 10, 2 ), new IntTestEntity( 8, 3 ), new IntTestEntity( 52, 2 ) ) ); } @Test - @TestForIssue( jiraKey = "HHH-8036" ) + @TestForIssue(jiraKey = "HHH-8036") public void testEntityIdOrdering() { - List list = getAuditReader().createQuery().forRevisionsOfEntity( IntTestEntity.class, true, true ) + List list = getAuditReader().createQuery().forRevisionsOfEntity( + IntTestEntity.class, + true, + true + ) .add( AuditEntity.revisionNumber().lt( 2 ) ) .addOrder( AuditEntity.id().desc() ) .getResultList(); @@ -146,7 +156,7 @@ public class AggregateQuery extends BaseEnversJPAFunctionalTestCase { } @Test - @TestForIssue( jiraKey = "HHH-8036" ) + @TestForIssue(jiraKey = "HHH-8036") public void testUnusualIdFieldName() { UnusualIdNamingEntity entity = (UnusualIdNamingEntity) getAuditReader().createQuery() .forRevisionsOfEntity( UnusualIdNamingEntity.class, true, true ) @@ -156,20 +166,20 @@ public class AggregateQuery extends BaseEnversJPAFunctionalTestCase { } @Test - @TestForIssue( jiraKey = "HHH-8036" ) + @TestForIssue(jiraKey = "HHH-8036") public void testEntityIdModifiedFlagNotSupported() { try { getAuditReader().createQuery().forRevisionsOfEntity( IntTestEntity.class, true, true ) .add( AuditEntity.id().hasChanged() ) .getResultList(); } - catch ( UnsupportedOperationException e1 ) { + catch (UnsupportedOperationException e1) { try { getAuditReader().createQuery().forRevisionsOfEntity( IntTestEntity.class, true, true ) .add( AuditEntity.id().hasNotChanged() ) .getResultList(); } - catch ( UnsupportedOperationException e2 ) { + catch (UnsupportedOperationException e2) { return; } Assert.fail(); diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/CustomRevEntityQuery.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/CustomRevEntityQuery.java index 5403661968..5fb1e47009 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/CustomRevEntityQuery.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/CustomRevEntityQuery.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.query; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.query.AuditEntity; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -34,93 +32,95 @@ import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrIntTestEntity; import org.hibernate.envers.test.entities.reventity.CustomRevEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ @SuppressWarnings({"unchecked"}) public class CustomRevEntityQuery extends BaseEnversJPAFunctionalTestCase { - private Integer id1; - private Integer id2; - private Long timestamp; + private Integer id1; + private Integer id2; + private Long timestamp; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrIntTestEntity.class, CustomRevEntity.class }; - } + return new Class[] {StrIntTestEntity.class, CustomRevEntity.class}; + } - @Test - @Priority(10) - public void initData() throws InterruptedException { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() throws InterruptedException { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - StrIntTestEntity site1 = new StrIntTestEntity("a", 10); - StrIntTestEntity site2 = new StrIntTestEntity("b", 15); + StrIntTestEntity site1 = new StrIntTestEntity( "a", 10 ); + StrIntTestEntity site2 = new StrIntTestEntity( "b", 15 ); - em.persist(site1); - em.persist(site2); + em.persist( site1 ); + em.persist( site2 ); - id1 = site1.getId(); - id2 = site2.getId(); + id1 = site1.getId(); + id2 = site2.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); - Thread.sleep(100); + Thread.sleep( 100 ); - timestamp = System.currentTimeMillis(); + timestamp = System.currentTimeMillis(); - Thread.sleep(100); + Thread.sleep( 100 ); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - site1 = em.find(StrIntTestEntity.class, id1); + site1 = em.find( StrIntTestEntity.class, id1 ); - site1.setStr1("c"); + site1.setStr1( "c" ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsOfId1Query() { - List result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .add(AuditEntity.id().eq(id1)) - .getResultList(); + @Test + public void testRevisionsOfId1Query() { + List result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .add( AuditEntity.id().eq( id1 ) ) + .getResultList(); - assert result.get(0)[0].equals(new StrIntTestEntity("a", 10, id1)); - assert result.get(0)[1] instanceof CustomRevEntity; - assert ((CustomRevEntity) result.get(0)[1]).getCustomId() == 1; + assert result.get( 0 )[0].equals( new StrIntTestEntity( "a", 10, id1 ) ); + assert result.get( 0 )[1] instanceof CustomRevEntity; + assert ((CustomRevEntity) result.get( 0 )[1]).getCustomId() == 1; - assert result.get(1)[0].equals(new StrIntTestEntity("c", 10, id1)); - assert result.get(1)[1] instanceof CustomRevEntity; - assert ((CustomRevEntity) result.get(1)[1]).getCustomId() == 2; - } + assert result.get( 1 )[0].equals( new StrIntTestEntity( "c", 10, id1 ) ); + assert result.get( 1 )[1] instanceof CustomRevEntity; + assert ((CustomRevEntity) result.get( 1 )[1]).getCustomId() == 2; + } - @Test - public void testRevisionsOfId2Query() { - List result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .add(AuditEntity.id().eq(id2)) - .getResultList(); + @Test + public void testRevisionsOfId2Query() { + List result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .add( AuditEntity.id().eq( id2 ) ) + .getResultList(); - assert result.get(0)[0].equals(new StrIntTestEntity("b", 15, id2)); - assert result.get(0)[1] instanceof CustomRevEntity; - assert ((CustomRevEntity) result.get(0)[1]).getCustomId() == 1; - } + assert result.get( 0 )[0].equals( new StrIntTestEntity( "b", 15, id2 ) ); + assert result.get( 0 )[1] instanceof CustomRevEntity; + assert ((CustomRevEntity) result.get( 0 )[1]).getCustomId() == 1; + } - @Test - public void testRevisionPropertyRestriction() { - List result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .add(AuditEntity.id().eq(id1)) - .add(AuditEntity.revisionProperty("customTimestamp").ge(timestamp)) - .getResultList(); + @Test + public void testRevisionPropertyRestriction() { + List result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .add( AuditEntity.id().eq( id1 ) ) + .add( AuditEntity.revisionProperty( "customTimestamp" ).ge( timestamp ) ) + .getResultList(); - assert result.get(0)[0].equals(new StrIntTestEntity("c", 10, id1)); - assert result.get(0)[1] instanceof CustomRevEntity; - assert ((CustomRevEntity) result.get(0)[1]).getCustomId() == 2; - assert ((CustomRevEntity) result.get(0)[1]).getCustomTimestamp() >= timestamp; - } + assert result.get( 0 )[0].equals( new StrIntTestEntity( "c", 10, id1 ) ); + assert result.get( 0 )[1] instanceof CustomRevEntity; + assert ((CustomRevEntity) result.get( 0 )[1]).getCustomId() == 2; + assert ((CustomRevEntity) result.get( 0 )[1]).getCustomTimestamp() >= timestamp; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/DeletedEntities.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/DeletedEntities.java index 88961086c4..32920cbbc1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/DeletedEntities.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/DeletedEntities.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.query; -import java.util.List; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.List; import org.hibernate.envers.RevisionType; import org.hibernate.envers.enhanced.SequenceIdRevisionEntity; @@ -35,67 +33,69 @@ import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrIntTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class DeletedEntities extends BaseEnversJPAFunctionalTestCase { - private Integer id2; + private Integer id2; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrIntTestEntity.class }; - } + return new Class[] {StrIntTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - StrIntTestEntity site1 = new StrIntTestEntity("a", 10); - StrIntTestEntity site2 = new StrIntTestEntity("b", 11); + StrIntTestEntity site1 = new StrIntTestEntity( "a", 10 ); + StrIntTestEntity site2 = new StrIntTestEntity( "b", 11 ); - em.persist(site1); - em.persist(site2); + em.persist( site1 ); + em.persist( site2 ); - id2 = site2.getId(); + id2 = site2.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - site2 = em.find(StrIntTestEntity.class, id2); - em.remove(site2); + site2 = em.find( StrIntTestEntity.class, id2 ); + em.remove( site2 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testProjectionsInEntitiesAtRevision() { - assert getAuditReader().createQuery().forEntitiesAtRevision(StrIntTestEntity.class, 1) - .getResultList().size() == 2; - assert getAuditReader().createQuery().forEntitiesAtRevision(StrIntTestEntity.class, 2) - .getResultList().size() == 1; + @Test + public void testProjectionsInEntitiesAtRevision() { + assert getAuditReader().createQuery().forEntitiesAtRevision( StrIntTestEntity.class, 1 ) + .getResultList().size() == 2; + assert getAuditReader().createQuery().forEntitiesAtRevision( StrIntTestEntity.class, 2 ) + .getResultList().size() == 1; - assert (Long) getAuditReader().createQuery().forEntitiesAtRevision(StrIntTestEntity.class, 1) - .addProjection(AuditEntity.id().count("id")).getResultList().get(0) == 2; - assert (Long) getAuditReader().createQuery().forEntitiesAtRevision(StrIntTestEntity.class, 2) - .addProjection(AuditEntity.id().count()).getResultList().get(0) == 1; - } + assert (Long) getAuditReader().createQuery().forEntitiesAtRevision( StrIntTestEntity.class, 1 ) + .addProjection( AuditEntity.id().count( "id" ) ).getResultList().get( 0 ) == 2; + assert (Long) getAuditReader().createQuery().forEntitiesAtRevision( StrIntTestEntity.class, 2 ) + .addProjection( AuditEntity.id().count() ).getResultList().get( 0 ) == 1; + } - @Test - public void testRevisionsOfEntityWithoutDelete() { - List result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, false) - .add(AuditEntity.id().eq(id2)) - .getResultList(); + @Test + public void testRevisionsOfEntityWithoutDelete() { + List result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, false ) + .add( AuditEntity.id().eq( id2 ) ) + .getResultList(); - assert result.size() == 1; + assert result.size() == 1; - assert ((Object []) result.get(0))[0].equals(new StrIntTestEntity("b", 11, id2)); - assert ((SequenceIdRevisionEntity) ((Object []) result.get(0))[1]).getId() == 1; - assert ((Object []) result.get(0))[2].equals(RevisionType.ADD); - } + assert ((Object[]) result.get( 0 ))[0].equals( new StrIntTestEntity( "b", 11, id2 ) ); + assert ((SequenceIdRevisionEntity) ((Object[]) result.get( 0 ))[1]).getId() == 1; + assert ((Object[]) result.get( 0 ))[2].equals( RevisionType.ADD ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/MaximalizePropertyQuery.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/MaximalizePropertyQuery.java index ed80431564..62a322d2ca 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/MaximalizePropertyQuery.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/MaximalizePropertyQuery.java @@ -23,14 +23,11 @@ */ package org.hibernate.envers.test.integration.query; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; -import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; import org.hibernate.envers.RevisionType; import org.hibernate.envers.enhanced.SequenceIdRevisionEntity; @@ -39,6 +36,10 @@ import org.hibernate.envers.query.criteria.AuditDisjunction; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrIntTestEntity; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -47,115 +48,121 @@ import org.hibernate.testing.TestForIssue; */ @SuppressWarnings({"unchecked"}) public class MaximalizePropertyQuery extends BaseEnversJPAFunctionalTestCase { - Integer id1; - Integer id2; - Integer id3; - Integer id4; + Integer id1; + Integer id2; + Integer id3; + Integer id4; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrIntTestEntity.class }; - } + return new Class[] {StrIntTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - StrIntTestEntity site1 = new StrIntTestEntity("a", 10); - StrIntTestEntity site2 = new StrIntTestEntity("b", 15); - StrIntTestEntity site3 = new StrIntTestEntity("c", 42); - StrIntTestEntity site4 = new StrIntTestEntity("d", 52); + StrIntTestEntity site1 = new StrIntTestEntity( "a", 10 ); + StrIntTestEntity site2 = new StrIntTestEntity( "b", 15 ); + StrIntTestEntity site3 = new StrIntTestEntity( "c", 42 ); + StrIntTestEntity site4 = new StrIntTestEntity( "d", 52 ); - em.persist(site1); - em.persist(site2); - em.persist(site3); - em.persist(site4); + em.persist( site1 ); + em.persist( site2 ); + em.persist( site3 ); + em.persist( site4 ); - id1 = site1.getId(); - id2 = site2.getId(); - id3 = site3.getId(); - id4 = site4.getId(); + id1 = site1.getId(); + id2 = site2.getId(); + id3 = site3.getId(); + id4 = site4.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - site1 = em.find(StrIntTestEntity.class, id1); - site2 = em.find(StrIntTestEntity.class, id2); + site1 = em.find( StrIntTestEntity.class, id1 ); + site2 = em.find( StrIntTestEntity.class, id2 ); - site1.setStr1("d"); - site2.setNumber(20); + site1.setStr1( "d" ); + site2.setNumber( 20 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - site1 = em.find(StrIntTestEntity.class, id1); - site2 = em.find(StrIntTestEntity.class, id2); + site1 = em.find( StrIntTestEntity.class, id1 ); + site2 = em.find( StrIntTestEntity.class, id2 ); - site1.setNumber(30); - site2.setStr1("z"); + site1.setNumber( 30 ); + site2.setStr1( "z" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); + // Revision 4 + em.getTransaction().begin(); - site1 = em.find(StrIntTestEntity.class, id1); - site2 = em.find(StrIntTestEntity.class, id2); + site1 = em.find( StrIntTestEntity.class, id1 ); + site2 = em.find( StrIntTestEntity.class, id2 ); - site1.setNumber(5); - site2.setStr1("a"); + site1.setNumber( 5 ); + site2.setStr1( "a" ); - em.getTransaction().commit(); + em.getTransaction().commit(); // Revision 5 em.getTransaction().begin(); site4 = em.find( StrIntTestEntity.class, id4 ); em.remove( site4 ); em.getTransaction().commit(); - } + } - @Test - public void testMaximizeWithIdEq() { - List revs_id1 = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .addProjection(AuditEntity.revisionNumber()) - .add(AuditEntity.property("number").maximize() - .add(AuditEntity.id().eq(id2))) - .getResultList(); + @Test + public void testMaximizeWithIdEq() { + List revs_id1 = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .addProjection( AuditEntity.revisionNumber() ) + .add( + AuditEntity.property( "number" ).maximize() + .add( AuditEntity.id().eq( id2 ) ) + ) + .getResultList(); - assert Arrays.asList(2, 3, 4).equals(revs_id1); - } + assert Arrays.asList( 2, 3, 4 ).equals( revs_id1 ); + } - @Test - public void testMinimizeWithPropertyEq() { - List result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .addProjection(AuditEntity.revisionNumber()) - .add(AuditEntity.property("number").minimize() - .add(AuditEntity.property("str1").eq("a"))) - .getResultList(); + @Test + public void testMinimizeWithPropertyEq() { + List result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .addProjection( AuditEntity.revisionNumber() ) + .add( + AuditEntity.property( "number" ).minimize() + .add( AuditEntity.property( "str1" ).eq( "a" ) ) + ) + .getResultList(); - assert Arrays.asList(1).equals(result); - } + assert Arrays.asList( 1 ).equals( result ); + } - @Test - public void testMaximizeRevision() { - List result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .addProjection(AuditEntity.revisionNumber()) - .add(AuditEntity.revisionNumber().maximize() - .add(AuditEntity.property("number").eq(10))) - .getResultList(); + @Test + public void testMaximizeRevision() { + List result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .addProjection( AuditEntity.revisionNumber() ) + .add( + AuditEntity.revisionNumber().maximize() + .add( AuditEntity.property( "number" ).eq( 10 ) ) + ) + .getResultList(); - assert Arrays.asList(2).equals(result); - } + assert Arrays.asList( 2 ).equals( result ); + } @Test @TestForIssue(jiraKey = "HHH-7800") @@ -207,7 +214,7 @@ public class MaximalizePropertyQuery extends BaseEnversJPAFunctionalTestCase { private void checkRevisionData(Object[] result, int revision, RevisionType type, StrIntTestEntity entity) { Assert.assertEquals( entity, result[0] ); - Assert.assertEquals( revision, ( (SequenceIdRevisionEntity) result[1] ).getId() ); + Assert.assertEquals( revision, ((SequenceIdRevisionEntity) result[1]).getId() ); Assert.assertEquals( type, result[2] ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/NullPropertyQuery.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/NullPropertyQuery.java index ffbd1d9433..1e146e7b47 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/NullPropertyQuery.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/NullPropertyQuery.java @@ -2,8 +2,6 @@ package org.hibernate.envers.test.integration.query; import javax.persistence.EntityManager; -import org.junit.Test; - import org.hibernate.envers.query.AuditEntity; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; @@ -14,15 +12,17 @@ import org.hibernate.envers.test.entities.onetomany.CollectionRefIngEntity; import org.hibernate.envers.test.entities.onetomany.ids.SetRefEdEmbIdEntity; import org.hibernate.envers.test.entities.onetomany.ids.SetRefIngEmbIdEntity; +import org.junit.Test; + /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class NullPropertyQuery extends BaseEnversJPAFunctionalTestCase { - private Integer idSimplePropertyNull = null; - private Integer idSimplePropertyNotNull = null; - private EmbId idMulticolumnReferenceToParentNull = new EmbId(0, 1); - private Integer idReferenceToParentNotNull = 1; - private Integer idParent = 1; + private Integer idSimplePropertyNull = null; + private Integer idSimplePropertyNotNull = null; + private EmbId idMulticolumnReferenceToParentNull = new EmbId( 0, 1 ); + private Integer idReferenceToParentNotNull = 1; + private Integer idParent = 1; @Override protected Class[] getAnnotatedClasses() { @@ -33,74 +33,82 @@ public class NullPropertyQuery extends BaseEnversJPAFunctionalTestCase { CollectionRefEdEntity.class, CollectionRefIngEntity.class }; - } + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - StrIntTestEntity nullSite = new StrIntTestEntity(null, 1); - StrIntTestEntity notNullSite = new StrIntTestEntity("data", 2); - em.persist(nullSite); - em.persist(notNullSite); - idSimplePropertyNull = nullSite.getId(); - idSimplePropertyNotNull = notNullSite.getId(); - em.getTransaction().commit(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + StrIntTestEntity nullSite = new StrIntTestEntity( null, 1 ); + StrIntTestEntity notNullSite = new StrIntTestEntity( "data", 2 ); + em.persist( nullSite ); + em.persist( notNullSite ); + idSimplePropertyNull = nullSite.getId(); + idSimplePropertyNotNull = notNullSite.getId(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); - SetRefIngEmbIdEntity nullParentSrieie = new SetRefIngEmbIdEntity(idMulticolumnReferenceToParentNull, "data", null); - em.persist(nullParentSrieie); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + SetRefIngEmbIdEntity nullParentSrieie = new SetRefIngEmbIdEntity( + idMulticolumnReferenceToParentNull, + "data", + null + ); + em.persist( nullParentSrieie ); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); - CollectionRefEdEntity parent = new CollectionRefEdEntity(idParent, "data"); - CollectionRefIngEntity notNullParentCrie = new CollectionRefIngEntity(idReferenceToParentNotNull, "data", parent); - em.persist(parent); - em.persist(notNullParentCrie); - em.getTransaction().commit(); - } + // Revision 3 + em.getTransaction().begin(); + CollectionRefEdEntity parent = new CollectionRefEdEntity( idParent, "data" ); + CollectionRefIngEntity notNullParentCrie = new CollectionRefIngEntity( + idReferenceToParentNotNull, + "data", + parent + ); + em.persist( parent ); + em.persist( notNullParentCrie ); + em.getTransaction().commit(); + } - @Test - public void testSimplePropertyIsNullQuery() { - StrIntTestEntity ver = (StrIntTestEntity) getAuditReader().createQuery() - .forEntitiesAtRevision(StrIntTestEntity.class, 1) - .add(AuditEntity.property("str1").isNull()) - .getSingleResult(); + @Test + public void testSimplePropertyIsNullQuery() { + StrIntTestEntity ver = (StrIntTestEntity) getAuditReader().createQuery() + .forEntitiesAtRevision( StrIntTestEntity.class, 1 ) + .add( AuditEntity.property( "str1" ).isNull() ) + .getSingleResult(); - assert ver.equals(new StrIntTestEntity(null, 1, idSimplePropertyNull)); - } + assert ver.equals( new StrIntTestEntity( null, 1, idSimplePropertyNull ) ); + } - @Test - public void testSimplePropertyIsNotNullQuery() { - StrIntTestEntity ver = (StrIntTestEntity) getAuditReader().createQuery() - .forEntitiesAtRevision(StrIntTestEntity.class, 1) - .add(AuditEntity.property("str1").isNotNull()) - .getSingleResult(); + @Test + public void testSimplePropertyIsNotNullQuery() { + StrIntTestEntity ver = (StrIntTestEntity) getAuditReader().createQuery() + .forEntitiesAtRevision( StrIntTestEntity.class, 1 ) + .add( AuditEntity.property( "str1" ).isNotNull() ) + .getSingleResult(); - assert ver.equals(new StrIntTestEntity("data", 2, idSimplePropertyNotNull)); - } + assert ver.equals( new StrIntTestEntity( "data", 2, idSimplePropertyNotNull ) ); + } - @Test - public void testReferenceMulticolumnPropertyIsNullQuery() { - SetRefIngEmbIdEntity ver = (SetRefIngEmbIdEntity) getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngEmbIdEntity.class, 2) - .add(AuditEntity.property("reference").isNull()) - .getSingleResult(); + @Test + public void testReferenceMulticolumnPropertyIsNullQuery() { + SetRefIngEmbIdEntity ver = (SetRefIngEmbIdEntity) getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngEmbIdEntity.class, 2 ) + .add( AuditEntity.property( "reference" ).isNull() ) + .getSingleResult(); - assert ver.getId().equals(idMulticolumnReferenceToParentNull); - } + assert ver.getId().equals( idMulticolumnReferenceToParentNull ); + } - @Test - public void testReferencePropertyIsNotNullQuery() { - CollectionRefIngEntity ver = (CollectionRefIngEntity) getAuditReader().createQuery() - .forEntitiesAtRevision(CollectionRefIngEntity.class, 3) - .add(AuditEntity.property("reference").isNotNull()) - .getSingleResult(); + @Test + public void testReferencePropertyIsNotNullQuery() { + CollectionRefIngEntity ver = (CollectionRefIngEntity) getAuditReader().createQuery() + .forEntitiesAtRevision( CollectionRefIngEntity.class, 3 ) + .add( AuditEntity.property( "reference" ).isNotNull() ) + .getSingleResult(); - assert ver.getId().equals(idReferenceToParentNotNull); - } + assert ver.getId().equals( idReferenceToParentNotNull ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/OrderByLimitQuery.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/OrderByLimitQuery.java index 53458de8c1..91ce3ef192 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/OrderByLimitQuery.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/OrderByLimitQuery.java @@ -23,126 +23,126 @@ */ package org.hibernate.envers.test.integration.query; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.query.AuditEntity; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.IntTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ @SuppressWarnings({"unchecked"}) public class OrderByLimitQuery extends BaseEnversJPAFunctionalTestCase { - private Integer id1; - private Integer id2; - private Integer id3; - private Integer id4; - private Integer id5; + private Integer id1; + private Integer id2; + private Integer id3; + private Integer id4; + private Integer id5; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { IntTestEntity.class }; - } + return new Class[] {IntTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - IntTestEntity ite1 = new IntTestEntity(12); - IntTestEntity ite2 = new IntTestEntity(5); - IntTestEntity ite3 = new IntTestEntity(8); - IntTestEntity ite4 = new IntTestEntity(1); + IntTestEntity ite1 = new IntTestEntity( 12 ); + IntTestEntity ite2 = new IntTestEntity( 5 ); + IntTestEntity ite3 = new IntTestEntity( 8 ); + IntTestEntity ite4 = new IntTestEntity( 1 ); - em.persist(ite1); - em.persist(ite2); - em.persist(ite3); - em.persist(ite4); + em.persist( ite1 ); + em.persist( ite2 ); + em.persist( ite3 ); + em.persist( ite4 ); - id1 = ite1.getId(); - id2 = ite2.getId(); - id3 = ite3.getId(); - id4 = ite4.getId(); + id1 = ite1.getId(); + id2 = ite2.getId(); + id3 = ite3.getId(); + id4 = ite4.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - IntTestEntity ite5 = new IntTestEntity(3); - em.persist(ite5); - id5 = ite5.getId(); + IntTestEntity ite5 = new IntTestEntity( 3 ); + em.persist( ite5 ); + id5 = ite5.getId(); - ite1 = em.find(IntTestEntity.class, id1); - ite1.setNumber(0); + ite1 = em.find( IntTestEntity.class, id1 ); + ite1.setNumber( 0 ); - ite4 = em.find(IntTestEntity.class, id4); - ite4.setNumber(15); + ite4 = em.find( IntTestEntity.class, id4 ); + ite4.setNumber( 15 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testEntitiesOrderLimitByQueryRev1() { - List res_0_to_1 = getAuditReader().createQuery() - .forEntitiesAtRevision(IntTestEntity.class, 1) - .addOrder(AuditEntity.property("number").desc()) - .setFirstResult(0) - .setMaxResults(2) - .getResultList(); + @Test + public void testEntitiesOrderLimitByQueryRev1() { + List res_0_to_1 = getAuditReader().createQuery() + .forEntitiesAtRevision( IntTestEntity.class, 1 ) + .addOrder( AuditEntity.property( "number" ).desc() ) + .setFirstResult( 0 ) + .setMaxResults( 2 ) + .getResultList(); - List res_2_to_3 = getAuditReader().createQuery() - .forEntitiesAtRevision(IntTestEntity.class, 1) - .addOrder(AuditEntity.property("number").desc()) - .setFirstResult(2) - .setMaxResults(2) - .getResultList(); + List res_2_to_3 = getAuditReader().createQuery() + .forEntitiesAtRevision( IntTestEntity.class, 1 ) + .addOrder( AuditEntity.property( "number" ).desc() ) + .setFirstResult( 2 ) + .setMaxResults( 2 ) + .getResultList(); - List res_empty = getAuditReader().createQuery() - .forEntitiesAtRevision(IntTestEntity.class, 1) - .addOrder(AuditEntity.property("number").desc()) - .setFirstResult(4) - .setMaxResults(2) - .getResultList(); + List res_empty = getAuditReader().createQuery() + .forEntitiesAtRevision( IntTestEntity.class, 1 ) + .addOrder( AuditEntity.property( "number" ).desc() ) + .setFirstResult( 4 ) + .setMaxResults( 2 ) + .getResultList(); - assert Arrays.asList(new IntTestEntity(12, id1), new IntTestEntity(8, id3)).equals(res_0_to_1); - assert Arrays.asList(new IntTestEntity(5, id2), new IntTestEntity(1, id4)).equals(res_2_to_3); - assert Arrays.asList().equals(res_empty); - } + assert Arrays.asList( new IntTestEntity( 12, id1 ), new IntTestEntity( 8, id3 ) ).equals( res_0_to_1 ); + assert Arrays.asList( new IntTestEntity( 5, id2 ), new IntTestEntity( 1, id4 ) ).equals( res_2_to_3 ); + assert Arrays.asList().equals( res_empty ); + } - @Test - public void testEntitiesOrderLimitByQueryRev2() { - List res_0_to_1 = getAuditReader().createQuery() - .forEntitiesAtRevision(IntTestEntity.class, 2) - .addOrder(AuditEntity.property("number").desc()) - .setFirstResult(0) - .setMaxResults(2) - .getResultList(); + @Test + public void testEntitiesOrderLimitByQueryRev2() { + List res_0_to_1 = getAuditReader().createQuery() + .forEntitiesAtRevision( IntTestEntity.class, 2 ) + .addOrder( AuditEntity.property( "number" ).desc() ) + .setFirstResult( 0 ) + .setMaxResults( 2 ) + .getResultList(); - List res_2_to_3 = getAuditReader().createQuery() - .forEntitiesAtRevision(IntTestEntity.class, 2) - .addOrder(AuditEntity.property("number").desc()) - .setFirstResult(2) - .setMaxResults(2) - .getResultList(); + List res_2_to_3 = getAuditReader().createQuery() + .forEntitiesAtRevision( IntTestEntity.class, 2 ) + .addOrder( AuditEntity.property( "number" ).desc() ) + .setFirstResult( 2 ) + .setMaxResults( 2 ) + .getResultList(); - List res_4 = getAuditReader().createQuery() - .forEntitiesAtRevision(IntTestEntity.class, 2) - .addOrder(AuditEntity.property("number").desc()) - .setFirstResult(4) - .setMaxResults(2) - .getResultList(); + List res_4 = getAuditReader().createQuery() + .forEntitiesAtRevision( IntTestEntity.class, 2 ) + .addOrder( AuditEntity.property( "number" ).desc() ) + .setFirstResult( 4 ) + .setMaxResults( 2 ) + .getResultList(); - assert Arrays.asList(new IntTestEntity(15, id4), new IntTestEntity(8, id3)).equals(res_0_to_1); - assert Arrays.asList(new IntTestEntity(5, id2), new IntTestEntity(3, id5)).equals(res_2_to_3); - assert Arrays.asList(new IntTestEntity(0, id1)).equals(res_4); - } + assert Arrays.asList( new IntTestEntity( 15, id4 ), new IntTestEntity( 8, id3 ) ).equals( res_0_to_1 ); + assert Arrays.asList( new IntTestEntity( 5, id2 ), new IntTestEntity( 3, id5 ) ).equals( res_2_to_3 ); + assert Arrays.asList( new IntTestEntity( 0, id1 ) ).equals( res_4 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/RevisionConstraintQuery.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/RevisionConstraintQuery.java index e8b361ea3b..0b4bef14d1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/RevisionConstraintQuery.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/RevisionConstraintQuery.java @@ -23,13 +23,10 @@ */ package org.hibernate.envers.test.integration.query; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.HashSet; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; import org.hibernate.envers.RevisionType; import org.hibernate.envers.query.AuditEntity; @@ -38,182 +35,185 @@ import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrIntTestEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Assert; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ @SuppressWarnings({"unchecked"}) public class RevisionConstraintQuery extends BaseEnversJPAFunctionalTestCase { - private Integer id1; + private Integer id1; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrIntTestEntity.class }; - } + return new Class[] {StrIntTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - StrIntTestEntity site1 = new StrIntTestEntity("a", 10); - StrIntTestEntity site2 = new StrIntTestEntity("b", 15); + StrIntTestEntity site1 = new StrIntTestEntity( "a", 10 ); + StrIntTestEntity site2 = new StrIntTestEntity( "b", 15 ); - em.persist(site1); - em.persist(site2); + em.persist( site1 ); + em.persist( site2 ); - id1 = site1.getId(); - Integer id2 = site2.getId(); + id1 = site1.getId(); + Integer id2 = site2.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - site1 = em.find(StrIntTestEntity.class, id1); - site2 = em.find(StrIntTestEntity.class, id2); + site1 = em.find( StrIntTestEntity.class, id1 ); + site2 = em.find( StrIntTestEntity.class, id2 ); - site1.setStr1("d"); - site2.setNumber(20); + site1.setStr1( "d" ); + site2.setNumber( 20 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - site1 = em.find(StrIntTestEntity.class, id1); - site2 = em.find(StrIntTestEntity.class, id2); + site1 = em.find( StrIntTestEntity.class, id1 ); + site2 = em.find( StrIntTestEntity.class, id2 ); - site1.setNumber(1); - site2.setStr1("z"); + site1.setNumber( 1 ); + site2.setStr1( "z" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); + // Revision 4 + em.getTransaction().begin(); - site1 = em.find(StrIntTestEntity.class, id1); - site2 = em.find(StrIntTestEntity.class, id2); + site1 = em.find( StrIntTestEntity.class, id1 ); + site2 = em.find( StrIntTestEntity.class, id2 ); - site1.setNumber(5); - site2.setStr1("a"); + site1.setNumber( 5 ); + site2.setStr1( "a" ); - em.getTransaction().commit(); - } - - @Test - public void testRevisionsLtQuery() { - List result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .addProjection(AuditEntity.revisionNumber().distinct()) - .add(AuditEntity.revisionNumber().lt(3)) - .getResultList(); + em.getTransaction().commit(); + } - Assert.assertEquals(Arrays.asList(1, 2), result); - } + @Test + public void testRevisionsLtQuery() { + List result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .addProjection( AuditEntity.revisionNumber().distinct() ) + .add( AuditEntity.revisionNumber().lt( 3 ) ) + .getResultList(); - @Test - public void testRevisionsGeQuery() { - List result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .addProjection(AuditEntity.revisionNumber().distinct()) - .add(AuditEntity.revisionNumber().ge(2)) - .getResultList(); + Assert.assertEquals( Arrays.asList( 1, 2 ), result ); + } - Assert.assertEquals(TestTools.makeSet(2, 3, 4), new HashSet(result)); - } + @Test + public void testRevisionsGeQuery() { + List result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .addProjection( AuditEntity.revisionNumber().distinct() ) + .add( AuditEntity.revisionNumber().ge( 2 ) ) + .getResultList(); - @Test - public void testRevisionsLeWithPropertyQuery() { - List result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .addProjection(AuditEntity.revisionNumber()) - .add(AuditEntity.revisionNumber().le(3)) - .add(AuditEntity.property("str1").eq("a")) - .getResultList(); + Assert.assertEquals( TestTools.makeSet( 2, 3, 4 ), new HashSet( result ) ); + } - Assert.assertEquals(Arrays.asList(1), result); - } + @Test + public void testRevisionsLeWithPropertyQuery() { + List result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .addProjection( AuditEntity.revisionNumber() ) + .add( AuditEntity.revisionNumber().le( 3 ) ) + .add( AuditEntity.property( "str1" ).eq( "a" ) ) + .getResultList(); - @Test - public void testRevisionsGtWithPropertyQuery() { - List result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .addProjection(AuditEntity.revisionNumber()) - .add(AuditEntity.revisionNumber().gt(1)) - .add(AuditEntity.property("number").lt(10)) - .getResultList(); + Assert.assertEquals( Arrays.asList( 1 ), result ); + } - Assert.assertEquals(Arrays.asList(3, 4), result); - } + @Test + public void testRevisionsGtWithPropertyQuery() { + List result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .addProjection( AuditEntity.revisionNumber() ) + .add( AuditEntity.revisionNumber().gt( 1 ) ) + .add( AuditEntity.property( "number" ).lt( 10 ) ) + .getResultList(); - @Test - public void testRevisionProjectionQuery() { - Object[] result = (Object[]) getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .addProjection(AuditEntity.revisionNumber().max()) - .addProjection(AuditEntity.revisionNumber().count()) - .addProjection(AuditEntity.revisionNumber().countDistinct()) - .addProjection(AuditEntity.revisionNumber().min()) - .add(AuditEntity.id().eq(id1)) - .getSingleResult(); + Assert.assertEquals( Arrays.asList( 3, 4 ), result ); + } - Assert.assertEquals(Integer.valueOf(4), result[0] ); - Assert.assertEquals(Long.valueOf(4), result[1] ); - Assert.assertEquals(Long.valueOf(4), result[2]); - Assert.assertEquals(Integer.valueOf(1), result[3] ); - } + @Test + public void testRevisionProjectionQuery() { + Object[] result = (Object[]) getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .addProjection( AuditEntity.revisionNumber().max() ) + .addProjection( AuditEntity.revisionNumber().count() ) + .addProjection( AuditEntity.revisionNumber().countDistinct() ) + .addProjection( AuditEntity.revisionNumber().min() ) + .add( AuditEntity.id().eq( id1 ) ) + .getSingleResult(); - @Test - public void testRevisionOrderQuery() { - List result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .addProjection(AuditEntity.revisionNumber()) - .add(AuditEntity.id().eq(id1)) - .addOrder(AuditEntity.revisionNumber().desc()) - .getResultList(); + Assert.assertEquals( Integer.valueOf( 4 ), result[0] ); + Assert.assertEquals( Long.valueOf( 4 ), result[1] ); + Assert.assertEquals( Long.valueOf( 4 ), result[2] ); + Assert.assertEquals( Integer.valueOf( 1 ), result[3] ); + } - Assert.assertEquals(Arrays.asList(4, 3, 2, 1), result); - } + @Test + public void testRevisionOrderQuery() { + List result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .addProjection( AuditEntity.revisionNumber() ) + .add( AuditEntity.id().eq( id1 ) ) + .addOrder( AuditEntity.revisionNumber().desc() ) + .getResultList(); - @Test - public void testRevisionCountQuery() { - // The query shouldn't be ordered as always, otherwise - we get an exception. - Object result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .addProjection(AuditEntity.revisionNumber().count()) - .add(AuditEntity.id().eq(id1)) - .getSingleResult(); + Assert.assertEquals( Arrays.asList( 4, 3, 2, 1 ), result ); + } - Assert.assertEquals(Long.valueOf(4), result ); - } + @Test + public void testRevisionCountQuery() { + // The query shouldn't be ordered as always, otherwise - we get an exception. + Object result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .addProjection( AuditEntity.revisionNumber().count() ) + .add( AuditEntity.id().eq( id1 ) ) + .getSingleResult(); - @Test - public void testRevisionTypeEqQuery() { - // The query shouldn't be ordered as always, otherwise - we get an exception. - List results = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, true, true) - .add(AuditEntity.id().eq(id1)) - .add(AuditEntity.revisionType().eq(RevisionType.MOD)) - .getResultList(); - - Assert.assertEquals(3, results.size()); - Assert.assertEquals(new StrIntTestEntity("d", 10, id1), results.get(0)); - Assert.assertEquals(new StrIntTestEntity("d", 1, id1), results.get(1)); - Assert.assertEquals(new StrIntTestEntity("d", 5, id1), results.get(2)); - } + Assert.assertEquals( Long.valueOf( 4 ), result ); + } - @Test - public void testRevisionTypeNeQuery() { - // The query shouldn't be ordered as always, otherwise - we get an exception. - List results = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, true, true) - .add(AuditEntity.id().eq(id1)) - .add(AuditEntity.revisionType().ne(RevisionType.MOD)) - .getResultList(); + @Test + public void testRevisionTypeEqQuery() { + // The query shouldn't be ordered as always, otherwise - we get an exception. + List results = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, true, true ) + .add( AuditEntity.id().eq( id1 ) ) + .add( AuditEntity.revisionType().eq( RevisionType.MOD ) ) + .getResultList(); - Assert.assertEquals(1, results.size()); - Assert.assertEquals(new StrIntTestEntity("a", 10, id1), results.get(0)); - } + Assert.assertEquals( 3, results.size() ); + Assert.assertEquals( new StrIntTestEntity( "d", 10, id1 ), results.get( 0 ) ); + Assert.assertEquals( new StrIntTestEntity( "d", 1, id1 ), results.get( 1 ) ); + Assert.assertEquals( new StrIntTestEntity( "d", 5, id1 ), results.get( 2 ) ); + } + + @Test + public void testRevisionTypeNeQuery() { + // The query shouldn't be ordered as always, otherwise - we get an exception. + List results = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, true, true ) + .add( AuditEntity.id().eq( id1 ) ) + .add( AuditEntity.revisionType().ne( RevisionType.MOD ) ) + .getResultList(); + + Assert.assertEquals( 1, results.size() ); + Assert.assertEquals( new StrIntTestEntity( "a", 10, id1 ), results.get( 0 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/SimpleQuery.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/SimpleQuery.java index f74e9667a8..88237e2a25 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/SimpleQuery.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/SimpleQuery.java @@ -23,13 +23,10 @@ */ package org.hibernate.envers.test.integration.query; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.HashSet; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; import org.hibernate.envers.RevisionType; import org.hibernate.envers.enhanced.SequenceIdRevisionEntity; @@ -38,6 +35,10 @@ import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrIntTestEntity; import org.hibernate.envers.test.tools.TestTools; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -46,301 +47,342 @@ import org.hibernate.testing.TestForIssue; */ @SuppressWarnings({"unchecked"}) public class SimpleQuery extends BaseEnversJPAFunctionalTestCase { - private Integer id1; - private Integer id2; - private Integer id3; + private Integer id1; + private Integer id2; + private Integer id3; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrIntTestEntity.class }; - } + return new Class[] {StrIntTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + @Test + @Priority(10) + public void initData() { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - StrIntTestEntity site1 = new StrIntTestEntity("a", 10); - StrIntTestEntity site2 = new StrIntTestEntity("a", 10); - StrIntTestEntity site3 = new StrIntTestEntity("b", 5); + StrIntTestEntity site1 = new StrIntTestEntity( "a", 10 ); + StrIntTestEntity site2 = new StrIntTestEntity( "a", 10 ); + StrIntTestEntity site3 = new StrIntTestEntity( "b", 5 ); - em.persist(site1); - em.persist(site2); - em.persist(site3); + em.persist( site1 ); + em.persist( site2 ); + em.persist( site3 ); - id1 = site1.getId(); - id2 = site2.getId(); - id3 = site3.getId(); + id1 = site1.getId(); + id2 = site2.getId(); + id3 = site3.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - site1 = em.find(StrIntTestEntity.class, id1); - site2 = em.find(StrIntTestEntity.class, id2); + site1 = em.find( StrIntTestEntity.class, id1 ); + site2 = em.find( StrIntTestEntity.class, id2 ); - site1.setStr1("c"); - site2.setNumber(20); + site1.setStr1( "c" ); + site2.setNumber( 20 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - site3 = em.find(StrIntTestEntity.class, id3); + site3 = em.find( StrIntTestEntity.class, id3 ); - site3.setStr1("a"); + site3.setStr1( "a" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 4 - em.getTransaction().begin(); + // Revision 4 + em.getTransaction().begin(); - site1 = em.find(StrIntTestEntity.class, id1); + site1 = em.find( StrIntTestEntity.class, id1 ); - em.remove(site1); + em.remove( site1 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testEntitiesIdQuery() { - StrIntTestEntity ver2 = (StrIntTestEntity) getAuditReader().createQuery() - .forEntitiesAtRevision(StrIntTestEntity.class, 2) - .add(AuditEntity.id().eq(id2)) - .getSingleResult(); + @Test + public void testEntitiesIdQuery() { + StrIntTestEntity ver2 = (StrIntTestEntity) getAuditReader().createQuery() + .forEntitiesAtRevision( StrIntTestEntity.class, 2 ) + .add( AuditEntity.id().eq( id2 ) ) + .getSingleResult(); - assert ver2.equals(new StrIntTestEntity("a", 20, id2)); - } + assert ver2.equals( new StrIntTestEntity( "a", 20, id2 ) ); + } - @Test - public void testEntitiesPropertyEqualsQuery() { - List ver1 = getAuditReader().createQuery() - .forEntitiesAtRevision(StrIntTestEntity.class, 1) - .add(AuditEntity.property("str1").eq("a")) - .getResultList(); + @Test + public void testEntitiesPropertyEqualsQuery() { + List ver1 = getAuditReader().createQuery() + .forEntitiesAtRevision( StrIntTestEntity.class, 1 ) + .add( AuditEntity.property( "str1" ).eq( "a" ) ) + .getResultList(); - List ver2 = getAuditReader().createQuery() - .forEntitiesAtRevision(StrIntTestEntity.class, 2) - .add(AuditEntity.property("str1").eq("a")) - .getResultList(); + List ver2 = getAuditReader().createQuery() + .forEntitiesAtRevision( StrIntTestEntity.class, 2 ) + .add( AuditEntity.property( "str1" ).eq( "a" ) ) + .getResultList(); - List ver3 = getAuditReader().createQuery() - .forEntitiesAtRevision(StrIntTestEntity.class, 3) - .add(AuditEntity.property("str1").eq("a")) - .getResultList(); + List ver3 = getAuditReader().createQuery() + .forEntitiesAtRevision( StrIntTestEntity.class, 3 ) + .add( AuditEntity.property( "str1" ).eq( "a" ) ) + .getResultList(); - assert new HashSet(ver1).equals(TestTools.makeSet(new StrIntTestEntity("a", 10, id1), - new StrIntTestEntity("a", 10, id2))); - assert new HashSet(ver2).equals(TestTools.makeSet(new StrIntTestEntity("a", 20, id2))); - assert new HashSet(ver3).equals(TestTools.makeSet(new StrIntTestEntity("a", 20, id2), - new StrIntTestEntity("a", 5, id3))); - } + assert new HashSet( ver1 ).equals( + TestTools.makeSet( + new StrIntTestEntity( "a", 10, id1 ), + new StrIntTestEntity( "a", 10, id2 ) + ) + ); + assert new HashSet( ver2 ).equals( TestTools.makeSet( new StrIntTestEntity( "a", 20, id2 ) ) ); + assert new HashSet( ver3 ).equals( + TestTools.makeSet( + new StrIntTestEntity( "a", 20, id2 ), + new StrIntTestEntity( "a", 5, id3 ) + ) + ); + } - @Test - public void testEntitiesPropertyLeQuery() { - List ver1 = getAuditReader().createQuery() - .forEntitiesAtRevision(StrIntTestEntity.class, 1) - .add(AuditEntity.property("number").le(10)) - .getResultList(); + @Test + public void testEntitiesPropertyLeQuery() { + List ver1 = getAuditReader().createQuery() + .forEntitiesAtRevision( StrIntTestEntity.class, 1 ) + .add( AuditEntity.property( "number" ).le( 10 ) ) + .getResultList(); - List ver2 = getAuditReader().createQuery() - .forEntitiesAtRevision(StrIntTestEntity.class, 2) - .add(AuditEntity.property("number").le(10)) - .getResultList(); + List ver2 = getAuditReader().createQuery() + .forEntitiesAtRevision( StrIntTestEntity.class, 2 ) + .add( AuditEntity.property( "number" ).le( 10 ) ) + .getResultList(); - List ver3 = getAuditReader().createQuery() - .forEntitiesAtRevision(StrIntTestEntity.class, 3) - .add(AuditEntity.property("number").le(10)) - .getResultList(); + List ver3 = getAuditReader().createQuery() + .forEntitiesAtRevision( StrIntTestEntity.class, 3 ) + .add( AuditEntity.property( "number" ).le( 10 ) ) + .getResultList(); - assert new HashSet(ver1).equals(TestTools.makeSet(new StrIntTestEntity("a", 10, id1), - new StrIntTestEntity("a", 10, id2), new StrIntTestEntity("b", 5, id3))); - assert new HashSet(ver2).equals(TestTools.makeSet(new StrIntTestEntity("c", 10, id1), - new StrIntTestEntity("b", 5, id3))); - assert new HashSet(ver3).equals(TestTools.makeSet(new StrIntTestEntity("c", 10, id1), - new StrIntTestEntity("a", 5, id3))); - } + assert new HashSet( ver1 ).equals( + TestTools.makeSet( + new StrIntTestEntity( "a", 10, id1 ), + new StrIntTestEntity( "a", 10, id2 ), new StrIntTestEntity( "b", 5, id3 ) + ) + ); + assert new HashSet( ver2 ).equals( + TestTools.makeSet( + new StrIntTestEntity( "c", 10, id1 ), + new StrIntTestEntity( "b", 5, id3 ) + ) + ); + assert new HashSet( ver3 ).equals( + TestTools.makeSet( + new StrIntTestEntity( "c", 10, id1 ), + new StrIntTestEntity( "a", 5, id3 ) + ) + ); + } - @Test - public void testRevisionsPropertyEqQuery() { - List revs_id1 = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .addProjection(AuditEntity.revisionNumber()) - .add(AuditEntity.property("str1").le("a")) - .add(AuditEntity.id().eq(id1)) - .getResultList(); + @Test + public void testRevisionsPropertyEqQuery() { + List revs_id1 = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .addProjection( AuditEntity.revisionNumber() ) + .add( AuditEntity.property( "str1" ).le( "a" ) ) + .add( AuditEntity.id().eq( id1 ) ) + .getResultList(); - List revs_id2 = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .addProjection(AuditEntity.revisionNumber()) - .add(AuditEntity.property("str1").le("a")) - .add(AuditEntity.id().eq(id2)) - .getResultList(); + List revs_id2 = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .addProjection( AuditEntity.revisionNumber() ) + .add( AuditEntity.property( "str1" ).le( "a" ) ) + .add( AuditEntity.id().eq( id2 ) ) + .getResultList(); - List revs_id3 = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .addProjection(AuditEntity.revisionNumber()) - .add(AuditEntity.property("str1").le("a")) - .add(AuditEntity.id().eq(id3)) - .getResultList(); + List revs_id3 = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .addProjection( AuditEntity.revisionNumber() ) + .add( AuditEntity.property( "str1" ).le( "a" ) ) + .add( AuditEntity.id().eq( id3 ) ) + .getResultList(); - assert Arrays.asList(1).equals(revs_id1); - assert Arrays.asList(1, 2).equals(revs_id2); - assert Arrays.asList(3).equals(revs_id3); - } + assert Arrays.asList( 1 ).equals( revs_id1 ); + assert Arrays.asList( 1, 2 ).equals( revs_id2 ); + assert Arrays.asList( 3 ).equals( revs_id3 ); + } - @Test - public void testSelectEntitiesQuery() { - List result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, true, false) - .add(AuditEntity.id().eq(id1)) - .getResultList(); + @Test + public void testSelectEntitiesQuery() { + List result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, true, false ) + .add( AuditEntity.id().eq( id1 ) ) + .getResultList(); - assert result.size() == 2; + assert result.size() == 2; - assert result.get(0).equals(new StrIntTestEntity("a", 10, id1)); - assert result.get(1).equals(new StrIntTestEntity("c", 10, id1)); - } + assert result.get( 0 ).equals( new StrIntTestEntity( "a", 10, id1 ) ); + assert result.get( 1 ).equals( new StrIntTestEntity( "c", 10, id1 ) ); + } - @Test - public void testSelectEntitiesAndRevisionsQuery() { - List result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .add(AuditEntity.id().eq(id1)) - .getResultList(); + @Test + public void testSelectEntitiesAndRevisionsQuery() { + List result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .add( AuditEntity.id().eq( id1 ) ) + .getResultList(); - assert result.size() == 3; + assert result.size() == 3; - assert ((Object []) result.get(0))[0].equals(new StrIntTestEntity("a", 10, id1)); - assert ((Object []) result.get(1))[0].equals(new StrIntTestEntity("c", 10, id1)); - assert ((Object []) result.get(2))[0].equals(new StrIntTestEntity(null, null, id1)); + assert ((Object[]) result.get( 0 ))[0].equals( new StrIntTestEntity( "a", 10, id1 ) ); + assert ((Object[]) result.get( 1 ))[0].equals( new StrIntTestEntity( "c", 10, id1 ) ); + assert ((Object[]) result.get( 2 ))[0].equals( new StrIntTestEntity( null, null, id1 ) ); - assert ((SequenceIdRevisionEntity) ((Object []) result.get(0))[1]).getId() == 1; - assert ((SequenceIdRevisionEntity) ((Object []) result.get(1))[1]).getId() == 2; - assert ((SequenceIdRevisionEntity) ((Object []) result.get(2))[1]).getId() == 4; + assert ((SequenceIdRevisionEntity) ((Object[]) result.get( 0 ))[1]).getId() == 1; + assert ((SequenceIdRevisionEntity) ((Object[]) result.get( 1 ))[1]).getId() == 2; + assert ((SequenceIdRevisionEntity) ((Object[]) result.get( 2 ))[1]).getId() == 4; - assert ((Object []) result.get(0))[2].equals(RevisionType.ADD); - assert ((Object []) result.get(1))[2].equals(RevisionType.MOD); - assert ((Object []) result.get(2))[2].equals(RevisionType.DEL); - } + assert ((Object[]) result.get( 0 ))[2].equals( RevisionType.ADD ); + assert ((Object[]) result.get( 1 ))[2].equals( RevisionType.MOD ); + assert ((Object[]) result.get( 2 ))[2].equals( RevisionType.DEL ); + } - @Test - public void testSelectRevisionTypeQuery() { - List result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .addProjection(AuditEntity.revisionType()) - .add(AuditEntity.id().eq(id1)) - .getResultList(); + @Test + public void testSelectRevisionTypeQuery() { + List result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .addProjection( AuditEntity.revisionType() ) + .add( AuditEntity.id().eq( id1 ) ) + .getResultList(); - assert result.size() == 3; + assert result.size() == 3; - assert result.get(0).equals(RevisionType.ADD); - assert result.get(1).equals(RevisionType.MOD); - assert result.get(2).equals(RevisionType.DEL); - } + assert result.get( 0 ).equals( RevisionType.ADD ); + assert result.get( 1 ).equals( RevisionType.MOD ); + assert result.get( 2 ).equals( RevisionType.DEL ); + } - @Test - public void testEmptyRevisionOfEntityQuery() { - List result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .getResultList(); + @Test + public void testEmptyRevisionOfEntityQuery() { + List result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .getResultList(); - assert result.size() == 7; - } + assert result.size() == 7; + } - @Test - public void testEmptyConjunctionRevisionOfEntityQuery() { - List result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .add(AuditEntity.conjunction()) - .getResultList(); + @Test + public void testEmptyConjunctionRevisionOfEntityQuery() { + List result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .add( AuditEntity.conjunction() ) + .getResultList(); - assert result.size() == 7; - } + assert result.size() == 7; + } - @Test - public void testEmptyDisjunctionRevisionOfEntityQuery() { - List result = getAuditReader().createQuery() - .forRevisionsOfEntity(StrIntTestEntity.class, false, true) - .add(AuditEntity.disjunction()) - .getResultList(); + @Test + public void testEmptyDisjunctionRevisionOfEntityQuery() { + List result = getAuditReader().createQuery() + .forRevisionsOfEntity( StrIntTestEntity.class, false, true ) + .add( AuditEntity.disjunction() ) + .getResultList(); - assert result.size() == 0; - } + assert result.size() == 0; + } - @Test - public void testEntitiesAddedAtRevision() { - StrIntTestEntity site1 = new StrIntTestEntity("a", 10, id1); - StrIntTestEntity site2 = new StrIntTestEntity("a", 10, id2); - StrIntTestEntity site3 = new StrIntTestEntity("b", 5, id3); + @Test + public void testEntitiesAddedAtRevision() { + StrIntTestEntity site1 = new StrIntTestEntity( "a", 10, id1 ); + StrIntTestEntity site2 = new StrIntTestEntity( "a", 10, id2 ); + StrIntTestEntity site3 = new StrIntTestEntity( "b", 5, id3 ); - List result = getAuditReader().createQuery().forEntitiesModifiedAtRevision(StrIntTestEntity.class, StrIntTestEntity.class.getName(), 1).getResultList(); - RevisionType revisionType = (RevisionType) getAuditReader().createQuery().forEntitiesModifiedAtRevision(StrIntTestEntity.class, 1) - .addProjection(AuditEntity.revisionType()).add(AuditEntity.id().eq(id1)) - .getSingleResult(); + List result = getAuditReader().createQuery().forEntitiesModifiedAtRevision( + StrIntTestEntity.class, + StrIntTestEntity.class.getName(), + 1 + ).getResultList(); + RevisionType revisionType = (RevisionType) getAuditReader().createQuery().forEntitiesModifiedAtRevision( + StrIntTestEntity.class, + 1 + ) + .addProjection( AuditEntity.revisionType() ).add( AuditEntity.id().eq( id1 ) ) + .getSingleResult(); - Assert.assertTrue(TestTools.checkList(result, site1, site2, site3)); - Assert.assertEquals(revisionType, RevisionType.ADD); - } + Assert.assertTrue( TestTools.checkList( result, site1, site2, site3 ) ); + Assert.assertEquals( revisionType, RevisionType.ADD ); + } - @Test - public void testEntitiesChangedAtRevision() { - StrIntTestEntity site1 = new StrIntTestEntity("c", 10, id1); - StrIntTestEntity site2 = new StrIntTestEntity("a", 20, id2); + @Test + public void testEntitiesChangedAtRevision() { + StrIntTestEntity site1 = new StrIntTestEntity( "c", 10, id1 ); + StrIntTestEntity site2 = new StrIntTestEntity( "a", 20, id2 ); - List result = getAuditReader().createQuery().forEntitiesModifiedAtRevision(StrIntTestEntity.class, 2).getResultList(); - RevisionType revisionType = (RevisionType) getAuditReader().createQuery().forEntitiesModifiedAtRevision(StrIntTestEntity.class, 2) - .addProjection(AuditEntity.revisionType()).add(AuditEntity.id().eq(id1)) - .getSingleResult(); + List result = getAuditReader().createQuery() + .forEntitiesModifiedAtRevision( StrIntTestEntity.class, 2 ) + .getResultList(); + RevisionType revisionType = (RevisionType) getAuditReader().createQuery().forEntitiesModifiedAtRevision( + StrIntTestEntity.class, + 2 + ) + .addProjection( AuditEntity.revisionType() ).add( AuditEntity.id().eq( id1 ) ) + .getSingleResult(); - Assert.assertTrue(TestTools.checkList(result, site1, site2)); - Assert.assertEquals(revisionType, RevisionType.MOD); - } + Assert.assertTrue( TestTools.checkList( result, site1, site2 ) ); + Assert.assertEquals( revisionType, RevisionType.MOD ); + } - @Test - public void testEntitiesRemovedAtRevision() { - StrIntTestEntity site1 = new StrIntTestEntity(null, null, id1); + @Test + public void testEntitiesRemovedAtRevision() { + StrIntTestEntity site1 = new StrIntTestEntity( null, null, id1 ); - List result = getAuditReader().createQuery().forEntitiesModifiedAtRevision(StrIntTestEntity.class, 4).getResultList(); - RevisionType revisionType = (RevisionType) getAuditReader().createQuery().forEntitiesModifiedAtRevision(StrIntTestEntity.class, 4) - .addProjection(AuditEntity.revisionType()).add(AuditEntity.id().eq(id1)) - .getSingleResult(); - - Assert.assertTrue(TestTools.checkList(result, site1)); - Assert.assertEquals(revisionType, RevisionType.DEL); - } + List result = getAuditReader().createQuery() + .forEntitiesModifiedAtRevision( StrIntTestEntity.class, 4 ) + .getResultList(); + RevisionType revisionType = (RevisionType) getAuditReader().createQuery().forEntitiesModifiedAtRevision( + StrIntTestEntity.class, + 4 + ) + .addProjection( AuditEntity.revisionType() ).add( AuditEntity.id().eq( id1 ) ) + .getSingleResult(); - @Test - public void testEntityNotModifiedAtRevision() { - List result = getAuditReader().createQuery().forEntitiesModifiedAtRevision(StrIntTestEntity.class, 3) - .add(AuditEntity.id().eq(id1)).getResultList(); - Assert.assertTrue(result.isEmpty()); - } + Assert.assertTrue( TestTools.checkList( result, site1 ) ); + Assert.assertEquals( revisionType, RevisionType.DEL ); + } - @Test - public void testNoEntitiesModifiedAtRevision() { - List result = getAuditReader().createQuery().forEntitiesModifiedAtRevision(StrIntTestEntity.class, 5).getResultList(); - Assert.assertTrue(result.isEmpty()); - } + @Test + public void testEntityNotModifiedAtRevision() { + List result = getAuditReader().createQuery().forEntitiesModifiedAtRevision( StrIntTestEntity.class, 3 ) + .add( AuditEntity.id().eq( id1 ) ).getResultList(); + Assert.assertTrue( result.isEmpty() ); + } + + @Test + public void testNoEntitiesModifiedAtRevision() { + List result = getAuditReader().createQuery() + .forEntitiesModifiedAtRevision( StrIntTestEntity.class, 5 ) + .getResultList(); + Assert.assertTrue( result.isEmpty() ); + } @Test @TestForIssue(jiraKey = "HHH-7800") public void testBetweenInsideDisjunction() { List result = getAuditReader().createQuery() .forRevisionsOfEntity( StrIntTestEntity.class, true, true ) - .add( AuditEntity.disjunction() + .add( + AuditEntity.disjunction() .add( AuditEntity.property( "number" ).between( 0, 5 ) ) - .add( AuditEntity.property( "number" ).between( 20, 100 ) ) ) + .add( AuditEntity.property( "number" ).between( 20, 100 ) ) + ) .getResultList(); for ( Object o : result ) { StrIntTestEntity entity = (StrIntTestEntity) o; int number = entity.getNumber(); - Assert.assertTrue( ( number >= 0 && number <= 5 ) || ( number >= 20 && number <= 100 ) ); + Assert.assertTrue( (number >= 0 && number <= 5) || (number >= 20 && number <= 100) ); } } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/StoreDeletedData.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/StoreDeletedData.java index 9ba7e07231..5d5f0dac32 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/StoreDeletedData.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/StoreDeletedData.java @@ -23,13 +23,10 @@ */ package org.hibernate.envers.test.integration.query; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.List; import java.util.Map; -import javax.persistence.EntityManager; - -import junit.framework.Assert; -import org.junit.Test; import org.hibernate.envers.RevisionType; import org.hibernate.envers.configuration.EnversSettings; @@ -40,13 +37,18 @@ import org.hibernate.envers.query.criteria.AuditDisjunction; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrIntTestEntity; + +import org.junit.Test; +import junit.framework.Assert; + import org.hibernate.testing.TestForIssue; /** * A test which checks if the data of a deleted entity is stored when the setting is on. + * * @author Adam Warski (adam at warski dot org) */ -@SuppressWarnings({ "unchecked" }) +@SuppressWarnings({"unchecked"}) public class StoreDeletedData extends BaseEnversJPAFunctionalTestCase { private Integer id1; private Integer id2; @@ -54,7 +56,7 @@ public class StoreDeletedData extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrIntTestEntity.class }; + return new Class[] {StrIntTestEntity.class}; } @Override @@ -107,8 +109,8 @@ public class StoreDeletedData extends BaseEnversJPAFunctionalTestCase { .getResultList(); Assert.assertEquals( 2, revs_id1.size() ); - Assert.assertEquals( new StrIntTestEntity( "a", 10, id1 ), ( (Object[]) revs_id1.get( 0 ) )[0] ); - Assert.assertEquals( new StrIntTestEntity( "a", 10, id1 ), ( (Object[]) revs_id1.get( 1 ) )[0] ); + Assert.assertEquals( new StrIntTestEntity( "a", 10, id1 ), ((Object[]) revs_id1.get( 0 ))[0] ); + Assert.assertEquals( new StrIntTestEntity( "a", 10, id1 ), ((Object[]) revs_id1.get( 1 ))[0] ); } @Test @@ -139,11 +141,11 @@ public class StoreDeletedData extends BaseEnversJPAFunctionalTestCase { Assert.assertEquals( new StrIntTestEntity( "b", 20, id2 ), result1[0] ); // Making sure that we have received an entity added at revision 3. - Assert.assertEquals( 3, ( (SequenceIdRevisionEntity) result1[1] ).getId() ); + Assert.assertEquals( 3, ((SequenceIdRevisionEntity) result1[1]).getId() ); Assert.assertEquals( RevisionType.ADD, result1[2] ); Assert.assertEquals( new StrIntTestEntity( "c", 30, id3 ), result2[0] ); // Making sure that we have received an entity added at revision 3. - Assert.assertEquals( 3, ( (SequenceIdRevisionEntity) result2[1] ).getId() ); + Assert.assertEquals( 3, ((SequenceIdRevisionEntity) result2[1]).getId() ); Assert.assertEquals( RevisionType.ADD, result2[2] ); } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/ids/EmbIdOneToManyQuery.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/ids/EmbIdOneToManyQuery.java index 56bb879d71..2e53bf689f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/ids/EmbIdOneToManyQuery.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/ids/EmbIdOneToManyQuery.java @@ -23,12 +23,10 @@ */ package org.hibernate.envers.test.integration.query.ids; +import javax.persistence.EntityManager; import java.util.HashSet; import java.util.List; import java.util.Set; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.query.AuditEntity; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -38,180 +36,204 @@ import org.hibernate.envers.test.entities.onetomany.ids.SetRefEdEmbIdEntity; import org.hibernate.envers.test.entities.onetomany.ids.SetRefIngEmbIdEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ @SuppressWarnings({"unchecked"}) public class EmbIdOneToManyQuery extends BaseEnversJPAFunctionalTestCase { - private EmbId id1; - private EmbId id2; + private EmbId id1; + private EmbId id2; - private EmbId id3; - private EmbId id4; + private EmbId id3; + private EmbId id4; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SetRefEdEmbIdEntity.class, SetRefIngEmbIdEntity.class }; - } + return new Class[] {SetRefEdEmbIdEntity.class, SetRefIngEmbIdEntity.class}; + } - @Test - @Priority(10) - public void initData() { - id1 = new EmbId(0, 1); - id2 = new EmbId(10, 11); - id3 = new EmbId(20, 21); - id4 = new EmbId(30, 31); + @Test + @Priority(10) + public void initData() { + id1 = new EmbId( 0, 1 ); + id2 = new EmbId( 10, 11 ); + id3 = new EmbId( 20, 21 ); + id4 = new EmbId( 30, 31 ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - SetRefIngEmbIdEntity refIng1 = new SetRefIngEmbIdEntity(id1, "x", null); - SetRefIngEmbIdEntity refIng2 = new SetRefIngEmbIdEntity(id2, "y", null); + SetRefIngEmbIdEntity refIng1 = new SetRefIngEmbIdEntity( id1, "x", null ); + SetRefIngEmbIdEntity refIng2 = new SetRefIngEmbIdEntity( id2, "y", null ); - em.persist(refIng1); - em.persist(refIng2); + em.persist( refIng1 ); + em.persist( refIng2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - SetRefEdEmbIdEntity refEd3 = new SetRefEdEmbIdEntity(id3, "a"); - SetRefEdEmbIdEntity refEd4 = new SetRefEdEmbIdEntity(id4, "a"); + SetRefEdEmbIdEntity refEd3 = new SetRefEdEmbIdEntity( id3, "a" ); + SetRefEdEmbIdEntity refEd4 = new SetRefEdEmbIdEntity( id4, "a" ); - em.persist(refEd3); - em.persist(refEd4); + em.persist( refEd3 ); + em.persist( refEd4 ); - refIng1 = em.find(SetRefIngEmbIdEntity.class, id1); - refIng2 = em.find(SetRefIngEmbIdEntity.class, id2); + refIng1 = em.find( SetRefIngEmbIdEntity.class, id1 ); + refIng2 = em.find( SetRefIngEmbIdEntity.class, id2 ); - refIng1.setReference(refEd3); - refIng2.setReference(refEd4); + refIng1.setReference( refEd3 ); + refIng2.setReference( refEd4 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - refEd3 = em.find(SetRefEdEmbIdEntity.class, id3); - refIng2 = em.find(SetRefIngEmbIdEntity.class, id2); - refIng2.setReference(refEd3); + refEd3 = em.find( SetRefEdEmbIdEntity.class, id3 ); + refIng2 = em.find( SetRefIngEmbIdEntity.class, id2 ); + refIng2.setReference( refEd3 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testEntitiesReferencedToId3() { - Set rev1_related = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngEmbIdEntity.class, 1) - .add(AuditEntity.relatedId("reference").eq(id3)) - .getResultList()); + @Test + public void testEntitiesReferencedToId3() { + Set rev1_related = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngEmbIdEntity.class, 1 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .getResultList() + ); - Set rev1 = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngEmbIdEntity.class, 1) - .add(AuditEntity.property("reference").eq(new SetRefEdEmbIdEntity(id3, null))) - .getResultList()); + Set rev1 = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngEmbIdEntity.class, 1 ) + .add( AuditEntity.property( "reference" ).eq( new SetRefEdEmbIdEntity( id3, null ) ) ) + .getResultList() + ); - Set rev2_related = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngEmbIdEntity.class, 2) - .add(AuditEntity.relatedId("reference").eq(id3)) - .getResultList()); + Set rev2_related = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngEmbIdEntity.class, 2 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .getResultList() + ); - Set rev2 = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngEmbIdEntity.class, 2) - .add(AuditEntity.property("reference").eq(new SetRefEdEmbIdEntity(id3, null))) - .getResultList()); + Set rev2 = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngEmbIdEntity.class, 2 ) + .add( AuditEntity.property( "reference" ).eq( new SetRefEdEmbIdEntity( id3, null ) ) ) + .getResultList() + ); - Set rev3_related = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngEmbIdEntity.class, 3) - .add(AuditEntity.relatedId("reference").eq(id3)) - .getResultList()); + Set rev3_related = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngEmbIdEntity.class, 3 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .getResultList() + ); - Set rev3 = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngEmbIdEntity.class, 3) - .add(AuditEntity.property("reference").eq(new SetRefEdEmbIdEntity(id3, null))) - .getResultList()); + Set rev3 = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngEmbIdEntity.class, 3 ) + .add( AuditEntity.property( "reference" ).eq( new SetRefEdEmbIdEntity( id3, null ) ) ) + .getResultList() + ); - assert rev1.equals(rev1_related); - assert rev2.equals(rev2_related); - assert rev3.equals(rev3_related); + assert rev1.equals( rev1_related ); + assert rev2.equals( rev2_related ); + assert rev3.equals( rev3_related ); - assert rev1.equals(TestTools.makeSet()); - assert rev2.equals(TestTools.makeSet(new SetRefIngEmbIdEntity(id1, "x", null))); - assert rev3.equals(TestTools.makeSet(new SetRefIngEmbIdEntity(id1, "x", null), - new SetRefIngEmbIdEntity(id2, "y", null))); - } + assert rev1.equals( TestTools.makeSet() ); + assert rev2.equals( TestTools.makeSet( new SetRefIngEmbIdEntity( id1, "x", null ) ) ); + assert rev3.equals( + TestTools.makeSet( + new SetRefIngEmbIdEntity( id1, "x", null ), + new SetRefIngEmbIdEntity( id2, "y", null ) + ) + ); + } - @Test - public void testEntitiesReferencedToId4() { - Set rev1_related = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngEmbIdEntity.class, 1) - .add(AuditEntity.relatedId("reference").eq(id4)) - .getResultList()); + @Test + public void testEntitiesReferencedToId4() { + Set rev1_related = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngEmbIdEntity.class, 1 ) + .add( AuditEntity.relatedId( "reference" ).eq( id4 ) ) + .getResultList() + ); - Set rev2_related = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngEmbIdEntity.class, 2) - .add(AuditEntity.relatedId("reference").eq(id4)) - .getResultList()); + Set rev2_related = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngEmbIdEntity.class, 2 ) + .add( AuditEntity.relatedId( "reference" ).eq( id4 ) ) + .getResultList() + ); - Set rev3_related = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngEmbIdEntity.class, 3) - .add(AuditEntity.relatedId("reference").eq(id4)) - .getResultList()); + Set rev3_related = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngEmbIdEntity.class, 3 ) + .add( AuditEntity.relatedId( "reference" ).eq( id4 ) ) + .getResultList() + ); - assert rev1_related.equals(TestTools.makeSet()); - assert rev2_related.equals(TestTools.makeSet(new SetRefIngEmbIdEntity(id2, "y", null))); - assert rev3_related.equals(TestTools.makeSet()); - } + assert rev1_related.equals( TestTools.makeSet() ); + assert rev2_related.equals( TestTools.makeSet( new SetRefIngEmbIdEntity( id2, "y", null ) ) ); + assert rev3_related.equals( TestTools.makeSet() ); + } - @Test - public void testEntitiesReferencedByIng1ToId3() { - List rev1_related = getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngEmbIdEntity.class, 1) - .add(AuditEntity.relatedId("reference").eq(id3)) - .add(AuditEntity.id().eq(id1)) - .getResultList(); + @Test + public void testEntitiesReferencedByIng1ToId3() { + List rev1_related = getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngEmbIdEntity.class, 1 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .add( AuditEntity.id().eq( id1 ) ) + .getResultList(); - Object rev2_related = getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngEmbIdEntity.class, 2) - .add(AuditEntity.relatedId("reference").eq(id3)) - .add(AuditEntity.id().eq(id1)) - .getSingleResult(); + Object rev2_related = getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngEmbIdEntity.class, 2 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .add( AuditEntity.id().eq( id1 ) ) + .getSingleResult(); - Object rev3_related = getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngEmbIdEntity.class, 3) - .add(AuditEntity.relatedId("reference").eq(id3)) - .add(AuditEntity.id().eq(id1)) - .getSingleResult(); + Object rev3_related = getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngEmbIdEntity.class, 3 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .add( AuditEntity.id().eq( id1 ) ) + .getSingleResult(); - assert rev1_related.size() == 0; - assert rev2_related.equals(new SetRefIngEmbIdEntity(id1, "x", null)); - assert rev3_related.equals(new SetRefIngEmbIdEntity(id1, "x", null)); - } + assert rev1_related.size() == 0; + assert rev2_related.equals( new SetRefIngEmbIdEntity( id1, "x", null ) ); + assert rev3_related.equals( new SetRefIngEmbIdEntity( id1, "x", null ) ); + } - @Test - public void testEntitiesReferencedByIng2ToId3() { - List rev1_related = getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngEmbIdEntity.class, 1) - .add(AuditEntity.relatedId("reference").eq(id3)) - .add(AuditEntity.id().eq(id2)) - .getResultList(); + @Test + public void testEntitiesReferencedByIng2ToId3() { + List rev1_related = getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngEmbIdEntity.class, 1 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .add( AuditEntity.id().eq( id2 ) ) + .getResultList(); - List rev2_related = getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngEmbIdEntity.class, 2) - .add(AuditEntity.relatedId("reference").eq(id3)) - .add(AuditEntity.id().eq(id2)) - .getResultList(); + List rev2_related = getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngEmbIdEntity.class, 2 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .add( AuditEntity.id().eq( id2 ) ) + .getResultList(); - Object rev3_related = getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngEmbIdEntity.class, 3) - .add(AuditEntity.relatedId("reference").eq(id3)) - .add(AuditEntity.id().eq(id2)) - .getSingleResult(); + Object rev3_related = getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngEmbIdEntity.class, 3 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .add( AuditEntity.id().eq( id2 ) ) + .getSingleResult(); - assert rev1_related.size() == 0; - assert rev2_related.size() == 0; - assert rev3_related.equals(new SetRefIngEmbIdEntity(id2, "y", null)); - } + assert rev1_related.size() == 0; + assert rev2_related.size() == 0; + assert rev3_related.equals( new SetRefIngEmbIdEntity( id2, "y", null ) ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/ids/MulIdOneToManyQuery.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/ids/MulIdOneToManyQuery.java index ff50d0bd16..f3c58669b0 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/ids/MulIdOneToManyQuery.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/query/ids/MulIdOneToManyQuery.java @@ -23,12 +23,10 @@ */ package org.hibernate.envers.test.integration.query.ids; +import javax.persistence.EntityManager; import java.util.HashSet; import java.util.List; import java.util.Set; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.query.AuditEntity; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -38,6 +36,8 @@ import org.hibernate.envers.test.entities.onetomany.ids.SetRefEdMulIdEntity; import org.hibernate.envers.test.entities.onetomany.ids.SetRefIngMulIdEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + import static org.junit.Assert.assertEquals; /** @@ -45,170 +45,192 @@ import static org.junit.Assert.assertEquals; */ @SuppressWarnings({"unchecked"}) public class MulIdOneToManyQuery extends BaseEnversJPAFunctionalTestCase { - private MulId id1; - private MulId id2; + private MulId id1; + private MulId id2; - private MulId id3; - private MulId id4; + private MulId id3; + private MulId id4; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SetRefEdMulIdEntity.class, SetRefIngMulIdEntity.class }; - } + return new Class[] {SetRefEdMulIdEntity.class, SetRefIngMulIdEntity.class}; + } - @Test - @Priority(10) - public void initData() { - id1 = new MulId(0, 1); - id2 = new MulId(10, 11); - id3 = new MulId(20, 21); - id4 = new MulId(30, 31); + @Test + @Priority(10) + public void initData() { + id1 = new MulId( 0, 1 ); + id2 = new MulId( 10, 11 ); + id3 = new MulId( 20, 21 ); + id4 = new MulId( 30, 31 ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - SetRefIngMulIdEntity refIng1 = new SetRefIngMulIdEntity(id1, "x", null); - SetRefIngMulIdEntity refIng2 = new SetRefIngMulIdEntity(id2, "y", null); + SetRefIngMulIdEntity refIng1 = new SetRefIngMulIdEntity( id1, "x", null ); + SetRefIngMulIdEntity refIng2 = new SetRefIngMulIdEntity( id2, "y", null ); - em.persist(refIng1); - em.persist(refIng2); + em.persist( refIng1 ); + em.persist( refIng2 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - SetRefEdMulIdEntity refEd3 = new SetRefEdMulIdEntity(id3, "a"); - SetRefEdMulIdEntity refEd4 = new SetRefEdMulIdEntity(id4, "a"); + SetRefEdMulIdEntity refEd3 = new SetRefEdMulIdEntity( id3, "a" ); + SetRefEdMulIdEntity refEd4 = new SetRefEdMulIdEntity( id4, "a" ); - em.persist(refEd3); - em.persist(refEd4); + em.persist( refEd3 ); + em.persist( refEd4 ); - refIng1 = em.find(SetRefIngMulIdEntity.class, id1); - refIng2 = em.find(SetRefIngMulIdEntity.class, id2); + refIng1 = em.find( SetRefIngMulIdEntity.class, id1 ); + refIng2 = em.find( SetRefIngMulIdEntity.class, id2 ); - refIng1.setReference(refEd3); - refIng2.setReference(refEd4); + refIng1.setReference( refEd3 ); + refIng2.setReference( refEd4 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - refEd3 = em.find(SetRefEdMulIdEntity.class, id3); - refIng2 = em.find(SetRefIngMulIdEntity.class, id2); - refIng2.setReference(refEd3); + refEd3 = em.find( SetRefEdMulIdEntity.class, id3 ); + refIng2 = em.find( SetRefIngMulIdEntity.class, id2 ); + refIng2.setReference( refEd3 ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testEntitiesReferencedToId3() { - Set rev1_related = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngMulIdEntity.class, 1) - .add(AuditEntity.relatedId("reference").eq(id3)) - .getResultList()); + @Test + public void testEntitiesReferencedToId3() { + Set rev1_related = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngMulIdEntity.class, 1 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .getResultList() + ); - Set rev1 = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngMulIdEntity.class, 1) - .add(AuditEntity.property("reference").eq(new SetRefEdMulIdEntity(id3, null))) - .getResultList()); + Set rev1 = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngMulIdEntity.class, 1 ) + .add( AuditEntity.property( "reference" ).eq( new SetRefEdMulIdEntity( id3, null ) ) ) + .getResultList() + ); - Set rev2_related = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngMulIdEntity.class, 2) - .add(AuditEntity.relatedId("reference").eq(id3)) - .getResultList()); + Set rev2_related = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngMulIdEntity.class, 2 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .getResultList() + ); - Set rev2 = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngMulIdEntity.class, 2) - .add(AuditEntity.property("reference").eq(new SetRefEdMulIdEntity(id3, null))) - .getResultList()); + Set rev2 = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngMulIdEntity.class, 2 ) + .add( AuditEntity.property( "reference" ).eq( new SetRefEdMulIdEntity( id3, null ) ) ) + .getResultList() + ); - Set rev3_related = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngMulIdEntity.class, 3) - .add(AuditEntity.relatedId("reference").eq(id3)) - .getResultList()); + Set rev3_related = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngMulIdEntity.class, 3 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .getResultList() + ); - Set rev3 = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngMulIdEntity.class, 3) - .add(AuditEntity.property("reference").eq(new SetRefEdMulIdEntity(id3, null))) - .getResultList()); + Set rev3 = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngMulIdEntity.class, 3 ) + .add( AuditEntity.property( "reference" ).eq( new SetRefEdMulIdEntity( id3, null ) ) ) + .getResultList() + ); assertEquals( rev1, rev1_related ); assertEquals( rev2, rev2_related ); assertEquals( rev3, rev3_related ); assertEquals( rev1, TestTools.makeSet() ); - assertEquals( rev2, TestTools.makeSet(new SetRefIngMulIdEntity(id1, "x", null)) ); - assertEquals( rev3, TestTools.makeSet(new SetRefIngMulIdEntity(id1, "x", null), - new SetRefIngMulIdEntity(id2, "y", null)) ); - } + assertEquals( rev2, TestTools.makeSet( new SetRefIngMulIdEntity( id1, "x", null ) ) ); + assertEquals( + rev3, TestTools.makeSet( + new SetRefIngMulIdEntity( id1, "x", null ), + new SetRefIngMulIdEntity( id2, "y", null ) + ) + ); + } - @Test - public void testEntitiesReferencedToId4() { - Set rev1_related = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngMulIdEntity.class, 1) - .add(AuditEntity.relatedId("reference").eq(id4)) - .getResultList()); + @Test + public void testEntitiesReferencedToId4() { + Set rev1_related = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngMulIdEntity.class, 1 ) + .add( AuditEntity.relatedId( "reference" ).eq( id4 ) ) + .getResultList() + ); - Set rev2_related = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngMulIdEntity.class, 2) - .add(AuditEntity.relatedId("reference").eq(id4)) - .getResultList()); + Set rev2_related = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngMulIdEntity.class, 2 ) + .add( AuditEntity.relatedId( "reference" ).eq( id4 ) ) + .getResultList() + ); - Set rev3_related = new HashSet(getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngMulIdEntity.class, 3) - .add(AuditEntity.relatedId("reference").eq(id4)) - .getResultList()); - assertEquals( rev1_related, TestTools.makeSet( )); - assertEquals( rev2_related, TestTools.makeSet(new SetRefIngMulIdEntity(id2, "y", null))); - assertEquals( rev3_related, TestTools.makeSet( )); - } + Set rev3_related = new HashSet( + getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngMulIdEntity.class, 3 ) + .add( AuditEntity.relatedId( "reference" ).eq( id4 ) ) + .getResultList() + ); + assertEquals( rev1_related, TestTools.makeSet() ); + assertEquals( rev2_related, TestTools.makeSet( new SetRefIngMulIdEntity( id2, "y", null ) ) ); + assertEquals( rev3_related, TestTools.makeSet() ); + } - @Test - public void testEntitiesReferencedByIng1ToId3() { - List rev1_related = getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngMulIdEntity.class, 1) - .add(AuditEntity.relatedId("reference").eq(id3)) - .add(AuditEntity.id().eq(id1)) - .getResultList(); + @Test + public void testEntitiesReferencedByIng1ToId3() { + List rev1_related = getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngMulIdEntity.class, 1 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .add( AuditEntity.id().eq( id1 ) ) + .getResultList(); - Object rev2_related = getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngMulIdEntity.class, 2) - .add(AuditEntity.relatedId("reference").eq(id3)) - .add(AuditEntity.id().eq(id1)) - .getSingleResult(); + Object rev2_related = getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngMulIdEntity.class, 2 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .add( AuditEntity.id().eq( id1 ) ) + .getSingleResult(); - Object rev3_related = getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngMulIdEntity.class, 3) - .add(AuditEntity.relatedId("reference").eq(id3)) - .add(AuditEntity.id().eq(id1)) - .getSingleResult(); + Object rev3_related = getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngMulIdEntity.class, 3 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .add( AuditEntity.id().eq( id1 ) ) + .getSingleResult(); assertEquals( 0, rev1_related.size() ); - assertEquals( rev2_related,new SetRefIngMulIdEntity(id1, "x", null) ); - assertEquals( rev3_related, new SetRefIngMulIdEntity(id1, "x", null) ); - } + assertEquals( rev2_related, new SetRefIngMulIdEntity( id1, "x", null ) ); + assertEquals( rev3_related, new SetRefIngMulIdEntity( id1, "x", null ) ); + } - @Test - public void testEntitiesReferencedByIng2ToId3() { - List rev1_related = getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngMulIdEntity.class, 1) - .add(AuditEntity.relatedId("reference").eq(id3)) - .add(AuditEntity.id().eq(id2)) - .getResultList(); + @Test + public void testEntitiesReferencedByIng2ToId3() { + List rev1_related = getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngMulIdEntity.class, 1 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .add( AuditEntity.id().eq( id2 ) ) + .getResultList(); - List rev2_related = getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngMulIdEntity.class, 2) - .add(AuditEntity.relatedId("reference").eq(id3)) - .add(AuditEntity.id().eq(id2)) - .getResultList(); + List rev2_related = getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngMulIdEntity.class, 2 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .add( AuditEntity.id().eq( id2 ) ) + .getResultList(); - Object rev3_related = getAuditReader().createQuery() - .forEntitiesAtRevision(SetRefIngMulIdEntity.class, 3) - .add(AuditEntity.relatedId("reference").eq(id3)) - .add(AuditEntity.id().eq(id2)) - .getSingleResult(); + Object rev3_related = getAuditReader().createQuery() + .forEntitiesAtRevision( SetRefIngMulIdEntity.class, 3 ) + .add( AuditEntity.relatedId( "reference" ).eq( id3 ) ) + .add( AuditEntity.id().eq( id2 ) ) + .getSingleResult(); assertEquals( 0, rev1_related.size() ); assertEquals( 0, rev2_related.size() ); - assertEquals( new SetRefIngMulIdEntity(id2, "y", null), rev3_related ); - } + assertEquals( new SetRefIngMulIdEntity( id2, "y", null ), rev3_related ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/readwriteexpression/ReadWriteExpressionChange.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/readwriteexpression/ReadWriteExpressionChange.java index d1a6edf212..e070f1bf3a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/readwriteexpression/ReadWriteExpressionChange.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/readwriteexpression/ReadWriteExpressionChange.java @@ -1,60 +1,61 @@ package org.hibernate.envers.test.integration.readwriteexpression; +import javax.persistence.EntityManager; import java.math.BigDecimal; import java.util.List; -import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; import org.hibernate.dialect.Oracle8iDialect; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Assert; +import org.junit.Test; + public class ReadWriteExpressionChange extends BaseEnversJPAFunctionalTestCase { - private static final Double HEIGHT_INCHES = 73.0d; - private static final Double HEIGHT_CENTIMETERS = HEIGHT_INCHES * 2.54d; + private static final Double HEIGHT_INCHES = 73.0d; + private static final Double HEIGHT_CENTIMETERS = HEIGHT_INCHES * 2.54d; - private Integer id; + private Integer id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { Staff.class }; - } + return new Class[] {Staff.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - Staff staff = new Staff(HEIGHT_INCHES, 1); - em.persist(staff); - em.getTransaction().commit(); - id = staff.getId(); - } + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + Staff staff = new Staff( HEIGHT_INCHES, 1 ); + em.persist( staff ); + em.getTransaction().commit(); + id = staff.getId(); + } - @Test - public void shouldRespectWriteExpression() { - EntityManager em = getEntityManager(); - List resultList = em.createNativeQuery("select size_in_cm from t_staff_AUD where id ="+id).getResultList(); - Assert.assertEquals(1, resultList.size()); - Double sizeInCm = null; - if (getDialect() instanceof Oracle8iDialect) { - sizeInCm = ((BigDecimal) resultList.get(0)).doubleValue(); - } else { - sizeInCm = (Double) resultList.get(0); - } - Assert.assertEquals(HEIGHT_CENTIMETERS, sizeInCm.doubleValue(), 0.00000001); - } + @Test + public void shouldRespectWriteExpression() { + EntityManager em = getEntityManager(); + List resultList = em.createNativeQuery( "select size_in_cm from t_staff_AUD where id =" + id ).getResultList(); + Assert.assertEquals( 1, resultList.size() ); + Double sizeInCm = null; + if ( getDialect() instanceof Oracle8iDialect ) { + sizeInCm = ((BigDecimal) resultList.get( 0 )).doubleValue(); + } + else { + sizeInCm = (Double) resultList.get( 0 ); + } + Assert.assertEquals( HEIGHT_CENTIMETERS, sizeInCm.doubleValue(), 0.00000001 ); + } - @Test - public void shouldRespectReadExpression() { - List revisions = getAuditReader().getRevisions(Staff.class, id); - Assert.assertEquals(1, revisions.size()); - Number number = revisions.get(0); - Staff staffRev = getAuditReader().find(Staff.class, id, number); - Assert.assertEquals(HEIGHT_INCHES, staffRev.getSizeInInches(), 0.00000001); - } + @Test + public void shouldRespectReadExpression() { + List revisions = getAuditReader().getRevisions( Staff.class, id ); + Assert.assertEquals( 1, revisions.size() ); + Number number = revisions.get( 0 ); + Staff staffRev = getAuditReader().find( Staff.class, id, number ); + Assert.assertEquals( HEIGHT_INCHES, staffRev.getSizeInInches(), 0.00000001 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/readwriteexpression/Staff.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/readwriteexpression/Staff.java index 354391c6c2..08f1290c4e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/readwriteexpression/Staff.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/readwriteexpression/Staff.java @@ -9,30 +9,42 @@ import org.hibernate.annotations.ColumnTransformer; import org.hibernate.envers.Audited; @Entity -@Table(name="t_staff") +@Table(name = "t_staff") public class Staff { - public Staff() { - } + public Staff() { + } - public Staff(double sizeInInches, Integer id) { + public Staff(double sizeInInches, Integer id) { this.sizeInInches = sizeInInches; this.id = id; } @Id - public Integer getId() { return id; } - public void setId(Integer id) { this.id = id; } + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + private Integer id; - @Audited - @Column(name="size_in_cm") + @Audited + @Column(name = "size_in_cm") @ColumnTransformer( forColumn = "size_in_cm", read = "size_in_cm / 2.54E0", - write = "? * 2.54E0" ) - public double getSizeInInches() { return sizeInInches; } - public void setSizeInInches(double sizeInInches) { this.sizeInInches = sizeInInches; } + write = "? * 2.54E0") + public double getSizeInInches() { + return sizeInInches; + } + + public void setSizeInInches(double sizeInInches) { + this.sizeInInches = sizeInInches; + } + private double sizeInInches; diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reference/BidirectionalReference.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reference/BidirectionalReference.java index 77d4812d30..1bd9eccdd6 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reference/BidirectionalReference.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reference/BidirectionalReference.java @@ -23,129 +23,129 @@ */ package org.hibernate.envers.test.integration.reference; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BidirectionalReference extends BaseEnversJPAFunctionalTestCase { - private Long set1_id; - private Long set2_id; + private Long set1_id; + private Long set2_id; - private Long g1_id; + private Long g1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { GreetingPO.class, GreetingSetPO.class }; - } + return new Class[] {GreetingPO.class, GreetingSetPO.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - GreetingSetPO set1 = new GreetingSetPO(); - set1.setName("a1"); + GreetingSetPO set1 = new GreetingSetPO(); + set1.setName( "a1" ); GreetingSetPO set2 = new GreetingSetPO(); - set2.setName("a2"); + set2.setName( "a2" ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(set1); - em.persist(set2); + em.persist( set1 ); + em.persist( set2 ); set1_id = set1.getId(); set2_id = set2.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); em.clear(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - GreetingPO g1 = new GreetingPO(); - g1.setGreeting("g1"); - g1.setGreetingSet(em.getReference(GreetingSetPO.class, set1_id)); + GreetingPO g1 = new GreetingPO(); + g1.setGreeting( "g1" ); + g1.setGreetingSet( em.getReference( GreetingSetPO.class, set1_id ) ); - em.persist(g1); + em.persist( g1 ); g1_id = g1.getId(); - em.getTransaction().commit(); + em.getTransaction().commit(); em.clear(); - // Revision 3 - em.getTransaction().begin(); + // Revision 3 + em.getTransaction().begin(); - g1 = em.find(GreetingPO.class, g1_id); + g1 = em.find( GreetingPO.class, g1_id ); - g1.setGreetingSet(em.getReference(GreetingSetPO.class, set2_id)); + g1.setGreetingSet( em.getReference( GreetingSetPO.class, set2_id ) ); - em.getTransaction().commit(); - } - - @Test - public void testRevisionsCounts() { - assert Arrays.asList(2, 3).equals(getAuditReader().getRevisions(GreetingPO.class, g1_id)); - - assert Arrays.asList(1, 2, 3).equals(getAuditReader().getRevisions(GreetingSetPO.class, set1_id)); - assert Arrays.asList(1, 3).equals(getAuditReader().getRevisions(GreetingSetPO.class, set2_id)); - } - - @Test - public void testHistoryOfG1() { - GreetingPO rev1 = getAuditReader().find(GreetingPO.class, g1_id, 1); - GreetingPO rev2 = getAuditReader().find(GreetingPO.class, g1_id, 2); - GreetingPO rev3 = getAuditReader().find(GreetingPO.class, g1_id, 3); - - assert rev1 == null; - assert rev2.getGreetingSet().getName().equals("a1"); - assert rev3.getGreetingSet().getName().equals("a2"); - } + em.getTransaction().commit(); + } @Test - public void testHistoryOfSet1() { - GreetingSetPO rev1 = getAuditReader().find(GreetingSetPO.class, set1_id, 1); - GreetingSetPO rev2 = getAuditReader().find(GreetingSetPO.class, set1_id, 2); - GreetingSetPO rev3 = getAuditReader().find(GreetingSetPO.class, set1_id, 3); + public void testRevisionsCounts() { + assert Arrays.asList( 2, 3 ).equals( getAuditReader().getRevisions( GreetingPO.class, g1_id ) ); - assert rev1.getName().equals("a1"); - assert rev2.getName().equals("a1"); - assert rev3.getName().equals("a1"); + assert Arrays.asList( 1, 2, 3 ).equals( getAuditReader().getRevisions( GreetingSetPO.class, set1_id ) ); + assert Arrays.asList( 1, 3 ).equals( getAuditReader().getRevisions( GreetingSetPO.class, set2_id ) ); + } + + @Test + public void testHistoryOfG1() { + GreetingPO rev1 = getAuditReader().find( GreetingPO.class, g1_id, 1 ); + GreetingPO rev2 = getAuditReader().find( GreetingPO.class, g1_id, 2 ); + GreetingPO rev3 = getAuditReader().find( GreetingPO.class, g1_id, 3 ); + + assert rev1 == null; + assert rev2.getGreetingSet().getName().equals( "a1" ); + assert rev3.getGreetingSet().getName().equals( "a2" ); + } + + @Test + public void testHistoryOfSet1() { + GreetingSetPO rev1 = getAuditReader().find( GreetingSetPO.class, set1_id, 1 ); + GreetingSetPO rev2 = getAuditReader().find( GreetingSetPO.class, set1_id, 2 ); + GreetingSetPO rev3 = getAuditReader().find( GreetingSetPO.class, set1_id, 3 ); + + assert rev1.getName().equals( "a1" ); + assert rev2.getName().equals( "a1" ); + assert rev3.getName().equals( "a1" ); GreetingPO g1 = new GreetingPO(); - g1.setId(g1_id); - g1.setGreeting("g1"); + g1.setId( g1_id ); + g1.setGreeting( "g1" ); assert rev1.getGreetings().size() == 0; - assert rev2.getGreetings().equals(TestTools.makeSet(g1)); + assert rev2.getGreetings().equals( TestTools.makeSet( g1 ) ); assert rev3.getGreetings().size() == 0; - } + } @Test - public void testHistoryOfSet2() { - GreetingSetPO rev1 = getAuditReader().find(GreetingSetPO.class, set2_id, 1); - GreetingSetPO rev2 = getAuditReader().find(GreetingSetPO.class, set2_id, 2); - GreetingSetPO rev3 = getAuditReader().find(GreetingSetPO.class, set2_id, 3); + public void testHistoryOfSet2() { + GreetingSetPO rev1 = getAuditReader().find( GreetingSetPO.class, set2_id, 1 ); + GreetingSetPO rev2 = getAuditReader().find( GreetingSetPO.class, set2_id, 2 ); + GreetingSetPO rev3 = getAuditReader().find( GreetingSetPO.class, set2_id, 3 ); - assert rev1.getName().equals("a2"); - assert rev2.getName().equals("a2"); - assert rev3.getName().equals("a2"); + assert rev1.getName().equals( "a2" ); + assert rev2.getName().equals( "a2" ); + assert rev3.getName().equals( "a2" ); GreetingPO g1 = new GreetingPO(); - g1.setId(g1_id); - g1.setGreeting("g1"); + g1.setId( g1_id ); + g1.setGreeting( "g1" ); assert rev1.getGreetings().size() == 0; assert rev2.getGreetings().size() == 0; - assert rev3.getGreetings().equals(TestTools.makeSet(g1)); - } + assert rev3.getGreetings().equals( TestTools.makeSet( g1 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingPO.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingPO.java index 94ad941827..b15a85718e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingPO.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingPO.java @@ -1,4 +1,5 @@ package org.hibernate.envers.test.integration.reference; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -44,13 +45,21 @@ public class GreetingPO { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof GreetingPO)) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof GreetingPO) ) { + return false; + } GreetingPO that = (GreetingPO) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (theGreeting != null ? !theGreeting.equals(that.theGreeting) : that.theGreeting != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( theGreeting != null ? !theGreeting.equals( that.theGreeting ) : that.theGreeting != null ) { + return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingSetPO.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingSetPO.java index 275cb74edb..72e6947994 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingSetPO.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reference/GreetingSetPO.java @@ -1,9 +1,10 @@ package org.hibernate.envers.test.integration.reference; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.util.Set; import org.hibernate.envers.Audited; @@ -45,13 +46,21 @@ public class GreetingSetPO { @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof GreetingSetPO)) return false; + if ( this == o ) { + return true; + } + if ( !(o instanceof GreetingSetPO) ) { + return false; + } GreetingSetPO that = (GreetingSetPO) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (name != null ? !name.equals(that.name) : that.name != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( name != null ? !name.equals( that.name ) : that.name != null ) { + return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CountingRevisionListener.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CountingRevisionListener.java index e05e82b422..61b26db7ca 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CountingRevisionListener.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CountingRevisionListener.java @@ -6,10 +6,10 @@ import org.hibernate.envers.RevisionListener; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class CountingRevisionListener implements RevisionListener { - public static int revisionCount = 0; + public static int revisionCount = 0; - @Override - public void newRevision(Object revisionEntity) { - ++revisionCount; - } + @Override + public void newRevision(Object revisionEntity) { + ++revisionCount; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/Custom.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/Custom.java index 381188a7ca..e89dda7391 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/Custom.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/Custom.java @@ -23,14 +23,12 @@ */ package org.hibernate.envers.test.integration.reventity; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.Map; import java.util.Set; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.AuditReader; import org.hibernate.envers.exception.RevisionDoesNotExistException; @@ -39,114 +37,117 @@ import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.reventity.CustomRevEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class Custom extends BaseEnversJPAFunctionalTestCase { - private Integer id; - private long timestamp1; - private long timestamp2; - private long timestamp3; + private Integer id; + private long timestamp1; + private long timestamp2; + private long timestamp3; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class, CustomRevEntity.class }; - } + return new Class[] {StrTestEntity.class, CustomRevEntity.class}; + } - @Test - @Priority(10) - public void initData() throws InterruptedException { - timestamp1 = System.currentTimeMillis(); + @Test + @Priority(10) + public void initData() throws InterruptedException { + timestamp1 = System.currentTimeMillis(); - Thread.sleep(100); + Thread.sleep( 100 ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - StrTestEntity te = new StrTestEntity("x"); - em.persist(te); - id = te.getId(); - em.getTransaction().commit(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + StrTestEntity te = new StrTestEntity( "x" ); + em.persist( te ); + id = te.getId(); + em.getTransaction().commit(); - timestamp2 = System.currentTimeMillis(); + timestamp2 = System.currentTimeMillis(); - Thread.sleep(100); + Thread.sleep( 100 ); - // Revision 2 - em.getTransaction().begin(); - te = em.find(StrTestEntity.class, id); - te.setStr("y"); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + te = em.find( StrTestEntity.class, id ); + te.setStr( "y" ); + em.getTransaction().commit(); - timestamp3 = System.currentTimeMillis(); - } + timestamp3 = System.currentTimeMillis(); + } - @Test(expected = RevisionDoesNotExistException.class) - public void testTimestamps1() { - getAuditReader().getRevisionNumberForDate(new Date(timestamp1)); - } + @Test(expected = RevisionDoesNotExistException.class) + public void testTimestamps1() { + getAuditReader().getRevisionNumberForDate( new Date( timestamp1 ) ); + } - @Test - public void testTimestamps() { - assert getAuditReader().getRevisionNumberForDate(new Date(timestamp2)).intValue() == 1; - assert getAuditReader().getRevisionNumberForDate(new Date(timestamp3)).intValue() == 2; - } + @Test + public void testTimestamps() { + assert getAuditReader().getRevisionNumberForDate( new Date( timestamp2 ) ).intValue() == 1; + assert getAuditReader().getRevisionNumberForDate( new Date( timestamp3 ) ).intValue() == 2; + } - @Test - public void testDatesForRevisions() { - AuditReader vr = getAuditReader(); - assert vr.getRevisionNumberForDate(vr.getRevisionDate(1)).intValue() == 1; - assert vr.getRevisionNumberForDate(vr.getRevisionDate(2)).intValue() == 2; - } + @Test + public void testDatesForRevisions() { + AuditReader vr = getAuditReader(); + assert vr.getRevisionNumberForDate( vr.getRevisionDate( 1 ) ).intValue() == 1; + assert vr.getRevisionNumberForDate( vr.getRevisionDate( 2 ) ).intValue() == 2; + } - @Test - public void testRevisionsForDates() { - AuditReader vr = getAuditReader(); + @Test + public void testRevisionsForDates() { + AuditReader vr = getAuditReader(); - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp2))).getTime() <= timestamp2; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp2)).intValue()+1).getTime() > timestamp2; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp2 ) ) ).getTime() <= timestamp2; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp2 ) ).intValue() + 1 ) + .getTime() > timestamp2; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp3))).getTime() <= timestamp3; - } + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp3 ) ) ).getTime() <= timestamp3; + } - @Test - public void testFindRevision() { - AuditReader vr = getAuditReader(); + @Test + public void testFindRevision() { + AuditReader vr = getAuditReader(); - long rev1Timestamp = vr.findRevision(CustomRevEntity.class, 1).getCustomTimestamp(); - assert rev1Timestamp > timestamp1; - assert rev1Timestamp <= timestamp2; + long rev1Timestamp = vr.findRevision( CustomRevEntity.class, 1 ).getCustomTimestamp(); + assert rev1Timestamp > timestamp1; + assert rev1Timestamp <= timestamp2; - long rev2Timestamp = vr.findRevision(CustomRevEntity.class, 2).getCustomTimestamp(); - assert rev2Timestamp > timestamp2; - assert rev2Timestamp <= timestamp3; - } + long rev2Timestamp = vr.findRevision( CustomRevEntity.class, 2 ).getCustomTimestamp(); + assert rev2Timestamp > timestamp2; + assert rev2Timestamp <= timestamp3; + } - @Test - public void testFindRevisions() { - AuditReader vr = getAuditReader(); + @Test + public void testFindRevisions() { + AuditReader vr = getAuditReader(); - Set revNumbers = new HashSet(); - revNumbers.add(1); - revNumbers.add(2); - - Map revisionMap = vr.findRevisions(CustomRevEntity.class, revNumbers); - assert(revisionMap.size() == 2); - assert(revisionMap.get(1).equals(vr.findRevision(CustomRevEntity.class, 1))); - assert(revisionMap.get(2).equals(vr.findRevision(CustomRevEntity.class, 2))); - } + Set revNumbers = new HashSet(); + revNumbers.add( 1 ); + revNumbers.add( 2 ); - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(StrTestEntity.class, id)); - } + Map revisionMap = vr.findRevisions( CustomRevEntity.class, revNumbers ); + assert (revisionMap.size() == 2); + assert (revisionMap.get( 1 ).equals( vr.findRevision( CustomRevEntity.class, 1 ) )); + assert (revisionMap.get( 2 ).equals( vr.findRevision( CustomRevEntity.class, 2 ) )); + } - @Test - public void testHistoryOfId1() { - StrTestEntity ver1 = new StrTestEntity("x", id); - StrTestEntity ver2 = new StrTestEntity("y", id); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( StrTestEntity.class, id ) ); + } - assert getAuditReader().find(StrTestEntity.class, id, 1).equals(ver1); - assert getAuditReader().find(StrTestEntity.class, id, 2).equals(ver2); - } + @Test + public void testHistoryOfId1() { + StrTestEntity ver1 = new StrTestEntity( "x", id ); + StrTestEntity ver2 = new StrTestEntity( "y", id ); + + assert getAuditReader().find( StrTestEntity.class, id, 1 ).equals( ver1 ); + assert getAuditReader().find( StrTestEntity.class, id, 2 ).equals( ver2 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomBoxed.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomBoxed.java index 67deef8641..c14288c4d9 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomBoxed.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomBoxed.java @@ -23,14 +23,12 @@ */ package org.hibernate.envers.test.integration.reventity; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.Map; import java.util.Set; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.AuditReader; import org.hibernate.envers.exception.RevisionDoesNotExistException; @@ -38,114 +36,117 @@ import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class CustomBoxed extends BaseEnversJPAFunctionalTestCase { - private Integer id; - private long timestamp1; - private long timestamp2; - private long timestamp3; + private Integer id; + private long timestamp1; + private long timestamp2; + private long timestamp3; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class, CustomBoxedRevEntity.class }; - } + return new Class[] {StrTestEntity.class, CustomBoxedRevEntity.class}; + } - @Test - @Priority(10) - public void initData() throws InterruptedException { - timestamp1 = System.currentTimeMillis(); + @Test + @Priority(10) + public void initData() throws InterruptedException { + timestamp1 = System.currentTimeMillis(); - Thread.sleep(100); + Thread.sleep( 100 ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - StrTestEntity te = new StrTestEntity("x"); - em.persist(te); - id = te.getId(); - em.getTransaction().commit(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + StrTestEntity te = new StrTestEntity( "x" ); + em.persist( te ); + id = te.getId(); + em.getTransaction().commit(); - timestamp2 = System.currentTimeMillis(); + timestamp2 = System.currentTimeMillis(); - Thread.sleep(100); + Thread.sleep( 100 ); - // Revision 2 - em.getTransaction().begin(); - te = em.find(StrTestEntity.class, id); - te.setStr("y"); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + te = em.find( StrTestEntity.class, id ); + te.setStr( "y" ); + em.getTransaction().commit(); - timestamp3 = System.currentTimeMillis(); - } + timestamp3 = System.currentTimeMillis(); + } - @Test(expected = RevisionDoesNotExistException.class) - public void testTimestamps1() { - getAuditReader().getRevisionNumberForDate(new Date(timestamp1)); - } + @Test(expected = RevisionDoesNotExistException.class) + public void testTimestamps1() { + getAuditReader().getRevisionNumberForDate( new Date( timestamp1 ) ); + } - @Test - public void testTimestamps() { - assert getAuditReader().getRevisionNumberForDate(new Date(timestamp2)).intValue() == 1; - assert getAuditReader().getRevisionNumberForDate(new Date(timestamp3)).intValue() == 2; - } + @Test + public void testTimestamps() { + assert getAuditReader().getRevisionNumberForDate( new Date( timestamp2 ) ).intValue() == 1; + assert getAuditReader().getRevisionNumberForDate( new Date( timestamp3 ) ).intValue() == 2; + } - @Test - public void testDatesForRevisions() { - AuditReader vr = getAuditReader(); - assert vr.getRevisionNumberForDate(vr.getRevisionDate(1)).intValue() == 1; - assert vr.getRevisionNumberForDate(vr.getRevisionDate(2)).intValue() == 2; - } + @Test + public void testDatesForRevisions() { + AuditReader vr = getAuditReader(); + assert vr.getRevisionNumberForDate( vr.getRevisionDate( 1 ) ).intValue() == 1; + assert vr.getRevisionNumberForDate( vr.getRevisionDate( 2 ) ).intValue() == 2; + } - @Test - public void testRevisionsForDates() { - AuditReader vr = getAuditReader(); + @Test + public void testRevisionsForDates() { + AuditReader vr = getAuditReader(); - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp2))).getTime() <= timestamp2; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp2)).intValue()+1).getTime() > timestamp2; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp2 ) ) ).getTime() <= timestamp2; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp2 ) ).intValue() + 1 ) + .getTime() > timestamp2; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp3))).getTime() <= timestamp3; - } + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp3 ) ) ).getTime() <= timestamp3; + } - @Test - public void testFindRevision() { - AuditReader vr = getAuditReader(); + @Test + public void testFindRevision() { + AuditReader vr = getAuditReader(); - long rev1Timestamp = vr.findRevision(CustomBoxedRevEntity.class, 1).getCustomTimestamp(); - assert rev1Timestamp > timestamp1; - assert rev1Timestamp <= timestamp2; + long rev1Timestamp = vr.findRevision( CustomBoxedRevEntity.class, 1 ).getCustomTimestamp(); + assert rev1Timestamp > timestamp1; + assert rev1Timestamp <= timestamp2; - long rev2Timestamp = vr.findRevision(CustomBoxedRevEntity.class, 2).getCustomTimestamp(); - assert rev2Timestamp > timestamp2; - assert rev2Timestamp <= timestamp3; - } + long rev2Timestamp = vr.findRevision( CustomBoxedRevEntity.class, 2 ).getCustomTimestamp(); + assert rev2Timestamp > timestamp2; + assert rev2Timestamp <= timestamp3; + } - @Test - public void testFindRevisions() { - AuditReader vr = getAuditReader(); + @Test + public void testFindRevisions() { + AuditReader vr = getAuditReader(); - Set revNumbers = new HashSet(); - revNumbers.add(1); - revNumbers.add(2); - - Map revisionMap = vr.findRevisions(CustomBoxedRevEntity.class, revNumbers); - assert(revisionMap.size() == 2); - assert(revisionMap.get(1).equals(vr.findRevision(CustomBoxedRevEntity.class, 1))); - assert(revisionMap.get(2).equals(vr.findRevision(CustomBoxedRevEntity.class, 2))); - } + Set revNumbers = new HashSet(); + revNumbers.add( 1 ); + revNumbers.add( 2 ); - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(StrTestEntity.class, id)); - } + Map revisionMap = vr.findRevisions( CustomBoxedRevEntity.class, revNumbers ); + assert (revisionMap.size() == 2); + assert (revisionMap.get( 1 ).equals( vr.findRevision( CustomBoxedRevEntity.class, 1 ) )); + assert (revisionMap.get( 2 ).equals( vr.findRevision( CustomBoxedRevEntity.class, 2 ) )); + } - @Test - public void testHistoryOfId1() { - StrTestEntity ver1 = new StrTestEntity("x", id); - StrTestEntity ver2 = new StrTestEntity("y", id); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( StrTestEntity.class, id ) ); + } - assert getAuditReader().find(StrTestEntity.class, id, 1).equals(ver1); - assert getAuditReader().find(StrTestEntity.class, id, 2).equals(ver2); - } + @Test + public void testHistoryOfId1() { + StrTestEntity ver1 = new StrTestEntity( "x", id ); + StrTestEntity ver2 = new StrTestEntity( "y", id ); + + assert getAuditReader().find( StrTestEntity.class, id, 1 ).equals( ver1 ); + assert getAuditReader().find( StrTestEntity.class, id, 2 ).equals( ver2 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomBoxedRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomBoxedRevEntity.java index c31ba406ff..5d1b5531cd 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomBoxedRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomBoxedRevEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.reventity; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -37,56 +38,66 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = {@Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class CustomBoxedRevEntity { - @Id - @GeneratedValue(generator = "EnversTestingRevisionGenerator") - @RevisionNumber - private Integer customId; + @Id + @GeneratedValue(generator = "EnversTestingRevisionGenerator") + @RevisionNumber + private Integer customId; - @RevisionTimestamp - private Long customTimestamp; + @RevisionTimestamp + private Long customTimestamp; - public Integer getCustomId() { - return customId; - } + public Integer getCustomId() { + return customId; + } - public void setCustomId(Integer customId) { - this.customId = customId; - } + public void setCustomId(Integer customId) { + this.customId = customId; + } - public Long getCustomTimestamp() { - return customTimestamp; - } + public Long getCustomTimestamp() { + return customTimestamp; + } - public void setCustomTimestamp(Long customTimestamp) { - this.customTimestamp = customTimestamp; - } + public void setCustomTimestamp(Long customTimestamp) { + this.customTimestamp = customTimestamp; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof CustomBoxedRevEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof CustomBoxedRevEntity) ) { + return false; + } - CustomBoxedRevEntity that = (CustomBoxedRevEntity) o; + CustomBoxedRevEntity that = (CustomBoxedRevEntity) o; - if (customId != null ? !customId.equals(that.customId) : that.customId != null) return false; - if (customTimestamp != null ? !customTimestamp.equals(that.customTimestamp) : that.customTimestamp != null) - return false; + if ( customId != null ? !customId.equals( that.customId ) : that.customId != null ) { + return false; + } + if ( customTimestamp != null ? + !customTimestamp.equals( that.customTimestamp ) : + that.customTimestamp != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (customId != null ? customId.hashCode() : 0); - result = 31 * result + (customTimestamp != null ? customTimestamp.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (customId != null ? customId.hashCode() : 0); + result = 31 * result + (customTimestamp != null ? customTimestamp.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomColumnMapping.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomColumnMapping.java index 30fd2de22f..57cea70248 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomColumnMapping.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomColumnMapping.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.reventity; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Date; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.AuditReader; import org.hibernate.envers.exception.RevisionDoesNotExistException; @@ -36,102 +34,106 @@ import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.reventity.CustomRevEntityColumnMapping; +import org.junit.Test; + /** * Test which checks if auditing when the revision number in the revision entity has a @Column annotation with * a columnDefinition specified works. + * * @author Adam Warski (adam at warski dot org) */ public class CustomColumnMapping extends BaseEnversJPAFunctionalTestCase { - private Integer id; - private long timestamp1; - private long timestamp2; - private long timestamp3; + private Integer id; + private long timestamp1; + private long timestamp2; + private long timestamp3; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class, CustomRevEntityColumnMapping.class }; - } + return new Class[] {StrTestEntity.class, CustomRevEntityColumnMapping.class}; + } - @Test - @Priority(10) - public void initData() throws InterruptedException { - timestamp1 = System.currentTimeMillis(); + @Test + @Priority(10) + public void initData() throws InterruptedException { + timestamp1 = System.currentTimeMillis(); - Thread.sleep(100); + Thread.sleep( 100 ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - StrTestEntity te = new StrTestEntity("x"); - em.persist(te); - id = te.getId(); - em.getTransaction().commit(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + StrTestEntity te = new StrTestEntity( "x" ); + em.persist( te ); + id = te.getId(); + em.getTransaction().commit(); - timestamp2 = System.currentTimeMillis(); + timestamp2 = System.currentTimeMillis(); - Thread.sleep(100); + Thread.sleep( 100 ); - // Revision 2 - em.getTransaction().begin(); - te = em.find(StrTestEntity.class, id); - te.setStr("y"); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + te = em.find( StrTestEntity.class, id ); + te.setStr( "y" ); + em.getTransaction().commit(); - timestamp3 = System.currentTimeMillis(); - } + timestamp3 = System.currentTimeMillis(); + } - @Test(expected = RevisionDoesNotExistException.class) - public void testTimestamps1() { - getAuditReader().getRevisionNumberForDate(new Date(timestamp1)); - } + @Test(expected = RevisionDoesNotExistException.class) + public void testTimestamps1() { + getAuditReader().getRevisionNumberForDate( new Date( timestamp1 ) ); + } - @Test - public void testTimestamps() { - assert getAuditReader().getRevisionNumberForDate(new Date(timestamp2)).intValue() == 1; - assert getAuditReader().getRevisionNumberForDate(new Date(timestamp3)).intValue() == 2; - } + @Test + public void testTimestamps() { + assert getAuditReader().getRevisionNumberForDate( new Date( timestamp2 ) ).intValue() == 1; + assert getAuditReader().getRevisionNumberForDate( new Date( timestamp3 ) ).intValue() == 2; + } - @Test - public void testDatesForRevisions() { - AuditReader vr = getAuditReader(); - assert vr.getRevisionNumberForDate(vr.getRevisionDate(1l)).intValue() == 1; - assert vr.getRevisionNumberForDate(vr.getRevisionDate(2l)).intValue() == 2; - } + @Test + public void testDatesForRevisions() { + AuditReader vr = getAuditReader(); + assert vr.getRevisionNumberForDate( vr.getRevisionDate( 1l ) ).intValue() == 1; + assert vr.getRevisionNumberForDate( vr.getRevisionDate( 2l ) ).intValue() == 2; + } - @Test - public void testRevisionsForDates() { - AuditReader vr = getAuditReader(); + @Test + public void testRevisionsForDates() { + AuditReader vr = getAuditReader(); - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp2))).getTime() <= timestamp2; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp2)).longValue()+1l).getTime() > timestamp2; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp2 ) ) ).getTime() <= timestamp2; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp2 ) ).longValue() + 1l ) + .getTime() > timestamp2; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp3))).getTime() <= timestamp3; - } + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp3 ) ) ).getTime() <= timestamp3; + } - @Test - public void testFindRevision() { - AuditReader vr = getAuditReader(); + @Test + public void testFindRevision() { + AuditReader vr = getAuditReader(); - long rev1Timestamp = vr.findRevision(CustomRevEntityColumnMapping.class, 1l).getCustomTimestamp(); - assert rev1Timestamp > timestamp1; - assert rev1Timestamp <= timestamp2; + long rev1Timestamp = vr.findRevision( CustomRevEntityColumnMapping.class, 1l ).getCustomTimestamp(); + assert rev1Timestamp > timestamp1; + assert rev1Timestamp <= timestamp2; - long rev2Timestamp = vr.findRevision(CustomRevEntityColumnMapping.class, 2l).getCustomTimestamp(); - assert rev2Timestamp > timestamp2; - assert rev2Timestamp <= timestamp3; - } + long rev2Timestamp = vr.findRevision( CustomRevEntityColumnMapping.class, 2l ).getCustomTimestamp(); + assert rev2Timestamp > timestamp2; + assert rev2Timestamp <= timestamp3; + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1l, 2l).equals(getAuditReader().getRevisions(StrTestEntity.class, id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1l, 2l ).equals( getAuditReader().getRevisions( StrTestEntity.class, id ) ); + } - @Test - public void testHistoryOfId1() { - StrTestEntity ver1 = new StrTestEntity("x", id); - StrTestEntity ver2 = new StrTestEntity("y", id); + @Test + public void testHistoryOfId1() { + StrTestEntity ver1 = new StrTestEntity( "x", id ); + StrTestEntity ver2 = new StrTestEntity( "y", id ); - assert getAuditReader().find(StrTestEntity.class, id, 1l).equals(ver1); - assert getAuditReader().find(StrTestEntity.class, id, 2l).equals(ver2); - } + assert getAuditReader().find( StrTestEntity.class, id, 1l ).equals( ver1 ); + assert getAuditReader().find( StrTestEntity.class, id, 2l ).equals( ver2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomDate.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomDate.java index 033daef984..ff56ea34e7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomDate.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomDate.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.reventity; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Date; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.AuditReader; import org.hibernate.envers.exception.RevisionDoesNotExistException; @@ -36,102 +34,105 @@ import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.reventity.CustomDateRevEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class CustomDate extends BaseEnversJPAFunctionalTestCase { - private Integer id; - private long timestamp1; - private long timestamp2; - private long timestamp3; + private Integer id; + private long timestamp1; + private long timestamp2; + private long timestamp3; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class, CustomDateRevEntity.class }; - } + return new Class[] {StrTestEntity.class, CustomDateRevEntity.class}; + } - @Test - @Priority(10) - public void initData() throws InterruptedException { - timestamp1 = System.currentTimeMillis(); + @Test + @Priority(10) + public void initData() throws InterruptedException { + timestamp1 = System.currentTimeMillis(); - Thread.sleep(1100); // CustomDateRevEntity.dateTimestamp field maps to date type which on some RDBMSs gets - // truncated to seconds (for example MySQL 5.1). + Thread.sleep( 1100 ); // CustomDateRevEntity.dateTimestamp field maps to date type which on some RDBMSs gets + // truncated to seconds (for example MySQL 5.1). - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - StrTestEntity te = new StrTestEntity("x"); - em.persist(te); - id = te.getId(); - em.getTransaction().commit(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + StrTestEntity te = new StrTestEntity( "x" ); + em.persist( te ); + id = te.getId(); + em.getTransaction().commit(); - timestamp2 = System.currentTimeMillis(); + timestamp2 = System.currentTimeMillis(); - Thread.sleep(1100); // CustomDateRevEntity.dateTimestamp field maps to date type which on some RDBMSs gets - // truncated to seconds (for example MySQL 5.1). + Thread.sleep( 1100 ); // CustomDateRevEntity.dateTimestamp field maps to date type which on some RDBMSs gets + // truncated to seconds (for example MySQL 5.1). - // Revision 2 - em.getTransaction().begin(); - te = em.find(StrTestEntity.class, id); - te.setStr("y"); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + te = em.find( StrTestEntity.class, id ); + te.setStr( "y" ); + em.getTransaction().commit(); - timestamp3 = System.currentTimeMillis(); - } + timestamp3 = System.currentTimeMillis(); + } - @Test(expected = RevisionDoesNotExistException.class) - public void testTimestamps1() { - getAuditReader().getRevisionNumberForDate(new Date(timestamp1)); - } + @Test(expected = RevisionDoesNotExistException.class) + public void testTimestamps1() { + getAuditReader().getRevisionNumberForDate( new Date( timestamp1 ) ); + } - @Test - public void testTimestamps() { - assert getAuditReader().getRevisionNumberForDate(new Date(timestamp2)).intValue() == 1; - assert getAuditReader().getRevisionNumberForDate(new Date(timestamp3)).intValue() == 2; - } + @Test + public void testTimestamps() { + assert getAuditReader().getRevisionNumberForDate( new Date( timestamp2 ) ).intValue() == 1; + assert getAuditReader().getRevisionNumberForDate( new Date( timestamp3 ) ).intValue() == 2; + } - @Test - public void testDatesForRevisions() { - AuditReader vr = getAuditReader(); - assert vr.getRevisionNumberForDate(vr.getRevisionDate(1)).intValue() == 1; - assert vr.getRevisionNumberForDate(vr.getRevisionDate(2)).intValue() == 2; - } + @Test + public void testDatesForRevisions() { + AuditReader vr = getAuditReader(); + assert vr.getRevisionNumberForDate( vr.getRevisionDate( 1 ) ).intValue() == 1; + assert vr.getRevisionNumberForDate( vr.getRevisionDate( 2 ) ).intValue() == 2; + } - @Test - public void testRevisionsForDates() { - AuditReader vr = getAuditReader(); + @Test + public void testRevisionsForDates() { + AuditReader vr = getAuditReader(); - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp2))).getTime() <= timestamp2; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp2)).intValue()+1).getTime() > timestamp2; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp2 ) ) ).getTime() <= timestamp2; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp2 ) ).intValue() + 1 ) + .getTime() > timestamp2; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp3))).getTime() <= timestamp3; - } + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp3 ) ) ).getTime() <= timestamp3; + } - @Test - public void testFindRevision() { - AuditReader vr = getAuditReader(); + @Test + public void testFindRevision() { + AuditReader vr = getAuditReader(); - long rev1Timestamp = vr.findRevision(CustomDateRevEntity.class, 1).getDateTimestamp().getTime(); - assert rev1Timestamp > timestamp1; - assert rev1Timestamp <= timestamp2; + long rev1Timestamp = vr.findRevision( CustomDateRevEntity.class, 1 ).getDateTimestamp().getTime(); + assert rev1Timestamp > timestamp1; + assert rev1Timestamp <= timestamp2; - long rev2Timestamp = vr.findRevision(CustomDateRevEntity.class, 2).getDateTimestamp().getTime(); - assert rev2Timestamp > timestamp2; - assert rev2Timestamp <= timestamp3; - } + long rev2Timestamp = vr.findRevision( CustomDateRevEntity.class, 2 ).getDateTimestamp().getTime(); + assert rev2Timestamp > timestamp2; + assert rev2Timestamp <= timestamp3; + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(StrTestEntity.class, id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( StrTestEntity.class, id ) ); + } - @Test - public void testHistoryOfId1() { - StrTestEntity ver1 = new StrTestEntity("x", id); - StrTestEntity ver2 = new StrTestEntity("y", id); + @Test + public void testHistoryOfId1() { + StrTestEntity ver1 = new StrTestEntity( "x", id ); + StrTestEntity ver2 = new StrTestEntity( "y", id ); - assert getAuditReader().find(StrTestEntity.class, id, 1).equals(ver1); - assert getAuditReader().find(StrTestEntity.class, id, 2).equals(ver2); - } + assert getAuditReader().find( StrTestEntity.class, id, 1 ).equals( ver1 ); + assert getAuditReader().find( StrTestEntity.class, id, 2 ).equals( ver2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomNoListener.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomNoListener.java index ab33abef01..4907bbaf65 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomNoListener.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomNoListener.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.reventity; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.AuditReader; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -34,102 +32,104 @@ import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.reventity.CustomDataRevEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class CustomNoListener extends BaseEnversJPAFunctionalTestCase { - private Integer id; + private Integer id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class, CustomDataRevEntity.class }; - } + return new Class[] {StrTestEntity.class, CustomDataRevEntity.class}; + } - @Test - @Priority(10) - public void initData() throws InterruptedException { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() throws InterruptedException { + EntityManager em = getEntityManager(); // Revision 1 - em.getTransaction().begin(); - StrTestEntity te = new StrTestEntity("x"); - em.persist(te); - id = te.getId(); + em.getTransaction().begin(); + StrTestEntity te = new StrTestEntity( "x" ); + em.persist( te ); + id = te.getId(); // Setting the data on the revision entity - CustomDataRevEntity custom = getAuditReader().getCurrentRevision(CustomDataRevEntity.class, false); - custom.setData("data1"); + CustomDataRevEntity custom = getAuditReader().getCurrentRevision( CustomDataRevEntity.class, false ); + custom.setData( "data1" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); - te = em.find(StrTestEntity.class, id); - te.setStr("y"); + // Revision 2 + em.getTransaction().begin(); + te = em.find( StrTestEntity.class, id ); + te.setStr( "y" ); // Setting the data on the revision entity - custom = getAuditReader().getCurrentRevision(CustomDataRevEntity.class, false); - custom.setData("data2"); + custom = getAuditReader().getCurrentRevision( CustomDataRevEntity.class, false ); + custom.setData( "data2" ); - em.getTransaction().commit(); + em.getTransaction().commit(); // Revision 3 - no changes, but rev entity should be persisted - em.getTransaction().begin(); + em.getTransaction().begin(); // Setting the data on the revision entity - custom = getAuditReader().getCurrentRevision(CustomDataRevEntity.class, true); - custom.setData("data3"); + custom = getAuditReader().getCurrentRevision( CustomDataRevEntity.class, true ); + custom.setData( "data3" ); - em.getTransaction().commit(); + em.getTransaction().commit(); // No changes, rev entity won't be persisted - em.getTransaction().begin(); + em.getTransaction().begin(); // Setting the data on the revision entity - custom = getAuditReader().getCurrentRevision(CustomDataRevEntity.class, false); - custom.setData("data4"); + custom = getAuditReader().getCurrentRevision( CustomDataRevEntity.class, false ); + custom.setData( "data4" ); - em.getTransaction().commit(); + em.getTransaction().commit(); // Revision 4 - em.getTransaction().begin(); - te = em.find(StrTestEntity.class, id); - te.setStr("z"); + em.getTransaction().begin(); + te = em.find( StrTestEntity.class, id ); + te.setStr( "z" ); // Setting the data on the revision entity - custom = getAuditReader().getCurrentRevision(CustomDataRevEntity.class, false); - custom.setData("data5"); + custom = getAuditReader().getCurrentRevision( CustomDataRevEntity.class, false ); + custom.setData( "data5" ); - custom = getAuditReader().getCurrentRevision(CustomDataRevEntity.class, false); - custom.setData("data5bis"); + custom = getAuditReader().getCurrentRevision( CustomDataRevEntity.class, false ); + custom.setData( "data5bis" ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testFindRevision() { - AuditReader vr = getAuditReader(); + @Test + public void testFindRevision() { + AuditReader vr = getAuditReader(); - assert "data1".equals(vr.findRevision(CustomDataRevEntity.class, 1).getData()); - assert "data2".equals(vr.findRevision(CustomDataRevEntity.class, 2).getData()); - assert "data3".equals(vr.findRevision(CustomDataRevEntity.class, 3).getData()); - assert "data5bis".equals(vr.findRevision(CustomDataRevEntity.class, 4).getData()); - } + assert "data1".equals( vr.findRevision( CustomDataRevEntity.class, 1 ).getData() ); + assert "data2".equals( vr.findRevision( CustomDataRevEntity.class, 2 ).getData() ); + assert "data3".equals( vr.findRevision( CustomDataRevEntity.class, 3 ).getData() ); + assert "data5bis".equals( vr.findRevision( CustomDataRevEntity.class, 4 ).getData() ); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 4).equals(getAuditReader().getRevisions(StrTestEntity.class, id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2, 4 ).equals( getAuditReader().getRevisions( StrTestEntity.class, id ) ); + } - @Test - public void testHistoryOfId1() { - StrTestEntity ver1 = new StrTestEntity("x", id); - StrTestEntity ver2 = new StrTestEntity("y", id); - StrTestEntity ver3 = new StrTestEntity("z", id); + @Test + public void testHistoryOfId1() { + StrTestEntity ver1 = new StrTestEntity( "x", id ); + StrTestEntity ver2 = new StrTestEntity( "y", id ); + StrTestEntity ver3 = new StrTestEntity( "z", id ); - assert getAuditReader().find(StrTestEntity.class, id, 1).equals(ver1); - assert getAuditReader().find(StrTestEntity.class, id, 2).equals(ver2); - assert getAuditReader().find(StrTestEntity.class, id, 3).equals(ver2); - assert getAuditReader().find(StrTestEntity.class, id, 4).equals(ver3); - } + assert getAuditReader().find( StrTestEntity.class, id, 1 ).equals( ver1 ); + assert getAuditReader().find( StrTestEntity.class, id, 2 ).equals( ver2 ); + assert getAuditReader().find( StrTestEntity.class, id, 3 ).equals( ver2 ); + assert getAuditReader().find( StrTestEntity.class, id, 4 ).equals( ver3 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomPropertyAccess.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomPropertyAccess.java index 84a6c4c1e3..8ca3ea1507 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomPropertyAccess.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/CustomPropertyAccess.java @@ -23,11 +23,9 @@ */ package org.hibernate.envers.test.integration.reventity; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Date; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.AuditReader; import org.hibernate.envers.exception.RevisionDoesNotExistException; @@ -36,99 +34,102 @@ import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.reventity.CustomPropertyAccessRevEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class CustomPropertyAccess extends BaseEnversJPAFunctionalTestCase { - private Integer id; - private long timestamp1; - private long timestamp2; - private long timestamp3; + private Integer id; + private long timestamp1; + private long timestamp2; + private long timestamp3; - protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class, CustomPropertyAccessRevEntity.class }; - } + protected Class[] getAnnotatedClasses() { + return new Class[] {StrTestEntity.class, CustomPropertyAccessRevEntity.class}; + } - @Test - @Priority(10) - public void initData() throws InterruptedException { - timestamp1 = System.currentTimeMillis(); + @Test + @Priority(10) + public void initData() throws InterruptedException { + timestamp1 = System.currentTimeMillis(); - Thread.sleep(100); + Thread.sleep( 100 ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - StrTestEntity te = new StrTestEntity("x"); - em.persist(te); - id = te.getId(); - em.getTransaction().commit(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + StrTestEntity te = new StrTestEntity( "x" ); + em.persist( te ); + id = te.getId(); + em.getTransaction().commit(); - timestamp2 = System.currentTimeMillis(); + timestamp2 = System.currentTimeMillis(); - Thread.sleep(100); + Thread.sleep( 100 ); - // Revision 2 - em.getTransaction().begin(); - te = em.find(StrTestEntity.class, id); - te.setStr("y"); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + te = em.find( StrTestEntity.class, id ); + te.setStr( "y" ); + em.getTransaction().commit(); - timestamp3 = System.currentTimeMillis(); - } + timestamp3 = System.currentTimeMillis(); + } - @Test(expected = RevisionDoesNotExistException.class) - public void testTimestamps1() { - getAuditReader().getRevisionNumberForDate(new Date(timestamp1)); - } + @Test(expected = RevisionDoesNotExistException.class) + public void testTimestamps1() { + getAuditReader().getRevisionNumberForDate( new Date( timestamp1 ) ); + } - @Test - public void testTimestamps() { - assert getAuditReader().getRevisionNumberForDate(new Date(timestamp2)).intValue() == 1; - assert getAuditReader().getRevisionNumberForDate(new Date(timestamp3)).intValue() == 2; - } + @Test + public void testTimestamps() { + assert getAuditReader().getRevisionNumberForDate( new Date( timestamp2 ) ).intValue() == 1; + assert getAuditReader().getRevisionNumberForDate( new Date( timestamp3 ) ).intValue() == 2; + } - @Test - public void testDatesForRevisions() { - AuditReader vr = getAuditReader(); - assert vr.getRevisionNumberForDate(vr.getRevisionDate(1)).intValue() == 1; - assert vr.getRevisionNumberForDate(vr.getRevisionDate(2)).intValue() == 2; - } + @Test + public void testDatesForRevisions() { + AuditReader vr = getAuditReader(); + assert vr.getRevisionNumberForDate( vr.getRevisionDate( 1 ) ).intValue() == 1; + assert vr.getRevisionNumberForDate( vr.getRevisionDate( 2 ) ).intValue() == 2; + } - @Test - public void testRevisionsForDates() { - AuditReader vr = getAuditReader(); + @Test + public void testRevisionsForDates() { + AuditReader vr = getAuditReader(); - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp2))).getTime() <= timestamp2; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp2)).intValue()+1).getTime() > timestamp2; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp2 ) ) ).getTime() <= timestamp2; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp2 ) ).intValue() + 1 ) + .getTime() > timestamp2; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp3))).getTime() <= timestamp3; - } + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp3 ) ) ).getTime() <= timestamp3; + } - @Test - public void testFindRevision() { - AuditReader vr = getAuditReader(); + @Test + public void testFindRevision() { + AuditReader vr = getAuditReader(); - long rev1Timestamp = vr.findRevision(CustomPropertyAccessRevEntity.class, 1).getCustomTimestamp(); - assert rev1Timestamp > timestamp1; - assert rev1Timestamp <= timestamp2; + long rev1Timestamp = vr.findRevision( CustomPropertyAccessRevEntity.class, 1 ).getCustomTimestamp(); + assert rev1Timestamp > timestamp1; + assert rev1Timestamp <= timestamp2; - long rev2Timestamp = vr.findRevision(CustomPropertyAccessRevEntity.class, 2).getCustomTimestamp(); - assert rev2Timestamp > timestamp2; - assert rev2Timestamp <= timestamp3; - } + long rev2Timestamp = vr.findRevision( CustomPropertyAccessRevEntity.class, 2 ).getCustomTimestamp(); + assert rev2Timestamp > timestamp2; + assert rev2Timestamp <= timestamp3; + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(StrTestEntity.class, id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( StrTestEntity.class, id ) ); + } - @Test - public void testHistoryOfId1() { - StrTestEntity ver1 = new StrTestEntity("x", id); - StrTestEntity ver2 = new StrTestEntity("y", id); + @Test + public void testHistoryOfId1() { + StrTestEntity ver1 = new StrTestEntity( "x", id ); + StrTestEntity ver2 = new StrTestEntity( "y", id ); - assert getAuditReader().find(StrTestEntity.class, id, 1).equals(ver1); - assert getAuditReader().find(StrTestEntity.class, id, 2).equals(ver2); - } + assert getAuditReader().find( StrTestEntity.class, id, 1 ).equals( ver1 ); + assert getAuditReader().find( StrTestEntity.class, id, 2 ).equals( ver2 ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/DifferentDBSchemaTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/DifferentDBSchemaTest.java index 4fb540ad74..96b90a80d1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/DifferentDBSchemaTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/DifferentDBSchemaTest.java @@ -1,10 +1,8 @@ package org.hibernate.envers.test.integration.reventity; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Map; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.cfg.Environment; import org.hibernate.dialect.H2Dialect; @@ -13,71 +11,76 @@ import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.mapping.Table; + +import org.junit.Test; + import org.hibernate.testing.RequiresDialect; /** * Tests simple auditing process (read and write operations) when REVINFO and audit tables * exist in a different database schema. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @RequiresDialect({H2Dialect.class}) public class DifferentDBSchemaTest extends BaseEnversJPAFunctionalTestCase { - private static final String SCHEMA_NAME = "ENVERS_AUDIT"; - private Integer steId = null; + private static final String SCHEMA_NAME = "ENVERS_AUDIT"; + private Integer steId = null; - @Override - protected void addConfigOptions(Map options) { - super.addConfigOptions(options); - // Creates new schema after establishing connection - options.putAll(Environment.getProperties()); - options.put(EnversSettings.DEFAULT_SCHEMA, SCHEMA_NAME); - } + @Override + protected void addConfigOptions(Map options) { + super.addConfigOptions( options ); + // Creates new schema after establishing connection + options.putAll( Environment.getProperties() ); + options.put( EnversSettings.DEFAULT_SCHEMA, SCHEMA_NAME ); + } - @Override - protected String createSecondSchema() { - return SCHEMA_NAME; - } + @Override + protected String createSecondSchema() { + return SCHEMA_NAME; + } @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class }; - } + return new Class[] {StrTestEntity.class}; + } - @Test - @Priority(10) - public void initData() throws InterruptedException { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - StrTestEntity ste = new StrTestEntity("x"); - em.persist(ste); - steId = ste.getId(); - em.getTransaction().commit(); + @Test + @Priority(10) + public void initData() throws InterruptedException { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + StrTestEntity ste = new StrTestEntity( "x" ); + em.persist( ste ); + steId = ste.getId(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); - ste = em.find(StrTestEntity.class, steId); - ste.setStr("y"); - em.getTransaction().commit(); - } + // Revision 2 + em.getTransaction().begin(); + ste = em.find( StrTestEntity.class, steId ); + ste.setStr( "y" ); + em.getTransaction().commit(); + } - @Test - public void testRevinfoSchemaName() { - Table revisionTable = getCfg().getClassMapping("org.hibernate.envers.enhanced.SequenceIdRevisionEntity").getTable(); - assert SCHEMA_NAME.equals(revisionTable.getSchema()); - } + @Test + public void testRevinfoSchemaName() { + Table revisionTable = getCfg().getClassMapping( "org.hibernate.envers.enhanced.SequenceIdRevisionEntity" ) + .getTable(); + assert SCHEMA_NAME.equals( revisionTable.getSchema() ); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(StrTestEntity.class, steId)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( StrTestEntity.class, steId ) ); + } - @Test - public void testHistoryOfId1() { - StrTestEntity ver1 = new StrTestEntity("x", steId); - StrTestEntity ver2 = new StrTestEntity("y", steId); + @Test + public void testHistoryOfId1() { + StrTestEntity ver1 = new StrTestEntity( "x", steId ); + StrTestEntity ver2 = new StrTestEntity( "y", steId ); - assert getAuditReader().find(StrTestEntity.class, steId, 1).equals(ver1); - assert getAuditReader().find(StrTestEntity.class, steId, 2).equals(ver2); - } + assert getAuditReader().find( StrTestEntity.class, steId, 1 ).equals( ver1 ); + assert getAuditReader().find( StrTestEntity.class, steId, 2 ).equals( ver2 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/ExceptionListener.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/ExceptionListener.java index d890550b9c..aaaadb92ae 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/ExceptionListener.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/ExceptionListener.java @@ -25,38 +25,39 @@ package org.hibernate.envers.test.integration.reventity; import javax.persistence.EntityManager; -import org.junit.Test; - import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.entities.StrTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class ExceptionListener extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class, ExceptionListenerRevEntity.class }; - } + return new Class[] {StrTestEntity.class, ExceptionListenerRevEntity.class}; + } - @Test(expected = RuntimeException.class) - public void testTransactionRollback() throws InterruptedException { - // Trying to persist an entity - however the listener should throw an exception, so the entity + @Test(expected = RuntimeException.class) + public void testTransactionRollback() throws InterruptedException { + // Trying to persist an entity - however the listener should throw an exception, so the entity // shouldn't be persisted - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - StrTestEntity te = new StrTestEntity("x"); - em.persist(te); - em.getTransaction().commit(); - } + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + StrTestEntity te = new StrTestEntity( "x" ); + em.persist( te ); + em.getTransaction().commit(); + } - @Test - public void testDataNotPersisted() { + @Test + public void testDataNotPersisted() { // Checking if the entity became persisted EntityManager em = getEntityManager(); - em.getTransaction().begin(); - Long count = (Long) em.createQuery("select count(s) from StrTestEntity s where s.str = 'x'").getSingleResult(); + em.getTransaction().begin(); + Long count = (Long) em.createQuery( "select count(s) from StrTestEntity s where s.str = 'x'" ) + .getSingleResult(); assert count == 0l; - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/ExceptionListenerRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/ExceptionListenerRevEntity.java index aaef924ed1..887f88f76c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/ExceptionListenerRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/ExceptionListenerRevEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.reventity; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -37,55 +38,64 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = {@Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity(TestExceptionRevisionListener.class) public class ExceptionListenerRevEntity { - @Id - @GeneratedValue(generator = "EnversTestingRevisionGenerator") - @RevisionNumber - private int id; + @Id + @GeneratedValue(generator = "EnversTestingRevisionGenerator") + @RevisionNumber + private int id; - @RevisionTimestamp - private long timestamp; + @RevisionTimestamp + private long timestamp; - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public long getTimestamp() { - return timestamp; - } + public long getTimestamp() { + return timestamp; + } - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ExceptionListenerRevEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ExceptionListenerRevEntity) ) { + return false; + } - ExceptionListenerRevEntity revEntity = (ExceptionListenerRevEntity) o; + ExceptionListenerRevEntity revEntity = (ExceptionListenerRevEntity) o; - if (id != revEntity.id) return false; - if (timestamp != revEntity.timestamp) return false; + if ( id != revEntity.id ) { + return false; + } + if ( timestamp != revEntity.timestamp ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = id; - result = 31 * result + (int) (timestamp ^ (timestamp >>> 32)); - return result; - } + public int hashCode() { + int result; + result = id; + result = 31 * result + (int) (timestamp ^ (timestamp >>> 32)); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/GloballyConfiguredRevListenerTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/GloballyConfiguredRevListenerTest.java index 00acda9ede..817d7ffcd6 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/GloballyConfiguredRevListenerTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/GloballyConfiguredRevListenerTest.java @@ -1,15 +1,16 @@ package org.hibernate.envers.test.integration.reventity; -import java.util.Map; import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; +import java.util.Map; import org.hibernate.envers.configuration.EnversSettings; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -19,28 +20,28 @@ import org.hibernate.testing.TestForIssue; public class GloballyConfiguredRevListenerTest extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class }; - } + return new Class[] {StrTestEntity.class}; + } @Override protected void addConfigOptions(Map options) { super.addConfigOptions( options ); - options.put(EnversSettings.REVISION_LISTENER, CountingRevisionListener.class.getName()); + options.put( EnversSettings.REVISION_LISTENER, CountingRevisionListener.class.getName() ); } @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - CountingRevisionListener.revisionCount = 0; + CountingRevisionListener.revisionCount = 0; - // Revision 1 - em.getTransaction().begin(); - StrTestEntity te = new StrTestEntity("data"); - em.persist(te); - em.getTransaction().commit(); + // Revision 1 + em.getTransaction().begin(); + StrTestEntity te = new StrTestEntity( "data" ); + em.persist( te ); + em.getTransaction().commit(); - Assert.assertEquals(1, CountingRevisionListener.revisionCount); - } + Assert.assertEquals( 1, CountingRevisionListener.revisionCount ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/Inherited.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/Inherited.java index 038219d650..8bf05f5d3b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/Inherited.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/Inherited.java @@ -23,14 +23,12 @@ */ package org.hibernate.envers.test.integration.reventity; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.Map; import java.util.Set; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.AuditReader; import org.hibernate.envers.exception.RevisionDoesNotExistException; @@ -38,113 +36,116 @@ import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class Inherited extends BaseEnversJPAFunctionalTestCase { - private Integer id; - private long timestamp1; - private long timestamp2; - private long timestamp3; + private Integer id; + private long timestamp1; + private long timestamp2; + private long timestamp3; - protected Class[] getAnnotatedClasses() { - return new Class[]{StrTestEntity.class, InheritedRevEntity.class}; - } + protected Class[] getAnnotatedClasses() { + return new Class[] {StrTestEntity.class, InheritedRevEntity.class}; + } - @Test - @Priority(10) - public void initData() throws InterruptedException { - timestamp1 = System.currentTimeMillis(); + @Test + @Priority(10) + public void initData() throws InterruptedException { + timestamp1 = System.currentTimeMillis(); - Thread.sleep(100); + Thread.sleep( 100 ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - StrTestEntity te = new StrTestEntity("x"); - em.persist(te); - id = te.getId(); - em.getTransaction().commit(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + StrTestEntity te = new StrTestEntity( "x" ); + em.persist( te ); + id = te.getId(); + em.getTransaction().commit(); - timestamp2 = System.currentTimeMillis(); + timestamp2 = System.currentTimeMillis(); - Thread.sleep(100); + Thread.sleep( 100 ); - // Revision 2 - em.getTransaction().begin(); - te = em.find(StrTestEntity.class, id); - te.setStr("y"); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + te = em.find( StrTestEntity.class, id ); + te.setStr( "y" ); + em.getTransaction().commit(); - timestamp3 = System.currentTimeMillis(); - } + timestamp3 = System.currentTimeMillis(); + } - @Test(expected = RevisionDoesNotExistException.class) - public void testTimestamps1() { - getAuditReader().getRevisionNumberForDate(new Date(timestamp1)); - } + @Test(expected = RevisionDoesNotExistException.class) + public void testTimestamps1() { + getAuditReader().getRevisionNumberForDate( new Date( timestamp1 ) ); + } - @Test - public void testTimestamps() { - assert getAuditReader().getRevisionNumberForDate(new Date(timestamp2)).intValue() == 1; - assert getAuditReader().getRevisionNumberForDate(new Date(timestamp3)).intValue() == 2; - } + @Test + public void testTimestamps() { + assert getAuditReader().getRevisionNumberForDate( new Date( timestamp2 ) ).intValue() == 1; + assert getAuditReader().getRevisionNumberForDate( new Date( timestamp3 ) ).intValue() == 2; + } - @Test - public void testDatesForRevisions() { - AuditReader vr = getAuditReader(); - assert vr.getRevisionNumberForDate(vr.getRevisionDate(1)).intValue() == 1; - assert vr.getRevisionNumberForDate(vr.getRevisionDate(2)).intValue() == 2; - } + @Test + public void testDatesForRevisions() { + AuditReader vr = getAuditReader(); + assert vr.getRevisionNumberForDate( vr.getRevisionDate( 1 ) ).intValue() == 1; + assert vr.getRevisionNumberForDate( vr.getRevisionDate( 2 ) ).intValue() == 2; + } - @Test - public void testRevisionsForDates() { - AuditReader vr = getAuditReader(); + @Test + public void testRevisionsForDates() { + AuditReader vr = getAuditReader(); - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp2))).getTime() <= timestamp2; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp2)).intValue()+1).getTime() > timestamp2; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp2 ) ) ).getTime() <= timestamp2; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp2 ) ).intValue() + 1 ) + .getTime() > timestamp2; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp3))).getTime() <= timestamp3; - } + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp3 ) ) ).getTime() <= timestamp3; + } - @Test - public void testFindRevision() { - AuditReader vr = getAuditReader(); + @Test + public void testFindRevision() { + AuditReader vr = getAuditReader(); - long rev1Timestamp = vr.findRevision(InheritedRevEntity.class, 1).getTimestamp(); - assert rev1Timestamp > timestamp1; - assert rev1Timestamp <= timestamp2; + long rev1Timestamp = vr.findRevision( InheritedRevEntity.class, 1 ).getTimestamp(); + assert rev1Timestamp > timestamp1; + assert rev1Timestamp <= timestamp2; - long rev2Timestamp = vr.findRevision(InheritedRevEntity.class, 2).getTimestamp(); - assert rev2Timestamp > timestamp2; - assert rev2Timestamp <= timestamp3; - } + long rev2Timestamp = vr.findRevision( InheritedRevEntity.class, 2 ).getTimestamp(); + assert rev2Timestamp > timestamp2; + assert rev2Timestamp <= timestamp3; + } - @Test - public void testFindRevisions() { - AuditReader vr = getAuditReader(); + @Test + public void testFindRevisions() { + AuditReader vr = getAuditReader(); - Set revNumbers = new HashSet(); - revNumbers.add(1); - revNumbers.add(2); + Set revNumbers = new HashSet(); + revNumbers.add( 1 ); + revNumbers.add( 2 ); - Map revisionMap = vr.findRevisions(InheritedRevEntity.class, revNumbers); - assert(revisionMap.size() == 2); - assert(revisionMap.get(1).equals(vr.findRevision(InheritedRevEntity.class, 1))); - assert(revisionMap.get(2).equals(vr.findRevision(InheritedRevEntity.class, 2))); - } + Map revisionMap = vr.findRevisions( InheritedRevEntity.class, revNumbers ); + assert (revisionMap.size() == 2); + assert (revisionMap.get( 1 ).equals( vr.findRevision( InheritedRevEntity.class, 1 ) )); + assert (revisionMap.get( 2 ).equals( vr.findRevision( InheritedRevEntity.class, 2 ) )); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(StrTestEntity.class, id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( StrTestEntity.class, id ) ); + } - @Test - public void testHistoryOfId1() { - StrTestEntity ver1 = new StrTestEntity("x", id); - StrTestEntity ver2 = new StrTestEntity("y", id); + @Test + public void testHistoryOfId1() { + StrTestEntity ver1 = new StrTestEntity( "x", id ); + StrTestEntity ver2 = new StrTestEntity( "y", id ); - assert getAuditReader().find(StrTestEntity.class, id, 1).equals(ver1); - assert getAuditReader().find(StrTestEntity.class, id, 2).equals(ver2); - } + assert getAuditReader().find( StrTestEntity.class, id, 1 ).equals( ver1 ); + assert getAuditReader().find( StrTestEntity.class, id, 2 ).equals( ver2 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/Listener.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/Listener.java index daf5cd8881..02d81d9d84 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/Listener.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/Listener.java @@ -23,14 +23,12 @@ */ package org.hibernate.envers.test.integration.reventity; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.Map; import java.util.Set; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.AuditReader; import org.hibernate.envers.exception.RevisionDoesNotExistException; @@ -38,127 +36,130 @@ import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class Listener extends BaseEnversJPAFunctionalTestCase { - private Integer id; - private long timestamp1; - private long timestamp2; - private long timestamp3; + private Integer id; + private long timestamp1; + private long timestamp2; + private long timestamp3; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class, ListenerRevEntity.class }; - } + return new Class[] {StrTestEntity.class, ListenerRevEntity.class}; + } - @Test - @Priority(10) - public void initData() throws InterruptedException { - timestamp1 = System.currentTimeMillis(); + @Test + @Priority(10) + public void initData() throws InterruptedException { + timestamp1 = System.currentTimeMillis(); - Thread.sleep(100); + Thread.sleep( 100 ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - TestRevisionListener.data = "data1"; + TestRevisionListener.data = "data1"; - StrTestEntity te = new StrTestEntity("x"); - em.persist(te); - id = te.getId(); - em.getTransaction().commit(); + StrTestEntity te = new StrTestEntity( "x" ); + em.persist( te ); + id = te.getId(); + em.getTransaction().commit(); - timestamp2 = System.currentTimeMillis(); + timestamp2 = System.currentTimeMillis(); - Thread.sleep(100); + Thread.sleep( 100 ); - // Revision 2 - em.getTransaction().begin(); - te = em.find(StrTestEntity.class, id); + // Revision 2 + em.getTransaction().begin(); + te = em.find( StrTestEntity.class, id ); - TestRevisionListener.data = "data2"; + TestRevisionListener.data = "data2"; - te.setStr("y"); - em.getTransaction().commit(); + te.setStr( "y" ); + em.getTransaction().commit(); - timestamp3 = System.currentTimeMillis(); - } + timestamp3 = System.currentTimeMillis(); + } - @Test(expected = RevisionDoesNotExistException.class) - public void testTimestamps1() { - getAuditReader().getRevisionNumberForDate(new Date(timestamp1)); - } + @Test(expected = RevisionDoesNotExistException.class) + public void testTimestamps1() { + getAuditReader().getRevisionNumberForDate( new Date( timestamp1 ) ); + } - @Test - public void testTimestamps() { - assert getAuditReader().getRevisionNumberForDate(new Date(timestamp2)).intValue() == 1; - assert getAuditReader().getRevisionNumberForDate(new Date(timestamp3)).intValue() == 2; - } + @Test + public void testTimestamps() { + assert getAuditReader().getRevisionNumberForDate( new Date( timestamp2 ) ).intValue() == 1; + assert getAuditReader().getRevisionNumberForDate( new Date( timestamp3 ) ).intValue() == 2; + } - @Test - public void testDatesForRevisions() { - AuditReader vr = getAuditReader(); - assert vr.getRevisionNumberForDate(vr.getRevisionDate(1)).intValue() == 1; - assert vr.getRevisionNumberForDate(vr.getRevisionDate(2)).intValue() == 2; - } + @Test + public void testDatesForRevisions() { + AuditReader vr = getAuditReader(); + assert vr.getRevisionNumberForDate( vr.getRevisionDate( 1 ) ).intValue() == 1; + assert vr.getRevisionNumberForDate( vr.getRevisionDate( 2 ) ).intValue() == 2; + } - @Test - public void testRevisionsForDates() { - AuditReader vr = getAuditReader(); + @Test + public void testRevisionsForDates() { + AuditReader vr = getAuditReader(); - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp2))).getTime() <= timestamp2; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp2)).intValue()+1).getTime() > timestamp2; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp2 ) ) ).getTime() <= timestamp2; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp2 ) ).intValue() + 1 ) + .getTime() > timestamp2; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp3))).getTime() <= timestamp3; - } + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp3 ) ) ).getTime() <= timestamp3; + } - @Test - public void testFindRevision() { - AuditReader vr = getAuditReader(); + @Test + public void testFindRevision() { + AuditReader vr = getAuditReader(); - ListenerRevEntity rev1Data = vr.findRevision(ListenerRevEntity.class, 1); - ListenerRevEntity rev2Data = vr.findRevision(ListenerRevEntity.class, 2); + ListenerRevEntity rev1Data = vr.findRevision( ListenerRevEntity.class, 1 ); + ListenerRevEntity rev2Data = vr.findRevision( ListenerRevEntity.class, 2 ); - long rev1Timestamp = rev1Data.getTimestamp(); - assert rev1Timestamp > timestamp1; - assert rev1Timestamp <= timestamp2; + long rev1Timestamp = rev1Data.getTimestamp(); + assert rev1Timestamp > timestamp1; + assert rev1Timestamp <= timestamp2; - assert "data1".equals(rev1Data.getData()); + assert "data1".equals( rev1Data.getData() ); - long rev2Timestamp = rev2Data.getTimestamp(); - assert rev2Timestamp > timestamp2; - assert rev2Timestamp <= timestamp3; + long rev2Timestamp = rev2Data.getTimestamp(); + assert rev2Timestamp > timestamp2; + assert rev2Timestamp <= timestamp3; - assert "data2".equals(rev2Data.getData()); - } + assert "data2".equals( rev2Data.getData() ); + } - @Test - public void testFindRevisions() { - AuditReader vr = getAuditReader(); + @Test + public void testFindRevisions() { + AuditReader vr = getAuditReader(); - Set revNumbers = new HashSet(); - revNumbers.add(1); - revNumbers.add(2); - - Map revisionMap = vr.findRevisions(ListenerRevEntity.class, revNumbers); - assert(revisionMap.size() == 2); - assert(revisionMap.get(1).equals(vr.findRevision(ListenerRevEntity.class, 1))); - assert(revisionMap.get(2).equals(vr.findRevision(ListenerRevEntity.class, 2))); - } + Set revNumbers = new HashSet(); + revNumbers.add( 1 ); + revNumbers.add( 2 ); - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(StrTestEntity.class, id)); - } + Map revisionMap = vr.findRevisions( ListenerRevEntity.class, revNumbers ); + assert (revisionMap.size() == 2); + assert (revisionMap.get( 1 ).equals( vr.findRevision( ListenerRevEntity.class, 1 ) )); + assert (revisionMap.get( 2 ).equals( vr.findRevision( ListenerRevEntity.class, 2 ) )); + } - @Test - public void testHistoryOfId1() { - StrTestEntity ver1 = new StrTestEntity("x", id); - StrTestEntity ver2 = new StrTestEntity("y", id); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( StrTestEntity.class, id ) ); + } - assert getAuditReader().find(StrTestEntity.class, id, 1).equals(ver1); - assert getAuditReader().find(StrTestEntity.class, id, 2).equals(ver2); - } + @Test + public void testHistoryOfId1() { + StrTestEntity ver1 = new StrTestEntity( "x", id ); + StrTestEntity ver2 = new StrTestEntity( "y", id ); + + assert getAuditReader().find( StrTestEntity.class, id, 1 ).equals( ver1 ); + assert getAuditReader().find( StrTestEntity.class, id, 2 ).equals( ver2 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/ListenerRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/ListenerRevEntity.java index 8f5111a117..040c32403a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/ListenerRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/ListenerRevEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.reventity; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -37,65 +38,74 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = {@Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity(TestRevisionListener.class) public class ListenerRevEntity { - @Id - @GeneratedValue(generator = "EnversTestingRevisionGenerator") - @RevisionNumber - private int id; + @Id + @GeneratedValue(generator = "EnversTestingRevisionGenerator") + @RevisionNumber + private int id; - @RevisionTimestamp - private long timestamp; + @RevisionTimestamp + private long timestamp; - private String data; + private String data; - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public long getTimestamp() { - return timestamp; - } + public long getTimestamp() { + return timestamp; + } - public void setTimestamp(long timestamp) { - this.timestamp = timestamp; - } + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ListenerRevEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ListenerRevEntity) ) { + return false; + } - ListenerRevEntity revEntity = (ListenerRevEntity) o; + ListenerRevEntity revEntity = (ListenerRevEntity) o; - if (id != revEntity.id) return false; - if (timestamp != revEntity.timestamp) return false; + if ( id != revEntity.id ) { + return false; + } + if ( timestamp != revEntity.timestamp ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = id; - result = 31 * result + (int) (timestamp ^ (timestamp >>> 32)); - return result; - } + public int hashCode() { + int result; + result = id; + result = 31 * result + (int) (timestamp ^ (timestamp >>> 32)); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/LongRevEntityInheritanceChildAuditing.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/LongRevEntityInheritanceChildAuditing.java index 1d6e090c11..c73030cd11 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/LongRevEntityInheritanceChildAuditing.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/LongRevEntityInheritanceChildAuditing.java @@ -26,36 +26,37 @@ package org.hibernate.envers.test.integration.reventity; import java.util.Iterator; -import org.junit.Test; - import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.integration.inheritance.joined.ChildEntity; import org.hibernate.envers.test.integration.inheritance.joined.ParentEntity; import org.hibernate.mapping.Column; +import org.junit.Test; + import static org.junit.Assert.assertEquals; /** * A join-inheritance test using a custom revision entity where the revision number is a long, mapped in the database * as an int. + * * @author Adam Warski (adam at warski dot org) */ public class LongRevEntityInheritanceChildAuditing extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ChildEntity.class, ParentEntity.class, LongRevNumberRevEntity.class }; - } + return new Class[] {ChildEntity.class, ParentEntity.class, LongRevNumberRevEntity.class}; + } - @Test - public void testChildRevColumnType() { - // We need the second column - Iterator childEntityKeyColumnsIterator = getCfg() - .getClassMapping("org.hibernate.envers.test.integration.inheritance.joined.ChildEntity_AUD") - .getKey() - .getColumnIterator(); - childEntityKeyColumnsIterator.next(); - Column second = (Column) childEntityKeyColumnsIterator.next(); + @Test + public void testChildRevColumnType() { + // We need the second column + Iterator childEntityKeyColumnsIterator = getCfg() + .getClassMapping( "org.hibernate.envers.test.integration.inheritance.joined.ChildEntity_AUD" ) + .getKey() + .getColumnIterator(); + childEntityKeyColumnsIterator.next(); + Column second = (Column) childEntityKeyColumnsIterator.next(); - assertEquals(second.getSqlType(), "int"); - } + assertEquals( second.getSqlType(), "int" ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/LongRevNumber.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/LongRevNumber.java index d450830366..a10bf14e51 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/LongRevNumber.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/LongRevNumber.java @@ -23,81 +23,81 @@ */ package org.hibernate.envers.test.integration.reventity; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Set; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.AuditReader; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class LongRevNumber extends BaseEnversJPAFunctionalTestCase { - private Integer id; + private Integer id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class, LongRevNumberRevEntity.class }; - } + return new Class[] {StrTestEntity.class, LongRevNumberRevEntity.class}; + } - @Test - @Priority(10) - public void initData() throws InterruptedException { - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - StrTestEntity te = new StrTestEntity("x"); - em.persist(te); - id = te.getId(); - em.getTransaction().commit(); + @Test + @Priority(10) + public void initData() throws InterruptedException { + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + StrTestEntity te = new StrTestEntity( "x" ); + em.persist( te ); + id = te.getId(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); - te = em.find(StrTestEntity.class, id); - te.setStr("y"); - em.getTransaction().commit(); - } + // Revision 2 + em.getTransaction().begin(); + te = em.find( StrTestEntity.class, id ); + te.setStr( "y" ); + em.getTransaction().commit(); + } - @Test - public void testFindRevision() { - AuditReader vr = getAuditReader(); + @Test + public void testFindRevision() { + AuditReader vr = getAuditReader(); - assert vr.findRevision(LongRevNumberRevEntity.class, 1l).getCustomId() == 1l; - assert vr.findRevision(LongRevNumberRevEntity.class, 2l).getCustomId() == 2l; - } + assert vr.findRevision( LongRevNumberRevEntity.class, 1l ).getCustomId() == 1l; + assert vr.findRevision( LongRevNumberRevEntity.class, 2l ).getCustomId() == 2l; + } - @Test - public void testFindRevisions() { - AuditReader vr = getAuditReader(); + @Test + public void testFindRevisions() { + AuditReader vr = getAuditReader(); - Set revNumbers = new HashSet(); - revNumbers.add(1l); - revNumbers.add(2l); - - Map revisionMap = vr.findRevisions(LongRevNumberRevEntity.class, revNumbers); - assert(revisionMap.size() == 2); - assert(revisionMap.get(1l).equals(vr.findRevision(LongRevNumberRevEntity.class, 1l))); - assert(revisionMap.get(2l).equals(vr.findRevision(LongRevNumberRevEntity.class, 2l))); - } + Set revNumbers = new HashSet(); + revNumbers.add( 1l ); + revNumbers.add( 2l ); - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1l, 2l).equals(getAuditReader().getRevisions(StrTestEntity.class, id)); - } + Map revisionMap = vr.findRevisions( LongRevNumberRevEntity.class, revNumbers ); + assert (revisionMap.size() == 2); + assert (revisionMap.get( 1l ).equals( vr.findRevision( LongRevNumberRevEntity.class, 1l ) )); + assert (revisionMap.get( 2l ).equals( vr.findRevision( LongRevNumberRevEntity.class, 2l ) )); + } - @Test - public void testHistoryOfId1() { - StrTestEntity ver1 = new StrTestEntity("x", id); - StrTestEntity ver2 = new StrTestEntity("y", id); + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1l, 2l ).equals( getAuditReader().getRevisions( StrTestEntity.class, id ) ); + } - assert getAuditReader().find(StrTestEntity.class, id, 1l).equals(ver1); - assert getAuditReader().find(StrTestEntity.class, id, 2l).equals(ver2); - } + @Test + public void testHistoryOfId1() { + StrTestEntity ver1 = new StrTestEntity( "x", id ); + StrTestEntity ver2 = new StrTestEntity( "y", id ); + + assert getAuditReader().find( StrTestEntity.class, id, 1l ).equals( ver1 ); + assert getAuditReader().find( StrTestEntity.class, id, 2l ).equals( ver2 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/LongRevNumberRevEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/LongRevNumberRevEntity.java index 997617cde9..f5bf854b1a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/LongRevNumberRevEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/LongRevNumberRevEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.reventity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -38,56 +39,65 @@ import org.hibernate.envers.RevisionTimestamp; */ @Entity @GenericGenerator(name = "EnversTestingRevisionGenerator", - strategy = "org.hibernate.id.enhanced.TableGenerator", - parameters = {@Parameter(name = "table_name", value = "REVISION_GENERATOR"), - @Parameter(name = "initial_value", value = "1"), - @Parameter(name = "increment_size", value = "1"), - @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") - } + strategy = "org.hibernate.id.enhanced.TableGenerator", + parameters = { + @Parameter(name = "table_name", value = "REVISION_GENERATOR"), + @Parameter(name = "initial_value", value = "1"), + @Parameter(name = "increment_size", value = "1"), + @Parameter(name = "prefer_entity_table_as_segment_value", value = "true") + } ) @RevisionEntity public class LongRevNumberRevEntity { - @Id - @GeneratedValue(generator = "EnversTestingRevisionGenerator") - @RevisionNumber - @Column(columnDefinition = "int") - private long customId; + @Id + @GeneratedValue(generator = "EnversTestingRevisionGenerator") + @RevisionNumber + @Column(columnDefinition = "int") + private long customId; - @RevisionTimestamp - private long customTimestamp; + @RevisionTimestamp + private long customTimestamp; - public long getCustomId() { - return customId; - } + public long getCustomId() { + return customId; + } - public void setCustomId(long customId) { - this.customId = customId; - } + public void setCustomId(long customId) { + this.customId = customId; + } - public long getCustomTimestamp() { - return customTimestamp; - } + public long getCustomTimestamp() { + return customTimestamp; + } - public void setCustomTimestamp(long customTimestamp) { - this.customTimestamp = customTimestamp; - } + public void setCustomTimestamp(long customTimestamp) { + this.customTimestamp = customTimestamp; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof LongRevNumberRevEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof LongRevNumberRevEntity) ) { + return false; + } - LongRevNumberRevEntity that = (LongRevNumberRevEntity) o; + LongRevNumberRevEntity that = (LongRevNumberRevEntity) o; - if (customId != that.customId) return false; - if (customTimestamp != that.customTimestamp) return false; + if ( customId != that.customId ) { + return false; + } + if ( customTimestamp != that.customTimestamp ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (int) (customId ^ (customId >>> 32)); - result = 31 * result + (int) (customTimestamp ^ (customTimestamp >>> 32)); - return result; - } + public int hashCode() { + int result; + result = (int) (customId ^ (customId >>> 32)); + result = 31 * result + (int) (customTimestamp ^ (customTimestamp >>> 32)); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/MonotonicRevisionNumberTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/MonotonicRevisionNumberTest.java index e42dbd66d0..1f33a17b19 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/MonotonicRevisionNumberTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/MonotonicRevisionNumberTest.java @@ -1,8 +1,5 @@ package org.hibernate.envers.test.integration.reventity; -import org.junit.Assert; -import org.junit.Test; - import org.hibernate.dialect.Oracle8iDialect; import org.hibernate.envers.enhanced.OrderedSequenceGenerator; import org.hibernate.envers.enhanced.SequenceIdRevisionEntity; @@ -10,6 +7,10 @@ import org.hibernate.envers.test.BaseEnversFunctionalTestCase; import org.hibernate.envers.test.entities.StrIntTestEntity; import org.hibernate.id.IdentifierGenerator; import org.hibernate.persister.entity.EntityPersister; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.TestForIssue; @@ -21,7 +22,7 @@ import org.hibernate.testing.TestForIssue; public class MonotonicRevisionNumberTest extends BaseEnversFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[]{ StrIntTestEntity.class }; // Otherwise revision entity is not generated. + return new Class[] {StrIntTestEntity.class}; // Otherwise revision entity is not generated. } @Test diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/OverrideCustomRevListenerTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/OverrideCustomRevListenerTest.java index ccaf0f5aea..96e840bca7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/OverrideCustomRevListenerTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/OverrideCustomRevListenerTest.java @@ -1,6 +1,7 @@ package org.hibernate.envers.test.integration.reventity; import org.hibernate.internal.util.collections.ArrayHelper; + import org.hibernate.testing.TestForIssue; /** @@ -11,5 +12,5 @@ public class OverrideCustomRevListenerTest extends GloballyConfiguredRevListener @Override protected Class[] getAnnotatedClasses() { return ArrayHelper.join( super.getAnnotatedClasses(), ListenerRevEntity.class ); - } + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/OverrideDefaultRevListenerTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/OverrideDefaultRevListenerTest.java index 097dd41932..d0acecb3ef 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/OverrideDefaultRevListenerTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/OverrideDefaultRevListenerTest.java @@ -1,6 +1,7 @@ package org.hibernate.envers.test.integration.reventity; import org.hibernate.internal.util.collections.ArrayHelper; + import org.hibernate.testing.TestForIssue; /** @@ -11,5 +12,5 @@ public class OverrideDefaultRevListenerTest extends GloballyConfiguredRevListene @Override protected Class[] getAnnotatedClasses() { return ArrayHelper.join( super.getAnnotatedClasses(), LongRevNumberRevEntity.class ); - } + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/TestExceptionRevisionListener.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/TestExceptionRevisionListener.java index 130555b81e..cdc1650169 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/TestExceptionRevisionListener.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/TestExceptionRevisionListener.java @@ -29,7 +29,7 @@ import org.hibernate.envers.RevisionListener; * @author Adam Warski (adam at warski dot org) */ public class TestExceptionRevisionListener implements RevisionListener { - public void newRevision(Object revisionEntity) { - throw new RuntimeException( "forcing transaction failure!" ); - } + public void newRevision(Object revisionEntity) { + throw new RuntimeException( "forcing transaction failure!" ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/TestRevisionListener.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/TestRevisionListener.java index 6f353be284..4ebe846e01 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/TestRevisionListener.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/TestRevisionListener.java @@ -22,15 +22,16 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.reventity; + import org.hibernate.envers.RevisionListener; /** * @author Adam Warski (adam at warski dot org) */ public class TestRevisionListener implements RevisionListener { - public static String data = "data0"; + public static String data = "data0"; - public void newRevision(Object revisionEntity) { - ((ListenerRevEntity) revisionEntity).setData(data); - } + public void newRevision(Object revisionEntity) { + ((ListenerRevEntity) revisionEntity).setData( data ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/AnnotatedTrackingEntitiesTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/AnnotatedTrackingEntitiesTest.java index 2d1255dcd4..229251a544 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/AnnotatedTrackingEntitiesTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/AnnotatedTrackingEntitiesTest.java @@ -9,17 +9,18 @@ import org.hibernate.internal.util.collections.ArrayHelper; /** * Tests proper behavior of revision entity that utilizes {@link ModifiedEntityNames} annotation. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class AnnotatedTrackingEntitiesTest extends DefaultTrackingEntitiesTest { @Override protected Class[] getAnnotatedClasses() { return ArrayHelper.join( super.getAnnotatedClasses(), AnnotatedTrackingRevisionEntity.class ); - } + } @Override public void addConfigOptions(Map configuration) { super.addConfigOptions( configuration ); - configuration.put(EnversSettings.TRACK_ENTITIES_CHANGED_IN_REVISION, "false"); + configuration.put( EnversSettings.TRACK_ENTITIES_CHANGED_IN_REVISION, "false" ); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/CustomTrackingEntitiesTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/CustomTrackingEntitiesTest.java index 64d4dd7dd2..7d79a34240 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/CustomTrackingEntitiesTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/CustomTrackingEntitiesTest.java @@ -2,8 +2,6 @@ package org.hibernate.envers.test.integration.reventity.trackmodifiedentities; import javax.persistence.EntityManager; -import org.junit.Test; - import org.hibernate.envers.EntityTrackingRevisionListener; import org.hibernate.envers.exception.AuditException; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -15,16 +13,19 @@ import org.hibernate.envers.test.entities.reventity.trackmodifiedentities.Custom import org.hibernate.envers.test.entities.reventity.trackmodifiedentities.ModifiedEntityTypeEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * Tests proper behavior of entity listener that implements {@link EntityTrackingRevisionListener} * interface. {@link CustomTrackingRevisionListener} shall be notified whenever an entity instance has been * added, modified or removed, so that changed entity name can be persisted. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class CustomTrackingEntitiesTest extends BaseEnversJPAFunctionalTestCase { - private Integer steId = null; - private Integer siteId = null; + private Integer steId = null; + private Integer siteId = null; @Override protected Class[] getAnnotatedClasses() { @@ -34,75 +35,75 @@ public class CustomTrackingEntitiesTest extends BaseEnversJPAFunctionalTestCase StrIntTestEntity.class, CustomTrackingRevisionEntity.class }; - } + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 1 - Adding two entities - em.getTransaction().begin(); - StrTestEntity ste = new StrTestEntity("x"); - StrIntTestEntity site = new StrIntTestEntity("y", 1); - em.persist(ste); - em.persist(site); - steId = ste.getId(); - siteId = site.getId(); - em.getTransaction().commit(); + // Revision 1 - Adding two entities + em.getTransaction().begin(); + StrTestEntity ste = new StrTestEntity( "x" ); + StrIntTestEntity site = new StrIntTestEntity( "y", 1 ); + em.persist( ste ); + em.persist( site ); + steId = ste.getId(); + siteId = site.getId(); + em.getTransaction().commit(); - // Revision 2 - Modifying one entity - em.getTransaction().begin(); - site = em.find(StrIntTestEntity.class, siteId); - site.setNumber(2); - em.getTransaction().commit(); + // Revision 2 - Modifying one entity + em.getTransaction().begin(); + site = em.find( StrIntTestEntity.class, siteId ); + site.setNumber( 2 ); + em.getTransaction().commit(); - // Revision 3 - Deleting both entities - em.getTransaction().begin(); - ste = em.find(StrTestEntity.class, steId); - site = em.find(StrIntTestEntity.class, siteId); - em.remove(ste); - em.remove(site); - em.getTransaction().commit(); - } + // Revision 3 - Deleting both entities + em.getTransaction().begin(); + ste = em.find( StrTestEntity.class, steId ); + site = em.find( StrIntTestEntity.class, siteId ); + em.remove( ste ); + em.remove( site ); + em.getTransaction().commit(); + } - @Test - public void testTrackAddedEntities() { - ModifiedEntityTypeEntity steDescriptor = new ModifiedEntityTypeEntity(StrTestEntity.class.getName()); - ModifiedEntityTypeEntity siteDescriptor = new ModifiedEntityTypeEntity(StrIntTestEntity.class.getName()); + @Test + public void testTrackAddedEntities() { + ModifiedEntityTypeEntity steDescriptor = new ModifiedEntityTypeEntity( StrTestEntity.class.getName() ); + ModifiedEntityTypeEntity siteDescriptor = new ModifiedEntityTypeEntity( StrIntTestEntity.class.getName() ); - CustomTrackingRevisionEntity ctre = getAuditReader().findRevision(CustomTrackingRevisionEntity.class, 1); + CustomTrackingRevisionEntity ctre = getAuditReader().findRevision( CustomTrackingRevisionEntity.class, 1 ); - assert ctre.getModifiedEntityTypes() != null; - assert ctre.getModifiedEntityTypes().size() == 2; - assert TestTools.makeSet(steDescriptor, siteDescriptor).equals(ctre.getModifiedEntityTypes()); - } + assert ctre.getModifiedEntityTypes() != null; + assert ctre.getModifiedEntityTypes().size() == 2; + assert TestTools.makeSet( steDescriptor, siteDescriptor ).equals( ctre.getModifiedEntityTypes() ); + } - @Test - public void testTrackModifiedEntities() { - ModifiedEntityTypeEntity siteDescriptor = new ModifiedEntityTypeEntity(StrIntTestEntity.class.getName()); + @Test + public void testTrackModifiedEntities() { + ModifiedEntityTypeEntity siteDescriptor = new ModifiedEntityTypeEntity( StrIntTestEntity.class.getName() ); - CustomTrackingRevisionEntity ctre = getAuditReader().findRevision(CustomTrackingRevisionEntity.class, 2); + CustomTrackingRevisionEntity ctre = getAuditReader().findRevision( CustomTrackingRevisionEntity.class, 2 ); - assert ctre.getModifiedEntityTypes() != null; - assert ctre.getModifiedEntityTypes().size() == 1; - assert TestTools.makeSet(siteDescriptor).equals(ctre.getModifiedEntityTypes()); - } + assert ctre.getModifiedEntityTypes() != null; + assert ctre.getModifiedEntityTypes().size() == 1; + assert TestTools.makeSet( siteDescriptor ).equals( ctre.getModifiedEntityTypes() ); + } - @Test - public void testTrackDeletedEntities() { - ModifiedEntityTypeEntity steDescriptor = new ModifiedEntityTypeEntity(StrTestEntity.class.getName()); - ModifiedEntityTypeEntity siteDescriptor = new ModifiedEntityTypeEntity(StrIntTestEntity.class.getName()); + @Test + public void testTrackDeletedEntities() { + ModifiedEntityTypeEntity steDescriptor = new ModifiedEntityTypeEntity( StrTestEntity.class.getName() ); + ModifiedEntityTypeEntity siteDescriptor = new ModifiedEntityTypeEntity( StrIntTestEntity.class.getName() ); - CustomTrackingRevisionEntity ctre = getAuditReader().findRevision(CustomTrackingRevisionEntity.class, 3); + CustomTrackingRevisionEntity ctre = getAuditReader().findRevision( CustomTrackingRevisionEntity.class, 3 ); - assert ctre.getModifiedEntityTypes() != null; - assert ctre.getModifiedEntityTypes().size() == 2; - assert TestTools.makeSet(steDescriptor, siteDescriptor).equals(ctre.getModifiedEntityTypes()); - } + assert ctre.getModifiedEntityTypes() != null; + assert ctre.getModifiedEntityTypes().size() == 2; + assert TestTools.makeSet( steDescriptor, siteDescriptor ).equals( ctre.getModifiedEntityTypes() ); + } - @Test(expected = AuditException.class) - public void testFindEntitiesChangedInRevisionException() { - getAuditReader().getCrossTypeRevisionChangesReader(); - } + @Test(expected = AuditException.class) + public void testFindEntitiesChangedInRevisionException() { + getAuditReader().getCrossTypeRevisionChangesReader(); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/DefaultTrackingEntitiesTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/DefaultTrackingEntitiesTest.java index 3865b63b90..2cf39b0101 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/DefaultTrackingEntitiesTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/DefaultTrackingEntitiesTest.java @@ -1,11 +1,9 @@ package org.hibernate.envers.test.integration.reventity.trackmodifiedentities; +import javax.persistence.EntityManager; import java.util.Iterator; import java.util.List; import java.util.Map; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.CrossTypeRevisionChangesReader; import org.hibernate.envers.RevisionType; @@ -19,170 +17,185 @@ import org.hibernate.envers.tools.Pair; import org.hibernate.mapping.Column; import org.hibernate.mapping.Table; +import org.junit.Test; + /** * Tests proper behavior of tracking modified entity names when {@code org.hibernate.envers.track_entities_changed_in_revision} * parameter is set to {@code true}. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @SuppressWarnings({"unchecked"}) public class DefaultTrackingEntitiesTest extends BaseEnversJPAFunctionalTestCase { - private Integer steId = null; - private Integer siteId = null; + private Integer steId = null; + private Integer siteId = null; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class, StrIntTestEntity.class }; - } + return new Class[] {StrTestEntity.class, StrIntTestEntity.class}; + } @Override public void addConfigOptions(Map configuration) { super.addConfigOptions( configuration ); - configuration.put(EnversSettings.TRACK_ENTITIES_CHANGED_IN_REVISION, "true"); + configuration.put( EnversSettings.TRACK_ENTITIES_CHANGED_IN_REVISION, "true" ); } @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - - // Revision 1 - Adding two entities - em.getTransaction().begin(); - StrTestEntity ste = new StrTestEntity("x"); - StrIntTestEntity site = new StrIntTestEntity("y", 1); - em.persist(ste); - em.persist(site); - steId = ste.getId(); - siteId = site.getId(); - em.getTransaction().commit(); + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 2 - Modifying one entity - em.getTransaction().begin(); - site = em.find(StrIntTestEntity.class, siteId); - site.setNumber(2); - em.getTransaction().commit(); + // Revision 1 - Adding two entities + em.getTransaction().begin(); + StrTestEntity ste = new StrTestEntity( "x" ); + StrIntTestEntity site = new StrIntTestEntity( "y", 1 ); + em.persist( ste ); + em.persist( site ); + steId = ste.getId(); + siteId = site.getId(); + em.getTransaction().commit(); - // Revision 3 - Deleting both entities - em.getTransaction().begin(); - ste = em.find(StrTestEntity.class, steId); - site = em.find(StrIntTestEntity.class, siteId); - em.remove(ste); - em.remove(site); - em.getTransaction().commit(); - } + // Revision 2 - Modifying one entity + em.getTransaction().begin(); + site = em.find( StrIntTestEntity.class, siteId ); + site.setNumber( 2 ); + em.getTransaction().commit(); - @Test - public void testRevEntityTableCreation() { - Iterator tableIterator = getCfg().getTableMappings(); - while (tableIterator.hasNext()) { - Table table = tableIterator.next(); - if ("REVCHANGES".equals(table.getName())) { - assert table.getColumnSpan() == 2; - assert table.getColumn(new Column("REV")) != null; - assert table.getColumn(new Column("ENTITYNAME")) != null; - return; - } - } - assert false; - } + // Revision 3 - Deleting both entities + em.getTransaction().begin(); + ste = em.find( StrTestEntity.class, steId ); + site = em.find( StrIntTestEntity.class, siteId ); + em.remove( ste ); + em.remove( site ); + em.getTransaction().commit(); + } - @Test - public void testTrackAddedEntities() { - StrTestEntity ste = new StrTestEntity("x", steId); - StrIntTestEntity site = new StrIntTestEntity("y", 1, siteId); + @Test + public void testRevEntityTableCreation() { + Iterator
      tableIterator = getCfg().getTableMappings(); + while ( tableIterator.hasNext() ) { + Table table = tableIterator.next(); + if ( "REVCHANGES".equals( table.getName() ) ) { + assert table.getColumnSpan() == 2; + assert table.getColumn( new Column( "REV" ) ) != null; + assert table.getColumn( new Column( "ENTITYNAME" ) ) != null; + return; + } + } + assert false; + } - assert TestTools.checkList(getCrossTypeRevisionChangesReader().findEntities(1), ste, site); - } + @Test + public void testTrackAddedEntities() { + StrTestEntity ste = new StrTestEntity( "x", steId ); + StrIntTestEntity site = new StrIntTestEntity( "y", 1, siteId ); - @Test - public void testTrackModifiedEntities() { - StrIntTestEntity site = new StrIntTestEntity("y", 2, siteId); + assert TestTools.checkList( getCrossTypeRevisionChangesReader().findEntities( 1 ), ste, site ); + } - assert TestTools.checkList(getCrossTypeRevisionChangesReader().findEntities(2), site); - } + @Test + public void testTrackModifiedEntities() { + StrIntTestEntity site = new StrIntTestEntity( "y", 2, siteId ); - @Test - public void testTrackDeletedEntities() { - StrTestEntity ste = new StrTestEntity(null, steId); - StrIntTestEntity site = new StrIntTestEntity(null, null, siteId); + assert TestTools.checkList( getCrossTypeRevisionChangesReader().findEntities( 2 ), site ); + } - assert TestTools.checkList(getCrossTypeRevisionChangesReader().findEntities(3), site, ste); - } + @Test + public void testTrackDeletedEntities() { + StrTestEntity ste = new StrTestEntity( null, steId ); + StrIntTestEntity site = new StrIntTestEntity( null, null, siteId ); - @Test - public void testFindChangesInInvalidRevision() { - assert getCrossTypeRevisionChangesReader().findEntities(4).isEmpty(); - } + assert TestTools.checkList( getCrossTypeRevisionChangesReader().findEntities( 3 ), site, ste ); + } - @Test - public void testTrackAddedEntitiesGroupByRevisionType() { - StrTestEntity ste = new StrTestEntity("x", steId); - StrIntTestEntity site = new StrIntTestEntity("y", 1, siteId); + @Test + public void testFindChangesInInvalidRevision() { + assert getCrossTypeRevisionChangesReader().findEntities( 4 ).isEmpty(); + } - Map> result = getCrossTypeRevisionChangesReader().findEntitiesGroupByRevisionType(1); - assert TestTools.checkList(result.get(RevisionType.ADD), site, ste); - assert TestTools.checkList(result.get(RevisionType.MOD)); - assert TestTools.checkList(result.get(RevisionType.DEL)); - } + @Test + public void testTrackAddedEntitiesGroupByRevisionType() { + StrTestEntity ste = new StrTestEntity( "x", steId ); + StrIntTestEntity site = new StrIntTestEntity( "y", 1, siteId ); - @Test - public void testTrackModifiedEntitiesGroupByRevisionType() { - StrIntTestEntity site = new StrIntTestEntity("y", 2, siteId); + Map> result = getCrossTypeRevisionChangesReader().findEntitiesGroupByRevisionType( 1 ); + assert TestTools.checkList( result.get( RevisionType.ADD ), site, ste ); + assert TestTools.checkList( result.get( RevisionType.MOD ) ); + assert TestTools.checkList( result.get( RevisionType.DEL ) ); + } - Map> result = getCrossTypeRevisionChangesReader().findEntitiesGroupByRevisionType(2); - assert TestTools.checkList(result.get(RevisionType.ADD)); - assert TestTools.checkList(result.get(RevisionType.MOD), site); - assert TestTools.checkList(result.get(RevisionType.DEL)); - } + @Test + public void testTrackModifiedEntitiesGroupByRevisionType() { + StrIntTestEntity site = new StrIntTestEntity( "y", 2, siteId ); - @Test - public void testTrackDeletedEntitiesGroupByRevisionType() { - StrTestEntity ste = new StrTestEntity(null, steId); - StrIntTestEntity site = new StrIntTestEntity(null, null, siteId); + Map> result = getCrossTypeRevisionChangesReader().findEntitiesGroupByRevisionType( 2 ); + assert TestTools.checkList( result.get( RevisionType.ADD ) ); + assert TestTools.checkList( result.get( RevisionType.MOD ), site ); + assert TestTools.checkList( result.get( RevisionType.DEL ) ); + } - Map> result = getCrossTypeRevisionChangesReader().findEntitiesGroupByRevisionType(3); - assert TestTools.checkList(result.get(RevisionType.ADD)); - assert TestTools.checkList(result.get(RevisionType.MOD)); - assert TestTools.checkList(result.get(RevisionType.DEL), site, ste); - } + @Test + public void testTrackDeletedEntitiesGroupByRevisionType() { + StrTestEntity ste = new StrTestEntity( null, steId ); + StrIntTestEntity site = new StrIntTestEntity( null, null, siteId ); - @Test - public void testFindChangedEntitiesByRevisionTypeADD() { - StrTestEntity ste = new StrTestEntity("x", steId); - StrIntTestEntity site = new StrIntTestEntity("y", 1, siteId); + Map> result = getCrossTypeRevisionChangesReader().findEntitiesGroupByRevisionType( 3 ); + assert TestTools.checkList( result.get( RevisionType.ADD ) ); + assert TestTools.checkList( result.get( RevisionType.MOD ) ); + assert TestTools.checkList( result.get( RevisionType.DEL ), site, ste ); + } - assert TestTools.checkList(getCrossTypeRevisionChangesReader().findEntities(1, RevisionType.ADD), ste, site); - } + @Test + public void testFindChangedEntitiesByRevisionTypeADD() { + StrTestEntity ste = new StrTestEntity( "x", steId ); + StrIntTestEntity site = new StrIntTestEntity( "y", 1, siteId ); - @Test - public void testFindChangedEntitiesByRevisionTypeMOD() { - StrIntTestEntity site = new StrIntTestEntity("y", 2, siteId); + assert TestTools.checkList( + getCrossTypeRevisionChangesReader().findEntities( 1, RevisionType.ADD ), + ste, + site + ); + } - assert TestTools.checkList(getCrossTypeRevisionChangesReader().findEntities(2, RevisionType.MOD), site); - } + @Test + public void testFindChangedEntitiesByRevisionTypeMOD() { + StrIntTestEntity site = new StrIntTestEntity( "y", 2, siteId ); - @Test - public void testFindChangedEntitiesByRevisionTypeDEL() { - StrTestEntity ste = new StrTestEntity(null, steId); - StrIntTestEntity site = new StrIntTestEntity(null, null, siteId); + assert TestTools.checkList( getCrossTypeRevisionChangesReader().findEntities( 2, RevisionType.MOD ), site ); + } - assert TestTools.checkList(getCrossTypeRevisionChangesReader().findEntities(3, RevisionType.DEL), ste, site); - } + @Test + public void testFindChangedEntitiesByRevisionTypeDEL() { + StrTestEntity ste = new StrTestEntity( null, steId ); + StrIntTestEntity site = new StrIntTestEntity( null, null, siteId ); - @Test - public void testFindEntityTypesChangedInRevision() { - assert TestTools.makeSet(Pair.make(StrTestEntity.class.getName(), StrTestEntity.class), - Pair.make(StrIntTestEntity.class.getName(), StrIntTestEntity.class)) - .equals(getCrossTypeRevisionChangesReader().findEntityTypes(1)); + assert TestTools.checkList( + getCrossTypeRevisionChangesReader().findEntities( 3, RevisionType.DEL ), + ste, + site + ); + } - assert TestTools.makeSet(Pair.make(StrIntTestEntity.class.getName(), StrIntTestEntity.class)) - .equals(getCrossTypeRevisionChangesReader().findEntityTypes(2)); - - assert TestTools.makeSet(Pair.make(StrTestEntity.class.getName(), StrTestEntity.class), - Pair.make(StrIntTestEntity.class.getName(), StrIntTestEntity.class)) - .equals(getCrossTypeRevisionChangesReader().findEntityTypes(3)); - } + @Test + public void testFindEntityTypesChangedInRevision() { + assert TestTools.makeSet( + Pair.make( StrTestEntity.class.getName(), StrTestEntity.class ), + Pair.make( StrIntTestEntity.class.getName(), StrIntTestEntity.class ) + ) + .equals( getCrossTypeRevisionChangesReader().findEntityTypes( 1 ) ); - private CrossTypeRevisionChangesReader getCrossTypeRevisionChangesReader() { - return getAuditReader().getCrossTypeRevisionChangesReader(); - } + assert TestTools.makeSet( Pair.make( StrIntTestEntity.class.getName(), StrIntTestEntity.class ) ) + .equals( getCrossTypeRevisionChangesReader().findEntityTypes( 2 ) ); + + assert TestTools.makeSet( + Pair.make( StrTestEntity.class.getName(), StrTestEntity.class ), + Pair.make( StrIntTestEntity.class.getName(), StrIntTestEntity.class ) + ) + .equals( getCrossTypeRevisionChangesReader().findEntityTypes( 3 ) ); + } + + private CrossTypeRevisionChangesReader getCrossTypeRevisionChangesReader() { + return getAuditReader().getCrossTypeRevisionChangesReader(); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/EntityNamesTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/EntityNamesTest.java index 1f9c245d9c..703fe1b19f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/EntityNamesTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/EntityNamesTest.java @@ -3,8 +3,6 @@ package org.hibernate.envers.test.integration.reventity.trackmodifiedentities; import java.util.ArrayList; import java.util.List; -import org.junit.Test; - import org.hibernate.cfg.Configuration; import org.hibernate.envers.configuration.EnversSettings; import org.hibernate.envers.test.BaseEnversFunctionalTestCase; @@ -14,62 +12,68 @@ import org.hibernate.envers.test.integration.entityNames.manyToManyAudited.Perso import org.hibernate.envers.test.tools.TestTools; import org.hibernate.envers.tools.Pair; +import org.junit.Test; + /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class EntityNamesTest extends BaseEnversFunctionalTestCase { - @Override - protected String[] getMappings() { - return new String[]{"mappings/entityNames/manyToManyAudited/mappings.hbm.xml"}; - } + @Override + protected String[] getMappings() { + return new String[] {"mappings/entityNames/manyToManyAudited/mappings.hbm.xml"}; + } - @Override - protected void configure(Configuration configuration) { - configuration.setProperty(EnversSettings.TRACK_ENTITIES_CHANGED_IN_REVISION, "true"); - } + @Override + protected void configure(Configuration configuration) { + configuration.setProperty( EnversSettings.TRACK_ENTITIES_CHANGED_IN_REVISION, "true" ); + } - @Test - @Priority(10) - public void initData() { - Person pers1 = new Person("Hernan", 28); - Person pers2 = new Person("Leandro", 29); - Person pers3 = new Person("Barba", 32); - Person pers4 = new Person("Camomo", 15); + @Test + @Priority(10) + public void initData() { + Person pers1 = new Person( "Hernan", 28 ); + Person pers2 = new Person( "Leandro", 29 ); + Person pers3 = new Person( "Barba", 32 ); + Person pers4 = new Person( "Camomo", 15 ); - // Revision 1 - getSession().getTransaction().begin(); - List owners = new ArrayList(); - owners.add(pers1); - owners.add(pers2); - owners.add(pers3); - Car car1 = new Car(5, owners); - getSession().persist(car1); - getSession().getTransaction().commit(); - long person1Id = pers1.getId(); + // Revision 1 + getSession().getTransaction().begin(); + List owners = new ArrayList(); + owners.add( pers1 ); + owners.add( pers2 ); + owners.add( pers3 ); + Car car1 = new Car( 5, owners ); + getSession().persist( car1 ); + getSession().getTransaction().commit(); + long person1Id = pers1.getId(); - // Revision 2 - owners = new ArrayList(); - owners.add(pers2); - owners.add(pers3); - owners.add(pers4); - Car car2 = new Car(27, owners); - getSession().getTransaction().begin(); - Person person1 = (Person)getSession().get("Personaje", person1Id); - person1.setName("Hernan David"); - person1.setAge(40); - getSession().persist(car1); - getSession().persist(car2); - getSession().getTransaction().commit(); - } + // Revision 2 + owners = new ArrayList(); + owners.add( pers2 ); + owners.add( pers3 ); + owners.add( pers4 ); + Car car2 = new Car( 27, owners ); + getSession().getTransaction().begin(); + Person person1 = (Person) getSession().get( "Personaje", person1Id ); + person1.setName( "Hernan David" ); + person1.setAge( 40 ); + getSession().persist( car1 ); + getSession().persist( car2 ); + getSession().getTransaction().commit(); + } - @Test - @SuppressWarnings("unchecked") - public void testModifiedEntityTypes() { - assert TestTools.makeSet(Pair.make(Car.class.getName(), Car.class), - Pair.make("Personaje", Person.class)) - .equals(getAuditReader().getCrossTypeRevisionChangesReader().findEntityTypes(1)); - assert TestTools.makeSet(Pair.make(Car.class.getName(), Car.class), - Pair.make("Personaje", Person.class)) - .equals(getAuditReader().getCrossTypeRevisionChangesReader().findEntityTypes(2)); - } + @Test + @SuppressWarnings("unchecked") + public void testModifiedEntityTypes() { + assert TestTools.makeSet( + Pair.make( Car.class.getName(), Car.class ), + Pair.make( "Personaje", Person.class ) + ) + .equals( getAuditReader().getCrossTypeRevisionChangesReader().findEntityTypes( 1 ) ); + assert TestTools.makeSet( + Pair.make( Car.class.getName(), Car.class ), + Pair.make( "Personaje", Person.class ) + ) + .equals( getAuditReader().getCrossTypeRevisionChangesReader().findEntityTypes( 2 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/ExtendedRevisionEntityTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/ExtendedRevisionEntityTest.java index 39f3385e9b..1b5a3d3643 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/ExtendedRevisionEntityTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/ExtendedRevisionEntityTest.java @@ -2,35 +2,36 @@ package org.hibernate.envers.test.integration.reventity.trackmodifiedentities; import java.util.Map; -import org.junit.Assert; -import org.junit.Test; - import org.hibernate.envers.DefaultTrackingModifiedEntitiesRevisionEntity; import org.hibernate.envers.configuration.EnversSettings; import org.hibernate.envers.test.entities.reventity.trackmodifiedentities.ExtendedRevisionEntity; import org.hibernate.envers.test.entities.reventity.trackmodifiedentities.ExtendedRevisionListener; import org.hibernate.internal.util.collections.ArrayHelper; +import org.junit.Assert; +import org.junit.Test; + /** * Tests proper behavior of revision entity that extends {@link DefaultTrackingModifiedEntitiesRevisionEntity}. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class ExtendedRevisionEntityTest extends DefaultTrackingEntitiesTest { @Override protected Class[] getAnnotatedClasses() { return ArrayHelper.join( super.getAnnotatedClasses(), ExtendedRevisionEntity.class ); - } + } - @Override - public void addConfigOptions(Map configuration) { - super.addConfigOptions(configuration); - configuration.put(EnversSettings.TRACK_ENTITIES_CHANGED_IN_REVISION, "false"); - } + @Override + public void addConfigOptions(Map configuration) { + super.addConfigOptions( configuration ); + configuration.put( EnversSettings.TRACK_ENTITIES_CHANGED_IN_REVISION, "false" ); + } - @Test - public void testCommentPropertyValue() { - ExtendedRevisionEntity ere = getAuditReader().findRevision(ExtendedRevisionEntity.class, 1); + @Test + public void testCommentPropertyValue() { + ExtendedRevisionEntity ere = getAuditReader().findRevision( ExtendedRevisionEntity.class, 1 ); - Assert.assertEquals(ExtendedRevisionListener.COMMENT_VALUE, ere.getComment()); - } + Assert.assertEquals( ExtendedRevisionListener.COMMENT_VALUE, ere.getComment() ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/TrackingEntitiesMultipleChangesTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/TrackingEntitiesMultipleChangesTest.java index 59f947b103..826b20b2b0 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/TrackingEntitiesMultipleChangesTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/reventity/trackmodifiedentities/TrackingEntitiesMultipleChangesTest.java @@ -1,11 +1,8 @@ package org.hibernate.envers.test.integration.reventity.trackmodifiedentities; +import javax.persistence.EntityManager; import java.util.HashSet; import java.util.Map; -import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; import org.hibernate.envers.CrossTypeRevisionChangesReader; import org.hibernate.envers.configuration.EnversSettings; @@ -14,80 +11,92 @@ import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Assert; +import org.junit.Test; + /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class TrackingEntitiesMultipleChangesTest extends BaseEnversJPAFunctionalTestCase { - private Integer steId1 = null; - private Integer steId2 = null; + private Integer steId1 = null; + private Integer steId2 = null; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class }; - } + return new Class[] {StrTestEntity.class}; + } @Override protected void addConfigOptions(Map options) { super.addConfigOptions( options ); - options.put( EnversSettings.TRACK_ENTITIES_CHANGED_IN_REVISION, "true" ) ; + options.put( EnversSettings.TRACK_ENTITIES_CHANGED_IN_REVISION, "true" ); } @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 1 - Adding two entities - em.getTransaction().begin(); - StrTestEntity ste1 = new StrTestEntity("x"); - StrTestEntity ste2 = new StrTestEntity("y"); - em.persist(ste1); - em.persist(ste2); - steId1 = ste1.getId(); - steId2 = ste2.getId(); - em.getTransaction().commit(); + // Revision 1 - Adding two entities + em.getTransaction().begin(); + StrTestEntity ste1 = new StrTestEntity( "x" ); + StrTestEntity ste2 = new StrTestEntity( "y" ); + em.persist( ste1 ); + em.persist( ste2 ); + steId1 = ste1.getId(); + steId2 = ste2.getId(); + em.getTransaction().commit(); - // Revision 2 - Adding first and removing second entity - em.getTransaction().begin(); - ste1 = em.find(StrTestEntity.class, steId1); - ste2 = em.find(StrTestEntity.class, steId2); - ste1.setStr("z"); - em.remove(ste2); - em.getTransaction().commit(); + // Revision 2 - Adding first and removing second entity + em.getTransaction().begin(); + ste1 = em.find( StrTestEntity.class, steId1 ); + ste2 = em.find( StrTestEntity.class, steId2 ); + ste1.setStr( "z" ); + em.remove( ste2 ); + em.getTransaction().commit(); - // Revision 3 - Modifying and removing the same entity. - em.getTransaction().begin(); - ste1 = em.find(StrTestEntity.class, steId1); - ste1.setStr("a"); - em.merge(ste1); - em.remove(ste1); - em.getTransaction().commit(); - } + // Revision 3 - Modifying and removing the same entity. + em.getTransaction().begin(); + ste1 = em.find( StrTestEntity.class, steId1 ); + ste1.setStr( "a" ); + em.merge( ste1 ); + em.remove( ste1 ); + em.getTransaction().commit(); + } - @Test - public void testTrackAddedTwoEntities() { - StrTestEntity ste1 = new StrTestEntity("x", steId1); - StrTestEntity ste2 = new StrTestEntity("y", steId2); + @Test + public void testTrackAddedTwoEntities() { + StrTestEntity ste1 = new StrTestEntity( "x", steId1 ); + StrTestEntity ste2 = new StrTestEntity( "y", steId2 ); - Assert.assertEquals(TestTools.makeSet(ste1, ste2), new HashSet(getCrossTypeRevisionChangesReader().findEntities(1))); - } + Assert.assertEquals( + TestTools.makeSet( ste1, ste2 ), + new HashSet( getCrossTypeRevisionChangesReader().findEntities( 1 ) ) + ); + } - @Test - public void testTrackUpdateAndRemoveDifferentEntities() { - StrTestEntity ste1 = new StrTestEntity("z", steId1); - StrTestEntity ste2 = new StrTestEntity(null, steId2); + @Test + public void testTrackUpdateAndRemoveDifferentEntities() { + StrTestEntity ste1 = new StrTestEntity( "z", steId1 ); + StrTestEntity ste2 = new StrTestEntity( null, steId2 ); - Assert.assertEquals(TestTools.makeSet(ste1, ste2), new HashSet(getCrossTypeRevisionChangesReader().findEntities(2))); - } + Assert.assertEquals( + TestTools.makeSet( ste1, ste2 ), + new HashSet( getCrossTypeRevisionChangesReader().findEntities( 2 ) ) + ); + } - @Test - public void testTrackUpdateAndRemoveTheSameEntity() { - StrTestEntity ste1 = new StrTestEntity(null, steId1); + @Test + public void testTrackUpdateAndRemoveTheSameEntity() { + StrTestEntity ste1 = new StrTestEntity( null, steId1 ); - Assert.assertEquals(TestTools.makeSet(ste1), new HashSet(getCrossTypeRevisionChangesReader().findEntities(3))); - } + Assert.assertEquals( + TestTools.makeSet( ste1 ), + new HashSet( getCrossTypeRevisionChangesReader().findEntities( 3 ) ) + ); + } - private CrossTypeRevisionChangesReader getCrossTypeRevisionChangesReader() { - return getAuditReader().getCrossTypeRevisionChangesReader(); - } + private CrossTypeRevisionChangesReader getCrossTypeRevisionChangesReader() { + return getAuditReader().getCrossTypeRevisionChangesReader(); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/revfordate/RevisionForDate.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/revfordate/RevisionForDate.java index 88b2f7ef63..9ed2bd5a33 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/revfordate/RevisionForDate.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/revfordate/RevisionForDate.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.revfordate; -import java.util.Date; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Date; import org.hibernate.envers.AuditReader; import org.hibernate.envers.exception.RevisionDoesNotExistException; @@ -34,88 +32,92 @@ import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class RevisionForDate extends BaseEnversJPAFunctionalTestCase { - private long timestamp1; - private long timestamp2; - private long timestamp3; - private long timestamp4; + private long timestamp1; + private long timestamp2; + private long timestamp3; + private long timestamp4; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class }; - } + return new Class[] {StrTestEntity.class}; + } - @Test - @Priority(10) - public void initData() throws InterruptedException { - timestamp1 = System.currentTimeMillis(); + @Test + @Priority(10) + public void initData() throws InterruptedException { + timestamp1 = System.currentTimeMillis(); - Thread.sleep(100); + Thread.sleep( 100 ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - StrTestEntity rfd = new StrTestEntity("x"); - em.persist(rfd); - Integer id = rfd.getId(); - em.getTransaction().commit(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + StrTestEntity rfd = new StrTestEntity( "x" ); + em.persist( rfd ); + Integer id = rfd.getId(); + em.getTransaction().commit(); - timestamp2 = System.currentTimeMillis(); + timestamp2 = System.currentTimeMillis(); - Thread.sleep(100); + Thread.sleep( 100 ); - // Revision 2 - em.getTransaction().begin(); - rfd = em.find(StrTestEntity.class, id); - rfd.setStr("y"); - em.getTransaction().commit(); + // Revision 2 + em.getTransaction().begin(); + rfd = em.find( StrTestEntity.class, id ); + rfd.setStr( "y" ); + em.getTransaction().commit(); - timestamp3 = System.currentTimeMillis(); + timestamp3 = System.currentTimeMillis(); - Thread.sleep(100); + Thread.sleep( 100 ); - // Revision 3 - em.getTransaction().begin(); - rfd = em.find(StrTestEntity.class, id); - rfd.setStr("z"); - em.getTransaction().commit(); + // Revision 3 + em.getTransaction().begin(); + rfd = em.find( StrTestEntity.class, id ); + rfd.setStr( "z" ); + em.getTransaction().commit(); - timestamp4 = System.currentTimeMillis(); - } + timestamp4 = System.currentTimeMillis(); + } - @Test(expected = RevisionDoesNotExistException.class) - public void testTimestamps1() { - getAuditReader().getRevisionNumberForDate(new Date(timestamp1)); - } + @Test(expected = RevisionDoesNotExistException.class) + public void testTimestamps1() { + getAuditReader().getRevisionNumberForDate( new Date( timestamp1 ) ); + } - @Test - public void testTimestamps() { - assert getAuditReader().getRevisionNumberForDate(new Date(timestamp2)).intValue() == 1; - assert getAuditReader().getRevisionNumberForDate(new Date(timestamp3)).intValue() == 2; - assert getAuditReader().getRevisionNumberForDate(new Date(timestamp4)).intValue() == 3; - } + @Test + public void testTimestamps() { + assert getAuditReader().getRevisionNumberForDate( new Date( timestamp2 ) ).intValue() == 1; + assert getAuditReader().getRevisionNumberForDate( new Date( timestamp3 ) ).intValue() == 2; + assert getAuditReader().getRevisionNumberForDate( new Date( timestamp4 ) ).intValue() == 3; + } - @Test - public void testDatesForRevisions() { - AuditReader vr = getAuditReader(); - assert vr.getRevisionNumberForDate(vr.getRevisionDate(1)).intValue() == 1; - assert vr.getRevisionNumberForDate(vr.getRevisionDate(2)).intValue() == 2; - assert vr.getRevisionNumberForDate(vr.getRevisionDate(3)).intValue() == 3; - } + @Test + public void testDatesForRevisions() { + AuditReader vr = getAuditReader(); + assert vr.getRevisionNumberForDate( vr.getRevisionDate( 1 ) ).intValue() == 1; + assert vr.getRevisionNumberForDate( vr.getRevisionDate( 2 ) ).intValue() == 2; + assert vr.getRevisionNumberForDate( vr.getRevisionDate( 3 ) ).intValue() == 3; + } - @Test - public void testRevisionsForDates() { - AuditReader vr = getAuditReader(); + @Test + public void testRevisionsForDates() { + AuditReader vr = getAuditReader(); - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp2))).getTime() <= timestamp2; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp2)).intValue()+1).getTime() > timestamp2; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp2 ) ) ).getTime() <= timestamp2; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp2 ) ).intValue() + 1 ) + .getTime() > timestamp2; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp3))).getTime() <= timestamp3; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp3)).intValue()+1).getTime() > timestamp3; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp3 ) ) ).getTime() <= timestamp3; + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp3 ) ).intValue() + 1 ) + .getTime() > timestamp3; - assert vr.getRevisionDate(vr.getRevisionNumberForDate(new Date(timestamp4))).getTime() <= timestamp4; - } + assert vr.getRevisionDate( vr.getRevisionNumberForDate( new Date( timestamp4 ) ) ).getTime() <= timestamp4; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/sameids/SameIdTestEntity1.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/sameids/SameIdTestEntity1.java index 50cb8e98e4..728ef921b4 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/sameids/SameIdTestEntity1.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/sameids/SameIdTestEntity1.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.sameids; + import javax.persistence.Entity; import javax.persistence.Id; @@ -32,56 +33,64 @@ import org.hibernate.envers.Audited; */ @Entity public class SameIdTestEntity1 { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String str1; + @Audited + private String str1; - public SameIdTestEntity1() { - } + public SameIdTestEntity1() { + } - public SameIdTestEntity1(String str1) { - this.str1 = str1; - } + public SameIdTestEntity1(String str1) { + this.str1 = str1; + } - public SameIdTestEntity1(Integer id, String str1) { - this.id = id; - this.str1 = str1; - } + public SameIdTestEntity1(Integer id, String str1) { + this.id = id; + this.str1 = str1; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SameIdTestEntity1)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SameIdTestEntity1) ) { + return false; + } - SameIdTestEntity1 that = (SameIdTestEntity1) o; + SameIdTestEntity1 that = (SameIdTestEntity1) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str1 != null ? str1.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str1 != null ? str1.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/sameids/SameIdTestEntity2.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/sameids/SameIdTestEntity2.java index c5a4b2f9e0..ae203fca56 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/sameids/SameIdTestEntity2.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/sameids/SameIdTestEntity2.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.sameids; + import javax.persistence.Entity; import javax.persistence.Id; @@ -32,56 +33,64 @@ import org.hibernate.envers.Audited; */ @Entity public class SameIdTestEntity2 { - @Id - private Integer id; + @Id + private Integer id; - @Audited - private String str1; + @Audited + private String str1; - public SameIdTestEntity2() { - } + public SameIdTestEntity2() { + } - public SameIdTestEntity2(String str1) { - this.str1 = str1; - } + public SameIdTestEntity2(String str1) { + this.str1 = str1; + } - public SameIdTestEntity2(Integer id, String str1) { - this.id = id; - this.str1 = str1; - } + public SameIdTestEntity2(Integer id, String str1) { + this.id = id; + this.str1 = str1; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SameIdTestEntity2)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SameIdTestEntity2) ) { + return false; + } - SameIdTestEntity2 that = (SameIdTestEntity2) o; + SameIdTestEntity2 that = (SameIdTestEntity2) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str1 != null ? str1.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str1 != null ? str1.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/sameids/SameIds.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/sameids/SameIds.java index 1b2947dc91..8c698131cb 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/sameids/SameIds.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/sameids/SameIds.java @@ -23,66 +23,67 @@ */ package org.hibernate.envers.test.integration.sameids; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; +import org.junit.Test; + /** * A test which checks that if we add two different entities with the same ids in one revision, they * will both be stored. + * * @author Adam Warski (adam at warski dot org) */ public class SameIds extends BaseEnversJPAFunctionalTestCase { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SameIdTestEntity1.class, SameIdTestEntity2.class }; - } + return new Class[] {SameIdTestEntity1.class, SameIdTestEntity2.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - em.getTransaction().begin(); - SameIdTestEntity1 site1 = new SameIdTestEntity1(1, "str1"); - SameIdTestEntity2 site2 = new SameIdTestEntity2(1, "str1"); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + em.getTransaction().begin(); + SameIdTestEntity1 site1 = new SameIdTestEntity1( 1, "str1" ); + SameIdTestEntity2 site2 = new SameIdTestEntity2( 1, "str1" ); - em.persist(site1); - em.persist(site2); - em.getTransaction().commit(); + em.persist( site1 ); + em.persist( site2 ); + em.getTransaction().commit(); - em.getTransaction().begin(); - site1 = em.find(SameIdTestEntity1.class, 1); - site2 = em.find(SameIdTestEntity2.class, 1); - site1.setStr1("str2"); - site2.setStr1("str2"); - em.getTransaction().commit(); - } + em.getTransaction().begin(); + site1 = em.find( SameIdTestEntity1.class, 1 ); + site2 = em.find( SameIdTestEntity2.class, 1 ); + site1.setStr1( "str2" ); + site2.setStr1( "str2" ); + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(SameIdTestEntity1.class, 1)); - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(SameIdTestEntity2.class, 1)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( SameIdTestEntity1.class, 1 ) ); + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( SameIdTestEntity2.class, 1 ) ); + } - @Test - public void testHistoryOfSite1() { - SameIdTestEntity1 ver1 = new SameIdTestEntity1(1, "str1"); - SameIdTestEntity1 ver2 = new SameIdTestEntity1(1, "str2"); + @Test + public void testHistoryOfSite1() { + SameIdTestEntity1 ver1 = new SameIdTestEntity1( 1, "str1" ); + SameIdTestEntity1 ver2 = new SameIdTestEntity1( 1, "str2" ); - assert getAuditReader().find(SameIdTestEntity1.class, 1, 1).equals(ver1); - assert getAuditReader().find(SameIdTestEntity1.class, 1, 2).equals(ver2); - } + assert getAuditReader().find( SameIdTestEntity1.class, 1, 1 ).equals( ver1 ); + assert getAuditReader().find( SameIdTestEntity1.class, 1, 2 ).equals( ver2 ); + } - @Test - public void testHistoryOfSite2() { - SameIdTestEntity2 ver1 = new SameIdTestEntity2(1, "str1"); - SameIdTestEntity2 ver2 = new SameIdTestEntity2(1, "str2"); + @Test + public void testHistoryOfSite2() { + SameIdTestEntity2 ver1 = new SameIdTestEntity2( 1, "str1" ); + SameIdTestEntity2 ver2 = new SameIdTestEntity2( 1, "str2" ); - assert getAuditReader().find(SameIdTestEntity2.class, 1, 1).equals(ver1); - assert getAuditReader().find(SameIdTestEntity2.class, 1, 2).equals(ver2); - } + assert getAuditReader().find( SameIdTestEntity2.class, 1, 1 ).equals( ver1 ); + assert getAuditReader().find( SameIdTestEntity2.class, 1, 2 ).equals( ver2 ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/BasicSecondary.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/BasicSecondary.java index 322a86b2da..f09bf20823 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/BasicSecondary.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/BasicSecondary.java @@ -23,74 +23,78 @@ */ package org.hibernate.envers.test.integration.secondary; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Iterator; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.mapping.Join; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class BasicSecondary extends BaseEnversJPAFunctionalTestCase { - private Integer id; + private Integer id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SecondaryTestEntity.class }; - } + return new Class[] {SecondaryTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - SecondaryTestEntity ste = new SecondaryTestEntity("a", "1"); + @Test + @Priority(10) + public void initData() { + SecondaryTestEntity ste = new SecondaryTestEntity( "a", "1" ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - em.persist(ste); + em.persist( ste ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ste = em.find(SecondaryTestEntity.class, ste.getId()); - ste.setS1("b"); - ste.setS2("2"); + ste = em.find( SecondaryTestEntity.class, ste.getId() ); + ste.setS1( "b" ); + ste.setS2( "2" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - id = ste.getId(); - } + id = ste.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(SecondaryTestEntity.class, id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( SecondaryTestEntity.class, id ) ); + } - @Test - public void testHistoryOfId() { - SecondaryTestEntity ver1 = new SecondaryTestEntity(id, "a", "1"); - SecondaryTestEntity ver2 = new SecondaryTestEntity(id, "b", "2"); + @Test + public void testHistoryOfId() { + SecondaryTestEntity ver1 = new SecondaryTestEntity( id, "a", "1" ); + SecondaryTestEntity ver2 = new SecondaryTestEntity( id, "b", "2" ); - assert getAuditReader().find(SecondaryTestEntity.class, id, 1).equals(ver1); - assert getAuditReader().find(SecondaryTestEntity.class, id, 2).equals(ver2); - } + assert getAuditReader().find( SecondaryTestEntity.class, id, 1 ).equals( ver1 ); + assert getAuditReader().find( SecondaryTestEntity.class, id, 2 ).equals( ver2 ); + } - @SuppressWarnings({"unchecked"}) - @Test - public void testTableNames() { - assert "secondary_AUD".equals(((Iterator) - getCfg().getClassMapping("org.hibernate.envers.test.integration.secondary.SecondaryTestEntity_AUD") - .getJoinIterator()) - .next().getTable().getName()); - } + @SuppressWarnings({"unchecked"}) + @Test + public void testTableNames() { + assert "secondary_AUD".equals( + ((Iterator) + getCfg().getClassMapping( + "org.hibernate.envers.test.integration.secondary.SecondaryTestEntity_AUD" + ) + .getJoinIterator()) + .next().getTable().getName() + ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/NamingSecondary.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/NamingSecondary.java index bd7af203d9..34122b1a8f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/NamingSecondary.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/NamingSecondary.java @@ -23,74 +23,78 @@ */ package org.hibernate.envers.test.integration.secondary; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Iterator; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.mapping.Join; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class NamingSecondary extends BaseEnversJPAFunctionalTestCase { - private Integer id; + private Integer id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SecondaryNamingTestEntity.class }; - } + return new Class[] {SecondaryNamingTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - SecondaryNamingTestEntity ste = new SecondaryNamingTestEntity("a", "1"); + @Test + @Priority(10) + public void initData() { + SecondaryNamingTestEntity ste = new SecondaryNamingTestEntity( "a", "1" ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - em.persist(ste); + em.persist( ste ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ste = em.find(SecondaryNamingTestEntity.class, ste.getId()); - ste.setS1("b"); - ste.setS2("2"); + ste = em.find( SecondaryNamingTestEntity.class, ste.getId() ); + ste.setS1( "b" ); + ste.setS2( "2" ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - id = ste.getId(); - } + id = ste.getId(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(SecondaryNamingTestEntity.class, id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( SecondaryNamingTestEntity.class, id ) ); + } - @Test - public void testHistoryOfId() { - SecondaryNamingTestEntity ver1 = new SecondaryNamingTestEntity(id, "a", "1"); - SecondaryNamingTestEntity ver2 = new SecondaryNamingTestEntity(id, "b", "2"); + @Test + public void testHistoryOfId() { + SecondaryNamingTestEntity ver1 = new SecondaryNamingTestEntity( id, "a", "1" ); + SecondaryNamingTestEntity ver2 = new SecondaryNamingTestEntity( id, "b", "2" ); - assert getAuditReader().find(SecondaryNamingTestEntity.class, id, 1).equals(ver1); - assert getAuditReader().find(SecondaryNamingTestEntity.class, id, 2).equals(ver2); - } + assert getAuditReader().find( SecondaryNamingTestEntity.class, id, 1 ).equals( ver1 ); + assert getAuditReader().find( SecondaryNamingTestEntity.class, id, 2 ).equals( ver2 ); + } - @SuppressWarnings({"unchecked"}) - @Test - public void testTableNames() { - assert "sec_versions".equals(((Iterator) - getCfg().getClassMapping("org.hibernate.envers.test.integration.secondary.SecondaryNamingTestEntity_AUD") - .getJoinIterator()) - .next().getTable().getName()); - } + @SuppressWarnings({"unchecked"}) + @Test + public void testTableNames() { + assert "sec_versions".equals( + ((Iterator) + getCfg().getClassMapping( + "org.hibernate.envers.test.integration.secondary.SecondaryNamingTestEntity_AUD" + ) + .getJoinIterator()) + .next().getTable().getName() + ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/SecondaryNamingTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/SecondaryNamingTestEntity.java index d5434bbf2f..85b0d1e654 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/SecondaryNamingTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/SecondaryNamingTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.secondary; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -39,71 +40,81 @@ import org.hibernate.envers.SecondaryAuditTable; @SecondaryAuditTable(secondaryTableName = "secondary", secondaryAuditTableName = "sec_versions") @Audited public class SecondaryNamingTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String s1; + private String s1; - @Column(table = "secondary") - private String s2; + @Column(table = "secondary") + private String s2; - public SecondaryNamingTestEntity(Integer id, String s1, String s2) { - this.id = id; - this.s1 = s1; - this.s2 = s2; - } + public SecondaryNamingTestEntity(Integer id, String s1, String s2) { + this.id = id; + this.s1 = s1; + this.s2 = s2; + } - public SecondaryNamingTestEntity(String s1, String s2) { - this.s1 = s1; - this.s2 = s2; - } + public SecondaryNamingTestEntity(String s1, String s2) { + this.s1 = s1; + this.s2 = s2; + } - public SecondaryNamingTestEntity() { - } + public SecondaryNamingTestEntity() { + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getS1() { - return s1; - } + public String getS1() { + return s1; + } - public void setS1(String s1) { - this.s1 = s1; - } + public void setS1(String s1) { + this.s1 = s1; + } - public String getS2() { - return s2; - } + public String getS2() { + return s2; + } - public void setS2(String s2) { - this.s2 = s2; - } + public void setS2(String s2) { + this.s2 = s2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SecondaryNamingTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SecondaryNamingTestEntity) ) { + return false; + } - SecondaryNamingTestEntity that = (SecondaryNamingTestEntity) o; + SecondaryNamingTestEntity that = (SecondaryNamingTestEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (s1 != null ? !s1.equals(that.s1) : that.s1 != null) return false; - if (s2 != null ? !s2.equals(that.s2) : that.s2 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( s1 != null ? !s1.equals( that.s1 ) : that.s1 != null ) { + return false; + } + if ( s2 != null ? !s2.equals( that.s2 ) : that.s2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (s1 != null ? s1.hashCode() : 0); - result = 31 * result + (s2 != null ? s2.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (s1 != null ? s1.hashCode() : 0); + result = 31 * result + (s2 != null ? s2.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/SecondaryTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/SecondaryTestEntity.java index b6546179e1..dbc8cb3ad9 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/SecondaryTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/SecondaryTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.secondary; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -37,71 +38,81 @@ import org.hibernate.envers.Audited; @SecondaryTable(name = "secondary") @Audited public class SecondaryTestEntity { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String s1; + private String s1; - @Column(table = "secondary") - private String s2; + @Column(table = "secondary") + private String s2; - public SecondaryTestEntity(Integer id, String s1, String s2) { - this.id = id; - this.s1 = s1; - this.s2 = s2; - } + public SecondaryTestEntity(Integer id, String s1, String s2) { + this.id = id; + this.s1 = s1; + this.s2 = s2; + } - public SecondaryTestEntity(String s1, String s2) { - this.s1 = s1; - this.s2 = s2; - } + public SecondaryTestEntity(String s1, String s2) { + this.s1 = s1; + this.s2 = s2; + } - public SecondaryTestEntity() { - } + public SecondaryTestEntity() { + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getS1() { - return s1; - } + public String getS1() { + return s1; + } - public void setS1(String s1) { - this.s1 = s1; - } + public void setS1(String s1) { + this.s1 = s1; + } - public String getS2() { - return s2; - } + public String getS2() { + return s2; + } - public void setS2(String s2) { - this.s2 = s2; - } + public void setS2(String s2) { + this.s2 = s2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SecondaryTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SecondaryTestEntity) ) { + return false; + } - SecondaryTestEntity that = (SecondaryTestEntity) o; + SecondaryTestEntity that = (SecondaryTestEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (s1 != null ? !s1.equals(that.s1) : that.s1 != null) return false; - if (s2 != null ? !s2.equals(that.s2) : that.s2 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( s1 != null ? !s1.equals( that.s1 ) : that.s1 != null ) { + return false; + } + if ( s2 != null ? !s2.equals( that.s2 ) : that.s2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (s1 != null ? s1.hashCode() : 0); - result = 31 * result + (s2 != null ? s2.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (s1 != null ? s1.hashCode() : 0); + result = 31 * result + (s2 != null ? s2.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/ids/EmbIdSecondary.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/ids/EmbIdSecondary.java index acdc146bb0..add9e2dba7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/ids/EmbIdSecondary.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/ids/EmbIdSecondary.java @@ -23,73 +23,77 @@ */ package org.hibernate.envers.test.integration.secondary.ids; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Iterator; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.ids.EmbId; import org.hibernate.mapping.Join; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class EmbIdSecondary extends BaseEnversJPAFunctionalTestCase { - private EmbId id; + private EmbId id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SecondaryEmbIdTestEntity.class }; - } + return new Class[] {SecondaryEmbIdTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - id = new EmbId(1, 2); + @Test + @Priority(10) + public void initData() { + id = new EmbId( 1, 2 ); - SecondaryEmbIdTestEntity ste = new SecondaryEmbIdTestEntity(id, "a", "1"); + SecondaryEmbIdTestEntity ste = new SecondaryEmbIdTestEntity( id, "a", "1" ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - em.persist(ste); + em.persist( ste ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ste = em.find(SecondaryEmbIdTestEntity.class, ste.getId()); - ste.setS1("b"); - ste.setS2("2"); + ste = em.find( SecondaryEmbIdTestEntity.class, ste.getId() ); + ste.setS1( "b" ); + ste.setS2( "2" ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(SecondaryEmbIdTestEntity.class, id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( SecondaryEmbIdTestEntity.class, id ) ); + } - @Test - public void testHistoryOfId() { - SecondaryEmbIdTestEntity ver1 = new SecondaryEmbIdTestEntity(id, "a", "1"); - SecondaryEmbIdTestEntity ver2 = new SecondaryEmbIdTestEntity(id, "b", "2"); + @Test + public void testHistoryOfId() { + SecondaryEmbIdTestEntity ver1 = new SecondaryEmbIdTestEntity( id, "a", "1" ); + SecondaryEmbIdTestEntity ver2 = new SecondaryEmbIdTestEntity( id, "b", "2" ); - assert getAuditReader().find(SecondaryEmbIdTestEntity.class, id, 1).equals(ver1); - assert getAuditReader().find(SecondaryEmbIdTestEntity.class, id, 2).equals(ver2); - } + assert getAuditReader().find( SecondaryEmbIdTestEntity.class, id, 1 ).equals( ver1 ); + assert getAuditReader().find( SecondaryEmbIdTestEntity.class, id, 2 ).equals( ver2 ); + } - @SuppressWarnings({"unchecked"}) - @Test - public void testTableNames() { - assert "sec_embid_versions".equals(((Iterator) - getCfg().getClassMapping("org.hibernate.envers.test.integration.secondary.ids.SecondaryEmbIdTestEntity_AUD") - .getJoinIterator()) - .next().getTable().getName()); - } + @SuppressWarnings({"unchecked"}) + @Test + public void testTableNames() { + assert "sec_embid_versions".equals( + ((Iterator) + getCfg().getClassMapping( + "org.hibernate.envers.test.integration.secondary.ids.SecondaryEmbIdTestEntity_AUD" + ) + .getJoinIterator()) + .next().getTable().getName() + ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/ids/MulIdSecondary.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/ids/MulIdSecondary.java index e7f1c6ceaf..897eb03149 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/ids/MulIdSecondary.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/ids/MulIdSecondary.java @@ -23,73 +23,77 @@ */ package org.hibernate.envers.test.integration.secondary.ids; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.Iterator; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.ids.MulId; import org.hibernate.mapping.Join; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class MulIdSecondary extends BaseEnversJPAFunctionalTestCase { - private MulId id; + private MulId id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SecondaryMulIdTestEntity.class }; - } + return new Class[] {SecondaryMulIdTestEntity.class}; + } - @Test - @Priority(10) - public void initData() { - id = new MulId(1, 2); + @Test + @Priority(10) + public void initData() { + id = new MulId( 1, 2 ); - SecondaryMulIdTestEntity ste = new SecondaryMulIdTestEntity(id, "a", "1"); + SecondaryMulIdTestEntity ste = new SecondaryMulIdTestEntity( id, "a", "1" ); - // Revision 1 - EntityManager em = getEntityManager(); - em.getTransaction().begin(); + // Revision 1 + EntityManager em = getEntityManager(); + em.getTransaction().begin(); - em.persist(ste); + em.persist( ste ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); + // Revision 2 + em.getTransaction().begin(); - ste = em.find(SecondaryMulIdTestEntity.class, id); - ste.setS1("b"); - ste.setS2("2"); + ste = em.find( SecondaryMulIdTestEntity.class, id ); + ste.setS1( "b" ); + ste.setS2( "2" ); - em.getTransaction().commit(); - } + em.getTransaction().commit(); + } - @Test - public void testRevisionsCounts() { - assert Arrays.asList(1, 2).equals(getAuditReader().getRevisions(SecondaryMulIdTestEntity.class, id)); - } + @Test + public void testRevisionsCounts() { + assert Arrays.asList( 1, 2 ).equals( getAuditReader().getRevisions( SecondaryMulIdTestEntity.class, id ) ); + } - @Test - public void testHistoryOfId() { - SecondaryMulIdTestEntity ver1 = new SecondaryMulIdTestEntity(id, "a", "1"); - SecondaryMulIdTestEntity ver2 = new SecondaryMulIdTestEntity(id, "b", "2"); + @Test + public void testHistoryOfId() { + SecondaryMulIdTestEntity ver1 = new SecondaryMulIdTestEntity( id, "a", "1" ); + SecondaryMulIdTestEntity ver2 = new SecondaryMulIdTestEntity( id, "b", "2" ); - assert getAuditReader().find(SecondaryMulIdTestEntity.class, id, 1).equals(ver1); - assert getAuditReader().find(SecondaryMulIdTestEntity.class, id, 2).equals(ver2); - } + assert getAuditReader().find( SecondaryMulIdTestEntity.class, id, 1 ).equals( ver1 ); + assert getAuditReader().find( SecondaryMulIdTestEntity.class, id, 2 ).equals( ver2 ); + } - @SuppressWarnings({"unchecked"}) - @Test - public void testTableNames() { - assert "sec_mulid_versions".equals(((Iterator) - getCfg().getClassMapping("org.hibernate.envers.test.integration.secondary.ids.SecondaryMulIdTestEntity_AUD") - .getJoinIterator()) - .next().getTable().getName()); - } + @SuppressWarnings({"unchecked"}) + @Test + public void testTableNames() { + assert "sec_mulid_versions".equals( + ((Iterator) + getCfg().getClassMapping( + "org.hibernate.envers.test.integration.secondary.ids.SecondaryMulIdTestEntity_AUD" + ) + .getJoinIterator()) + .next().getTable().getName() + ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/ids/SecondaryEmbIdTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/ids/SecondaryEmbIdTestEntity.java index 482906c27a..27153f994a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/ids/SecondaryEmbIdTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/ids/SecondaryEmbIdTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.secondary.ids; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @@ -39,70 +40,80 @@ import org.hibernate.envers.test.entities.ids.EmbId; @SecondaryAuditTable(secondaryTableName = "secondary", secondaryAuditTableName = "sec_embid_versions") @Audited public class SecondaryEmbIdTestEntity { - @Id - private EmbId id; + @Id + private EmbId id; - private String s1; + private String s1; - @Column(table = "secondary") - private String s2; + @Column(table = "secondary") + private String s2; - public SecondaryEmbIdTestEntity(EmbId id, String s1, String s2) { - this.id = id; - this.s1 = s1; - this.s2 = s2; - } + public SecondaryEmbIdTestEntity(EmbId id, String s1, String s2) { + this.id = id; + this.s1 = s1; + this.s2 = s2; + } - public SecondaryEmbIdTestEntity(String s1, String s2) { - this.s1 = s1; - this.s2 = s2; - } + public SecondaryEmbIdTestEntity(String s1, String s2) { + this.s1 = s1; + this.s2 = s2; + } - public SecondaryEmbIdTestEntity() { - } + public SecondaryEmbIdTestEntity() { + } - public EmbId getId() { - return id; - } + public EmbId getId() { + return id; + } - public void setId(EmbId id) { - this.id = id; - } + public void setId(EmbId id) { + this.id = id; + } - public String getS1() { - return s1; - } + public String getS1() { + return s1; + } - public void setS1(String s1) { - this.s1 = s1; - } + public void setS1(String s1) { + this.s1 = s1; + } - public String getS2() { - return s2; - } + public String getS2() { + return s2; + } - public void setS2(String s2) { - this.s2 = s2; - } + public void setS2(String s2) { + this.s2 = s2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SecondaryEmbIdTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SecondaryEmbIdTestEntity) ) { + return false; + } - SecondaryEmbIdTestEntity that = (SecondaryEmbIdTestEntity) o; + SecondaryEmbIdTestEntity that = (SecondaryEmbIdTestEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (s1 != null ? !s1.equals(that.s1) : that.s1 != null) return false; - if (s2 != null ? !s2.equals(that.s2) : that.s2 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( s1 != null ? !s1.equals( that.s1 ) : that.s1 != null ) { + return false; + } + if ( s2 != null ? !s2.equals( that.s2 ) : that.s2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (s1 != null ? s1.hashCode() : 0); - result = 31 * result + (s2 != null ? s2.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (s1 != null ? s1.hashCode() : 0); + result = 31 * result + (s2 != null ? s2.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/ids/SecondaryMulIdTestEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/ids/SecondaryMulIdTestEntity.java index f42da96e67..cdda6a50e5 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/ids/SecondaryMulIdTestEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/secondary/ids/SecondaryMulIdTestEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.secondary.ids; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @@ -41,84 +42,96 @@ import org.hibernate.envers.test.entities.ids.MulId; @Audited @IdClass(MulId.class) public class SecondaryMulIdTestEntity { - @Id - private Integer id1; + @Id + private Integer id1; - @Id - private Integer id2; + @Id + private Integer id2; - private String s1; + private String s1; - @Column(table = "secondary") - private String s2; + @Column(table = "secondary") + private String s2; - public SecondaryMulIdTestEntity(MulId id, String s1, String s2) { - this.id1 = id.getId1(); - this.id2 = id.getId2(); - this.s1 = s1; - this.s2 = s2; - } + public SecondaryMulIdTestEntity(MulId id, String s1, String s2) { + this.id1 = id.getId1(); + this.id2 = id.getId2(); + this.s1 = s1; + this.s2 = s2; + } - public SecondaryMulIdTestEntity(String s1, String s2) { - this.s1 = s1; - this.s2 = s2; - } + public SecondaryMulIdTestEntity(String s1, String s2) { + this.s1 = s1; + this.s2 = s2; + } - public SecondaryMulIdTestEntity() { - } + public SecondaryMulIdTestEntity() { + } - public Integer getId1() { - return id1; - } + public Integer getId1() { + return id1; + } - public void setId1(Integer id1) { - this.id1 = id1; - } + public void setId1(Integer id1) { + this.id1 = id1; + } - public Integer getId2() { - return id2; - } + public Integer getId2() { + return id2; + } - public void setId2(Integer id2) { - this.id2 = id2; - } + public void setId2(Integer id2) { + this.id2 = id2; + } - public String getS1() { - return s1; - } + public String getS1() { + return s1; + } - public void setS1(String s1) { - this.s1 = s1; - } + public void setS1(String s1) { + this.s1 = s1; + } - public String getS2() { - return s2; - } + public String getS2() { + return s2; + } - public void setS2(String s2) { - this.s2 = s2; - } + public void setS2(String s2) { + this.s2 = s2; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SecondaryMulIdTestEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof SecondaryMulIdTestEntity) ) { + return false; + } - SecondaryMulIdTestEntity that = (SecondaryMulIdTestEntity) o; + SecondaryMulIdTestEntity that = (SecondaryMulIdTestEntity) o; - if (id1 != null ? !id1.equals(that.id1) : that.id1 != null) return false; - if (id2 != null ? !id2.equals(that.id2) : that.id2 != null) return false; - if (s1 != null ? !s1.equals(that.s1) : that.s1 != null) return false; - if (s2 != null ? !s2.equals(that.s2) : that.s2 != null) return false; + if ( id1 != null ? !id1.equals( that.id1 ) : that.id1 != null ) { + return false; + } + if ( id2 != null ? !id2.equals( that.id2 ) : that.id2 != null ) { + return false; + } + if ( s1 != null ? !s1.equals( that.s1 ) : that.s1 != null ) { + return false; + } + if ( s2 != null ? !s2.equals( that.s2 ) : that.s2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id1 != null ? id1.hashCode() : 0); - result = 31 * result + (id2 != null ? id2.hashCode() : 0); - result = 31 * result + (s1 != null ? s1.hashCode() : 0); - result = 31 * result + (s2 != null ? s2.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id1 != null ? id1.hashCode() : 0); + result = 31 * result + (id2 != null ? id2.hashCode() : 0); + result = 31 * result + (s1 != null ? s1.hashCode() : 0); + result = 31 * result + (s2 != null ? s2.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/serialization/SerializingCollection.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/serialization/SerializingCollection.java index 2002c0cbc0..d42717173e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/serialization/SerializingCollection.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/serialization/SerializingCollection.java @@ -23,83 +23,85 @@ */ package org.hibernate.envers.test.integration.serialization; +import javax.persistence.EntityManager; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.onetomany.CollectionRefEdEntity; import org.hibernate.envers.test.entities.onetomany.CollectionRefIngEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) */ public class SerializingCollection extends BaseEnversJPAFunctionalTestCase { - private Integer ed1_id; - private Integer ing1_id; + private Integer ed1_id; + private Integer ing1_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { CollectionRefEdEntity.class, CollectionRefIngEntity.class }; - } + return new Class[] {CollectionRefEdEntity.class, CollectionRefIngEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - CollectionRefEdEntity ed1 = new CollectionRefEdEntity(1, "data_ed_1"); + CollectionRefEdEntity ed1 = new CollectionRefEdEntity( 1, "data_ed_1" ); - CollectionRefIngEntity ing1 = new CollectionRefIngEntity(3, "data_ing_1", ed1); + CollectionRefIngEntity ing1 = new CollectionRefIngEntity( 3, "data_ing_1", ed1 ); - // Revision 1 - em.getTransaction().begin(); + // Revision 1 + em.getTransaction().begin(); - em.persist(ed1); - em.persist(ing1); + em.persist( ed1 ); + em.persist( ing1 ); - em.getTransaction().commit(); + em.getTransaction().commit(); - // + // - ed1_id = ed1.getId(); - ing1_id = ing1.getId(); - } + ed1_id = ed1.getId(); + ing1_id = ing1.getId(); + } - @Test - public void testDetach()throws Exception { - CollectionRefIngEntity ing1 = getEntityManager().find(CollectionRefIngEntity.class, ing1_id); - CollectionRefEdEntity rev1 = getAuditReader().find(CollectionRefEdEntity.class, ed1_id, 1); + @Test + public void testDetach() throws Exception { + CollectionRefIngEntity ing1 = getEntityManager().find( CollectionRefIngEntity.class, ing1_id ); + CollectionRefEdEntity rev1 = getAuditReader().find( CollectionRefEdEntity.class, ed1_id, 1 ); // First forcing loading of the collection assert rev1.getReffering().size() == 1; // Now serializing and de-serializing the - rev1 = serializeDeserialize(rev1); + rev1 = serializeDeserialize( rev1 ); // And checking the colleciton again - assert rev1.getReffering().contains(ing1); - assert rev1.getReffering().size() == 1; + assert rev1.getReffering().contains( ing1 ); + assert rev1.getReffering().size() == 1; - } + } @SuppressWarnings({"unchecked"}) public static T serializeDeserialize(T o) throws Exception { - if (o == null) return null; + if ( o == null ) { + return null; + } ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(o); + ObjectOutputStream oos = new ObjectOutputStream( baos ); + oos.writeObject( o ); byte[] buffer = baos.toByteArray(); baos.close(); - ByteArrayInputStream bais = new ByteArrayInputStream(buffer); - ObjectInputStream ois = new ObjectInputStream(bais); - return (T) ois.readObject(); + ByteArrayInputStream bais = new ByteArrayInputStream( buffer ); + ObjectInputStream ois = new ObjectInputStream( bais ); + return (T) ois.readObject(); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/strategy/ValidityAuditStrategyManyToManyTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/strategy/ValidityAuditStrategyManyToManyTest.java index 2e96ea9a7f..a424925d89 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/strategy/ValidityAuditStrategyManyToManyTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/strategy/ValidityAuditStrategyManyToManyTest.java @@ -1,11 +1,9 @@ package org.hibernate.envers.test.integration.strategy; +import javax.persistence.EntityManager; import java.util.Arrays; import java.util.HashSet; import java.util.Map; -import javax.persistence.EntityManager; - -import org.junit.Test; import org.hibernate.envers.configuration.EnversSettings; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -13,6 +11,8 @@ import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.manytomany.SetOwnedEntity; import org.hibernate.envers.test.entities.manytomany.SetOwningEntity; +import org.junit.Test; + import static org.junit.Assert.assertEquals; /** @@ -26,143 +26,143 @@ import static org.junit.Assert.assertEquals; */ public class ValidityAuditStrategyManyToManyTest extends BaseEnversJPAFunctionalTestCase { - private Integer ing_id; + private Integer ing_id; - private Integer ed_id; + private Integer ed_id; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { SetOwningEntity.class, SetOwnedEntity.class }; - } + return new Class[] {SetOwningEntity.class, SetOwnedEntity.class}; + } @Override protected void addConfigOptions(Map options) { - options.put(EnversSettings.AUDIT_STRATEGY, "org.hibernate.envers.strategy.ValidityAuditStrategy"); + options.put( EnversSettings.AUDIT_STRATEGY, "org.hibernate.envers.strategy.ValidityAuditStrategy" ); } @Test - @Priority(10) - public void initData() { - final EntityManager em = getEntityManager(); + @Priority(10) + public void initData() { + final EntityManager em = getEntityManager(); - final SetOwningEntity setOwningEntity = new SetOwningEntity(1, "parent"); - final SetOwnedEntity setOwnedEntity = new SetOwnedEntity(2, "child"); + final SetOwningEntity setOwningEntity = new SetOwningEntity( 1, "parent" ); + final SetOwnedEntity setOwnedEntity = new SetOwnedEntity( 2, "child" ); - // Revision 1: Initial persist - em.getTransaction().begin(); + // Revision 1: Initial persist + em.getTransaction().begin(); - em.persist(setOwningEntity); - em.persist(setOwnedEntity); + em.persist( setOwningEntity ); + em.persist( setOwnedEntity ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - ing_id = setOwningEntity.getId(); - ed_id = setOwnedEntity.getId(); - } + ing_id = setOwningEntity.getId(); + ed_id = setOwnedEntity.getId(); + } - @Test - @Priority(5) - public void testMultipleAddAndRemove() { - final EntityManager em = getEntityManager(); + @Test + @Priority(5) + public void testMultipleAddAndRemove() { + final EntityManager em = getEntityManager(); - // Revision 2: add child for first time - em.getTransaction().begin(); + // Revision 2: add child for first time + em.getTransaction().begin(); - SetOwningEntity owningEntity = getEntityManager().find(SetOwningEntity.class, ing_id); - SetOwnedEntity ownedEntity = getEntityManager().find(SetOwnedEntity.class, ed_id); + SetOwningEntity owningEntity = getEntityManager().find( SetOwningEntity.class, ing_id ); + SetOwnedEntity ownedEntity = getEntityManager().find( SetOwnedEntity.class, ed_id ); - owningEntity.setReferences(new HashSet()); - owningEntity.getReferences().add(ownedEntity); + owningEntity.setReferences( new HashSet() ); + owningEntity.getReferences().add( ownedEntity ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 3: remove child - em.getTransaction().begin(); + // Revision 3: remove child + em.getTransaction().begin(); - owningEntity = getEntityManager().find(SetOwningEntity.class, ing_id); - ownedEntity = getEntityManager().find(SetOwnedEntity.class, ed_id); + owningEntity = getEntityManager().find( SetOwningEntity.class, ing_id ); + ownedEntity = getEntityManager().find( SetOwnedEntity.class, ed_id ); - owningEntity.getReferences().remove(ownedEntity); + owningEntity.getReferences().remove( ownedEntity ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 4: add child again - em.getTransaction().begin(); + // Revision 4: add child again + em.getTransaction().begin(); - owningEntity = getEntityManager().find(SetOwningEntity.class, ing_id); - ownedEntity = getEntityManager().find(SetOwnedEntity.class, ed_id); + owningEntity = getEntityManager().find( SetOwningEntity.class, ing_id ); + ownedEntity = getEntityManager().find( SetOwnedEntity.class, ed_id ); - owningEntity.getReferences().add(ownedEntity); + owningEntity.getReferences().add( ownedEntity ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // Revision 5: remove child again - em.getTransaction().begin(); + // Revision 5: remove child again + em.getTransaction().begin(); - owningEntity = getEntityManager().find(SetOwningEntity.class, ing_id); - ownedEntity = getEntityManager().find(SetOwnedEntity.class, ed_id); + owningEntity = getEntityManager().find( SetOwningEntity.class, ing_id ); + ownedEntity = getEntityManager().find( SetOwnedEntity.class, ed_id ); - owningEntity.getReferences().remove(ownedEntity); + owningEntity.getReferences().remove( ownedEntity ); - em.getTransaction().commit(); - em.clear(); + em.getTransaction().commit(); + em.clear(); - // now the set owning entity list should be empty again - owningEntity = getEntityManager().find(SetOwningEntity.class, ing_id); - assertEquals(owningEntity.getReferences().size(), 0); - } + // now the set owning entity list should be empty again + owningEntity = getEntityManager().find( SetOwningEntity.class, ing_id ); + assertEquals( owningEntity.getReferences().size(), 0 ); + } - @Test + @Test public void testRevisionsCounts() { - assertEquals(getAuditReader().getRevisions(SetOwningEntity.class, ing_id), Arrays.asList(1, 2, 3, 4, 5)); - assertEquals(getAuditReader().getRevisions(SetOwnedEntity.class, ed_id), Arrays.asList(1, 2, 3, 4, 5)); + assertEquals( getAuditReader().getRevisions( SetOwningEntity.class, ing_id ), Arrays.asList( 1, 2, 3, 4, 5 ) ); + assertEquals( getAuditReader().getRevisions( SetOwnedEntity.class, ed_id ), Arrays.asList( 1, 2, 3, 4, 5 ) ); } @Test public void testHistoryOfIng1() { SetOwningEntity ver_empty = createOwningEntity(); - SetOwningEntity ver_child = createOwningEntity(new SetOwnedEntity(ed_id, "child")); + SetOwningEntity ver_child = createOwningEntity( new SetOwnedEntity( ed_id, "child" ) ); - assertEquals(getAuditReader().find(SetOwningEntity.class, ing_id, 1), ver_empty); - assertEquals(getAuditReader().find(SetOwningEntity.class, ing_id, 2), ver_child); - assertEquals(getAuditReader().find(SetOwningEntity.class, ing_id, 3), ver_empty); - assertEquals(getAuditReader().find(SetOwningEntity.class, ing_id, 4), ver_child); - assertEquals(getAuditReader().find(SetOwningEntity.class, ing_id, 5), ver_empty); + assertEquals( getAuditReader().find( SetOwningEntity.class, ing_id, 1 ), ver_empty ); + assertEquals( getAuditReader().find( SetOwningEntity.class, ing_id, 2 ), ver_child ); + assertEquals( getAuditReader().find( SetOwningEntity.class, ing_id, 3 ), ver_empty ); + assertEquals( getAuditReader().find( SetOwningEntity.class, ing_id, 4 ), ver_child ); + assertEquals( getAuditReader().find( SetOwningEntity.class, ing_id, 5 ), ver_empty ); } - @Test + @Test public void testHistoryOfEd1() { SetOwnedEntity ver_empty = createOwnedEntity(); - SetOwnedEntity ver_child = createOwnedEntity(new SetOwningEntity(ing_id, "parent")); + SetOwnedEntity ver_child = createOwnedEntity( new SetOwningEntity( ing_id, "parent" ) ); - assertEquals(getAuditReader().find(SetOwnedEntity.class, ed_id, 1), ver_empty); - assertEquals(getAuditReader().find(SetOwnedEntity.class, ed_id, 2), ver_child); - assertEquals(getAuditReader().find(SetOwnedEntity.class, ed_id, 3), ver_empty); - assertEquals(getAuditReader().find(SetOwnedEntity.class, ed_id, 4), ver_child); - assertEquals(getAuditReader().find(SetOwnedEntity.class, ed_id, 5), ver_empty); + assertEquals( getAuditReader().find( SetOwnedEntity.class, ed_id, 1 ), ver_empty ); + assertEquals( getAuditReader().find( SetOwnedEntity.class, ed_id, 2 ), ver_child ); + assertEquals( getAuditReader().find( SetOwnedEntity.class, ed_id, 3 ), ver_empty ); + assertEquals( getAuditReader().find( SetOwnedEntity.class, ed_id, 4 ), ver_child ); + assertEquals( getAuditReader().find( SetOwnedEntity.class, ed_id, 5 ), ver_empty ); } - private SetOwningEntity createOwningEntity(SetOwnedEntity... owned) { - SetOwningEntity result = new SetOwningEntity(ing_id, "parent"); - result.setReferences(new HashSet()); - for (SetOwnedEntity setOwnedEntity : owned) { - result.getReferences().add(setOwnedEntity); - } + private SetOwningEntity createOwningEntity(SetOwnedEntity... owned) { + SetOwningEntity result = new SetOwningEntity( ing_id, "parent" ); + result.setReferences( new HashSet() ); + for ( SetOwnedEntity setOwnedEntity : owned ) { + result.getReferences().add( setOwnedEntity ); + } - return result; - } + return result; + } - private SetOwnedEntity createOwnedEntity(SetOwningEntity... owning) { - SetOwnedEntity result = new SetOwnedEntity(ed_id, "child"); - result.setReferencing(new HashSet()); - for (SetOwningEntity setOwningEntity : owning) { - result.getReferencing().add(setOwningEntity); - } + private SetOwnedEntity createOwnedEntity(SetOwningEntity... owning) { + SetOwnedEntity result = new SetOwnedEntity( ed_id, "child" ); + result.setReferencing( new HashSet() ); + for ( SetOwningEntity setOwningEntity : owning ) { + result.getReferencing().add( setOwningEntity ); + } - return result; - } + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/strategy/ValidityAuditStrategyRevEndTestCustomRevEnt.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/strategy/ValidityAuditStrategyRevEndTestCustomRevEnt.java index d0d6007575..214f57f724 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/strategy/ValidityAuditStrategyRevEndTestCustomRevEnt.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/strategy/ValidityAuditStrategyRevEndTestCustomRevEnt.java @@ -23,6 +23,8 @@ */ package org.hibernate.envers.test.integration.strategy; +import javax.persistence.EntityManager; +import javax.persistence.Query; import java.sql.Types; import java.util.Arrays; import java.util.Date; @@ -30,10 +32,6 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import javax.persistence.EntityManager; -import javax.persistence.Query; - -import org.junit.Test; import org.hibernate.Session; import org.hibernate.envers.configuration.EnversSettings; @@ -46,10 +44,12 @@ import org.hibernate.envers.test.entities.manytomany.sametable.ParentEntity; import org.hibernate.envers.test.entities.reventity.CustomDateRevEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Test; + /** * Test which checks that the revision end timestamp is correctly set for * {@link ValidityAuditStrategy}. - * + * * @author Erik-Berndt Scheper */ public class ValidityAuditStrategyRevEndTestCustomRevEnt extends BaseEnversJPAFunctionalTestCase { @@ -75,14 +75,14 @@ public class ValidityAuditStrategyRevEndTestCustomRevEnt extends BaseEnversJPAFu @Override protected void addConfigOptions(Map options) { - super.addConfigOptions( options ); - options.put(EnversSettings.AUDIT_STRATEGY, "org.hibernate.envers.strategy.ValidityAuditStrategy"); - options.put(EnversSettings.AUDIT_STRATEGY_VALIDITY_STORE_REVEND_TIMESTAMP, "true"); - options.put(EnversSettings.AUDIT_STRATEGY_VALIDITY_REVEND_TIMESTAMP_FIELD_NAME, revendTimestampColumName); - } + super.addConfigOptions( options ); + options.put( EnversSettings.AUDIT_STRATEGY, "org.hibernate.envers.strategy.ValidityAuditStrategy" ); + options.put( EnversSettings.AUDIT_STRATEGY_VALIDITY_STORE_REVEND_TIMESTAMP, "true" ); + options.put( EnversSettings.AUDIT_STRATEGY_VALIDITY_REVEND_TIMESTAMP_FIELD_NAME, revendTimestampColumName ); + } @Test - @Priority(10) + @Priority(10) public void initData() { EntityManager em = getEntityManager(); @@ -91,45 +91,47 @@ public class ValidityAuditStrategyRevEndTestCustomRevEnt extends BaseEnversJPAFu // to allow this. em.getTransaction().begin(); Session session = (Session) em.getDelegate(); - session.createSQLQuery("DROP TABLE children").executeUpdate(); + session.createSQLQuery( "DROP TABLE children" ).executeUpdate(); session .createSQLQuery( - "CREATE TABLE children ( parent_id " + getDialect().getTypeName(Types.INTEGER) + - ", child1_id " + getDialect().getTypeName(Types.INTEGER) + " NULL" + - ", child2_id " + getDialect().getTypeName(Types.INTEGER) + " NULL )") + "CREATE TABLE children ( parent_id " + getDialect().getTypeName( Types.INTEGER ) + + ", child1_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL" + + ", child2_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL )" + ) .executeUpdate(); - session.createSQLQuery("DROP TABLE children_AUD").executeUpdate(); + session.createSQLQuery( "DROP TABLE children_AUD" ).executeUpdate(); session .createSQLQuery( - "CREATE TABLE children_AUD ( REV " + getDialect().getTypeName(Types.INTEGER) + " NOT NULL" + - ", REVEND " + getDialect().getTypeName(Types.INTEGER) + - ", " + revendTimestampColumName + " " + getDialect().getTypeName(Types.TIMESTAMP) + - ", REVTYPE " + getDialect().getTypeName(Types.TINYINT) + - ", parent_id " + getDialect().getTypeName(Types.INTEGER) + - ", child1_id " + getDialect().getTypeName(Types.INTEGER) + " NULL" + - ", child2_id " + getDialect().getTypeName(Types.INTEGER) + " NULL )") + "CREATE TABLE children_AUD ( REV " + getDialect().getTypeName( Types.INTEGER ) + " NOT NULL" + + ", REVEND " + getDialect().getTypeName( Types.INTEGER ) + + ", " + revendTimestampColumName + " " + getDialect().getTypeName( Types.TIMESTAMP ) + + ", REVTYPE " + getDialect().getTypeName( Types.TINYINT ) + + ", parent_id " + getDialect().getTypeName( Types.INTEGER ) + + ", child1_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL" + + ", child2_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL )" + ) .executeUpdate(); em.getTransaction().commit(); em.clear(); - ParentEntity p1 = new ParentEntity("parent_1"); - ParentEntity p2 = new ParentEntity("parent_2"); + ParentEntity p1 = new ParentEntity( "parent_1" ); + ParentEntity p2 = new ParentEntity( "parent_2" ); - Child1Entity c1_1 = new Child1Entity("child1_1"); - Child1Entity c1_2 = new Child1Entity("child1_2"); + Child1Entity c1_1 = new Child1Entity( "child1_1" ); + Child1Entity c1_2 = new Child1Entity( "child1_2" ); - Child2Entity c2_1 = new Child2Entity("child2_1"); - Child2Entity c2_2 = new Child2Entity("child2_2"); + Child2Entity c2_1 = new Child2Entity( "child2_1" ); + Child2Entity c2_2 = new Child2Entity( "child2_2" ); // Revision 1 em.getTransaction().begin(); - em.persist(p1); - em.persist(p2); - em.persist(c1_1); - em.persist(c1_2); - em.persist(c2_1); - em.persist(c2_2); + em.persist( p1 ); + em.persist( p2 ); + em.persist( c1_1 ); + em.persist( c1_2 ); + em.persist( c2_1 ); + em.persist( c2_2 ); em.getTransaction().commit(); em.clear(); @@ -138,13 +140,13 @@ public class ValidityAuditStrategyRevEndTestCustomRevEnt extends BaseEnversJPAFu em.getTransaction().begin(); - p1 = em.find(ParentEntity.class, p1.getId()); - p2 = em.find(ParentEntity.class, p2.getId()); - c1_1 = em.find(Child1Entity.class, c1_1.getId()); - c2_1 = em.find(Child2Entity.class, c2_1.getId()); + p1 = em.find( ParentEntity.class, p1.getId() ); + p2 = em.find( ParentEntity.class, p2.getId() ); + c1_1 = em.find( Child1Entity.class, c1_1.getId() ); + c2_1 = em.find( Child2Entity.class, c2_1.getId() ); - p1.getChildren1().add(c1_1); - p2.getChildren2().add(c2_1); + p1.getChildren1().add( c1_1 ); + p2.getChildren2().add( c2_1 ); em.getTransaction().commit(); em.clear(); @@ -152,16 +154,16 @@ public class ValidityAuditStrategyRevEndTestCustomRevEnt extends BaseEnversJPAFu // Revision 3 - (p1: c1_1, c1_2, c2_2, p2: c1_1, c2_1) em.getTransaction().begin(); - p1 = em.find(ParentEntity.class, p1.getId()); - p2 = em.find(ParentEntity.class, p2.getId()); - c1_1 = em.find(Child1Entity.class, c1_1.getId()); - c1_2 = em.find(Child1Entity.class, c1_2.getId()); - c2_2 = em.find(Child2Entity.class, c2_2.getId()); + p1 = em.find( ParentEntity.class, p1.getId() ); + p2 = em.find( ParentEntity.class, p2.getId() ); + c1_1 = em.find( Child1Entity.class, c1_1.getId() ); + c1_2 = em.find( Child1Entity.class, c1_2.getId() ); + c2_2 = em.find( Child2Entity.class, c2_2.getId() ); - p1.getChildren1().add(c1_2); - p1.getChildren2().add(c2_2); + p1.getChildren1().add( c1_2 ); + p1.getChildren2().add( c2_2 ); - p2.getChildren1().add(c1_1); + p2.getChildren1().add( c1_1 ); em.getTransaction().commit(); em.clear(); @@ -169,13 +171,13 @@ public class ValidityAuditStrategyRevEndTestCustomRevEnt extends BaseEnversJPAFu // Revision 4 - (p1: c1_2, c2_2, p2: c1_1, c2_1, c2_2) em.getTransaction().begin(); - p1 = em.find(ParentEntity.class, p1.getId()); - p2 = em.find(ParentEntity.class, p2.getId()); - c1_1 = em.find(Child1Entity.class, c1_1.getId()); - c2_2 = em.find(Child2Entity.class, c2_2.getId()); + p1 = em.find( ParentEntity.class, p1.getId() ); + p2 = em.find( ParentEntity.class, p2.getId() ); + c1_1 = em.find( Child1Entity.class, c1_1.getId() ); + c2_2 = em.find( Child2Entity.class, c2_2.getId() ); - p1.getChildren1().remove(c1_1); - p2.getChildren2().add(c2_2); + p1.getChildren1().remove( c1_1 ); + p2.getChildren2().add( c2_2 ); em.getTransaction().commit(); em.clear(); @@ -183,13 +185,13 @@ public class ValidityAuditStrategyRevEndTestCustomRevEnt extends BaseEnversJPAFu // Revision 5 - (p1: c2_2, p2: c1_1, c2_1) em.getTransaction().begin(); - p1 = em.find(ParentEntity.class, p1.getId()); - p2 = em.find(ParentEntity.class, p2.getId()); - c1_2 = em.find(Child1Entity.class, c1_2.getId()); - c2_2 = em.find(Child2Entity.class, c2_2.getId()); + p1 = em.find( ParentEntity.class, p1.getId() ); + p2 = em.find( ParentEntity.class, p2.getId() ); + c1_2 = em.find( Child1Entity.class, c1_2.getId() ); + c2_2 = em.find( Child2Entity.class, c2_2.getId() ); - c2_2.getParents().remove(p2); - c1_2.getParents().remove(p1); + c2_2.getParents().remove( p2 ); + c1_2.getParents().remove( p1 ); em.getTransaction().commit(); em.clear(); @@ -204,52 +206,72 @@ public class ValidityAuditStrategyRevEndTestCustomRevEnt extends BaseEnversJPAFu c2_2_id = c2_2.getId(); Set revisionNumbers = new HashSet(); - revisionNumbers.addAll(Arrays.asList(1, 2, 3, 4, 5)); - revisions = getAuditReader().findRevisions(CustomDateRevEntity.class, - revisionNumbers); + revisionNumbers.addAll( Arrays.asList( 1, 2, 3, 4, 5 ) ); + revisions = getAuditReader().findRevisions( + CustomDateRevEntity.class, + revisionNumbers + ); assert revisions.size() == 5; } @Test public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3, 4).equals( - getAuditReader().getRevisions(ParentEntity.class, p1_id)); - assert Arrays.asList(1, 2, 3, 4).equals( - getAuditReader().getRevisions(ParentEntity.class, p2_id)); + assert Arrays.asList( 1, 2, 3, 4 ).equals( + getAuditReader().getRevisions( ParentEntity.class, p1_id ) + ); + assert Arrays.asList( 1, 2, 3, 4 ).equals( + getAuditReader().getRevisions( ParentEntity.class, p2_id ) + ); - assert Arrays.asList(1).equals( - getAuditReader().getRevisions(Child1Entity.class, c1_1_id)); - assert Arrays.asList(1, 5).equals( - getAuditReader().getRevisions(Child1Entity.class, c1_2_id)); + assert Arrays.asList( 1 ).equals( + getAuditReader().getRevisions( Child1Entity.class, c1_1_id ) + ); + assert Arrays.asList( 1, 5 ).equals( + getAuditReader().getRevisions( Child1Entity.class, c1_2_id ) + ); - assert Arrays.asList(1).equals( - getAuditReader().getRevisions(Child2Entity.class, c2_1_id)); - assert Arrays.asList(1, 5).equals( - getAuditReader().getRevisions(Child2Entity.class, c2_2_id)); + assert Arrays.asList( 1 ).equals( + getAuditReader().getRevisions( Child2Entity.class, c2_1_id ) + ); + assert Arrays.asList( 1, 5 ).equals( + getAuditReader().getRevisions( Child2Entity.class, c2_2_id ) + ); } @Test public void testAllRevEndTimeStamps() { - List> p1RevList = getRevisions(ParentEntity.class, - p1_id); - List> p2RevList = getRevisions(ParentEntity.class, - p2_id); - List> c1_1_List = getRevisions(Child1Entity.class, - c1_1_id); - List> c1_2_List = getRevisions(Child1Entity.class, - c1_2_id); - List> c2_1_List = getRevisions(Child2Entity.class, - c2_1_id); - List> c2_2_List = getRevisions(Child2Entity.class, - c2_2_id); + List> p1RevList = getRevisions( + ParentEntity.class, + p1_id + ); + List> p2RevList = getRevisions( + ParentEntity.class, + p2_id + ); + List> c1_1_List = getRevisions( + Child1Entity.class, + c1_1_id + ); + List> c1_2_List = getRevisions( + Child1Entity.class, + c1_2_id + ); + List> c2_1_List = getRevisions( + Child2Entity.class, + c2_1_id + ); + List> c2_2_List = getRevisions( + Child2Entity.class, + c2_2_id + ); - verifyRevEndTimeStamps("ParentEntity: " + p1_id, p1RevList); - verifyRevEndTimeStamps("ParentEntity: " + p2_id, p2RevList); - verifyRevEndTimeStamps("Child1Entity: " + c1_1_id, c1_1_List); - verifyRevEndTimeStamps("Child1Entity: " + c1_2_id, c1_2_List); - verifyRevEndTimeStamps("Child2Entity: " + c2_1_id, c2_1_List); - verifyRevEndTimeStamps("Child2Entity: " + c2_2_id, c2_2_List); + verifyRevEndTimeStamps( "ParentEntity: " + p1_id, p1RevList ); + verifyRevEndTimeStamps( "ParentEntity: " + p2_id, p2RevList ); + verifyRevEndTimeStamps( "Child1Entity: " + c1_1_id, c1_1_List ); + verifyRevEndTimeStamps( "Child1Entity: " + c1_2_id, c1_2_List ); + verifyRevEndTimeStamps( "Child2Entity: " + c2_1_id, c2_1_List ); + verifyRevEndTimeStamps( "Child2Entity: " + c2_2_id, c2_2_List ); } @@ -257,148 +279,188 @@ public class ValidityAuditStrategyRevEndTestCustomRevEnt extends BaseEnversJPAFu public void testHistoryOfParent1() { Child1Entity c1_1 = getEntityManager() - .find(Child1Entity.class, c1_1_id); + .find( Child1Entity.class, c1_1_id ); Child1Entity c1_2 = getEntityManager() - .find(Child1Entity.class, c1_2_id); + .find( Child1Entity.class, c1_2_id ); Child2Entity c2_2 = getEntityManager() - .find(Child2Entity.class, c2_2_id); + .find( Child2Entity.class, c2_2_id ); - ParentEntity rev1 = getAuditReader().find(ParentEntity.class, p1_id, 1); - ParentEntity rev2 = getAuditReader().find(ParentEntity.class, p1_id, 2); - ParentEntity rev3 = getAuditReader().find(ParentEntity.class, p1_id, 3); - ParentEntity rev4 = getAuditReader().find(ParentEntity.class, p1_id, 4); - ParentEntity rev5 = getAuditReader().find(ParentEntity.class, p1_id, 5); + ParentEntity rev1 = getAuditReader().find( ParentEntity.class, p1_id, 1 ); + ParentEntity rev2 = getAuditReader().find( ParentEntity.class, p1_id, 2 ); + ParentEntity rev3 = getAuditReader().find( ParentEntity.class, p1_id, 3 ); + ParentEntity rev4 = getAuditReader().find( ParentEntity.class, p1_id, 4 ); + ParentEntity rev5 = getAuditReader().find( ParentEntity.class, p1_id, 5 ); - assert TestTools.checkList(rev1.getChildren1()); - assert TestTools.checkList(rev2.getChildren1(), c1_1); - assert TestTools.checkList(rev3.getChildren1(), c1_1, c1_2); - assert TestTools.checkList(rev4.getChildren1(), c1_2); - assert TestTools.checkList(rev5.getChildren1()); + assert TestTools.checkList( rev1.getChildren1() ); + assert TestTools.checkList( rev2.getChildren1(), c1_1 ); + assert TestTools.checkList( rev3.getChildren1(), c1_1, c1_2 ); + assert TestTools.checkList( rev4.getChildren1(), c1_2 ); + assert TestTools.checkList( rev5.getChildren1() ); - assert TestTools.checkList(rev1.getChildren2()); - assert TestTools.checkList(rev2.getChildren2()); - assert TestTools.checkList(rev3.getChildren2(), c2_2); - assert TestTools.checkList(rev4.getChildren2(), c2_2); - assert TestTools.checkList(rev5.getChildren2(), c2_2); + assert TestTools.checkList( rev1.getChildren2() ); + assert TestTools.checkList( rev2.getChildren2() ); + assert TestTools.checkList( rev3.getChildren2(), c2_2 ); + assert TestTools.checkList( rev4.getChildren2(), c2_2 ); + assert TestTools.checkList( rev5.getChildren2(), c2_2 ); } @Test public void testHistoryOfParent2() { Child1Entity c1_1 = getEntityManager() - .find(Child1Entity.class, c1_1_id); + .find( Child1Entity.class, c1_1_id ); Child2Entity c2_1 = getEntityManager() - .find(Child2Entity.class, c2_1_id); + .find( Child2Entity.class, c2_1_id ); Child2Entity c2_2 = getEntityManager() - .find(Child2Entity.class, c2_2_id); + .find( Child2Entity.class, c2_2_id ); - ParentEntity rev1 = getAuditReader().find(ParentEntity.class, p2_id, 1); - ParentEntity rev2 = getAuditReader().find(ParentEntity.class, p2_id, 2); - ParentEntity rev3 = getAuditReader().find(ParentEntity.class, p2_id, 3); - ParentEntity rev4 = getAuditReader().find(ParentEntity.class, p2_id, 4); - ParentEntity rev5 = getAuditReader().find(ParentEntity.class, p2_id, 5); + ParentEntity rev1 = getAuditReader().find( ParentEntity.class, p2_id, 1 ); + ParentEntity rev2 = getAuditReader().find( ParentEntity.class, p2_id, 2 ); + ParentEntity rev3 = getAuditReader().find( ParentEntity.class, p2_id, 3 ); + ParentEntity rev4 = getAuditReader().find( ParentEntity.class, p2_id, 4 ); + ParentEntity rev5 = getAuditReader().find( ParentEntity.class, p2_id, 5 ); - assert TestTools.checkList(rev1.getChildren1()); - assert TestTools.checkList(rev2.getChildren1()); - assert TestTools.checkList(rev3.getChildren1(), c1_1); - assert TestTools.checkList(rev4.getChildren1(), c1_1); - assert TestTools.checkList(rev5.getChildren1(), c1_1); + assert TestTools.checkList( rev1.getChildren1() ); + assert TestTools.checkList( rev2.getChildren1() ); + assert TestTools.checkList( rev3.getChildren1(), c1_1 ); + assert TestTools.checkList( rev4.getChildren1(), c1_1 ); + assert TestTools.checkList( rev5.getChildren1(), c1_1 ); - assert TestTools.checkList(rev1.getChildren2()); - assert TestTools.checkList(rev2.getChildren2(), c2_1); - assert TestTools.checkList(rev3.getChildren2(), c2_1); - assert TestTools.checkList(rev4.getChildren2(), c2_1, c2_2); - assert TestTools.checkList(rev5.getChildren2(), c2_1); + assert TestTools.checkList( rev1.getChildren2() ); + assert TestTools.checkList( rev2.getChildren2(), c2_1 ); + assert TestTools.checkList( rev3.getChildren2(), c2_1 ); + assert TestTools.checkList( rev4.getChildren2(), c2_1, c2_2 ); + assert TestTools.checkList( rev5.getChildren2(), c2_1 ); } @Test public void testHistoryOfChild1_1() { - ParentEntity p1 = getEntityManager().find(ParentEntity.class, p1_id); - ParentEntity p2 = getEntityManager().find(ParentEntity.class, p2_id); + ParentEntity p1 = getEntityManager().find( ParentEntity.class, p1_id ); + ParentEntity p2 = getEntityManager().find( ParentEntity.class, p2_id ); - Child1Entity rev1 = getAuditReader().find(Child1Entity.class, c1_1_id, - 1); - Child1Entity rev2 = getAuditReader().find(Child1Entity.class, c1_1_id, - 2); - Child1Entity rev3 = getAuditReader().find(Child1Entity.class, c1_1_id, - 3); - Child1Entity rev4 = getAuditReader().find(Child1Entity.class, c1_1_id, - 4); - Child1Entity rev5 = getAuditReader().find(Child1Entity.class, c1_1_id, - 5); + Child1Entity rev1 = getAuditReader().find( + Child1Entity.class, c1_1_id, + 1 + ); + Child1Entity rev2 = getAuditReader().find( + Child1Entity.class, c1_1_id, + 2 + ); + Child1Entity rev3 = getAuditReader().find( + Child1Entity.class, c1_1_id, + 3 + ); + Child1Entity rev4 = getAuditReader().find( + Child1Entity.class, c1_1_id, + 4 + ); + Child1Entity rev5 = getAuditReader().find( + Child1Entity.class, c1_1_id, + 5 + ); - assert TestTools.checkList(rev1.getParents()); - assert TestTools.checkList(rev2.getParents(), p1); - assert TestTools.checkList(rev3.getParents(), p1, p2); - assert TestTools.checkList(rev4.getParents(), p2); - assert TestTools.checkList(rev5.getParents(), p2); + assert TestTools.checkList( rev1.getParents() ); + assert TestTools.checkList( rev2.getParents(), p1 ); + assert TestTools.checkList( rev3.getParents(), p1, p2 ); + assert TestTools.checkList( rev4.getParents(), p2 ); + assert TestTools.checkList( rev5.getParents(), p2 ); } - // TODO: this was disabled? + // TODO: this was disabled? @Test public void testHistoryOfChild1_2() { - ParentEntity p1 = getEntityManager().find(ParentEntity.class, p1_id); + ParentEntity p1 = getEntityManager().find( ParentEntity.class, p1_id ); - Child1Entity rev1 = getAuditReader().find(Child1Entity.class, c1_2_id, - 1); - Child1Entity rev2 = getAuditReader().find(Child1Entity.class, c1_2_id, - 2); - Child1Entity rev3 = getAuditReader().find(Child1Entity.class, c1_2_id, - 3); - Child1Entity rev4 = getAuditReader().find(Child1Entity.class, c1_2_id, - 4); - Child1Entity rev5 = getAuditReader().find(Child1Entity.class, c1_2_id, - 5); + Child1Entity rev1 = getAuditReader().find( + Child1Entity.class, c1_2_id, + 1 + ); + Child1Entity rev2 = getAuditReader().find( + Child1Entity.class, c1_2_id, + 2 + ); + Child1Entity rev3 = getAuditReader().find( + Child1Entity.class, c1_2_id, + 3 + ); + Child1Entity rev4 = getAuditReader().find( + Child1Entity.class, c1_2_id, + 4 + ); + Child1Entity rev5 = getAuditReader().find( + Child1Entity.class, c1_2_id, + 5 + ); - assert TestTools.checkList(rev1.getParents()); - assert TestTools.checkList(rev2.getParents()); - assert TestTools.checkList(rev3.getParents(), p1); - assert TestTools.checkList(rev4.getParents(), p1); - assert TestTools.checkList(rev5.getParents()); + assert TestTools.checkList( rev1.getParents() ); + assert TestTools.checkList( rev2.getParents() ); + assert TestTools.checkList( rev3.getParents(), p1 ); + assert TestTools.checkList( rev4.getParents(), p1 ); + assert TestTools.checkList( rev5.getParents() ); } @Test public void testHistoryOfChild2_1() { - ParentEntity p2 = getEntityManager().find(ParentEntity.class, p2_id); + ParentEntity p2 = getEntityManager().find( ParentEntity.class, p2_id ); - Child2Entity rev1 = getAuditReader().find(Child2Entity.class, c2_1_id, - 1); - Child2Entity rev2 = getAuditReader().find(Child2Entity.class, c2_1_id, - 2); - Child2Entity rev3 = getAuditReader().find(Child2Entity.class, c2_1_id, - 3); - Child2Entity rev4 = getAuditReader().find(Child2Entity.class, c2_1_id, - 4); - Child2Entity rev5 = getAuditReader().find(Child2Entity.class, c2_1_id, - 5); + Child2Entity rev1 = getAuditReader().find( + Child2Entity.class, c2_1_id, + 1 + ); + Child2Entity rev2 = getAuditReader().find( + Child2Entity.class, c2_1_id, + 2 + ); + Child2Entity rev3 = getAuditReader().find( + Child2Entity.class, c2_1_id, + 3 + ); + Child2Entity rev4 = getAuditReader().find( + Child2Entity.class, c2_1_id, + 4 + ); + Child2Entity rev5 = getAuditReader().find( + Child2Entity.class, c2_1_id, + 5 + ); - assert TestTools.checkList(rev1.getParents()); - assert TestTools.checkList(rev2.getParents(), p2); - assert TestTools.checkList(rev3.getParents(), p2); - assert TestTools.checkList(rev4.getParents(), p2); - assert TestTools.checkList(rev5.getParents(), p2); + assert TestTools.checkList( rev1.getParents() ); + assert TestTools.checkList( rev2.getParents(), p2 ); + assert TestTools.checkList( rev3.getParents(), p2 ); + assert TestTools.checkList( rev4.getParents(), p2 ); + assert TestTools.checkList( rev5.getParents(), p2 ); } @Test public void testHistoryOfChild2_2() { - ParentEntity p1 = getEntityManager().find(ParentEntity.class, p1_id); - ParentEntity p2 = getEntityManager().find(ParentEntity.class, p2_id); + ParentEntity p1 = getEntityManager().find( ParentEntity.class, p1_id ); + ParentEntity p2 = getEntityManager().find( ParentEntity.class, p2_id ); - Child2Entity rev1 = getAuditReader().find(Child2Entity.class, c2_2_id, - 1); - Child2Entity rev2 = getAuditReader().find(Child2Entity.class, c2_2_id, - 2); - Child2Entity rev3 = getAuditReader().find(Child2Entity.class, c2_2_id, - 3); - Child2Entity rev4 = getAuditReader().find(Child2Entity.class, c2_2_id, - 4); - Child2Entity rev5 = getAuditReader().find(Child2Entity.class, c2_2_id, - 5); + Child2Entity rev1 = getAuditReader().find( + Child2Entity.class, c2_2_id, + 1 + ); + Child2Entity rev2 = getAuditReader().find( + Child2Entity.class, c2_2_id, + 2 + ); + Child2Entity rev3 = getAuditReader().find( + Child2Entity.class, c2_2_id, + 3 + ); + Child2Entity rev4 = getAuditReader().find( + Child2Entity.class, c2_2_id, + 4 + ); + Child2Entity rev5 = getAuditReader().find( + Child2Entity.class, c2_2_id, + 5 + ); - assert TestTools.checkList(rev1.getParents()); - assert TestTools.checkList(rev2.getParents()); - assert TestTools.checkList(rev3.getParents(), p1); - assert TestTools.checkList(rev4.getParents(), p1, p2); - assert TestTools.checkList(rev5.getParents(), p1); + assert TestTools.checkList( rev1.getParents() ); + assert TestTools.checkList( rev2.getParents() ); + assert TestTools.checkList( rev3.getParents(), p1 ); + assert TestTools.checkList( rev4.getParents(), p1, p2 ); + assert TestTools.checkList( rev5.getParents(), p1 ); } private List> getRevisions( @@ -408,31 +470,33 @@ public class ValidityAuditStrategyRevEndTestCustomRevEnt extends BaseEnversJPAFu // org.hibernate.envers.test.entities.manytomany.sametable.ParentEntity_AUD // auditEntity where auditEntity.originalId.id = :originalEntityId - StringBuilder builder = new StringBuilder("select auditEntity from "); - builder.append(originalEntityClazz.getName()) - .append("_AUD auditEntity"); - builder.append(" where auditEntity.originalId.id = :originalEntityId"); + StringBuilder builder = new StringBuilder( "select auditEntity from " ); + builder.append( originalEntityClazz.getName() ) + .append( "_AUD auditEntity" ); + builder.append( " where auditEntity.originalId.id = :originalEntityId" ); - Query qry = getEntityManager().createQuery(builder.toString()); - qry.setParameter("originalEntityId", originalEntityId); + Query qry = getEntityManager().createQuery( builder.toString() ); + qry.setParameter( "originalEntityId", originalEntityId ); @SuppressWarnings("unchecked") List> resultList = qry.getResultList(); return resultList; } - private void verifyRevEndTimeStamps(String debugInfo, + private void verifyRevEndTimeStamps( + String debugInfo, List> revisionEntities) { - for (Map revisionEntity : revisionEntities) { + for ( Map revisionEntity : revisionEntities ) { Date revendTimestamp = (Date) revisionEntity - .get(revendTimestampColumName); + .get( revendTimestampColumName ); CustomDateRevEntity revEnd = (CustomDateRevEntity) revisionEntity - .get("REVEND"); + .get( "REVEND" ); - if (revendTimestamp == null) { + if ( revendTimestamp == null ) { assert revEnd == null; - } else { + } + else { assert revendTimestamp.getTime() == revEnd.getDateTimestamp().getTime(); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/strategy/ValidityAuditStrategyRevEndTsTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/strategy/ValidityAuditStrategyRevEndTsTest.java index 6c79992434..0957f120ea 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/strategy/ValidityAuditStrategyRevEndTsTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/strategy/ValidityAuditStrategyRevEndTsTest.java @@ -23,6 +23,8 @@ */ package org.hibernate.envers.test.integration.strategy; +import javax.persistence.EntityManager; +import javax.persistence.Query; import java.sql.Types; import java.util.Arrays; import java.util.Date; @@ -30,11 +32,6 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import javax.persistence.EntityManager; -import javax.persistence.Query; - -import org.junit.Assert; -import org.junit.Test; import org.hibernate.Session; import org.hibernate.dialect.MySQL5Dialect; @@ -49,10 +46,13 @@ import org.hibernate.envers.test.entities.manytomany.sametable.Child2Entity; import org.hibernate.envers.test.entities.manytomany.sametable.ParentEntity; import org.hibernate.envers.test.tools.TestTools; +import org.junit.Assert; +import org.junit.Test; + /** * Test which checks that the revision end timestamp is correctly set for * {@link ValidityAuditStrategy}. - * + * * @author Erik-Berndt Scheper */ public class ValidityAuditStrategyRevEndTsTest extends BaseEnversJPAFunctionalTestCase { @@ -68,19 +68,19 @@ public class ValidityAuditStrategyRevEndTsTest extends BaseEnversJPAFunctionalTe @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ParentEntity.class, Child1Entity.class, Child2Entity.class }; + return new Class[] {ParentEntity.class, Child1Entity.class, Child2Entity.class}; } @Override protected void addConfigOptions(Map options) { super.addConfigOptions( options ); - options.put(EnversSettings.AUDIT_STRATEGY, "org.hibernate.envers.strategy.ValidityAuditStrategy"); - options.put(EnversSettings.AUDIT_STRATEGY_VALIDITY_STORE_REVEND_TIMESTAMP, "true"); - options.put(EnversSettings.AUDIT_STRATEGY_VALIDITY_REVEND_TIMESTAMP_FIELD_NAME, revendTimestampColumName); + options.put( EnversSettings.AUDIT_STRATEGY, "org.hibernate.envers.strategy.ValidityAuditStrategy" ); + options.put( EnversSettings.AUDIT_STRATEGY_VALIDITY_STORE_REVEND_TIMESTAMP, "true" ); + options.put( EnversSettings.AUDIT_STRATEGY_VALIDITY_REVEND_TIMESTAMP_FIELD_NAME, revendTimestampColumName ); } @Test - @Priority(10) + @Priority(10) public void initData() { EntityManager em = getEntityManager(); @@ -89,45 +89,47 @@ public class ValidityAuditStrategyRevEndTsTest extends BaseEnversJPAFunctionalTe // to allow this. em.getTransaction().begin(); Session session = (Session) em.getDelegate(); - session.createSQLQuery("DROP TABLE children").executeUpdate(); + session.createSQLQuery( "DROP TABLE children" ).executeUpdate(); session .createSQLQuery( - "CREATE TABLE children ( parent_id " + getDialect().getTypeName(Types.INTEGER) + - ", child1_id " + getDialect().getTypeName(Types.INTEGER) + " NULL" + - ", child2_id " + getDialect().getTypeName(Types.INTEGER) + " NULL )") + "CREATE TABLE children ( parent_id " + getDialect().getTypeName( Types.INTEGER ) + + ", child1_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL" + + ", child2_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL )" + ) .executeUpdate(); - session.createSQLQuery("DROP TABLE children_AUD").executeUpdate(); + session.createSQLQuery( "DROP TABLE children_AUD" ).executeUpdate(); session .createSQLQuery( - "CREATE TABLE children_AUD ( REV " + getDialect().getTypeName(Types.INTEGER) + " NOT NULL" + - ", REVEND " + getDialect().getTypeName(Types.INTEGER) + - ", " + revendTimestampColumName + " " + getDialect().getTypeName(Types.TIMESTAMP) + - ", REVTYPE " + getDialect().getTypeName(Types.TINYINT) + - ", parent_id " + getDialect().getTypeName(Types.INTEGER) + - ", child1_id " + getDialect().getTypeName(Types.INTEGER) + " NULL" + - ", child2_id " + getDialect().getTypeName(Types.INTEGER) + " NULL )") + "CREATE TABLE children_AUD ( REV " + getDialect().getTypeName( Types.INTEGER ) + " NOT NULL" + + ", REVEND " + getDialect().getTypeName( Types.INTEGER ) + + ", " + revendTimestampColumName + " " + getDialect().getTypeName( Types.TIMESTAMP ) + + ", REVTYPE " + getDialect().getTypeName( Types.TINYINT ) + + ", parent_id " + getDialect().getTypeName( Types.INTEGER ) + + ", child1_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL" + + ", child2_id " + getDialect().getTypeName( Types.INTEGER ) + " NULL )" + ) .executeUpdate(); em.getTransaction().commit(); em.clear(); - ParentEntity p1 = new ParentEntity("parent_1"); - ParentEntity p2 = new ParentEntity("parent_2"); + ParentEntity p1 = new ParentEntity( "parent_1" ); + ParentEntity p2 = new ParentEntity( "parent_2" ); - Child1Entity c1_1 = new Child1Entity("child1_1"); - Child1Entity c1_2 = new Child1Entity("child1_2"); + Child1Entity c1_1 = new Child1Entity( "child1_1" ); + Child1Entity c1_2 = new Child1Entity( "child1_2" ); - Child2Entity c2_1 = new Child2Entity("child2_1"); - Child2Entity c2_2 = new Child2Entity("child2_2"); + Child2Entity c2_1 = new Child2Entity( "child2_1" ); + Child2Entity c2_2 = new Child2Entity( "child2_2" ); // Revision 1 em.getTransaction().begin(); - em.persist(p1); - em.persist(p2); - em.persist(c1_1); - em.persist(c1_2); - em.persist(c2_1); - em.persist(c2_2); + em.persist( p1 ); + em.persist( p2 ); + em.persist( c1_1 ); + em.persist( c1_2 ); + em.persist( c2_1 ); + em.persist( c2_2 ); em.getTransaction().commit(); em.clear(); @@ -136,13 +138,13 @@ public class ValidityAuditStrategyRevEndTsTest extends BaseEnversJPAFunctionalTe em.getTransaction().begin(); - p1 = em.find(ParentEntity.class, p1.getId()); - p2 = em.find(ParentEntity.class, p2.getId()); - c1_1 = em.find(Child1Entity.class, c1_1.getId()); - c2_1 = em.find(Child2Entity.class, c2_1.getId()); + p1 = em.find( ParentEntity.class, p1.getId() ); + p2 = em.find( ParentEntity.class, p2.getId() ); + c1_1 = em.find( Child1Entity.class, c1_1.getId() ); + c2_1 = em.find( Child2Entity.class, c2_1.getId() ); - p1.getChildren1().add(c1_1); - p2.getChildren2().add(c2_1); + p1.getChildren1().add( c1_1 ); + p2.getChildren2().add( c2_1 ); em.getTransaction().commit(); em.clear(); @@ -150,16 +152,16 @@ public class ValidityAuditStrategyRevEndTsTest extends BaseEnversJPAFunctionalTe // Revision 3 - (p1: c1_1, c1_2, c2_2, p2: c1_1, c2_1) em.getTransaction().begin(); - p1 = em.find(ParentEntity.class, p1.getId()); - p2 = em.find(ParentEntity.class, p2.getId()); - c1_1 = em.find(Child1Entity.class, c1_1.getId()); - c1_2 = em.find(Child1Entity.class, c1_2.getId()); - c2_2 = em.find(Child2Entity.class, c2_2.getId()); + p1 = em.find( ParentEntity.class, p1.getId() ); + p2 = em.find( ParentEntity.class, p2.getId() ); + c1_1 = em.find( Child1Entity.class, c1_1.getId() ); + c1_2 = em.find( Child1Entity.class, c1_2.getId() ); + c2_2 = em.find( Child2Entity.class, c2_2.getId() ); - p1.getChildren1().add(c1_2); - p1.getChildren2().add(c2_2); + p1.getChildren1().add( c1_2 ); + p1.getChildren2().add( c2_2 ); - p2.getChildren1().add(c1_1); + p2.getChildren1().add( c1_1 ); em.getTransaction().commit(); em.clear(); @@ -167,13 +169,13 @@ public class ValidityAuditStrategyRevEndTsTest extends BaseEnversJPAFunctionalTe // Revision 4 - (p1: c1_2, c2_2, p2: c1_1, c2_1, c2_2) em.getTransaction().begin(); - p1 = em.find(ParentEntity.class, p1.getId()); - p2 = em.find(ParentEntity.class, p2.getId()); - c1_1 = em.find(Child1Entity.class, c1_1.getId()); - c2_2 = em.find(Child2Entity.class, c2_2.getId()); + p1 = em.find( ParentEntity.class, p1.getId() ); + p2 = em.find( ParentEntity.class, p2.getId() ); + c1_1 = em.find( Child1Entity.class, c1_1.getId() ); + c2_2 = em.find( Child2Entity.class, c2_2.getId() ); - p1.getChildren1().remove(c1_1); - p2.getChildren2().add(c2_2); + p1.getChildren1().remove( c1_1 ); + p2.getChildren2().add( c2_2 ); em.getTransaction().commit(); em.clear(); @@ -181,13 +183,13 @@ public class ValidityAuditStrategyRevEndTsTest extends BaseEnversJPAFunctionalTe // Revision 5 - (p1: c2_2, p2: c1_1, c2_1) em.getTransaction().begin(); - p1 = em.find(ParentEntity.class, p1.getId()); - p2 = em.find(ParentEntity.class, p2.getId()); - c1_2 = em.find(Child1Entity.class, c1_2.getId()); - c2_2 = em.find(Child2Entity.class, c2_2.getId()); + p1 = em.find( ParentEntity.class, p1.getId() ); + p2 = em.find( ParentEntity.class, p2.getId() ); + c1_2 = em.find( Child1Entity.class, c1_2.getId() ); + c2_2 = em.find( Child2Entity.class, c2_2.getId() ); - c2_2.getParents().remove(p2); - c1_2.getParents().remove(p1); + c2_2.getParents().remove( p2 ); + c1_2.getParents().remove( p1 ); em.getTransaction().commit(); em.clear(); @@ -202,53 +204,72 @@ public class ValidityAuditStrategyRevEndTsTest extends BaseEnversJPAFunctionalTe c2_2_id = c2_2.getId(); Set revisionNumbers = new HashSet(); - revisionNumbers.addAll(Arrays.asList(1, 2, 3, 4, 5)); + revisionNumbers.addAll( Arrays.asList( 1, 2, 3, 4, 5 ) ); revisions = getAuditReader().findRevisions( SequenceIdRevisionEntity.class, - revisionNumbers); + revisionNumbers + ); assert revisions.size() == 5; } @Test public void testRevisionsCounts() { - assert Arrays.asList(1, 2, 3, 4).equals( - getAuditReader().getRevisions(ParentEntity.class, p1_id)); - assert Arrays.asList(1, 2, 3, 4).equals( - getAuditReader().getRevisions(ParentEntity.class, p2_id)); + assert Arrays.asList( 1, 2, 3, 4 ).equals( + getAuditReader().getRevisions( ParentEntity.class, p1_id ) + ); + assert Arrays.asList( 1, 2, 3, 4 ).equals( + getAuditReader().getRevisions( ParentEntity.class, p2_id ) + ); - assert Arrays.asList(1).equals( - getAuditReader().getRevisions(Child1Entity.class, c1_1_id)); - assert Arrays.asList(1, 5).equals( - getAuditReader().getRevisions(Child1Entity.class, c1_2_id)); + assert Arrays.asList( 1 ).equals( + getAuditReader().getRevisions( Child1Entity.class, c1_1_id ) + ); + assert Arrays.asList( 1, 5 ).equals( + getAuditReader().getRevisions( Child1Entity.class, c1_2_id ) + ); - assert Arrays.asList(1).equals( - getAuditReader().getRevisions(Child2Entity.class, c2_1_id)); - assert Arrays.asList(1, 5).equals( - getAuditReader().getRevisions(Child2Entity.class, c2_2_id)); + assert Arrays.asList( 1 ).equals( + getAuditReader().getRevisions( Child2Entity.class, c2_1_id ) + ); + assert Arrays.asList( 1, 5 ).equals( + getAuditReader().getRevisions( Child2Entity.class, c2_2_id ) + ); } @Test public void testAllRevEndTimeStamps() { - List> p1RevList = getRevisions(ParentEntity.class, - p1_id); - List> p2RevList = getRevisions(ParentEntity.class, - p2_id); - List> c1_1_List = getRevisions(Child1Entity.class, - c1_1_id); - List> c1_2_List = getRevisions(Child1Entity.class, - c1_2_id); - List> c2_1_List = getRevisions(Child2Entity.class, - c2_1_id); - List> c2_2_List = getRevisions(Child2Entity.class, - c2_2_id); + List> p1RevList = getRevisions( + ParentEntity.class, + p1_id + ); + List> p2RevList = getRevisions( + ParentEntity.class, + p2_id + ); + List> c1_1_List = getRevisions( + Child1Entity.class, + c1_1_id + ); + List> c1_2_List = getRevisions( + Child1Entity.class, + c1_2_id + ); + List> c2_1_List = getRevisions( + Child2Entity.class, + c2_1_id + ); + List> c2_2_List = getRevisions( + Child2Entity.class, + c2_2_id + ); - verifyRevEndTimeStamps("ParentEntity: " + p1_id, p1RevList); - verifyRevEndTimeStamps("ParentEntity: " + p2_id, p2RevList); - verifyRevEndTimeStamps("Child1Entity: " + c1_1_id, c1_1_List); - verifyRevEndTimeStamps("Child1Entity: " + c1_2_id, c1_2_List); - verifyRevEndTimeStamps("Child2Entity: " + c2_1_id, c2_1_List); - verifyRevEndTimeStamps("Child2Entity: " + c2_2_id, c2_2_List); + verifyRevEndTimeStamps( "ParentEntity: " + p1_id, p1RevList ); + verifyRevEndTimeStamps( "ParentEntity: " + p2_id, p2RevList ); + verifyRevEndTimeStamps( "Child1Entity: " + c1_1_id, c1_1_List ); + verifyRevEndTimeStamps( "Child1Entity: " + c1_2_id, c1_2_List ); + verifyRevEndTimeStamps( "Child2Entity: " + c2_1_id, c2_1_List ); + verifyRevEndTimeStamps( "Child2Entity: " + c2_2_id, c2_2_List ); } @@ -256,148 +277,188 @@ public class ValidityAuditStrategyRevEndTsTest extends BaseEnversJPAFunctionalTe public void testHistoryOfParent1() { Child1Entity c1_1 = getEntityManager() - .find(Child1Entity.class, c1_1_id); + .find( Child1Entity.class, c1_1_id ); Child1Entity c1_2 = getEntityManager() - .find(Child1Entity.class, c1_2_id); + .find( Child1Entity.class, c1_2_id ); Child2Entity c2_2 = getEntityManager() - .find(Child2Entity.class, c2_2_id); + .find( Child2Entity.class, c2_2_id ); - ParentEntity rev1 = getAuditReader().find(ParentEntity.class, p1_id, 1); - ParentEntity rev2 = getAuditReader().find(ParentEntity.class, p1_id, 2); - ParentEntity rev3 = getAuditReader().find(ParentEntity.class, p1_id, 3); - ParentEntity rev4 = getAuditReader().find(ParentEntity.class, p1_id, 4); - ParentEntity rev5 = getAuditReader().find(ParentEntity.class, p1_id, 5); + ParentEntity rev1 = getAuditReader().find( ParentEntity.class, p1_id, 1 ); + ParentEntity rev2 = getAuditReader().find( ParentEntity.class, p1_id, 2 ); + ParentEntity rev3 = getAuditReader().find( ParentEntity.class, p1_id, 3 ); + ParentEntity rev4 = getAuditReader().find( ParentEntity.class, p1_id, 4 ); + ParentEntity rev5 = getAuditReader().find( ParentEntity.class, p1_id, 5 ); - assert TestTools.checkList(rev1.getChildren1()); - assert TestTools.checkList(rev2.getChildren1(), c1_1); - assert TestTools.checkList(rev3.getChildren1(), c1_1, c1_2); - assert TestTools.checkList(rev4.getChildren1(), c1_2); - assert TestTools.checkList(rev5.getChildren1()); + assert TestTools.checkList( rev1.getChildren1() ); + assert TestTools.checkList( rev2.getChildren1(), c1_1 ); + assert TestTools.checkList( rev3.getChildren1(), c1_1, c1_2 ); + assert TestTools.checkList( rev4.getChildren1(), c1_2 ); + assert TestTools.checkList( rev5.getChildren1() ); - assert TestTools.checkList(rev1.getChildren2()); - assert TestTools.checkList(rev2.getChildren2()); - assert TestTools.checkList(rev3.getChildren2(), c2_2); - assert TestTools.checkList(rev4.getChildren2(), c2_2); - assert TestTools.checkList(rev5.getChildren2(), c2_2); + assert TestTools.checkList( rev1.getChildren2() ); + assert TestTools.checkList( rev2.getChildren2() ); + assert TestTools.checkList( rev3.getChildren2(), c2_2 ); + assert TestTools.checkList( rev4.getChildren2(), c2_2 ); + assert TestTools.checkList( rev5.getChildren2(), c2_2 ); } @Test public void testHistoryOfParent2() { Child1Entity c1_1 = getEntityManager() - .find(Child1Entity.class, c1_1_id); + .find( Child1Entity.class, c1_1_id ); Child2Entity c2_1 = getEntityManager() - .find(Child2Entity.class, c2_1_id); + .find( Child2Entity.class, c2_1_id ); Child2Entity c2_2 = getEntityManager() - .find(Child2Entity.class, c2_2_id); + .find( Child2Entity.class, c2_2_id ); - ParentEntity rev1 = getAuditReader().find(ParentEntity.class, p2_id, 1); - ParentEntity rev2 = getAuditReader().find(ParentEntity.class, p2_id, 2); - ParentEntity rev3 = getAuditReader().find(ParentEntity.class, p2_id, 3); - ParentEntity rev4 = getAuditReader().find(ParentEntity.class, p2_id, 4); - ParentEntity rev5 = getAuditReader().find(ParentEntity.class, p2_id, 5); + ParentEntity rev1 = getAuditReader().find( ParentEntity.class, p2_id, 1 ); + ParentEntity rev2 = getAuditReader().find( ParentEntity.class, p2_id, 2 ); + ParentEntity rev3 = getAuditReader().find( ParentEntity.class, p2_id, 3 ); + ParentEntity rev4 = getAuditReader().find( ParentEntity.class, p2_id, 4 ); + ParentEntity rev5 = getAuditReader().find( ParentEntity.class, p2_id, 5 ); - assert TestTools.checkList(rev1.getChildren1()); - assert TestTools.checkList(rev2.getChildren1()); - assert TestTools.checkList(rev3.getChildren1(), c1_1); - assert TestTools.checkList(rev4.getChildren1(), c1_1); - assert TestTools.checkList(rev5.getChildren1(), c1_1); + assert TestTools.checkList( rev1.getChildren1() ); + assert TestTools.checkList( rev2.getChildren1() ); + assert TestTools.checkList( rev3.getChildren1(), c1_1 ); + assert TestTools.checkList( rev4.getChildren1(), c1_1 ); + assert TestTools.checkList( rev5.getChildren1(), c1_1 ); - assert TestTools.checkList(rev1.getChildren2()); - assert TestTools.checkList(rev2.getChildren2(), c2_1); - assert TestTools.checkList(rev3.getChildren2(), c2_1); - assert TestTools.checkList(rev4.getChildren2(), c2_1, c2_2); - assert TestTools.checkList(rev5.getChildren2(), c2_1); + assert TestTools.checkList( rev1.getChildren2() ); + assert TestTools.checkList( rev2.getChildren2(), c2_1 ); + assert TestTools.checkList( rev3.getChildren2(), c2_1 ); + assert TestTools.checkList( rev4.getChildren2(), c2_1, c2_2 ); + assert TestTools.checkList( rev5.getChildren2(), c2_1 ); } @Test public void testHistoryOfChild1_1() { - ParentEntity p1 = getEntityManager().find(ParentEntity.class, p1_id); - ParentEntity p2 = getEntityManager().find(ParentEntity.class, p2_id); + ParentEntity p1 = getEntityManager().find( ParentEntity.class, p1_id ); + ParentEntity p2 = getEntityManager().find( ParentEntity.class, p2_id ); - Child1Entity rev1 = getAuditReader().find(Child1Entity.class, c1_1_id, - 1); - Child1Entity rev2 = getAuditReader().find(Child1Entity.class, c1_1_id, - 2); - Child1Entity rev3 = getAuditReader().find(Child1Entity.class, c1_1_id, - 3); - Child1Entity rev4 = getAuditReader().find(Child1Entity.class, c1_1_id, - 4); - Child1Entity rev5 = getAuditReader().find(Child1Entity.class, c1_1_id, - 5); + Child1Entity rev1 = getAuditReader().find( + Child1Entity.class, c1_1_id, + 1 + ); + Child1Entity rev2 = getAuditReader().find( + Child1Entity.class, c1_1_id, + 2 + ); + Child1Entity rev3 = getAuditReader().find( + Child1Entity.class, c1_1_id, + 3 + ); + Child1Entity rev4 = getAuditReader().find( + Child1Entity.class, c1_1_id, + 4 + ); + Child1Entity rev5 = getAuditReader().find( + Child1Entity.class, c1_1_id, + 5 + ); - assert TestTools.checkList(rev1.getParents()); - assert TestTools.checkList(rev2.getParents(), p1); - assert TestTools.checkList(rev3.getParents(), p1, p2); - assert TestTools.checkList(rev4.getParents(), p2); - assert TestTools.checkList(rev5.getParents(), p2); + assert TestTools.checkList( rev1.getParents() ); + assert TestTools.checkList( rev2.getParents(), p1 ); + assert TestTools.checkList( rev3.getParents(), p1, p2 ); + assert TestTools.checkList( rev4.getParents(), p2 ); + assert TestTools.checkList( rev5.getParents(), p2 ); } - // TODO: this was disabled? + // TODO: this was disabled? @Test public void testHistoryOfChild1_2() { - ParentEntity p1 = getEntityManager().find(ParentEntity.class, p1_id); + ParentEntity p1 = getEntityManager().find( ParentEntity.class, p1_id ); - Child1Entity rev1 = getAuditReader().find(Child1Entity.class, c1_2_id, - 1); - Child1Entity rev2 = getAuditReader().find(Child1Entity.class, c1_2_id, - 2); - Child1Entity rev3 = getAuditReader().find(Child1Entity.class, c1_2_id, - 3); - Child1Entity rev4 = getAuditReader().find(Child1Entity.class, c1_2_id, - 4); - Child1Entity rev5 = getAuditReader().find(Child1Entity.class, c1_2_id, - 5); + Child1Entity rev1 = getAuditReader().find( + Child1Entity.class, c1_2_id, + 1 + ); + Child1Entity rev2 = getAuditReader().find( + Child1Entity.class, c1_2_id, + 2 + ); + Child1Entity rev3 = getAuditReader().find( + Child1Entity.class, c1_2_id, + 3 + ); + Child1Entity rev4 = getAuditReader().find( + Child1Entity.class, c1_2_id, + 4 + ); + Child1Entity rev5 = getAuditReader().find( + Child1Entity.class, c1_2_id, + 5 + ); - assert TestTools.checkList(rev1.getParents()); - assert TestTools.checkList(rev2.getParents()); - assert TestTools.checkList(rev3.getParents(), p1); - assert TestTools.checkList(rev4.getParents(), p1); - assert TestTools.checkList(rev5.getParents()); + assert TestTools.checkList( rev1.getParents() ); + assert TestTools.checkList( rev2.getParents() ); + assert TestTools.checkList( rev3.getParents(), p1 ); + assert TestTools.checkList( rev4.getParents(), p1 ); + assert TestTools.checkList( rev5.getParents() ); } @Test public void testHistoryOfChild2_1() { - ParentEntity p2 = getEntityManager().find(ParentEntity.class, p2_id); + ParentEntity p2 = getEntityManager().find( ParentEntity.class, p2_id ); - Child2Entity rev1 = getAuditReader().find(Child2Entity.class, c2_1_id, - 1); - Child2Entity rev2 = getAuditReader().find(Child2Entity.class, c2_1_id, - 2); - Child2Entity rev3 = getAuditReader().find(Child2Entity.class, c2_1_id, - 3); - Child2Entity rev4 = getAuditReader().find(Child2Entity.class, c2_1_id, - 4); - Child2Entity rev5 = getAuditReader().find(Child2Entity.class, c2_1_id, - 5); + Child2Entity rev1 = getAuditReader().find( + Child2Entity.class, c2_1_id, + 1 + ); + Child2Entity rev2 = getAuditReader().find( + Child2Entity.class, c2_1_id, + 2 + ); + Child2Entity rev3 = getAuditReader().find( + Child2Entity.class, c2_1_id, + 3 + ); + Child2Entity rev4 = getAuditReader().find( + Child2Entity.class, c2_1_id, + 4 + ); + Child2Entity rev5 = getAuditReader().find( + Child2Entity.class, c2_1_id, + 5 + ); - assert TestTools.checkList(rev1.getParents()); - assert TestTools.checkList(rev2.getParents(), p2); - assert TestTools.checkList(rev3.getParents(), p2); - assert TestTools.checkList(rev4.getParents(), p2); - assert TestTools.checkList(rev5.getParents(), p2); + assert TestTools.checkList( rev1.getParents() ); + assert TestTools.checkList( rev2.getParents(), p2 ); + assert TestTools.checkList( rev3.getParents(), p2 ); + assert TestTools.checkList( rev4.getParents(), p2 ); + assert TestTools.checkList( rev5.getParents(), p2 ); } @Test public void testHistoryOfChild2_2() { - ParentEntity p1 = getEntityManager().find(ParentEntity.class, p1_id); - ParentEntity p2 = getEntityManager().find(ParentEntity.class, p2_id); + ParentEntity p1 = getEntityManager().find( ParentEntity.class, p1_id ); + ParentEntity p2 = getEntityManager().find( ParentEntity.class, p2_id ); - Child2Entity rev1 = getAuditReader().find(Child2Entity.class, c2_2_id, - 1); - Child2Entity rev2 = getAuditReader().find(Child2Entity.class, c2_2_id, - 2); - Child2Entity rev3 = getAuditReader().find(Child2Entity.class, c2_2_id, - 3); - Child2Entity rev4 = getAuditReader().find(Child2Entity.class, c2_2_id, - 4); - Child2Entity rev5 = getAuditReader().find(Child2Entity.class, c2_2_id, - 5); + Child2Entity rev1 = getAuditReader().find( + Child2Entity.class, c2_2_id, + 1 + ); + Child2Entity rev2 = getAuditReader().find( + Child2Entity.class, c2_2_id, + 2 + ); + Child2Entity rev3 = getAuditReader().find( + Child2Entity.class, c2_2_id, + 3 + ); + Child2Entity rev4 = getAuditReader().find( + Child2Entity.class, c2_2_id, + 4 + ); + Child2Entity rev5 = getAuditReader().find( + Child2Entity.class, c2_2_id, + 5 + ); - assert TestTools.checkList(rev1.getParents()); - assert TestTools.checkList(rev2.getParents()); - assert TestTools.checkList(rev3.getParents(), p1); - assert TestTools.checkList(rev4.getParents(), p1, p2); - assert TestTools.checkList(rev5.getParents(), p1); + assert TestTools.checkList( rev1.getParents() ); + assert TestTools.checkList( rev2.getParents() ); + assert TestTools.checkList( rev3.getParents(), p1 ); + assert TestTools.checkList( rev4.getParents(), p1, p2 ); + assert TestTools.checkList( rev5.getParents(), p1 ); } private List> getRevisions( @@ -407,13 +468,13 @@ public class ValidityAuditStrategyRevEndTsTest extends BaseEnversJPAFunctionalTe // org.hibernate.envers.test.entities.manytomany.sametable.ParentEntity_AUD // auditEntity where auditEntity.originalId.id = :originalEntityId - StringBuilder builder = new StringBuilder("select auditEntity from "); - builder.append(originalEntityClazz.getName()) - .append("_AUD auditEntity"); - builder.append(" where auditEntity.originalId.id = :originalEntityId"); + StringBuilder builder = new StringBuilder( "select auditEntity from " ); + builder.append( originalEntityClazz.getName() ) + .append( "_AUD auditEntity" ); + builder.append( " where auditEntity.originalId.id = :originalEntityId" ); - Query qry = getEntityManager().createQuery(builder.toString()); - qry.setParameter("originalEntityId", originalEntityId); + Query qry = getEntityManager().createQuery( builder.toString() ); + qry.setParameter( "originalEntityId", originalEntityId ); @SuppressWarnings("unchecked") List> resultList = qry.getResultList(); @@ -421,23 +482,29 @@ public class ValidityAuditStrategyRevEndTsTest extends BaseEnversJPAFunctionalTe } private void verifyRevEndTimeStamps(String debugInfo, List> revisionEntities) { - for (Map revisionEntity : revisionEntities) { - Date revendTimestamp = (Date) revisionEntity.get(revendTimestampColumName); - SequenceIdRevisionEntity revEnd = (SequenceIdRevisionEntity) revisionEntity.get("REVEND"); + for ( Map revisionEntity : revisionEntities ) { + Date revendTimestamp = (Date) revisionEntity.get( revendTimestampColumName ); + SequenceIdRevisionEntity revEnd = (SequenceIdRevisionEntity) revisionEntity.get( "REVEND" ); - if (revendTimestamp == null) { - Assert.assertNull(revEnd); - } else { - if (getDialect() instanceof MySQL5Dialect) { + if ( revendTimestamp == null ) { + Assert.assertNull( revEnd ); + } + else { + if ( getDialect() instanceof MySQL5Dialect ) { // MySQL5 DATETIME column type does not contain milliseconds. - Assert.assertEquals(revendTimestamp.getTime(), (revEnd.getTimestamp() - (revEnd.getTimestamp() % 1000))); - } else if (getDialect() instanceof SybaseASE15Dialect) { + Assert.assertEquals( + revendTimestamp.getTime(), + (revEnd.getTimestamp() - (revEnd.getTimestamp() % 1000)) + ); + } + else if ( getDialect() instanceof SybaseASE15Dialect ) { // Sybase "DATETIME values are accurate to 1/300 second on platforms that support this level of granularity". Assert.assertEquals( revendTimestamp.getTime() / 1000.0, revEnd.getTimestamp() / 1000.0, 1.0 / 300.0 ); - } else { - Assert.assertEquals(revendTimestamp.getTime(), revEnd.getTimestamp()); + } + else { + Assert.assertEquals( revendTimestamp.getTime(), revEnd.getTimestamp() ); } } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/AuditedMethodMappedSuperclass.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/AuditedMethodMappedSuperclass.java index 4612664885..0b2f6b7cc7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/AuditedMethodMappedSuperclass.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/AuditedMethodMappedSuperclass.java @@ -22,13 +22,13 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.superclass.auditAtMethodSuperclassLevel; + import javax.persistence.MappedSuperclass; import org.hibernate.envers.Audited; /** * @author Adam Warski (adam at warski dot org) - * * @author Hern&aacut;n Chanfreau */ @MappedSuperclass @@ -36,7 +36,7 @@ public class AuditedMethodMappedSuperclass { @Audited private String str; - + private String otherStr; public AuditedMethodMappedSuperclass() { @@ -64,15 +64,18 @@ public class AuditedMethodMappedSuperclass { } public boolean equals(Object o) { - if (this == o) + if ( this == o ) { return true; - if (!(o instanceof AuditedMethodMappedSuperclass)) + } + if ( !(o instanceof AuditedMethodMappedSuperclass) ) { return false; + } AuditedMethodMappedSuperclass that = (AuditedMethodMappedSuperclass) o; - if (str != null ? !str.equals(that.str) : that.str != null) + if ( str != null ? !str.equals( that.str ) : that.str != null ) { return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/NotAuditedSubclassEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/NotAuditedSubclassEntity.java index d44bda246c..a1a277150e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/NotAuditedSubclassEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/NotAuditedSubclassEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.superclass.auditAtMethodSuperclassLevel; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -30,9 +31,7 @@ import javax.persistence.Table; /** * @author Adam Warski (adam at warski dot org) - * * @author Hernán Chanfreau - * */ @Entity @Table(name = "NotAuditedSubclass") @@ -40,20 +39,20 @@ public class NotAuditedSubclassEntity extends AuditedMethodMappedSuperclass { @Id @GeneratedValue private Integer id; - + private String notAuditedStr; public NotAuditedSubclassEntity() { } public NotAuditedSubclassEntity(Integer id, String str, String otherStr, String notAuditedStr) { - super(str, otherStr); + super( str, otherStr ); this.notAuditedStr = notAuditedStr; this.id = id; } public NotAuditedSubclassEntity(String str, String otherStr, String notAuditedStr) { - super(str, otherStr); + super( str, otherStr ); this.notAuditedStr = notAuditedStr; } @@ -74,17 +73,21 @@ public class NotAuditedSubclassEntity extends AuditedMethodMappedSuperclass { } public boolean equals(Object o) { - if (this == o) + if ( this == o ) { return true; - if (!(o instanceof NotAuditedSubclassEntity)) + } + if ( !(o instanceof NotAuditedSubclassEntity) ) { return false; - if (!super.equals(o)) + } + if ( !super.equals( o ) ) { return false; + } NotAuditedSubclassEntity that = (NotAuditedSubclassEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) + if ( id != null ? !id.equals( that.id ) : that.id != null ) { return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/auditAllSubclass/AuditedAllSubclassEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/auditAllSubclass/AuditedAllSubclassEntity.java index 37823e9cf8..af3aecdcc8 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/auditAllSubclass/AuditedAllSubclassEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/auditAllSubclass/AuditedAllSubclassEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.superclass.auditAtMethodSuperclassLevel.auditAllSubclass; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -36,58 +37,66 @@ import org.hibernate.envers.test.integration.superclass.auditAtMethodSuperclassL @Entity @Audited public class AuditedAllSubclassEntity extends AuditedMethodMappedSuperclass { - @Id - @GeneratedValue - private Integer id; - - private String subAuditedStr; + @Id + @GeneratedValue + private Integer id; + + private String subAuditedStr; public AuditedAllSubclassEntity() { - } + } - public AuditedAllSubclassEntity(Integer id, String str, String otherString, String subAuditedStr) { - super(str, otherString); - this.subAuditedStr = subAuditedStr; - this.id = id; - } + public AuditedAllSubclassEntity(Integer id, String str, String otherString, String subAuditedStr) { + super( str, otherString ); + this.subAuditedStr = subAuditedStr; + this.id = id; + } - public AuditedAllSubclassEntity(String str, String otherString, String subAuditedStr ) { - super(str, otherString); - this.subAuditedStr = subAuditedStr; - } + public AuditedAllSubclassEntity(String str, String otherString, String subAuditedStr) { + super( str, otherString ); + this.subAuditedStr = subAuditedStr; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getSubAuditedStr() { + public String getSubAuditedStr() { return subAuditedStr; } public void setSubAuditedStr(String subAuditedStr) { this.subAuditedStr = subAuditedStr; } - - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof AuditedAllSubclassEntity)) return false; - if (!super.equals(o)) return false; - AuditedAllSubclassEntity that = (AuditedAllSubclassEntity) o; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof AuditedAllSubclassEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - if (id != null ? !id.equals(that.id) : that.id != null) return false; + AuditedAllSubclassEntity that = (AuditedAllSubclassEntity) o; - return true; - } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (id != null ? id.hashCode() : 0); - return result; - } + return true; + } + + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (id != null ? id.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/auditAllSubclass/MappedSubclassingAllAuditedTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/auditAllSubclass/MappedSubclassingAllAuditedTest.java index 6fe565e61b..eb8f62e86f 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/auditAllSubclass/MappedSubclassingAllAuditedTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/auditAllSubclass/MappedSubclassingAllAuditedTest.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.superclass.auditAtMethodSuperclassLevel.auditAllSubclass; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.exception.NotAuditedException; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -34,11 +32,11 @@ import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.superclass.auditAtMethodSuperclassLevel.AuditedMethodMappedSuperclass; import org.hibernate.envers.test.integration.superclass.auditAtMethodSuperclassLevel.NotAuditedSubclassEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) - * * @author Hern&aacut;n Chanfreau - * */ public class MappedSubclassingAllAuditedTest extends BaseEnversJPAFunctionalTestCase { private Integer id2_1; @@ -46,75 +44,82 @@ public class MappedSubclassingAllAuditedTest extends BaseEnversJPAFunctionalTest @Override protected Class[] getAnnotatedClasses() { - return new Class[] { AuditedMethodMappedSuperclass.class, AuditedAllSubclassEntity.class, NotAuditedSubclassEntity.class }; + return new Class[] { + AuditedMethodMappedSuperclass.class, + AuditedAllSubclassEntity.class, + NotAuditedSubclassEntity.class + }; } @Test - @Priority(10) + @Priority(10) public void initData() { // Revision 1 EntityManager em = getEntityManager(); em.getTransaction().begin(); - NotAuditedSubclassEntity nas = new NotAuditedSubclassEntity("nae","super str","not audited str"); - em.persist(nas); - AuditedAllSubclassEntity ae = new AuditedAllSubclassEntity("ae", "super str", "audited str"); - em.persist(ae); + NotAuditedSubclassEntity nas = new NotAuditedSubclassEntity( "nae", "super str", "not audited str" ); + em.persist( nas ); + AuditedAllSubclassEntity ae = new AuditedAllSubclassEntity( "ae", "super str", "audited str" ); + em.persist( ae ); id1_1 = ae.getId(); id2_1 = nas.getId(); em.getTransaction().commit(); // Revision 2 em.getTransaction().begin(); - ae = em.find(AuditedAllSubclassEntity.class, id1_1); - ae.setStr("ae new"); - ae.setSubAuditedStr("audited str new"); - nas = em.find(NotAuditedSubclassEntity.class, id2_1); - nas.setStr("nae new"); - nas.setNotAuditedStr("not aud str new"); + ae = em.find( AuditedAllSubclassEntity.class, id1_1 ); + ae.setStr( "ae new" ); + ae.setSubAuditedStr( "audited str new" ); + nas = em.find( NotAuditedSubclassEntity.class, id2_1 ); + nas.setStr( "nae new" ); + nas.setNotAuditedStr( "not aud str new" ); em.getTransaction().commit(); } @Test public void testRevisionsCountsForAudited() { - assert Arrays.asList(1, 2).equals( - getAuditReader().getRevisions(AuditedAllSubclassEntity.class, id1_1)); + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( AuditedAllSubclassEntity.class, id1_1 ) + ); } - - @Test(expected= NotAuditedException.class ) + + @Test(expected = NotAuditedException.class) public void testRevisionsCountsForNotAudited() { try { - getAuditReader().getRevisions(NotAuditedSubclassEntity.class, id2_1); - assert(false); - } catch (NotAuditedException nae) { + getAuditReader().getRevisions( NotAuditedSubclassEntity.class, id2_1 ); + assert (false); + } + catch (NotAuditedException nae) { throw nae; } } - + @Test public void testHistoryOfAudited() { - AuditedAllSubclassEntity ver1 = new AuditedAllSubclassEntity(id1_1, "ae", "super str", "audited str"); - AuditedAllSubclassEntity ver2 = new AuditedAllSubclassEntity(id1_1, "ae new", "super str", "audited str new"); - - AuditedAllSubclassEntity rev1 = getAuditReader().find(AuditedAllSubclassEntity.class, id1_1, 1); - AuditedAllSubclassEntity rev2 = getAuditReader().find(AuditedAllSubclassEntity.class, id1_1, 2); - + AuditedAllSubclassEntity ver1 = new AuditedAllSubclassEntity( id1_1, "ae", "super str", "audited str" ); + AuditedAllSubclassEntity ver2 = new AuditedAllSubclassEntity( id1_1, "ae new", "super str", "audited str new" ); + + AuditedAllSubclassEntity rev1 = getAuditReader().find( AuditedAllSubclassEntity.class, id1_1, 1 ); + AuditedAllSubclassEntity rev2 = getAuditReader().find( AuditedAllSubclassEntity.class, id1_1, 2 ); + //this property is not audited on superclass - assert(rev1.getOtherStr() == null); - assert(rev2.getOtherStr() == null); - - assert rev1.equals(ver1); - assert rev2.equals(ver2); + assert (rev1.getOtherStr() == null); + assert (rev2.getOtherStr() == null); + + assert rev1.equals( ver1 ); + assert rev2.equals( ver2 ); } - - @Test(expected=NotAuditedException.class) + + @Test(expected = NotAuditedException.class) public void testHistoryOfNotAudited() { try { - getAuditReader().find(NotAuditedSubclassEntity.class, id2_1, 1); - assert(false); - } catch (NotAuditedException nae) { + getAuditReader().find( NotAuditedSubclassEntity.class, id2_1, 1 ); + assert (false); + } + catch (NotAuditedException nae) { throw nae; } } - + } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/auditMethodSubclass/AuditedMethodSubclassEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/auditMethodSubclass/AuditedMethodSubclassEntity.java index 7750f124e0..d0650d795e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/auditMethodSubclass/AuditedMethodSubclassEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/auditMethodSubclass/AuditedMethodSubclassEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.superclass.auditAtMethodSuperclassLevel.auditMethodSubclass; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -37,59 +38,67 @@ import org.hibernate.envers.test.integration.superclass.auditAtMethodSuperclassL @Entity @Table(name = "AuditedMethodSubclass") public class AuditedMethodSubclassEntity extends AuditedMethodMappedSuperclass { - @Id - @GeneratedValue - private Integer id; - - @Audited - private String subAuditedStr; + @Id + @GeneratedValue + private Integer id; + + @Audited + private String subAuditedStr; public AuditedMethodSubclassEntity() { - } + } - public AuditedMethodSubclassEntity(Integer id, String str, String otherString, String subAuditedStr) { - super(str, otherString); - this.subAuditedStr = subAuditedStr; - this.id = id; - } + public AuditedMethodSubclassEntity(Integer id, String str, String otherString, String subAuditedStr) { + super( str, otherString ); + this.subAuditedStr = subAuditedStr; + this.id = id; + } - public AuditedMethodSubclassEntity(String str, String otherString, String subAuditedStr ) { - super(str, otherString); - this.subAuditedStr = subAuditedStr; - } + public AuditedMethodSubclassEntity(String str, String otherString, String subAuditedStr) { + super( str, otherString ); + this.subAuditedStr = subAuditedStr; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getSubAuditedStr() { + public String getSubAuditedStr() { return subAuditedStr; } public void setSubAuditedStr(String subAuditedStr) { this.subAuditedStr = subAuditedStr; } - - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof AuditedMethodSubclassEntity)) return false; - if (!super.equals(o)) return false; - AuditedMethodSubclassEntity that = (AuditedMethodSubclassEntity) o; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof AuditedMethodSubclassEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - if (id != null ? !id.equals(that.id) : that.id != null) return false; + AuditedMethodSubclassEntity that = (AuditedMethodSubclassEntity) o; - return true; - } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (id != null ? id.hashCode() : 0); - return result; - } + return true; + } + + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (id != null ? id.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/auditMethodSubclass/MappedSubclassingMethodAuditedTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/auditMethodSubclass/MappedSubclassingMethodAuditedTest.java index 22175c351b..788c385ea0 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/auditMethodSubclass/MappedSubclassingMethodAuditedTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditAtMethodSuperclassLevel/auditMethodSubclass/MappedSubclassingMethodAuditedTest.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.superclass.auditAtMethodSuperclassLevel.auditMethodSubclass; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.exception.NotAuditedException; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -34,11 +32,11 @@ import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.superclass.auditAtMethodSuperclassLevel.AuditedMethodMappedSuperclass; import org.hibernate.envers.test.integration.superclass.auditAtMethodSuperclassLevel.NotAuditedSubclassEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) - * * @author Hern&aacut;n Chanfreau - * */ public class MappedSubclassingMethodAuditedTest extends BaseEnversJPAFunctionalTestCase { private Integer id2_1; @@ -54,71 +52,79 @@ public class MappedSubclassingMethodAuditedTest extends BaseEnversJPAFunctionalT } @Test - @Priority(10) + @Priority(10) public void initData() { // Revision 1 EntityManager em = getEntityManager(); em.getTransaction().begin(); - NotAuditedSubclassEntity nas = new NotAuditedSubclassEntity("nae","super str","not audited str"); - em.persist(nas); - AuditedMethodSubclassEntity ae = new AuditedMethodSubclassEntity("ae", "super str", "audited str"); - em.persist(ae); + NotAuditedSubclassEntity nas = new NotAuditedSubclassEntity( "nae", "super str", "not audited str" ); + em.persist( nas ); + AuditedMethodSubclassEntity ae = new AuditedMethodSubclassEntity( "ae", "super str", "audited str" ); + em.persist( ae ); id1_1 = ae.getId(); id2_1 = nas.getId(); em.getTransaction().commit(); // Revision 2 em.getTransaction().begin(); - ae = em.find(AuditedMethodSubclassEntity.class, id1_1); - ae.setStr("ae new"); - ae.setSubAuditedStr("audited str new"); - nas = em.find(NotAuditedSubclassEntity.class, id2_1); - nas.setStr("nae new"); - nas.setNotAuditedStr("not aud str new"); + ae = em.find( AuditedMethodSubclassEntity.class, id1_1 ); + ae.setStr( "ae new" ); + ae.setSubAuditedStr( "audited str new" ); + nas = em.find( NotAuditedSubclassEntity.class, id2_1 ); + nas.setStr( "nae new" ); + nas.setNotAuditedStr( "not aud str new" ); em.getTransaction().commit(); } @Test public void testRevisionsCountsForAudited() { - assert Arrays.asList(1, 2).equals( - getAuditReader().getRevisions(AuditedMethodSubclassEntity.class, id1_1)); + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( AuditedMethodSubclassEntity.class, id1_1 ) + ); } - - @Test(expected= NotAuditedException.class ) + + @Test(expected = NotAuditedException.class) public void testRevisionsCountsForNotAudited() { try { - getAuditReader().getRevisions(NotAuditedSubclassEntity.class, id2_1); - assert(false); - } catch (NotAuditedException nae) { + getAuditReader().getRevisions( NotAuditedSubclassEntity.class, id2_1 ); + assert (false); + } + catch (NotAuditedException nae) { throw nae; } } - + @Test public void testHistoryOfAudited() { - AuditedMethodSubclassEntity ver1 = new AuditedMethodSubclassEntity(id1_1, "ae", "super str", "audited str"); - AuditedMethodSubclassEntity ver2 = new AuditedMethodSubclassEntity(id1_1, "ae new", "super str", "audited str new"); - - AuditedMethodSubclassEntity rev1 = getAuditReader().find(AuditedMethodSubclassEntity.class, id1_1, 1); - AuditedMethodSubclassEntity rev2 = getAuditReader().find(AuditedMethodSubclassEntity.class, id1_1, 2); - + AuditedMethodSubclassEntity ver1 = new AuditedMethodSubclassEntity( id1_1, "ae", "super str", "audited str" ); + AuditedMethodSubclassEntity ver2 = new AuditedMethodSubclassEntity( + id1_1, + "ae new", + "super str", + "audited str new" + ); + + AuditedMethodSubclassEntity rev1 = getAuditReader().find( AuditedMethodSubclassEntity.class, id1_1, 1 ); + AuditedMethodSubclassEntity rev2 = getAuditReader().find( AuditedMethodSubclassEntity.class, id1_1, 2 ); + //this property is not audited on superclass - assert(rev1.getOtherStr() == null); - assert(rev2.getOtherStr() == null); - - assert rev1.equals(ver1); - assert rev2.equals(ver2); + assert (rev1.getOtherStr() == null); + assert (rev2.getOtherStr() == null); + + assert rev1.equals( ver1 ); + assert rev2.equals( ver2 ); } - - @Test(expected=NotAuditedException.class) + + @Test(expected = NotAuditedException.class) public void testHistoryOfNotAudited() { try { - getAuditReader().find(NotAuditedSubclassEntity.class, id2_1, 1); - assert(false); - } catch (NotAuditedException nae) { + getAuditReader().find( NotAuditedSubclassEntity.class, id2_1, 1 ); + assert (false); + } + catch (NotAuditedException nae) { throw nae; } } - + } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/AuditedAllMappedSuperclass.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/AuditedAllMappedSuperclass.java index 7adcaa9628..cce9062251 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/AuditedAllMappedSuperclass.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/AuditedAllMappedSuperclass.java @@ -22,13 +22,13 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.superclass.auditedAtSuperclassLevel; + import javax.persistence.MappedSuperclass; import org.hibernate.envers.Audited; /** * @author Adam Warski (adam at warski dot org) - * * @author Hern&aacut;n Chanfreau */ @MappedSuperclass @@ -36,7 +36,7 @@ import org.hibernate.envers.Audited; public class AuditedAllMappedSuperclass { private String str; - + private String otherStr; public AuditedAllMappedSuperclass() { @@ -64,15 +64,18 @@ public class AuditedAllMappedSuperclass { } public boolean equals(Object o) { - if (this == o) + if ( this == o ) { return true; - if (!(o instanceof AuditedAllMappedSuperclass)) + } + if ( !(o instanceof AuditedAllMappedSuperclass) ) { return false; + } AuditedAllMappedSuperclass that = (AuditedAllMappedSuperclass) o; - if (str != null ? !str.equals(that.str) : that.str != null) + if ( str != null ? !str.equals( that.str ) : that.str != null ) { return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/NotAuditedSubclassEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/NotAuditedSubclassEntity.java index d128436b05..87d4d1e6bf 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/NotAuditedSubclassEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/NotAuditedSubclassEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.superclass.auditedAtSuperclassLevel; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -30,9 +31,7 @@ import javax.persistence.Table; /** * @author Adam Warski (adam at warski dot org) - * * @author Hernán Chanfreau - * */ @Entity @Table(name = "NotAuditedSubclass") @@ -40,20 +39,20 @@ public class NotAuditedSubclassEntity extends AuditedAllMappedSuperclass { @Id @GeneratedValue private Integer id; - + private String notAuditedStr; public NotAuditedSubclassEntity() { } public NotAuditedSubclassEntity(Integer id, String str, String otherStr, String notAuditedStr) { - super(str, otherStr); + super( str, otherStr ); this.notAuditedStr = notAuditedStr; this.id = id; } public NotAuditedSubclassEntity(String str, String otherStr, String notAuditedStr) { - super(str, otherStr); + super( str, otherStr ); this.notAuditedStr = notAuditedStr; } @@ -74,17 +73,21 @@ public class NotAuditedSubclassEntity extends AuditedAllMappedSuperclass { } public boolean equals(Object o) { - if (this == o) + if ( this == o ) { return true; - if (!(o instanceof NotAuditedSubclassEntity)) + } + if ( !(o instanceof NotAuditedSubclassEntity) ) { return false; - if (!super.equals(o)) + } + if ( !super.equals( o ) ) { return false; + } NotAuditedSubclassEntity that = (NotAuditedSubclassEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) + if ( id != null ? !id.equals( that.id ) : that.id != null ) { return false; + } return true; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/auditAllSubclass/AuditedAllSubclassEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/auditAllSubclass/AuditedAllSubclassEntity.java index 380ed6dc62..a40c69c973 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/auditAllSubclass/AuditedAllSubclassEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/auditAllSubclass/AuditedAllSubclassEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.superclass.auditedAtSuperclassLevel.auditAllSubclass; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -35,59 +36,67 @@ import org.hibernate.envers.test.integration.superclass.auditedAtSuperclassLevel */ @Entity @Audited -public class AuditedAllSubclassEntity extends AuditedAllMappedSuperclass { - @Id - @GeneratedValue - private Integer id; - - private String subAuditedStr; +public class AuditedAllSubclassEntity extends AuditedAllMappedSuperclass { + @Id + @GeneratedValue + private Integer id; + + private String subAuditedStr; public AuditedAllSubclassEntity() { - } + } - public AuditedAllSubclassEntity(Integer id, String str, String otherString, String subAuditedStr) { - super(str, otherString); - this.subAuditedStr = subAuditedStr; - this.id = id; - } + public AuditedAllSubclassEntity(Integer id, String str, String otherString, String subAuditedStr) { + super( str, otherString ); + this.subAuditedStr = subAuditedStr; + this.id = id; + } - public AuditedAllSubclassEntity(String str, String otherString, String subAuditedStr ) { - super(str, otherString); - this.subAuditedStr = subAuditedStr; - } + public AuditedAllSubclassEntity(String str, String otherString, String subAuditedStr) { + super( str, otherString ); + this.subAuditedStr = subAuditedStr; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getSubAuditedStr() { + public String getSubAuditedStr() { return subAuditedStr; } public void setSubAuditedStr(String subAuditedStr) { this.subAuditedStr = subAuditedStr; } - - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof AuditedAllSubclassEntity)) return false; - if (!super.equals(o)) return false; - AuditedAllSubclassEntity that = (AuditedAllSubclassEntity) o; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof AuditedAllSubclassEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - if (id != null ? !id.equals(that.id) : that.id != null) return false; + AuditedAllSubclassEntity that = (AuditedAllSubclassEntity) o; - return true; - } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (id != null ? id.hashCode() : 0); - return result; - } + return true; + } + + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (id != null ? id.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/auditAllSubclass/MappedSubclassingAllAuditedTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/auditAllSubclass/MappedSubclassingAllAuditedTest.java index 89a621f1b4..d5c38c3572 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/auditAllSubclass/MappedSubclassingAllAuditedTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/auditAllSubclass/MappedSubclassingAllAuditedTest.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.superclass.auditedAtSuperclassLevel.auditAllSubclass; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.exception.NotAuditedException; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -34,11 +32,11 @@ import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.superclass.auditedAtSuperclassLevel.AuditedAllMappedSuperclass; import org.hibernate.envers.test.integration.superclass.auditedAtSuperclassLevel.NotAuditedSubclassEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) - * * @author Hern&aacut;n Chanfreau - * */ public class MappedSubclassingAllAuditedTest extends BaseEnversJPAFunctionalTestCase { private Integer id2_1; @@ -46,74 +44,81 @@ public class MappedSubclassingAllAuditedTest extends BaseEnversJPAFunctionalTest @Override protected Class[] getAnnotatedClasses() { - return new Class[] { AuditedAllMappedSuperclass.class, AuditedAllSubclassEntity.class, NotAuditedSubclassEntity.class }; + return new Class[] { + AuditedAllMappedSuperclass.class, + AuditedAllSubclassEntity.class, + NotAuditedSubclassEntity.class + }; } @Test - @Priority(10) + @Priority(10) public void initData() { // Revision 1 EntityManager em = getEntityManager(); em.getTransaction().begin(); - NotAuditedSubclassEntity nas = new NotAuditedSubclassEntity("nae","super str","not audited str"); - em.persist(nas); - AuditedAllSubclassEntity ae = new AuditedAllSubclassEntity("ae", "super str", "audited str"); - em.persist(ae); + NotAuditedSubclassEntity nas = new NotAuditedSubclassEntity( "nae", "super str", "not audited str" ); + em.persist( nas ); + AuditedAllSubclassEntity ae = new AuditedAllSubclassEntity( "ae", "super str", "audited str" ); + em.persist( ae ); id1_1 = ae.getId(); id2_1 = nas.getId(); em.getTransaction().commit(); // Revision 2 em.getTransaction().begin(); - ae = em.find(AuditedAllSubclassEntity.class, id1_1); - ae.setStr("ae new"); - ae.setSubAuditedStr("audited str new"); - nas = em.find(NotAuditedSubclassEntity.class, id2_1); - nas.setStr("nae new"); - nas.setNotAuditedStr("not aud str new"); + ae = em.find( AuditedAllSubclassEntity.class, id1_1 ); + ae.setStr( "ae new" ); + ae.setSubAuditedStr( "audited str new" ); + nas = em.find( NotAuditedSubclassEntity.class, id2_1 ); + nas.setStr( "nae new" ); + nas.setNotAuditedStr( "not aud str new" ); em.getTransaction().commit(); } @Test public void testRevisionsCountsForAudited() { - assert Arrays.asList(1, 2).equals( - getAuditReader().getRevisions(AuditedAllSubclassEntity.class, id1_1)); + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( AuditedAllSubclassEntity.class, id1_1 ) + ); } - - @Test(expected= NotAuditedException.class ) + + @Test(expected = NotAuditedException.class) public void testRevisionsCountsForNotAudited() { try { - getAuditReader().getRevisions(NotAuditedSubclassEntity.class, id2_1); - assert(false); - } catch (NotAuditedException nae) { + getAuditReader().getRevisions( NotAuditedSubclassEntity.class, id2_1 ); + assert (false); + } + catch (NotAuditedException nae) { throw nae; } } - + @Test public void testHistoryOfAudited() { - AuditedAllSubclassEntity ver1 = new AuditedAllSubclassEntity(id1_1, "ae", "super str", "audited str"); - AuditedAllSubclassEntity ver2 = new AuditedAllSubclassEntity(id1_1, "ae new", "super str", "audited str new"); + AuditedAllSubclassEntity ver1 = new AuditedAllSubclassEntity( id1_1, "ae", "super str", "audited str" ); + AuditedAllSubclassEntity ver2 = new AuditedAllSubclassEntity( id1_1, "ae new", "super str", "audited str new" ); - AuditedAllSubclassEntity rev1 = getAuditReader().find(AuditedAllSubclassEntity.class, id1_1, 1); - AuditedAllSubclassEntity rev2 = getAuditReader().find(AuditedAllSubclassEntity.class, id1_1, 2); - - assert(rev1.getOtherStr() != null); - assert(rev2.getOtherStr() != null); - - assert rev1.equals(ver1); - assert rev2.equals(ver2); + AuditedAllSubclassEntity rev1 = getAuditReader().find( AuditedAllSubclassEntity.class, id1_1, 1 ); + AuditedAllSubclassEntity rev2 = getAuditReader().find( AuditedAllSubclassEntity.class, id1_1, 2 ); + + assert (rev1.getOtherStr() != null); + assert (rev2.getOtherStr() != null); + + assert rev1.equals( ver1 ); + assert rev2.equals( ver2 ); } - - @Test(expected=NotAuditedException.class) + + @Test(expected = NotAuditedException.class) public void testHistoryOfNotAudited() { try { - getAuditReader().find(NotAuditedSubclassEntity.class, id2_1, 1); - assert(false); - } catch (NotAuditedException nae) { + getAuditReader().find( NotAuditedSubclassEntity.class, id2_1, 1 ); + assert (false); + } + catch (NotAuditedException nae) { throw nae; } -} - + } + } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/auditMethodSubclass/AuditedMethodSubclassEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/auditMethodSubclass/AuditedMethodSubclassEntity.java index a51e103483..c940eb29f7 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/auditMethodSubclass/AuditedMethodSubclassEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/auditMethodSubclass/AuditedMethodSubclassEntity.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.integration.superclass.auditedAtSuperclassLevel.auditMethodSubclass; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -36,60 +37,68 @@ import org.hibernate.envers.test.integration.superclass.auditedAtSuperclassLevel */ @Entity @Table(name = "AuditedMethodSubclass") -public class AuditedMethodSubclassEntity extends AuditedAllMappedSuperclass { - @Id - @GeneratedValue - private Integer id; - - @Audited - private String subAuditedStr; +public class AuditedMethodSubclassEntity extends AuditedAllMappedSuperclass { + @Id + @GeneratedValue + private Integer id; + + @Audited + private String subAuditedStr; public AuditedMethodSubclassEntity() { - } + } - public AuditedMethodSubclassEntity(Integer id, String str, String otherString, String subAuditedStr) { - super(str, otherString); - this.subAuditedStr = subAuditedStr; - this.id = id; - } + public AuditedMethodSubclassEntity(Integer id, String str, String otherString, String subAuditedStr) { + super( str, otherString ); + this.subAuditedStr = subAuditedStr; + this.id = id; + } - public AuditedMethodSubclassEntity(String str, String otherString, String subAuditedStr ) { - super(str, otherString); - this.subAuditedStr = subAuditedStr; - } + public AuditedMethodSubclassEntity(String str, String otherString, String subAuditedStr) { + super( str, otherString ); + this.subAuditedStr = subAuditedStr; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getSubAuditedStr() { + public String getSubAuditedStr() { return subAuditedStr; } public void setSubAuditedStr(String subAuditedStr) { this.subAuditedStr = subAuditedStr; } - - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof AuditedMethodSubclassEntity)) return false; - if (!super.equals(o)) return false; - AuditedMethodSubclassEntity that = (AuditedMethodSubclassEntity) o; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof AuditedMethodSubclassEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - if (id != null ? !id.equals(that.id) : that.id != null) return false; + AuditedMethodSubclassEntity that = (AuditedMethodSubclassEntity) o; - return true; - } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (id != null ? id.hashCode() : 0); - return result; - } + return true; + } + + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (id != null ? id.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/auditMethodSubclass/MappedSubclassingMethodAuditedTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/auditMethodSubclass/MappedSubclassingMethodAuditedTest.java index a35141252b..84e4e08f7a 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/auditMethodSubclass/MappedSubclassingMethodAuditedTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditedAtSuperclassLevel/auditMethodSubclass/MappedSubclassingMethodAuditedTest.java @@ -23,10 +23,8 @@ */ package org.hibernate.envers.test.integration.superclass.auditedAtSuperclassLevel.auditMethodSubclass; -import java.util.Arrays; import javax.persistence.EntityManager; - -import org.junit.Test; +import java.util.Arrays; import org.hibernate.envers.exception.NotAuditedException; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -34,11 +32,11 @@ import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.integration.superclass.auditedAtSuperclassLevel.AuditedAllMappedSuperclass; import org.hibernate.envers.test.integration.superclass.auditedAtSuperclassLevel.NotAuditedSubclassEntity; +import org.junit.Test; + /** * @author Adam Warski (adam at warski dot org) - * * @author Hern&aacut;n Chanfreau - * */ public class MappedSubclassingMethodAuditedTest extends BaseEnversJPAFunctionalTestCase { private Integer id2_1; @@ -54,70 +52,78 @@ public class MappedSubclassingMethodAuditedTest extends BaseEnversJPAFunctionalT } @Test - @Priority(10) + @Priority(10) public void initData() { // Revision 1 EntityManager em = getEntityManager(); em.getTransaction().begin(); - NotAuditedSubclassEntity nas = new NotAuditedSubclassEntity("nae","super str","not audited str"); - em.persist(nas); - AuditedMethodSubclassEntity ae = new AuditedMethodSubclassEntity("ae", "super str", "audited str"); - em.persist(ae); + NotAuditedSubclassEntity nas = new NotAuditedSubclassEntity( "nae", "super str", "not audited str" ); + em.persist( nas ); + AuditedMethodSubclassEntity ae = new AuditedMethodSubclassEntity( "ae", "super str", "audited str" ); + em.persist( ae ); id1_1 = ae.getId(); id2_1 = nas.getId(); em.getTransaction().commit(); // Revision 2 em.getTransaction().begin(); - ae = em.find(AuditedMethodSubclassEntity.class, id1_1); - ae.setStr("ae new"); - ae.setSubAuditedStr("audited str new"); - nas = em.find(NotAuditedSubclassEntity.class, id2_1); - nas.setStr("nae new"); - nas.setNotAuditedStr("not aud str new"); + ae = em.find( AuditedMethodSubclassEntity.class, id1_1 ); + ae.setStr( "ae new" ); + ae.setSubAuditedStr( "audited str new" ); + nas = em.find( NotAuditedSubclassEntity.class, id2_1 ); + nas.setStr( "nae new" ); + nas.setNotAuditedStr( "not aud str new" ); em.getTransaction().commit(); } @Test public void testRevisionsCountsForAudited() { - assert Arrays.asList(1, 2).equals( - getAuditReader().getRevisions(AuditedMethodSubclassEntity.class, id1_1)); + assert Arrays.asList( 1, 2 ).equals( + getAuditReader().getRevisions( AuditedMethodSubclassEntity.class, id1_1 ) + ); } - - @Test(expected=NotAuditedException.class) + + @Test(expected = NotAuditedException.class) public void testRevisionsCountsForNotAudited() { try { - getAuditReader().getRevisions(NotAuditedSubclassEntity.class, id2_1); - assert(false); - } catch (NotAuditedException nae) { + getAuditReader().getRevisions( NotAuditedSubclassEntity.class, id2_1 ); + assert (false); + } + catch (NotAuditedException nae) { throw nae; } } - + @Test public void testHistoryOfAudited() { - AuditedMethodSubclassEntity ver1 = new AuditedMethodSubclassEntity(id1_1, "ae", "super str", "audited str"); - AuditedMethodSubclassEntity ver2 = new AuditedMethodSubclassEntity(id1_1, "ae new", "super str", "audited str new"); - - AuditedMethodSubclassEntity rev1 = getAuditReader().find(AuditedMethodSubclassEntity.class, id1_1, 1); - AuditedMethodSubclassEntity rev2 = getAuditReader().find(AuditedMethodSubclassEntity.class, id1_1, 2); - - assert(rev1.getOtherStr() != null); - assert(rev2.getOtherStr() != null); - - assert rev1.equals(ver1); - assert rev2.equals(ver2); + AuditedMethodSubclassEntity ver1 = new AuditedMethodSubclassEntity( id1_1, "ae", "super str", "audited str" ); + AuditedMethodSubclassEntity ver2 = new AuditedMethodSubclassEntity( + id1_1, + "ae new", + "super str", + "audited str new" + ); + + AuditedMethodSubclassEntity rev1 = getAuditReader().find( AuditedMethodSubclassEntity.class, id1_1, 1 ); + AuditedMethodSubclassEntity rev2 = getAuditReader().find( AuditedMethodSubclassEntity.class, id1_1, 2 ); + + assert (rev1.getOtherStr() != null); + assert (rev2.getOtherStr() != null); + + assert rev1.equals( ver1 ); + assert rev2.equals( ver2 ); } - - @Test(expected= NotAuditedException.class ) + + @Test(expected = NotAuditedException.class) public void testHistoryOfNotAudited() { try { - getAuditReader().find(NotAuditedSubclassEntity.class, id2_1, 1); - assert(false); - } catch (NotAuditedException nae) { + getAuditReader().find( NotAuditedSubclassEntity.class, id2_1, 1 ); + assert (false); + } + catch (NotAuditedException nae) { throw nae; } -} - + } + } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/AuditClassOverrideTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/AuditClassOverrideTest.java index d5e78e07a8..2d9a2cb159 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/AuditClassOverrideTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/AuditClassOverrideTest.java @@ -2,13 +2,14 @@ package org.hibernate.envers.test.integration.superclass.auditoverride; import javax.persistence.EntityManager; -import org.junit.Assert; -import org.junit.Test; - import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.mapping.Column; import org.hibernate.mapping.Table; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -16,62 +17,81 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-4439") public class AuditClassOverrideTest extends BaseEnversJPAFunctionalTestCase { - private Integer classAuditedEntityId = null; - private Integer classNotAuditedEntityId = null; - private Table classAuditedTable = null; - private Table classNotAuditedTable = null; + private Integer classAuditedEntityId = null; + private Integer classNotAuditedEntityId = null; + private Table classAuditedTable = null; + private Table classNotAuditedTable = null; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { ClassOverrideAuditedEntity.class, ClassOverrideNotAuditedEntity.class }; - } + return new Class[] {ClassOverrideAuditedEntity.class, ClassOverrideNotAuditedEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 1 - em.getTransaction().begin(); - ClassOverrideAuditedEntity classOverrideAuditedEntity = new ClassOverrideAuditedEntity("data 1", 1, "data 2"); - em.persist(classOverrideAuditedEntity); - em.getTransaction().commit(); - classAuditedEntityId = classOverrideAuditedEntity.getId(); + // Revision 1 + em.getTransaction().begin(); + ClassOverrideAuditedEntity classOverrideAuditedEntity = new ClassOverrideAuditedEntity( "data 1", 1, "data 2" ); + em.persist( classOverrideAuditedEntity ); + em.getTransaction().commit(); + classAuditedEntityId = classOverrideAuditedEntity.getId(); - // Revision 2 - em.getTransaction().begin(); - ClassOverrideNotAuditedEntity classOverrideNotAuditedEntity = new ClassOverrideNotAuditedEntity("data 1", 1, "data 2"); - em.persist(classOverrideNotAuditedEntity); - em.getTransaction().commit(); - classNotAuditedEntityId = classOverrideNotAuditedEntity.getId(); + // Revision 2 + em.getTransaction().begin(); + ClassOverrideNotAuditedEntity classOverrideNotAuditedEntity = new ClassOverrideNotAuditedEntity( + "data 1", + 1, + "data 2" + ); + em.persist( classOverrideNotAuditedEntity ); + em.getTransaction().commit(); + classNotAuditedEntityId = classOverrideNotAuditedEntity.getId(); - classAuditedTable = getCfg().getClassMapping("org.hibernate.envers.test.integration.superclass.auditoverride.ClassOverrideAuditedEntity_AUD").getTable(); - classNotAuditedTable = getCfg().getClassMapping("org.hibernate.envers.test.integration.superclass.auditoverride.ClassOverrideNotAuditedEntity_AUD").getTable(); - } + classAuditedTable = getCfg().getClassMapping( + "org.hibernate.envers.test.integration.superclass.auditoverride.ClassOverrideAuditedEntity_AUD" + ).getTable(); + classNotAuditedTable = getCfg().getClassMapping( + "org.hibernate.envers.test.integration.superclass.auditoverride.ClassOverrideNotAuditedEntity_AUD" + ).getTable(); + } - @Test - public void testAuditedProperty() { - Assert.assertNotNull(classAuditedTable.getColumn(new Column("number1"))); - Assert.assertNotNull(classAuditedTable.getColumn(new Column("str1"))); - Assert.assertNotNull(classAuditedTable.getColumn(new Column("str2"))); - Assert.assertNotNull(classNotAuditedTable.getColumn(new Column("str2"))); - } + @Test + public void testAuditedProperty() { + Assert.assertNotNull( classAuditedTable.getColumn( new Column( "number1" ) ) ); + Assert.assertNotNull( classAuditedTable.getColumn( new Column( "str1" ) ) ); + Assert.assertNotNull( classAuditedTable.getColumn( new Column( "str2" ) ) ); + Assert.assertNotNull( classNotAuditedTable.getColumn( new Column( "str2" ) ) ); + } - @Test - public void testNotAuditedProperty() { - Assert.assertNull(classNotAuditedTable.getColumn(new Column("number1"))); - Assert.assertNull(classNotAuditedTable.getColumn(new Column("str1"))); - } + @Test + public void testNotAuditedProperty() { + Assert.assertNull( classNotAuditedTable.getColumn( new Column( "number1" ) ) ); + Assert.assertNull( classNotAuditedTable.getColumn( new Column( "str1" ) ) ); + } - @Test - public void testHistoryOfClassOverrideAuditedEntity() { - ClassOverrideAuditedEntity ver1 = new ClassOverrideAuditedEntity("data 1", 1, classAuditedEntityId, "data 2"); - Assert.assertEquals(ver1, getAuditReader().find(ClassOverrideAuditedEntity.class, classAuditedEntityId, 1)); - } + @Test + public void testHistoryOfClassOverrideAuditedEntity() { + ClassOverrideAuditedEntity ver1 = new ClassOverrideAuditedEntity( "data 1", 1, classAuditedEntityId, "data 2" ); + Assert.assertEquals( ver1, getAuditReader().find( ClassOverrideAuditedEntity.class, classAuditedEntityId, 1 ) ); + } - @Test - public void testHistoryOfClassOverrideNotAuditedEntity() { - ClassOverrideNotAuditedEntity ver1 = new ClassOverrideNotAuditedEntity(null, null, classNotAuditedEntityId, "data 2"); - Assert.assertEquals(ver1, getAuditReader().find(ClassOverrideNotAuditedEntity.class, classNotAuditedEntityId, 2)); - } + @Test + public void testHistoryOfClassOverrideNotAuditedEntity() { + ClassOverrideNotAuditedEntity ver1 = new ClassOverrideNotAuditedEntity( + null, + null, + classNotAuditedEntityId, + "data 2" + ); + Assert.assertEquals( + ver1, getAuditReader().find( + ClassOverrideNotAuditedEntity.class, + classNotAuditedEntityId, + 2 + ) + ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/AuditPropertyOverrideTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/AuditPropertyOverrideTest.java index 512b805a6a..4ee096fb92 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/AuditPropertyOverrideTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/AuditPropertyOverrideTest.java @@ -2,13 +2,14 @@ package org.hibernate.envers.test.integration.superclass.auditoverride; import javax.persistence.EntityManager; -import org.junit.Assert; -import org.junit.Test; - import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.mapping.Column; import org.hibernate.mapping.Table; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** @@ -16,82 +17,95 @@ import org.hibernate.testing.TestForIssue; */ @TestForIssue(jiraKey = "HHH-4439") public class AuditPropertyOverrideTest extends BaseEnversJPAFunctionalTestCase { - private Integer propertyEntityId = null; - private Integer transitiveEntityId = null; - private Integer auditedEntityId = null; - private Table propertyTable = null; - private Table transitiveTable = null; - private Table auditedTable = null; + private Integer propertyEntityId = null; + private Integer transitiveEntityId = null; + private Integer auditedEntityId = null; + private Table propertyTable = null; + private Table transitiveTable = null; + private Table auditedTable = null; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { PropertyOverrideEntity.class, TransitiveOverrideEntity.class, AuditedSpecialEntity.class }; - } + return new Class[] {PropertyOverrideEntity.class, TransitiveOverrideEntity.class, AuditedSpecialEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 1 - em.getTransaction().begin(); - PropertyOverrideEntity propertyEntity = new PropertyOverrideEntity("data 1", 1, "data 2"); - em.persist(propertyEntity); - em.getTransaction().commit(); - propertyEntityId = propertyEntity.getId(); + // Revision 1 + em.getTransaction().begin(); + PropertyOverrideEntity propertyEntity = new PropertyOverrideEntity( "data 1", 1, "data 2" ); + em.persist( propertyEntity ); + em.getTransaction().commit(); + propertyEntityId = propertyEntity.getId(); - // Revision 2 - em.getTransaction().begin(); - TransitiveOverrideEntity transitiveEntity = new TransitiveOverrideEntity("data 1", 1, "data 2", 2, "data 3"); - em.persist(transitiveEntity); - em.getTransaction().commit(); - transitiveEntityId = transitiveEntity.getId(); + // Revision 2 + em.getTransaction().begin(); + TransitiveOverrideEntity transitiveEntity = new TransitiveOverrideEntity( "data 1", 1, "data 2", 2, "data 3" ); + em.persist( transitiveEntity ); + em.getTransaction().commit(); + transitiveEntityId = transitiveEntity.getId(); - // Revision 3 - em.getTransaction().begin(); - AuditedSpecialEntity auditedEntity = new AuditedSpecialEntity("data 1", 1, "data 2"); - em.persist(auditedEntity); - em.getTransaction().commit(); - auditedEntityId = auditedEntity.getId(); + // Revision 3 + em.getTransaction().begin(); + AuditedSpecialEntity auditedEntity = new AuditedSpecialEntity( "data 1", 1, "data 2" ); + em.persist( auditedEntity ); + em.getTransaction().commit(); + auditedEntityId = auditedEntity.getId(); - propertyTable = getCfg().getClassMapping("org.hibernate.envers.test.integration.superclass.auditoverride.PropertyOverrideEntity_AUD").getTable(); - transitiveTable = getCfg().getClassMapping("org.hibernate.envers.test.integration.superclass.auditoverride.TransitiveOverrideEntity_AUD").getTable(); - auditedTable = getCfg().getClassMapping("org.hibernate.envers.test.integration.superclass.auditoverride.AuditedSpecialEntity_AUD").getTable(); - } + propertyTable = getCfg().getClassMapping( + "org.hibernate.envers.test.integration.superclass.auditoverride.PropertyOverrideEntity_AUD" + ).getTable(); + transitiveTable = getCfg().getClassMapping( + "org.hibernate.envers.test.integration.superclass.auditoverride.TransitiveOverrideEntity_AUD" + ).getTable(); + auditedTable = getCfg().getClassMapping( + "org.hibernate.envers.test.integration.superclass.auditoverride.AuditedSpecialEntity_AUD" + ).getTable(); + } - @Test - public void testNotAuditedProperty() { - Assert.assertNull(propertyTable.getColumn(new Column("str1"))); - } + @Test + public void testNotAuditedProperty() { + Assert.assertNull( propertyTable.getColumn( new Column( "str1" ) ) ); + } - @Test - public void testAuditedProperty() { - Assert.assertNotNull(propertyTable.getColumn(new Column("number1"))); - Assert.assertNotNull(transitiveTable.getColumn(new Column("number2"))); - Assert.assertNotNull(auditedTable.getColumn(new Column("str1"))); - } + @Test + public void testAuditedProperty() { + Assert.assertNotNull( propertyTable.getColumn( new Column( "number1" ) ) ); + Assert.assertNotNull( transitiveTable.getColumn( new Column( "number2" ) ) ); + Assert.assertNotNull( auditedTable.getColumn( new Column( "str1" ) ) ); + } - @Test - public void testTransitiveAuditedProperty() { - Assert.assertNotNull(transitiveTable.getColumn(new Column("number1"))); - Assert.assertNotNull(transitiveTable.getColumn(new Column("str1"))); - } + @Test + public void testTransitiveAuditedProperty() { + Assert.assertNotNull( transitiveTable.getColumn( new Column( "number1" ) ) ); + Assert.assertNotNull( transitiveTable.getColumn( new Column( "str1" ) ) ); + } - @Test - public void testHistoryOfPropertyOverrideEntity() { - PropertyOverrideEntity ver1 = new PropertyOverrideEntity(null, 1, propertyEntityId, "data 2"); - Assert.assertEquals(ver1, getAuditReader().find(PropertyOverrideEntity.class, propertyEntityId, 1)); - } + @Test + public void testHistoryOfPropertyOverrideEntity() { + PropertyOverrideEntity ver1 = new PropertyOverrideEntity( null, 1, propertyEntityId, "data 2" ); + Assert.assertEquals( ver1, getAuditReader().find( PropertyOverrideEntity.class, propertyEntityId, 1 ) ); + } - @Test - public void testHistoryOfTransitiveOverrideEntity() { - TransitiveOverrideEntity ver1 = new TransitiveOverrideEntity("data 1", 1, transitiveEntityId, "data 2", 2, "data 3"); - Assert.assertEquals(ver1, getAuditReader().find(TransitiveOverrideEntity.class, transitiveEntityId, 2)); - } + @Test + public void testHistoryOfTransitiveOverrideEntity() { + TransitiveOverrideEntity ver1 = new TransitiveOverrideEntity( + "data 1", + 1, + transitiveEntityId, + "data 2", + 2, + "data 3" + ); + Assert.assertEquals( ver1, getAuditReader().find( TransitiveOverrideEntity.class, transitiveEntityId, 2 ) ); + } - @Test - public void testHistoryOfAuditedSpecialEntity() { - AuditedSpecialEntity ver1 = new AuditedSpecialEntity("data 1", null, auditedEntityId, "data 2"); - Assert.assertEquals(ver1, getAuditReader().find(AuditedSpecialEntity.class, auditedEntityId, 3)); - } + @Test + public void testHistoryOfAuditedSpecialEntity() { + AuditedSpecialEntity ver1 = new AuditedSpecialEntity( "data 1", null, auditedEntityId, "data 2" ); + Assert.assertEquals( ver1, getAuditReader().find( AuditedSpecialEntity.class, auditedEntityId, 3 ) ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/AuditedBaseEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/AuditedBaseEntity.java index 08c4bb9464..98613404b1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/AuditedBaseEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/AuditedBaseEntity.java @@ -1,9 +1,9 @@ package org.hibernate.envers.test.integration.superclass.auditoverride; -import java.io.Serializable; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.MappedSuperclass; +import java.io.Serializable; import org.hibernate.envers.Audited; @@ -13,74 +13,84 @@ import org.hibernate.envers.Audited; @Audited @MappedSuperclass public class AuditedBaseEntity implements Serializable { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String str1; + private String str1; - private Integer number1; + private Integer number1; - public AuditedBaseEntity() { - } + public AuditedBaseEntity() { + } - public AuditedBaseEntity(String str1, Integer number1, Integer id) { - this.id = id; - this.str1 = str1; - this.number1 = number1; - } + public AuditedBaseEntity(String str1, Integer number1, Integer id) { + this.id = id; + this.str1 = str1; + this.number1 = number1; + } - public AuditedBaseEntity(String str1, Integer number1) { - this.str1 = str1; - this.number1 = number1; - } + public AuditedBaseEntity(String str1, Integer number1) { + this.str1 = str1; + this.number1 = number1; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - public Integer getNumber1() { - return number1; - } + public Integer getNumber1() { + return number1; + } - public void setNumber1(Integer number1) { - this.number1 = number1; - } + public void setNumber1(Integer number1) { + this.number1 = number1; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof AuditedBaseEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof AuditedBaseEntity) ) { + return false; + } - AuditedBaseEntity that = (AuditedBaseEntity) o; + AuditedBaseEntity that = (AuditedBaseEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (number1 != null ? !number1.equals(that.number1) : that.number1 != null) return false; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( number1 != null ? !number1.equals( that.number1 ) : that.number1 != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str1 != null ? str1.hashCode() : 0); - result = 31 * result + (number1 != null ? number1.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str1 != null ? str1.hashCode() : 0); + result = 31 * result + (number1 != null ? number1.hashCode() : 0); + return result; + } - public String toString() { - return "AuditedBaseEntity(id = " + id + ", str1 = " + str1 + ", number1 = " + number1 + ")"; - } + public String toString() { + return "AuditedBaseEntity(id = " + id + ", str1 = " + str1 + ", number1 = " + number1 + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/AuditedSpecialEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/AuditedSpecialEntity.java index 16461b72d4..2e3b5e1c21 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/AuditedSpecialEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/AuditedSpecialEntity.java @@ -12,52 +12,60 @@ import org.hibernate.envers.Audited; @Entity @AuditOverrides({@AuditOverride(forClass = NotAuditedBaseEntity.class, name = "str1", isAudited = true)}) public class AuditedSpecialEntity extends NotAuditedBaseEntity { - @Audited - private String str2; + @Audited + private String str2; - public AuditedSpecialEntity() { - } + public AuditedSpecialEntity() { + } - public AuditedSpecialEntity(String str1, Integer number, String str2) { - super(str1, number); - this.str2 = str2; - } + public AuditedSpecialEntity(String str1, Integer number, String str2) { + super( str1, number ); + this.str2 = str2; + } - public AuditedSpecialEntity(String str1, Integer number, Integer id, String str2) { - super(str1, number, id); - this.str2 = str2; - } + public AuditedSpecialEntity(String str1, Integer number, Integer id, String str2) { + super( str1, number, id ); + this.str2 = str2; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof AuditedSpecialEntity)) return false; - if (!super.equals(o)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof AuditedSpecialEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - AuditedSpecialEntity that = (AuditedSpecialEntity) o; + AuditedSpecialEntity that = (AuditedSpecialEntity) o; - if (str2 != null ? !str2.equals(that.str2) : that.str2 != null) return false; + if ( str2 != null ? !str2.equals( that.str2 ) : that.str2 != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (str2 != null ? str2.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (str2 != null ? str2.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "AuditedSpecialEntity(" + super.toString() + ", str2 = " + str2 + ")"; - } + @Override + public String toString() { + return "AuditedSpecialEntity(" + super.toString() + ", str2 = " + str2 + ")"; + } - public String getStr2() { - return str2; - } + public String getStr2() { + return str2; + } - public void setStr2(String str2) { - this.str2 = str2; - } + public void setStr2(String str2) { + this.str2 = str2; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/BaseEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/BaseEntity.java index 59599cee64..9cf952d2b5 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/BaseEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/BaseEntity.java @@ -1,9 +1,9 @@ package org.hibernate.envers.test.integration.superclass.auditoverride; -import java.io.Serializable; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.MappedSuperclass; +import java.io.Serializable; import org.hibernate.envers.Audited; import org.hibernate.envers.NotAudited; @@ -13,76 +13,86 @@ import org.hibernate.envers.NotAudited; */ @MappedSuperclass public class BaseEntity implements Serializable { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - @Audited - private String str1; + @Audited + private String str1; - @NotAudited - private Integer number1; + @NotAudited + private Integer number1; - public BaseEntity() { - } + public BaseEntity() { + } - public BaseEntity(String str1, Integer number1, Integer id) { - this.id = id; - this.str1 = str1; - this.number1 = number1; - } + public BaseEntity(String str1, Integer number1, Integer id) { + this.id = id; + this.str1 = str1; + this.number1 = number1; + } - public BaseEntity(String str1, Integer number1) { - this.str1 = str1; - this.number1 = number1; - } + public BaseEntity(String str1, Integer number1) { + this.str1 = str1; + this.number1 = number1; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - public Integer getNumber1() { - return number1; - } + public Integer getNumber1() { + return number1; + } - public void setNumber1(Integer number1) { - this.number1 = number1; - } + public void setNumber1(Integer number1) { + this.number1 = number1; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof BaseEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof BaseEntity) ) { + return false; + } - BaseEntity that = (BaseEntity) o; + BaseEntity that = (BaseEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (number1 != null ? !number1.equals(that.number1) : that.number1 != null) return false; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( number1 != null ? !number1.equals( that.number1 ) : that.number1 != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str1 != null ? str1.hashCode() : 0); - result = 31 * result + (number1 != null ? number1.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str1 != null ? str1.hashCode() : 0); + result = 31 * result + (number1 != null ? number1.hashCode() : 0); + return result; + } - public String toString() { - return "BaseEntity(id = " + id + ", str1 = " + str1 + ", number1 = " + number1 + ")"; - } + public String toString() { + return "BaseEntity(id = " + id + ", str1 = " + str1 + ", number1 = " + number1 + ")"; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/ClassOverrideAuditedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/ClassOverrideAuditedEntity.java index 1ba841cc08..9b200b27e3 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/ClassOverrideAuditedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/ClassOverrideAuditedEntity.java @@ -14,52 +14,60 @@ import org.hibernate.envers.Audited; @Table(name = "ClassOverrideAudited") @AuditOverrides({@AuditOverride(forClass = NotAuditedBaseEntity.class, isAudited = true)}) public class ClassOverrideAuditedEntity extends NotAuditedBaseEntity { - @Audited - private String str2; + @Audited + private String str2; - public ClassOverrideAuditedEntity() { - } + public ClassOverrideAuditedEntity() { + } - public ClassOverrideAuditedEntity(String str1, Integer number, String str2) { - super(str1, number); - this.str2 = str2; - } + public ClassOverrideAuditedEntity(String str1, Integer number, String str2) { + super( str1, number ); + this.str2 = str2; + } - public ClassOverrideAuditedEntity(String str1, Integer number, Integer id, String str2) { - super(str1, number, id); - this.str2 = str2; - } + public ClassOverrideAuditedEntity(String str1, Integer number, Integer id, String str2) { + super( str1, number, id ); + this.str2 = str2; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ClassOverrideAuditedEntity)) return false; - if (!super.equals(o)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ClassOverrideAuditedEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ClassOverrideAuditedEntity that = (ClassOverrideAuditedEntity) o; + ClassOverrideAuditedEntity that = (ClassOverrideAuditedEntity) o; - if (str2 != null ? !str2.equals(that.str2) : that.str2 != null) return false; + if ( str2 != null ? !str2.equals( that.str2 ) : that.str2 != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (str2 != null ? str2.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (str2 != null ? str2.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "ClassOverrideAuditedEntity(" + super.toString() + ", str2 = " + str2 + ")"; - } + @Override + public String toString() { + return "ClassOverrideAuditedEntity(" + super.toString() + ", str2 = " + str2 + ")"; + } - public String getStr2() { - return str2; - } + public String getStr2() { + return str2; + } - public void setStr2(String str2) { - this.str2 = str2; - } + public void setStr2(String str2) { + this.str2 = str2; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/ClassOverrideNotAuditedEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/ClassOverrideNotAuditedEntity.java index d31cbc0773..32803c0b17 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/ClassOverrideNotAuditedEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/ClassOverrideNotAuditedEntity.java @@ -14,52 +14,60 @@ import org.hibernate.envers.Audited; @Table(name = "ClassOverrideNotAudited") @AuditOverrides({@AuditOverride(forClass = AuditedBaseEntity.class, isAudited = false)}) public class ClassOverrideNotAuditedEntity extends AuditedBaseEntity { - @Audited - private String str2; + @Audited + private String str2; - public ClassOverrideNotAuditedEntity() { - } + public ClassOverrideNotAuditedEntity() { + } - public ClassOverrideNotAuditedEntity(String str1, Integer number, String str2) { - super(str1, number); - this.str2 = str2; - } + public ClassOverrideNotAuditedEntity(String str1, Integer number, String str2) { + super( str1, number ); + this.str2 = str2; + } - public ClassOverrideNotAuditedEntity(String str1, Integer number, Integer id, String str2) { - super(str1, number, id); - this.str2 = str2; - } + public ClassOverrideNotAuditedEntity(String str1, Integer number, Integer id, String str2) { + super( str1, number, id ); + this.str2 = str2; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ClassOverrideNotAuditedEntity)) return false; - if (!super.equals(o)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ClassOverrideNotAuditedEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ClassOverrideNotAuditedEntity that = (ClassOverrideNotAuditedEntity) o; + ClassOverrideNotAuditedEntity that = (ClassOverrideNotAuditedEntity) o; - if (str2 != null ? !str2.equals(that.str2) : that.str2 != null) return false; + if ( str2 != null ? !str2.equals( that.str2 ) : that.str2 != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (str2 != null ? str2.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (str2 != null ? str2.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "ClassOverrideNotAuditedEntity(" + super.toString() + ", str2 = " + str2 + ")"; - } + @Override + public String toString() { + return "ClassOverrideNotAuditedEntity(" + super.toString() + ", str2 = " + str2 + ")"; + } - public String getStr2() { - return str2; - } + public String getStr2() { + return str2; + } - public void setStr2(String str2) { - this.str2 = str2; - } + public void setStr2(String str2) { + this.str2 = str2; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/ExtendedBaseEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/ExtendedBaseEntity.java index 7be515cb33..bda036c637 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/ExtendedBaseEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/ExtendedBaseEntity.java @@ -11,70 +11,82 @@ import org.hibernate.envers.NotAudited; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @MappedSuperclass -@AuditOverrides({@AuditOverride(forClass = BaseEntity.class, name = "str1", isAudited = false), - @AuditOverride(forClass = BaseEntity.class, name = "number1", isAudited = true)}) +@AuditOverrides({ + @AuditOverride(forClass = BaseEntity.class, name = "str1", isAudited = false), + @AuditOverride(forClass = BaseEntity.class, name = "number1", isAudited = true) + }) public class ExtendedBaseEntity extends BaseEntity { - @Audited - private String str2; + @Audited + private String str2; - @NotAudited - private Integer number2; + @NotAudited + private Integer number2; - public ExtendedBaseEntity() { - } + public ExtendedBaseEntity() { + } - public ExtendedBaseEntity(String str1, Integer number1, Integer id, String str2, Integer number2) { - super(str1, number1, id); - this.str2 = str2; - this.number2 = number2; - } + public ExtendedBaseEntity(String str1, Integer number1, Integer id, String str2, Integer number2) { + super( str1, number1, id ); + this.str2 = str2; + this.number2 = number2; + } - public ExtendedBaseEntity(String str1, Integer number1, String str2, Integer number2) { - super(str1, number1); - this.str2 = str2; - this.number2 = number2; - } + public ExtendedBaseEntity(String str1, Integer number1, String str2, Integer number2) { + super( str1, number1 ); + this.str2 = str2; + this.number2 = number2; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ExtendedBaseEntity)) return false; - if (!super.equals(o)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ExtendedBaseEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ExtendedBaseEntity that = (ExtendedBaseEntity) o; + ExtendedBaseEntity that = (ExtendedBaseEntity) o; - if (number2 != null ? !number2.equals(that.number2) : that.number2 != null) return false; - if (str2 != null ? !str2.equals(that.str2) : that.str2 != null) return false; + if ( number2 != null ? !number2.equals( that.number2 ) : that.number2 != null ) { + return false; + } + if ( str2 != null ? !str2.equals( that.str2 ) : that.str2 != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (str2 != null ? str2.hashCode() : 0); - result = 31 * result + (number2 != null ? number2.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (str2 != null ? str2.hashCode() : 0); + result = 31 * result + (number2 != null ? number2.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "ExtendedBaseEntity(" + super.toString() + ", str2 = " + str2 + ", number2 = " + number2 + ")"; - } + @Override + public String toString() { + return "ExtendedBaseEntity(" + super.toString() + ", str2 = " + str2 + ", number2 = " + number2 + ")"; + } - public String getStr2() { - return str2; - } + public String getStr2() { + return str2; + } - public void setStr2(String str2) { - this.str2 = str2; - } + public void setStr2(String str2) { + this.str2 = str2; + } - public Integer getNumber2() { - return number2; - } + public Integer getNumber2() { + return number2; + } - public void setNumber2(Integer number2) { - this.number2 = number2; - } + public void setNumber2(Integer number2) { + this.number2 = number2; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/MixedOverrideEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/MixedOverrideEntity.java index 415bcf34f1..e3f6e20d8e 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/MixedOverrideEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/MixedOverrideEntity.java @@ -11,54 +11,64 @@ import org.hibernate.envers.Audited; */ @Entity @Audited -@AuditOverrides({@AuditOverride(forClass = AuditedBaseEntity.class, isAudited = false), - @AuditOverride(forClass = AuditedBaseEntity.class, name = "number1", isAudited = true)}) +@AuditOverrides({ + @AuditOverride(forClass = AuditedBaseEntity.class, isAudited = false), + @AuditOverride(forClass = AuditedBaseEntity.class, name = "number1", isAudited = true) + }) public class MixedOverrideEntity extends AuditedBaseEntity { - private String str2; + private String str2; - public MixedOverrideEntity() { - } + public MixedOverrideEntity() { + } - public MixedOverrideEntity(String str1, Integer number, String str2) { - super(str1, number); - this.str2 = str2; - } + public MixedOverrideEntity(String str1, Integer number, String str2) { + super( str1, number ); + this.str2 = str2; + } - public MixedOverrideEntity(String str1, Integer number, Integer id, String str2) { - super(str1, number, id); - this.str2 = str2; - } + public MixedOverrideEntity(String str1, Integer number, Integer id, String str2) { + super( str1, number, id ); + this.str2 = str2; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof MixedOverrideEntity)) return false; - if (!super.equals(o)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof MixedOverrideEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - MixedOverrideEntity that = (MixedOverrideEntity) o; + MixedOverrideEntity that = (MixedOverrideEntity) o; - if (str2 != null ? !str2.equals(that.str2) : that.str2 != null) return false; + if ( str2 != null ? !str2.equals( that.str2 ) : that.str2 != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (str2 != null ? str2.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (str2 != null ? str2.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "MixedOverrideEntity(" + super.toString() + ", str2 = " + str2 + ")"; - } + @Override + public String toString() { + return "MixedOverrideEntity(" + super.toString() + ", str2 = " + str2 + ")"; + } - public String getStr2() { - return str2; - } + public String getStr2() { + return str2; + } - public void setStr2(String str2) { - this.str2 = str2; - } + public void setStr2(String str2) { + this.str2 = str2; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/MixedOverrideTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/MixedOverrideTest.java index 97d09f4eee..169d0afb68 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/MixedOverrideTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/MixedOverrideTest.java @@ -2,57 +2,60 @@ package org.hibernate.envers.test.integration.superclass.auditoverride; import javax.persistence.EntityManager; -import org.junit.Assert; -import org.junit.Test; - import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.mapping.Column; import org.hibernate.mapping.Table; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @TestForIssue(jiraKey = "HHH-4439") -public class MixedOverrideTest extends BaseEnversJPAFunctionalTestCase { - private Integer mixedEntityId = null; - private Table mixedTable = null; +public class MixedOverrideTest extends BaseEnversJPAFunctionalTestCase { + private Integer mixedEntityId = null; + private Table mixedTable = null; @Override protected Class[] getAnnotatedClasses() { - return new Class[] { MixedOverrideEntity.class }; - } + return new Class[] {MixedOverrideEntity.class}; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 1 - em.getTransaction().begin(); - MixedOverrideEntity mixedEntity = new MixedOverrideEntity("data 1", 1, "data 2"); - em.persist(mixedEntity); - em.getTransaction().commit(); - mixedEntityId = mixedEntity.getId(); + // Revision 1 + em.getTransaction().begin(); + MixedOverrideEntity mixedEntity = new MixedOverrideEntity( "data 1", 1, "data 2" ); + em.persist( mixedEntity ); + em.getTransaction().commit(); + mixedEntityId = mixedEntity.getId(); - mixedTable = getCfg().getClassMapping("org.hibernate.envers.test.integration.superclass.auditoverride.MixedOverrideEntity_AUD").getTable(); - } + mixedTable = getCfg().getClassMapping( + "org.hibernate.envers.test.integration.superclass.auditoverride.MixedOverrideEntity_AUD" + ).getTable(); + } - @Test - public void testAuditedProperty() { - Assert.assertNotNull(mixedTable.getColumn(new Column("number1"))); - Assert.assertNotNull(mixedTable.getColumn(new Column("str2"))); - } + @Test + public void testAuditedProperty() { + Assert.assertNotNull( mixedTable.getColumn( new Column( "number1" ) ) ); + Assert.assertNotNull( mixedTable.getColumn( new Column( "str2" ) ) ); + } - @Test - public void testNotAuditedProperty() { - Assert.assertNull(mixedTable.getColumn(new Column("str1"))); - } + @Test + public void testNotAuditedProperty() { + Assert.assertNull( mixedTable.getColumn( new Column( "str1" ) ) ); + } - @Test - public void testHistoryOfMixedEntity() { - MixedOverrideEntity ver1 = new MixedOverrideEntity(null, 1, mixedEntityId, "data 2"); - Assert.assertEquals(ver1, getAuditReader().find(MixedOverrideEntity.class, mixedEntityId, 1)); - } + @Test + public void testHistoryOfMixedEntity() { + MixedOverrideEntity ver1 = new MixedOverrideEntity( null, 1, mixedEntityId, "data 2" ); + Assert.assertEquals( ver1, getAuditReader().find( MixedOverrideEntity.class, mixedEntityId, 1 ) ); + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/NotAuditedBaseEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/NotAuditedBaseEntity.java index e9fefa4cb8..85c9b833f1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/NotAuditedBaseEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/NotAuditedBaseEntity.java @@ -1,83 +1,93 @@ package org.hibernate.envers.test.integration.superclass.auditoverride; -import java.io.Serializable; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.MappedSuperclass; +import java.io.Serializable; /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @MappedSuperclass public class NotAuditedBaseEntity implements Serializable { - @Id - @GeneratedValue - private Integer id; + @Id + @GeneratedValue + private Integer id; - private String str1; + private String str1; - private Integer number1; + private Integer number1; - public NotAuditedBaseEntity() { - } + public NotAuditedBaseEntity() { + } - public NotAuditedBaseEntity(String str1, Integer number1, Integer id) { - this.id = id; - this.str1 = str1; - this.number1 = number1; - } + public NotAuditedBaseEntity(String str1, Integer number1, Integer id) { + this.id = id; + this.str1 = str1; + this.number1 = number1; + } - public NotAuditedBaseEntity(String str1, Integer number1) { - this.str1 = str1; - this.number1 = number1; - } + public NotAuditedBaseEntity(String str1, Integer number1) { + this.str1 = str1; + this.number1 = number1; + } - public Integer getId() { - return id; - } + public Integer getId() { + return id; + } - public void setId(Integer id) { - this.id = id; - } + public void setId(Integer id) { + this.id = id; + } - public String getStr1() { - return str1; - } + public String getStr1() { + return str1; + } - public void setStr1(String str1) { - this.str1 = str1; - } + public void setStr1(String str1) { + this.str1 = str1; + } - public Integer getNumber1() { - return number1; - } + public Integer getNumber1() { + return number1; + } - public void setNumber1(Integer number1) { - this.number1 = number1; - } + public void setNumber1(Integer number1) { + this.number1 = number1; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof NotAuditedBaseEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof NotAuditedBaseEntity) ) { + return false; + } - NotAuditedBaseEntity that = (NotAuditedBaseEntity) o; + NotAuditedBaseEntity that = (NotAuditedBaseEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (number1 != null ? !number1.equals(that.number1) : that.number1 != null) return false; - if (str1 != null ? !str1.equals(that.str1) : that.str1 != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( number1 != null ? !number1.equals( that.number1 ) : that.number1 != null ) { + return false; + } + if ( str1 != null ? !str1.equals( that.str1 ) : that.str1 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (str1 != null ? str1.hashCode() : 0); - result = 31 * result + (number1 != null ? number1.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (str1 != null ? str1.hashCode() : 0); + result = 31 * result + (number1 != null ? number1.hashCode() : 0); + return result; + } - public String toString() { - return "NotAuditedBaseEntity(id = " + id + ", str1 = " + str1 + ", number1 = " + number1 + ")"; - } + public String toString() { + return "NotAuditedBaseEntity(id = " + id + ", str1 = " + str1 + ", number1 = " + number1 + ")"; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/PropertyOverrideEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/PropertyOverrideEntity.java index 1ad72ced95..02d03b8b28 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/PropertyOverrideEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/PropertyOverrideEntity.java @@ -11,54 +11,64 @@ import org.hibernate.envers.Audited; */ @Entity @Audited -@AuditOverrides({@AuditOverride(forClass = BaseEntity.class, name = "str1", isAudited = false), - @AuditOverride(forClass = BaseEntity.class, name = "number1", isAudited = true)}) +@AuditOverrides({ + @AuditOverride(forClass = BaseEntity.class, name = "str1", isAudited = false), + @AuditOverride(forClass = BaseEntity.class, name = "number1", isAudited = true) + }) public class PropertyOverrideEntity extends BaseEntity { - private String str2; + private String str2; - public PropertyOverrideEntity() { - } + public PropertyOverrideEntity() { + } - public PropertyOverrideEntity(String str1, Integer number1, String str2) { - super(str1, number1); - this.str2 = str2; - } + public PropertyOverrideEntity(String str1, Integer number1, String str2) { + super( str1, number1 ); + this.str2 = str2; + } - public PropertyOverrideEntity(String str1, Integer number1, Integer id, String str2) { - super(str1, number1, id); - this.str2 = str2; - } + public PropertyOverrideEntity(String str1, Integer number1, Integer id, String str2) { + super( str1, number1, id ); + this.str2 = str2; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof PropertyOverrideEntity)) return false; - if (!super.equals(o)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof PropertyOverrideEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - PropertyOverrideEntity that = (PropertyOverrideEntity) o; + PropertyOverrideEntity that = (PropertyOverrideEntity) o; - if (str2 != null ? !str2.equals(that.str2) : that.str2 != null) return false; + if ( str2 != null ? !str2.equals( that.str2 ) : that.str2 != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (str2 != null ? str2.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (str2 != null ? str2.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "PropertyOverrideEntity(" + super.toString() + ", str2 = " + str2 + ")"; - } + @Override + public String toString() { + return "PropertyOverrideEntity(" + super.toString() + ", str2 = " + str2 + ")"; + } - public String getStr2() { - return str2; - } + public String getStr2() { + return str2; + } - public void setStr2(String str2) { - this.str2 = str2; - } + public void setStr2(String str2) { + this.str2 = str2; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/TransitiveOverrideEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/TransitiveOverrideEntity.java index 9675ee8608..a5161c7998 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/TransitiveOverrideEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditoverride/TransitiveOverrideEntity.java @@ -11,54 +11,70 @@ import org.hibernate.envers.Audited; */ @Entity @Audited -@AuditOverrides({@AuditOverride(forClass = BaseEntity.class, name = "str1", isAudited = true), - @AuditOverride(forClass = ExtendedBaseEntity.class, name = "number2", isAudited = true)}) +@AuditOverrides({ + @AuditOverride(forClass = BaseEntity.class, name = "str1", isAudited = true), + @AuditOverride(forClass = ExtendedBaseEntity.class, name = "number2", isAudited = true) + }) public class TransitiveOverrideEntity extends ExtendedBaseEntity { - private String str3; + private String str3; - public TransitiveOverrideEntity() { - } + public TransitiveOverrideEntity() { + } - public TransitiveOverrideEntity(String str1, Integer number1, Integer id, String str2, Integer number2, String str3) { - super(str1, number1, id, str2, number2); - this.str3 = str3; - } + public TransitiveOverrideEntity( + String str1, + Integer number1, + Integer id, + String str2, + Integer number2, + String str3) { + super( str1, number1, id, str2, number2 ); + this.str3 = str3; + } - public TransitiveOverrideEntity(String str1, Integer number1, String str2, Integer number2, String str3) { - super(str1, number1, str2, number2); - this.str3 = str3; - } + public TransitiveOverrideEntity(String str1, Integer number1, String str2, Integer number2, String str3) { + super( str1, number1, str2, number2 ); + this.str3 = str3; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof TransitiveOverrideEntity)) return false; - if (!super.equals(o)) return false; + @Override + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof TransitiveOverrideEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - TransitiveOverrideEntity that = (TransitiveOverrideEntity) o; + TransitiveOverrideEntity that = (TransitiveOverrideEntity) o; - if (str3 != null ? !str3.equals(that.str3) : that.str3 != null) return false; + if ( str3 != null ? !str3.equals( that.str3 ) : that.str3 != null ) { + return false; + } - return true; - } + return true; + } - @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (str3 != null ? str3.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (str3 != null ? str3.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "TransitiveOverrideEntity(" + super.toString() + ", str3 = " + str3 + ")"; - } + @Override + public String toString() { + return "TransitiveOverrideEntity(" + super.toString() + ", str3 = " + str3 + ")"; + } - public String getStr3() { - return str3; - } + public String getStr3() { + return str3; + } - public void setStr3(String str3) { - this.str3 = str3; - } + public void setStr3(String str3) { + this.str3 = str3; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/BabyCompleteEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/BabyCompleteEntity.java index f6e2366772..05d02f744c 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/BabyCompleteEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/BabyCompleteEntity.java @@ -11,43 +11,58 @@ import org.hibernate.envers.test.entities.StrIntTestEntity; @Entity @Audited(auditParents = {MappedParentEntity.class}) public class BabyCompleteEntity extends ChildCompleteEntity { - private String baby; + private String baby; - public BabyCompleteEntity() { - } + public BabyCompleteEntity() { + } - public BabyCompleteEntity(Long id, String grandparent, String notAudited, String parent, String child, StrIntTestEntity relation, String baby) { - super(id, grandparent, notAudited, parent, child, relation); - this.baby = baby; - } + public BabyCompleteEntity( + Long id, + String grandparent, + String notAudited, + String parent, + String child, + StrIntTestEntity relation, + String baby) { + super( id, grandparent, notAudited, parent, child, relation ); + this.baby = baby; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof BabyCompleteEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof BabyCompleteEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - BabyCompleteEntity that = (BabyCompleteEntity) o; + BabyCompleteEntity that = (BabyCompleteEntity) o; - if (baby != null ? !baby.equals(that.baby) : that.baby != null) return false; + if ( baby != null ? !baby.equals( that.baby ) : that.baby != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (baby != null ? baby.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (baby != null ? baby.hashCode() : 0); + return result; + } - public String toString() { - return "BabyCompleteEntity(" + super.toString() + ", baby = " + baby + ")"; - } + public String toString() { + return "BabyCompleteEntity(" + super.toString() + ", baby = " + baby + ")"; + } - public String getBaby() { - return baby; - } + public String getBaby() { + return baby; + } - public void setBaby(String baby) { - this.baby = baby; - } + public void setBaby(String baby) { + this.baby = baby; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ChildCompleteEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ChildCompleteEntity.java index f0f3e157f6..ea84df73da 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ChildCompleteEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ChildCompleteEntity.java @@ -11,44 +11,58 @@ import org.hibernate.envers.test.entities.StrIntTestEntity; @MappedSuperclass @Audited(auditParents = {MappedGrandparentEntity.class}) public class ChildCompleteEntity extends MappedParentEntity { - private String child; + private String child; - public ChildCompleteEntity() { - super(null, null, null, null, null); - } + public ChildCompleteEntity() { + super( null, null, null, null, null ); + } - public ChildCompleteEntity(Long id, String grandparent, String notAudited, String parent, String child, StrIntTestEntity relation) { - super(id, grandparent, notAudited, parent, relation); - this.child = child; - } + public ChildCompleteEntity( + Long id, + String grandparent, + String notAudited, + String parent, + String child, + StrIntTestEntity relation) { + super( id, grandparent, notAudited, parent, relation ); + this.child = child; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ChildCompleteEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ChildCompleteEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ChildCompleteEntity that = (ChildCompleteEntity) o; + ChildCompleteEntity that = (ChildCompleteEntity) o; - if (child != null ? !child.equals(that.child) : that.child != null) return false; + if ( child != null ? !child.equals( that.child ) : that.child != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (child != null ? child.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (child != null ? child.hashCode() : 0); + return result; + } - public String toString() { - return "ChildCompleteEntity(" + super.toString() + ", child = " + child + ")"; - } + public String toString() { + return "ChildCompleteEntity(" + super.toString() + ", child = " + child + ")"; + } - public String getChild() { - return child; - } + public String getChild() { + return child; + } - public void setChild(String child) { - this.child = child; - } + public void setChild(String child) { + this.child = child; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ChildMultipleParentsEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ChildMultipleParentsEntity.java index 22f88e9820..fa5ec71c04 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ChildMultipleParentsEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ChildMultipleParentsEntity.java @@ -11,45 +11,59 @@ import org.hibernate.envers.test.entities.StrIntTestEntity; @Entity @Audited(auditParents = {MappedParentEntity.class, MappedGrandparentEntity.class}) public class ChildMultipleParentsEntity extends MappedParentEntity { - private String child; + private String child; - public ChildMultipleParentsEntity() { - super(null, null, null, null, null); - } + public ChildMultipleParentsEntity() { + super( null, null, null, null, null ); + } - public ChildMultipleParentsEntity(Long id, String grandparent, String notAudited, String parent, String child, StrIntTestEntity relation) { - super(id, grandparent, notAudited, parent, relation); - this.child = child; - } + public ChildMultipleParentsEntity( + Long id, + String grandparent, + String notAudited, + String parent, + String child, + StrIntTestEntity relation) { + super( id, grandparent, notAudited, parent, relation ); + this.child = child; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ChildMultipleParentsEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ChildMultipleParentsEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ChildMultipleParentsEntity that = (ChildMultipleParentsEntity) o; + ChildMultipleParentsEntity that = (ChildMultipleParentsEntity) o; - if (child != null ? !child.equals(that.child) : that.child != null) return false; + if ( child != null ? !child.equals( that.child ) : that.child != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (child != null ? child.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (child != null ? child.hashCode() : 0); + return result; + } - public String toString() { - return "ChildMultipleParentsEntity(" + super.toString() + ", child = " + child + ")"; - } + public String toString() { + return "ChildMultipleParentsEntity(" + super.toString() + ", child = " + child + ")"; + } - public String getChild() { - return child; - } + public String getChild() { + return child; + } - public void setChild(String child) { - this.child = child; - } + public void setChild(String child) { + this.child = child; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ChildSingleParentEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ChildSingleParentEntity.java index 9f92d9b93d..25d50d616b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ChildSingleParentEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ChildSingleParentEntity.java @@ -11,44 +11,58 @@ import org.hibernate.envers.test.entities.StrIntTestEntity; @Entity @Audited(auditParents = {MappedGrandparentEntity.class}) public class ChildSingleParentEntity extends MappedParentEntity { - private String child; + private String child; - public ChildSingleParentEntity() { - super(null, null, null, null, null); - } + public ChildSingleParentEntity() { + super( null, null, null, null, null ); + } - public ChildSingleParentEntity(Long id, String grandparent, String notAudited, String parent, String child, StrIntTestEntity relation) { - super(id, grandparent, notAudited, parent, relation); - this.child = child; - } + public ChildSingleParentEntity( + Long id, + String grandparent, + String notAudited, + String parent, + String child, + StrIntTestEntity relation) { + super( id, grandparent, notAudited, parent, relation ); + this.child = child; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ChildSingleParentEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ChildSingleParentEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ChildSingleParentEntity that = (ChildSingleParentEntity) o; + ChildSingleParentEntity that = (ChildSingleParentEntity) o; - if (child != null ? !child.equals(that.child) : that.child != null) return false; + if ( child != null ? !child.equals( that.child ) : that.child != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (child != null ? child.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (child != null ? child.hashCode() : 0); + return result; + } - public String toString() { - return "ChildSingleParentEntity(" + super.toString() + ", child = " + child + ")"; - } + public String toString() { + return "ChildSingleParentEntity(" + super.toString() + ", child = " + child + ")"; + } - public String getChild() { - return child; - } + public String getChild() { + return child; + } - public void setChild(String child) { - this.child = child; - } + public void setChild(String child) { + this.child = child; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ExplicitTransitiveChildEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ExplicitTransitiveChildEntity.java index bc5d1ddb1f..05586965a3 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ExplicitTransitiveChildEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ExplicitTransitiveChildEntity.java @@ -12,44 +12,52 @@ import org.hibernate.envers.Audited; @Table(name = "ExplicitTransitiveChild") @Audited(auditParents = {TransitiveParentEntity.class}) public class ExplicitTransitiveChildEntity extends TransitiveParentEntity { - private String child; + private String child; - public ExplicitTransitiveChildEntity() { - super(null, null, null, null); - } + public ExplicitTransitiveChildEntity() { + super( null, null, null, null ); + } - public ExplicitTransitiveChildEntity(Long id, String grandparent, String notAudited, String parent, String child) { - super(id, grandparent, notAudited, parent); - this.child = child; - } + public ExplicitTransitiveChildEntity(Long id, String grandparent, String notAudited, String parent, String child) { + super( id, grandparent, notAudited, parent ); + this.child = child; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ExplicitTransitiveChildEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ExplicitTransitiveChildEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ExplicitTransitiveChildEntity that = (ExplicitTransitiveChildEntity) o; + ExplicitTransitiveChildEntity that = (ExplicitTransitiveChildEntity) o; - if (child != null ? !child.equals(that.child) : that.child != null) return false; + if ( child != null ? !child.equals( that.child ) : that.child != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (child != null ? child.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (child != null ? child.hashCode() : 0); + return result; + } - public String toString() { - return "ExplicitTransitiveChildEntity(" + super.toString() + ", child = " + child + ")"; - } + public String toString() { + return "ExplicitTransitiveChildEntity(" + super.toString() + ", child = " + child + ")"; + } - public String getChild() { - return child; - } + public String getChild() { + return child; + } - public void setChild(String child) { - this.child = child; - } + public void setChild(String child) { + this.child = child; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ImplicitTransitiveChildEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ImplicitTransitiveChildEntity.java index ef46f0404b..b8247eb7f5 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ImplicitTransitiveChildEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/ImplicitTransitiveChildEntity.java @@ -12,44 +12,52 @@ import org.hibernate.envers.Audited; @Table(name = "ImplicitTransitiveChild") @Audited public class ImplicitTransitiveChildEntity extends TransitiveParentEntity { - private String child; + private String child; - public ImplicitTransitiveChildEntity() { - super(null, null, null, null); - } + public ImplicitTransitiveChildEntity() { + super( null, null, null, null ); + } - public ImplicitTransitiveChildEntity(Long id, String grandparent, String notAudited, String parent, String child) { - super(id, grandparent, notAudited, parent); - this.child = child; - } + public ImplicitTransitiveChildEntity(Long id, String grandparent, String notAudited, String parent, String child) { + super( id, grandparent, notAudited, parent ); + this.child = child; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ImplicitTransitiveChildEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ImplicitTransitiveChildEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - ImplicitTransitiveChildEntity that = (ImplicitTransitiveChildEntity) o; + ImplicitTransitiveChildEntity that = (ImplicitTransitiveChildEntity) o; - if (child != null ? !child.equals(that.child) : that.child != null) return false; + if ( child != null ? !child.equals( that.child ) : that.child != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (child != null ? child.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (child != null ? child.hashCode() : 0); + return result; + } - public String toString() { - return "ImplicitTransitiveChildEntity(" + super.toString() + ", child = " + child + ")"; - } + public String toString() { + return "ImplicitTransitiveChildEntity(" + super.toString() + ", child = " + child + ")"; + } - public String getChild() { - return child; - } + public String getChild() { + return child; + } - public void setChild(String child) { - this.child = child; - } + public void setChild(String child) { + this.child = child; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/MappedGrandparentEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/MappedGrandparentEntity.java index 642347ecd0..13b520a248 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/MappedGrandparentEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/MappedGrandparentEntity.java @@ -10,65 +10,75 @@ import org.hibernate.envers.NotAudited; */ @MappedSuperclass public class MappedGrandparentEntity { - @Id - private Long id; + @Id + private Long id; - private String grandparent; + private String grandparent; - @NotAudited - private String notAudited; + @NotAudited + private String notAudited; - public MappedGrandparentEntity(Long id, String grandparent, String notAudited) { - this.id = id; - this.grandparent = grandparent; - this.notAudited = notAudited; - } + public MappedGrandparentEntity(Long id, String grandparent, String notAudited) { + this.id = id; + this.grandparent = grandparent; + this.notAudited = notAudited; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof MappedGrandparentEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof MappedGrandparentEntity) ) { + return false; + } - MappedGrandparentEntity that = (MappedGrandparentEntity) o; + MappedGrandparentEntity that = (MappedGrandparentEntity) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (grandparent != null ? !grandparent.equals(that.grandparent) : that.grandparent != null) return false; - if (notAudited != null ? !notAudited.equals(that.notAudited) : that.notAudited != null) return false; + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( grandparent != null ? !grandparent.equals( that.grandparent ) : that.grandparent != null ) { + return false; + } + if ( notAudited != null ? !notAudited.equals( that.notAudited ) : that.notAudited != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = (id != null ? id.hashCode() : 0); - result = 31 * result + (grandparent != null ? grandparent.hashCode() : 0); - result = 31 * result + (notAudited != null ? notAudited.hashCode() : 0); - return result; - } + public int hashCode() { + int result = (id != null ? id.hashCode() : 0); + result = 31 * result + (grandparent != null ? grandparent.hashCode() : 0); + result = 31 * result + (notAudited != null ? notAudited.hashCode() : 0); + return result; + } - public String toString() { - return "MappedGrandparentEntity(id = " + id + ", grandparent = " + grandparent + ", notAudited = " + notAudited + ")"; - } + public String toString() { + return "MappedGrandparentEntity(id = " + id + ", grandparent = " + grandparent + ", notAudited = " + notAudited + ")"; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getGrandparent() { - return grandparent; - } + public String getGrandparent() { + return grandparent; + } - public void setGrandparent(String grandparent) { - this.grandparent = grandparent; - } + public void setGrandparent(String grandparent) { + this.grandparent = grandparent; + } - public String getNotAudited() { - return notAudited; - } + public String getNotAudited() { + return notAudited; + } - public void setNotAudited(String notAudited) { - this.notAudited = notAudited; - } + public void setNotAudited(String notAudited) { + this.notAudited = notAudited; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/MappedParentEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/MappedParentEntity.java index 33c4590220..911a44f670 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/MappedParentEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/MappedParentEntity.java @@ -10,52 +10,65 @@ import org.hibernate.envers.test.entities.StrIntTestEntity; */ @MappedSuperclass public class MappedParentEntity extends MappedGrandparentEntity { - private String parent; + private String parent; - @ManyToOne - private StrIntTestEntity relation; + @ManyToOne + private StrIntTestEntity relation; - public MappedParentEntity(Long id, String grandparent, String notAudited, String parent, StrIntTestEntity relation) { - super(id, grandparent, notAudited); - this.parent = parent; - this.relation = relation; - } + public MappedParentEntity( + Long id, + String grandparent, + String notAudited, + String parent, + StrIntTestEntity relation) { + super( id, grandparent, notAudited ); + this.parent = parent; + this.relation = relation; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof MappedParentEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof MappedParentEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - MappedParentEntity that = (MappedParentEntity) o; + MappedParentEntity that = (MappedParentEntity) o; - if (parent != null ? !parent.equals(that.parent) : that.parent != null) return false; + if ( parent != null ? !parent.equals( that.parent ) : that.parent != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (parent != null ? parent.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (parent != null ? parent.hashCode() : 0); + return result; + } - public String toString() { - return "MappedParentEntity(" + super.toString() + ", parent = " + parent + ", relation = " + relation + ")"; - } + public String toString() { + return "MappedParentEntity(" + super.toString() + ", parent = " + parent + ", relation = " + relation + ")"; + } - public String getParent() { - return parent; - } + public String getParent() { + return parent; + } - public void setParent(String parent) { - this.parent = parent; - } + public void setParent(String parent) { + this.parent = parent; + } - public StrIntTestEntity getRelation() { - return relation; - } + public StrIntTestEntity getRelation() { + return relation; + } - public void setRelation(StrIntTestEntity relation) { - this.relation = relation; - } + public void setRelation(StrIntTestEntity relation) { + this.relation = relation; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/MultipleAuditParentsTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/MultipleAuditParentsTest.java index 0e957d41ce..760190bd94 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/MultipleAuditParentsTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/MultipleAuditParentsTest.java @@ -1,11 +1,8 @@ package org.hibernate.envers.test.integration.superclass.auditparents; -import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.MappedSuperclass; - -import org.junit.Assert; -import org.junit.Test; +import java.util.Set; import org.hibernate.envers.Audited; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -15,14 +12,18 @@ import org.hibernate.envers.test.tools.TestTools; import org.hibernate.mapping.Column; import org.hibernate.mapping.Table; +import org.junit.Assert; +import org.junit.Test; + /** * Tests mapping of child entity that declares all of its ancestors as audited with {@link Audited#auditParents()} property. * All supperclasses are marked with {@link MappedSuperclass} annotation but not {@link Audited}. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class MultipleAuditParentsTest extends BaseEnversJPAFunctionalTestCase { - private long childMultipleId = 1L; - private Integer siteMultipleId = null; + private long childMultipleId = 1L; + private Integer siteMultipleId = null; @Override protected Class[] getAnnotatedClasses() { @@ -32,44 +33,70 @@ public class MultipleAuditParentsTest extends BaseEnversJPAFunctionalTestCase { ChildMultipleParentsEntity.class, StrIntTestEntity.class }; - } + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - // Revision 1 - em.getTransaction().begin(); - StrIntTestEntity siteMultiple = new StrIntTestEntity("data 1", 1); - em.persist(siteMultiple); - em.persist(new ChildMultipleParentsEntity(childMultipleId, "grandparent 1", "notAudited 1", "parent 1", "child 1", siteMultiple)); - em.getTransaction().commit(); - siteMultipleId = siteMultiple.getId(); - } + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + // Revision 1 + em.getTransaction().begin(); + StrIntTestEntity siteMultiple = new StrIntTestEntity( "data 1", 1 ); + em.persist( siteMultiple ); + em.persist( + new ChildMultipleParentsEntity( + childMultipleId, + "grandparent 1", + "notAudited 1", + "parent 1", + "child 1", + siteMultiple + ) + ); + em.getTransaction().commit(); + siteMultipleId = siteMultiple.getId(); + } - @Test - public void testCreatedAuditTable() { - Set expectedColumns = TestTools.makeSet("child", "parent", "relation_id", "grandparent", "id"); - Set unexpectedColumns = TestTools.makeSet("notAudited"); + @Test + public void testCreatedAuditTable() { + Set expectedColumns = TestTools.makeSet( "child", "parent", "relation_id", "grandparent", "id" ); + Set unexpectedColumns = TestTools.makeSet( "notAudited" ); - Table table = getCfg().getClassMapping("org.hibernate.envers.test.integration.superclass.auditparents.ChildMultipleParentsEntity_AUD").getTable(); + Table table = getCfg().getClassMapping( + "org.hibernate.envers.test.integration.superclass.auditparents.ChildMultipleParentsEntity_AUD" + ).getTable(); - for (String columnName : expectedColumns) { - // Check whether expected column exists. - Assert.assertNotNull(table.getColumn(new Column(columnName))); - } - for (String columnName : unexpectedColumns) { - // Check whether unexpected column does not exist. - Assert.assertNull(table.getColumn(new Column(columnName))); - } - } + for ( String columnName : expectedColumns ) { + // Check whether expected column exists. + Assert.assertNotNull( table.getColumn( new Column( columnName ) ) ); + } + for ( String columnName : unexpectedColumns ) { + // Check whether unexpected column does not exist. + Assert.assertNull( table.getColumn( new Column( columnName ) ) ); + } + } - @Test - public void testMultipleAuditParents() { - // expectedMultipleChild.notAudited shall be null, because it is not audited. - ChildMultipleParentsEntity expectedMultipleChild = new ChildMultipleParentsEntity(childMultipleId, "grandparent 1", null, "parent 1", "child 1", new StrIntTestEntity("data 1", 1, siteMultipleId)); - ChildMultipleParentsEntity child = getAuditReader().find(ChildMultipleParentsEntity.class, childMultipleId, 1); - Assert.assertEquals(expectedMultipleChild, child); - Assert.assertEquals(expectedMultipleChild.getRelation().getId(), child.getRelation().getId()); - } + @Test + public void testMultipleAuditParents() { + // expectedMultipleChild.notAudited shall be null, because it is not audited. + ChildMultipleParentsEntity expectedMultipleChild = new ChildMultipleParentsEntity( + childMultipleId, + "grandparent 1", + null, + "parent 1", + "child 1", + new StrIntTestEntity( + "data 1", + 1, + siteMultipleId + ) + ); + ChildMultipleParentsEntity child = getAuditReader().find( + ChildMultipleParentsEntity.class, + childMultipleId, + 1 + ); + Assert.assertEquals( expectedMultipleChild, child ); + Assert.assertEquals( expectedMultipleChild.getRelation().getId(), child.getRelation().getId() ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/SingleAuditParentsTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/SingleAuditParentsTest.java index f46196e3be..57e7c38ba6 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/SingleAuditParentsTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/SingleAuditParentsTest.java @@ -1,11 +1,8 @@ package org.hibernate.envers.test.integration.superclass.auditparents; -import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.MappedSuperclass; - -import org.junit.Assert; -import org.junit.Test; +import java.util.Set; import org.hibernate.envers.Audited; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -15,57 +12,84 @@ import org.hibernate.envers.test.tools.TestTools; import org.hibernate.mapping.Column; import org.hibernate.mapping.Table; +import org.junit.Assert; +import org.junit.Test; + /** * Tests mapping of child entity that declares one of its ancestors as audited with {@link Audited#auditParents()} property. * All supperclasses are marked with {@link MappedSuperclass} annotation but not {@link Audited}. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class SingleAuditParentsTest extends BaseEnversJPAFunctionalTestCase { - private long childSingleId = 1L; - private Integer siteSingleId = null; + private long childSingleId = 1L; + private Integer siteSingleId = null; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[]{MappedGrandparentEntity.class, MappedParentEntity.class, ChildSingleParentEntity.class, StrIntTestEntity.class}; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] { + MappedGrandparentEntity.class, + MappedParentEntity.class, + ChildSingleParentEntity.class, + StrIntTestEntity.class + }; + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - // Revision 1 - em.getTransaction().begin(); - StrIntTestEntity siteSingle = new StrIntTestEntity("data 1", 1); - em.persist(siteSingle); - em.persist(new ChildSingleParentEntity(childSingleId, "grandparent 1", "notAudited 1", "parent 1", "child 1", siteSingle)); - em.getTransaction().commit(); - siteSingleId = siteSingle.getId(); - em.close(); - } + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + // Revision 1 + em.getTransaction().begin(); + StrIntTestEntity siteSingle = new StrIntTestEntity( "data 1", 1 ); + em.persist( siteSingle ); + em.persist( + new ChildSingleParentEntity( + childSingleId, + "grandparent 1", + "notAudited 1", + "parent 1", + "child 1", + siteSingle + ) + ); + em.getTransaction().commit(); + siteSingleId = siteSingle.getId(); + em.close(); + } - @Test - public void testCreatedAuditTable() { - Set expectedColumns = TestTools.makeSet("child", "grandparent", "id"); - Set unexpectedColumns = TestTools.makeSet("parent", "relation_id", "notAudited"); + @Test + public void testCreatedAuditTable() { + Set expectedColumns = TestTools.makeSet( "child", "grandparent", "id" ); + Set unexpectedColumns = TestTools.makeSet( "parent", "relation_id", "notAudited" ); - Table table = getCfg().getClassMapping("org.hibernate.envers.test.integration.superclass.auditparents.ChildSingleParentEntity_AUD").getTable(); + Table table = getCfg().getClassMapping( + "org.hibernate.envers.test.integration.superclass.auditparents.ChildSingleParentEntity_AUD" + ).getTable(); - for (String columnName : expectedColumns) { - // Check whether expected column exists. - Assert.assertNotNull(table.getColumn(new Column(columnName))); - } - for (String columnName : unexpectedColumns) { - // Check whether unexpected column does not exist. - Assert.assertNull(table.getColumn(new Column(columnName))); - } - } + for ( String columnName : expectedColumns ) { + // Check whether expected column exists. + Assert.assertNotNull( table.getColumn( new Column( columnName ) ) ); + } + for ( String columnName : unexpectedColumns ) { + // Check whether unexpected column does not exist. + Assert.assertNull( table.getColumn( new Column( columnName ) ) ); + } + } - @Test - public void testSingleAuditParent() { - // expectedSingleChild.parent, expectedSingleChild.relation and expectedSingleChild.notAudited shall be null, because they are not audited. - ChildSingleParentEntity expectedSingleChild = new ChildSingleParentEntity(childSingleId, "grandparent 1", null, null, "child 1", null); - ChildSingleParentEntity child = getAuditReader().find(ChildSingleParentEntity.class, childSingleId, 1); - Assert.assertEquals(expectedSingleChild, child); - Assert.assertNull(child.getRelation()); - } + @Test + public void testSingleAuditParent() { + // expectedSingleChild.parent, expectedSingleChild.relation and expectedSingleChild.notAudited shall be null, because they are not audited. + ChildSingleParentEntity expectedSingleChild = new ChildSingleParentEntity( + childSingleId, + "grandparent 1", + null, + null, + "child 1", + null + ); + ChildSingleParentEntity child = getAuditReader().find( ChildSingleParentEntity.class, childSingleId, 1 ); + Assert.assertEquals( expectedSingleChild, child ); + Assert.assertNull( child.getRelation() ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/TotalAuditParentsTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/TotalAuditParentsTest.java index 3a6950aea8..5c58a455bc 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/TotalAuditParentsTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/TotalAuditParentsTest.java @@ -1,10 +1,7 @@ package org.hibernate.envers.test.integration.superclass.auditparents; -import java.util.Set; import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; +import java.util.Set; import org.hibernate.envers.Audited; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -14,15 +11,19 @@ import org.hibernate.envers.test.tools.TestTools; import org.hibernate.mapping.Column; import org.hibernate.mapping.Table; +import org.junit.Assert; +import org.junit.Test; + /** * Tests mapping of baby entity which declares its parent as audited with {@link Audited#auditParents()} property. * Moreover, child class (mapped superclass of baby entity) declares grandparent entity as audited. In this case all * attributes of baby class shall be audited. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class TotalAuditParentsTest extends BaseEnversJPAFunctionalTestCase { - private long babyCompleteId = 1L; - private Integer siteCompleteId = null; + private long babyCompleteId = 1L; + private Integer siteCompleteId = null; @Override protected Class[] getAnnotatedClasses() { @@ -33,44 +34,71 @@ public class TotalAuditParentsTest extends BaseEnversJPAFunctionalTestCase { ChildCompleteEntity.class, BabyCompleteEntity.class }; - } + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); - // Revision 1 - em.getTransaction().begin(); - StrIntTestEntity siteComplete = new StrIntTestEntity("data 1", 1); - em.persist(siteComplete); - em.persist(new BabyCompleteEntity(babyCompleteId, "grandparent 1", "notAudited 1", "parent 1", "child 1", siteComplete, "baby 1")); - em.getTransaction().commit(); - siteCompleteId = siteComplete.getId(); - } + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); + // Revision 1 + em.getTransaction().begin(); + StrIntTestEntity siteComplete = new StrIntTestEntity( "data 1", 1 ); + em.persist( siteComplete ); + em.persist( + new BabyCompleteEntity( + babyCompleteId, + "grandparent 1", + "notAudited 1", + "parent 1", + "child 1", + siteComplete, + "baby 1" + ) + ); + em.getTransaction().commit(); + siteCompleteId = siteComplete.getId(); + } - @Test - public void testCreatedAuditTable() { - Set expectedColumns = TestTools.makeSet("baby", "child", "parent", "relation_id", "grandparent", "id"); - Set unexpectedColumns = TestTools.makeSet("notAudited"); + @Test + public void testCreatedAuditTable() { + Set expectedColumns = TestTools.makeSet( + "baby", + "child", + "parent", + "relation_id", + "grandparent", + "id" + ); + Set unexpectedColumns = TestTools.makeSet( "notAudited" ); - Table table = getCfg().getClassMapping("org.hibernate.envers.test.integration.superclass.auditparents.BabyCompleteEntity_AUD").getTable(); + Table table = getCfg().getClassMapping( + "org.hibernate.envers.test.integration.superclass.auditparents.BabyCompleteEntity_AUD" + ).getTable(); - for (String columnName : expectedColumns) { - // Check whether expected column exists. - Assert.assertNotNull(table.getColumn(new Column(columnName))); - } - for (String columnName : unexpectedColumns) { - // Check whether unexpected column does not exist. - Assert.assertNull(table.getColumn(new Column(columnName))); - } - } + for ( String columnName : expectedColumns ) { + // Check whether expected column exists. + Assert.assertNotNull( table.getColumn( new Column( columnName ) ) ); + } + for ( String columnName : unexpectedColumns ) { + // Check whether unexpected column does not exist. + Assert.assertNull( table.getColumn( new Column( columnName ) ) ); + } + } - @Test - public void testCompleteAuditParents() { - // expectedBaby.notAudited shall be null, because it is not audited. - BabyCompleteEntity expectedBaby = new BabyCompleteEntity(babyCompleteId, "grandparent 1", null, "parent 1", "child 1", new StrIntTestEntity("data 1", 1, siteCompleteId), "baby 1"); - BabyCompleteEntity baby = getAuditReader().find(BabyCompleteEntity.class, babyCompleteId, 1); - Assert.assertEquals(expectedBaby, baby); - Assert.assertEquals(expectedBaby.getRelation().getId(), baby.getRelation().getId()); - } + @Test + public void testCompleteAuditParents() { + // expectedBaby.notAudited shall be null, because it is not audited. + BabyCompleteEntity expectedBaby = new BabyCompleteEntity( + babyCompleteId, + "grandparent 1", + null, + "parent 1", + "child 1", + new StrIntTestEntity( "data 1", 1, siteCompleteId ), + "baby 1" + ); + BabyCompleteEntity baby = getAuditReader().find( BabyCompleteEntity.class, babyCompleteId, 1 ); + Assert.assertEquals( expectedBaby, baby ); + Assert.assertEquals( expectedBaby.getRelation().getId(), baby.getRelation().getId() ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/TransitiveAuditParentsTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/TransitiveAuditParentsTest.java index 7723028c56..c6add0fe2d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/TransitiveAuditParentsTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/TransitiveAuditParentsTest.java @@ -1,10 +1,7 @@ package org.hibernate.envers.test.integration.superclass.auditparents; -import java.util.Set; import javax.persistence.EntityManager; - -import org.junit.Assert; -import org.junit.Test; +import java.util.Set; import org.hibernate.envers.Audited; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; @@ -13,14 +10,18 @@ import org.hibernate.envers.test.tools.TestTools; import org.hibernate.mapping.Column; import org.hibernate.mapping.Table; +import org.junit.Assert; +import org.junit.Test; + /** * Tests mapping of child entity which parent declares one of its ancestors as audited with {@link Audited#auditParents()} * property. Child entity may mark explicitly its parent as audited or not. + * * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public class TransitiveAuditParentsTest extends BaseEnversJPAFunctionalTestCase { - private long childImpTransId = 1L; - private long childExpTransId = 2L; + private long childImpTransId = 1L; + private long childExpTransId = 2L; @Override protected Class[] getAnnotatedClasses() { @@ -30,57 +31,105 @@ public class TransitiveAuditParentsTest extends BaseEnversJPAFunctionalTestCase ImplicitTransitiveChildEntity.class, ExplicitTransitiveChildEntity.class }; - } + } - @Test - @Priority(10) - public void initData() { - EntityManager em = getEntityManager(); + @Test + @Priority(10) + public void initData() { + EntityManager em = getEntityManager(); - // Revision 1 - em.getTransaction().begin(); - em.persist(new ImplicitTransitiveChildEntity(childImpTransId, "grandparent 1", "notAudited 1", "parent 1", "child 1")); - em.getTransaction().commit(); + // Revision 1 + em.getTransaction().begin(); + em.persist( + new ImplicitTransitiveChildEntity( + childImpTransId, + "grandparent 1", + "notAudited 1", + "parent 1", + "child 1" + ) + ); + em.getTransaction().commit(); - // Revision 2 - em.getTransaction().begin(); - em.persist(new ExplicitTransitiveChildEntity(childExpTransId, "grandparent 2", "notAudited 2", "parent 2", "child 2")); - em.getTransaction().commit(); - } + // Revision 2 + em.getTransaction().begin(); + em.persist( + new ExplicitTransitiveChildEntity( + childExpTransId, + "grandparent 2", + "notAudited 2", + "parent 2", + "child 2" + ) + ); + em.getTransaction().commit(); + } - @Test - public void testCreatedAuditTables() { - Table explicitTransChildTable = getCfg().getClassMapping("org.hibernate.envers.test.integration.superclass.auditparents.ExplicitTransitiveChildEntity_AUD").getTable(); - checkTableColumns(TestTools.makeSet("child", "parent", "grandparent", "id"), TestTools.makeSet("notAudited"), explicitTransChildTable); + @Test + public void testCreatedAuditTables() { + Table explicitTransChildTable = getCfg().getClassMapping( + "org.hibernate.envers.test.integration.superclass.auditparents.ExplicitTransitiveChildEntity_AUD" + ).getTable(); + checkTableColumns( + TestTools.makeSet( "child", "parent", "grandparent", "id" ), + TestTools.makeSet( "notAudited" ), + explicitTransChildTable + ); - Table implicitTransChildTable = getCfg().getClassMapping("org.hibernate.envers.test.integration.superclass.auditparents.ImplicitTransitiveChildEntity_AUD").getTable(); - checkTableColumns(TestTools.makeSet("child", "parent", "grandparent", "id"), TestTools.makeSet("notAudited"), implicitTransChildTable); - } + Table implicitTransChildTable = getCfg().getClassMapping( + "org.hibernate.envers.test.integration.superclass.auditparents.ImplicitTransitiveChildEntity_AUD" + ).getTable(); + checkTableColumns( + TestTools.makeSet( "child", "parent", "grandparent", "id" ), + TestTools.makeSet( "notAudited" ), + implicitTransChildTable + ); + } - private void checkTableColumns(Set expectedColumns, Set unexpectedColumns, Table table) { - for (String columnName : expectedColumns) { - // Check whether expected column exists. - Assert.assertNotNull(table.getColumn(new Column(columnName))); - } - for (String columnName : unexpectedColumns) { - // Check whether unexpected column does not exist. - Assert.assertNull(table.getColumn(new Column(columnName))); - } - } + private void checkTableColumns(Set expectedColumns, Set unexpectedColumns, Table table) { + for ( String columnName : expectedColumns ) { + // Check whether expected column exists. + Assert.assertNotNull( table.getColumn( new Column( columnName ) ) ); + } + for ( String columnName : unexpectedColumns ) { + // Check whether unexpected column does not exist. + Assert.assertNull( table.getColumn( new Column( columnName ) ) ); + } + } - @Test - public void testImplicitTransitiveAuditParents() { - // expectedChild.notAudited shall be null, because it is not audited. - ImplicitTransitiveChildEntity expectedChild = new ImplicitTransitiveChildEntity(childImpTransId, "grandparent 1", null, "parent 1", "child 1"); - ImplicitTransitiveChildEntity child = getAuditReader().find(ImplicitTransitiveChildEntity.class, childImpTransId, 1); - Assert.assertEquals(expectedChild, child); - } + @Test + public void testImplicitTransitiveAuditParents() { + // expectedChild.notAudited shall be null, because it is not audited. + ImplicitTransitiveChildEntity expectedChild = new ImplicitTransitiveChildEntity( + childImpTransId, + "grandparent 1", + null, + "parent 1", + "child 1" + ); + ImplicitTransitiveChildEntity child = getAuditReader().find( + ImplicitTransitiveChildEntity.class, + childImpTransId, + 1 + ); + Assert.assertEquals( expectedChild, child ); + } - @Test - public void testExplicitTransitiveAuditParents() { - // expectedChild.notAudited shall be null, because it is not audited. - ExplicitTransitiveChildEntity expectedChild = new ExplicitTransitiveChildEntity(childExpTransId, "grandparent 2", null, "parent 2", "child 2"); - ExplicitTransitiveChildEntity child = getAuditReader().find(ExplicitTransitiveChildEntity.class, childExpTransId, 2); - Assert.assertEquals(expectedChild, child); - } + @Test + public void testExplicitTransitiveAuditParents() { + // expectedChild.notAudited shall be null, because it is not audited. + ExplicitTransitiveChildEntity expectedChild = new ExplicitTransitiveChildEntity( + childExpTransId, + "grandparent 2", + null, + "parent 2", + "child 2" + ); + ExplicitTransitiveChildEntity child = getAuditReader().find( + ExplicitTransitiveChildEntity.class, + childExpTransId, + 2 + ); + Assert.assertEquals( expectedChild, child ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/TransitiveParentEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/TransitiveParentEntity.java index 2047c7aa9e..198abced98 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/TransitiveParentEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/superclass/auditparents/TransitiveParentEntity.java @@ -10,44 +10,52 @@ import org.hibernate.envers.Audited; @MappedSuperclass @Audited(auditParents = {MappedGrandparentEntity.class}) public class TransitiveParentEntity extends MappedGrandparentEntity { - private String parent; + private String parent; - public TransitiveParentEntity() { - super(null, null, null); - } + public TransitiveParentEntity() { + super( null, null, null ); + } - public TransitiveParentEntity(Long id, String grandparent, String notAudited, String parent) { - super(id, grandparent, notAudited); - this.parent = parent; - } + public TransitiveParentEntity(Long id, String grandparent, String notAudited, String parent) { + super( id, grandparent, notAudited ); + this.parent = parent; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof TransitiveParentEntity)) return false; - if (!super.equals(o)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof TransitiveParentEntity) ) { + return false; + } + if ( !super.equals( o ) ) { + return false; + } - TransitiveParentEntity that = (TransitiveParentEntity) o; + TransitiveParentEntity that = (TransitiveParentEntity) o; - if (parent != null ? !parent.equals(that.parent) : that.parent != null) return false; + if ( parent != null ? !parent.equals( that.parent ) : that.parent != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + (parent != null ? parent.hashCode() : 0); - return result; - } + public int hashCode() { + int result = super.hashCode(); + result = 31 * result + (parent != null ? parent.hashCode() : 0); + return result; + } - public String toString() { - return "TransitiveParentEntity(" + super.toString() + ", parent = " + parent + ")"; - } + public String toString() { + return "TransitiveParentEntity(" + super.toString() + ", parent = " + parent + ")"; + } - public String getParent() { - return parent; - } + public String getParent() { + return parent; + } - public void setParent(String parent) { - this.parent = parent; - } + public void setParent(String parent) { + this.parent = parent; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/tools/SchemaExportTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/tools/SchemaExportTest.java index 130eea54a4..791ee99801 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/tools/SchemaExportTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/tools/SchemaExportTest.java @@ -2,58 +2,60 @@ package org.hibernate.envers.test.integration.tools; import java.util.Arrays; -import org.junit.Assert; -import org.junit.Test; - import org.hibernate.Session; import org.hibernate.envers.test.BaseEnversFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.tools.hbm2ddl.EnversSchemaGenerator; + +import org.junit.Assert; +import org.junit.Test; + import org.hibernate.testing.TestForIssue; /** * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ @TestForIssue(jiraKey = "HHH-7106") -public class SchemaExportTest extends BaseEnversFunctionalTestCase { - private Integer id = null; +public class SchemaExportTest extends BaseEnversFunctionalTestCase { + private Integer id = null; - @Override - protected Class[] getAnnotatedClasses() { - return new Class[] {StrTestEntity.class}; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {StrTestEntity.class}; + } protected boolean createSchema() { // Disable schema auto generation. return false; } - @Test - @Priority(10) - public void testSchemaCreation() { - // Generate complete schema. - new EnversSchemaGenerator(configuration()).export().create( true, true ); - - // Populate database with test data. - Session session = getSession(); - session.getTransaction().begin(); - StrTestEntity entity = new StrTestEntity("data"); - session.save(entity); - session.getTransaction().commit(); - - id = entity.getId(); - } @Test - @Priority(9) - public void testAuditDataRetrieval() { - Assert.assertEquals(Arrays.asList(1), getAuditReader().getRevisions(StrTestEntity.class, id)); - Assert.assertEquals(new StrTestEntity("data", id), getAuditReader().find(StrTestEntity.class, id, 1)); - } + @Priority(10) + public void testSchemaCreation() { + // Generate complete schema. + new EnversSchemaGenerator( configuration() ).export().create( true, true ); - @Test - @Priority(8) - public void testSchemaDrop() { - new EnversSchemaGenerator(configuration()).export().drop( true, true ); - } + // Populate database with test data. + Session session = getSession(); + session.getTransaction().begin(); + StrTestEntity entity = new StrTestEntity( "data" ); + session.save( entity ); + session.getTransaction().commit(); + + id = entity.getId(); + } + + @Test + @Priority(9) + public void testAuditDataRetrieval() { + Assert.assertEquals( Arrays.asList( 1 ), getAuditReader().getRevisions( StrTestEntity.class, id ) ); + Assert.assertEquals( new StrTestEntity( "data", id ), getAuditReader().find( StrTestEntity.class, id, 1 ) ); + } + + @Test + @Priority(8) + public void testSchemaDrop() { + new EnversSchemaGenerator( configuration() ).export().drop( true, true ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/AbstractEntityManagerTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/AbstractEntityManagerTest.java index d388dc9ecf..e8583f53f9 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/AbstractEntityManagerTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/AbstractEntityManagerTest.java @@ -23,12 +23,10 @@ */ package org.hibernate.envers.test.performance; +import javax.persistence.EntityManager; import java.io.IOException; import java.util.Arrays; import java.util.Properties; -import javax.persistence.EntityManager; - -import org.junit.Before; import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder; import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl; @@ -44,6 +42,9 @@ import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl; import org.hibernate.jpa.boot.spi.Bootstrap; import org.hibernate.jpa.internal.EntityManagerFactoryImpl; import org.hibernate.jpa.test.PersistenceUnitDescriptorAdapter; + +import org.junit.Before; + import org.hibernate.testing.AfterClassOnce; import org.hibernate.testing.BeforeClassOnce; @@ -52,63 +53,63 @@ import org.hibernate.testing.BeforeClassOnce; * @author Lukasz Antoniak (lukasz dot antoniak at gmail dot com) */ public abstract class AbstractEntityManagerTest extends AbstractEnversTest { - public static final Dialect DIALECT = Dialect.getDialect(); + public static final Dialect DIALECT = Dialect.getDialect(); private EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder; private StandardServiceRegistryImpl serviceRegistry; private EntityManagerFactoryImpl emf; - private EntityManager entityManager; - private AuditReader auditReader; - private boolean audited; + private EntityManager entityManager; + private AuditReader auditReader; + private boolean audited; - public void addConfigurationProperties(Properties configuration) { + public void addConfigurationProperties(Properties configuration) { } - protected static Dialect getDialect() { - return DIALECT; - } + protected static Dialect getDialect() { + return DIALECT; + } - private void closeEntityManager() { - if (entityManager != null) { - entityManager.close(); - entityManager = null; - } - } + private void closeEntityManager() { + if ( entityManager != null ) { + entityManager.close(); + entityManager = null; + } + } - @Before - public void newEntityManager() { - closeEntityManager(); - - entityManager = emf.createEntityManager(); + @Before + public void newEntityManager() { + closeEntityManager(); - if (audited) { - auditReader = AuditReaderFactory.get(entityManager); - } - } + entityManager = emf.createEntityManager(); - @BeforeClassOnce - public void init() throws IOException { - init(true, getAuditStrategy()); - } + if ( audited ) { + auditReader = AuditReaderFactory.get( entityManager ); + } + } - protected void init(boolean audited, String auditStrategy) throws IOException { - this.audited = audited; + @BeforeClassOnce + public void init() throws IOException { + init( true, getAuditStrategy() ); + } - Properties configurationProperties = new Properties(); + protected void init(boolean audited, String auditStrategy) throws IOException { + this.audited = audited; + + Properties configurationProperties = new Properties(); configurationProperties.putAll( Environment.getProperties() ); - if (!audited) { - configurationProperties.setProperty( EnversIntegrator.AUTO_REGISTER, "false"); - } + if ( !audited ) { + configurationProperties.setProperty( EnversIntegrator.AUTO_REGISTER, "false" ); + } if ( createSchema() ) { configurationProperties.setProperty( Environment.HBM2DDL_AUTO, "create-drop" ); configurationProperties.setProperty( Environment.USE_NEW_ID_GENERATOR_MAPPINGS, "true" ); configurationProperties.setProperty( EnversSettings.USE_REVISION_ENTITY_WITH_NATIVE_ID, "false" ); } - if (auditStrategy != null && !"".equals(auditStrategy)) { - configurationProperties.setProperty("org.hibernate.envers.audit_strategy", auditStrategy); - } + if ( auditStrategy != null && !"".equals( auditStrategy ) ) { + configurationProperties.setProperty( "org.hibernate.envers.audit_strategy", auditStrategy ); + } - addConfigurationProperties( configurationProperties ); + addConfigurationProperties( configurationProperties ); configurationProperties.put( AvailableSettings.LOADED_CLASSES, Arrays.asList( getAnnotatedClasses() ) ); @@ -117,12 +118,14 @@ public abstract class AbstractEntityManagerTest extends AbstractEnversTest { configurationProperties ); - emf = (EntityManagerFactoryImpl) entityManagerFactoryBuilder.build(); + emf = (EntityManagerFactoryImpl) entityManagerFactoryBuilder.build(); - serviceRegistry = (StandardServiceRegistryImpl) emf.getSessionFactory().getServiceRegistry().getParentServiceRegistry(); + serviceRegistry = (StandardServiceRegistryImpl) emf.getSessionFactory() + .getServiceRegistry() + .getParentServiceRegistry(); - newEntityManager(); - } + newEntityManager(); + } protected Class[] getAnnotatedClasses() { return new Class[0]; @@ -137,17 +140,17 @@ public abstract class AbstractEntityManagerTest extends AbstractEnversTest { } @AfterClassOnce - public void close() { - closeEntityManager(); - emf.close(); + public void close() { + closeEntityManager(); + emf.close(); //NOTE we don't build the service registry so we don't destroy it - } + } - public EntityManager getEntityManager() { - return entityManager; - } + public EntityManager getEntityManager() { + return entityManager; + } - public AuditReader getAuditReader() { - return auditReader; - } + public AuditReader getAuditReader() { + return auditReader; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/AbstractPerformanceTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/AbstractPerformanceTest.java index 11b543f2e8..a0d889e6dd 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/AbstractPerformanceTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/AbstractPerformanceTest.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.performance; + import java.io.IOException; import java.util.ArrayList; import java.util.List; @@ -30,76 +31,76 @@ import java.util.List; * @author Adam Warski (adam at warski dot org) */ public abstract class AbstractPerformanceTest extends AbstractEntityManagerTest { - protected String getSecondsString(long milliseconds) { - return (milliseconds/1000) + "." + (milliseconds%1000); - } + protected String getSecondsString(long milliseconds) { + return (milliseconds / 1000) + "." + (milliseconds % 1000); + } - protected abstract void doTest(); + protected abstract void doTest(); - private void printResults(long unaudited, long audited) { - System.out.println("Unaudited: " + getSecondsString(unaudited)); - System.out.println(" Audited: " + getSecondsString(audited)); - System.out.println(" Delta: " + getSecondsString(audited-unaudited)); - System.out.println(" Factor: " + (double)audited/unaudited); - } + private void printResults(long unaudited, long audited) { + System.out.println( "Unaudited: " + getSecondsString( unaudited ) ); + System.out.println( " Audited: " + getSecondsString( audited ) ); + System.out.println( " Delta: " + getSecondsString( audited - unaudited ) ); + System.out.println( " Factor: " + (double) audited / unaudited ); + } - private long startTime; - private long runTotal; + private long startTime; + private long runTotal; - protected void start() { - startTime = System.currentTimeMillis(); - } + protected void start() { + startTime = System.currentTimeMillis(); + } - protected void stop() { - long stopTime = System.currentTimeMillis(); - runTotal += stopTime - startTime; - } + protected void stop() { + long stopTime = System.currentTimeMillis(); + runTotal += stopTime - startTime; + } - protected void reset() { - runTotal = 0; - } + protected void reset() { + runTotal = 0; + } - public long run(int numberOfRuns, List results) { - long total = 0; - for (int i=0; i<=numberOfRuns; i++) { - System.out.println(); - System.out.println("RUN " + i); - reset(); - doTest(); - results.add(runTotal); - total += runTotal; + public long run(int numberOfRuns, List results) { + long total = 0; + for ( int i = 0; i <= numberOfRuns; i++ ) { + System.out.println(); + System.out.println( "RUN " + i ); + reset(); + doTest(); + results.add( runTotal ); + total += runTotal; - newEntityManager(); + newEntityManager(); /*System.gc(); - System.gc(); + System.gc(); System.gc(); System.out.println(Runtime.getRuntime().freeMemory() + ", " + Runtime.getRuntime().totalMemory() + ", " + (Runtime.getRuntime().totalMemory()-Runtime.getRuntime().freeMemory()));*/ - } + } - return total; - } + return total; + } - public void test(int numberOfRuns) throws IOException { - List unauditedRuns = new ArrayList(); - List auditedRuns = new ArrayList(); + public void test(int numberOfRuns) throws IOException { + List unauditedRuns = new ArrayList(); + List auditedRuns = new ArrayList(); - init(true, null); - long audited = run(numberOfRuns, auditedRuns); - close(); + init( true, null ); + long audited = run( numberOfRuns, auditedRuns ); + close(); - init(false, null); - long unaudited = run(numberOfRuns, unauditedRuns); - close(); + init( false, null ); + long unaudited = run( numberOfRuns, unauditedRuns ); + close(); - for (int i=0; i<=numberOfRuns; i++) { - System.out.println("RUN " + i); - printResults(unauditedRuns.get(i), auditedRuns.get(i)); - System.out.println(); - } + for ( int i = 0; i <= numberOfRuns; i++ ) { + System.out.println( "RUN " + i ); + printResults( unauditedRuns.get( i ), auditedRuns.get( i ) ); + System.out.println(); + } - System.out.println("TOTAL"); - printResults(unaudited, audited); - } + System.out.println( "TOTAL" ); + printResults( unaudited, audited ); + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/AllPerformance.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/AllPerformance.java index 002ec72e2b..503f3b625b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/AllPerformance.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/AllPerformance.java @@ -1,11 +1,12 @@ package org.hibernate.envers.test.performance; + import java.io.IOException; public class AllPerformance { public static void main(String[] args) throws IOException { - new InsertsPerformance().test(10); - new ComplexInsertPerformance().test(10); - new UpdatesPerformance().test(10); - new InsertsOneTransactionPerformance().test(10); + new InsertsPerformance().test( 10 ); + new ComplexInsertPerformance().test( 10 ); + new UpdatesPerformance().test( 10 ); + new InsertsOneTransactionPerformance().test( 10 ); } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/ComplexInsertPerformance.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/ComplexInsertPerformance.java index ac0931392c..6d38bb76dc 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/ComplexInsertPerformance.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/ComplexInsertPerformance.java @@ -24,17 +24,17 @@ package org.hibernate.envers.test.performance; +import javax.persistence.EntityManager; import java.io.IOException; import java.util.Date; import java.util.HashSet; -import javax.persistence.EntityManager; - -import org.junit.Ignore; import org.hibernate.envers.test.performance.complex.ChildEntity1; import org.hibernate.envers.test.performance.complex.ChildEntity2; import org.hibernate.envers.test.performance.complex.RootEntity; +import org.junit.Ignore; + /** * @author Adam Warski (adam at warski dot org) */ @@ -43,64 +43,64 @@ public class ComplexInsertPerformance extends AbstractPerformanceTest { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { RootEntity.class, ChildEntity1.class, ChildEntity2.class }; - } + return new Class[] {RootEntity.class, ChildEntity1.class, ChildEntity2.class}; + } - private final static int NUMBER_INSERTS = 1000; + private final static int NUMBER_INSERTS = 1000; - private long idCounter = 0; + private long idCounter = 0; - private ChildEntity2 createChildEntity2() { - ChildEntity2 ce = new ChildEntity2(); - ce.setId(idCounter++); - ce.setNumber(12345678); - ce.setData("some data, not really meaningful"); - ce.setStrings(new HashSet()); - ce.getStrings().add("aaa"); - ce.getStrings().add("bbb"); - ce.getStrings().add("ccc"); + private ChildEntity2 createChildEntity2() { + ChildEntity2 ce = new ChildEntity2(); + ce.setId( idCounter++ ); + ce.setNumber( 12345678 ); + ce.setData( "some data, not really meaningful" ); + ce.setStrings( new HashSet() ); + ce.getStrings().add( "aaa" ); + ce.getStrings().add( "bbb" ); + ce.getStrings().add( "ccc" ); - return ce; - } + return ce; + } - private ChildEntity1 createChildEntity1() { - ChildEntity1 ce = new ChildEntity1(); - ce.setId(idCounter++); - ce.setData1("xxx"); - ce.setData2("yyy"); - ce.setChild1(createChildEntity2()); - ce.setChild2(createChildEntity2()); + private ChildEntity1 createChildEntity1() { + ChildEntity1 ce = new ChildEntity1(); + ce.setId( idCounter++ ); + ce.setData1( "xxx" ); + ce.setData2( "yyy" ); + ce.setChild1( createChildEntity2() ); + ce.setChild2( createChildEntity2() ); - return ce; - } + return ce; + } - protected void doTest() { - for (int i=0; i[] getAnnotatedClasses() { - return new Class[]{StrTestEntity.class, SetRefEdEntity.class, SetRefIngEntity.class}; - } + @Override + protected Class[] getAnnotatedClasses() { + return new Class[] {StrTestEntity.class, SetRefEdEntity.class, SetRefIngEntity.class}; + } - @Test - @TestForIssue(jiraKey = "HHH-6614") - public void testSessionCacheClear() { - Session session = openSession(); - session.getTransaction().begin(); - StrTestEntity ste = new StrTestEntity("data"); - session.persist(ste); - session.getTransaction().commit(); - checkEmptyAuditSessionCache(session, "org.hibernate.envers.test.entities.StrTestEntity_AUD"); - } + @Test + @TestForIssue(jiraKey = "HHH-6614") + public void testSessionCacheClear() { + Session session = openSession(); + session.getTransaction().begin(); + StrTestEntity ste = new StrTestEntity( "data" ); + session.persist( ste ); + session.getTransaction().commit(); + checkEmptyAuditSessionCache( session, "org.hibernate.envers.test.entities.StrTestEntity_AUD" ); + } - @Test - @TestForIssue(jiraKey = "HHH-6614") - public void testSessionCacheCollectionClear() { - final String[] auditEntityNames = new String[] {"org.hibernate.envers.test.entities.onetomany.SetRefEdEntity_AUD", - "org.hibernate.envers.test.entities.onetomany.SetRefIngEntity_AUD"}; + @Test + @TestForIssue(jiraKey = "HHH-6614") + public void testSessionCacheCollectionClear() { + final String[] auditEntityNames = new String[] { + "org.hibernate.envers.test.entities.onetomany.SetRefEdEntity_AUD", + "org.hibernate.envers.test.entities.onetomany.SetRefIngEntity_AUD" + }; - SetRefEdEntity ed1 = new SetRefEdEntity(1, "data_ed_1"); - SetRefEdEntity ed2 = new SetRefEdEntity(2, "data_ed_2"); - SetRefIngEntity ing1 = new SetRefIngEntity(3, "data_ing_1"); - SetRefIngEntity ing2 = new SetRefIngEntity(4, "data_ing_2"); + SetRefEdEntity ed1 = new SetRefEdEntity( 1, "data_ed_1" ); + SetRefEdEntity ed2 = new SetRefEdEntity( 2, "data_ed_2" ); + SetRefIngEntity ing1 = new SetRefIngEntity( 3, "data_ing_1" ); + SetRefIngEntity ing2 = new SetRefIngEntity( 4, "data_ing_2" ); - Session session = openSession(); - session.getTransaction().begin(); - session.persist(ed1); - session.persist(ed2); - session.persist(ing1); - session.persist(ing2); - session.getTransaction().commit(); - checkEmptyAuditSessionCache(session, auditEntityNames); + Session session = openSession(); + session.getTransaction().begin(); + session.persist( ed1 ); + session.persist( ed2 ); + session.persist( ing1 ); + session.persist( ing2 ); + session.getTransaction().commit(); + checkEmptyAuditSessionCache( session, auditEntityNames ); - session.getTransaction().begin(); - ed1 = (SetRefEdEntity) session.load(SetRefEdEntity.class, ed1.getId()); - ing1.setReference(ed1); - ing2.setReference(ed1); - session.getTransaction().commit(); - checkEmptyAuditSessionCache(session, auditEntityNames); + session.getTransaction().begin(); + ed1 = (SetRefEdEntity) session.load( SetRefEdEntity.class, ed1.getId() ); + ing1.setReference( ed1 ); + ing2.setReference( ed1 ); + session.getTransaction().commit(); + checkEmptyAuditSessionCache( session, auditEntityNames ); - session.getTransaction().begin(); - ed2 = (SetRefEdEntity) session.load(SetRefEdEntity.class, ed2.getId()); - Set reffering = new HashSet(); - reffering.add(ing1); - reffering.add(ing2); - ed2.setReffering(reffering); - session.getTransaction().commit(); - checkEmptyAuditSessionCache(session, auditEntityNames); + session.getTransaction().begin(); + ed2 = (SetRefEdEntity) session.load( SetRefEdEntity.class, ed2.getId() ); + Set reffering = new HashSet(); + reffering.add( ing1 ); + reffering.add( ing2 ); + ed2.setReffering( reffering ); + session.getTransaction().commit(); + checkEmptyAuditSessionCache( session, auditEntityNames ); - session.getTransaction().begin(); - ed2 = (SetRefEdEntity) session.load(SetRefEdEntity.class, ed2.getId()); - ed2.getReffering().remove(ing1); - session.getTransaction().commit(); - checkEmptyAuditSessionCache(session, auditEntityNames); + session.getTransaction().begin(); + ed2 = (SetRefEdEntity) session.load( SetRefEdEntity.class, ed2.getId() ); + ed2.getReffering().remove( ing1 ); + session.getTransaction().commit(); + checkEmptyAuditSessionCache( session, auditEntityNames ); - session.getTransaction().begin(); - ed2 = (SetRefEdEntity) session.load(SetRefEdEntity.class, ed2.getId()); - ed2.getReffering().iterator().next().setData("mod_data_ing_2"); - session.getTransaction().commit(); - checkEmptyAuditSessionCache(session, auditEntityNames); + session.getTransaction().begin(); + ed2 = (SetRefEdEntity) session.load( SetRefEdEntity.class, ed2.getId() ); + ed2.getReffering().iterator().next().setData( "mod_data_ing_2" ); + session.getTransaction().commit(); + checkEmptyAuditSessionCache( session, auditEntityNames ); - session.close(); - } + session.close(); + } - private void checkEmptyAuditSessionCache(Session session, String ... auditEntityNames) { - List entityNames = Arrays.asList(auditEntityNames); - PersistenceContext persistenceContext = ((SessionImplementor) session).getPersistenceContext(); - for ( Map.Entry entrySet : persistenceContext.reentrantSafeEntityEntries() ) { - final EntityEntry entityEntry = entrySet.getValue(); - if (entityNames.contains(entityEntry.getEntityName())) { - assert false : "Audit data shall not be stored in the session level cache. This causes performance issues."; - } - Assert.assertFalse("Revision entity shall not be stored in the session level cache. This causes performance issues.", - SequenceIdRevisionEntity.class.getName().equals(entityEntry.getEntityName())); - } - } + private void checkEmptyAuditSessionCache(Session session, String... auditEntityNames) { + List entityNames = Arrays.asList( auditEntityNames ); + PersistenceContext persistenceContext = ((SessionImplementor) session).getPersistenceContext(); + for ( Map.Entry entrySet : persistenceContext.reentrantSafeEntityEntries() ) { + final EntityEntry entityEntry = entrySet.getValue(); + if ( entityNames.contains( entityEntry.getEntityName() ) ) { + assert false : "Audit data shall not be stored in the session level cache. This causes performance issues."; + } + Assert.assertFalse( + "Revision entity shall not be stored in the session level cache. This causes performance issues.", + SequenceIdRevisionEntity.class.getName().equals( entityEntry.getEntityName() ) + ); + } + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/InsertsOneTransactionPerformance.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/InsertsOneTransactionPerformance.java index a458349c01..e54143e5c3 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/InsertsOneTransactionPerformance.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/InsertsOneTransactionPerformance.java @@ -24,13 +24,13 @@ package org.hibernate.envers.test.performance; -import java.io.IOException; import javax.persistence.EntityManager; - -import org.junit.Ignore; +import java.io.IOException; import org.hibernate.envers.test.entities.StrTestEntity; +import org.junit.Ignore; + /** * @author Adam Warski (adam at warski dot org) */ @@ -38,24 +38,24 @@ import org.hibernate.envers.test.entities.StrTestEntity; public class InsertsOneTransactionPerformance extends AbstractPerformanceTest { @Override protected Class[] getAnnotatedClasses() { - return new Class[] { StrTestEntity.class }; - } + return new Class[] {StrTestEntity.class}; + } - private final static int NUMBER_INSERTS = 5000; + private final static int NUMBER_INSERTS = 5000; - protected void doTest() { - EntityManager entityManager = getEntityManager(); - entityManager.getTransaction().begin(); - start(); - for (int i=0; i ids = new ArrayList(); + private List ids = new ArrayList(); - private void setup() { - EntityManager entityManager = getEntityManager(); - entityManager.getTransaction().begin(); + private void setup() { + EntityManager entityManager = getEntityManager(); + entityManager.getTransaction().begin(); - for (int i=0; i strings; + @ElementCollection + private Set strings; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getData() { - return data; - } + public String getData() { + return data; + } - public void setData(String data) { - this.data = data; - } + public void setData(String data) { + this.data = data; + } - public Integer getNumber() { - return number; - } + public Integer getNumber() { + return number; + } - public void setNumber(Integer number) { - this.number = number; - } + public void setNumber(Integer number) { + this.number = number; + } - public Set getStrings() { - return strings; - } + public Set getStrings() { + return strings; + } - public void setStrings(Set strings) { - this.strings = strings; - } + public void setStrings(Set strings) { + this.strings = strings; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof ChildEntity2)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof ChildEntity2) ) { + return false; + } - ChildEntity2 that = (ChildEntity2) o; + ChildEntity2 that = (ChildEntity2) o; - if (data != null ? !data.equals(that.data) : that.data != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (number != null ? !number.equals(that.number) : that.number != null) return false; + if ( data != null ? !data.equals( that.data ) : that.data != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( number != null ? !number.equals( that.number ) : that.number != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data != null ? data.hashCode() : 0); - result = 31 * result + (number != null ? number.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data != null ? data.hashCode() : 0); + result = 31 * result + (number != null ? number.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/complex/RootEntity.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/complex/RootEntity.java index 2d5142204b..8bd26eb97b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/complex/RootEntity.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/performance/complex/RootEntity.java @@ -23,13 +23,14 @@ */ package org.hibernate.envers.test.performance.complex; -import java.util.Date; + import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; +import java.util.Date; import org.hibernate.envers.Audited; @@ -39,125 +40,141 @@ import org.hibernate.envers.Audited; @Entity @Audited public class RootEntity { - @Id - private Long id; + @Id + private Long id; - private String data1; + private String data1; - private String data2; + private String data2; - private Integer number1; + private Integer number1; - private Integer number2; + private Integer number2; - @Temporal(TemporalType.TIMESTAMP) - private Date date1; + @Temporal(TemporalType.TIMESTAMP) + private Date date1; - @ManyToOne(cascade = CascadeType.ALL) - private ChildEntity1 child1; + @ManyToOne(cascade = CascadeType.ALL) + private ChildEntity1 child1; - @ManyToOne(cascade = CascadeType.ALL) - private ChildEntity1 child2; + @ManyToOne(cascade = CascadeType.ALL) + private ChildEntity1 child2; - @ManyToOne(cascade = CascadeType.ALL) - private ChildEntity1 child3; + @ManyToOne(cascade = CascadeType.ALL) + private ChildEntity1 child3; - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public String getData1() { - return data1; - } + public String getData1() { + return data1; + } - public void setData1(String data1) { - this.data1 = data1; - } + public void setData1(String data1) { + this.data1 = data1; + } - public String getData2() { - return data2; - } + public String getData2() { + return data2; + } - public void setData2(String data2) { - this.data2 = data2; - } + public void setData2(String data2) { + this.data2 = data2; + } - public Integer getNumber1() { - return number1; - } + public Integer getNumber1() { + return number1; + } - public void setNumber1(Integer number1) { - this.number1 = number1; - } + public void setNumber1(Integer number1) { + this.number1 = number1; + } - public Integer getNumber2() { - return number2; - } + public Integer getNumber2() { + return number2; + } - public void setNumber2(Integer number2) { - this.number2 = number2; - } + public void setNumber2(Integer number2) { + this.number2 = number2; + } - public Date getDate1() { - return date1; - } + public Date getDate1() { + return date1; + } - public void setDate1(Date date1) { - this.date1 = date1; - } + public void setDate1(Date date1) { + this.date1 = date1; + } - public ChildEntity1 getChild1() { - return child1; - } + public ChildEntity1 getChild1() { + return child1; + } - public void setChild1(ChildEntity1 child1) { - this.child1 = child1; - } + public void setChild1(ChildEntity1 child1) { + this.child1 = child1; + } - public ChildEntity1 getChild2() { - return child2; - } + public ChildEntity1 getChild2() { + return child2; + } - public void setChild2(ChildEntity1 child2) { - this.child2 = child2; - } + public void setChild2(ChildEntity1 child2) { + this.child2 = child2; + } - public ChildEntity1 getChild3() { - return child3; - } + public ChildEntity1 getChild3() { + return child3; + } - public void setChild3(ChildEntity1 child3) { - this.child3 = child3; - } + public void setChild3(ChildEntity1 child3) { + this.child3 = child3; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof RootEntity)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof RootEntity) ) { + return false; + } - RootEntity that = (RootEntity) o; + RootEntity that = (RootEntity) o; - if (data1 != null ? !data1.equals(that.data1) : that.data1 != null) return false; - if (data2 != null ? !data2.equals(that.data2) : that.data2 != null) return false; - if (date1 != null ? !date1.equals(that.date1) : that.date1 != null) return false; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if (number1 != null ? !number1.equals(that.number1) : that.number1 != null) return false; - if (number2 != null ? !number2.equals(that.number2) : that.number2 != null) return false; + if ( data1 != null ? !data1.equals( that.data1 ) : that.data1 != null ) { + return false; + } + if ( data2 != null ? !data2.equals( that.data2 ) : that.data2 != null ) { + return false; + } + if ( date1 != null ? !date1.equals( that.date1 ) : that.date1 != null ) { + return false; + } + if ( id != null ? !id.equals( that.id ) : that.id != null ) { + return false; + } + if ( number1 != null ? !number1.equals( that.number1 ) : that.number1 != null ) { + return false; + } + if ( number2 != null ? !number2.equals( that.number2 ) : that.number2 != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = (id != null ? id.hashCode() : 0); - result = 31 * result + (data1 != null ? data1.hashCode() : 0); - result = 31 * result + (data2 != null ? data2.hashCode() : 0); - result = 31 * result + (number1 != null ? number1.hashCode() : 0); - result = 31 * result + (number2 != null ? number2.hashCode() : 0); - result = 31 * result + (date1 != null ? date1.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = (id != null ? id.hashCode() : 0); + result = 31 * result + (data1 != null ? data1.hashCode() : 0); + result = 31 * result + (data2 != null ? data2.hashCode() : 0); + result = 31 * result + (number1 != null ? number1.hashCode() : 0); + result = 31 * result + (number2 != null ? number2.hashCode() : 0); + result = 31 * result + (date1 != null ? date1.hashCode() : 0); + return result; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/tools/TestTools.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/tools/TestTools.java index 1e1e6108e2..aa1b56083d 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/tools/TestTools.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/tools/TestTools.java @@ -78,7 +78,7 @@ public class TestTools { public static List extractRevisionNumbers(List queryResults) { final List result = new ArrayList(); for ( Object queryResult : queryResults ) { - result.add( ( (SequenceIdRevisionEntity) ( (Object[]) queryResult )[1] ).getId() ); + result.add( ((SequenceIdRevisionEntity) ((Object[]) queryResult)[1]).getId() ); } return result; } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/various/Address.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/various/Address.java index 0f0cf61495..84e0444744 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/various/Address.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/various/Address.java @@ -22,11 +22,12 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.various; -import java.util.Set; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; +import java.util.Set; import org.hibernate.envers.Audited; @@ -35,83 +36,95 @@ import org.hibernate.envers.Audited; */ @Entity public class Address { - @Id - @GeneratedValue - private int id; + @Id + @GeneratedValue + private int id; - @Audited - private String streetName; + @Audited + private String streetName; - @Audited - private Integer houseNumber; + @Audited + private Integer houseNumber; - @Audited - private Integer flatNumber; + @Audited + private Integer flatNumber; - @Audited - @OneToMany(mappedBy = "address") - private Set persons; + @Audited + @OneToMany(mappedBy = "address") + private Set persons; - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public String getStreetName() { - return streetName; - } + public String getStreetName() { + return streetName; + } - public void setStreetName(String streetName) { - this.streetName = streetName; - } + public void setStreetName(String streetName) { + this.streetName = streetName; + } - public Integer getHouseNumber() { - return houseNumber; - } + public Integer getHouseNumber() { + return houseNumber; + } - public void setHouseNumber(Integer houseNumber) { - this.houseNumber = houseNumber; - } + public void setHouseNumber(Integer houseNumber) { + this.houseNumber = houseNumber; + } - public Integer getFlatNumber() { - return flatNumber; - } + public Integer getFlatNumber() { + return flatNumber; + } - public void setFlatNumber(Integer flatNumber) { - this.flatNumber = flatNumber; - } + public void setFlatNumber(Integer flatNumber) { + this.flatNumber = flatNumber; + } - public Set getPersons() { - return persons; - } + public Set getPersons() { + return persons; + } - public void setPersons(Set persons) { - this.persons = persons; - } + public void setPersons(Set persons) { + this.persons = persons; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Address)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Address) ) { + return false; + } - Address address = (Address) o; + Address address = (Address) o; - if (id != address.id) return false; - if (flatNumber != null ? !flatNumber.equals(address.flatNumber) : address.flatNumber != null) return false; - if (houseNumber != null ? !houseNumber.equals(address.houseNumber) : address.houseNumber != null) return false; - if (streetName != null ? !streetName.equals(address.streetName) : address.streetName != null) return false; + if ( id != address.id ) { + return false; + } + if ( flatNumber != null ? !flatNumber.equals( address.flatNumber ) : address.flatNumber != null ) { + return false; + } + if ( houseNumber != null ? !houseNumber.equals( address.houseNumber ) : address.houseNumber != null ) { + return false; + } + if ( streetName != null ? !streetName.equals( address.streetName ) : address.streetName != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = id; - result = 31 * result + (streetName != null ? streetName.hashCode() : 0); - result = 31 * result + (houseNumber != null ? houseNumber.hashCode() : 0); - result = 31 * result + (flatNumber != null ? flatNumber.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = id; + result = 31 * result + (streetName != null ? streetName.hashCode() : 0); + result = 31 * result + (houseNumber != null ? houseNumber.hashCode() : 0); + result = 31 * result + (flatNumber != null ? flatNumber.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/various/HsqlTest.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/various/HsqlTest.java index 9f9d3011bb..8b970586f1 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/various/HsqlTest.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/various/HsqlTest.java @@ -22,12 +22,13 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.various; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; + import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; import org.hibernate.Session; @@ -35,7 +36,7 @@ import org.hibernate.Session; * @author Adam Warski (adam at warski dot org) */ public class HsqlTest { - /* + /* Query generated by Hibernate from an old demo, when criteria was used: (works) select @@ -90,62 +91,65 @@ public class HsqlTest { TODO: post hibernate bug */ - public static void main(String[] argv) { - Map configurationOverrides = new HashMap(); - EntityManagerFactory emf = Persistence.createEntityManagerFactory("ConsolePU", configurationOverrides); - EntityManager entityManager = emf.createEntityManager(); + public static void main(String[] argv) { + Map configurationOverrides = new HashMap(); + EntityManagerFactory emf = Persistence.createEntityManagerFactory( "ConsolePU", configurationOverrides ); + EntityManager entityManager = emf.createEntityManager(); - populateTestData(entityManager); + populateTestData( entityManager ); - entityManager.getTransaction().begin(); + entityManager.getTransaction().begin(); - Session sesion = (Session) entityManager.getDelegate(); - System.out.println(sesion.createQuery( - "select e from org.hibernate.envers.demo.Person_versions e " + - "where " + - "e.originalId._revision.id =" + - "(select max(e2.originalId._revision.id) " + - "from org.hibernate.envers.demo.Person_versions e2 " + - "where e.originalId.id = :p0) ") - .setParameter("p0", 1) - .list()); + Session sesion = (Session) entityManager.getDelegate(); + System.out.println( + sesion.createQuery( + "select e from org.hibernate.envers.demo.Person_versions e " + + "where " + + "e.originalId._revision.id =" + + "(select max(e2.originalId._revision.id) " + + "from org.hibernate.envers.demo.Person_versions e2 " + + "where e.originalId.id = :p0) " + ) + .setParameter( "p0", 1 ) + .list() + ); - entityManager.getTransaction().commit(); + entityManager.getTransaction().commit(); - entityManager.close(); - emf.close(); - } + entityManager.close(); + emf.close(); + } - private static void populateTestData(EntityManager entityManager) { - entityManager.getTransaction().begin(); + private static void populateTestData(EntityManager entityManager) { + entityManager.getTransaction().begin(); - if (!hasData(entityManager)) { - Person p1 = new Person(); + if ( !hasData( entityManager ) ) { + Person p1 = new Person(); - Address a1 = new Address(); + Address a1 = new Address(); - p1.setName("James"); - p1.setSurname("Bond"); - p1.setAddress(a1); + p1.setName( "James" ); + p1.setSurname( "Bond" ); + p1.setAddress( a1 ); - a1.setStreetName("MI6"); - a1.setHouseNumber(18); - a1.setFlatNumber(25); - a1.setPersons(new HashSet()); - a1.getPersons().add(p1); + a1.setStreetName( "MI6" ); + a1.setHouseNumber( 18 ); + a1.setFlatNumber( 25 ); + a1.setPersons( new HashSet() ); + a1.getPersons().add( p1 ); - entityManager.persist(a1); + entityManager.persist( a1 ); - entityManager.persist(p1); + entityManager.persist( p1 ); - System.out.println("The DB was populated with example data."); - } + System.out.println( "The DB was populated with example data." ); + } - entityManager.getTransaction().commit(); - } + entityManager.getTransaction().commit(); + } - private static boolean hasData(EntityManager entityManager) { - return (((Long) entityManager.createQuery("select count(a) from Address a").getSingleResult()) + - ((Long) entityManager.createQuery("select count(p) from Person p").getSingleResult())) > 0; - } + private static boolean hasData(EntityManager entityManager) { + return (((Long) entityManager.createQuery( "select count(a) from Address a" ).getSingleResult()) + + ((Long) entityManager.createQuery( "select count(p) from Person p" ).getSingleResult())) > 0; + } } diff --git a/hibernate-envers/src/test/java/org/hibernate/envers/test/various/Person.java b/hibernate-envers/src/test/java/org/hibernate/envers/test/various/Person.java index eda68bb7f7..4a75501f4b 100644 --- a/hibernate-envers/src/test/java/org/hibernate/envers/test/various/Person.java +++ b/hibernate-envers/src/test/java/org/hibernate/envers/test/various/Person.java @@ -22,6 +22,7 @@ * Boston, MA 02110-1301 USA */ package org.hibernate.envers.test.various; + import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @@ -34,70 +35,80 @@ import org.hibernate.envers.Audited; */ @Entity public class Person { - @Id - @GeneratedValue - private int id; + @Id + @GeneratedValue + private int id; - @Audited - private String name; + @Audited + private String name; - @Audited - private String surname; + @Audited + private String surname; - @Audited - @ManyToOne - private Address address; + @Audited + @ManyToOne + private Address address; - public int getId() { - return id; - } + public int getId() { + return id; + } - public void setId(int id) { - this.id = id; - } + public void setId(int id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getSurname() { - return surname; - } + public String getSurname() { + return surname; + } - public void setSurname(String surname) { - this.surname = surname; - } + public void setSurname(String surname) { + this.surname = surname; + } - public Address getAddress() { - return address; - } + public Address getAddress() { + return address; + } - public void setAddress(Address address) { - this.address = address; - } + public void setAddress(Address address) { + this.address = address; + } - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Person)) return false; + public boolean equals(Object o) { + if ( this == o ) { + return true; + } + if ( !(o instanceof Person) ) { + return false; + } - Person person = (Person) o; + Person person = (Person) o; - if (id != person.id) return false; - if (name != null ? !name.equals(person.name) : person.name != null) return false; - if (surname != null ? !surname.equals(person.surname) : person.surname != null) return false; + if ( id != person.id ) { + return false; + } + if ( name != null ? !name.equals( person.name ) : person.name != null ) { + return false; + } + if ( surname != null ? !surname.equals( person.surname ) : person.surname != null ) { + return false; + } - return true; - } + return true; + } - public int hashCode() { - int result; - result = id; - result = 31 * result + (name != null ? name.hashCode() : 0); - result = 31 * result + (surname != null ? surname.hashCode() : 0); - return result; - } + public int hashCode() { + int result; + result = id; + result = 31 * result + (name != null ? name.hashCode() : 0); + result = 31 * result + (surname != null ? surname.hashCode() : 0); + return result; + } } \ No newline at end of file diff --git a/shared/config/checkstyle/checkstyle.xml b/shared/config/checkstyle/checkstyle.xml index 35417093de..cb92c14394 100644 --- a/shared/config/checkstyle/checkstyle.xml +++ b/shared/config/checkstyle/checkstyle.xml @@ -143,6 +143,7 @@ + From 3275855c5b634a2211d0683207a72deef455b321 Mon Sep 17 00:00:00 2001 From: Steve Ebersole Date: Thu, 2 May 2013 10:11:59 -0500 Subject: [PATCH 55/57] HHH-8159 - Apply fixups indicated by analysis tools --- .../src/main/java/org/hibernate/jpa/QueryHints.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/QueryHints.java b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/QueryHints.java index a2c35a0517..da1d05ea5b 100644 --- a/hibernate-entitymanager/src/main/java/org/hibernate/jpa/QueryHints.java +++ b/hibernate-entitymanager/src/main/java/org/hibernate/jpa/QueryHints.java @@ -104,6 +104,6 @@ public class QueryHints { return HINTS; } - private QueryHints() { + protected QueryHints() { } } From 9a003f921b3ba0c9db2bbfa405f785976f588ef0 Mon Sep 17 00:00:00 2001 From: Brett Meyer Date: Thu, 2 May 2013 15:12:28 -0400 Subject: [PATCH 56/57] 4.3.0.Beta2 release --- build.gradle | 2 +- changelog.txt | 62 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 8788526015..6020ff978b 100644 --- a/build.gradle +++ b/build.gradle @@ -25,7 +25,7 @@ buildscript { } } -ext.hibernateTargetVersion = '4.3.0-SNAPSHOT' +ext.hibernateTargetVersion = '4.3.0.Beta2' ext.javaLanguageLevel = "1.6" task wrapper(type: Wrapper) { diff --git a/changelog.txt b/changelog.txt index e679bf4880..07d9b6127b 100644 --- a/changelog.txt +++ b/changelog.txt @@ -5,6 +5,68 @@ match the actual issue resolution (i.e. a bug might not be a bug). Please refer to the particular case on JIRA using the issue tracking number to learn more about each case. +Changes in version 4.3.0.Beta2 (2013.05.02) +------------------------------------------------------------------------------------------------------------------------ +https://hibernate.atlassian.net/browse/HHH/fixforversion/13052 + +** Sub-task + * [HHH-7617] - Gradle eclipse task missing src paths and test source generation + * [HHH-7943] - C3P0, Proxool, ehcache, and infinispan services for OSGi + * [HHH-7944] - Envers OSGi support + * [HHH-7993] - Support jar scanning in OSGi + * [HHH-7995] - Auto-discovery of Hibernate extension points in OSGi + * [HHH-8141] - Upgrade to Gradle 1.5 + * [HHH-8142] - Create a 'compile' task that performs all copmpilations + * [HHH-8143] - Create a 'generateSources' task that performs all generation tasks + * [HHH-8145] - Add MaxPermSize to test configuration + * [HHH-8146] - Update to use maven-publishing plugin + * [HHH-8147] - Update to use distribution plugin for createing release bundles + * [HHH-8151] - Consolidate defining "java language level" in one place + * [HHH-8152] - General cleanup + * [HHH-8156] - Apply new Gradle plugins + * [HHH-8160] - Integrate with Aries JPA 2.1 branch + +** Bug + * [HHH-5845] - Lazy Loading of audited entites with revision type 'delete' + * [HHH-7357] - Incorrect exception translation when using Oracle + * [HHH-7478] - ConcurrentModificationException when adding a BeforeTransactionCompletionProcess from with a PostInsertEventListener for an @Audited entity + * [HHH-7880] - SessionFactory.openStatelessSession() does not respect tenant identifier from CurrentTenantIdentifierResolver + * [HHH-7974] - Session.getTenantIdentifier() not callable without active transaction + * [HHH-8049] - Initialization error with mapping + * [HHH-8084] - LobMergeTest fails on oracle + * [HHH-8103] - Oracle LOB ordering not working with SequenceIdentityGenerator + * [HHH-8137] - Javadoc generation is currently not playing nicely with Java7 javadoc changes + * [HHH-8171] - Auditing of collections of embeddables only supporting single element changes + * [HHH-8173] - AvailableSettings constants for javax.persistence.schema-generation contain space + * [HHH-8178] - Natural IDs generating one UniqueKey per Column + * [HHH-8182] - Correct intermittent UpgradeLockTest failures + * [HHH-8189] - Audit records are not rolled back when transaction is rolled back + * [HHH-8207] - Locale conversion is broken + * [HHH-8215] - Windows Build with Eclipse does not work + +** Deprecation + * [HHH-8170] - Deprecate Hibernate @ForeignKey in favor of JPA 2.1 introduced @ForeignKey annotation + +** Improvement + * [HHH-7605] - Provide details "An entity copy was already assigned to a different entity." + * [HHH-7908] - Logging level checking. + * [HHH-8138] - Log SQLException in DatabaseTarget with cause of schema export CREATE statement failure + * [HHH-8159] - Apply fixups indicated by analysis tools + * [HHH-8162] - Make unique constraint handling on schema update configurable + * [HHH-8167] - Adding @NotNull to a @ManyToOne association with @JoinColumnsOrFormulas leads to ClassCastException + * [HHH-8180] - Improve performance of logging level checks + * [HHH-8183] - Also support synonyms for schema validation + +** New Feature + * [HHH-8157] - Adding DBAllocator labels for new DBs + * [HHH-8163] - Deprecate @IndexColumn and add @ListIndexBase + +** Task + * [HHH-8164] - Deprecate @Sort in favor of @SortNatural and @SortComparator + * [HHH-8175] - Add support for Postgresql 9.2, Postgres Plus 9.2 and IBM DB2 10.1 + * [HHH-8186] - Type in docs? Caching section nonstrict != nontrict + * [HHH-8212] - Add CLA ref to CONTRIBUTING.md + Changes in version 4.3.0.Beta1 (2012.07.12) ------------------------------------------------------------------------------------------------------------------------ From f40f814b001d20d6b33dd5c7b8b85bbf10968676 Mon Sep 17 00:00:00 2001 From: Brett Meyer Date: Thu, 2 May 2013 15:44:41 -0400 Subject: [PATCH 57/57] 4.3.0.Beta2 post release --- build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle b/build.gradle index 6020ff978b..8788526015 100644 --- a/build.gradle +++ b/build.gradle @@ -25,7 +25,7 @@ buildscript { } } -ext.hibernateTargetVersion = '4.3.0.Beta2' +ext.hibernateTargetVersion = '4.3.0-SNAPSHOT' ext.javaLanguageLevel = "1.6" task wrapper(type: Wrapper) {