HHH-6827 code format and javadoc, logging

This commit is contained in:
Strong Liu 2011-11-21 20:02:09 +08:00
parent c4776e2a92
commit f8e347dabd
15 changed files with 141 additions and 89 deletions

View File

@ -56,7 +56,10 @@ import org.hibernate.type.TypeHelper;
*/
public class StandardQueryCache implements QueryCache {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, StandardQueryCache.class.getName());
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class,
StandardQueryCache.class.getName()
);
private QueryResultsRegion cacheRegion;
private UpdateTimestampsCache updateTimestampsCache;
@ -90,22 +93,28 @@ public class StandardQueryCache implements QueryCache {
List result,
boolean isNaturalKeyLookup,
SessionImplementor session) throws HibernateException {
if (isNaturalKeyLookup && result.size() == 0) return false;
Long ts = session.getFactory().getSettings().getRegionFactory().nextTimestamp();
if ( isNaturalKeyLookup && result.size() == 0 ) {
return false;
}
Long ts = session.getFactory().getSettings().getRegionFactory().nextTimestamp();
LOG.debugf( "Caching query results in region: %s; timestamp=%s", cacheRegion.getName(), ts );
List cacheable = new ArrayList(result.size() + 1);
logCachedResultDetails(key, null, returnTypes, cacheable);
cacheable.add(ts);
for (Object aResult : result) {
if (returnTypes.length == 1) cacheable.add(returnTypes[0].disassemble(aResult, session, null));
else cacheable.add(TypeHelper.disassemble((Object[])aResult, returnTypes, null, session, null));
logCachedResultRowDetails(returnTypes, aResult);
}
List cacheable = new ArrayList( result.size() + 1 );
logCachedResultDetails( key, null, returnTypes, cacheable );
cacheable.add( ts );
for ( Object aResult : result ) {
if ( returnTypes.length == 1 ) {
cacheable.add( returnTypes[0].disassemble( aResult, session, null ) );
}
else {
cacheable.add( TypeHelper.disassemble( (Object[]) aResult, returnTypes, null, session, null ) );
}
logCachedResultRowDetails( returnTypes, aResult );
}
cacheRegion.put(key, cacheable);
return true;
cacheRegion.put( key, cacheable );
return true;
}
@SuppressWarnings({ "unchecked" })
@ -117,7 +126,7 @@ public class StandardQueryCache implements QueryCache {
SessionImplementor session) throws HibernateException {
LOG.debugf( "Checking cached query results in region: %s", cacheRegion.getName() );
List cacheable = ( List ) cacheRegion.get( key );
List cacheable = (List) cacheRegion.get( key );
logCachedResultDetails( key, spaces, returnTypes, cacheable );
if ( cacheable == null ) {
@ -125,7 +134,7 @@ public class StandardQueryCache implements QueryCache {
return null;
}
Long timestamp = ( Long ) cacheable.get( 0 );
Long timestamp = (Long) cacheable.get( 0 );
if ( !isNaturalKeyLookup && !isUpToDate( spaces, timestamp ) ) {
LOG.debugf( "Cached query results were not up-to-date" );
return null;
@ -134,21 +143,21 @@ public class StandardQueryCache implements QueryCache {
LOG.debugf( "Returning cached query results" );
for ( int i = 1; i < cacheable.size(); i++ ) {
if ( returnTypes.length == 1 ) {
returnTypes[0].beforeAssemble( ( Serializable ) cacheable.get( i ), session );
returnTypes[0].beforeAssemble( (Serializable) cacheable.get( i ), session );
}
else {
TypeHelper.beforeAssemble( ( Serializable[] ) cacheable.get( i ), returnTypes, session );
TypeHelper.beforeAssemble( (Serializable[]) cacheable.get( i ), returnTypes, session );
}
}
List result = new ArrayList( cacheable.size() - 1 );
for ( int i = 1; i < cacheable.size(); i++ ) {
try {
if ( returnTypes.length == 1 ) {
result.add( returnTypes[0].assemble( ( Serializable ) cacheable.get( i ), session, null ) );
result.add( returnTypes[0].assemble( (Serializable) cacheable.get( i ), session, null ) );
}
else {
result.add(
TypeHelper.assemble( ( Serializable[] ) cacheable.get( i ), returnTypes, session, null )
TypeHelper.assemble( (Serializable[]) cacheable.get( i ), returnTypes, session, null )
);
}
logCachedResultRowDetails( returnTypes, result.get( i - 1 ) );
@ -156,7 +165,7 @@ public class StandardQueryCache implements QueryCache {
catch ( RuntimeException ex ) {
if ( isNaturalKeyLookup &&
( UnresolvableObjectException.class.isInstance( ex ) ||
EntityNotFoundException.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
@ -190,56 +199,84 @@ public class StandardQueryCache implements QueryCache {
}
@Override
public String toString() {
public String toString() {
return "StandardQueryCache(" + cacheRegion.getName() + ')';
}
private static void logCachedResultDetails(QueryKey key, Set querySpaces, Type[] returnTypes, List result) {
if (!LOG.isTraceEnabled()) return;
LOG.trace("key.hashCode=" + key.hashCode());
LOG.trace("querySpaces=" + querySpaces);
if (returnTypes == null || returnTypes.length == 0) LOG.trace("Unexpected returnTypes is "
+ (returnTypes == null ? "null" : "empty") + "! result"
+ (result == null ? " is null" : ".size()=" + result.size()));
if ( !LOG.isTraceEnabled() ) {
return;
}
LOG.trace( "key.hashCode=" + key.hashCode() );
LOG.trace( "querySpaces=" + querySpaces );
if ( returnTypes == null || returnTypes.length == 0 ) {
LOG.trace(
"Unexpected returnTypes is "
+ ( returnTypes == null ? "null" : "empty" ) + "! result"
+ ( result == null ? " is null" : ".size()=" + result.size() )
);
}
else {
StringBuffer returnTypeInfo = new StringBuffer();
for ( int i=0; i<returnTypes.length; i++ ) {
StringBuilder returnTypeInfo = new StringBuilder();
for ( int i = 0; i < returnTypes.length; i++ ) {
returnTypeInfo.append( "typename=" )
.append( returnTypes[ i ].getName() )
.append(" class=" )
.append( returnTypes[ i ].getReturnedClass().getName() ).append(' ');
.append( returnTypes[i].getName() )
.append( " class=" )
.append( returnTypes[i].getReturnedClass().getName() ).append( ' ' );
}
LOG.trace("unexpected returnTypes is " + returnTypeInfo.toString() + "! result");
LOG.trace( "unexpected returnTypes is " + returnTypeInfo.toString() + "! result" );
}
}
private static void logCachedResultRowDetails(Type[] returnTypes, Object result) {
if ( !LOG.isTraceEnabled() ) return;
if ( !LOG.isTraceEnabled() ) {
return;
}
logCachedResultRowDetails(
returnTypes,
( result instanceof Object[] ? ( Object[] ) result : new Object[] { result } )
( result instanceof Object[] ? (Object[]) result : new Object[] { result } )
);
}
private static void logCachedResultRowDetails(Type[] returnTypes, Object[] tuple) {
if (!LOG.isTraceEnabled()) return;
if ( !LOG.isTraceEnabled() ) {
return;
}
if ( tuple == null ) {
LOG.trace(" tuple is null; returnTypes is " + returnTypes == null ? "null" : "Type[" + returnTypes.length + "]");
if (returnTypes != null && returnTypes.length > 1) LOG.trace("Unexpected result tuple! tuple is null; should be Object["
+ returnTypes.length + "]!");
LOG.trace( " tuple is null; returnTypes is " + returnTypes == null ? "null" : "Type[" + returnTypes.length + "]" );
if ( returnTypes != null && returnTypes.length > 1 ) {
LOG.trace(
"Unexpected result tuple! tuple is null; should be Object["
+ returnTypes.length + "]!"
);
}
}
else {
if (returnTypes == null || returnTypes.length == 0) LOG.trace("Unexpected result tuple! tuple is null; returnTypes is "
+ (returnTypes == null ? "null" : "empty"));
LOG.trace(" tuple is Object[" + tuple.length + "]; returnTypes is Type[" + returnTypes.length + "]");
if (tuple.length != returnTypes.length) LOG.trace("Unexpected tuple length! transformer= expected="
+ returnTypes.length + " got=" + tuple.length);
else for (int j = 0; j < tuple.length; j++) {
if (tuple[j] != null && !returnTypes[j].getReturnedClass().isInstance(tuple[j])) LOG.trace("Unexpected tuple value type! transformer= expected="
+ returnTypes[j].getReturnedClass().getName()
+ " got="
+ tuple[j].getClass().getName());
}
if ( returnTypes == null || returnTypes.length == 0 ) {
LOG.trace(
"Unexpected result tuple! tuple is null; returnTypes is "
+ ( returnTypes == null ? "null" : "empty" )
);
}
LOG.trace( " tuple is Object[" + tuple.length + "]; returnTypes is Type[" + returnTypes.length + "]" );
if ( tuple.length != returnTypes.length ) {
LOG.trace(
"Unexpected tuple length! transformer= expected="
+ returnTypes.length + " got=" + tuple.length
);
}
else {
for ( int j = 0; j < tuple.length; j++ ) {
if ( tuple[j] != null && !returnTypes[j].getReturnedClass().isInstance( tuple[j] ) ) {
LOG.trace(
"Unexpected tuple value type! transformer= expected="
+ returnTypes[j].getReturnedClass().getName()
+ " got="
+ tuple[j].getClass().getName()
);
}
}
}
}
}
}

View File

@ -97,5 +97,7 @@ public interface Region {
public Map toMap();
public long nextTimestamp();
//we really should change this return type to `long` instead of `int`
public int getTimeout();
}

View File

@ -79,7 +79,7 @@ public interface RegionAccessStrategy {
* We are going to attempt to update/delete the keyed object. This
* method is used by "asynchronous" concurrency strategies.
* <p/>
* The returned object must be passed back to release(), to release the
* The returned object must be passed back to {@link #unlockItem}, to release the
* lock. Concurrency strategies which do not support client-visible
* locks may silently return null.
*

View File

@ -107,7 +107,7 @@ public class DefaultInitializeCollectionEventListener implements InitializeColle
PersistentCollection collection,
SessionImplementor source) {
if ( !source.getEnabledFilters().isEmpty() && persister.isAffectedByEnabledFilters( source ) ) {
if ( !source.getLoadQueryInfluencers().getEnabledFilters().isEmpty() && persister.isAffectedByEnabledFilters( source ) ) {
LOG.trace( "Disregarding cached version (if any) of collection due to enabled filters" );
return false;
}

View File

@ -217,7 +217,7 @@ public final class SessionFactoryImpl
SessionFactoryObserver observer) throws HibernateException {
LOG.debug( "Building session factory" );
sessionFactoryOptions = new SessionFactoryOptions() {
sessionFactoryOptions = new SessionFactoryOptions() {
private EntityNotFoundDelegate entityNotFoundDelegate;
@Override

View File

@ -139,7 +139,7 @@ public class CustomSQLTest extends LegacyTestCase {
Person p = new Person();
p.setName("Max");
p.setLastName("Andersen");
p.setNationalID("110974XYZ<EFBFBD>");
p.setNationalID("110974XYZ");
p.setAddress("P. P. Street 8");
Session s = openSession();
@ -166,11 +166,11 @@ public class CustomSQLTest extends LegacyTestCase {
s = openSession();
s.beginTransaction();
list = s.createQuery( "select p from Person as p where p.address = 'L<EFBFBD>rkev<EFBFBD>nget 1'" ).list();
list = s.createQuery( "select p from Person as p where p.address = 'Lrkevnget 1'" ).list();
assertTrue(list.size() == 0);
p.setAddress("L<EFBFBD>rkev<EFBFBD>nget 1");
p.setAddress("Lrkevnget 1");
s.update(p);
list = s.createQuery( "select p from Person as p where p.address = 'L<EFBFBD>rkev<EFBFBD>nget 1'" ).list();
list = s.createQuery( "select p from Person as p where p.address = 'Lrkevnget 1'" ).list();
assertTrue(list.size() == 1);
list = s.createQuery( "select p from Party as p where p.address = 'P. P. Street 8'" ).list();
assertTrue(list.size() == 0);

View File

@ -88,7 +88,7 @@ public class EntityManagerTest extends BaseEntityManagerFunctionalTestCase {
@Override
public Map<String, String> getCachedCollections() {
Map<String, String> result = new HashMap<String, String>();
result.put( Item.class.getName() + ".distributors", "read-write, RegionName" );
result.put( Item.class.getName() + ".distributors", "read-write,"+Item.class.getName() + ".distributors" );
return result;
}

View File

@ -17,23 +17,23 @@ import javax.persistence.SqlResultSetMapping;
* @author Gavin King
*/
@Entity(name = "Item")
@SqlResultSetMapping(name = "getItem", entities =
@EntityResult(entityClass = org.hibernate.ejb.test.Item.class, fields = {
@FieldResult(name = "name", column = "itemname"),
@FieldResult(name = "descr", column = "itemdescription")
})
@SqlResultSetMapping(name = "getItem", entities =
@EntityResult(entityClass = org.hibernate.ejb.test.Item.class, fields = {
@FieldResult(name = "name", column = "itemname"),
@FieldResult(name = "descr", column = "itemdescription")
})
)
@NamedNativeQueries({
@NamedNativeQuery(
name = "nativeItem1",
query = "select name as itemname, descr as itemdescription from Item",
resultSetMapping = "getItem"
),
@NamedNativeQuery(
name = "nativeItem2",
query = "select * from Item",
resultClass = Item.class
)
@NamedNativeQuery(
name = "nativeItem1",
query = "select name as itemname, descr as itemdescription from Item",
resultSetMapping = "getItem"
),
@NamedNativeQuery(
name = "nativeItem2",
query = "select * from Item",
resultClass = Item.class
)
})
//@Cache(region="Item", usage=NONSTRICT_READ_WRITE)
public class Item implements Serializable {

View File

@ -29,7 +29,7 @@ hibernate.connection.username sa
hibernate.connection.pool_size 5
hibernate.show_sql true
hibernate.format_sql true
hibernate.max_fetch_depth 5
hibernate.cache.region_prefix hibernate.test

View File

@ -39,7 +39,7 @@ import org.hibernate.cache.CacheException;
/**
* Encapsulates logic to allow a {@link TransactionalAccessDelegate} to determine
* whether a {@link TransactionalAccessDelegate#putFromLoad(Object, Object, long, Object, boolean)
* whether a {@link TransactionalAccessDelegate#putFromLoad(Object, Object, long, Object, boolean)}
* call should be allowed to update the cache. A <code>putFromLoad</code> 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

View File

@ -31,15 +31,22 @@ abstract class AbstractReadWriteAccessStrategy extends BaseRegionAccessStrategy
*/
@Override
public final Object get(Object key, long txTimestamp) throws CacheException {
LOG.debugf( "getting key[%s] from region[%s]", key, getInternalRegion().getName() );
try {
readLock.lock();
Lockable item = (Lockable) getInternalRegion().get( key );
boolean readable = item != null && item.isReadable( txTimestamp );
if ( readable ) {
LOG.debugf( "hit key[%s] in region[%s]", key, getInternalRegion().getName() );
return item.getValue();
}
else {
if ( item == null ) {
LOG.debugf( "miss key[%s] in region[%s]", key, getInternalRegion().getName());
} else {
LOG.debugf( "hit key[%s] in region[%s], but it is unreadable", key, getInternalRegion().getName() );
}
return null;
}
}
@ -58,14 +65,17 @@ abstract class AbstractReadWriteAccessStrategy extends BaseRegionAccessStrategy
public final boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride)
throws CacheException {
try {
LOG.debugf( "putting key[%s] -> value[%s] into region[%s]", key, value, getInternalRegion().getName() );
writeLock.lock();
Lockable item = (Lockable) getInternalRegion().get( key );
boolean writeable = item == null || item.isWriteable( txTimestamp, version, getVersionComparator() );
if ( writeable ) {
LOG.debugf( "putting key[%s] -> value[%s] into region[%s] success", key, value, getInternalRegion().getName() );
getInternalRegion().put( key, new Item( value, version, getInternalRegion().nextTimestamp() ) );
return true;
}
else {
LOG.debugf( "putting key[%s] -> value[%s] into region[%s] fail due to it is unwriteable", key, value, getInternalRegion().getName() );
return false;
}
}
@ -80,6 +90,7 @@ abstract class AbstractReadWriteAccessStrategy extends BaseRegionAccessStrategy
public final SoftLock lockItem(Object key, Object version) throws CacheException {
try {
LOG.debugf( "locking key[%s] in region[%s]", key, getInternalRegion().getName() );
writeLock.lock();
Lockable item = (Lockable) getInternalRegion().get( key );
long timeout = getInternalRegion().nextTimestamp() + getInternalRegion().getTimeout();
@ -102,6 +113,7 @@ abstract class AbstractReadWriteAccessStrategy extends BaseRegionAccessStrategy
public final void unlockItem(Object key, SoftLock lock) throws CacheException {
try {
LOG.debugf( "unlocking key[%s] in region[%s]", key, getInternalRegion().getName() );
writeLock.lock();
Lockable item = (Lockable) getInternalRegion().get( key );

View File

@ -24,7 +24,6 @@
package org.hibernate.testing.cache;
import org.hibernate.cache.spi.CollectionRegion;
import org.hibernate.cache.spi.GeneralDataRegion;
import org.hibernate.cache.spi.access.CollectionRegionAccessStrategy;
/**

View File

@ -46,20 +46,20 @@ class BaseGeneralDataRegion extends BaseRegion implements GeneralDataRegion {
@Override
public Object get(Object key) throws CacheException {
LOG.debugf( "Cache lookup : key[%s]", key );
LOG.debugf( "Cache[%s] lookup : key[%s]",getName(), key );
if ( key == null ) {
return null;
}
Object result = cache.get( key );
if ( result != null ) {
LOG.debugf( "Cache hit: %s", key );
LOG.debugf( "Cache[%s] hit: %s",getName(), key );
}
return result;
}
@Override
public void put(Object key, Object value) throws CacheException {
LOG.debugf( "Caching : [%s] -> [%s]", key, value );
LOG.debugf( "Caching[%s] : [%s] -> [%s]",getName(), key, value );
if ( key == null || value == null ) {
LOG.debug( "Key or Value is null" );
return;
@ -69,7 +69,7 @@ class BaseGeneralDataRegion extends BaseRegion implements GeneralDataRegion {
@Override
public void evict(Object key) throws CacheException {
LOG.debugf( "Invalidating: %s", key );
LOG.debugf( "Evicting[%s]: %s",getName(), key );
if ( key == null ) {
LOG.debug( "Key is null" );
return;
@ -79,13 +79,7 @@ class BaseGeneralDataRegion extends BaseRegion implements GeneralDataRegion {
@Override
public void evictAll() throws CacheException {
LOG.debug( "evict cache" );
LOG.debugf( "evict cache[%s]", getName() );
cache.clear();
}
}

View File

@ -59,6 +59,4 @@ class ReadWriteCollectionRegionAccessStrategy extends AbstractReadWriteAccessStr
public CollectionRegion getRegion() {
return region;
}
}

View File

@ -419,6 +419,16 @@ public abstract class BaseCoreFunctionalTestCase extends BaseUnitTestCase {
assertAllDataRemoved();
}
protected void cleanupCache() {
if ( sessionFactory != null ) {
sessionFactory.getCache().evictCollectionRegions();
sessionFactory.getCache().evictDefaultQueryRegion();
sessionFactory.getCache().evictEntityRegions();
sessionFactory.getCache().evictQueryRegions();
}
}
private void cleanupSession() {
if ( session != null && ! ( (SessionImplementor) session ).isClosed() ) {
if ( session.isConnected() ) {