HHH-9803 - Checkstyle fix ups

This commit is contained in:
Steve Ebersole 2015-05-15 18:07:07 -05:00
parent e4e76ba23b
commit 7308e14fed
137 changed files with 1597 additions and 2634 deletions

View File

@ -428,6 +428,8 @@ public class MetadataSources implements Serializable {
* @param document The DOM document
*
* @return this (for method chaining purposes)
*
* @deprecated since 5.0. Use one of the other methods for passing mapping source(s).
*/
@Deprecated
public MetadataSources addDocument(Document document) {

View File

@ -1500,17 +1500,17 @@ public class InFlightMetadataCollectorImpl implements InFlightMetadataCollector
}
}
private ArrayList<PkDrivenByDefaultMapsIdSecondPass> pkDrivenByDefaultMapsId_secondPassList;
private ArrayList<SetSimpleValueTypeSecondPass> setSimpleValueType_secondPassList;
private ArrayList<CopyIdentifierComponentSecondPass> copyIdentifierComponent_secondPasList;
private ArrayList<FkSecondPass> fk_secondPassList;
private ArrayList<CreateKeySecondPass> createKey_secondPasList;
private ArrayList<SecondaryTableSecondPass> secondaryTable_secondPassList;
private ArrayList<QuerySecondPass> query_secondPassList;
private ArrayList<ConstraintSecondPass> constraint_secondPassList;
private ArrayList<ImplicitColumnNamingSecondPass> implicitColumnNaming_secondPassList;
private ArrayList<PkDrivenByDefaultMapsIdSecondPass> pkDrivenByDefaultMapsIdSecondPassList;
private ArrayList<SetSimpleValueTypeSecondPass> setSimpleValueTypeSecondPassList;
private ArrayList<CopyIdentifierComponentSecondPass> copyIdentifierComponentSecondPasList;
private ArrayList<FkSecondPass> fkSecondPassList;
private ArrayList<CreateKeySecondPass> createKeySecondPasList;
private ArrayList<SecondaryTableSecondPass> secondaryTableSecondPassList;
private ArrayList<QuerySecondPass> querySecondPassList;
private ArrayList<ConstraintSecondPass> constraintSecondPassList;
private ArrayList<ImplicitColumnNamingSecondPass> implicitColumnNamingSecondPassList;
private ArrayList<SecondPass> general_secondPassList;
private ArrayList<SecondPass> generalSecondPassList;
@Override
public void addSecondPass(SecondPass secondPass) {
@ -1548,20 +1548,20 @@ public class InFlightMetadataCollectorImpl implements InFlightMetadataCollector
}
else {
// add to the general SecondPass list
if ( general_secondPassList == null ) {
general_secondPassList = new ArrayList<SecondPass>();
if ( generalSecondPassList == null ) {
generalSecondPassList = new ArrayList<SecondPass>();
}
addSecondPass( secondPass, general_secondPassList, onTopOfTheQueue );
addSecondPass( secondPass, generalSecondPassList, onTopOfTheQueue );
}
}
private void addPkDrivenByDefaultMapsIdSecondPass(
PkDrivenByDefaultMapsIdSecondPass secondPass,
boolean onTopOfTheQueue) {
if ( pkDrivenByDefaultMapsId_secondPassList == null ) {
pkDrivenByDefaultMapsId_secondPassList = new ArrayList<PkDrivenByDefaultMapsIdSecondPass>();
if ( pkDrivenByDefaultMapsIdSecondPassList == null ) {
pkDrivenByDefaultMapsIdSecondPassList = new ArrayList<PkDrivenByDefaultMapsIdSecondPass>();
}
addSecondPass( secondPass, pkDrivenByDefaultMapsId_secondPassList, onTopOfTheQueue );
addSecondPass( secondPass, pkDrivenByDefaultMapsIdSecondPassList, onTopOfTheQueue );
}
private <T extends SecondPass> void addSecondPass(T secondPass, ArrayList<T> secondPassList, boolean onTopOfTheQueue) {
@ -1574,61 +1574,61 @@ public class InFlightMetadataCollectorImpl implements InFlightMetadataCollector
}
private void addSetSimpleValueTypeSecondPass(SetSimpleValueTypeSecondPass secondPass, boolean onTopOfTheQueue) {
if ( setSimpleValueType_secondPassList == null ) {
setSimpleValueType_secondPassList = new ArrayList<SetSimpleValueTypeSecondPass>();
if ( setSimpleValueTypeSecondPassList == null ) {
setSimpleValueTypeSecondPassList = new ArrayList<SetSimpleValueTypeSecondPass>();
}
addSecondPass( secondPass, setSimpleValueType_secondPassList, onTopOfTheQueue );
addSecondPass( secondPass, setSimpleValueTypeSecondPassList, onTopOfTheQueue );
}
private void addCopyIdentifierComponentSecondPass(
CopyIdentifierComponentSecondPass secondPass,
boolean onTopOfTheQueue) {
if ( copyIdentifierComponent_secondPasList == null ) {
copyIdentifierComponent_secondPasList = new ArrayList<CopyIdentifierComponentSecondPass>();
if ( copyIdentifierComponentSecondPasList == null ) {
copyIdentifierComponentSecondPasList = new ArrayList<CopyIdentifierComponentSecondPass>();
}
addSecondPass( secondPass, copyIdentifierComponent_secondPasList, onTopOfTheQueue );
addSecondPass( secondPass, copyIdentifierComponentSecondPasList, onTopOfTheQueue );
}
private void addFkSecondPass(FkSecondPass secondPass, boolean onTopOfTheQueue) {
if ( fk_secondPassList == null ) {
fk_secondPassList = new ArrayList<FkSecondPass>();
if ( fkSecondPassList == null ) {
fkSecondPassList = new ArrayList<FkSecondPass>();
}
addSecondPass( secondPass, fk_secondPassList, onTopOfTheQueue );
addSecondPass( secondPass, fkSecondPassList, onTopOfTheQueue );
}
private void addCreateKeySecondPass(CreateKeySecondPass secondPass, boolean onTopOfTheQueue) {
if ( createKey_secondPasList == null ) {
createKey_secondPasList = new ArrayList<CreateKeySecondPass>();
if ( createKeySecondPasList == null ) {
createKeySecondPasList = new ArrayList<CreateKeySecondPass>();
}
addSecondPass( secondPass, createKey_secondPasList, onTopOfTheQueue );
addSecondPass( secondPass, createKeySecondPasList, onTopOfTheQueue );
}
private void addSecondaryTableSecondPass(SecondaryTableSecondPass secondPass, boolean onTopOfTheQueue) {
if ( secondaryTable_secondPassList == null ) {
secondaryTable_secondPassList = new ArrayList<SecondaryTableSecondPass>();
if ( secondaryTableSecondPassList == null ) {
secondaryTableSecondPassList = new ArrayList<SecondaryTableSecondPass>();
}
addSecondPass( secondPass, secondaryTable_secondPassList, onTopOfTheQueue );
addSecondPass( secondPass, secondaryTableSecondPassList, onTopOfTheQueue );
}
private void addQuerySecondPass(QuerySecondPass secondPass, boolean onTopOfTheQueue) {
if ( query_secondPassList == null ) {
query_secondPassList = new ArrayList<QuerySecondPass>();
if ( querySecondPassList == null ) {
querySecondPassList = new ArrayList<QuerySecondPass>();
}
addSecondPass( secondPass, query_secondPassList, onTopOfTheQueue );
addSecondPass( secondPass, querySecondPassList, onTopOfTheQueue );
}
private void addConstraintSecondPass(ConstraintSecondPass secondPass, boolean onTopOfTheQueue) {
if ( constraint_secondPassList == null ) {
constraint_secondPassList = new ArrayList<ConstraintSecondPass>();
if ( constraintSecondPassList == null ) {
constraintSecondPassList = new ArrayList<ConstraintSecondPass>();
}
addSecondPass( secondPass, constraint_secondPassList, onTopOfTheQueue );
addSecondPass( secondPass, constraintSecondPassList, onTopOfTheQueue );
}
private void addImplicitColumnNamingSecondPass(ImplicitColumnNamingSecondPass secondPass) {
if ( implicitColumnNaming_secondPassList == null ) {
implicitColumnNaming_secondPassList = new ArrayList<ImplicitColumnNamingSecondPass>();
if ( implicitColumnNamingSecondPassList == null ) {
implicitColumnNamingSecondPassList = new ArrayList<ImplicitColumnNamingSecondPass>();
}
implicitColumnNaming_secondPassList.add( secondPass );
implicitColumnNamingSecondPassList.add( secondPass );
}
@ -1642,25 +1642,25 @@ public class InFlightMetadataCollectorImpl implements InFlightMetadataCollector
inSecondPass = true;
try {
processSecondPasses( implicitColumnNaming_secondPassList );
processSecondPasses( implicitColumnNamingSecondPassList );
processSecondPasses( pkDrivenByDefaultMapsId_secondPassList );
processSecondPasses( setSimpleValueType_secondPassList );
processSecondPasses( copyIdentifierComponent_secondPasList );
processSecondPasses( pkDrivenByDefaultMapsIdSecondPassList );
processSecondPasses( setSimpleValueTypeSecondPassList );
processSecondPasses( copyIdentifierComponentSecondPasList );
processFkSecondPassesInOrder();
processSecondPasses( createKey_secondPasList );
processSecondPasses( secondaryTable_secondPassList );
processSecondPasses( createKeySecondPasList );
processSecondPasses( secondaryTableSecondPassList );
processSecondPasses( query_secondPassList );
processSecondPasses( general_secondPassList );
processSecondPasses( querySecondPassList );
processSecondPasses( generalSecondPassList );
processPropertyReferences();
secondPassCompileForeignKeys( buildingContext );
processSecondPasses( constraint_secondPassList );
processSecondPasses( constraintSecondPassList );
processUniqueConstraintHolders( buildingContext );
processJPAIndexHolders( buildingContext );
@ -1686,15 +1686,15 @@ public class InFlightMetadataCollectorImpl implements InFlightMetadataCollector
}
private void processFkSecondPassesInOrder() {
if ( fk_secondPassList == null || fk_secondPassList.isEmpty() ) {
if ( fkSecondPassList == null || fkSecondPassList.isEmpty() ) {
return;
}
// split FkSecondPass instances into primary key and non primary key FKs.
// While doing so build a map of class names to FkSecondPass instances depending on this class.
Map<String, Set<FkSecondPass>> isADependencyOf = new HashMap<String, Set<FkSecondPass>>();
List<FkSecondPass> endOfQueueFkSecondPasses = new ArrayList<FkSecondPass>( fk_secondPassList.size() );
for ( FkSecondPass sp : fk_secondPassList ) {
List<FkSecondPass> endOfQueueFkSecondPasses = new ArrayList<FkSecondPass>( fkSecondPassList.size() );
for ( FkSecondPass sp : fkSecondPassList ) {
if ( sp.isInPrimaryKey() ) {
final String referenceEntityName = sp.getReferencedEntityName();
final PersistentClass classMapping = getEntityBinding( referenceEntityName );
@ -1710,7 +1710,7 @@ public class InFlightMetadataCollectorImpl implements InFlightMetadataCollector
}
// using the isADependencyOf map we order the FkSecondPass recursively instances into the right order for processing
List<FkSecondPass> orderedFkSecondPasses = new ArrayList<FkSecondPass>( fk_secondPassList.size() );
List<FkSecondPass> orderedFkSecondPasses = new ArrayList<FkSecondPass>( fkSecondPassList.size() );
for ( String tableName : isADependencyOf.keySet() ) {
buildRecursiveOrderedFkSecondPasses( orderedFkSecondPasses, isADependencyOf, tableName, tableName );
}
@ -1722,7 +1722,7 @@ public class InFlightMetadataCollectorImpl implements InFlightMetadataCollector
processEndOfQueue( endOfQueueFkSecondPasses );
fk_secondPassList.clear();
fkSecondPassList.clear();
}
/**

View File

@ -30,6 +30,8 @@ import org.hibernate.boot.jaxb.Origin;
/**
* @author Steve Ebersole
*
* @deprecated since 5.0; no longer used internally.
*/
@Deprecated
public enum SupportedOrmXsdVersion {

View File

@ -28,6 +28,7 @@ import org.hibernate.boot.jaxb.Origin;
/**
* @author Steve Ebersole
*
* @deprecated Use {@link org.hibernate.boot.UnsupportedOrmXsdVersionException} instead
*/
@Deprecated

View File

@ -310,6 +310,7 @@ public class ModelBinder {
false,
TruthValue.UNKNOWN
);
break;
}
case NONE: {
// Ideally we'd disable all caching...
@ -1633,6 +1634,7 @@ public class ModelBinder {
false,
TruthValue.UNKNOWN
);
break;
}
case NONE: {
// Ideally we'd disable all caching...

View File

@ -152,7 +152,6 @@ public abstract class AbstractDelegatingSessionFactoryBuilder<T extends Abstract
}
@Override
@Deprecated
@SuppressWarnings("deprecation")
public T applyDefaultEntityMode(EntityMode entityMode) {
delegate.applyDefaultEntityMode( entityMode );
@ -258,7 +257,6 @@ public abstract class AbstractDelegatingSessionFactoryBuilder<T extends Abstract
}
@Override
@Deprecated
@SuppressWarnings("deprecation")
public T applyQuerySubstitutions(Map substitutions) {
delegate.applyQuerySubstitutions( substitutions );

View File

@ -40,8 +40,8 @@ import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.loader.CollectionAliases;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.type.StringRepresentableType;
import org.hibernate.type.Type;
import org.hibernate.type.XmlRepresentableType;
import org.dom4j.Element;
@ -204,7 +204,7 @@ public abstract class PersistentIndexedElementHolder extends AbstractPersistentC
final Type indexType = persister.getIndexType();
final Object indexValue = persister.readIndex( rs, descriptor.getSuffixedIndexAliases(), getSession() );
final String index = ( (XmlRepresentableType) indexType ).toXMLString( indexValue, factory );
final String index = ( (StringRepresentableType) indexType ).toString( indexValue );
setIndex( elem, indexNode, index );
return object;
}
@ -251,7 +251,7 @@ public abstract class PersistentIndexedElementHolder extends AbstractPersistentC
final Map.Entry me = (Map.Entry) o;
final Object object = indexIsFormula
? me.getValue()
: ( (XmlRepresentableType) indexType ).fromXMLString( (String) me.getKey(), persister.getFactory() );
: ( (StringRepresentableType) indexType ).fromStringValue( (String) me.getKey() );
if ( object != null ) {
deleteList.add( object );
}
@ -279,7 +279,7 @@ public abstract class PersistentIndexedElementHolder extends AbstractPersistentC
public Object getIndex(Object entry, int i, CollectionPersister persister) {
final String index = ( (IndexedValue) entry ).index;
final Type indexType = persister.getIndexType();
return ( (XmlRepresentableType) indexType ).fromXMLString( index, persister.getFactory() );
return ( (StringRepresentableType) indexType ).fromStringValue( index );
}
@Override

View File

@ -29,8 +29,8 @@ import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.type.StringRepresentableType;
import org.hibernate.type.Type;
import org.hibernate.type.XmlRepresentableType;
import org.dom4j.Element;
@ -84,7 +84,7 @@ public class PersistentMapElementHolder extends PersistentIndexedElementHolder {
final Element subElement = element.addElement( persister.getElementNodeName() );
elementType.setToXMLNode( subElement, object, persister.getFactory() );
final String indexString = ( (XmlRepresentableType) indexType ).toXMLString( index, persister.getFactory() );
final String indexString = ( (StringRepresentableType) indexType ).toString( index );
setIndex( subElement, indexNodeName, indexString );
}
}
@ -104,7 +104,7 @@ public class PersistentMapElementHolder extends PersistentIndexedElementHolder {
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() );
final Object index = ( (StringRepresentableType) indexType ).fromStringValue( indexString );
result[i++] = indexType.disassemble( index, getSession(), null );
result[i++] = elementType.disassemble( object, getSession(), null );
}

View File

@ -68,7 +68,9 @@ public class StandardAnsiSqlAggregationFunctions {
private String renderCountDistinct(List arguments, Dialect dialect) {
final StringBuilder buffer = new StringBuilder();
buffer.append( "count(distinct " );
if (dialect.requiresParensForTupleDistinctCounts()) buffer.append("(");
if (dialect.requiresParensForTupleDistinctCounts()) {
buffer.append("(");
}
String sep = "";
final Iterator itr = arguments.iterator();
// intentionally skip first
@ -77,7 +79,9 @@ public class StandardAnsiSqlAggregationFunctions {
buffer.append( sep ).append( itr.next() );
sep = ", ";
}
if (dialect.requiresParensForTupleDistinctCounts()) buffer.append(")");
if (dialect.requiresParensForTupleDistinctCounts()) {
buffer.append(")");
}
return buffer.append( ")" ).toString();
}
}

View File

@ -78,7 +78,7 @@ public class HQLQueryPlan implements Serializable {
/**
* We'll check the trace level only once per instance
*/
private final boolean TRACE_ENABLED = LOG.isTraceEnabled();
private final boolean traceEnabled = LOG.isTraceEnabled();
/**
* Constructs a HQLQueryPlan
@ -121,8 +121,9 @@ public class HQLQueryPlan implements Serializable {
final Set<Serializable> combinedQuerySpaces = new HashSet<Serializable>();
final boolean hasCollectionRole = (collectionRole == null);
final Map querySubstitutions = factory.getSettings().getQuerySubstitutions();
final QueryTranslatorFactory queryTranslatorFactory = factory.getSettings().getQueryTranslatorFactory();
final Map querySubstitutions = factory.getSessionFactoryOptions().getQuerySubstitutions();
final QueryTranslatorFactory queryTranslatorFactory = factory.getServiceRegistry().getService( QueryTranslatorFactory.class );
for ( int i=0; i<length; i++ ) {
if ( hasCollectionRole ) {
@ -205,7 +206,7 @@ public class HQLQueryPlan implements Serializable {
public List performList(
QueryParameters queryParameters,
SessionImplementor session) throws HibernateException {
if ( TRACE_ENABLED ) {
if ( traceEnabled ) {
LOG.tracev( "Find: {0}", getSourceQuery() );
queryParameters.traceParameters( session.getFactory() );
}
@ -276,7 +277,8 @@ public class HQLQueryPlan implements Serializable {
* @param rowSelection
* @return a reasonable size to use for allocation
*/
private final int guessResultSize(RowSelection rowSelection) {
@SuppressWarnings("UnnecessaryUnboxing")
private int guessResultSize(RowSelection rowSelection) {
if ( rowSelection != null ) {
final int maxReasonableAllocation = rowSelection.getFetchSize() != null ? rowSelection.getFetchSize().intValue() : 100;
if ( rowSelection.getMaxRows() != null && rowSelection.getMaxRows().intValue() > 0 ) {
@ -303,7 +305,7 @@ public class HQLQueryPlan implements Serializable {
public Iterator performIterate(
QueryParameters queryParameters,
EventSource session) throws HibernateException {
if ( TRACE_ENABLED ) {
if ( traceEnabled ) {
LOG.tracev( "Iterate: {0}", getSourceQuery() );
queryParameters.traceParameters( session.getFactory() );
}
@ -341,7 +343,7 @@ public class HQLQueryPlan implements Serializable {
public ScrollableResults performScroll(
QueryParameters queryParameters,
SessionImplementor session) throws HibernateException {
if ( TRACE_ENABLED ) {
if ( traceEnabled ) {
LOG.tracev( "Iterate: {0}", getSourceQuery() );
queryParameters.traceParameters( session.getFactory() );
}
@ -367,7 +369,7 @@ public class HQLQueryPlan implements Serializable {
*/
public int performExecuteUpdate(QueryParameters queryParameters, SessionImplementor session)
throws HibernateException {
if ( TRACE_ENABLED ) {
if ( traceEnabled ) {
LOG.tracev( "Execute update: {0}", getSourceQuery() );
queryParameters.traceParameters( session.getFactory() );
}
@ -382,10 +384,10 @@ public class HQLQueryPlan implements Serializable {
}
private ParameterMetadata buildParameterMetadata(ParameterTranslations parameterTranslations, String hql) {
final long start = TRACE_ENABLED ? System.nanoTime() : 0;
final long start = traceEnabled ? System.nanoTime() : 0;
final ParamLocationRecognizer recognizer = ParamLocationRecognizer.parseLocations( hql );
if ( TRACE_ENABLED ) {
if ( traceEnabled ) {
final long end = System.nanoTime();
LOG.tracev( "HQL param location recognition took {0} nanoseconds ({1})", ( end - start ), hql );
}

View File

@ -124,6 +124,7 @@ public interface SessionFactoryImplementor extends Mapping, SessionFactory {
*
* @deprecated since 5.0; use {@link #getServiceRegistry()} instead to locate the JdbcServices
*/
@Deprecated
JdbcServices getJdbcServices();
/**

View File

@ -204,7 +204,9 @@ public class WebSphereExtendedJtaPlatform extends AbstractJtaPlatform {
@Override
public boolean equals(Object other) {
if ( !(other instanceof TransactionAdapter) ) return false;
if ( !(other instanceof TransactionAdapter) ) {
return false;
}
TransactionAdapter that = (TransactionAdapter) other;
return getLocalId().equals( that.getLocalId() );
}

View File

@ -26,10 +26,9 @@ package org.hibernate.event.internal;
import org.hibernate.HibernateException;
import org.hibernate.event.spi.DirtyCheckEvent;
import org.hibernate.event.spi.DirtyCheckEventListener;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.jboss.logging.Logger;
/**
* Defines the default dirty-check event listener used by hibernate for
* checking the session for dirtiness in response to generated dirty-check
@ -38,8 +37,7 @@ import org.jboss.logging.Logger;
* @author Steve Ebersole
*/
public class DefaultDirtyCheckEventListener extends AbstractFlushingEventListener implements DirtyCheckEventListener {
private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, DefaultDirtyCheckEventListener.class.getName() );
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( DefaultDirtyCheckEventListener.class );
/**
* Handle the given dirty-check event.
@ -48,21 +46,21 @@ public class DefaultDirtyCheckEventListener extends AbstractFlushingEventListene
* @throws HibernateException
*/
public void onDirtyCheck(DirtyCheckEvent event) throws HibernateException {
int oldSize = event.getSession().getActionQueue().numberOfCollectionRemovals();
try {
flushEverythingToExecutions(event);
boolean wasNeeded = event.getSession().getActionQueue().hasAnyQueuedActions();
if ( wasNeeded )
if ( wasNeeded ) {
LOG.debug( "Session dirty" );
else
}
else {
LOG.debug( "Session not dirty" );
}
event.setDirty( wasNeeded );
}
finally {
event.getSession().getActionQueue().clearFromFlushNeededCheck( oldSize );
}
}
}

View File

@ -72,21 +72,30 @@ public class DefaultResolveNaturalIdEventListener
final EntityPersister persister = event.getEntityPersister();
final boolean traceEnabled = LOG.isTraceEnabled();
if ( traceEnabled )
LOG.tracev( "Attempting to resolve: {0}",
MessageHelper.infoString( persister, event.getNaturalIdValues(), event.getSession().getFactory() ) );
if ( traceEnabled ) {
LOG.tracev(
"Attempting to resolve: {0}",
MessageHelper.infoString( persister, event.getNaturalIdValues(), event.getSession().getFactory() )
);
}
Serializable entityId = resolveFromCache( event );
if ( entityId != null ) {
if ( traceEnabled )
LOG.tracev( "Resolved object in cache: {0}",
MessageHelper.infoString( persister, event.getNaturalIdValues(), event.getSession().getFactory() ) );
if ( traceEnabled ) {
LOG.tracev(
"Resolved object in cache: {0}",
MessageHelper.infoString( persister, event.getNaturalIdValues(), event.getSession().getFactory() )
);
}
return entityId;
}
if ( traceEnabled )
LOG.tracev( "Object not resolved in any cache: {0}",
MessageHelper.infoString( persister, event.getNaturalIdValues(), event.getSession().getFactory() ) );
if ( traceEnabled ) {
LOG.tracev(
"Object not resolved in any cache: {0}",
MessageHelper.infoString( persister, event.getNaturalIdValues(), event.getSession().getFactory() )
);
}
return loadFromDatasource( event );
}

View File

@ -28,6 +28,7 @@ import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.spi.CollectionEntry;
import org.hibernate.engine.spi.CollectionKey;
import org.hibernate.event.spi.EventSource;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.type.CollectionType;
@ -42,23 +43,21 @@ import org.jboss.logging.Logger;
* @author Gavin King
*/
public class EvictVisitor extends AbstractVisitor {
private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, EvictVisitor.class.getName() );
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( EvictVisitor.class );
EvictVisitor(EventSource session) {
super(session);
}
@Override
Object processCollection(Object collection, CollectionType type)
throws HibernateException {
if (collection!=null) evictCollection(collection, type);
Object processCollection(Object collection, CollectionType type) throws HibernateException {
if (collection != null) {
evictCollection(collection, type);
}
return null;
}
public void evictCollection(Object value, CollectionType type) {
final Object pc;
if ( type.hasHolder() ) {
pc = getSession().getPersistenceContext().removeCollectionHolder(value);
@ -71,13 +70,16 @@ public class EvictVisitor extends AbstractVisitor {
}
PersistentCollection collection = (PersistentCollection) pc;
if ( collection.unsetSession( getSession() ) ) evictCollection(collection);
if ( collection.unsetSession( getSession() ) ) {
evictCollection(collection);
}
}
private void evictCollection(PersistentCollection collection) {
CollectionEntry ce = (CollectionEntry) getSession().getPersistenceContext().getCollectionEntries().remove(collection);
if ( LOG.isDebugEnabled() ) {
LOG.debugf( "Evicting collection: %s",
LOG.debugf(
"Evicting collection: %s",
MessageHelper.collectionInfoString( ce.getLoadedPersister(),
collection,
ce.getLoadedKey(),

View File

@ -312,8 +312,9 @@ public class FromElement extends HqlSqlWalkerNode implements DisplayableNode, Pa
}
public void setIncludeSubclasses(boolean includeSubclasses) {
if ( !includeSubclasses && isDereferencedBySuperclassOrSubclassProperty() && LOG.isTraceEnabled() )
if ( !includeSubclasses && isDereferencedBySuperclassOrSubclassProperty() && LOG.isTraceEnabled() ) {
LOG.trace( "Attempt to disable subclass-inclusions : ", new Exception( "Stack-trace source" ) );
}
this.includeSubclasses = includeSubclasses;
}

View File

@ -87,7 +87,9 @@ public class ClauseParser implements Parser {
byExpected = true;
}
else if ( lcToken.equals( "by" ) ) {
if ( !byExpected ) throw new QueryException( "GROUP or ORDER expected before BY" );
if ( !byExpected ) {
throw new QueryException( "GROUP or ORDER expected before BY" );
}
child.start( q );
byExpected = false;
}

View File

@ -73,7 +73,9 @@ public class FromParser implements Parser {
// start by looking for HQL keywords...
String lcToken = token.toLowerCase(Locale.ROOT);
if ( lcToken.equals( "," ) ) {
if ( !( expectingJoin | expectingAs ) ) throw new QueryException( "unexpected token: ," );
if ( !( expectingJoin | expectingAs ) ) {
throw new QueryException( "unexpected token: ," );
}
expectingJoin = false;
expectingAs = false;
}
@ -90,8 +92,12 @@ public class FromParser implements Parser {
}
}
else if ( lcToken.equals( "fetch" ) ) {
if ( q.isShallowQuery() ) throw new QueryException( QueryTranslator.ERROR_CANNOT_FETCH_WITH_ITERATE );
if ( joinType == JoinType.NONE ) throw new QueryException( "unexpected token: fetch" );
if ( q.isShallowQuery() ) {
throw new QueryException( QueryTranslator.ERROR_CANNOT_FETCH_WITH_ITERATE );
}
if ( joinType == JoinType.NONE ) {
throw new QueryException( "unexpected token: fetch" );
}
if ( joinType == JoinType.FULL_JOIN || joinType == JoinType.RIGHT_OUTER_JOIN ) {
throw new QueryException( "fetch may only be used with inner join or left outer join" );
}
@ -106,15 +112,21 @@ public class FromParser implements Parser {
}
}
else if ( JOIN_TYPES.containsKey( lcToken ) ) {
if ( !( expectingJoin | expectingAs ) ) throw new QueryException( "unexpected token: " + token );
if ( !( expectingJoin | expectingAs ) ) {
throw new QueryException( "unexpected token: " + token );
}
joinType = JOIN_TYPES.get( lcToken );
afterJoinType = true;
expectingJoin = false;
expectingAs = false;
}
else if ( lcToken.equals( "class" ) ) {
if ( !afterIn ) throw new QueryException( "unexpected token: class" );
if ( joinType != JoinType.NONE ) throw new QueryException( "outer or full join must be followed by path expression" );
if ( !afterIn ) {
throw new QueryException( "unexpected token: class" );
}
if ( joinType != JoinType.NONE ) {
throw new QueryException( "outer or full join must be followed by path expression" );
}
afterClass = true;
}
else if ( lcToken.equals( "in" ) ) {
@ -124,18 +136,23 @@ public class FromParser implements Parser {
}
else if ( !expectingIn ) {
throw new QueryException( "unexpected token: in" );
} else {
}
else {
afterIn = true;
expectingIn = false;
}
}
else if ( lcToken.equals( "as" ) ) {
if ( !expectingAs ) throw new QueryException( "unexpected token: as" );
if ( !expectingAs ) {
throw new QueryException( "unexpected token: as" );
}
afterAs = true;
expectingAs = false;
}
else if ( "(".equals( token ) ){
if( !memberDeclarations ) throw new QueryException( "unexpected token: (" );
if( !memberDeclarations ) {
throw new QueryException( "unexpected token: (" );
}
//TODO alias should be null here
expectingPathExpression = true;
@ -146,10 +163,15 @@ public class FromParser implements Parser {
afterMemberDeclarations = true;
}
else {
if ( afterJoinType ) throw new QueryException( "join expected: " + token );
if ( expectingJoin ) throw new QueryException( "unexpected token: " + token );
if ( expectingIn ) throw new QueryException( "in expected: " + token );
if ( afterJoinType ) {
throw new QueryException( "join expected: " + token );
}
if ( expectingJoin ) {
throw new QueryException( "unexpected token: " + token );
}
if ( expectingIn ) {
throw new QueryException( "in expected: " + token );
}
// now anything that is not a HQL keyword
@ -185,9 +207,13 @@ public class FromParser implements Parser {
// process the "old" HQL style where aliases appear _first_
// ie. using the IN or IN CLASS constructions
if ( alias == null ) throw new QueryException( "alias not specified for: " + token );
if ( alias == null ) {
throw new QueryException( "alias not specified for: " + token );
}
if ( joinType != JoinType.NONE ) throw new QueryException( "outer or full join must be followed by path expression" );
if ( joinType != JoinType.NONE ) {
throw new QueryException( "outer or full join must be followed by path expression" );
}
if ( afterClass ) {
// treat it as a classname
@ -215,7 +241,9 @@ public class FromParser implements Parser {
peParser.setJoinType( JoinType.INNER_JOIN );
peParser.setUseThetaStyleJoin( false );
ParserHelper.parse( peParser, q.unalias( token ), ParserHelper.PATH_SEPARATORS, q );
if ( !peParser.isCollectionValued() ) throw new QueryException( "path expression did not resolve to collection: " + token );
if ( !peParser.isCollectionValued() ) {
throw new QueryException( "path expression did not resolve to collection: " + token );
}
collectionName = peParser.addFromCollection( q );
expectingPathExpression = false;
memberDeclarations = false;
@ -230,7 +258,9 @@ public class FromParser implements Parser {
Queryable p = q.getEntityPersisterUsingImports( token );
if ( p != null ) {
// starts with the name of a mapped class (new style)
if ( joinType != JoinType.NONE ) throw new QueryException( "outer or full join must be followed by path expression" );
if ( joinType != JoinType.NONE ) {
throw new QueryException( "outer or full join must be followed by path expression" );
}
entityName = q.createNameFor( p.getEntityName() );
q.addFromClass( entityName, p );
expectingAs = true;
@ -293,7 +323,7 @@ public class FromParser implements Parser {
}
public void end(QueryTranslatorImpl q) {
if( afterMemberDeclarations ){
if( afterMemberDeclarations ) {
//The exception throwned by the AST query translator contains the error token location, respensent by line and colum,
//but it hard to get that info here.
throw new QueryException("alias not specified for IN");

View File

@ -122,7 +122,9 @@ public class PathExpressionParser implements Parser {
public void token(String token, QueryTranslatorImpl q) throws QueryException {
if ( token != null ) path.append( token );
if ( token != null ) {
path.append( token );
}
String alias = q.getPathAlias( path.toString() );
if ( alias != null ) {
@ -148,7 +150,9 @@ public class PathExpressionParser implements Parser {
else {
if ( dotcount == 0 ) {
if ( !continuation ) {
if ( !q.isName( token ) ) throw new QueryException( "undefined alias: " + token );
if ( !q.isName( token ) ) {
throw new QueryException( "undefined alias: " + token );
}
currentName = token;
currentPropertyMapping = q.getPropertyMapping( currentName );
}
@ -178,14 +182,18 @@ public class PathExpressionParser implements Parser {
dereferenceComponent( token );
}
else if ( propertyType.isEntityType() ) {
if ( !isCollectionValued() ) dereferenceEntity( token, ( EntityType ) propertyType, q );
if ( !isCollectionValued() ) {
dereferenceEntity( token, ( EntityType ) propertyType, q );
}
}
else if ( propertyType.isCollectionType() ) {
dereferenceCollection( token, ( ( CollectionType ) propertyType ).getRole(), q );
}
else {
if ( token != null ) throw new QueryException( "dereferenced: " + path );
if ( token != null ) {
throw new QueryException( "dereferenced: " + path );
}
}
}
@ -197,8 +205,8 @@ public class PathExpressionParser implements Parser {
//NOTE: we avoid joining to the next table if the named property is just the foreign key value
//if its "id"
boolean isIdShortcut = EntityPersister.ENTITY_ID.equals( propertyName ) &&
propertyType.isReferenceToPrimaryKey();
boolean isIdShortcut = EntityPersister.ENTITY_ID.equals( propertyName )
&& propertyType.isReferenceToPrimaryKey();
//or its the id property name
final String idPropertyName;
@ -216,7 +224,9 @@ public class PathExpressionParser implements Parser {
if ( isIdShortcut || isNamedIdPropertyShortcut ) {
// special shortcut for id properties, skip the join!
// this must only occur at the _end_ of a path expression
if ( componentPath.length() > 0 ) componentPath.append( '.' );
if ( componentPath.length() > 0 ) {
componentPath.append( '.' );
}
componentPath.append( propertyName );
}
else {
@ -224,7 +234,9 @@ public class PathExpressionParser implements Parser {
String name = q.createNameFor( entityClass );
q.addType( name, entityClass );
addJoin( name, propertyType );
if ( propertyType.isOneToOne() ) oneToOneOwnerName = currentName;
if ( propertyType.isOneToOne() ) {
oneToOneOwnerName = currentName;
}
ownerAssociationType = propertyType;
currentName = name;
currentProperty = propertyName;
@ -236,7 +248,9 @@ public class PathExpressionParser implements Parser {
private void dereferenceComponent(String propertyName) {
if ( propertyName != null ) {
if ( componentPath.length() > 0 ) componentPath.append( '.' );
if ( componentPath.length() > 0 ) {
componentPath.append( '.' );
}
componentPath.append( propertyName );
}
}
@ -261,11 +275,7 @@ public class PathExpressionParser implements Parser {
}
else {
if ( componentPath.length() > 0 ) {
return new StringBuilder()
.append( currentProperty )
.append( '.' )
.append( componentPath.toString() )
.toString();
return currentProperty + '.' + componentPath.toString();
}
else {
return currentProperty;
@ -351,9 +361,14 @@ public class PathExpressionParser implements Parser {
QueryableCollection collPersister = q.getCollectionPersister( collectionRole );
if ( !collPersister.hasIndex() ) throw new QueryException( "unindexed collection before []: " + path );
if ( !collPersister.hasIndex() ) {
throw new QueryException( "unindexed collection before []: " + path );
}
String[] indexCols = collPersister.getIndexColumnNames();
if ( indexCols.length != 1 ) throw new QueryException( "composite-index appears in []: " + path );
if ( indexCols.length != 1 ) {
throw new QueryException( "composite-index appears in []: " + path );
}
//String[] keyCols = collPersister.getKeyColumnNames();
JoinSequence fromJoins = new JoinSequence( q.getFactory() )
@ -361,7 +376,9 @@ public class PathExpressionParser implements Parser {
.setRoot( collPersister, collectionName )
.setNext( joinSequence.copy() );
if ( !continuation ) addJoin( collectionName, collPersister.getCollectionType() );
if ( !continuation ) {
addJoin( collectionName, collPersister.getCollectionType() );
}
joinSequence.addCondition( collectionName + '.' + indexCols[0] + " = " ); //TODO: get SQL rendering out of here

View File

@ -335,14 +335,20 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
String unalias(String path) {
String alias = StringHelper.root( path );
String name = getAliasName( alias );
if (name != null) return name + path.substring(alias.length());
if (name != null) {
return name + path.substring(alias.length());
}
return path;
}
void addEntityToFetch(String name, String oneToOneOwnerName, AssociationType ownerAssociationType) {
addEntityToFetch( name );
if ( oneToOneOwnerName != null ) oneToOneOwnerNames.put( name, oneToOneOwnerName );
if ( ownerAssociationType != null ) uniqueKeyOwnerReferences.put( name, ownerAssociationType );
if ( oneToOneOwnerName != null ) {
oneToOneOwnerNames.put( name, oneToOneOwnerName );
}
if ( ownerAssociationType != null ) {
uniqueKeyOwnerReferences.put( name, ownerAssociationType );
}
}
private void addEntityToFetch(String name) {
@ -387,7 +393,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
PropertyMapping getPropertyMapping(String name) throws QueryException {
PropertyMapping decorator = getDecoratedPropertyMapping( name );
if ( decorator != null ) return decorator;
if ( decorator != null ) {
return decorator;
}
String type = getType( name );
if ( type == null ) {
@ -399,7 +407,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
}
else {
Queryable persister = getEntityPersister( type );
if ( persister == null ) throw new QueryException( "persistent class not found: " + type );
if ( persister == null ) {
throw new QueryException( "persistent class not found: " + type );
}
return persister;
}
}
@ -415,7 +425,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
private Queryable getEntityPersisterForName(String name) throws QueryException {
String type = getType( name );
Queryable persister = getEntityPersister( type );
if ( persister == null ) throw new QueryException( "persistent class not found: " + type );
if ( persister == null ) {
throw new QueryException( "persistent class not found: " + type );
}
return persister;
}
@ -525,11 +537,15 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
}
void addJoin(String name, JoinSequence joinSequence) throws QueryException {
if ( !joins.containsKey( name ) ) joins.put( name, joinSequence );
if ( !joins.containsKey( name ) ) {
joins.put( name, joinSequence );
}
}
void addNamedParameter(String name) {
if ( superQuery != null ) superQuery.addNamedParameter( name );
if ( superQuery != null ) {
superQuery.addNamedParameter( name );
}
Integer loc = parameterCount++;
Object o = namedParameters.get( name );
if ( o == null ) {
@ -552,7 +568,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
if ( o == null ) {
throw new QueryException( ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name, queryString );
}
if ( o instanceof Integer ) return new int[] { (Integer) o };
if ( o instanceof Integer ) {
return new int[] { (Integer) o };
}
else {
return ArrayHelper.toIntArray( ( ArrayList ) o );
}
@ -588,14 +606,20 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
suffixes[i] = ( size == 1 ) ? "" : Integer.toString( i ) + '_';
names[i] = name;
includeInSelect[i] = !entitiesToFetch.contains( name );
if ( includeInSelect[i] ) selectLength++;
if ( name.equals( collectionOwnerName ) ) collectionOwnerColumn = i;
if ( includeInSelect[i] ) {
selectLength++;
}
if ( name.equals( collectionOwnerName ) ) {
collectionOwnerColumn = i;
}
String oneToOneOwner = ( String ) oneToOneOwnerNames.get( name );
owners[i] = ( oneToOneOwner == null ) ? -1 : returnedTypes.indexOf( oneToOneOwner );
ownerAssociationTypes[i] = (EntityType) uniqueKeyOwnerReferences.get( name );
}
if ( ArrayHelper.isAllNegative( owners ) ) owners = null;
if ( ArrayHelper.isAllNegative( owners ) ) {
owners = null;
}
String scalarSelect = renderScalarSelect(); //Must be done here because of side-effect! yuck...
@ -619,7 +643,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
sql.addSelectFragmentString( collectionPersister.selectFragment( fetchName, "__" ) );
}
if ( hasScalars || shallowQuery ) sql.addSelectFragmentString( scalarSelect );
if ( hasScalars || shallowQuery ) {
sql.addSelectFragmentString( scalarSelect );
}
//TODO: for some dialects it would be appropriate to add the renderOrderByPropertiesSelect() to other select strings
mergeJoins( sql.getJoinFragment() );
@ -650,7 +676,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
sqlString = sql.toQueryString();
if ( holderClass != null ) holderConstructor = ReflectHelper.getConstructor( holderClass, returnTypes );
if ( holderClass != null ) {
holderConstructor = ReflectHelper.getConstructor( holderClass, returnTypes );
}
if ( hasScalars ) {
actualReturnTypes = returnTypes;
@ -726,8 +754,12 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
String[] idColumnNames = persisters[k].getIdentifierColumnNames();
for ( int i = 0; i < idColumnNames.length; i++ ) {
buf.append( returnedTypes.get( k ) ).append( '.' ).append( idColumnNames[i] );
if ( !isSubselect ) buf.append( " as " ).append( NameGenerator.scalarName( k, i ) );
if ( i != idColumnNames.length - 1 || k != size - 1 ) buf.append( ", " );
if ( !isSubselect ) {
buf.append( " as " ).append( NameGenerator.scalarName( k, i ) );
}
if ( i != idColumnNames.length - 1 || k != size - 1 ) {
buf.append( ", " );
}
}
}
@ -759,8 +791,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
else {
if ( !isSubselect && parenCount == 0 ) {
int x = c++;
buf.append( " as " )
.append( NameGenerator.scalarName( x, 0 ) );
buf.append( " as " ).append( NameGenerator.scalarName( x, 0 ) );
}
}
}
@ -775,18 +806,18 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
for ( int i = 0; i < tokens.length; i++ ) {
buf.append( tokens[i] );
if ( !isSubselect ) {
buf.append( " as " )
.append( NameGenerator.scalarName( c, i ) );
buf.append( " as " ).append( NameGenerator.scalarName( c, i ) );
}
if ( i != tokens.length - 1 ) {
buf.append( ", " );
}
if ( i != tokens.length - 1 ) buf.append( ", " );
}
c++;
}
}
if ( !isSubselect && !nolast ) {
int x = c++;
buf.append( " as " )
.append( NameGenerator.scalarName( x, 0 ) );
buf.append( " as " ).append( NameGenerator.scalarName( x, 0 ) );
}
}
@ -803,8 +834,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
JoinSequence join = ( JoinSequence ) me.getValue();
join.setSelector( new JoinSequence.Selector() {
public boolean includeSubclasses(String alias) {
boolean include = returnedTypes.contains( alias ) && !isShallowQuery();
return include;
return returnedTypes.contains( alias ) && !isShallowQuery();
}
} );
@ -814,10 +844,6 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
else if ( collections.containsKey( name ) ) {
ojf.addFragment( join.toJoinFragment( enabledFilters, true ) );
}
else {
//name from a super query (a bit inelegant that it shows up here)
}
}
}
@ -950,7 +976,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
boolean stats = session.getFactory().getStatistics().isStatisticsEnabled();
long startTime = 0;
if ( stats ) startTime = System.nanoTime();
if ( stats ) {
startTime = System.nanoTime();
}
try {
final List<AfterLoadAction> afterLoadActions = new ArrayList<AfterLoadAction>();
@ -1091,7 +1119,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
for ( int i = 0; i < names.length; i++ ) {
LockMode lm = ( LockMode ) nameLockOptions.get( names[i] );
//if ( lm == null ) lm = LockOptions.NONE;
if ( lm == null ) lm = lockOptions.getLockMode();
if ( lm == null ) {
lm = lockOptions.getLockMode();
}
lockModesArray[i] = lm;
}
return lockModesArray;
@ -1170,11 +1200,12 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
return enabledFilters;
}
public ScrollableResults scroll(final QueryParameters queryParameters,
final SessionImplementor session)
throws HibernateException {
public ScrollableResults scroll(
final QueryParameters queryParameters,
final SessionImplementor session) throws HibernateException {
HolderInstantiator hi = HolderInstantiator.createClassicHolderInstantiator(
holderConstructor, queryParameters.getResultTransformer()
holderConstructor,
queryParameters.getResultTransformer()
);
return scroll( queryParameters, returnTypes, hi, session );
}

View File

@ -45,7 +45,7 @@ public class SelectParser implements Parser {
//TODO: arithmetic expressions, multiple new Foo(...)
private static final Set COUNT_MODIFIERS = new HashSet();
private static final Set<String> COUNT_MODIFIERS = new HashSet<String>();
static {
COUNT_MODIFIERS.add( "distinct" );
@ -53,7 +53,7 @@ public class SelectParser implements Parser {
COUNT_MODIFIERS.add( "*" );
}
private LinkedList aggregateFuncTokenList = new LinkedList();
private LinkedList<String> aggregateFuncTokenList = new LinkedList<String>();
private boolean ready;
private boolean aggregate;
@ -75,7 +75,6 @@ public class SelectParser implements Parser {
}
public void token(String token, QueryTranslatorImpl q) throws QueryException {
String lctoken = token.toLowerCase(Locale.ROOT);
if ( first ) {
@ -98,12 +97,16 @@ public class SelectParser implements Parser {
catch ( ClassNotFoundException cnfe ) {
throw new QueryException( cnfe );
}
if ( holderClass == null ) throw new QueryException( "class not found: " + token );
if ( holderClass == null ) {
throw new QueryException( "class not found: " + token );
}
q.setHolderClass( holderClass );
insideNew = true;
}
else if ( token.equals( "," ) ) {
if ( !aggregate && ready ) throw new QueryException( "alias or expression expected in SELECT" );
if ( !aggregate && ready ) {
throw new QueryException( "alias or expression expected in SELECT" );
}
q.appendScalarSelectToken( ", " );
ready = true;
}
@ -175,7 +178,9 @@ public class SelectParser implements Parser {
}
else if ( aggregate ) {
boolean constantToken = false;
if ( !ready ) throw new QueryException( "( expected after aggregate function in SELECT" );
if ( !ready ) {
throw new QueryException( "( expected after aggregate function in SELECT" );
}
try {
ParserHelper.parse( aggregatePathExpressionParser, q.unalias( token ), ParserHelper.PATH_SEPARATORS, q );
}
@ -200,7 +205,9 @@ public class SelectParser implements Parser {
}
}
else {
if ( !ready ) throw new QueryException( ", expected in SELECT" );
if ( !ready ) {
throw new QueryException( ", expected in SELECT" );
}
ParserHelper.parse( pathExpressionParser, q.unalias( token ), ParserHelper.PATH_SEPARATORS, q );
if ( pathExpressionParser.isCollectionValued() ) {
q.addCollection( pathExpressionParser.getCollectionName(),

View File

@ -69,10 +69,10 @@ public class WhereParser implements Parser {
pathExpressionParser.setUseThetaStyleJoin( true ); //Need this, since join condition can appear inside parens!
}
private static final Set EXPRESSION_TERMINATORS = new HashSet(); //tokens that close a sub expression
private static final Set EXPRESSION_OPENERS = new HashSet(); //tokens that open a sub expression
private static final Set BOOLEAN_OPERATORS = new HashSet(); //tokens that would indicate a sub expression is a boolean expression
private static final Map NEGATIONS = new HashMap();
private static final Set<String> EXPRESSION_TERMINATORS = new HashSet<String>(); //tokens that close a sub expression
private static final Set<String> EXPRESSION_OPENERS = new HashSet<String>(); //tokens that open a sub expression
private static final Set<String> BOOLEAN_OPERATORS = new HashSet<String>(); //tokens that would indicate a sub expression is a boolean expression
private static final Map<String,String> NEGATIONS = new HashMap<String,String>();
static {
EXPRESSION_TERMINATORS.add( "and" );
@ -188,7 +188,7 @@ public class WhereParser implements Parser {
// in the list of nested subexpressions we are currently processing.
private LinkedList<Boolean> nots = new LinkedList<Boolean>(); //were an odd or even number of NOTs encountered
private LinkedList joins = new LinkedList(); //the join string built up by compound paths inside this expression
private LinkedList<StringBuilder> joins = new LinkedList<StringBuilder>(); //the join string built up by compound paths inside this expression
private LinkedList<Boolean> booleanTests = new LinkedList<Boolean>(); //a flag indicating if the subexpression is known to be boolean
private String getElementName(PathExpressionParser.CollectionElement element, QueryTranslatorImpl q) throws QueryException {
@ -210,13 +210,14 @@ public class WhereParser implements Parser {
}
public void token(String token, QueryTranslatorImpl q) throws QueryException {
String lcToken = token.toLowerCase(Locale.ROOT);
//Cope with [,]
if ( token.equals( "[" ) && !expectingPathContinuation ) {
expectingPathContinuation = false;
if ( expectingIndex == 0 ) throw new QueryException( "unexpected [" );
if ( expectingIndex == 0 ) {
throw new QueryException( "unexpected [" );
}
return;
}
else if ( token.equals( "]" ) ) {
@ -228,7 +229,9 @@ public class WhereParser implements Parser {
//Cope with a continued path expression (ie. ].baz)
if ( expectingPathContinuation ) {
boolean pathExpressionContinuesFurther = continuePathExpression( token, q );
if ( pathExpressionContinuesFurther ) return; //NOTE: early return
if ( pathExpressionContinuesFurther ) {
return; //NOTE: early return
}
}
//Cope with a subselect
@ -257,7 +260,9 @@ public class WhereParser implements Parser {
}
}
if ( inSubselect ) {
if ( token.equals( "(" ) ) bracketsSinceSelect++;
if ( token.equals( "(" ) ) {
bracketsSinceSelect++;
}
subselect.append( token ).append( ' ' );
return;
}
@ -303,7 +308,9 @@ public class WhereParser implements Parser {
if ( expectingPathContinuation ) {
expectingPathContinuation = false;
PathExpressionParser.CollectionElement element = pathExpressionParser.lastCollectionElement();
if ( element.elementColumns.length != 1 ) throw new QueryException( "path expression ended in composite collection element" );
if ( element.elementColumns.length != 1 ) {
throw new QueryException( "path expression ended in composite collection element" );
}
appendToken( q, element.elementColumns[0] );
addToCurrentJoin( element );
}
@ -324,20 +331,26 @@ public class WhereParser implements Parser {
}
else {
StringBuilder join = ( StringBuilder ) joins.removeLast();
( ( StringBuilder ) joins.getLast() ).append( join.toString() );
StringBuilder join = joins.removeLast();
joins.getLast().append( join.toString() );
}
if ( nots.removeLast() ) negated = !negated;
if ( nots.removeLast() ) {
negated = !negated;
}
if ( !")".equals( lcToken ) ) appendToken( q, ")" );
if ( !")".equals( lcToken ) ) {
appendToken( q, ")" );
}
}
private void openExpression(QueryTranslatorImpl q, String lcToken) {
nots.addLast( Boolean.FALSE );
booleanTests.addLast( Boolean.FALSE );
joins.addLast( new StringBuilder() );
if ( !"(".equals( lcToken ) ) appendToken( q, "(" );
if ( !"(".equals( lcToken ) ) {
appendToken( q, "(" );
}
}
private void preprocess(String token, QueryTranslatorImpl q) throws QueryException {
@ -434,6 +447,7 @@ public class WhereParser implements Parser {
}
if ( type == null ) throw new QueryException( QueryTranslator.ERROR_CANNOT_DETERMINE_TYPE + token );
try {
//noinspection unchecked
appendToken( q, ( ( LiteralType ) type ).objectToSQLString( constant, q.getFactory().getDialect() ) );
}
catch ( Exception e ) {
@ -442,7 +456,7 @@ public class WhereParser implements Parser {
}
else { //anything else
String negatedToken = negated ? ( String ) NEGATIONS.get( token.toLowerCase(Locale.ROOT) ) : null;
String negatedToken = negated ? NEGATIONS.get( token.toLowerCase(Locale.ROOT) ) : null;
if ( negatedToken != null && ( !betweenSpecialCase || !"or".equals( negatedToken ) ) ) {
appendToken( q, negatedToken );
}
@ -455,7 +469,7 @@ public class WhereParser implements Parser {
}
private void addToCurrentJoin(String sql) {
( ( StringBuilder ) joins.getLast() ).append( sql );
joins.getLast().append( sql );
}
private void addToCurrentJoin(PathExpressionParser.CollectionElement ce)

View File

@ -20,9 +20,9 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.id;
import java.net.InetAddress;
import org.hibernate.internal.util.BytesHelper;
@ -35,7 +35,6 @@ import org.hibernate.internal.util.BytesHelper;
* @see UUIDHexGenerator
* @author Gavin King
*/
public abstract class AbstractUUIDGenerator implements IdentifierGenerator {
private static final int IP;
@ -49,6 +48,7 @@ public abstract class AbstractUUIDGenerator implements IdentifierGenerator {
}
IP = ipadd;
}
private static short counter = (short) 0;
private static final int JVM = (int) ( System.currentTimeMillis() >>> 8 );
@ -69,7 +69,9 @@ public abstract class AbstractUUIDGenerator implements IdentifierGenerator {
*/
protected short getCount() {
synchronized(AbstractUUIDGenerator.class) {
if (counter<0) counter=0;
if ( counter < 0 ) {
counter=0;
}
return counter++;
}
}
@ -87,11 +89,11 @@ public abstract class AbstractUUIDGenerator implements IdentifierGenerator {
protected short getHiTime() {
return (short) ( System.currentTimeMillis() >>> 32 );
}
protected int getLoTime() {
return (int) System.currentTimeMillis();
}
}

View File

@ -34,13 +34,12 @@ import org.hibernate.MappingException;
import org.hibernate.boot.model.naming.ObjectNameNormalizer;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.mapping.Table;
import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/**
* <b>increment</b><br>
* <br>
@ -56,8 +55,7 @@ import org.jboss.logging.Logger;
* @author Brett Meyer
*/
public class IncrementGenerator implements IdentifierGenerator, Configurable {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, IncrementGenerator.class.getName());
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( IncrementGenerator.class );
private Class returnClass;
private String sql;
@ -128,8 +126,12 @@ public class IncrementGenerator implements IdentifierGenerator, Configurable {
try {
ResultSet rs = session.getJdbcCoordinator().getResultSetReturn().extract( st );
try {
if (rs.next()) previousValueHolder.initialize(rs, 0L).increment();
else previousValueHolder.initialize(1L);
if (rs.next()) {
previousValueHolder.initialize(rs, 0L).increment();
}
else {
previousValueHolder.initialize(1L);
}
sql = null;
if ( debugEnabled ) {
LOG.debugf( "First free id: %s", previousValueHolder.makeValue() );

View File

@ -968,7 +968,9 @@ public abstract class AbstractQueryImpl implements Query {
static Object uniqueElement(List list) throws NonUniqueResultException {
int size = list.size();
if (size==0) return null;
if (size==0) {
return null;
}
Object first = list.get(0);
for ( int i=1; i<size; i++ ) {
if ( list.get(i)!=first ) {

View File

@ -88,7 +88,9 @@ public class CollectionFilterImpl extends QueryImpl {
List typeList = getTypes();
int size = typeList.size();
Type[] result = new Type[size+1];
for (int i=0; i<size; i++) result[i+1] = (Type) typeList.get(i);
for (int i=0; i<size; i++) {
result[i+1] = (Type) typeList.get(i);
}
return result;
}
@ -96,7 +98,9 @@ public class CollectionFilterImpl extends QueryImpl {
List valueList = getValues();
int size = valueList.size();
Object[] result = new Object[size+1];
for (int i=0; i<size; i++) result[i+1] = valueList.get(i);
for (int i=0; i<size; i++) {
result[i+1] = valueList.get(i);
}
return result;
}

View File

@ -37,16 +37,13 @@ import org.hibernate.hql.internal.HolderInstantiator;
import org.hibernate.type.EntityType;
import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/**
* An implementation of <tt>java.util.Iterator</tt> that is
* returned by <tt>iterate()</tt> query execution methods.
* @author Gavin King
*/
public final class IteratorImpl implements HibernateIterator {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, IteratorImpl.class.getName());
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( IteratorImpl.class );
private ResultSet rs;
private final EventSource session;
@ -84,12 +81,8 @@ public final class IteratorImpl implements HibernateIterator {
public void close() throws JDBCException {
if (ps!=null) {
LOG.debug("Closing iterator");
LOG.debug( "Closing iterator" );
session.getJdbcCoordinator().getResourceRegistry().release( ps );
session.getJdbcCoordinator().afterStatementExecution();
ps = null;
rs = null;
hasNext = false;
try {
session.getPersistenceContext().getLoadContexts().cleanup( rs );
}
@ -97,6 +90,10 @@ public final class IteratorImpl implements HibernateIterator {
// ignore this error for now
LOG.debugf("Exception trying to cleanup load context : %s", ignore.getMessage());
}
session.getJdbcCoordinator().afterStatementExecution();
ps = null;
rs = null;
hasNext = false;
}
}
@ -106,7 +103,10 @@ public final class IteratorImpl implements HibernateIterator {
if (!hasNext) {
LOG.debug("Exhausted results");
close();
} else LOG.debug("Retrieved next results");
}
else {
LOG.debug("Retrieved next results");
}
}
public boolean hasNext() {
@ -114,7 +114,9 @@ public final class IteratorImpl implements HibernateIterator {
}
public Object next() throws HibernateException {
if ( !hasNext ) throw new NoSuchElementException("No more results");
if ( !hasNext ) {
throw new NoSuchElementException("No more results");
}
boolean sessionDefaultReadOnlyOrig = session.isDefaultReadOnly();
session.setDefaultReadOnly( readOnly );
try {
@ -169,6 +171,6 @@ public final class IteratorImpl implements HibernateIterator {
currentResult,
false,
null
);
);
}
}

View File

@ -826,7 +826,7 @@ public final class SessionFactoryImpl implements SessionFactoryImplementor {
return result;
}
@Deprecated
@SuppressWarnings("deprecation")
public Settings getSettings() {
return settings;
}

View File

@ -45,7 +45,6 @@ import org.jboss.logging.Logger;
* @author Steve Ebersole
*/
public final class ConfigHelper {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, ConfigHelper.class.getName());
/** Try to locate a local URL representing the incoming path. The first attempt
@ -82,13 +81,15 @@ public final class ConfigHelper {
if (contextClassLoader!=null) {
url = contextClassLoader.getResource(path);
}
if (url != null)
if (url != null) {
return url;
}
// Next, try to locate this resource through this class's classloader
url = ConfigHelper.class.getClassLoader().getResource(path);
if (url != null)
if (url != null) {
return url;
}
// Next, try to locate this resource through the system classloader
url = ClassLoader.getSystemClassLoader().getResource(path);
@ -155,8 +156,9 @@ public final class ConfigHelper {
private ConfigHelper() {}
public static InputStream getResourceAsStream(String resource) {
String stripped = resource.startsWith("/") ?
resource.substring(1) : resource;
String stripped = resource.startsWith("/")
? resource.substring(1)
: resource;
InputStream stream = null;
ClassLoader classLoader = ClassLoaderHelper.getContextClassLoader();

View File

@ -32,19 +32,17 @@ import org.hibernate.bytecode.instrumentation.spi.LazyPropertyInitializer;
import org.hibernate.engine.spi.EntityKey;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.TypedValue;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/**
* Renders entities and query parameters to a nicely readable string.
* @author Gavin King
*/
public final class EntityPrinter {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, EntityPrinter.class.getName());
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( EntityPrinter.class );
private SessionFactoryImplementor factory;
@ -100,9 +98,9 @@ public final class EntityPrinter {
for ( Map.Entry<String, TypedValue> entry : namedTypedValues.entrySet() ) {
result.put(
entry.getKey(), entry.getValue().getType().toLoggableString(
entry.getValue().getValue(),
factory
)
entry.getValue().getValue(),
factory
)
);
}
return result.toString();
@ -110,7 +108,10 @@ public final class EntityPrinter {
// Cannot use Map as an argument because it clashes with the previous method (due to type erasure)
public void toString(Iterable<Map.Entry<EntityKey,Object>> entitiesByEntityKey) throws HibernateException {
if ( ! LOG.isDebugEnabled() || ! entitiesByEntityKey.iterator().hasNext() ) return;
if ( ! LOG.isDebugEnabled() || ! entitiesByEntityKey.iterator().hasNext() ) {
return;
}
LOG.debug( "Listing entities:" );
int i=0;
for ( Map.Entry<EntityKey,Object> entityKeyAndEntity : entitiesByEntityKey ) {

View File

@ -35,6 +35,7 @@ import java.io.OutputStream;
import java.io.Serializable;
import org.hibernate.Hibernate;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.type.SerializationException;
@ -63,8 +64,7 @@ import org.jboss.logging.Logger;
* @since 1.0
*/
public final class SerializationHelper {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, SerializationHelper.class.getName());
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( SerializationHelper.class );
private SerializationHelper() {
}
@ -371,7 +371,9 @@ public final class SerializationHelper {
}
private boolean different(ClassLoader one, ClassLoader other) {
if (one == null) return other != null;
if (one == null) {
return other != null;
}
return !one.equals(other);
}
}

View File

@ -44,25 +44,22 @@ public final class StringHelper {
private StringHelper() { /* static methods only - hide constructor */
}
/*public static boolean containsDigits(String string) {
for ( int i=0; i<string.length(); i++ ) {
if ( Character.isDigit( string.charAt(i) ) ) return true;
}
return false;
}*/
public static int lastIndexOfLetter(String string) {
for ( int i=0; i<string.length(); i++ ) {
char character = string.charAt(i);
// Include "_". See HHH-8073
if ( !Character.isLetter(character) && !('_'==character) ) return i-1;
if ( !Character.isLetter(character) && !('_'==character) ) {
return i-1;
}
}
return string.length()-1;
}
public static String join(String seperator, String[] strings) {
int length = strings.length;
if ( length == 0 ) return "";
if ( length == 0 ) {
return "";
}
StringBuilder buf = new StringBuilder( length * strings[0].length() )
.append( strings[0] );
for ( int i = 1; i < length; i++ ) {
@ -73,7 +70,9 @@ public final class StringHelper {
public static String joinWithQualifierAndSuffix(String[] values, String qualifier, String suffix, String deliminator) {
int length = values.length;
if ( length == 0 ) return "";
if ( length == 0 ) {
return "";
}
StringBuilder buf = new StringBuilder( length * ( values[0].length() + suffix.length() ) )
.append( qualify( qualifier, values[0] ) ).append( suffix );
for ( int i = 1; i < length; i++ ) {
@ -84,7 +83,9 @@ public final class StringHelper {
public static String join(String seperator, Iterator objects) {
StringBuilder buf = new StringBuilder();
if ( objects.hasNext() ) buf.append( objects.next() );
if ( objects.hasNext() ) {
buf.append( objects.next() );
}
while ( objects.hasNext() ) {
buf.append( seperator ).append( objects.next() );
}
@ -105,7 +106,9 @@ public final class StringHelper {
public static String repeat(String string, int times) {
StringBuilder buf = new StringBuilder( string.length() * times );
for ( int i = 0; i < times; i++ ) buf.append( string );
for ( int i = 0; i < times; i++ ) {
buf.append( string );
}
return buf.toString();
}
@ -141,13 +144,14 @@ public final class StringHelper {
return replace( template, placeholder, replacement, wholeWords, false );
}
public static String replace(String template,
String placeholder,
String replacement,
boolean wholeWords,
boolean encloseInParensIfNecessary) {
public static String replace(
String template,
String placeholder,
String replacement,
boolean wholeWords,
boolean encloseInParensIfNecessary) {
if ( template == null ) {
return template;
return null;
}
int loc = template.indexOf( placeholder );
if ( loc < 0 ) {
@ -161,21 +165,22 @@ public final class StringHelper {
}
public static String replace(String beforePlaceholder,
String afterPlaceholder,
String placeholder,
String replacement,
boolean wholeWords,
boolean encloseInParensIfNecessary) {
public static String replace(
String beforePlaceholder,
String afterPlaceholder,
String placeholder,
String replacement,
boolean wholeWords,
boolean encloseInParensIfNecessary) {
final boolean actuallyReplace =
! wholeWords ||
afterPlaceholder.length() == 0 ||
! Character.isJavaIdentifierPart( afterPlaceholder.charAt( 0 ) );
! wholeWords
|| afterPlaceholder.length() == 0
|| ! Character.isJavaIdentifierPart( afterPlaceholder.charAt( 0 ) );
boolean encloseInParens =
actuallyReplace &&
encloseInParensIfNecessary &&
! ( getLastNonWhitespaceCharacter( beforePlaceholder ) == '(' ) &&
! ( getFirstNonWhitespaceCharacter( afterPlaceholder ) == ')' );
actuallyReplace
&& encloseInParensIfNecessary
&& ! ( getLastNonWhitespaceCharacter( beforePlaceholder ) == '(' )
&& ! ( getFirstNonWhitespaceCharacter( afterPlaceholder ) == ')' );
StringBuilder buf = new StringBuilder( beforePlaceholder );
if ( encloseInParens ) {
buf.append( '(' );
@ -222,17 +227,14 @@ public final class StringHelper {
public static String replaceOnce(String template, String placeholder, String replacement) {
if ( template == null ) {
return template; // returnign null!
return null; // returnign null!
}
int loc = template.indexOf( placeholder );
if ( loc < 0 ) {
return template;
}
else {
return new StringBuilder( template.substring( 0, loc ) )
.append( replacement )
.append( template.substring( loc + placeholder.length() ) )
.toString();
return template.substring( 0, loc ) + replacement + template.substring( loc + placeholder.length() );
}
}
@ -357,13 +359,15 @@ public final class StringHelper {
}
public static boolean booleanValue(String tfString) {
String trimmed = tfString.trim().toLowerCase(Locale.ROOT);
String trimmed = tfString.trim().toLowerCase( Locale.ROOT );
return trimmed.equals( "true" ) || trimmed.equals( "t" );
}
public static String toString(Object[] array) {
int len = array.length;
if ( len == 0 ) return "";
if ( len == 0 ) {
return "";
}
StringBuilder buf = new StringBuilder( len * 12 );
for ( int i = 0; i < len - 1; i++ ) {
buf.append( array[i] ).append(", ");
@ -382,9 +386,9 @@ public final class StringHelper {
private static String[] multiply(String[] strings, String placeholder, String[] replacements) {
String[] results = new String[replacements.length * strings.length];
int n = 0;
for ( int i = 0; i < replacements.length; i++ ) {
for ( int j = 0; j < strings.length; j++ ) {
results[n++] = replaceOnce( strings[j], placeholder, replacements[i] );
for ( String replacement : replacements ) {
for ( String string : strings ) {
results[n++] = replaceOnce( string, placeholder, replacement );
}
}
return results;
@ -541,9 +545,9 @@ public final class StringHelper {
* @return an alias of the form <samp>foo1_</samp>
*/
public static String generateAlias(String description, int unique) {
return generateAliasRoot(description) +
Integer.toString(unique) +
'_';
return generateAliasRoot(description)
+ Integer.toString(unique)
+ '_';
}
/**
@ -602,7 +606,9 @@ public final class StringHelper {
public static String moveAndToBeginning(String filter) {
if ( filter.trim().length()>0 ){
filter += " and ";
if ( filter.startsWith(" and ") ) filter = filter.substring(4);
if ( filter.startsWith(" and ") ) {
filter = filter.substring(4);
}
}
return filter;
}
@ -635,7 +641,7 @@ public final class StringHelper {
name = name.substring( 1, name.length() - 1 );
}
return new StringBuilder( name.length() + 2 ).append('`').append( name ).append( '`' ).toString();
return "`" + name + '`';
}
/**

View File

@ -45,8 +45,9 @@ public final class ArrayHelper {
public static int indexOf(Object[] array, Object object) {
for ( int i = 0; i < array.length; i++ ) {
if ( array[i].equals( object ) )
if ( array[i].equals( object ) ) {
return i;
}
}
return -1;
}
@ -205,7 +206,9 @@ public final class ArrayHelper {
sb.append("[");
for (int i = 0; i < array.length; i++) {
sb.append( array[i] );
if( i<array.length-1 ) sb.append(",");
if( i<array.length-1 ) {
sb.append(",");
}
}
sb.append("]");
return sb.toString();
@ -256,7 +259,7 @@ public final class ArrayHelper {
return true;
}
public static void addAll(Collection collection, Object[] array) {
public static <T> void addAll(Collection<T> collection, T[] array) {
collection.addAll( Arrays.asList( array ) );
}
@ -343,12 +346,20 @@ public final class ArrayHelper {
* Compare 2 arrays only at the first level
*/
public static boolean isEquals(Object[] o1, Object[] o2) {
if (o1 == o2) return true;
if (o1 == null || o2 == null) return false;
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
int length = o1.length;
if (length != o2.length) return false;
if (length != o2.length) {
return false;
}
for (int index = 0 ; index < length ; index++) {
if ( ! o1[index].equals( o2[index] ) ) return false;
if ( ! o1[index].equals( o2[index] ) ) {
return false;
}
}
return true;
}
@ -357,12 +368,20 @@ public final class ArrayHelper {
* Compare 2 arrays only at the first level
*/
public static boolean isEquals(char[] o1, char[] o2) {
if (o1 == o2) return true;
if (o1 == null || o2 == null) return false;
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
int length = o1.length;
if (length != o2.length) return false;
if (length != o2.length) {
return false;
}
for (int index = 0 ; index < length ; index++) {
if ( ! ( o1[index] == o2[index] ) ) return false;
if ( ! ( o1[index] == o2[index] ) ) {
return false;
}
}
return true;
}
@ -371,12 +390,20 @@ public final class ArrayHelper {
* Compare 2 arrays only at the first level
*/
public static boolean isEquals(byte[] b1, byte[] b2) {
if (b1 == b2) return true;
if (b1 == null || b2 == null) return false;
if (b1 == b2) {
return true;
}
if (b1 == null || b2 == null) {
return false;
}
int length = b1.length;
if (length != b2.length) return false;
if (length != b2.length) {
return false;
}
for (int index = 0 ; index < length ; index++) {
if ( ! ( b1[index] == b2[index] ) ) return false;
if ( ! ( b1[index] == b2[index] ) ) {
return false;
}
}
return true;
}

View File

@ -75,13 +75,20 @@ public class Expectations {
}
private void checkBatched(int rowCount, int batchPosition) {
if (rowCount == -2) LOG.debugf("Success of batch update unknown: %s", batchPosition);
else if (rowCount == -3) throw new BatchFailedException("Batch update failed: " + batchPosition);
if (rowCount == -2) {
LOG.debugf("Success of batch update unknown: %s", batchPosition);
}
else if (rowCount == -3) {
throw new BatchFailedException("Batch update failed: " + batchPosition);
}
else {
if (expectedRowCount > rowCount) throw new StaleStateException(
"Batch update returned unexpected row count from update ["
+ batchPosition + "]; actual row count: " + rowCount
+ "; expected: " + expectedRowCount);
if (expectedRowCount > rowCount) {
throw new StaleStateException(
"Batch update returned unexpected row count from update ["
+ batchPosition + "]; actual row count: " + rowCount
+ "; expected: " + expectedRowCount
);
}
if ( expectedRowCount < rowCount ) {
String msg = "Batch update returned unexpected row count from update [" +
batchPosition + "]; actual row count: " + rowCount +

View File

@ -112,7 +112,9 @@ public abstract class BasicLoader extends Loader {
}
public static String[] generateSuffixes(int seed, int length) {
if ( length == 0 ) return NO_SUFFIX;
if ( length == 0 ) {
return NO_SUFFIX;
}
String[] suffixes = new String[length];
for ( int i = 0; i < length; i++ ) {

View File

@ -129,7 +129,9 @@ public class GeneratedCollectionAliases implements CollectionAliases {
}
private String join(String[] aliases) {
if ( aliases == null) return null;
if ( aliases == null) {
return null;
}
return StringHelper.join( ", ", aliases );
}

View File

@ -745,8 +745,12 @@ public class JoinWalker {
return false;
}
else {
if (config==FetchMode.JOIN) return true;
if (config==FetchMode.SELECT) return false;
if (config==FetchMode.JOIN) {
return true;
}
if (config==FetchMode.SELECT) {
return false;
}
if ( type.isEntityType() ) {
//TODO: look at the owning property and check that it
// isn't lazy (by instrumentation)
@ -844,7 +848,7 @@ public class JoinWalker {
return true;
}
Integer maxFetchDepth = getFactory().getSettings().getMaximumFetchDepth();
Integer maxFetchDepth = getFactory().getSessionFactoryOptions().getMaximumFetchDepth();
final boolean tooDeep = maxFetchDepth!=null && depth >= maxFetchDepth;
return !tooDeep && !isDuplicateAssociation(lhsTable, lhsColumnNames, type);
@ -875,7 +879,7 @@ public class JoinWalker {
Iterator iter = associations.iterator();
OuterJoinableAssociation last = null;
while ( iter.hasNext() ) {
OuterJoinableAssociation oj = (OuterJoinableAssociation) iter.next();
final OuterJoinableAssociation oj = (OuterJoinableAssociation) iter.next();
if ( last != null && last.isManyToManyWith( oj ) ) {
oj.addManyToManyJoin( outerjoin, ( QueryableCollection ) last.getJoinable() );
}
@ -892,12 +896,11 @@ public class JoinWalker {
* Count the number of instances of Joinable which are actually
* also instances of Loadable, or are one-to-many associations
*/
protected static final int countEntityPersisters(List associations)
protected static int countEntityPersisters(List associations)
throws MappingException {
int result = 0;
Iterator iter = associations.iterator();
while ( iter.hasNext() ) {
OuterJoinableAssociation oj = (OuterJoinableAssociation) iter.next();
for ( Object association : associations ) {
final OuterJoinableAssociation oj = (OuterJoinableAssociation) association;
if ( oj.getJoinable().consumesEntityAlias() ) {
result++;
}
@ -910,15 +913,14 @@ public class JoinWalker {
* also instances of PersistentCollection which are being fetched
* by outer join
*/
protected static final int countCollectionPersisters(List associations)
protected static int countCollectionPersisters(List associations)
throws MappingException {
int result = 0;
Iterator iter = associations.iterator();
while ( iter.hasNext() ) {
OuterJoinableAssociation oj = (OuterJoinableAssociation) iter.next();
if ( oj.getJoinType()==JoinType.LEFT_OUTER_JOIN &&
for ( Object association : associations ) {
final OuterJoinableAssociation oj = (OuterJoinableAssociation) association;
if ( oj.getJoinType() == JoinType.LEFT_OUTER_JOIN &&
oj.getJoinable().isCollection() &&
! oj.hasRestriction() ) {
!oj.hasRestriction() ) {
result++;
}
}
@ -928,7 +930,7 @@ public class JoinWalker {
/**
* Get the order by string required for collection fetching
*/
protected static final String orderBy(List associations)
protected static String orderBy(List associations)
throws MappingException {
StringBuilder buf = new StringBuilder();
Iterator iter = associations.iterator();
@ -959,7 +961,9 @@ public class JoinWalker {
}
last = oj;
}
if ( buf.length()>0 ) buf.setLength( buf.length()-2 );
if ( buf.length()>0 ) {
buf.setLength( buf.length()-2 );
}
return buf.toString();
}
@ -971,7 +975,9 @@ public class JoinWalker {
// if not a composite key, use "foo in (?, ?, ?)" for batching
// if no batch, and not a composite key, use "foo = ?"
InFragment in = new InFragment().setColumn( alias, columnNames[0] );
for ( int i=0; i<batchSize; i++ ) in.addValue("?");
for ( int i=0; i<batchSize; i++ ) {
in.addValue("?");
}
return new StringBuilder( in.toFragmentString() );
}
else {
@ -1004,13 +1010,13 @@ public class JoinWalker {
initPersisters( associations, new LockOptions(lockMode));
}
protected static interface AssociationInitCallback {
public static final AssociationInitCallback NO_CALLBACK = new AssociationInitCallback() {
protected interface AssociationInitCallback {
AssociationInitCallback NO_CALLBACK = new AssociationInitCallback() {
public void associationProcessed(OuterJoinableAssociation oja, int position) {
}
};
public void associationProcessed(OuterJoinableAssociation oja, int position);
void associationProcessed(OuterJoinableAssociation oja, int position);
}
protected void initPersisters(final List associations, final LockOptions lockOptions) throws MappingException {
initPersisters( associations, lockOptions, AssociationInitCallback.NO_CALLBACK );
@ -1069,7 +1075,9 @@ public class JoinWalker {
}
}
if ( ArrayHelper.isAllNegative(owners) ) owners = null;
if ( ArrayHelper.isAllNegative(owners) ) {
owners = null;
}
if ( collectionOwners!=null && ArrayHelper.isAllNegative(collectionOwners) ) {
collectionOwners = null;
}
@ -1078,8 +1086,7 @@ public class JoinWalker {
/**
* Generate a select list of columns containing all properties of the entity classes
*/
protected final String selectString(List associations)
throws MappingException {
protected final String selectString(List associations) throws MappingException {
if ( associations.size()==0 ) {
return "";
@ -1111,7 +1118,9 @@ public class JoinWalker {
if (selectFragment.trim().length() > 0) {
buf.append(", ").append(selectFragment);
}
if ( joinable.consumesEntityAlias() ) entityAliasCount++;
if ( joinable.consumesEntityAlias() ) {
entityAliasCount++;
}
if ( joinable.consumesCollectionAlias() &&
join.getJoinType()==JoinType.LEFT_OUTER_JOIN &&
!join.hasRestriction() ) {

View File

@ -950,8 +950,9 @@ public abstract class Loader {
int count;
for ( count = 0; count < maxRows && rs.next(); count++ ) {
if ( DEBUG_ENABLED )
if ( DEBUG_ENABLED ) {
LOG.debugf( "Result set row: %s", count );
}
Object result = getRowFromResultSet(
rs,
session,
@ -1019,13 +1020,11 @@ public abstract class Loader {
final Loadable[] loadables = getEntityPersisters();
final String[] aliases = getAliases();
final Iterator iter = keys.iterator();
while ( iter.hasNext() ) {
for ( Object key : keys ) {
final EntityKey[] rowKeys = (EntityKey[]) key;
for ( int i = 0; i < rowKeys.length; i++ ) {
final EntityKey[] rowKeys = (EntityKey[]) iter.next();
for ( int i=0; i<rowKeys.length; i++ ) {
if ( rowKeys[i]!=null && loadables[i].hasSubselectLoadableCollections() ) {
if ( rowKeys[i] != null && loadables[i].hasSubselectLoadableCollections() ) {
SubselectFetch subselectFetch = new SubselectFetch(
//getSQLString(),
@ -1034,7 +1033,7 @@ public abstract class Loader {
queryParameters,
keySets[i],
namedParameterLocMap
);
);
session.getPersistenceContext()
.getBatchFetchQueue()
@ -1113,19 +1112,19 @@ public abstract class Loader {
if ( hydratedObjects!=null ) {
int hydratedObjectsSize = hydratedObjects.size();
LOG.tracev( "Total objects hydrated: {0}", hydratedObjectsSize );
for ( int i = 0; i < hydratedObjectsSize; i++ ) {
TwoPhaseLoad.initializeEntity( hydratedObjects.get(i), readOnly, session, pre );
for ( Object hydratedObject : hydratedObjects ) {
TwoPhaseLoad.initializeEntity( hydratedObject, readOnly, session, pre );
}
}
if ( collectionPersisters != null ) {
for ( int i=0; i<collectionPersisters.length; i++ ) {
if ( !collectionPersisters[i].isArray() ) {
for ( CollectionPersister collectionPersister : collectionPersisters ) {
if ( !collectionPersister.isArray() ) {
//for sets, we should end the collection load after resolving
//the entities, since we might call hashCode() on the elements
//TODO: or we could do this polymorphically, and have two
// different operations implemented differently for arrays
endCollectionLoad( resultSetId, session, collectionPersisters[i] );
endCollectionLoad( resultSetId, session, collectionPersister );
}
}
}
@ -1366,21 +1365,21 @@ public abstract class Loader {
// for each of the passed-in keys, to account for the possibility
// that the collection is empty and has no rows in the result set
CollectionPersister[] collectionPersisters = getCollectionPersisters();
for ( int j=0; j<collectionPersisters.length; j++ ) {
for ( CollectionPersister collectionPersister : collectionPersisters )
for ( int i = 0; i < keys.length; i++ ) {
//handle empty collections
if ( debugEnabled ) {
LOG.debugf( "Result set contains (possibly empty) collection: %s",
MessageHelper.collectionInfoString( collectionPersisters[j], keys[i], getFactory() ) );
LOG.debugf(
"Result set contains (possibly empty) collection: %s",
MessageHelper.collectionInfoString( collectionPersister, keys[i], getFactory() )
);
}
session.getPersistenceContext()
.getLoadContexts()
.getCollectionLoadContext( ( ResultSet ) resultSetId )
.getLoadingCollection( collectionPersisters[j], keys[i] );
.getCollectionLoadContext( (ResultSet) resultSetId )
.getLoadingCollection( collectionPersister, keys[i] );
}
}
}
// else this is not a collection initializer (and empty collections will
@ -1410,20 +1409,21 @@ public abstract class Loader {
resultId = id;
}
else {
Type idType = persister.getIdentifierType();
final Type idType = persister.getIdentifierType();
resultId = (Serializable) idType.nullSafeGet(
rs,
getEntityAliases()[i].getSuffixedKeyAliases(),
session,
null //problematic for <key-many-to-one>!
);
);
final boolean idIsResultId = id != null &&
resultId != null &&
idType.isEqual( id, resultId, factory );
if ( idIsResultId ) resultId = id; //use the id passed in
if ( idIsResultId ) {
resultId = id; //use the id passed in
}
}
return resultId == null ? null : session.generateEntityKey( resultId, persister );
@ -1440,19 +1440,18 @@ public abstract class Loader {
final Serializable id,
final Object entity,
final ResultSet rs,
final SessionImplementor session)
throws HibernateException, SQLException {
final SessionImplementor session) throws HibernateException, SQLException {
Object version = session.getPersistenceContext().getEntry( entity ).getVersion();
if ( version != null ) { //null version means the object is in the process of being loaded somewhere else in the ResultSet
VersionType versionType = persister.getVersionType();
Object currentVersion = versionType.nullSafeGet(
final VersionType versionType = persister.getVersionType();
final Object currentVersion = versionType.nullSafeGet(
rs,
getEntityAliases()[i].getSuffixedVersionAliases(),
session,
null
);
);
if ( !versionType.isEqual(version, currentVersion) ) {
if ( session.getFactory().getStatistics().isStatisticsEnabled() ) {
session.getFactory().getStatisticsImplementor()
@ -1479,13 +1478,13 @@ public abstract class Loader {
final EntityKey optionalObjectKey,
final LockMode[] lockModes,
final List hydratedObjects,
final SessionImplementor session)
throws HibernateException, SQLException {
final SessionImplementor session) throws HibernateException, SQLException {
final int cols = persisters.length;
final EntityAliases[] descriptors = getEntityAliases();
if ( LOG.isDebugEnabled() ) LOG.debugf( "Result row: %s", StringHelper.toString( keys ) );
if ( LOG.isDebugEnabled() ) {
LOG.debugf( "Result row: %s", StringHelper.toString( keys ) );
}
final Object[] rowResults = new Object[cols];
@ -1498,7 +1497,6 @@ public abstract class Loader {
//do nothing
}
else {
//If the object is already loaded, return the loaded one
object = session.getEntityUsingInterceptor( key );
if ( object != null ) {
@ -1511,7 +1509,7 @@ public abstract class Loader {
object,
lockModes[i],
session
);
);
}
else {
object = instanceNotYetLoaded(
@ -1525,9 +1523,8 @@ public abstract class Loader {
optionalObject,
hydratedObjects,
session
);
);
}
}
rowResults[i] = object;
@ -1637,7 +1634,7 @@ public abstract class Loader {
acquiredLockMode,
persister,
session
);
);
//materialize associations (and initialize the object) later
hydratedObjects.add( object );
@ -1665,16 +1662,16 @@ public abstract class Loader {
final String rowIdAlias,
final LockMode lockMode,
final Loadable rootPersister,
final SessionImplementor session)
throws SQLException, HibernateException {
final SessionImplementor session) throws SQLException, HibernateException {
final Serializable id = key.getIdentifier();
// Get the persister for the _subclass_
final Loadable persister = (Loadable) getFactory().getEntityPersister( instanceEntityName );
if ( LOG.isTraceEnabled() )
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Initializing object from ResultSet: {0}", MessageHelper.infoString( persister, id, getFactory() ) );
}
boolean eagerPropertyFetch = isEagerPropertyFetchEnabled(i);
@ -1688,7 +1685,7 @@ public abstract class Loader {
lockMode,
!eagerPropertyFetch,
session
);
);
//This is not very nice (and quite slow):
final String[][] cols = persister == rootPersister ?
@ -1703,7 +1700,7 @@ public abstract class Loader {
cols,
eagerPropertyFetch,
session
);
);
final Object rowId = persister.hasRowId() ? rs.getObject(rowIdAlias) : null;
@ -1752,18 +1749,17 @@ public abstract class Loader {
final int i,
final Loadable persister,
final Serializable id,
final SessionImplementor session)
throws HibernateException, SQLException {
final SessionImplementor session) throws HibernateException, SQLException {
if ( persister.hasSubclasses() ) {
// Code to handle subclasses of topClass
Object discriminatorValue = persister.getDiscriminatorType().nullSafeGet(
final Object discriminatorValue = persister.getDiscriminatorType().nullSafeGet(
rs,
getEntityAliases()[i].getSuffixedDiscriminatorAlias(),
session,
null
);
);
final String result = persister.getSubclassForDiscriminatorValue( discriminatorValue );
@ -1787,18 +1783,19 @@ public abstract class Loader {
/**
* Advance the cursor to the first required row of the <tt>ResultSet</tt>
*/
private void advance(final ResultSet rs, final RowSelection selection)
throws SQLException {
private void advance(final ResultSet rs, final RowSelection selection) throws SQLException {
final int firstRow = LimitHelper.getFirstRow( selection );
if ( firstRow != 0 ) {
if ( getFactory().getSettings().isScrollableResultSetsEnabled() ) {
if ( getFactory().getSessionFactoryOptions().isScrollableResultSetsEnabled() ) {
// we can go straight to the first required row
rs.absolute( firstRow );
}
else {
// we need to step through the rows one row at a time (slow)
for ( int m = 0; m < firstRow; m++ ) rs.next();
for ( int m = 0; m < firstRow; m++ ) {
rs.next();
}
}
}
}
@ -1876,10 +1873,10 @@ public abstract class Loader {
final SessionImplementor session) throws SQLException, HibernateException {
final Dialect dialect = getFactory().getDialect();
final RowSelection selection = queryParameters.getRowSelection();
boolean useLimit = LimitHelper.useLimit( limitHandler, selection );
boolean hasFirstRow = LimitHelper.hasFirstRow( selection );
boolean useLimitOffset = hasFirstRow && useLimit && limitHandler.supportsLimitOffset();
boolean callable = queryParameters.isCallable();
final boolean useLimit = LimitHelper.useLimit( limitHandler, selection );
final boolean hasFirstRow = LimitHelper.hasFirstRow( selection );
final boolean useLimitOffset = hasFirstRow && useLimit && limitHandler.supportsLimitOffset();
final boolean callable = queryParameters.isCallable();
final ScrollMode scrollMode = getScrollMode( scroll, hasFirstRow, useLimitOffset, queryParameters );
PreparedStatement st = session.getJdbcCoordinator().getStatementPreparer().prepareQueryStatement(
@ -2061,9 +2058,7 @@ public abstract class Loader {
final RowSelection selection,
final LimitHandler limitHandler,
final boolean autodiscovertypes,
final SessionImplementor session)
throws SQLException, HibernateException {
final SessionImplementor session) throws SQLException, HibernateException {
try {
ResultSet rs = session.getJdbcCoordinator().getResultSetReturn().extract( st );
rs = wrapResultSetIfEnabled( rs , session );
@ -2124,8 +2119,6 @@ public abstract class Loader {
/**
* Called by subclasses that load entities
* @param persister only needed for logging
* @param lockOptions
*/
protected final List loadEntity(
final SessionImplementor session,
@ -2136,7 +2129,6 @@ public abstract class Loader {
final Serializable optionalIdentifier,
final EntityPersister persister,
LockOptions lockOptions) throws HibernateException {
if ( LOG.isDebugEnabled() ) {
LOG.debugf( "Loading entity: %s", MessageHelper.infoString( persister, id, identifierType, getFactory() ) );
}
@ -2159,7 +2151,7 @@ public abstract class Loader {
"could not load an entity: " +
MessageHelper.infoString( persisters[persisters.length-1], id, identifierType, getFactory() ),
getSQLString()
);
);
}
LOG.debug( "Done entity load" );
@ -2179,7 +2171,6 @@ public abstract class Loader {
final Type keyType,
final Type indexType,
final EntityPersister persister) throws HibernateException {
LOG.debug( "Loading collection element by index" );
List result;
@ -2198,7 +2189,7 @@ public abstract class Loader {
sqle,
"could not load collection element by index",
getSQLString()
);
);
}
LOG.debug( "Done entity load" );
@ -2209,8 +2200,6 @@ public abstract class Loader {
/**
* Called by wrappers that batch load entities
* @param persister only needed for logging
* @param lockOptions
*/
public final List loadEntityBatch(
final SessionImplementor session,
@ -2221,7 +2210,6 @@ public abstract class Loader {
final Serializable optionalId,
final EntityPersister persister,
LockOptions lockOptions) throws HibernateException {
if ( LOG.isDebugEnabled() )
LOG.debugf( "Batch loading entity: %s", MessageHelper.infoString( persister, ids, getFactory() ) );
@ -2244,7 +2232,7 @@ public abstract class Loader {
"could not load an entity batch: " +
MessageHelper.infoString( getEntityPersisters()[0], ids, getFactory() ),
getSQLString()
);
);
}
LOG.debug( "Done entity batch load" );
@ -2260,10 +2248,12 @@ public abstract class Loader {
final SessionImplementor session,
final Serializable id,
final Type type) throws HibernateException {
if ( LOG.isDebugEnabled() )
LOG.debugf( "Loading collection: %s",
MessageHelper.collectionInfoString( getCollectionPersisters()[0], id, getFactory() ) );
if ( LOG.isDebugEnabled() ) {
LOG.debugf(
"Loading collection: %s",
MessageHelper.collectionInfoString( getCollectionPersisters()[0], id, getFactory() )
);
}
Serializable[] ids = new Serializable[]{id};
try {
@ -2271,7 +2261,7 @@ public abstract class Loader {
session,
new QueryParameters( new Type[]{type}, ids, ids ),
true
);
);
}
catch ( SQLException sqle ) {
throw factory.getSQLExceptionHelper().convert(
@ -2279,11 +2269,10 @@ public abstract class Loader {
"could not initialize a collection: " +
MessageHelper.collectionInfoString( getCollectionPersisters()[0], id, getFactory() ),
getSQLString()
);
);
}
LOG.debug( "Done loading collection" );
}
/**
@ -2293,10 +2282,12 @@ public abstract class Loader {
final SessionImplementor session,
final Serializable[] ids,
final Type type) throws HibernateException {
if ( LOG.isDebugEnabled() )
LOG.debugf( "Batch loading collection: %s",
MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ) );
if ( LOG.isDebugEnabled() ) {
LOG.debugf(
"Batch loading collection: %s",
MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() )
);
}
Type[] idTypes = new Type[ids.length];
Arrays.fill( idTypes, type );
@ -2305,7 +2296,7 @@ public abstract class Loader {
session,
new QueryParameters( idTypes, ids, ids ),
true
);
);
}
catch ( SQLException sqle ) {
throw factory.getSQLExceptionHelper().convert(
@ -2313,11 +2304,10 @@ public abstract class Loader {
"could not initialize a collection batch: " +
MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ),
getSQLString()
);
);
}
LOG.debug( "Done batch load" );
}
/**
@ -2330,14 +2320,13 @@ public abstract class Loader {
final Type[] parameterTypes,
final Map<String, TypedValue> namedParameters,
final Type type) throws HibernateException {
Type[] idTypes = new Type[ids.length];
final Type[] idTypes = new Type[ids.length];
Arrays.fill( idTypes, type );
try {
doQueryAndInitializeNonLazyCollections( session,
new QueryParameters( parameterTypes, parameterValues, namedParameters, ids ),
true
);
);
}
catch ( SQLException sqle ) {
throw factory.getSQLExceptionHelper().convert(
@ -2345,7 +2334,7 @@ public abstract class Loader {
"could not load collection by subselect: " +
MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ),
getSQLString()
);
);
}
}
@ -2358,8 +2347,7 @@ public abstract class Loader {
final QueryParameters queryParameters,
final Set<Serializable> querySpaces,
final Type[] resultTypes) throws HibernateException {
final boolean cacheable = factory.getSettings().isQueryCacheEnabled() &&
final boolean cacheable = factory.getSessionFactoryOptions().isQueryCacheEnabled() &&
queryParameters.isCacheable();
if ( cacheable ) {
@ -2384,8 +2372,9 @@ public abstract class Loader {
QueryKey key = generateQueryKey( session, queryParameters );
if ( querySpaces == null || querySpaces.size() == 0 )
if ( querySpaces == null || querySpaces.size() == 0 ) {
LOG.tracev( "Unexpected querySpaces is {0}", ( querySpaces == null ? querySpaces : "empty" ) );
}
else {
LOG.tracev( "querySpaces is {0}", querySpaces );
}
@ -2397,7 +2386,7 @@ public abstract class Loader {
resultTypes,
queryCache,
key
);
);
if ( result == null ) {
result = doList( session, queryParameters, key.getResultTransformer() );
@ -2551,7 +2540,9 @@ public abstract class Loader {
final boolean stats = getFactory().getStatistics().isStatisticsEnabled();
long startTime = 0;
if ( stats ) startTime = System.nanoTime();
if ( stats ) {
startTime = System.nanoTime();
}
List result;
try {
@ -2562,7 +2553,7 @@ public abstract class Loader {
sqle,
"could not execute query",
getSQLString()
);
);
}
if ( stats ) {
@ -2572,7 +2563,7 @@ public abstract class Loader {
getQueryIdentifier(),
result.size(),
milliseconds
);
);
}
return result;
@ -2617,13 +2608,14 @@ public abstract class Loader {
final Type[] returnTypes,
final HolderInstantiator holderInstantiator,
final SessionImplementor session) throws HibernateException {
checkScrollability();
final boolean stats = getQueryIdentifier() != null &&
getFactory().getStatistics().isStatisticsEnabled();
long startTime = 0;
if ( stats ) startTime = System.nanoTime();
if ( stats ) {
startTime = System.nanoTime();
}
try {
// Don't use Collections#emptyList() here -- follow on locking potentially adds AfterLoadActions,
@ -2639,7 +2631,7 @@ public abstract class Loader {
getQueryIdentifier(),
0,
milliseconds
);
);
}
if ( needsFetchingScroll() ) {
@ -2651,7 +2643,7 @@ public abstract class Loader {
queryParameters,
returnTypes,
holderInstantiator
);
);
}
else {
return new ScrollableResultsImpl(
@ -2662,7 +2654,7 @@ public abstract class Loader {
queryParameters,
returnTypes,
holderInstantiator
);
);
}
}
@ -2671,7 +2663,7 @@ public abstract class Loader {
sqle,
"could not execute query using scroll",
getSQLString()
);
);
}
}

View File

@ -163,10 +163,12 @@ public final class OuterJoinableAssociation {
*/
private static int getPosition(String lhsAlias, List associations) {
int result = 0;
for ( int i=0; i<associations.size(); i++ ) {
OuterJoinableAssociation oj = (OuterJoinableAssociation) associations.get(i);
for ( Object association : associations ) {
final OuterJoinableAssociation oj = (OuterJoinableAssociation) association;
if ( oj.getJoinable().consumesEntityAlias() /*|| oj.getJoinable().consumesCollectionAlias() */ ) {
if ( oj.rhsAlias.equals(lhsAlias) ) return result;
if ( oj.rhsAlias.equals( lhsAlias ) ) {
return result;
}
result++;
}
}

View File

@ -37,7 +37,6 @@ import org.hibernate.loader.JoinWalker;
* @author Gavin King
*/
public abstract class CollectionJoinWalker extends JoinWalker {
public CollectionJoinWalker(SessionFactoryImplementor factory, LoadQueryInfluencers loadQueryInfluencers) {
super( factory, loadQueryInfluencers );
}
@ -48,9 +47,13 @@ public abstract class CollectionJoinWalker extends JoinWalker {
}
else {
StringBuilder buf = new StringBuilder();
if (columnNames.length>1) buf.append('(');
if (columnNames.length>1) {
buf.append('(');
}
buf.append( StringHelper.join(", ", StringHelper.qualify(alias, columnNames) ) );
if (columnNames.length>1) buf.append(')');
if (columnNames.length>1) {
buf.append(')');
}
buf.append(" in ")
.append('(')
.append(subselect)

View File

@ -190,9 +190,12 @@ public class DynamicBatchingCollectionInitializerBuilder extends BatchingCollect
final Serializable[] ids,
final Type type) throws HibernateException {
if ( LOG.isDebugEnabled() )
LOG.debugf( "Batch loading collection: %s",
MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() ) );
if ( LOG.isDebugEnabled() ) {
LOG.debugf(
"Batch loading collection: %s",
MessageHelper.collectionInfoString( getCollectionPersisters()[0], ids, getFactory() )
);
}
final Type[] idTypes = new Type[ids.length];
Arrays.fill( idTypes, type );

View File

@ -74,7 +74,7 @@ public abstract class AbstractLoadPlanBasedCollectionInitializer
);
final LoadPlan plan = MetamodelDrivenLoadPlanBuilder.buildRootCollectionLoadPlan( strategy, collectionPersister );
this.staticLoadQuery = BatchingLoadQueryDetailsFactory.makeCollectionLoadQueryDetails(
this.staticLoadQuery = BatchingLoadQueryDetailsFactory.INSTANCE.makeCollectionLoadQueryDetails(
collectionPersister,
plan,
buildingParameters

View File

@ -184,7 +184,9 @@ public class CriteriaLoader extends OuterJoinLoader {
Object[] result = new Object[ resultRowLength ];
int j = 0;
for ( int i = 0; i < row.length; i++ ) {
if ( includeInResultRow[i] ) result[j++] = row[i];
if ( includeInResultRow[i] ) {
result[j++] = row[i];
}
}
return result;
}

View File

@ -62,7 +62,6 @@ public abstract class BatchingEntityLoader implements UniqueEntityLoader {
}
@Override
@Deprecated
public Object load(Serializable id, Object optionalObject, SessionImplementor session) {
return load( id, optionalObject, session, LockOptions.NONE );
}

View File

@ -97,7 +97,7 @@ public abstract class AbstractLoadPlanBasedEntityLoader extends AbstractLoadPlan
}
final LoadPlan plan = MetamodelDrivenLoadPlanBuilder.buildRootEntityLoadPlan( strategy, entityPersister );
this.staticLoadQuery = BatchingLoadQueryDetailsFactory.makeEntityLoadQueryDetails(
this.staticLoadQuery = BatchingLoadQueryDetailsFactory.INSTANCE.makeEntityLoadQueryDetails(
plan,
uniqueKeyColumnNames,
buildingParameters,
@ -165,7 +165,6 @@ public abstract class AbstractLoadPlanBasedEntityLoader extends AbstractLoadPlan
}
@Override
@Deprecated
public Object load(Serializable id, Object optionalObject, SessionImplementor session) throws HibernateException {
return load( id, optionalObject, session, LockOptions.NONE );
}

View File

@ -65,7 +65,6 @@ public abstract class BatchingEntityLoader implements UniqueEntityLoader {
}
@Override
@Deprecated
public Object load(Serializable id, Object optionalObject, SessionImplementor session) {
return load( id, optionalObject, session, LockOptions.NONE );
}

View File

@ -36,9 +36,14 @@ import org.hibernate.persister.entity.Queryable;
* A factory class for creating a {@link org.hibernate.loader.plan.exec.spi.LoadQueryDetails} object.
*/
public class BatchingLoadQueryDetailsFactory {
public final BatchingLoadQueryDetailsFactory INSTANCE = new BatchingLoadQueryDetailsFactory();
/**
* Singleton access
*/
public static final BatchingLoadQueryDetailsFactory INSTANCE = new BatchingLoadQueryDetailsFactory();
// protect against external instantiation.
/**
* Private to disallow instantiation
*/
private BatchingLoadQueryDetailsFactory() {
}
@ -53,7 +58,7 @@ public class BatchingLoadQueryDetailsFactory {
*
* @return The EntityLoadQueryDetails
*/
public static LoadQueryDetails makeEntityLoadQueryDetails(
public LoadQueryDetails makeEntityLoadQueryDetails(
LoadPlan loadPlan,
String[] keyColumnNames,
QueryBuildingParameters buildingParameters,
@ -90,7 +95,7 @@ public class BatchingLoadQueryDetailsFactory {
*
* @return The EntityLoadQueryDetails
*/
public static LoadQueryDetails makeCollectionLoadQueryDetails(
public LoadQueryDetails makeCollectionLoadQueryDetails(
CollectionPersister collectionPersister,
LoadPlan loadPlan,
QueryBuildingParameters buildingParameters) {

View File

@ -20,9 +20,9 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.lob;
import java.io.IOException;
import java.io.Reader;
@ -31,6 +31,7 @@ import java.io.Reader;
*
* @deprecated Should not be used anymore.
*/
@Deprecated
public class ReaderInputStream extends org.hibernate.engine.jdbc.ReaderInputStream {
public ReaderInputStream(Reader reader) {

View File

@ -177,9 +177,14 @@ public class Column implements Selectable, Serializable, Cloneable {
return object instanceof Column && equals( (Column) object );
}
@SuppressWarnings("SimplifiableIfStatement")
public boolean equals(Column column) {
if (null == column) return false;
if (this == column) return true;
if (null == column) {
return false;
}
if (this == column) {
return true;
}
return isQuoted() ?
name.equals(column.name) :

View File

@ -31,6 +31,7 @@ import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import org.hibernate.HibernateException;
import org.hibernate.annotations.common.util.StringHelper;
@ -64,10 +65,6 @@ public abstract class Constraint implements RelationalModel, Exportable, Seriali
* Static so the name can be generated prior to creating the Constraint.
* They're cached, keyed by name, in multiple locations.
*
* @param prefix
* Appended to the beginning of the generated name
* @param table
* @param columns
* @return String The generated name
*/
public static String generateName(String prefix, Table table, Column... columns) {
@ -84,7 +81,7 @@ public abstract class Constraint implements RelationalModel, Exportable, Seriali
Arrays.sort( alphabeticalColumns, ColumnComparator.INSTANCE );
for ( Column column : alphabeticalColumns ) {
String columnName = column == null ? "" : column.getName();
sb.append( "column`" + columnName + "`" );
sb.append( "column`" ).append( columnName ).append( "`" );
}
return prefix + hashedName( sb.toString() );
}
@ -92,10 +89,6 @@ public abstract class Constraint implements RelationalModel, Exportable, Seriali
/**
* Helper method for {@link #generateName(String, Table, Column...)}.
*
* @param prefix
* Appended to the beginning of the generated name
* @param table
* @param columns
* @return String The generated name
*/
public static String generateName(String prefix, Table table, List<Column> columns) {
@ -138,18 +131,21 @@ public abstract class Constraint implements RelationalModel, Exportable, Seriali
}
public void addColumn(Column column) {
if ( !columns.contains( column ) ) columns.add( column );
if ( !columns.contains( column ) ) {
columns.add( column );
}
}
public void addColumns(Iterator columnIterator) {
while ( columnIterator.hasNext() ) {
Selectable col = (Selectable) columnIterator.next();
if ( !col.isFormula() ) addColumn( (Column) col );
if ( !col.isFormula() ) {
addColumn( (Column) col );
}
}
}
/**
* @param column
* @return true if this constraint already contains a column with same name.
*/
public boolean containsColumn(Column column) {
@ -186,12 +182,12 @@ public abstract class Constraint implements RelationalModel, Exportable, Seriali
public String sqlDropString(Dialect dialect, String defaultCatalog, String defaultSchema) {
if ( isGenerated( dialect ) ) {
return new StringBuilder()
.append( "alter table " )
.append( getTable().getQualifiedName( dialect, defaultCatalog, defaultSchema ) )
.append( " drop constraint " )
.append( dialect.quote( getName() ) )
.toString();
return String.format(
Locale.ROOT,
"alter table %s drop constraint %s",
getTable().getQualifiedName( dialect, defaultCatalog, defaultSchema ),
dialect.quote( getName() )
);
}
else {
return null;
@ -205,10 +201,8 @@ public abstract class Constraint implements RelationalModel, Exportable, Seriali
// empty string. Prevent blank "alter table" statements.
String constraintString = sqlConstraintString( dialect, getName(), defaultCatalog, defaultSchema );
if ( !StringHelper.isEmpty( constraintString ) ) {
StringBuilder buf = new StringBuilder( "alter table " )
.append( getTable().getQualifiedName( dialect, defaultCatalog, defaultSchema ) )
.append( constraintString );
return buf.toString();
return "alter table " + getTable().getQualifiedName( dialect, defaultCatalog, defaultSchema )
+ constraintString;
}
}
return null;
@ -218,8 +212,11 @@ public abstract class Constraint implements RelationalModel, Exportable, Seriali
return columns;
}
public abstract String sqlConstraintString(Dialect d, String constraintName, String defaultCatalog,
String defaultSchema);
public abstract String sqlConstraintString(
Dialect d,
String constraintName,
String defaultCatalog,
String defaultSchema);
public String toString() {
return getClass().getName() + '(' + getTable().getName() + getColumns() + ") as " + name;

View File

@ -35,11 +35,10 @@ import org.hibernate.internal.util.StringHelper;
* @author Gavin King
*/
public class ForeignKey extends Constraint {
private Table referencedTable;
private String referencedEntityName;
private boolean cascadeDeleteEnabled;
private List referencedColumns = new ArrayList();
private List<Column> referencedColumns = new ArrayList<Column>();
private boolean creationEnabled = true;
public ForeignKey() {
@ -73,7 +72,7 @@ public class ForeignKey extends Constraint {
String[] columnNames = new String[ getColumnSpan() ];
String[] referencedColumnNames = new String[ getColumnSpan() ];
final Iterator referencedColumnItr;
final Iterator<Column> referencedColumnItr;
if ( isReferenceToPrimaryKey() ) {
referencedColumnItr = referencedTable.getPrimaryKey().getColumnIterator();
}
@ -85,7 +84,7 @@ public class ForeignKey extends Constraint {
int i=0;
while ( columnItr.hasNext() ) {
columnNames[i] = ( (Column) columnItr.next() ).getQuotedName(dialect);
referencedColumnNames[i] = ( (Column) referencedColumnItr.next() ).getQuotedName(dialect);
referencedColumnNames[i] = referencedColumnItr.next().getQuotedName(dialect);
i++;
}
@ -109,7 +108,9 @@ public class ForeignKey extends Constraint {
while( columns.hasNext() ) {
Column column = (Column) columns.next();
buf.append( column.getName() );
if ( columns.hasNext() ) buf.append(",");
if ( columns.hasNext() ) {
buf.append(",");
}
}
}
@ -125,7 +126,9 @@ public class ForeignKey extends Constraint {
* Furthermore it aligns the length of the underlying tables columns.
*/
public void alignColumns() {
if ( isReferenceToPrimaryKey() ) alignColumns(referencedTable);
if ( isReferenceToPrimaryKey() ) {
alignColumns(referencedTable);
}
}
private void alignColumns(Table referencedTable) {
@ -133,13 +136,13 @@ public class ForeignKey extends Constraint {
if ( referencedPkColumnSpan != getColumnSpan() ) {
StringBuilder sb = new StringBuilder();
sb.append( "Foreign key (" ).append( getName() ).append( ":" )
.append( getTable().getName() )
.append(" [");
.append( getTable().getName() )
.append( " [" );
appendColumns( sb, getColumnIterator() );
sb.append("])")
.append(") must have same number of columns as the referenced primary key (")
.append( referencedTable.getName() )
.append(" [");
.append( ") must have same number of columns as the referenced primary key (" )
.append( referencedTable.getName() )
.append( " [" );
appendColumns( sb, referencedTable.getPrimaryKey().getColumnIterator() );
sb.append("])");
throw new MappingException( sb.toString() );
@ -214,10 +217,9 @@ public class ForeignKey extends Constraint {
public String toString() {
if(!isReferenceToPrimaryKey() ) {
StringBuilder result = new StringBuilder(getClass().getName() + '(' + getTable().getName() + getColumns() );
result.append( " ref-columns:" + '(' + getReferencedColumns() );
result.append( ") as " + getName() );
return result.toString();
return getClass().getName()
+ '(' + getTable().getName() + getColumns()
+ " ref-columns:" + '(' + getReferencedColumns() + ") as " + getName() + ")";
}
else {
return super.toString();

View File

@ -116,7 +116,9 @@ public class Index implements RelationalModel, Exportable, Serializable {
if ( columnOrderMap.containsKey( column ) ) {
buf.append( " " ).append( columnOrderMap.get( column ) );
}
if ( columns.hasNext() ) buf.append( ", " );
if ( columns.hasNext() ) {
buf.append( ", " );
}
}
buf.append( ")" );
return buf.toString();
@ -204,7 +206,9 @@ public class Index implements RelationalModel, Exportable, Serializable {
}
public void addColumn(Column column) {
if ( !columns.contains( column ) ) columns.add( column );
if ( !columns.contains( column ) ) {
columns.add( column );
}
}
public void addColumn(Column column, String order) {

View File

@ -64,7 +64,9 @@ public abstract class IndexedCollection extends Collection {
boolean isFormula = false;
Iterator iter = getIndex().getColumnIterator();
while ( iter.hasNext() ) {
if ( ( (Selectable) iter.next() ).isFormula() ) isFormula=true;
if ( ( (Selectable) iter.next() ).isFormula() ) {
isFormula=true;
}
}
if (isFormula) {
//if it is a formula index, use the element columns in the PK

View File

@ -197,7 +197,9 @@ public class Join implements AttributeContainer, Serializable {
Iterator iter = getPropertyIterator();
while ( iter.hasNext() ) {
Property prop = (Property) iter.next();
if ( !prop.isLazy() ) return false;
if ( !prop.isLazy() ) {
return false;
}
}
return true;
}

View File

@ -103,7 +103,9 @@ public class OneToOne extends ToOne {
public java.util.List getConstraintColumns() {
ArrayList list = new ArrayList();
Iterator iter = identifier.getColumnIterator();
while ( iter.hasNext() ) list.add( iter.next() );
while ( iter.hasNext() ) {
list.add( iter.next() );
}
return list;
}
/**

View File

@ -72,7 +72,7 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl
private boolean lazy;
private ArrayList properties = new ArrayList();
private ArrayList declaredProperties = new ArrayList();
private final ArrayList subclasses = new ArrayList();
private final ArrayList<Subclass> subclasses = new ArrayList<Subclass>();
private final ArrayList subclassProperties = new ArrayList();
private final ArrayList subclassTables = new ArrayList();
private boolean dynamicInsert;
@ -80,7 +80,7 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl
private int batchSize=-1;
private boolean selectBeforeUpdate;
private java.util.Map metaAttributes;
private ArrayList joins = new ArrayList();
private ArrayList<Join> joins = new ArrayList<Join>();
private final ArrayList subclassJoins = new ArrayList();
private final java.util.List filters = new ArrayList();
protected final java.util.Set synchronizedTables = new HashSet();
@ -125,9 +125,11 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl
}
public Class getMappedClass() throws MappingException {
if (className==null) return null;
if (className==null) {
return null;
}
try {
if(mappedClass == null) {
if (mappedClass == null) {
mappedClass = ReflectHelper.classForName(className);
}
return mappedClass;
@ -138,9 +140,11 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl
}
public Class getProxyInterface() {
if (proxyInterfaceName==null) return null;
if (proxyInterfaceName==null) {
return null;
}
try {
if(proxyInterface == null) {
if (proxyInterface == null) {
proxyInterface = ReflectHelper.classForName( proxyInterfaceName );
}
return proxyInterface;
@ -149,6 +153,7 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl
throw new MappingException("proxy class not found: " + proxyInterfaceName, cnfe);
}
}
public boolean useDynamicInsert() {
return dynamicInsert;
}
@ -177,7 +182,7 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl
// inheritance cycle detection (paranoid check)
PersistentClass superclass = getSuperclass();
while (superclass!=null) {
if( subclass.getEntityName().equals( superclass.getEntityName() ) ) {
if ( subclass.getEntityName().equals( superclass.getEntityName() ) ) {
throw new MappingException(
"Circular inheritance mapping detected: " +
subclass.getEntityName() +
@ -461,8 +466,7 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl
Iterator iter = getPropertyClosureIterator();
Property identifierProperty = getIdentifierProperty();
if ( identifierProperty != null
&& identifierProperty.getName().equals( StringHelper.root(propertyName) )
) {
&& identifierProperty.getName().equals( StringHelper.root(propertyName) ) ) {
return identifierProperty;
}
else {
@ -470,11 +474,17 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl
}
}
/**
* @deprecated prefer {@link #getOptimisticLockStyle}
*/
@Deprecated
public int getOptimisticLockMode() {
return getOptimisticLockStyle().getOldCode();
}
/**
* @deprecated prefer {@link #setOptimisticLockStyle}
*/
@Deprecated
public void setOptimisticLockMode(int optimisticLockMode) {
setOptimisticLockStyle( OptimisticLockStyle.interpretOldCode( optimisticLockMode ) );
@ -498,7 +508,7 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl
StringHelper.qualify( getEntityName(), prop.getName() ) +
" type: " +
prop.getType().getName()
);
);
}
}
checkPropertyDuplication();
@ -506,7 +516,7 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl
}
private void checkPropertyDuplication() throws MappingException {
HashSet names = new HashSet();
HashSet<String> names = new HashSet<String>();
Iterator iter = getPropertyIterator();
while ( iter.hasNext() ) {
Property prop = (Property) iter.next();
@ -561,8 +571,7 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl
public int getPropertyClosureSpan() {
int span = properties.size();
for ( int i=0; i<joins.size(); i++ ) {
Join join = (Join) joins.get(i);
for ( Join join : joins ) {
span += join.getPropertySpan();
}
return span;
@ -573,7 +582,9 @@ public abstract class PersistentClass implements AttributeContainer, Serializabl
Iterator iter = getSubclassJoinClosureIterator();
while ( iter.hasNext() ) {
Join join = (Join) iter.next();
if ( join.containsProperty(prop) ) return result;
if ( join.containsProperty(prop) ) {
return result;
}
result++;
}
return 0;

View File

@ -38,7 +38,9 @@ public class PrimaryKey extends Constraint {
Iterator iter = getColumnIterator();
while ( iter.hasNext() ) {
buf.append( ( (Column) iter.next() ).getQuotedName(dialect) );
if ( iter.hasNext() ) buf.append(", ");
if ( iter.hasNext() ) {
buf.append(", ");
}
}
return buf.append(')').toString();
}
@ -50,7 +52,9 @@ public class PrimaryKey extends Constraint {
Iterator iter = getColumnIterator();
while ( iter.hasNext() ) {
buf.append( ( (Column) iter.next() ).getQuotedName(dialect) );
if ( iter.hasNext() ) buf.append(", ");
if ( iter.hasNext() ) {
buf.append(", ");
}
}
return buf.append(')').toString();
}

View File

@ -346,12 +346,15 @@ public class RootClass extends PersistentClass implements TableOwner {
return synchronizedTables;
}
public Set getIdentityTables() {
Set tables = new HashSet();
@SuppressWarnings("UnnecessaryUnboxing")
public Set<Table> getIdentityTables() {
Set<Table> tables = new HashSet<Table>();
Iterator iter = getSubclassClosureIterator();
while ( iter.hasNext() ) {
PersistentClass clazz = (PersistentClass) iter.next();
if ( clazz.isAbstract() == null || !clazz.isAbstract().booleanValue() ) tables.add( clazz.getIdentityTable() );
if ( clazz.isAbstract() == null || !clazz.isAbstract().booleanValue() ) {
tables.add( clazz.getIdentityTable() );
}
}
return tables;
}

View File

@ -110,7 +110,9 @@ public class SimpleValue implements KeyValue {
}
public void addColumn(Column column) {
if ( !columns.contains(column) ) columns.add(column);
if ( !columns.contains(column) ) {
columns.add(column);
}
column.setValue(this);
column.setTypeIndex( columns.size()-1 );
}
@ -124,7 +126,9 @@ public class SimpleValue implements KeyValue {
Iterator iter = getColumnIterator();
while ( iter.hasNext() ) {
Object o = iter.next();
if (o instanceof Formula) return true;
if (o instanceof Formula) {
return true;
}
}
return false;
}

View File

@ -46,88 +46,88 @@ public interface ClassMetadata {
/**
* The name of the entity
*/
public String getEntityName();
String getEntityName();
/**
* Get the name of the identifier property (or return null)
*/
public String getIdentifierPropertyName();
String getIdentifierPropertyName();
/**
* Get the names of the class' persistent properties
*/
public String[] getPropertyNames();
String[] getPropertyNames();
/**
* Get the identifier Hibernate type
*/
public Type getIdentifierType();
Type getIdentifierType();
/**
* Get the Hibernate types of the class properties
*/
public Type[] getPropertyTypes();
Type[] getPropertyTypes();
/**
* Get the type of a particular (named) property
*/
public Type getPropertyType(String propertyName) throws HibernateException;
Type getPropertyType(String propertyName) throws HibernateException;
/**
* Does this class support dynamic proxies?
*/
public boolean hasProxy();
boolean hasProxy();
/**
* Are instances of this class mutable?
*/
public boolean isMutable();
boolean isMutable();
/**
* Are instances of this class versioned by a timestamp or version number column?
*/
public boolean isVersioned();
boolean isVersioned();
/**
* Get the index of the version property
*/
public int getVersionProperty();
int getVersionProperty();
/**
* Get the nullability of the class' persistent properties
*/
public boolean[] getPropertyNullability();
boolean[] getPropertyNullability();
/**
* Get the "laziness" of the properties of this class
*/
public boolean[] getPropertyLaziness();
boolean[] getPropertyLaziness();
/**
* Does this class have an identifier property?
*/
public boolean hasIdentifierProperty();
boolean hasIdentifierProperty();
/**
* Does this entity declare a natural id?
*/
public boolean hasNaturalIdentifier();
boolean hasNaturalIdentifier();
/**
* Which properties hold the natural id?
*/
public int[] getNaturalIdentifierProperties();
int[] getNaturalIdentifierProperties();
/**
* Does this entity have mapped subclasses?
*/
public boolean hasSubclasses();
boolean hasSubclasses();
/**
* Does this entity extend a mapped superclass?
*/
public boolean isInherited();
boolean isInherited();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// stuff that is tuplizer-centric, but is passed a session ~~~~~~~~~~~~~~~~
@ -137,7 +137,7 @@ public interface ClassMetadata {
* Return the values of the mapped properties of the object
*/
@SuppressWarnings( {"UnusedDeclaration"})
public Object[] getPropertyValuesToInsert(Object entity, Map mergeMap, SessionImplementor session)
Object[] getPropertyValuesToInsert(Object entity, Map mergeMap, SessionImplementor session)
throws HibernateException;
@ -148,7 +148,7 @@ public interface ClassMetadata {
/**
* The persistent class, or null
*/
public Class getMappedClass();
Class getMappedClass();
/**
* Create a class instance initialized with the given identifier
@ -158,12 +158,12 @@ public interface ClassMetadata {
*
* @return The instantiated entity.
*/
public Object instantiate(Serializable id, SessionImplementor session);
Object instantiate(Serializable id, SessionImplementor session);
/**
* Get the value of a particular (named) property
*/
public Object getPropertyValue(Object object, String propertyName) throws HibernateException;
Object getPropertyValue(Object object, String propertyName) throws HibernateException;
/**
* Extract the property values from the given entity.
@ -172,25 +172,26 @@ public interface ClassMetadata {
* @return The property values.
* @throws HibernateException
*/
public Object[] getPropertyValues(Object entity) throws HibernateException;
Object[] getPropertyValues(Object entity) throws HibernateException;
/**
* Set the value of a particular (named) property
*/
public void setPropertyValue(Object object, String propertyName, Object value) throws HibernateException;
void setPropertyValue(Object object, String propertyName, Object value) throws HibernateException;
/**
* Set the given values to the mapped properties of the given object
*/
public void setPropertyValues(Object object, Object[] values) throws HibernateException;
void setPropertyValues(Object object, Object[] values) throws HibernateException;
/**
* Get the identifier of an instance (throw an exception if no identifier property)
*
* @deprecated Use {@link #getIdentifier(Object,SessionImplementor)} instead
*/
@Deprecated
@SuppressWarnings( {"JavaDoc"})
public Serializable getIdentifier(Object object) throws HibernateException;
Serializable getIdentifier(Object object) throws HibernateException;
/**
* Get the identifier of an instance (throw an exception if no identifier property)
@ -200,7 +201,7 @@ public interface ClassMetadata {
*
* @return The identifier
*/
public Serializable getIdentifier(Object entity, SessionImplementor session);
Serializable getIdentifier(Object entity, SessionImplementor session);
/**
* Inject the identifier value into the given entity.
@ -209,19 +210,19 @@ public interface ClassMetadata {
* @param id The value to be injected as the identifier.
* @param session The session from which is requests originates
*/
public void setIdentifier(Object entity, Serializable id, SessionImplementor session);
void setIdentifier(Object entity, Serializable id, SessionImplementor session);
/**
* Does the class implement the <tt>Lifecycle</tt> interface?
*/
@SuppressWarnings( {"UnusedDeclaration"})
public boolean implementsLifecycle();
boolean implementsLifecycle();
/**
* Get the version number (or timestamp) from the object's version property
* (or return null if not versioned)
*/
public Object getVersion(Object object) throws HibernateException;
Object getVersion(Object object) throws HibernateException;
}

View File

@ -680,10 +680,18 @@ public abstract class AbstractCollectionPersister
protected void logStaticSQL() {
if ( LOG.isDebugEnabled() ) {
LOG.debugf( "Static SQL for collection: %s", getRole() );
if ( getSQLInsertRowString() != null ) LOG.debugf( " Row insert: %s", getSQLInsertRowString() );
if ( getSQLUpdateRowString() != null ) LOG.debugf( " Row update: %s", getSQLUpdateRowString() );
if ( getSQLDeleteRowString() != null ) LOG.debugf( " Row delete: %s", getSQLDeleteRowString() );
if ( getSQLDeleteString() != null ) LOG.debugf( " One-shot delete: %s", getSQLDeleteString() );
if ( getSQLInsertRowString() != null ) {
LOG.debugf( " Row insert: %s", getSQLInsertRowString() );
}
if ( getSQLUpdateRowString() != null ) {
LOG.debugf( " Row update: %s", getSQLUpdateRowString() );
}
if ( getSQLDeleteRowString() != null ) {
LOG.debugf( " Row delete: %s", getSQLDeleteRowString() );
}
if ( getSQLDeleteString() != null ) {
LOG.debugf( " One-shot delete: %s", getSQLDeleteString() );
}
}
}

View File

@ -80,14 +80,15 @@ public class BasicCollectionPersister extends AbstractCollectionPersister {
*/
@Override
protected String generateDeleteString() {
Delete delete = new Delete()
final Delete delete = new Delete()
.setTableName( qualifiedTableName )
.addPrimaryKeyColumns( keyColumnNames );
if ( hasWhere ) delete.setWhere( sqlWhereString );
if ( hasWhere ) {
delete.setWhere( sqlWhereString );
}
if ( getFactory().getSettings().isCommentsEnabled() ) {
if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
delete.setComment( "delete collection " + getRole() );
}
@ -99,18 +100,19 @@ public class BasicCollectionPersister extends AbstractCollectionPersister {
*/
@Override
protected String generateInsertRowString() {
Insert insert = new Insert( getDialect() )
final Insert insert = new Insert( getDialect() )
.setTableName( qualifiedTableName )
.addColumns( keyColumnNames );
if ( hasIdentifier) insert.addColumn( identifierColumnName );
if ( hasIdentifier) {
insert.addColumn( identifierColumnName );
}
if ( hasIndex /*&& !indexIsFormula*/ ) {
insert.addColumns( indexColumnNames, indexColumnIsSettable );
}
if ( getFactory().getSettings().isCommentsEnabled() ) {
if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
insert.setComment( "insert collection row " + getRole() );
}
@ -126,8 +128,7 @@ public class BasicCollectionPersister extends AbstractCollectionPersister {
*/
@Override
protected String generateUpdateRowString() {
Update update = new Update( getDialect() )
final Update update = new Update( getDialect() )
.setTableName( qualifiedTableName );
//if ( !elementIsFormula ) {
@ -145,7 +146,7 @@ public class BasicCollectionPersister extends AbstractCollectionPersister {
update.addPrimaryKeyColumns( elementColumnNames, elementColumnIsInPrimaryKey, elementColumnWriters );
}
if ( getFactory().getSettings().isCommentsEnabled() ) {
if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
update.setComment( "update collection row " + getRole() );
}
@ -163,9 +164,7 @@ public class BasicCollectionPersister extends AbstractCollectionPersister {
*/
@Override
protected String generateDeleteRowString() {
Delete delete = new Delete()
.setTableName( qualifiedTableName );
final Delete delete = new Delete().setTableName( qualifiedTableName );
if ( hasIdentifier ) {
delete.addPrimaryKeyColumns( new String[]{ identifierColumnName } );
@ -178,7 +177,7 @@ public class BasicCollectionPersister extends AbstractCollectionPersister {
delete.addPrimaryKeyColumns( elementColumnNames, elementColumnIsInPrimaryKey, elementColumnWriters );
}
if ( getFactory().getSettings().isCommentsEnabled() ) {
if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
delete.setComment( "delete collection row " + getRole() );
}
@ -206,10 +205,10 @@ public class BasicCollectionPersister extends AbstractCollectionPersister {
private BasicBatchKey updateBatchKey;
@Override
protected int doUpdateRows(Serializable id, PersistentCollection collection, SessionImplementor session)
throws HibernateException {
if ( ArrayHelper.isAllFalse(elementColumnIsSettable) ) return 0;
protected int doUpdateRows(Serializable id, PersistentCollection collection, SessionImplementor session) throws HibernateException {
if ( ArrayHelper.isAllFalse(elementColumnIsSettable) ) {
return 0;
}
try {
PreparedStatement st = null;
@ -261,8 +260,7 @@ public class BasicCollectionPersister extends AbstractCollectionPersister {
}
if ( useBatch ) {
session
.getJdbcCoordinator()
session.getJdbcCoordinator()
.getBatch( updateBatchKey )
.addToBatch();
}
@ -293,7 +291,7 @@ public class BasicCollectionPersister extends AbstractCollectionPersister {
sqle,
"could not update collection rows: " + MessageHelper.collectionInfoString( this, collection, id, session ),
getSQLUpdateRowString()
);
);
}
}

View File

@ -32,7 +32,6 @@ import org.hibernate.type.Type;
* @author Gavin King
*/
public class CollectionPropertyMapping implements PropertyMapping {
private final QueryableCollection memberPersister;
public CollectionPropertyMapping(QueryableCollection memberPersister) {
@ -73,7 +72,9 @@ public class CollectionPropertyMapping implements PropertyMapping {
return memberPersister.getElementColumnNames(alias);
}
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_INDICES) ) {
if ( !memberPersister.hasIndex() ) throw new QueryException("unindexed collection in indices()");
if ( !memberPersister.hasIndex() ) {
throw new QueryException("unindexed collection in indices()");
}
return memberPersister.getIndexColumnNames(alias);
}
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_SIZE) ) {
@ -81,25 +82,37 @@ public class CollectionPropertyMapping implements PropertyMapping {
return new String[] { "count(" + alias + '.' + cols[0] + ')' };
}
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MAX_INDEX) ) {
if ( !memberPersister.hasIndex() ) throw new QueryException("unindexed collection in maxIndex()");
if ( !memberPersister.hasIndex() ) {
throw new QueryException("unindexed collection in maxIndex()");
}
String[] cols = memberPersister.getIndexColumnNames(alias);
if ( cols.length!=1 ) throw new QueryException("composite collection index in maxIndex()");
if ( cols.length!=1 ) {
throw new QueryException("composite collection index in maxIndex()");
}
return new String[] { "max(" + cols[0] + ')' };
}
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MIN_INDEX) ) {
if ( !memberPersister.hasIndex() ) throw new QueryException("unindexed collection in minIndex()");
if ( !memberPersister.hasIndex() ) {
throw new QueryException("unindexed collection in minIndex()");
}
String[] cols = memberPersister.getIndexColumnNames(alias);
if ( cols.length!=1 ) throw new QueryException("composite collection index in minIndex()");
if ( cols.length!=1 ) {
throw new QueryException("composite collection index in minIndex()");
}
return new String[] { "min(" + cols[0] + ')' };
}
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MAX_ELEMENT) ) {
String[] cols = memberPersister.getElementColumnNames(alias);
if ( cols.length!=1 ) throw new QueryException("composite collection element in maxElement()");
if ( cols.length!=1 ) {
throw new QueryException("composite collection element in maxElement()");
}
return new String[] { "max(" + cols[0] + ')' };
}
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MIN_ELEMENT) ) {
String[] cols = memberPersister.getElementColumnNames(alias);
if ( cols.length!=1 ) throw new QueryException("composite collection element in minElement()");
if ( cols.length!=1 ) {
throw new QueryException("composite collection element in minElement()");
}
return new String[] { "min(" + cols[0] + ')' };
}
else {

View File

@ -96,17 +96,20 @@ public class OneToManyPersister extends AbstractCollectionPersister {
*/
@Override
protected String generateDeleteString() {
Update update = new Update( getDialect() )
final Update update = new Update( getDialect() )
.setTableName( qualifiedTableName )
.addColumns( keyColumnNames, "null" )
.addPrimaryKeyColumns( keyColumnNames );
if ( hasIndex && !indexContainsFormula ) update.addColumns( indexColumnNames, "null" );
if ( hasIndex && !indexContainsFormula ) {
update.addColumns( indexColumnNames, "null" );
}
if ( hasWhere ) update.setWhere( sqlWhereString );
if ( hasWhere ) {
update.setWhere( sqlWhereString );
}
if ( getFactory().getSettings().isCommentsEnabled() ) {
if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
update.setComment( "delete one-to-many " + getRole() );
}
@ -118,15 +121,17 @@ public class OneToManyPersister extends AbstractCollectionPersister {
*/
@Override
protected String generateInsertRowString() {
Update update = new Update( getDialect() )
final Update update = new Update( getDialect() )
.setTableName( qualifiedTableName )
.addColumns( keyColumnNames );
if ( hasIndex && !indexContainsFormula ) update.addColumns( indexColumnNames );
if ( hasIndex && !indexContainsFormula ) {
update.addColumns( indexColumnNames );
}
//identifier collections not supported for 1-to-many
if ( getFactory().getSettings().isCommentsEnabled() ) {
if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
update.setComment( "create one-to-many row " + getRole() );
}
@ -139,7 +144,7 @@ public class OneToManyPersister extends AbstractCollectionPersister {
*/
@Override
protected String generateUpdateRowString() {
Update update = new Update( getDialect() ).setTableName( qualifiedTableName );
final Update update = new Update( getDialect() ).setTableName( qualifiedTableName );
update.addPrimaryKeyColumns( elementColumnNames, elementColumnIsSettable, elementColumnWriters );
if ( hasIdentifier ) {
update.addPrimaryKeyColumns( new String[]{ identifierColumnName } );
@ -157,14 +162,15 @@ public class OneToManyPersister extends AbstractCollectionPersister {
*/
@Override
protected String generateDeleteRowString() {
Update update = new Update( getDialect() )
final Update update = new Update( getDialect() )
.setTableName( qualifiedTableName )
.addColumns( keyColumnNames, "null" );
if ( hasIndex && !indexContainsFormula ) update.addColumns( indexColumnNames, "null" );
if ( hasIndex && !indexContainsFormula ) {
update.addColumns( indexColumnNames, "null" );
}
if ( getFactory().getSettings().isCommentsEnabled() ) {
if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
update.setComment( "delete one-to-many row " + getRole() );
}
@ -246,8 +252,7 @@ public class OneToManyPersister extends AbstractCollectionPersister {
offset = writeElement( st, collection.getElement( entry ), offset, session );
if ( useBatch ) {
session
.getJdbcCoordinator()
session.getJdbcCoordinator()
.getBatch( recreateBatchKey )
.addToBatch();
}
@ -279,7 +284,7 @@ public class OneToManyPersister extends AbstractCollectionPersister {
"could not update collection: " +
MessageHelper.collectionInfoString( this, collection, id, session ),
getSQLUpdateRowString()
);
);
}
}
}

View File

@ -879,9 +879,11 @@ public abstract class AbstractEntityPersister
return null;
}
return renderSelect( ArrayHelper.toIntArray( tableNumbers ),
return renderSelect(
ArrayHelper.toIntArray( tableNumbers ),
ArrayHelper.toIntArray( columnNumbers ),
ArrayHelper.toIntArray( formulaNumbers ) );
ArrayHelper.toIntArray( formulaNumbers )
);
}
@ -922,7 +924,9 @@ public abstract class AbstractEntityPersister
final Serializable id,
final EntityEntry entry) {
if ( !hasLazyProperties() ) throw new AssertionFailure( "no lazy properties" );
if ( !hasLazyProperties() ) {
throw new AssertionFailure( "no lazy properties" );
}
LOG.trace( "Initializing lazy properties from datastore" );
@ -1345,7 +1349,7 @@ public abstract class AbstractEntityPersister
else {
select.addColumns( rootTableKeyColumnNames );
}
if ( getFactory().getSettings().isCommentsEnabled() ) {
if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
select.setComment( "get version " + getEntityName() );
}
return select.addCondition( rootTableKeyColumnNames, "=?" ).toStatementString();
@ -1366,7 +1370,7 @@ public abstract class AbstractEntityPersister
private String generateGeneratedValuesSelectString(final GenerationTiming generationTimingToMatch) {
Select select = new Select( getFactory().getDialect() );
if ( getFactory().getSettings().isCommentsEnabled() ) {
if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
select.setComment( "get generated state " + getEntityName() );
}
@ -1447,7 +1451,7 @@ public abstract class AbstractEntityPersister
Select select = new Select( getFactory().getDialect() );
if ( getFactory().getSettings().isCommentsEnabled() ) {
if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
select.setComment( "get current state " + getEntityName() );
}
@ -1490,9 +1494,13 @@ public abstract class AbstractEntityPersister
}
Object nextVersion = getVersionType().next( currentVersion, session );
if (LOG.isTraceEnabled()) LOG.trace("Forcing version increment [" + MessageHelper.infoString(this, id, getFactory()) + "; "
+ getVersionType().toLoggableString(currentVersion, getFactory()) + " -> "
+ getVersionType().toLoggableString(nextVersion, getFactory()) + "]");
if ( LOG.isTraceEnabled() ) {
LOG.trace(
"Forcing version increment [" + MessageHelper.infoString( this, id, getFactory() ) + "; "
+ getVersionType().toLoggableString( currentVersion, getFactory() ) + " -> "
+ getVersionType().toLoggableString( nextVersion, getFactory() ) + "]"
);
}
// todo : cache this sql...
String versionIncrementString = generateVersionIncrementUpdateString();
@ -1522,7 +1530,7 @@ public abstract class AbstractEntityPersister
"could not retrieve version: " +
MessageHelper.infoString( this, id, getFactory() ),
getVersionSelectString()
);
);
}
return nextVersion;
@ -1531,7 +1539,7 @@ public abstract class AbstractEntityPersister
private String generateVersionIncrementUpdateString() {
Update update = new Update( getFactory().getDialect() );
update.setTableName( getTableName( 0 ) );
if ( getFactory().getSettings().isCommentsEnabled() ) {
if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
update.setComment( "forced version increment" );
}
update.addColumn( getVersionColumnName() );
@ -1660,7 +1668,7 @@ public abstract class AbstractEntityPersister
* which takes the entity name.
*/
public int getSubclassPropertyTableNumber(String propertyPath) {
String rootPropertyName = StringHelper.root(propertyPath);
String rootPropertyName = StringHelper.root( propertyPath );
Type type = propertyMapping.toType(rootPropertyName);
if ( type.isAssociationType() ) {
AssociationType assocType = ( AssociationType ) type;
@ -1830,8 +1838,9 @@ public abstract class AbstractEntityPersister
int counter = 0;
while(iter.hasNext()) {
Integer index = entityMetamodel.getPropertyIndexOrNull( iter.next() );
if ( index != null )
if ( index != null ) {
fields[counter++] = index;
}
}
return fields;
}
@ -2085,13 +2094,15 @@ public abstract class AbstractEntityPersister
}
private void initDiscriminatorPropertyPath(Mapping mapping) throws MappingException {
propertyMapping.initPropertyPaths( ENTITY_CLASS,
propertyMapping.initPropertyPaths(
ENTITY_CLASS,
getDiscriminatorType(),
new String[]{getDiscriminatorColumnName()},
new String[]{getDiscriminatorColumnReaders()},
new String[]{getDiscriminatorColumnReaderTemplate()},
new String[]{getDiscriminatorFormulaTemplate()},
getFactory() );
new String[] {getDiscriminatorColumnName()},
new String[] {getDiscriminatorColumnReaders()},
new String[] {getDiscriminatorColumnReaderTemplate()},
new String[] {getDiscriminatorFormulaTemplate()},
getFactory()
);
}
protected void initPropertyPaths(Mapping mapping) throws MappingException {
@ -2324,7 +2335,7 @@ public abstract class AbstractEntityPersister
insert.addColumns( getKeyColumns( j ) );
}
if ( getFactory().getSettings().isCommentsEnabled() ) {
if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
insert.setComment( "insert " + getEntityName() );
}
@ -2387,7 +2398,7 @@ public abstract class AbstractEntityPersister
// delegate already handles PK columns
if ( getFactory().getSettings().isCommentsEnabled() ) {
if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
insert.setComment( "insert " + getEntityName() );
}
@ -2398,13 +2409,13 @@ public abstract class AbstractEntityPersister
* Generate the SQL that deletes a row by id (and version)
*/
protected String generateDeleteString(int j) {
Delete delete = new Delete()
final Delete delete = new Delete()
.setTableName( getTableName( j ) )
.addPrimaryKeyColumns( getKeyColumns( j ) );
if ( j == 0 ) {
delete.setVersionColumnName( getVersionColumnName() );
}
if ( getFactory().getSettings().isCommentsEnabled() ) {
if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
delete.setComment( "delete " + getEntityName() );
}
return delete.toStatementString();
@ -2641,8 +2652,8 @@ public abstract class AbstractEntityPersister
public String getIdentitySelectString() {
//TODO: cache this in an instvar
return getFactory().getDialect().getIdentitySelectString(
getTableName(0),
getKeyColumns(0)[0],
getTableName( 0 ),
getKeyColumns( 0 )[0],
getIdentifierType().sqlTypes( getFactory() )[0]
);
}
@ -2684,8 +2695,9 @@ public abstract class AbstractEntityPersister
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Inserting entity: {0}", MessageHelper.infoString( this, id, getFactory() ) );
if ( j == 0 && isVersioned() )
if ( j == 0 && isVersioned() ) {
LOG.tracev( "Version: {0}", Versioning.getVersion( fields, this ) );
}
}
// TODO : shouldn't inserts be Expectations.NONE?
@ -2912,7 +2924,7 @@ public abstract class AbstractEntityPersister
e,
"could not update: " + MessageHelper.infoString( this, id, getFactory() ),
sql
);
);
}
}
@ -3032,7 +3044,7 @@ public abstract class AbstractEntityPersister
"could not delete: " +
MessageHelper.infoString( this, id, getFactory() ),
sql
);
);
}
@ -3142,7 +3154,7 @@ public abstract class AbstractEntityPersister
object,
updateStrings[j],
session
);
);
}
}
}
@ -3253,7 +3265,7 @@ public abstract class AbstractEntityPersister
Delete delete = new Delete()
.setTableName( getTableName( j ) )
.addPrimaryKeyColumns( getKeyColumns( j ) );
if ( getFactory().getSettings().isCommentsEnabled() ) {
if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
delete.setComment( "delete " + getEntityName() + " [" + j + "]" );
}
@ -3856,7 +3868,7 @@ public abstract class AbstractEntityPersister
propertyColumnUpdateable,
hasUninitializedLazyProperties( entity ),
session
);
);
if ( props == null ) {
return null;
}
@ -3885,7 +3897,7 @@ public abstract class AbstractEntityPersister
propertyColumnUpdateable,
hasUninitializedLazyProperties( entity ),
session
);
);
if ( props == null ) {
return null;
}
@ -4126,7 +4138,6 @@ public abstract class AbstractEntityPersister
}
private boolean isModifiableEntity(EntityEntry entry) {
return ( entry == null ? isMutable() : entry.isModifiableEntity() );
}
@ -4289,11 +4300,17 @@ public abstract class AbstractEntityPersister
return entityMetamodel.getPropertyInsertability();
}
/**
* @deprecated no simple, direct replacement
*/
@Deprecated
public ValueInclusion[] getPropertyInsertGenerationInclusions() {
return null;
}
/**
* @deprecated no simple, direct replacement
*/
@Deprecated
public ValueInclusion[] getPropertyUpdateGenerationInclusions() {
return null;
@ -4737,7 +4754,7 @@ public abstract class AbstractEntityPersister
}
Select select = new Select( getFactory().getDialect() );
if ( getFactory().getSettings().isCommentsEnabled() ) {
if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
select.setComment( "get current natural-id->entity-id state " + getEntityName() );
}
@ -4832,10 +4849,9 @@ public abstract class AbstractEntityPersister
/**
* Consolidated these onto a single helper because the 2 pieces work in tandem.
*/
public static interface CacheEntryHelper {
public CacheEntryStructure getCacheEntryStructure();
public CacheEntry buildCacheEntry(Object entity, Object[] state, Object version, SessionImplementor session);
public interface CacheEntryHelper {
CacheEntryStructure getCacheEntryStructure();
CacheEntry buildCacheEntry(Object entity, Object[] state, Object version, SessionImplementor session);
}
private static class StandardCacheEntryHelper implements CacheEntryHelper {

View File

@ -30,6 +30,7 @@ import java.util.Map;
import org.hibernate.MappingException;
import org.hibernate.QueryException;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.ArrayHelper;
@ -47,9 +48,7 @@ import org.jboss.logging.Logger;
* @author Gavin King
*/
public abstract class AbstractPropertyMapping implements PropertyMapping {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class,
AbstractPropertyMapping.class.getName());
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( AbstractPropertyMapping.class );
private final Map typesByPropertyPath = new HashMap();
private final Map columnsByPropertyPath = new HashMap();
@ -202,7 +201,9 @@ public abstract class AbstractPropertyMapping implements PropertyMapping {
}
}
if (path!=null) addPropertyPath(path, type, columns, columnReaders, columnReaderTemplates, formulaTemplates);
if (path!=null) {
addPropertyPath(path, type, columns, columnReaders, columnReaderTemplates, formulaTemplates);
}
if ( type.isComponentType() ) {
CompositeType actype = (CompositeType) type;

View File

@ -714,6 +714,7 @@ public interface EntityPersister extends OptimisticCacheSource, EntityDefinition
*
* @deprecated Use {@link #getIdentifier(Object,SessionImplementor)} instead
*/
@Deprecated
@SuppressWarnings( {"JavaDoc"})
public Serializable getIdentifier(Object object) throws HibernateException;

View File

@ -266,7 +266,9 @@ public class SingleTableEntityPersister extends AbstractEntityPersister {
isInverses.add( join.isInverse() );
isNullables.add( join.isOptional() );
isLazies.add( lazyAvailable && join.isLazy() );
if ( join.isSequentialSelect() && !persistentClass.isClassOrSuperclassJoin(join) ) hasDeferred = true;
if ( join.isSequentialSelect() && !persistentClass.isClassOrSuperclassJoin(join) ) {
hasDeferred = true;
}
subclassTables.add( join.getTable().getQualifiedName(
factory.getDialect(),
factory.getSettings().getDefaultCatalogName(),
@ -512,7 +514,9 @@ public class SingleTableEntityPersister extends AbstractEntityPersister {
}
else {
String result = (String) subclassesByDiscriminatorValue.get(value);
if (result==null) result = (String) subclassesByDiscriminatorValue.get(NOT_NULL_DISCRIMINATOR);
if (result==null) {
result = (String) subclassesByDiscriminatorValue.get(NOT_NULL_DISCRIMINATOR);
}
return result;
}
}
@ -560,7 +564,9 @@ public class SingleTableEntityPersister extends AbstractEntityPersister {
@Override
public String filterFragment(String alias) throws MappingException {
String result = discriminatorFilterFragment(alias);
if ( hasWhere() ) result += " and " + getSQLWhereString(alias);
if ( hasWhere() ) {
result += " and " + getSQLWhereString(alias);
}
return result;
}
@ -704,7 +710,9 @@ public class SingleTableEntityPersister extends AbstractEntityPersister {
private int getSubclassPropertyTableNumber(String propertyName, String entityName) {
Type type = propertyMapping.toType(propertyName);
if ( type.isAssociationType() && ( (AssociationType) type ).useLHSPrimaryKey() ) return 0;
if ( type.isAssociationType() && ( (AssociationType) type ).useLHSPrimaryKey() ) {
return 0;
}
final Integer tabnum = (Integer) propertyTableNumbersByNameAndSubclass.get(entityName + '.' + propertyName);
return tabnum==null ? 0 : tabnum;
}
@ -730,7 +738,9 @@ public class SingleTableEntityPersister extends AbstractEntityPersister {
tableNumbers.add( propTableNumber);
}
}
if ( tableNumbers.isEmpty() ) return null;
if ( tableNumbers.isEmpty() ) {
return null;
}
//figure out which columns are needed
ArrayList columnNumbers = new ArrayList();
@ -789,7 +799,9 @@ public class SingleTableEntityPersister extends AbstractEntityPersister {
public String getPropertyTableName(String propertyName) {
Integer index = getEntityMetamodel().getPropertyIndexOrNull(propertyName);
if (index==null) return null;
if (index==null) {
return null;
}
return qualifiedTableNames[ propertyTableNumbers[index] ];
}

View File

@ -415,7 +415,9 @@ public class UnionSubclassEntityPersister extends AbstractEntityPersister {
Table table = (Table) titer.next();
if ( !table.isAbstractUnionTable() ) {
Iterator citer = table.getColumnIterator();
while ( citer.hasNext() ) columns.add( citer.next() );
while ( citer.hasNext() ) {
columns.add( citer.next() );
}
}
}
@ -468,12 +470,16 @@ public class UnionSubclassEntityPersister extends AbstractEntityPersister {
}
protected String[] getSubclassTableKeyColumns(int j) {
if (j!=0) throw new AssertionFailure("only one table");
if (j!=0) {
throw new AssertionFailure("only one table");
}
return getIdentifierColumnNames();
}
public String getSubclassTableName(int j) {
if (j!=0) throw new AssertionFailure("only one table");
if (j!=0) {
throw new AssertionFailure("only one table");
}
return tableName;
}
@ -482,7 +488,9 @@ public class UnionSubclassEntityPersister extends AbstractEntityPersister {
}
protected boolean isClassOrSuperclassTable(int j) {
if (j!=0) throw new AssertionFailure("only one table");
if (j!=0) {
throw new AssertionFailure("only one table");
}
return true;
}
@ -492,7 +500,7 @@ public class UnionSubclassEntityPersister extends AbstractEntityPersister {
}
public String[] getConstraintOrderedTableNameClosure() {
return constraintOrderedTableNames;
return constraintOrderedTableNames;
}
public String[][] getContraintOrderedTableKeyColumnClosure() {

View File

@ -75,7 +75,7 @@ public class BasicPropertyAccessor implements PropertyAccessor {
true,
clazz,
propertyName
);
);
}
else {
throw new PropertyAccessException(
@ -84,7 +84,7 @@ public class BasicPropertyAccessor implements PropertyAccessor {
true,
clazz,
propertyName
);
);
}
}
catch (InvocationTargetException ite) {
@ -94,7 +94,7 @@ public class BasicPropertyAccessor implements PropertyAccessor {
true,
clazz,
propertyName
);
);
}
catch (IllegalAccessException iae) {
throw new PropertyAccessException(
@ -103,7 +103,7 @@ public class BasicPropertyAccessor implements PropertyAccessor {
true,
clazz,
propertyName
);
);
//cannot occur
}
catch (IllegalArgumentException iae) {
@ -114,7 +114,7 @@ public class BasicPropertyAccessor implements PropertyAccessor {
true,
clazz,
propertyName
);
);
}
else {
final Class expectedType = method.getParameterTypes()[0];
@ -127,7 +127,7 @@ public class BasicPropertyAccessor implements PropertyAccessor {
expectedType,
target,
value
);
);
}
}
}
@ -175,7 +175,7 @@ public class BasicPropertyAccessor implements PropertyAccessor {
false,
clazz,
propertyName
);
);
}
catch (IllegalAccessException iae) {
throw new PropertyAccessException(
@ -184,7 +184,7 @@ public class BasicPropertyAccessor implements PropertyAccessor {
false,
clazz,
propertyName
);
);
//cannot occur
}
catch (IllegalArgumentException iae) {
@ -195,7 +195,7 @@ public class BasicPropertyAccessor implements PropertyAccessor {
false,
clazz,
propertyName
);
);
}
}
@ -248,14 +248,15 @@ public class BasicPropertyAccessor implements PropertyAccessor {
propertyName +
" in class " +
theClass.getName()
);
);
}
return result;
}
private static BasicSetter getSetterOrNull(Class theClass, String propertyName) {
if (theClass==Object.class || theClass==null) return null;
if (theClass==Object.class || theClass==null) {
return null;
}
Method method = setterMethod(theClass, propertyName);
@ -284,7 +285,6 @@ public class BasicPropertyAccessor implements PropertyAccessor {
Method potentialSetter = null;
for ( Method method : methods ) {
final String methodName = method.getName();
if ( method.getParameterTypes().length == 1 && methodName.startsWith( "set" ) ) {
String testStdMethod = Introspector.decapitalize( methodName.substring( 3 ) );
String testOldMethod = methodName.substring( 3 );

View File

@ -38,7 +38,6 @@ import org.hibernate.mapping.Property;
* @author Steve Ebersole
*/
public final class PropertyAccessorFactory {
private static final PropertyAccessor BASIC_PROPERTY_ACCESSOR = new BasicPropertyAccessor();
private static final PropertyAccessor DIRECT_PROPERTY_ACCESSOR = new DirectPropertyAccessor();
private static final PropertyAccessor MAP_ACCESSOR = new MapAccessor();
@ -129,17 +128,29 @@ public final class PropertyAccessorFactory {
// todo : this eventually needs to be removed
public static PropertyAccessor getPropertyAccessor(Class optionalClass, String type) throws MappingException {
if ( type==null ) type = optionalClass==null || optionalClass==Map.class ? "map" : "property";
if ( type==null ) {
type = optionalClass==null || optionalClass==Map.class ? "map" : "property";
}
return getPropertyAccessor(type);
}
// todo : this eventually needs to be removed
public static PropertyAccessor getPropertyAccessor(String type) throws MappingException {
if ( type==null || "property".equals(type) ) return BASIC_PROPERTY_ACCESSOR;
if ( "field".equals(type) ) return DIRECT_PROPERTY_ACCESSOR;
if ( "map".equals(type) ) return MAP_ACCESSOR;
if ( "embedded".equals(type) ) return EMBEDDED_PROPERTY_ACCESSOR;
if ( "noop".equals(type)) return NOOP_ACCESSOR;
if ( type==null || "property".equals(type) ) {
return BASIC_PROPERTY_ACCESSOR;
}
if ( "field".equals(type) ) {
return DIRECT_PROPERTY_ACCESSOR;
}
if ( "map".equals(type) ) {
return MAP_ACCESSOR;
}
if ( "embedded".equals(type) ) {
return EMBEDDED_PROPERTY_ACCESSOR;
}
if ( "noop".equals(type)) {
return NOOP_ACCESSOR;
}
return resolveCustomAccessor(type);
}

View File

@ -115,7 +115,9 @@ public abstract class BasicLazyInitializer extends AbstractLazyInitializer {
session.getFactory().getEntityPersister( getEntityName() )
);
final Object entity = session.getPersistenceContext().getEntity(key);
if (entity!=null) setImplementation( entity );
if (entity!=null) {
setImplementation( entity );
}
}
if ( isUninitialized() ) {

View File

@ -114,14 +114,15 @@ public class OutputsImpl implements Outputs {
return false;
}
if ( currentReturnState.indicatesMoreOutputs() )
// prepare the next return state
try {
final boolean isResultSet = jdbcStatement.getMoreResults();
currentReturnState = buildCurrentReturnState( isResultSet );
}
catch (SQLException e) {
throw convert( e, "Error calling CallableStatement.getMoreResults" );
if ( currentReturnState.indicatesMoreOutputs() ) {
// prepare the next return state
try {
final boolean isResultSet = jdbcStatement.getMoreResults();
currentReturnState = buildCurrentReturnState( isResultSet );
}
catch (SQLException e) {
throw convert( e, "Error calling CallableStatement.getMoreResults" );
}
}
// and return

View File

@ -73,7 +73,9 @@ public class ConditionFragment {
.append( lhs[i] )
.append(op)
.append( rhs[i] );
if (i<lhs.length-1) buf.append(" and ");
if (i<lhs.length-1) {
buf.append(" and ");
}
}
return buf.toString();
}

View File

@ -108,15 +108,17 @@ public class Delete {
}
public Delete addPrimaryKeyColumns(String[] columnNames) {
for ( int i=0; i<columnNames.length; i++ ) {
addPrimaryKeyColumn( columnNames[i], "?" );
for ( String columnName : columnNames ) {
addPrimaryKeyColumn( columnName, "?" );
}
return this;
}
public Delete addPrimaryKeyColumns(String[] columnNames, boolean[] includeColumns, String[] valueExpressions) {
for ( int i=0; i<columnNames.length; i++ ) {
if( includeColumns[i] ) addPrimaryKeyColumn( columnNames[i], valueExpressions[i] );
if( includeColumns[i] ) {
addPrimaryKeyColumn( columnNames[i], valueExpressions[i] );
}
}
return this;
}

View File

@ -36,7 +36,6 @@ import org.hibernate.dialect.Dialect;
* @author Steve Ebersole
*/
public class InsertSelect {
private Dialect dialect;
private String tableName;
private String comment;
@ -75,8 +74,12 @@ public class InsertSelect {
}
public String toStatementString() {
if ( tableName == null ) throw new HibernateException( "no table name defined for insert-select" );
if ( select == null ) throw new HibernateException( "no select defined for insert-select" );
if ( tableName == null ) {
throw new HibernateException( "no table name defined for insert-select" );
}
if ( select == null ) {
throw new HibernateException( "no select defined for insert-select" );
}
StringBuilder buf = new StringBuilder( (columnNames.size() * 15) + tableName.length() + 10 );
if ( comment!=null ) {

View File

@ -37,21 +37,23 @@ public class OracleJoinFragment extends JoinFragment {
private StringBuilder afterWhere = new StringBuilder();
public void addJoin(String tableName, String alias, String[] fkColumns, String[] pkColumns, JoinType joinType) {
addCrossJoin( tableName, alias );
for ( int j = 0; j < fkColumns.length; j++ ) {
setHasThetaJoins( true );
afterWhere.append( " and " )
.append( fkColumns[j] );
if ( joinType == JoinType.RIGHT_OUTER_JOIN || joinType == JoinType.FULL_JOIN ) afterWhere.append( "(+)" );
if ( joinType == JoinType.RIGHT_OUTER_JOIN || joinType == JoinType.FULL_JOIN ) {
afterWhere.append( "(+)" );
}
afterWhere.append( '=' )
.append( alias )
.append( '.' )
.append( pkColumns[j] );
if ( joinType == JoinType.LEFT_OUTER_JOIN || joinType == JoinType.FULL_JOIN ) afterWhere.append( "(+)" );
if ( joinType == JoinType.LEFT_OUTER_JOIN || joinType == JoinType.FULL_JOIN ) {
afterWhere.append( "(+)" );
}
}
}
public String toFromFragmentString() {
@ -75,11 +77,11 @@ public class OracleJoinFragment extends JoinFragment {
}
public void addCondition(String alias, String[] columns, String condition) {
for ( int i = 0; i < columns.length; i++ ) {
for ( String column : columns ) {
afterWhere.append( " and " )
.append( alias )
.append( '.' )
.append( columns[i] )
.append( column )
.append( condition );
}
}

View File

@ -43,7 +43,7 @@ public class QuerySelect {
private String comment;
private boolean distinct;
private static final HashSet DONT_SPACE_TOKENS = new HashSet();
private static final HashSet<String> DONT_SPACE_TOKENS = new HashSet<String>();
static {
//dontSpace.add("'");
DONT_SPACE_TOKENS.add(".");
@ -82,10 +82,14 @@ public class QuerySelect {
}
public void addSelectFragmentString(String fragment) {
if ( fragment.length()>0 && fragment.charAt(0)==',' ) fragment = fragment.substring(1);
if ( fragment.length()>0 && fragment.charAt(0)==',' ) {
fragment = fragment.substring(1);
}
fragment = fragment.trim();
if ( fragment.length()>0 ) {
if ( select.length()>0 ) select.append(", ");
if ( select.length()>0 ) {
select.append(", ");
}
select.append(fragment);
}
}
@ -128,15 +132,21 @@ public class QuerySelect {
}
public void addOrderBy(String orderByString) {
if ( orderBy.length() > 0 ) orderBy.append(", ");
if ( orderBy.length() > 0 ) {
orderBy.append(", ");
}
orderBy.append(orderByString);
}
public String toQueryString() {
StringBuilder buf = new StringBuilder(50);
if (comment!=null) buf.append("/* ").append(comment).append(" */ ");
if (comment!=null) {
buf.append("/* ").append(comment).append(" */ ");
}
buf.append("select ");
if (distinct) buf.append("distinct ");
if (distinct) {
buf.append("distinct ");
}
String from = joins.toFromFragmentString();
if ( from.startsWith(",") ) {
from = from.substring(1);
@ -169,9 +179,15 @@ public class QuerySelect {
}
}
if ( groupBy.length() > 0 ) buf.append(" group by ").append( groupBy.toString() );
if ( having.length() > 0 ) buf.append(" having ").append( having.toString() );
if ( orderBy.length() > 0 ) buf.append(" order by ").append( orderBy.toString() );
if ( groupBy.length() > 0 ) {
buf.append(" group by ").append( groupBy.toString() );
}
if ( having.length() > 0 ) {
buf.append(" having ").append( having.toString() );
}
if ( orderBy.length() > 0 ) {
buf.append(" order by ").append( orderBy.toString() );
}
return dialect.transformSelectString( buf.toString() );
}

View File

@ -177,6 +177,7 @@ public class Select {
* @return LockMode
* @deprecated Instead use getLockOptions
*/
@Deprecated
public LockMode getLockMode() {
return lockOptions.getLockMode();
}
@ -187,6 +188,7 @@ public class Select {
* @return this object
* @deprecated Instead use setLockOptions
*/
@Deprecated
public Select setLockMode(LockMode lockMode) {
lockOptions.setLockMode(lockMode);
return this;

View File

@ -81,7 +81,9 @@ public class SelectFragment {
}
public SelectFragment addColumns(String[] columnNames) {
for (int i=0; i<columnNames.length; i++) addColumn( columnNames[i] );
for ( String columnName : columnNames ) {
addColumn( columnName );
}
return this;
}
@ -98,13 +100,17 @@ public class SelectFragment {
}
public SelectFragment addColumns(String tableAlias, String[] columnNames) {
for (int i=0; i<columnNames.length; i++) addColumn( tableAlias, columnNames[i] );
for ( String columnName : columnNames ) {
addColumn( tableAlias, columnName );
}
return this;
}
public SelectFragment addColumns(String tableAlias, String[] columnNames, String[] columnAliases) {
for (int i=0; i<columnNames.length; i++) {
if ( columnNames[i]!=null ) addColumn( tableAlias, columnNames[i], columnAliases[i] );
if ( columnNames[i]!=null ) {
addColumn( tableAlias, columnNames[i], columnAliases[i] );
}
}
return this;
}
@ -138,7 +144,9 @@ public class SelectFragment {
Iterator columnAliasIter = columnAliases.iterator();
//HashMap columnsUnique = new HashMap();
HashSet columnsUnique = new HashSet();
if (usedAliases!=null) columnsUnique.addAll( Arrays.asList(usedAliases) );
if (usedAliases!=null) {
columnsUnique.addAll( Arrays.asList(usedAliases) );
}
while ( iter.hasNext() ) {
String column = (String) iter.next();
String columnAlias = (String) columnAliasIter.next();

View File

@ -77,8 +77,10 @@ public class SimpleSelect {
}
public SimpleSelect addColumns(String[] columnNames) {
for ( int i=0; i<columnNames.length; i++ ) {
if ( columnNames[i]!=null ) addColumn( columnNames[i] );
for ( String columnName : columnNames ) {
if ( columnName != null ) {
addColumn( columnName );
}
}
return this;
}
@ -140,8 +142,10 @@ public class SimpleSelect {
}
public SimpleSelect addCondition(String[] lhs, String condition) {
for ( int i=0; i<lhs.length; i++ ) {
if ( lhs[i]!=null ) addCondition( lhs[i], condition );
for ( String lh : lhs ) {
if ( lh != null ) {
addCondition( lh, condition );
}
}
return this;
}
@ -152,7 +156,7 @@ public class SimpleSelect {
tableName.length() +
whereTokens.size() * 10 +
10
);
);
if ( comment!=null ) {
buf.append("/* ").append(comment).append(" */ ");
@ -184,7 +188,9 @@ public class SimpleSelect {
.append( toWhereClause() );
}
if (orderBy!=null) buf.append(orderBy);
if (orderBy!=null) {
buf.append(orderBy);
}
if (lockOptions!=null) {
buf.append( dialect.getForUpdateString(lockOptions) );
@ -198,7 +204,9 @@ public class SimpleSelect {
Iterator iter = whereTokens.iterator();
while ( iter.hasNext() ) {
buf.append( iter.next() );
if ( iter.hasNext() ) buf.append(' ');
if ( iter.hasNext() ) {
buf.append(' ');
}
}
return buf.toString();
}

View File

@ -79,15 +79,17 @@ public class Update {
}
public Update addPrimaryKeyColumns(String[] columnNames) {
for ( int i=0; i<columnNames.length; i++ ) {
addPrimaryKeyColumn( columnNames[i], "?" );
for ( String columnName : columnNames ) {
addPrimaryKeyColumn( columnName, "?" );
}
return this;
}
public Update addPrimaryKeyColumns(String[] columnNames, boolean[] includeColumns, String[] valueExpressions) {
for ( int i=0; i<columnNames.length; i++ ) {
if( includeColumns[i] ) addPrimaryKeyColumn( columnNames[i], valueExpressions[i] );
if( includeColumns[i] ) {
addPrimaryKeyColumn( columnNames[i], valueExpressions[i] );
}
}
return this;
}
@ -116,22 +118,24 @@ public class Update {
}
public Update addColumns(String[] columnNames) {
for ( int i=0; i<columnNames.length; i++ ) {
addColumn( columnNames[i] );
for ( String columnName : columnNames ) {
addColumn( columnName );
}
return this;
}
public Update addColumns(String[] columnNames, boolean[] updateable, String[] valueExpressions) {
for ( int i=0; i<columnNames.length; i++ ) {
if ( updateable[i] ) addColumn( columnNames[i], valueExpressions[i] );
if ( updateable[i] ) {
addColumn( columnNames[i], valueExpressions[i] );
}
}
return this;
}
public Update addColumns(String[] columnNames, String valueExpression) {
for ( int i=0; i<columnNames.length; i++ ) {
addColumn( columnNames[i], valueExpression );
for ( String columnName : columnNames ) {
addColumn( columnName, valueExpression );
}
return this;
}
@ -150,15 +154,15 @@ public class Update {
}
public Update addWhereColumns(String[] columnNames) {
for ( int i=0; i<columnNames.length; i++ ) {
addWhereColumn( columnNames[i] );
for ( String columnName : columnNames ) {
addWhereColumn( columnName );
}
return this;
}
public Update addWhereColumns(String[] columnNames, String valueExpression) {
for ( int i=0; i<columnNames.length; i++ ) {
addWhereColumn( columnNames[i], valueExpression );
for ( String columnName : columnNames ) {
addWhereColumn( columnName, valueExpression );
}
return this;
}

View File

@ -109,7 +109,8 @@ public class ConcurrentQueryStatisticsImpl extends CategorizedStatistics impleme
avgExecutionTime = totalExecutionTime.get() / executionCount.get();
}
return avgExecutionTime;
} finally {
}
finally {
writeLock.unlock();
}
}
@ -140,29 +141,28 @@ public class ConcurrentQueryStatisticsImpl extends CategorizedStatistics impleme
readLock.lock();
try {
// Less chances for a context switch
for (long old = executionMinTime.get(); (time < old) && !executionMinTime.compareAndSet(old, time); old = executionMinTime.get());
for (long old = executionMaxTime.get(); (time > old) && !executionMaxTime.compareAndSet(old, time); old = executionMaxTime.get());
for (long old = executionMinTime.get(); (time < old) && !executionMinTime.compareAndSet(old, time); old = executionMinTime.get()) {}
for (long old = executionMaxTime.get(); (time > old) && !executionMaxTime.compareAndSet(old, time); old = executionMaxTime.get()) {}
executionCount.getAndIncrement();
executionRowCount.addAndGet(rows);
totalExecutionTime.addAndGet(time);
} finally {
}
finally {
readLock.unlock();
}
}
public String toString() {
return new StringBuilder()
.append("QueryStatistics")
.append("[cacheHitCount=").append(this.cacheHitCount)
.append(",cacheMissCount=").append(this.cacheMissCount)
.append(",cachePutCount=").append(this.cachePutCount)
.append(",executionCount=").append(this.executionCount)
.append(",executionRowCount=").append(this.executionRowCount)
.append(",executionAvgTime=").append(this.getExecutionAvgTime())
.append(",executionMaxTime=").append(this.executionMaxTime)
.append(",executionMinTime=").append(this.executionMinTime)
.append(']')
.toString();
return "QueryStatistics"
+ "[cacheHitCount=" + this.cacheHitCount
+ ",cacheMissCount=" + this.cacheMissCount
+ ",cachePutCount=" + this.cachePutCount
+ ",executionCount=" + this.executionCount
+ ",executionRowCount=" + this.executionRowCount
+ ",executionAvgTime=" + this.getExecutionAvgTime()
+ ",executionMaxTime=" + this.executionMaxTime
+ ",executionMinTime=" + this.executionMinTime
+ ']';
}
void incrementCacheHitCount() {

View File

@ -26,11 +26,13 @@ package org.hibernate.tool.enhance;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
import org.hibernate.bytecode.enhance.spi.EnhancementContext;
import org.hibernate.bytecode.enhance.spi.Enhancer;
@ -56,7 +58,6 @@ import java.util.List;
* just a PoC though...
*
* @author Steve Ebersole
*
* @see org.hibernate.engine.spi.Managed
*/
public class EnhancementTask extends Task implements EnhancementContext {
@ -72,7 +73,7 @@ public class EnhancementTask extends Task implements EnhancementContext {
@Override
public void execute() throws BuildException {
log("Starting Hibernate EnhancementTask execution", Project.MSG_INFO);
log( "Starting Hibernate EnhancementTask execution", Project.MSG_INFO );
// we use the CtClass stuff here just as a simple vehicle for obtaining low level information about
// the class(es) contained in a file while still maintaining easy access to the underlying byte[]
@ -83,91 +84,96 @@ public class EnhancementTask extends Task implements EnhancementContext {
final DirectoryScanner directoryScanner = fileSet.getDirectoryScanner( project );
for ( String relativeIncludedFileName : directoryScanner.getIncludedFiles() ) {
final File javaClassFile = new File( fileSetBaseDir, relativeIncludedFileName );
if ( ! javaClassFile.exists() ) {
if ( !javaClassFile.exists() ) {
continue;
}
processClassFile( javaClassFile);
processClassFile( javaClassFile );
}
}
}
/**
* Atm only process files annotated with either @Entity or @Embeddable
* @param javaClassFile
*/
private void processClassFile(File javaClassFile) {
/**
* Atm only process files annotated with either @Entity or @Embeddable
*
* @param javaClassFile
*/
private void processClassFile(File javaClassFile) {
try {
final CtClass ctClass = classPool.makeClass( new FileInputStream( javaClassFile ) );
if(this.isEntityClass(ctClass))
processEntityClassFile(javaClassFile, ctClass);
else if(this.isCompositeClass(ctClass))
processCompositeClassFile(javaClassFile, ctClass);
if ( this.isEntityClass( ctClass ) ) {
processEntityClassFile( javaClassFile, ctClass );
}
else if ( this.isCompositeClass( ctClass ) ) {
processCompositeClassFile( javaClassFile, ctClass );
}
}
catch (IOException e) {
throw new BuildException(
String.format( "Error processing included file [%s]", javaClassFile.getAbsolutePath() ), e );
}
}
}
catch (IOException e) {
throw new BuildException(
String.format( "Error processing included file [%s]", javaClassFile.getAbsolutePath() ), e
);
}
}
private void processEntityClassFile(File javaClassFile, CtClass ctClass ) {
try {
byte[] result = enhancer.enhance(ctClass.getName(), ctClass.toBytecode());
if(result != null)
writeEnhancedClass(javaClassFile, result);
}
catch (Exception e) {
log( "Unable to enhance class [" + ctClass.getName() + "]", e, Project.MSG_WARN );
return;
}
}
private void processEntityClassFile(File javaClassFile, CtClass ctClass) {
try {
byte[] result = enhancer.enhance( ctClass.getName(), ctClass.toBytecode() );
if ( result != null ) {
writeEnhancedClass( javaClassFile, result );
}
}
catch (Exception e) {
log( "Unable to enhance class [" + ctClass.getName() + "]", e, Project.MSG_WARN );
}
}
private void processCompositeClassFile(File javaClassFile, CtClass ctClass) {
try {
byte[] result = enhancer.enhanceComposite(ctClass.getName(), ctClass.toBytecode());
if(result != null)
writeEnhancedClass(javaClassFile, result);
}
catch (Exception e) {
log( "Unable to enhance class [" + ctClass.getName() + "]", e, Project.MSG_WARN );
return;
}
}
private void processCompositeClassFile(File javaClassFile, CtClass ctClass) {
try {
byte[] result = enhancer.enhanceComposite( ctClass.getName(), ctClass.toBytecode() );
if ( result != null ) {
writeEnhancedClass( javaClassFile, result );
}
}
catch (Exception e) {
log( "Unable to enhance class [" + ctClass.getName() + "]", e, Project.MSG_WARN );
}
}
private void writeEnhancedClass(File javaClassFile, byte[] result) {
try {
private void writeEnhancedClass(File javaClassFile, byte[] result) {
try {
if ( javaClassFile.delete() ) {
if ( ! javaClassFile.createNewFile() ) {
log( "Unable to recreate class file [" + javaClassFile.getName() + "]", Project.MSG_INFO );
}
}
if ( !javaClassFile.createNewFile() ) {
log( "Unable to recreate class file [" + javaClassFile.getName() + "]", Project.MSG_INFO );
}
}
else {
log( "Unable to delete class file [" + javaClassFile.getName() + "]", Project.MSG_INFO );
}
FileOutputStream outputStream = new FileOutputStream( javaClassFile, false );
try {
outputStream.write( result);
outputStream.write( result );
outputStream.flush();
}
finally {
try {
outputStream.close();
}
catch ( IOException ignore) {
catch (IOException ignore) {
}
}
}
catch (FileNotFoundException ignore) {
// should not ever happen because of explicit checks
}
catch (IOException e) {
throw new BuildException(
String.format( "Error processing included file [%s]", javaClassFile.getAbsolutePath() ), e );
}
}
}
catch (FileNotFoundException ignore) {
// should not ever happen because of explicit checks
}
catch (IOException e) {
throw new BuildException(
String.format( "Error processing included file [%s]", javaClassFile.getAbsolutePath() ), e
);
}
}
// EnhancementContext impl ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@Override
@ -177,12 +183,12 @@ public class EnhancementTask extends Task implements EnhancementContext {
@Override
public boolean isEntityClass(CtClass classDescriptor) {
return classDescriptor.hasAnnotation(Entity.class);
}
return classDescriptor.hasAnnotation( Entity.class );
}
@Override
public boolean isCompositeClass(CtClass classDescriptor) {
return classDescriptor.hasAnnotation(Embeddable.class);
return classDescriptor.hasAnnotation( Embeddable.class );
}
@Override
@ -208,20 +214,20 @@ public class EnhancementTask extends Task implements EnhancementContext {
@Override
public boolean isPersistentField(CtField ctField) {
// current check is to look for @Transient
return ! ctField.hasAnnotation( Transient.class );
return !ctField.hasAnnotation( Transient.class );
}
@Override
public boolean isMappedCollection(CtField field) {
try {
return (field.getAnnotation(OneToMany.class) != null ||
field.getAnnotation(ManyToMany.class) != null ||
field.getAnnotation(ElementCollection.class) != null);
}
catch (ClassNotFoundException e) {
return false;
}
}
@Override
public boolean isMappedCollection(CtField field) {
try {
return ( field.getAnnotation( OneToMany.class ) != null ||
field.getAnnotation( ManyToMany.class ) != null ||
field.getAnnotation( ElementCollection.class ) != null );
}
catch (ClassNotFoundException e) {
return false;
}
}
@Override
public CtField[] order(CtField[] persistentFields) {

View File

@ -45,7 +45,9 @@ public class IndexMetadata {
}
void addColumn(ColumnMetadata column) {
if (column != null) columns.add(column);
if (column != null) {
columns.add(column);
}
}
public ColumnMetadata[] getColumns() {

View File

@ -38,7 +38,6 @@ public abstract class AbstractAttribute implements Attribute, Property {
}
@Override
@Deprecated
public String getNode() {
return null;
}

View File

@ -382,16 +382,10 @@ public class ElementWrapper implements Element, Serializable {
return element.attributeValue( qName, defaultValue );
}
/**
* @deprecated
*/
public void setAttributeValue(String name, String value) {
element.setAttributeValue( name, value );
}
/**
* @deprecated
*/
public void setAttributeValue(QName qName, String value) {
element.setAttributeValue( qName, value );
}

View File

@ -30,6 +30,9 @@ package org.hibernate.tuple;
*/
@Deprecated
public interface Property extends Attribute {
/**
* @deprecated DOM4j entity mode is no longer supported
*/
@Deprecated
public String getNode();
}

View File

@ -273,6 +273,9 @@ public final class PropertyFactory {
}
}
/**
* @deprecated See mainly {@link #buildEntityBasedAttribute}
*/
@Deprecated
public static StandardProperty buildStandardProperty(Property property, boolean lazyAvailable) {
final Type type = property.getValue().getType();

View File

@ -31,6 +31,8 @@ import org.hibernate.type.Type;
* Represents a non-identifier property within the Hibernate runtime-metamodel.
*
* @author Steve Ebersole
*
* @deprecated Use one of the {@link org.hibernate.tuple.Attribute}-based impls instead.
*/
@Deprecated
public class StandardProperty extends AbstractNonIdentifierAttribute implements NonIdentifierAttribute {

View File

@ -241,7 +241,9 @@ public class EntityMetamodel implements Serializable {
// temporary ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
boolean lazy = prop.isLazy() && instrumentationMetadata.isInstrumented();
if ( lazy ) hasLazy = true;
if ( lazy ) {
hasLazy = true;
}
propertyLaziness[i] = lazy;
propertyNames[i] = properties[i].getName();
@ -330,7 +332,9 @@ public class EntityMetamodel implements Serializable {
hasNonIdentifierPropertyNamedId = foundNonIdentifierPropertyNamedId;
versionPropertyIndex = tempVersionProperty;
hasLazyProperties = hasLazy;
if (hasLazyProperties) LOG.lazyPropertyFetchingAvailable(name);
if (hasLazyProperties) {
LOG.lazyPropertyFetchingAvailable(name);
}
lazy = persistentClass.isLazy() && (
// TODO: this disables laziness even in non-pojo entity modes:

View File

@ -51,7 +51,7 @@ public interface EntityTuplizer extends Tuplizer {
*
* @return The entity-mode
*/
public EntityMode getEntityMode();
EntityMode getEntityMode();
/**
* Create an entity instance initialized with the given identifier.
@ -62,8 +62,9 @@ public interface EntityTuplizer extends Tuplizer {
*
* @deprecated Use {@link #instantiate(Serializable, SessionImplementor)} instead.
*/
@Deprecated
@SuppressWarnings( {"JavaDoc"})
public Object instantiate(Serializable id) throws HibernateException;
Object instantiate(Serializable id) throws HibernateException;
/**
* Create an entity instance initialized with the given identifier.
@ -73,7 +74,7 @@ public interface EntityTuplizer extends Tuplizer {
*
* @return The instantiated entity.
*/
public Object instantiate(Serializable id, SessionImplementor session);
Object instantiate(Serializable id, SessionImplementor session);
/**
* Extract the identifier value from the given entity.
@ -87,7 +88,8 @@ public interface EntityTuplizer extends Tuplizer {
*
* @deprecated Use {@link #getIdentifier(Object,SessionImplementor)} instead.
*/
public Serializable getIdentifier(Object entity) throws HibernateException;
@Deprecated
Serializable getIdentifier(Object entity) throws HibernateException;
/**
* Extract the identifier value from the given entity.
@ -97,7 +99,7 @@ public interface EntityTuplizer extends Tuplizer {
*
* @return The identifier value.
*/
public Serializable getIdentifier(Object entity, SessionImplementor session);
Serializable getIdentifier(Object entity, SessionImplementor session);
/**
* Inject the identifier value into the given entity.
@ -109,8 +111,9 @@ public interface EntityTuplizer extends Tuplizer {
*
* @deprecated Use {@link #setIdentifier(Object, Serializable, SessionImplementor)} instead.
*/
@Deprecated
@SuppressWarnings( {"JavaDoc"})
public void setIdentifier(Object entity, Serializable id) throws HibernateException;
void setIdentifier(Object entity, Serializable id) throws HibernateException;
/**
* Inject the identifier value into the given entity.
@ -121,7 +124,7 @@ public interface EntityTuplizer extends Tuplizer {
* @param id The value to be injected as the identifier.
* @param session The session from which is requests originates
*/
public void setIdentifier(Object entity, Serializable id, SessionImplementor session);
void setIdentifier(Object entity, Serializable id, SessionImplementor session);
/**
* Inject the given identifier and version into the entity, in order to
@ -133,8 +136,9 @@ public interface EntityTuplizer extends Tuplizer {
*
* @deprecated Use {@link #resetIdentifier(Object, Serializable, Object, SessionImplementor)} instead
*/
@Deprecated
@SuppressWarnings( {"UnusedDeclaration"})
public void resetIdentifier(Object entity, Serializable currentId, Object currentVersion);
void resetIdentifier(Object entity, Serializable currentId, Object currentVersion);
/**
* Inject the given identifier and version into the entity, in order to
@ -145,7 +149,7 @@ public interface EntityTuplizer extends Tuplizer {
* @param currentVersion The version value to inject into the entity.
* @param session The session from which the request originated
*/
public void resetIdentifier(Object entity, Serializable currentId, Object currentVersion, SessionImplementor session);
void resetIdentifier(Object entity, Serializable currentId, Object currentVersion, SessionImplementor session);
/**
* Extract the value of the version property from the given entity.
@ -154,7 +158,7 @@ public interface EntityTuplizer extends Tuplizer {
* @return The value of the version property, or null if not versioned.
* @throws HibernateException Indicates a problem accessing the version property
*/
public Object getVersion(Object entity) throws HibernateException;
Object getVersion(Object entity) throws HibernateException;
/**
* Inject the value of a particular property.
@ -164,7 +168,7 @@ public interface EntityTuplizer extends Tuplizer {
* @param value The property value to inject.
* @throws HibernateException Indicates a problem access the property
*/
public void setPropertyValue(Object entity, int i, Object value) throws HibernateException;
void setPropertyValue(Object entity, int i, Object value) throws HibernateException;
/**
* Inject the value of a particular property.
@ -174,7 +178,7 @@ public interface EntityTuplizer extends Tuplizer {
* @param value The property value to inject.
* @throws HibernateException Indicates a problem access the property
*/
public void setPropertyValue(Object entity, String propertyName, Object value) throws HibernateException;
void setPropertyValue(Object entity, String propertyName, Object value) throws HibernateException;
/**
* Extract the values of the insertable properties of the entity (including backrefs)
@ -185,7 +189,7 @@ public interface EntityTuplizer extends Tuplizer {
* @return The insertable property values.
* @throws HibernateException Indicates a problem access the properties
*/
public Object[] getPropertyValuesToInsert(Object entity, Map mergeMap, SessionImplementor session)
Object[] getPropertyValuesToInsert(Object entity, Map mergeMap, SessionImplementor session)
throws HibernateException;
/**
@ -196,7 +200,7 @@ public interface EntityTuplizer extends Tuplizer {
* @return The current value of the given property on the given entity.
* @throws HibernateException Indicates a problem access the property
*/
public Object getPropertyValue(Object entity, String propertyName) throws HibernateException;
Object getPropertyValue(Object entity, String propertyName) throws HibernateException;
/**
* Called just after the entities properties have been initialized.
@ -205,14 +209,14 @@ public interface EntityTuplizer extends Tuplizer {
* @param lazyPropertiesAreUnfetched Are defined lazy properties currently unfecthed
* @param session The session initializing this entity.
*/
public void afterInitialize(Object entity, boolean lazyPropertiesAreUnfetched, SessionImplementor session);
void afterInitialize(Object entity, boolean lazyPropertiesAreUnfetched, SessionImplementor session);
/**
* Does this entity, for this mode, present a possibility for proxying?
*
* @return True if this tuplizer can generate proxies for this entity.
*/
public boolean hasProxy();
boolean hasProxy();
/**
* Generates an appropriate proxy representation of this entity for this
@ -223,7 +227,7 @@ public interface EntityTuplizer extends Tuplizer {
* @return The generate proxies.
* @throws HibernateException Indicates an error generating the proxy.
*/
public Object createProxy(Serializable id, SessionImplementor session) throws HibernateException;
Object createProxy(Serializable id, SessionImplementor session) throws HibernateException;
/**
* Does the {@link #getMappedClass() class} managed by this tuplizer implement
@ -231,7 +235,7 @@ public interface EntityTuplizer extends Tuplizer {
*
* @return True if the Lifecycle interface is implemented; false otherwise.
*/
public boolean isLifecycleImplementor();
boolean isLifecycleImplementor();
/**
* Returns the java class to which generated proxies will be typed.
@ -241,7 +245,7 @@ public interface EntityTuplizer extends Tuplizer {
*
* @return The java class to which generated proxies will be typed
*/
public Class getConcreteProxyClass();
Class getConcreteProxyClass();
/**
* Does the given entity instance have any currently uninitialized lazy properties?
@ -249,21 +253,21 @@ public interface EntityTuplizer extends Tuplizer {
* @param entity The entity to be check for uninitialized lazy properties.
* @return True if uninitialized lazy properties were found; false otherwise.
*/
public boolean hasUninitializedLazyProperties(Object entity);
boolean hasUninitializedLazyProperties(Object entity);
/**
* Is it an instrumented POJO?
*
* @return {@code true} if the entity class is instrumented; {@code false} otherwise.
*/
public boolean isInstrumented();
boolean isInstrumented();
/**
* Get any {@link EntityNameResolver EntityNameResolvers} associated with this {@link Tuplizer}.
*
* @return The associated resolvers. May be null or empty.
*/
public EntityNameResolver[] getEntityNameResolvers();
EntityNameResolver[] getEntityNameResolvers();
/**
* Given an entity instance, determine the most appropriate (most targeted) entity-name which represents it.
@ -287,19 +291,19 @@ public interface EntityTuplizer extends Tuplizer {
*
* @throws HibernateException If we are unable to determine an entity-name within the inheritence hierarchy.
*/
public String determineConcreteSubclassEntityName(Object entityInstance, SessionFactoryImplementor factory);
String determineConcreteSubclassEntityName(Object entityInstance, SessionFactoryImplementor factory);
/**
* Retrieve the getter for the identifier property. May return null.
*
* @return The getter for the identifier property.
*/
public Getter getIdentifierGetter();
Getter getIdentifierGetter();
/**
* Retrieve the getter for the version property. May return null.
*
* @return The getter for the version property.
*/
public Getter getVersionGetter();
Getter getVersionGetter();
}

View File

@ -1,186 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.type;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Comparator;
import org.hibernate.HibernateException;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.spi.SessionImplementor;
/**
* Logic to bind stream of byte into a VARBINARY
*
* @author Gavin King
* @author Emmanuel Bernard
*
* @deprecated Use the {@link AbstractStandardBasicType} approach instead
*/
public abstract class AbstractBynaryType extends MutableType implements VersionType, Comparator {
/**
* Convert the byte[] into the expected object type
*/
abstract protected Object toExternalFormat(byte[] bytes);
/**
* Convert the object into the internal byte[] representation
*/
abstract protected byte[] toInternalFormat(Object bytes);
public void set(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
byte[] internalValue = toInternalFormat( value );
if ( Environment.useStreamsForBinary() ) {
st.setBinaryStream( index, new ByteArrayInputStream( internalValue ), internalValue.length );
}
else {
st.setBytes( index, internalValue );
}
}
public Object get(ResultSet rs, String name) throws HibernateException, SQLException {
if ( Environment.useStreamsForBinary() ) {
InputStream inputStream = rs.getBinaryStream(name);
if (inputStream==null) return toExternalFormat( null ); // is this really necessary?
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(2048);
byte[] buffer = new byte[2048];
try {
while (true) {
int amountRead = inputStream.read(buffer);
if (amountRead == -1) {
break;
}
outputStream.write(buffer, 0, amountRead);
}
inputStream.close();
outputStream.close();
}
catch (IOException ioe) {
throw new HibernateException( "IOException occurred reading a binary value", ioe );
}
return toExternalFormat( outputStream.toByteArray() );
}
else {
return toExternalFormat( rs.getBytes(name) );
}
}
public int sqlType() {
return Types.VARBINARY;
}
// VersionType impl ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Note : simply returns null for seed() and next() as the only known
// application of binary types for versioning is for use with the
// TIMESTAMP datatype supported by Sybase and SQL Server, which
// are completely db-generated values...
public Object seed(SessionImplementor session) {
return null;
}
public Object next(Object current, SessionImplementor session) {
return current;
}
public Comparator getComparator() {
return this;
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public boolean isEqual(Object x, Object y) {
return x==y || ( x!=null && y!=null && java.util.Arrays.equals( toInternalFormat(x), toInternalFormat(y) ) );
}
public int getHashCode(Object x) {
byte[] bytes = toInternalFormat(x);
int hashCode = 1;
for ( int j=0; j<bytes.length; j++ ) {
hashCode = 31 * hashCode + bytes[j];
}
return hashCode;
}
public int compare(Object x, Object y) {
byte[] xbytes = toInternalFormat(x);
byte[] ybytes = toInternalFormat(y);
if ( xbytes.length < ybytes.length ) return -1;
if ( xbytes.length > ybytes.length ) return 1;
for ( int i=0; i<xbytes.length; i++ ) {
if ( xbytes[i] < ybytes[i] ) return -1;
if ( xbytes[i] > ybytes[i] ) return 1;
}
return 0;
}
public abstract String getName();
public String toString(Object val) {
byte[] bytes = toInternalFormat(val);
StringBuilder buf = new StringBuilder();
for ( int i=0; i<bytes.length; i++ ) {
String hexStr = Integer.toHexString( bytes[i] - Byte.MIN_VALUE );
if ( hexStr.length()==1 ) buf.append('0');
buf.append(hexStr);
}
return buf.toString();
}
public Object deepCopyNotNull(Object value) {
byte[] bytes = toInternalFormat(value);
byte[] result = new byte[bytes.length];
System.arraycopy(bytes, 0, result, 0, bytes.length);
return toExternalFormat(result);
}
public Object fromStringValue(String xml) throws HibernateException {
if (xml == null)
return null;
if (xml.length() % 2 != 0)
throw new IllegalArgumentException("The string is not a valid xml representation of a binary content.");
byte[] bytes = new byte[xml.length() / 2];
for (int i = 0; i < bytes.length; i++) {
String hexStr = xml.substring(i * 2, (i + 1) * 2);
bytes[i] = (byte) (Integer.parseInt(hexStr, 16) + Byte.MIN_VALUE);
}
return toExternalFormat(bytes);
}
}

View File

@ -1,120 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.type;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.Reader;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.hibernate.HibernateException;
import org.hibernate.dialect.Dialect;
/**
* Logic to bind stream of char into a VARCHAR
*
* @author Emmanuel Bernard
*
* @deprecated Use the {@link AbstractStandardBasicType} approach instead
*/
public abstract class AbstractCharArrayType extends MutableType {
/**
* Convert the char[] into the expected object type
*/
abstract protected Object toExternalFormat(char[] chars);
/**
* Convert the object into the internal char[] representation
*/
abstract protected char[] toInternalFormat(Object chars);
public Object get(ResultSet rs, String name) throws SQLException {
Reader stream = rs.getCharacterStream(name);
if ( stream == null ) return toExternalFormat( null );
CharArrayWriter writer = new CharArrayWriter();
for(;;) {
try {
int c = stream.read();
if ( c == -1) return toExternalFormat( writer.toCharArray() );
writer.write( c );
}
catch (IOException e) {
throw new HibernateException("Unable to read character stream from rs");
}
}
}
public abstract Class getReturnedClass();
public void set(PreparedStatement st, Object value, int index) throws SQLException {
char[] chars = toInternalFormat( value );
st.setCharacterStream(index, new CharArrayReader(chars), chars.length);
}
public int sqlType() {
return Types.VARCHAR;
}
public String objectToSQLString(Object value, Dialect dialect) throws Exception {
return '\'' + new String( toInternalFormat( value ) ) + '\'';
}
public Object stringToObject(String xml) throws Exception {
if (xml == null) return toExternalFormat( null );
int length = xml.length();
char[] chars = new char[length];
for (int index = 0 ; index < length ; index++ ) {
chars[index] = xml.charAt( index );
}
return toExternalFormat( chars );
}
public String toString(Object value) {
if (value == null) return null;
return new String( toInternalFormat( value ) );
}
public Object fromStringValue(String xml) {
if (xml == null) return null;
int length = xml.length();
char[] chars = new char[length];
for (int index = 0 ; index < length ; index++ ) {
chars[index] = xml.charAt( index );
}
return toExternalFormat( chars );
}
protected Object deepCopyNotNull(Object value) throws HibernateException {
char[] chars = toInternalFormat(value);
char[] result = new char[chars.length];
System.arraycopy(chars, 0, result, 0, chars.length);
return toExternalFormat(result);
}
}

View File

@ -1,37 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.type;
/**
* Enables other Component-like types to hold collections and have cascades, etc.
*
* @see ComponentType
* @see AnyType
* @author Gavin King
*
* @deprecated in favor of {@link org.hibernate.type.CompositeType}
*/
public interface AbstractComponentType extends CompositeType {
}

View File

@ -1,100 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.type;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.engine.jdbc.Size;
/**
* @author Emmanuel Bernard
* @deprecated
*/
@Deprecated
public abstract class AbstractLobType extends AbstractType implements Serializable {
public boolean isDirty(Object old, Object current, boolean[] checkable, SessionImplementor session)
throws HibernateException {
return checkable[0] ? ! isEqual( old, current ) : false;
}
@Override
public Size[] dictatedSizes(Mapping mapping) throws MappingException {
return new Size[] { LEGACY_DICTATED_SIZE };
}
@Override
public Size[] defaultSizes(Mapping mapping) throws MappingException {
return new Size[] { LEGACY_DEFAULT_SIZE };
}
@Override
public boolean isEqual(Object x, Object y) {
return isEqual( x, y, null );
}
@Override
public int getHashCode(Object x) {
return getHashCode( x, null );
}
public String getName() {
return this.getClass().getName();
}
public int getColumnSpan(Mapping mapping) throws MappingException {
return 1;
}
protected abstract Object get(ResultSet rs, String name) throws SQLException;
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
throws HibernateException, SQLException {
return get( rs, names[0] );
}
public Object nullSafeGet(ResultSet rs, String name, SessionImplementor session, Object owner)
throws HibernateException, SQLException {
return get( rs, name );
}
public void nullSafeSet(
PreparedStatement st, Object value, int index, boolean[] settable, SessionImplementor session
) throws HibernateException, SQLException {
if ( settable[0] ) set( st, value, index, session );
}
protected abstract void set(PreparedStatement st, Object value, int index, SessionImplementor session)
throws SQLException;
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session)
throws HibernateException, SQLException {
set( st, value, index, session );
}
}

View File

@ -1,47 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.type;
/**
* An abstract type for mapping long binary SQL types to Java byte[].
*
* @author Gail Badner
*
* @deprecated Use the {@link AbstractStandardBasicType} approach instead
*/
public abstract class AbstractLongBinaryType extends AbstractBynaryType {
public Class getReturnedClass() {
return byte[].class;
}
protected Object toExternalFormat(byte[] bytes) {
return bytes;
}
protected byte[] toInternalFormat(Object bytes) {
return ( byte[] ) bytes;
}
}

View File

@ -1,94 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.type;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.HibernateException;
/**
* An abstract type for mapping long string SQL types to a Java String.
* @author Gavin King, Bertrand Renuart (from TextType)
*
* @deprecated Use the {@link AbstractStandardBasicType} approach instead
*/
public abstract class AbstractLongStringType extends ImmutableType {
public void set(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
String str = (String) value;
st.setCharacterStream( index, new StringReader(str), str.length() );
}
public Object get(ResultSet rs, String name) throws HibernateException, SQLException {
// Retrieve the value of the designated column in the current row of this
// ResultSet object as a java.io.Reader object
Reader charReader = rs.getCharacterStream(name);
// if the corresponding SQL value is NULL, the reader we got is NULL as well
if (charReader==null) return null;
// Fetch Reader content up to the end - and put characters in a StringBuilder
StringBuilder sb = new StringBuilder();
try {
char[] buffer = new char[2048];
while (true) {
int amountRead = charReader.read(buffer, 0, buffer.length);
if ( amountRead == -1 ) break;
sb.append(buffer, 0, amountRead);
}
}
catch (IOException ioe) {
throw new HibernateException( "IOException occurred reading text", ioe );
}
finally {
try {
charReader.close();
}
catch (IOException e) {
throw new HibernateException( "IOException occurred closing stream", e );
}
}
// Return StringBuilder content as a large String
return sb.toString();
}
public Class getReturnedClass() {
return String.class;
}
public String toString(Object val) {
return (String) val;
}
public Object fromStringValue(String xml) {
return xml;
}
}

View File

@ -55,7 +55,7 @@ import org.dom4j.Node;
* @author Brett Meyer
*/
public abstract class AbstractStandardBasicType<T>
implements BasicType, StringRepresentableType<T>, XmlRepresentableType<T>, ProcedureParameterExtractionAware<T> {
implements BasicType, StringRepresentableType<T>, ProcedureParameterExtractionAware<T> {
private static final Size DEFAULT_SIZE = new Size( 19, 2, 255, Size.LobMultiplier.NONE ); // to match legacy behavior
private final Size dictatedSize = new Size();
@ -85,14 +85,6 @@ public abstract class AbstractStandardBasicType<T>
return fromString( xml );
}
public String toXMLString(T value, SessionFactoryImplementor factory) throws HibernateException {
return toString( value );
}
public T fromXMLString(String xml, Mapping factory) throws HibernateException {
return StringHelper.isEmpty( xml ) ? null : fromStringValue( xml );
}
protected MutabilityPlan<T> getMutabilityPlan() {
return javaTypeDescriptor.getMutabilityPlan();
}

View File

@ -136,7 +136,9 @@ public class ArrayType extends CollectionType {
int length = Array.getLength(array);
for ( int i=0; i<length; i++ ) {
//TODO: proxies!
if ( Array.get(array, i)==element ) return i;
if ( Array.get(array, i)==element ) {
return i;
}
}
return null;
}

Some files were not shown because too many files have changed in this diff Show More