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 * @param document The DOM document
* *
* @return this (for method chaining purposes) * @return this (for method chaining purposes)
*
* @deprecated since 5.0. Use one of the other methods for passing mapping source(s).
*/ */
@Deprecated @Deprecated
public MetadataSources addDocument(Document document) { public MetadataSources addDocument(Document document) {

View File

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

View File

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

View File

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

View File

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

View File

@ -152,7 +152,6 @@ public abstract class AbstractDelegatingSessionFactoryBuilder<T extends Abstract
} }
@Override @Override
@Deprecated
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public T applyDefaultEntityMode(EntityMode entityMode) { public T applyDefaultEntityMode(EntityMode entityMode) {
delegate.applyDefaultEntityMode( entityMode ); delegate.applyDefaultEntityMode( entityMode );
@ -258,7 +257,6 @@ public abstract class AbstractDelegatingSessionFactoryBuilder<T extends Abstract
} }
@Override @Override
@Deprecated
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public T applyQuerySubstitutions(Map substitutions) { public T applyQuerySubstitutions(Map substitutions) {
delegate.applyQuerySubstitutions( 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.engine.spi.SessionImplementor;
import org.hibernate.loader.CollectionAliases; import org.hibernate.loader.CollectionAliases;
import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.type.StringRepresentableType;
import org.hibernate.type.Type; import org.hibernate.type.Type;
import org.hibernate.type.XmlRepresentableType;
import org.dom4j.Element; import org.dom4j.Element;
@ -204,7 +204,7 @@ public abstract class PersistentIndexedElementHolder extends AbstractPersistentC
final Type indexType = persister.getIndexType(); final Type indexType = persister.getIndexType();
final Object indexValue = persister.readIndex( rs, descriptor.getSuffixedIndexAliases(), getSession() ); 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 ); setIndex( elem, indexNode, index );
return object; return object;
} }
@ -251,7 +251,7 @@ public abstract class PersistentIndexedElementHolder extends AbstractPersistentC
final Map.Entry me = (Map.Entry) o; final Map.Entry me = (Map.Entry) o;
final Object object = indexIsFormula final Object object = indexIsFormula
? me.getValue() ? me.getValue()
: ( (XmlRepresentableType) indexType ).fromXMLString( (String) me.getKey(), persister.getFactory() ); : ( (StringRepresentableType) indexType ).fromStringValue( (String) me.getKey() );
if ( object != null ) { if ( object != null ) {
deleteList.add( object ); deleteList.add( object );
} }
@ -279,7 +279,7 @@ public abstract class PersistentIndexedElementHolder extends AbstractPersistentC
public Object getIndex(Object entry, int i, CollectionPersister persister) { public Object getIndex(Object entry, int i, CollectionPersister persister) {
final String index = ( (IndexedValue) entry ).index; final String index = ( (IndexedValue) entry ).index;
final Type indexType = persister.getIndexType(); final Type indexType = persister.getIndexType();
return ( (XmlRepresentableType) indexType ).fromXMLString( index, persister.getFactory() ); return ( (StringRepresentableType) indexType ).fromStringValue( index );
} }
@Override @Override

View File

@ -29,8 +29,8 @@ import java.util.List;
import org.hibernate.HibernateException; import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.type.StringRepresentableType;
import org.hibernate.type.Type; import org.hibernate.type.Type;
import org.hibernate.type.XmlRepresentableType;
import org.dom4j.Element; import org.dom4j.Element;
@ -84,7 +84,7 @@ public class PersistentMapElementHolder extends PersistentIndexedElementHolder {
final Element subElement = element.addElement( persister.getElementNodeName() ); final Element subElement = element.addElement( persister.getElementNodeName() );
elementType.setToXMLNode( subElement, object, persister.getFactory() ); 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 ); setIndex( subElement, indexNodeName, indexString );
} }
} }
@ -104,7 +104,7 @@ public class PersistentMapElementHolder extends PersistentIndexedElementHolder {
final Element elem = (Element) elements.get( i/2 ); final Element elem = (Element) elements.get( i/2 );
final Object object = elementType.fromXMLNode( elem, persister.getFactory() ); final Object object = elementType.fromXMLNode( elem, persister.getFactory() );
final String indexString = getIndex( elem, indexNodeName, i ); 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++] = indexType.disassemble( index, getSession(), null );
result[i++] = elementType.disassemble( object, 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) { private String renderCountDistinct(List arguments, Dialect dialect) {
final StringBuilder buffer = new StringBuilder(); final StringBuilder buffer = new StringBuilder();
buffer.append( "count(distinct " ); buffer.append( "count(distinct " );
if (dialect.requiresParensForTupleDistinctCounts()) buffer.append("("); if (dialect.requiresParensForTupleDistinctCounts()) {
buffer.append("(");
}
String sep = ""; String sep = "";
final Iterator itr = arguments.iterator(); final Iterator itr = arguments.iterator();
// intentionally skip first // intentionally skip first
@ -77,7 +79,9 @@ public class StandardAnsiSqlAggregationFunctions {
buffer.append( sep ).append( itr.next() ); buffer.append( sep ).append( itr.next() );
sep = ", "; sep = ", ";
} }
if (dialect.requiresParensForTupleDistinctCounts()) buffer.append(")"); if (dialect.requiresParensForTupleDistinctCounts()) {
buffer.append(")");
}
return buffer.append( ")" ).toString(); 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 * 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 * Constructs a HQLQueryPlan
@ -121,8 +121,9 @@ public class HQLQueryPlan implements Serializable {
final Set<Serializable> combinedQuerySpaces = new HashSet<Serializable>(); final Set<Serializable> combinedQuerySpaces = new HashSet<Serializable>();
final boolean hasCollectionRole = (collectionRole == null); final boolean hasCollectionRole = (collectionRole == null);
final Map querySubstitutions = factory.getSettings().getQuerySubstitutions(); final Map querySubstitutions = factory.getSessionFactoryOptions().getQuerySubstitutions();
final QueryTranslatorFactory queryTranslatorFactory = factory.getSettings().getQueryTranslatorFactory(); final QueryTranslatorFactory queryTranslatorFactory = factory.getServiceRegistry().getService( QueryTranslatorFactory.class );
for ( int i=0; i<length; i++ ) { for ( int i=0; i<length; i++ ) {
if ( hasCollectionRole ) { if ( hasCollectionRole ) {
@ -205,7 +206,7 @@ public class HQLQueryPlan implements Serializable {
public List performList( public List performList(
QueryParameters queryParameters, QueryParameters queryParameters,
SessionImplementor session) throws HibernateException { SessionImplementor session) throws HibernateException {
if ( TRACE_ENABLED ) { if ( traceEnabled ) {
LOG.tracev( "Find: {0}", getSourceQuery() ); LOG.tracev( "Find: {0}", getSourceQuery() );
queryParameters.traceParameters( session.getFactory() ); queryParameters.traceParameters( session.getFactory() );
} }
@ -276,7 +277,8 @@ public class HQLQueryPlan implements Serializable {
* @param rowSelection * @param rowSelection
* @return a reasonable size to use for allocation * @return a reasonable size to use for allocation
*/ */
private final int guessResultSize(RowSelection rowSelection) { @SuppressWarnings("UnnecessaryUnboxing")
private int guessResultSize(RowSelection rowSelection) {
if ( rowSelection != null ) { if ( rowSelection != null ) {
final int maxReasonableAllocation = rowSelection.getFetchSize() != null ? rowSelection.getFetchSize().intValue() : 100; final int maxReasonableAllocation = rowSelection.getFetchSize() != null ? rowSelection.getFetchSize().intValue() : 100;
if ( rowSelection.getMaxRows() != null && rowSelection.getMaxRows().intValue() > 0 ) { if ( rowSelection.getMaxRows() != null && rowSelection.getMaxRows().intValue() > 0 ) {
@ -303,7 +305,7 @@ public class HQLQueryPlan implements Serializable {
public Iterator performIterate( public Iterator performIterate(
QueryParameters queryParameters, QueryParameters queryParameters,
EventSource session) throws HibernateException { EventSource session) throws HibernateException {
if ( TRACE_ENABLED ) { if ( traceEnabled ) {
LOG.tracev( "Iterate: {0}", getSourceQuery() ); LOG.tracev( "Iterate: {0}", getSourceQuery() );
queryParameters.traceParameters( session.getFactory() ); queryParameters.traceParameters( session.getFactory() );
} }
@ -341,7 +343,7 @@ public class HQLQueryPlan implements Serializable {
public ScrollableResults performScroll( public ScrollableResults performScroll(
QueryParameters queryParameters, QueryParameters queryParameters,
SessionImplementor session) throws HibernateException { SessionImplementor session) throws HibernateException {
if ( TRACE_ENABLED ) { if ( traceEnabled ) {
LOG.tracev( "Iterate: {0}", getSourceQuery() ); LOG.tracev( "Iterate: {0}", getSourceQuery() );
queryParameters.traceParameters( session.getFactory() ); queryParameters.traceParameters( session.getFactory() );
} }
@ -367,7 +369,7 @@ public class HQLQueryPlan implements Serializable {
*/ */
public int performExecuteUpdate(QueryParameters queryParameters, SessionImplementor session) public int performExecuteUpdate(QueryParameters queryParameters, SessionImplementor session)
throws HibernateException { throws HibernateException {
if ( TRACE_ENABLED ) { if ( traceEnabled ) {
LOG.tracev( "Execute update: {0}", getSourceQuery() ); LOG.tracev( "Execute update: {0}", getSourceQuery() );
queryParameters.traceParameters( session.getFactory() ); queryParameters.traceParameters( session.getFactory() );
} }
@ -382,10 +384,10 @@ public class HQLQueryPlan implements Serializable {
} }
private ParameterMetadata buildParameterMetadata(ParameterTranslations parameterTranslations, String hql) { 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 ); final ParamLocationRecognizer recognizer = ParamLocationRecognizer.parseLocations( hql );
if ( TRACE_ENABLED ) { if ( traceEnabled ) {
final long end = System.nanoTime(); final long end = System.nanoTime();
LOG.tracev( "HQL param location recognition took {0} nanoseconds ({1})", ( end - start ), hql ); 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 since 5.0; use {@link #getServiceRegistry()} instead to locate the JdbcServices
*/ */
@Deprecated
JdbcServices getJdbcServices(); JdbcServices getJdbcServices();
/** /**

View File

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

View File

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

View File

@ -72,21 +72,30 @@ public class DefaultResolveNaturalIdEventListener
final EntityPersister persister = event.getEntityPersister(); final EntityPersister persister = event.getEntityPersister();
final boolean traceEnabled = LOG.isTraceEnabled(); final boolean traceEnabled = LOG.isTraceEnabled();
if ( traceEnabled ) if ( traceEnabled ) {
LOG.tracev( "Attempting to resolve: {0}", LOG.tracev(
MessageHelper.infoString( persister, event.getNaturalIdValues(), event.getSession().getFactory() ) ); "Attempting to resolve: {0}",
MessageHelper.infoString( persister, event.getNaturalIdValues(), event.getSession().getFactory() )
);
}
Serializable entityId = resolveFromCache( event ); Serializable entityId = resolveFromCache( event );
if ( entityId != null ) { if ( entityId != null ) {
if ( traceEnabled ) if ( traceEnabled ) {
LOG.tracev( "Resolved object in cache: {0}", LOG.tracev(
MessageHelper.infoString( persister, event.getNaturalIdValues(), event.getSession().getFactory() ) ); "Resolved object in cache: {0}",
MessageHelper.infoString( persister, event.getNaturalIdValues(), event.getSession().getFactory() )
);
}
return entityId; return entityId;
} }
if ( traceEnabled ) if ( traceEnabled ) {
LOG.tracev( "Object not resolved in any cache: {0}", LOG.tracev(
MessageHelper.infoString( persister, event.getNaturalIdValues(), event.getSession().getFactory() ) ); "Object not resolved in any cache: {0}",
MessageHelper.infoString( persister, event.getNaturalIdValues(), event.getSession().getFactory() )
);
}
return loadFromDatasource( event ); 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.CollectionEntry;
import org.hibernate.engine.spi.CollectionKey; import org.hibernate.engine.spi.CollectionKey;
import org.hibernate.event.spi.EventSource; import org.hibernate.event.spi.EventSource;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.pretty.MessageHelper; import org.hibernate.pretty.MessageHelper;
import org.hibernate.type.CollectionType; import org.hibernate.type.CollectionType;
@ -42,23 +43,21 @@ import org.jboss.logging.Logger;
* @author Gavin King * @author Gavin King
*/ */
public class EvictVisitor extends AbstractVisitor { public class EvictVisitor extends AbstractVisitor {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( EvictVisitor.class );
private static final CoreMessageLogger LOG = Logger.getMessageLogger( CoreMessageLogger.class, EvictVisitor.class.getName() );
EvictVisitor(EventSource session) { EvictVisitor(EventSource session) {
super(session); super(session);
} }
@Override @Override
Object processCollection(Object collection, CollectionType type) Object processCollection(Object collection, CollectionType type) throws HibernateException {
throws HibernateException { if (collection != null) {
evictCollection(collection, type);
if (collection!=null) evictCollection(collection, type); }
return null; return null;
} }
public void evictCollection(Object value, CollectionType type) { public void evictCollection(Object value, CollectionType type) {
final Object pc; final Object pc;
if ( type.hasHolder() ) { if ( type.hasHolder() ) {
pc = getSession().getPersistenceContext().removeCollectionHolder(value); pc = getSession().getPersistenceContext().removeCollectionHolder(value);
@ -71,13 +70,16 @@ public class EvictVisitor extends AbstractVisitor {
} }
PersistentCollection collection = (PersistentCollection) pc; PersistentCollection collection = (PersistentCollection) pc;
if ( collection.unsetSession( getSession() ) ) evictCollection(collection); if ( collection.unsetSession( getSession() ) ) {
evictCollection(collection);
}
} }
private void evictCollection(PersistentCollection collection) { private void evictCollection(PersistentCollection collection) {
CollectionEntry ce = (CollectionEntry) getSession().getPersistenceContext().getCollectionEntries().remove(collection); CollectionEntry ce = (CollectionEntry) getSession().getPersistenceContext().getCollectionEntries().remove(collection);
if ( LOG.isDebugEnabled() ) { if ( LOG.isDebugEnabled() ) {
LOG.debugf( "Evicting collection: %s", LOG.debugf(
"Evicting collection: %s",
MessageHelper.collectionInfoString( ce.getLoadedPersister(), MessageHelper.collectionInfoString( ce.getLoadedPersister(),
collection, collection,
ce.getLoadedKey(), ce.getLoadedKey(),

View File

@ -312,8 +312,9 @@ public class FromElement extends HqlSqlWalkerNode implements DisplayableNode, Pa
} }
public void setIncludeSubclasses(boolean includeSubclasses) { 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" ) ); LOG.trace( "Attempt to disable subclass-inclusions : ", new Exception( "Stack-trace source" ) );
}
this.includeSubclasses = includeSubclasses; this.includeSubclasses = includeSubclasses;
} }

View File

@ -87,7 +87,9 @@ public class ClauseParser implements Parser {
byExpected = true; byExpected = true;
} }
else if ( lcToken.equals( "by" ) ) { 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 ); child.start( q );
byExpected = false; byExpected = false;
} }

View File

@ -73,7 +73,9 @@ public class FromParser implements Parser {
// start by looking for HQL keywords... // start by looking for HQL keywords...
String lcToken = token.toLowerCase(Locale.ROOT); String lcToken = token.toLowerCase(Locale.ROOT);
if ( lcToken.equals( "," ) ) { if ( lcToken.equals( "," ) ) {
if ( !( expectingJoin | expectingAs ) ) throw new QueryException( "unexpected token: ," ); if ( !( expectingJoin | expectingAs ) ) {
throw new QueryException( "unexpected token: ," );
}
expectingJoin = false; expectingJoin = false;
expectingAs = false; expectingAs = false;
} }
@ -90,8 +92,12 @@ public class FromParser implements Parser {
} }
} }
else if ( lcToken.equals( "fetch" ) ) { else if ( lcToken.equals( "fetch" ) ) {
if ( q.isShallowQuery() ) throw new QueryException( QueryTranslator.ERROR_CANNOT_FETCH_WITH_ITERATE ); if ( q.isShallowQuery() ) {
if ( joinType == JoinType.NONE ) throw new QueryException( "unexpected token: fetch" ); 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 ) { 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" ); 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 ) ) { 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 ); joinType = JOIN_TYPES.get( lcToken );
afterJoinType = true; afterJoinType = true;
expectingJoin = false; expectingJoin = false;
expectingAs = false; expectingAs = false;
} }
else if ( lcToken.equals( "class" ) ) { else if ( lcToken.equals( "class" ) ) {
if ( !afterIn ) throw new QueryException( "unexpected token: class" ); if ( !afterIn ) {
if ( joinType != JoinType.NONE ) throw new QueryException( "outer or full join must be followed by path expression" ); 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; afterClass = true;
} }
else if ( lcToken.equals( "in" ) ) { else if ( lcToken.equals( "in" ) ) {
@ -124,18 +136,23 @@ public class FromParser implements Parser {
} }
else if ( !expectingIn ) { else if ( !expectingIn ) {
throw new QueryException( "unexpected token: in" ); throw new QueryException( "unexpected token: in" );
} else { }
else {
afterIn = true; afterIn = true;
expectingIn = false; expectingIn = false;
} }
} }
else if ( lcToken.equals( "as" ) ) { else if ( lcToken.equals( "as" ) ) {
if ( !expectingAs ) throw new QueryException( "unexpected token: as" ); if ( !expectingAs ) {
throw new QueryException( "unexpected token: as" );
}
afterAs = true; afterAs = true;
expectingAs = false; expectingAs = false;
} }
else if ( "(".equals( token ) ){ else if ( "(".equals( token ) ){
if( !memberDeclarations ) throw new QueryException( "unexpected token: (" ); if( !memberDeclarations ) {
throw new QueryException( "unexpected token: (" );
}
//TODO alias should be null here //TODO alias should be null here
expectingPathExpression = true; expectingPathExpression = true;
@ -146,10 +163,15 @@ public class FromParser implements Parser {
afterMemberDeclarations = true; afterMemberDeclarations = true;
} }
else { else {
if ( afterJoinType ) {
if ( afterJoinType ) throw new QueryException( "join expected: " + token ); throw new QueryException( "join expected: " + token );
if ( expectingJoin ) throw new QueryException( "unexpected token: " + token ); }
if ( expectingIn ) throw new QueryException( "in 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 // 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_ // process the "old" HQL style where aliases appear _first_
// ie. using the IN or IN CLASS constructions // 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 ) { if ( afterClass ) {
// treat it as a classname // treat it as a classname
@ -215,7 +241,9 @@ public class FromParser implements Parser {
peParser.setJoinType( JoinType.INNER_JOIN ); peParser.setJoinType( JoinType.INNER_JOIN );
peParser.setUseThetaStyleJoin( false ); peParser.setUseThetaStyleJoin( false );
ParserHelper.parse( peParser, q.unalias( token ), ParserHelper.PATH_SEPARATORS, q ); 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 ); collectionName = peParser.addFromCollection( q );
expectingPathExpression = false; expectingPathExpression = false;
memberDeclarations = false; memberDeclarations = false;
@ -230,7 +258,9 @@ public class FromParser implements Parser {
Queryable p = q.getEntityPersisterUsingImports( token ); Queryable p = q.getEntityPersisterUsingImports( token );
if ( p != null ) { if ( p != null ) {
// starts with the name of a mapped class (new style) // 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() ); entityName = q.createNameFor( p.getEntityName() );
q.addFromClass( entityName, p ); q.addFromClass( entityName, p );
expectingAs = true; expectingAs = true;
@ -293,7 +323,7 @@ public class FromParser implements Parser {
} }
public void end(QueryTranslatorImpl q) { 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, //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. //but it hard to get that info here.
throw new QueryException("alias not specified for IN"); 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 { 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() ); String alias = q.getPathAlias( path.toString() );
if ( alias != null ) { if ( alias != null ) {
@ -148,7 +150,9 @@ public class PathExpressionParser implements Parser {
else { else {
if ( dotcount == 0 ) { if ( dotcount == 0 ) {
if ( !continuation ) { if ( !continuation ) {
if ( !q.isName( token ) ) throw new QueryException( "undefined alias: " + token ); if ( !q.isName( token ) ) {
throw new QueryException( "undefined alias: " + token );
}
currentName = token; currentName = token;
currentPropertyMapping = q.getPropertyMapping( currentName ); currentPropertyMapping = q.getPropertyMapping( currentName );
} }
@ -178,14 +182,18 @@ public class PathExpressionParser implements Parser {
dereferenceComponent( token ); dereferenceComponent( token );
} }
else if ( propertyType.isEntityType() ) { else if ( propertyType.isEntityType() ) {
if ( !isCollectionValued() ) dereferenceEntity( token, ( EntityType ) propertyType, q ); if ( !isCollectionValued() ) {
dereferenceEntity( token, ( EntityType ) propertyType, q );
}
} }
else if ( propertyType.isCollectionType() ) { else if ( propertyType.isCollectionType() ) {
dereferenceCollection( token, ( ( CollectionType ) propertyType ).getRole(), q ); dereferenceCollection( token, ( ( CollectionType ) propertyType ).getRole(), q );
} }
else { 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 //NOTE: we avoid joining to the next table if the named property is just the foreign key value
//if its "id" //if its "id"
boolean isIdShortcut = EntityPersister.ENTITY_ID.equals( propertyName ) && boolean isIdShortcut = EntityPersister.ENTITY_ID.equals( propertyName )
propertyType.isReferenceToPrimaryKey(); && propertyType.isReferenceToPrimaryKey();
//or its the id property name //or its the id property name
final String idPropertyName; final String idPropertyName;
@ -216,7 +224,9 @@ public class PathExpressionParser implements Parser {
if ( isIdShortcut || isNamedIdPropertyShortcut ) { if ( isIdShortcut || isNamedIdPropertyShortcut ) {
// special shortcut for id properties, skip the join! // special shortcut for id properties, skip the join!
// this must only occur at the _end_ of a path expression // 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 ); componentPath.append( propertyName );
} }
else { else {
@ -224,7 +234,9 @@ public class PathExpressionParser implements Parser {
String name = q.createNameFor( entityClass ); String name = q.createNameFor( entityClass );
q.addType( name, entityClass ); q.addType( name, entityClass );
addJoin( name, propertyType ); addJoin( name, propertyType );
if ( propertyType.isOneToOne() ) oneToOneOwnerName = currentName; if ( propertyType.isOneToOne() ) {
oneToOneOwnerName = currentName;
}
ownerAssociationType = propertyType; ownerAssociationType = propertyType;
currentName = name; currentName = name;
currentProperty = propertyName; currentProperty = propertyName;
@ -236,7 +248,9 @@ public class PathExpressionParser implements Parser {
private void dereferenceComponent(String propertyName) { private void dereferenceComponent(String propertyName) {
if ( propertyName != null ) { if ( propertyName != null ) {
if ( componentPath.length() > 0 ) componentPath.append( '.' ); if ( componentPath.length() > 0 ) {
componentPath.append( '.' );
}
componentPath.append( propertyName ); componentPath.append( propertyName );
} }
} }
@ -261,11 +275,7 @@ public class PathExpressionParser implements Parser {
} }
else { else {
if ( componentPath.length() > 0 ) { if ( componentPath.length() > 0 ) {
return new StringBuilder() return currentProperty + '.' + componentPath.toString();
.append( currentProperty )
.append( '.' )
.append( componentPath.toString() )
.toString();
} }
else { else {
return currentProperty; return currentProperty;
@ -351,9 +361,14 @@ public class PathExpressionParser implements Parser {
QueryableCollection collPersister = q.getCollectionPersister( collectionRole ); 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(); 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(); //String[] keyCols = collPersister.getKeyColumnNames();
JoinSequence fromJoins = new JoinSequence( q.getFactory() ) JoinSequence fromJoins = new JoinSequence( q.getFactory() )
@ -361,7 +376,9 @@ public class PathExpressionParser implements Parser {
.setRoot( collPersister, collectionName ) .setRoot( collPersister, collectionName )
.setNext( joinSequence.copy() ); .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 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 unalias(String path) {
String alias = StringHelper.root( path ); String alias = StringHelper.root( path );
String name = getAliasName( alias ); String name = getAliasName( alias );
if (name != null) return name + path.substring(alias.length()); if (name != null) {
return name + path.substring(alias.length());
}
return path; return path;
} }
void addEntityToFetch(String name, String oneToOneOwnerName, AssociationType ownerAssociationType) { void addEntityToFetch(String name, String oneToOneOwnerName, AssociationType ownerAssociationType) {
addEntityToFetch( name ); addEntityToFetch( name );
if ( oneToOneOwnerName != null ) oneToOneOwnerNames.put( name, oneToOneOwnerName ); if ( oneToOneOwnerName != null ) {
if ( ownerAssociationType != null ) uniqueKeyOwnerReferences.put( name, ownerAssociationType ); oneToOneOwnerNames.put( name, oneToOneOwnerName );
}
if ( ownerAssociationType != null ) {
uniqueKeyOwnerReferences.put( name, ownerAssociationType );
}
} }
private void addEntityToFetch(String name) { private void addEntityToFetch(String name) {
@ -387,7 +393,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
PropertyMapping getPropertyMapping(String name) throws QueryException { PropertyMapping getPropertyMapping(String name) throws QueryException {
PropertyMapping decorator = getDecoratedPropertyMapping( name ); PropertyMapping decorator = getDecoratedPropertyMapping( name );
if ( decorator != null ) return decorator; if ( decorator != null ) {
return decorator;
}
String type = getType( name ); String type = getType( name );
if ( type == null ) { if ( type == null ) {
@ -399,7 +407,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
} }
else { else {
Queryable persister = getEntityPersister( type ); 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; return persister;
} }
} }
@ -415,7 +425,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
private Queryable getEntityPersisterForName(String name) throws QueryException { private Queryable getEntityPersisterForName(String name) throws QueryException {
String type = getType( name ); String type = getType( name );
Queryable persister = getEntityPersister( type ); 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; return persister;
} }
@ -525,11 +537,15 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
} }
void addJoin(String name, JoinSequence joinSequence) throws QueryException { 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) { void addNamedParameter(String name) {
if ( superQuery != null ) superQuery.addNamedParameter( name ); if ( superQuery != null ) {
superQuery.addNamedParameter( name );
}
Integer loc = parameterCount++; Integer loc = parameterCount++;
Object o = namedParameters.get( name ); Object o = namedParameters.get( name );
if ( o == null ) { if ( o == null ) {
@ -552,7 +568,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
if ( o == null ) { if ( o == null ) {
throw new QueryException( ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name, queryString ); 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 { else {
return ArrayHelper.toIntArray( ( ArrayList ) o ); return ArrayHelper.toIntArray( ( ArrayList ) o );
} }
@ -588,14 +606,20 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
suffixes[i] = ( size == 1 ) ? "" : Integer.toString( i ) + '_'; suffixes[i] = ( size == 1 ) ? "" : Integer.toString( i ) + '_';
names[i] = name; names[i] = name;
includeInSelect[i] = !entitiesToFetch.contains( name ); includeInSelect[i] = !entitiesToFetch.contains( name );
if ( includeInSelect[i] ) selectLength++; if ( includeInSelect[i] ) {
if ( name.equals( collectionOwnerName ) ) collectionOwnerColumn = i; selectLength++;
}
if ( name.equals( collectionOwnerName ) ) {
collectionOwnerColumn = i;
}
String oneToOneOwner = ( String ) oneToOneOwnerNames.get( name ); String oneToOneOwner = ( String ) oneToOneOwnerNames.get( name );
owners[i] = ( oneToOneOwner == null ) ? -1 : returnedTypes.indexOf( oneToOneOwner ); owners[i] = ( oneToOneOwner == null ) ? -1 : returnedTypes.indexOf( oneToOneOwner );
ownerAssociationTypes[i] = (EntityType) uniqueKeyOwnerReferences.get( name ); 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... 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, "__" ) ); 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 //TODO: for some dialects it would be appropriate to add the renderOrderByPropertiesSelect() to other select strings
mergeJoins( sql.getJoinFragment() ); mergeJoins( sql.getJoinFragment() );
@ -650,7 +676,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
sqlString = sql.toQueryString(); sqlString = sql.toQueryString();
if ( holderClass != null ) holderConstructor = ReflectHelper.getConstructor( holderClass, returnTypes ); if ( holderClass != null ) {
holderConstructor = ReflectHelper.getConstructor( holderClass, returnTypes );
}
if ( hasScalars ) { if ( hasScalars ) {
actualReturnTypes = returnTypes; actualReturnTypes = returnTypes;
@ -726,8 +754,12 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
String[] idColumnNames = persisters[k].getIdentifierColumnNames(); String[] idColumnNames = persisters[k].getIdentifierColumnNames();
for ( int i = 0; i < idColumnNames.length; i++ ) { for ( int i = 0; i < idColumnNames.length; i++ ) {
buf.append( returnedTypes.get( k ) ).append( '.' ).append( idColumnNames[i] ); buf.append( returnedTypes.get( k ) ).append( '.' ).append( idColumnNames[i] );
if ( !isSubselect ) buf.append( " as " ).append( NameGenerator.scalarName( k, i ) ); if ( !isSubselect ) {
if ( i != idColumnNames.length - 1 || k != size - 1 ) buf.append( ", " ); 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 { else {
if ( !isSubselect && parenCount == 0 ) { if ( !isSubselect && parenCount == 0 ) {
int x = c++; int x = c++;
buf.append( " as " ) buf.append( " as " ).append( NameGenerator.scalarName( x, 0 ) );
.append( NameGenerator.scalarName( x, 0 ) );
} }
} }
} }
@ -775,18 +806,18 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
for ( int i = 0; i < tokens.length; i++ ) { for ( int i = 0; i < tokens.length; i++ ) {
buf.append( tokens[i] ); buf.append( tokens[i] );
if ( !isSubselect ) { if ( !isSubselect ) {
buf.append( " as " ) buf.append( " as " ).append( NameGenerator.scalarName( c, i ) );
.append( NameGenerator.scalarName( c, i ) ); }
if ( i != tokens.length - 1 ) {
buf.append( ", " );
} }
if ( i != tokens.length - 1 ) buf.append( ", " );
} }
c++; c++;
} }
} }
if ( !isSubselect && !nolast ) { if ( !isSubselect && !nolast ) {
int x = c++; int x = c++;
buf.append( " as " ) buf.append( " as " ).append( NameGenerator.scalarName( x, 0 ) );
.append( NameGenerator.scalarName( x, 0 ) );
} }
} }
@ -803,8 +834,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
JoinSequence join = ( JoinSequence ) me.getValue(); JoinSequence join = ( JoinSequence ) me.getValue();
join.setSelector( new JoinSequence.Selector() { join.setSelector( new JoinSequence.Selector() {
public boolean includeSubclasses(String alias) { public boolean includeSubclasses(String alias) {
boolean include = returnedTypes.contains( alias ) && !isShallowQuery(); return returnedTypes.contains( alias ) && !isShallowQuery();
return include;
} }
} ); } );
@ -814,10 +844,6 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
else if ( collections.containsKey( name ) ) { else if ( collections.containsKey( name ) ) {
ojf.addFragment( join.toJoinFragment( enabledFilters, true ) ); 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(); boolean stats = session.getFactory().getStatistics().isStatisticsEnabled();
long startTime = 0; long startTime = 0;
if ( stats ) startTime = System.nanoTime(); if ( stats ) {
startTime = System.nanoTime();
}
try { try {
final List<AfterLoadAction> afterLoadActions = new ArrayList<AfterLoadAction>(); 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++ ) { for ( int i = 0; i < names.length; i++ ) {
LockMode lm = ( LockMode ) nameLockOptions.get( names[i] ); LockMode lm = ( LockMode ) nameLockOptions.get( names[i] );
//if ( lm == null ) lm = LockOptions.NONE; //if ( lm == null ) lm = LockOptions.NONE;
if ( lm == null ) lm = lockOptions.getLockMode(); if ( lm == null ) {
lm = lockOptions.getLockMode();
}
lockModesArray[i] = lm; lockModesArray[i] = lm;
} }
return lockModesArray; return lockModesArray;
@ -1170,11 +1200,12 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
return enabledFilters; return enabledFilters;
} }
public ScrollableResults scroll(final QueryParameters queryParameters, public ScrollableResults scroll(
final SessionImplementor session) final QueryParameters queryParameters,
throws HibernateException { final SessionImplementor session) throws HibernateException {
HolderInstantiator hi = HolderInstantiator.createClassicHolderInstantiator( HolderInstantiator hi = HolderInstantiator.createClassicHolderInstantiator(
holderConstructor, queryParameters.getResultTransformer() holderConstructor,
queryParameters.getResultTransformer()
); );
return scroll( queryParameters, returnTypes, hi, session ); return scroll( queryParameters, returnTypes, hi, session );
} }

View File

@ -45,7 +45,7 @@ public class SelectParser implements Parser {
//TODO: arithmetic expressions, multiple new Foo(...) //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 { static {
COUNT_MODIFIERS.add( "distinct" ); COUNT_MODIFIERS.add( "distinct" );
@ -53,7 +53,7 @@ public class SelectParser implements Parser {
COUNT_MODIFIERS.add( "*" ); COUNT_MODIFIERS.add( "*" );
} }
private LinkedList aggregateFuncTokenList = new LinkedList(); private LinkedList<String> aggregateFuncTokenList = new LinkedList<String>();
private boolean ready; private boolean ready;
private boolean aggregate; private boolean aggregate;
@ -75,7 +75,6 @@ public class SelectParser implements Parser {
} }
public void token(String token, QueryTranslatorImpl q) throws QueryException { public void token(String token, QueryTranslatorImpl q) throws QueryException {
String lctoken = token.toLowerCase(Locale.ROOT); String lctoken = token.toLowerCase(Locale.ROOT);
if ( first ) { if ( first ) {
@ -98,12 +97,16 @@ public class SelectParser implements Parser {
catch ( ClassNotFoundException cnfe ) { catch ( ClassNotFoundException cnfe ) {
throw new QueryException( 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 ); q.setHolderClass( holderClass );
insideNew = true; insideNew = true;
} }
else if ( token.equals( "," ) ) { 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( ", " ); q.appendScalarSelectToken( ", " );
ready = true; ready = true;
} }
@ -175,7 +178,9 @@ public class SelectParser implements Parser {
} }
else if ( aggregate ) { else if ( aggregate ) {
boolean constantToken = false; 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 { try {
ParserHelper.parse( aggregatePathExpressionParser, q.unalias( token ), ParserHelper.PATH_SEPARATORS, q ); ParserHelper.parse( aggregatePathExpressionParser, q.unalias( token ), ParserHelper.PATH_SEPARATORS, q );
} }
@ -200,7 +205,9 @@ public class SelectParser implements Parser {
} }
} }
else { 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 ); ParserHelper.parse( pathExpressionParser, q.unalias( token ), ParserHelper.PATH_SEPARATORS, q );
if ( pathExpressionParser.isCollectionValued() ) { if ( pathExpressionParser.isCollectionValued() ) {
q.addCollection( pathExpressionParser.getCollectionName(), 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! 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<String> EXPRESSION_TERMINATORS = new HashSet<String>(); //tokens that close a sub expression
private static final Set EXPRESSION_OPENERS = new HashSet(); //tokens that open a sub expression private static final Set<String> EXPRESSION_OPENERS = new HashSet<String>(); //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 Set<String> BOOLEAN_OPERATORS = new HashSet<String>(); //tokens that would indicate a sub expression is a boolean expression
private static final Map NEGATIONS = new HashMap(); private static final Map<String,String> NEGATIONS = new HashMap<String,String>();
static { static {
EXPRESSION_TERMINATORS.add( "and" ); EXPRESSION_TERMINATORS.add( "and" );
@ -188,7 +188,7 @@ public class WhereParser implements Parser {
// in the list of nested subexpressions we are currently processing. // 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<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 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 { 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 { public void token(String token, QueryTranslatorImpl q) throws QueryException {
String lcToken = token.toLowerCase(Locale.ROOT); String lcToken = token.toLowerCase(Locale.ROOT);
//Cope with [,] //Cope with [,]
if ( token.equals( "[" ) && !expectingPathContinuation ) { if ( token.equals( "[" ) && !expectingPathContinuation ) {
expectingPathContinuation = false; expectingPathContinuation = false;
if ( expectingIndex == 0 ) throw new QueryException( "unexpected [" ); if ( expectingIndex == 0 ) {
throw new QueryException( "unexpected [" );
}
return; return;
} }
else if ( token.equals( "]" ) ) { else if ( token.equals( "]" ) ) {
@ -228,7 +229,9 @@ public class WhereParser implements Parser {
//Cope with a continued path expression (ie. ].baz) //Cope with a continued path expression (ie. ].baz)
if ( expectingPathContinuation ) { if ( expectingPathContinuation ) {
boolean pathExpressionContinuesFurther = continuePathExpression( token, q ); boolean pathExpressionContinuesFurther = continuePathExpression( token, q );
if ( pathExpressionContinuesFurther ) return; //NOTE: early return if ( pathExpressionContinuesFurther ) {
return; //NOTE: early return
}
} }
//Cope with a subselect //Cope with a subselect
@ -257,7 +260,9 @@ public class WhereParser implements Parser {
} }
} }
if ( inSubselect ) { if ( inSubselect ) {
if ( token.equals( "(" ) ) bracketsSinceSelect++; if ( token.equals( "(" ) ) {
bracketsSinceSelect++;
}
subselect.append( token ).append( ' ' ); subselect.append( token ).append( ' ' );
return; return;
} }
@ -303,7 +308,9 @@ public class WhereParser implements Parser {
if ( expectingPathContinuation ) { if ( expectingPathContinuation ) {
expectingPathContinuation = false; expectingPathContinuation = false;
PathExpressionParser.CollectionElement element = pathExpressionParser.lastCollectionElement(); 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] ); appendToken( q, element.elementColumns[0] );
addToCurrentJoin( element ); addToCurrentJoin( element );
} }
@ -324,20 +331,26 @@ public class WhereParser implements Parser {
} }
else { else {
StringBuilder join = ( StringBuilder ) joins.removeLast(); StringBuilder join = joins.removeLast();
( ( StringBuilder ) joins.getLast() ).append( join.toString() ); 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) { private void openExpression(QueryTranslatorImpl q, String lcToken) {
nots.addLast( Boolean.FALSE ); nots.addLast( Boolean.FALSE );
booleanTests.addLast( Boolean.FALSE ); booleanTests.addLast( Boolean.FALSE );
joins.addLast( new StringBuilder() ); joins.addLast( new StringBuilder() );
if ( !"(".equals( lcToken ) ) appendToken( q, "(" ); if ( !"(".equals( lcToken ) ) {
appendToken( q, "(" );
}
} }
private void preprocess(String token, QueryTranslatorImpl q) throws QueryException { 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 ); if ( type == null ) throw new QueryException( QueryTranslator.ERROR_CANNOT_DETERMINE_TYPE + token );
try { try {
//noinspection unchecked
appendToken( q, ( ( LiteralType ) type ).objectToSQLString( constant, q.getFactory().getDialect() ) ); appendToken( q, ( ( LiteralType ) type ).objectToSQLString( constant, q.getFactory().getDialect() ) );
} }
catch ( Exception e ) { catch ( Exception e ) {
@ -442,7 +456,7 @@ public class WhereParser implements Parser {
} }
else { //anything else 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 ) ) ) { if ( negatedToken != null && ( !betweenSpecialCase || !"or".equals( negatedToken ) ) ) {
appendToken( q, negatedToken ); appendToken( q, negatedToken );
} }
@ -455,7 +469,7 @@ public class WhereParser implements Parser {
} }
private void addToCurrentJoin(String sql) { private void addToCurrentJoin(String sql) {
( ( StringBuilder ) joins.getLast() ).append( sql ); joins.getLast().append( sql );
} }
private void addToCurrentJoin(PathExpressionParser.CollectionElement ce) private void addToCurrentJoin(PathExpressionParser.CollectionElement ce)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -45,7 +45,6 @@ import org.jboss.logging.Logger;
* @author Steve Ebersole * @author Steve Ebersole
*/ */
public final class ConfigHelper { public final class ConfigHelper {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, ConfigHelper.class.getName()); 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 /** Try to locate a local URL representing the incoming path. The first attempt
@ -82,13 +81,15 @@ public final class ConfigHelper {
if (contextClassLoader!=null) { if (contextClassLoader!=null) {
url = contextClassLoader.getResource(path); url = contextClassLoader.getResource(path);
} }
if (url != null) if (url != null) {
return url; return url;
}
// Next, try to locate this resource through this class's classloader // Next, try to locate this resource through this class's classloader
url = ConfigHelper.class.getClassLoader().getResource(path); url = ConfigHelper.class.getClassLoader().getResource(path);
if (url != null) if (url != null) {
return url; return url;
}
// Next, try to locate this resource through the system classloader // Next, try to locate this resource through the system classloader
url = ClassLoader.getSystemClassLoader().getResource(path); url = ClassLoader.getSystemClassLoader().getResource(path);
@ -155,8 +156,9 @@ public final class ConfigHelper {
private ConfigHelper() {} private ConfigHelper() {}
public static InputStream getResourceAsStream(String resource) { public static InputStream getResourceAsStream(String resource) {
String stripped = resource.startsWith("/") ? String stripped = resource.startsWith("/")
resource.substring(1) : resource; ? resource.substring(1)
: resource;
InputStream stream = null; InputStream stream = null;
ClassLoader classLoader = ClassLoaderHelper.getContextClassLoader(); 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.EntityKey;
import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.TypedValue; import org.hibernate.engine.spi.TypedValue;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.type.Type; import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/** /**
* Renders entities and query parameters to a nicely readable string. * Renders entities and query parameters to a nicely readable string.
* @author Gavin King * @author Gavin King
*/ */
public final class EntityPrinter { public final class EntityPrinter {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( EntityPrinter.class );
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, EntityPrinter.class.getName());
private SessionFactoryImplementor factory; private SessionFactoryImplementor factory;
@ -100,9 +98,9 @@ public final class EntityPrinter {
for ( Map.Entry<String, TypedValue> entry : namedTypedValues.entrySet() ) { for ( Map.Entry<String, TypedValue> entry : namedTypedValues.entrySet() ) {
result.put( result.put(
entry.getKey(), entry.getValue().getType().toLoggableString( entry.getKey(), entry.getValue().getType().toLoggableString(
entry.getValue().getValue(), entry.getValue().getValue(),
factory factory
) )
); );
} }
return result.toString(); 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) // 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 { 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:" ); LOG.debug( "Listing entities:" );
int i=0; int i=0;
for ( Map.Entry<EntityKey,Object> entityKeyAndEntity : entitiesByEntityKey ) { for ( Map.Entry<EntityKey,Object> entityKeyAndEntity : entitiesByEntityKey ) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -65,7 +65,6 @@ public abstract class BatchingEntityLoader implements UniqueEntityLoader {
} }
@Override @Override
@Deprecated
public Object load(Serializable id, Object optionalObject, SessionImplementor session) { public Object load(Serializable id, Object optionalObject, SessionImplementor session) {
return load( id, optionalObject, session, LockOptions.NONE ); 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. * A factory class for creating a {@link org.hibernate.loader.plan.exec.spi.LoadQueryDetails} object.
*/ */
public class BatchingLoadQueryDetailsFactory { 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() { private BatchingLoadQueryDetailsFactory() {
} }
@ -53,7 +58,7 @@ public class BatchingLoadQueryDetailsFactory {
* *
* @return The EntityLoadQueryDetails * @return The EntityLoadQueryDetails
*/ */
public static LoadQueryDetails makeEntityLoadQueryDetails( public LoadQueryDetails makeEntityLoadQueryDetails(
LoadPlan loadPlan, LoadPlan loadPlan,
String[] keyColumnNames, String[] keyColumnNames,
QueryBuildingParameters buildingParameters, QueryBuildingParameters buildingParameters,
@ -90,7 +95,7 @@ public class BatchingLoadQueryDetailsFactory {
* *
* @return The EntityLoadQueryDetails * @return The EntityLoadQueryDetails
*/ */
public static LoadQueryDetails makeCollectionLoadQueryDetails( public LoadQueryDetails makeCollectionLoadQueryDetails(
CollectionPersister collectionPersister, CollectionPersister collectionPersister,
LoadPlan loadPlan, LoadPlan loadPlan,
QueryBuildingParameters buildingParameters) { QueryBuildingParameters buildingParameters) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -64,7 +64,9 @@ public abstract class IndexedCollection extends Collection {
boolean isFormula = false; boolean isFormula = false;
Iterator iter = getIndex().getColumnIterator(); Iterator iter = getIndex().getColumnIterator();
while ( iter.hasNext() ) { while ( iter.hasNext() ) {
if ( ( (Selectable) iter.next() ).isFormula() ) isFormula=true; if ( ( (Selectable) iter.next() ).isFormula() ) {
isFormula=true;
}
} }
if (isFormula) { if (isFormula) {
//if it is a formula index, use the element columns in the PK //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(); Iterator iter = getPropertyIterator();
while ( iter.hasNext() ) { while ( iter.hasNext() ) {
Property prop = (Property) iter.next(); Property prop = (Property) iter.next();
if ( !prop.isLazy() ) return false; if ( !prop.isLazy() ) {
return false;
}
} }
return true; return true;
} }

View File

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

View File

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

View File

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

View File

@ -346,12 +346,15 @@ public class RootClass extends PersistentClass implements TableOwner {
return synchronizedTables; return synchronizedTables;
} }
public Set getIdentityTables() { @SuppressWarnings("UnnecessaryUnboxing")
Set tables = new HashSet(); public Set<Table> getIdentityTables() {
Set<Table> tables = new HashSet<Table>();
Iterator iter = getSubclassClosureIterator(); Iterator iter = getSubclassClosureIterator();
while ( iter.hasNext() ) { while ( iter.hasNext() ) {
PersistentClass clazz = (PersistentClass) iter.next(); 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; return tables;
} }

View File

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

View File

@ -46,88 +46,88 @@ public interface ClassMetadata {
/** /**
* The name of the entity * The name of the entity
*/ */
public String getEntityName(); String getEntityName();
/** /**
* Get the name of the identifier property (or return null) * Get the name of the identifier property (or return null)
*/ */
public String getIdentifierPropertyName(); String getIdentifierPropertyName();
/** /**
* Get the names of the class' persistent properties * Get the names of the class' persistent properties
*/ */
public String[] getPropertyNames(); String[] getPropertyNames();
/** /**
* Get the identifier Hibernate type * Get the identifier Hibernate type
*/ */
public Type getIdentifierType(); Type getIdentifierType();
/** /**
* Get the Hibernate types of the class properties * Get the Hibernate types of the class properties
*/ */
public Type[] getPropertyTypes(); Type[] getPropertyTypes();
/** /**
* Get the type of a particular (named) property * 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? * Does this class support dynamic proxies?
*/ */
public boolean hasProxy(); boolean hasProxy();
/** /**
* Are instances of this class mutable? * Are instances of this class mutable?
*/ */
public boolean isMutable(); boolean isMutable();
/** /**
* Are instances of this class versioned by a timestamp or version number column? * 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 * Get the index of the version property
*/ */
public int getVersionProperty(); int getVersionProperty();
/** /**
* Get the nullability of the class' persistent properties * Get the nullability of the class' persistent properties
*/ */
public boolean[] getPropertyNullability(); boolean[] getPropertyNullability();
/** /**
* Get the "laziness" of the properties of this class * Get the "laziness" of the properties of this class
*/ */
public boolean[] getPropertyLaziness(); boolean[] getPropertyLaziness();
/** /**
* Does this class have an identifier property? * Does this class have an identifier property?
*/ */
public boolean hasIdentifierProperty(); boolean hasIdentifierProperty();
/** /**
* Does this entity declare a natural id? * Does this entity declare a natural id?
*/ */
public boolean hasNaturalIdentifier(); boolean hasNaturalIdentifier();
/** /**
* Which properties hold the natural id? * Which properties hold the natural id?
*/ */
public int[] getNaturalIdentifierProperties(); int[] getNaturalIdentifierProperties();
/** /**
* Does this entity have mapped subclasses? * Does this entity have mapped subclasses?
*/ */
public boolean hasSubclasses(); boolean hasSubclasses();
/** /**
* Does this entity extend a mapped superclass? * Does this entity extend a mapped superclass?
*/ */
public boolean isInherited(); boolean isInherited();
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// stuff that is tuplizer-centric, but is passed a session ~~~~~~~~~~~~~~~~ // 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 * Return the values of the mapped properties of the object
*/ */
@SuppressWarnings( {"UnusedDeclaration"}) @SuppressWarnings( {"UnusedDeclaration"})
public Object[] getPropertyValuesToInsert(Object entity, Map mergeMap, SessionImplementor session) Object[] getPropertyValuesToInsert(Object entity, Map mergeMap, SessionImplementor session)
throws HibernateException; throws HibernateException;
@ -148,7 +148,7 @@ public interface ClassMetadata {
/** /**
* The persistent class, or null * The persistent class, or null
*/ */
public Class getMappedClass(); Class getMappedClass();
/** /**
* Create a class instance initialized with the given identifier * Create a class instance initialized with the given identifier
@ -158,12 +158,12 @@ public interface ClassMetadata {
* *
* @return The instantiated entity. * @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 * 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. * Extract the property values from the given entity.
@ -172,25 +172,26 @@ public interface ClassMetadata {
* @return The property values. * @return The property values.
* @throws HibernateException * @throws HibernateException
*/ */
public Object[] getPropertyValues(Object entity) throws HibernateException; Object[] getPropertyValues(Object entity) throws HibernateException;
/** /**
* Set the value of a particular (named) property * 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 * 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) * Get the identifier of an instance (throw an exception if no identifier property)
* *
* @deprecated Use {@link #getIdentifier(Object,SessionImplementor)} instead * @deprecated Use {@link #getIdentifier(Object,SessionImplementor)} instead
*/ */
@Deprecated
@SuppressWarnings( {"JavaDoc"}) @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) * Get the identifier of an instance (throw an exception if no identifier property)
@ -200,7 +201,7 @@ public interface ClassMetadata {
* *
* @return The identifier * @return The identifier
*/ */
public Serializable getIdentifier(Object entity, SessionImplementor session); Serializable getIdentifier(Object entity, SessionImplementor session);
/** /**
* Inject the identifier value into the given entity. * 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 id The value to be injected as the identifier.
* @param session The session from which is requests originates * @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? * Does the class implement the <tt>Lifecycle</tt> interface?
*/ */
@SuppressWarnings( {"UnusedDeclaration"}) @SuppressWarnings( {"UnusedDeclaration"})
public boolean implementsLifecycle(); boolean implementsLifecycle();
/** /**
* Get the version number (or timestamp) from the object's version property * Get the version number (or timestamp) from the object's version property
* (or return null if not versioned) * (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() { protected void logStaticSQL() {
if ( LOG.isDebugEnabled() ) { if ( LOG.isDebugEnabled() ) {
LOG.debugf( "Static SQL for collection: %s", getRole() ); LOG.debugf( "Static SQL for collection: %s", getRole() );
if ( getSQLInsertRowString() != null ) LOG.debugf( " Row insert: %s", getSQLInsertRowString() ); if ( getSQLInsertRowString() != null ) {
if ( getSQLUpdateRowString() != null ) LOG.debugf( " Row update: %s", getSQLUpdateRowString() ); LOG.debugf( " Row insert: %s", getSQLInsertRowString() );
if ( getSQLDeleteRowString() != null ) LOG.debugf( " Row delete: %s", getSQLDeleteRowString() ); }
if ( getSQLDeleteString() != null ) LOG.debugf( " One-shot delete: %s", getSQLDeleteString() ); 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 @Override
protected String generateDeleteString() { protected String generateDeleteString() {
final Delete delete = new Delete()
Delete delete = new Delete()
.setTableName( qualifiedTableName ) .setTableName( qualifiedTableName )
.addPrimaryKeyColumns( keyColumnNames ); .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() ); delete.setComment( "delete collection " + getRole() );
} }
@ -99,18 +100,19 @@ public class BasicCollectionPersister extends AbstractCollectionPersister {
*/ */
@Override @Override
protected String generateInsertRowString() { protected String generateInsertRowString() {
final Insert insert = new Insert( getDialect() )
Insert insert = new Insert( getDialect() )
.setTableName( qualifiedTableName ) .setTableName( qualifiedTableName )
.addColumns( keyColumnNames ); .addColumns( keyColumnNames );
if ( hasIdentifier) insert.addColumn( identifierColumnName ); if ( hasIdentifier) {
insert.addColumn( identifierColumnName );
}
if ( hasIndex /*&& !indexIsFormula*/ ) { if ( hasIndex /*&& !indexIsFormula*/ ) {
insert.addColumns( indexColumnNames, indexColumnIsSettable ); insert.addColumns( indexColumnNames, indexColumnIsSettable );
} }
if ( getFactory().getSettings().isCommentsEnabled() ) { if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
insert.setComment( "insert collection row " + getRole() ); insert.setComment( "insert collection row " + getRole() );
} }
@ -126,8 +128,7 @@ public class BasicCollectionPersister extends AbstractCollectionPersister {
*/ */
@Override @Override
protected String generateUpdateRowString() { protected String generateUpdateRowString() {
final Update update = new Update( getDialect() )
Update update = new Update( getDialect() )
.setTableName( qualifiedTableName ); .setTableName( qualifiedTableName );
//if ( !elementIsFormula ) { //if ( !elementIsFormula ) {
@ -145,7 +146,7 @@ public class BasicCollectionPersister extends AbstractCollectionPersister {
update.addPrimaryKeyColumns( elementColumnNames, elementColumnIsInPrimaryKey, elementColumnWriters ); update.addPrimaryKeyColumns( elementColumnNames, elementColumnIsInPrimaryKey, elementColumnWriters );
} }
if ( getFactory().getSettings().isCommentsEnabled() ) { if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
update.setComment( "update collection row " + getRole() ); update.setComment( "update collection row " + getRole() );
} }
@ -163,9 +164,7 @@ public class BasicCollectionPersister extends AbstractCollectionPersister {
*/ */
@Override @Override
protected String generateDeleteRowString() { protected String generateDeleteRowString() {
final Delete delete = new Delete().setTableName( qualifiedTableName );
Delete delete = new Delete()
.setTableName( qualifiedTableName );
if ( hasIdentifier ) { if ( hasIdentifier ) {
delete.addPrimaryKeyColumns( new String[]{ identifierColumnName } ); delete.addPrimaryKeyColumns( new String[]{ identifierColumnName } );
@ -178,7 +177,7 @@ public class BasicCollectionPersister extends AbstractCollectionPersister {
delete.addPrimaryKeyColumns( elementColumnNames, elementColumnIsInPrimaryKey, elementColumnWriters ); delete.addPrimaryKeyColumns( elementColumnNames, elementColumnIsInPrimaryKey, elementColumnWriters );
} }
if ( getFactory().getSettings().isCommentsEnabled() ) { if ( getFactory().getSessionFactoryOptions().isCommentsEnabled() ) {
delete.setComment( "delete collection row " + getRole() ); delete.setComment( "delete collection row " + getRole() );
} }
@ -206,10 +205,10 @@ public class BasicCollectionPersister extends AbstractCollectionPersister {
private BasicBatchKey updateBatchKey; private BasicBatchKey updateBatchKey;
@Override @Override
protected int doUpdateRows(Serializable id, PersistentCollection collection, SessionImplementor session) protected int doUpdateRows(Serializable id, PersistentCollection collection, SessionImplementor session) throws HibernateException {
throws HibernateException { if ( ArrayHelper.isAllFalse(elementColumnIsSettable) ) {
return 0;
if ( ArrayHelper.isAllFalse(elementColumnIsSettable) ) return 0; }
try { try {
PreparedStatement st = null; PreparedStatement st = null;
@ -261,8 +260,7 @@ public class BasicCollectionPersister extends AbstractCollectionPersister {
} }
if ( useBatch ) { if ( useBatch ) {
session session.getJdbcCoordinator()
.getJdbcCoordinator()
.getBatch( updateBatchKey ) .getBatch( updateBatchKey )
.addToBatch(); .addToBatch();
} }
@ -293,7 +291,7 @@ public class BasicCollectionPersister extends AbstractCollectionPersister {
sqle, sqle,
"could not update collection rows: " + MessageHelper.collectionInfoString( this, collection, id, session ), "could not update collection rows: " + MessageHelper.collectionInfoString( this, collection, id, session ),
getSQLUpdateRowString() getSQLUpdateRowString()
); );
} }
} }

View File

@ -32,7 +32,6 @@ import org.hibernate.type.Type;
* @author Gavin King * @author Gavin King
*/ */
public class CollectionPropertyMapping implements PropertyMapping { public class CollectionPropertyMapping implements PropertyMapping {
private final QueryableCollection memberPersister; private final QueryableCollection memberPersister;
public CollectionPropertyMapping(QueryableCollection memberPersister) { public CollectionPropertyMapping(QueryableCollection memberPersister) {
@ -73,7 +72,9 @@ public class CollectionPropertyMapping implements PropertyMapping {
return memberPersister.getElementColumnNames(alias); return memberPersister.getElementColumnNames(alias);
} }
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_INDICES) ) { 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); return memberPersister.getIndexColumnNames(alias);
} }
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_SIZE) ) { else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_SIZE) ) {
@ -81,25 +82,37 @@ public class CollectionPropertyMapping implements PropertyMapping {
return new String[] { "count(" + alias + '.' + cols[0] + ')' }; return new String[] { "count(" + alias + '.' + cols[0] + ')' };
} }
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MAX_INDEX) ) { 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); 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] + ')' }; return new String[] { "max(" + cols[0] + ')' };
} }
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MIN_INDEX) ) { 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); 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] + ')' }; return new String[] { "min(" + cols[0] + ')' };
} }
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MAX_ELEMENT) ) { else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MAX_ELEMENT) ) {
String[] cols = memberPersister.getElementColumnNames(alias); 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] + ')' }; return new String[] { "max(" + cols[0] + ')' };
} }
else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MIN_ELEMENT) ) { else if ( propertyName.equals(CollectionPropertyNames.COLLECTION_MIN_ELEMENT) ) {
String[] cols = memberPersister.getElementColumnNames(alias); 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] + ')' }; return new String[] { "min(" + cols[0] + ')' };
} }
else { else {

View File

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

View File

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

View File

@ -30,6 +30,7 @@ import java.util.Map;
import org.hibernate.MappingException; import org.hibernate.MappingException;
import org.hibernate.QueryException; import org.hibernate.QueryException;
import org.hibernate.engine.spi.Mapping; import org.hibernate.engine.spi.Mapping;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.StringHelper; import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.ArrayHelper; import org.hibernate.internal.util.collections.ArrayHelper;
@ -47,9 +48,7 @@ import org.jboss.logging.Logger;
* @author Gavin King * @author Gavin King
*/ */
public abstract class AbstractPropertyMapping implements PropertyMapping { public abstract class AbstractPropertyMapping implements PropertyMapping {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( AbstractPropertyMapping.class );
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class,
AbstractPropertyMapping.class.getName());
private final Map typesByPropertyPath = new HashMap(); private final Map typesByPropertyPath = new HashMap();
private final Map columnsByPropertyPath = 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() ) { if ( type.isComponentType() ) {
CompositeType actype = (CompositeType) type; CompositeType actype = (CompositeType) type;

View File

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

View File

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

View File

@ -415,7 +415,9 @@ public class UnionSubclassEntityPersister extends AbstractEntityPersister {
Table table = (Table) titer.next(); Table table = (Table) titer.next();
if ( !table.isAbstractUnionTable() ) { if ( !table.isAbstractUnionTable() ) {
Iterator citer = table.getColumnIterator(); 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) { 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(); return getIdentifierColumnNames();
} }
public String getSubclassTableName(int j) { 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; return tableName;
} }
@ -482,7 +488,9 @@ public class UnionSubclassEntityPersister extends AbstractEntityPersister {
} }
protected boolean isClassOrSuperclassTable(int j) { 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; return true;
} }
@ -492,7 +500,7 @@ public class UnionSubclassEntityPersister extends AbstractEntityPersister {
} }
public String[] getConstraintOrderedTableNameClosure() { public String[] getConstraintOrderedTableNameClosure() {
return constraintOrderedTableNames; return constraintOrderedTableNames;
} }
public String[][] getContraintOrderedTableKeyColumnClosure() { public String[][] getContraintOrderedTableKeyColumnClosure() {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -273,6 +273,9 @@ public final class PropertyFactory {
} }
} }
/**
* @deprecated See mainly {@link #buildEntityBasedAttribute}
*/
@Deprecated @Deprecated
public static StandardProperty buildStandardProperty(Property property, boolean lazyAvailable) { public static StandardProperty buildStandardProperty(Property property, boolean lazyAvailable) {
final Type type = property.getValue().getType(); 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. * Represents a non-identifier property within the Hibernate runtime-metamodel.
* *
* @author Steve Ebersole * @author Steve Ebersole
*
* @deprecated Use one of the {@link org.hibernate.tuple.Attribute}-based impls instead.
*/ */
@Deprecated @Deprecated
public class StandardProperty extends AbstractNonIdentifierAttribute implements NonIdentifierAttribute { public class StandardProperty extends AbstractNonIdentifierAttribute implements NonIdentifierAttribute {

View File

@ -241,7 +241,9 @@ public class EntityMetamodel implements Serializable {
// temporary ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // temporary ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
boolean lazy = prop.isLazy() && instrumentationMetadata.isInstrumented(); boolean lazy = prop.isLazy() && instrumentationMetadata.isInstrumented();
if ( lazy ) hasLazy = true; if ( lazy ) {
hasLazy = true;
}
propertyLaziness[i] = lazy; propertyLaziness[i] = lazy;
propertyNames[i] = properties[i].getName(); propertyNames[i] = properties[i].getName();
@ -330,7 +332,9 @@ public class EntityMetamodel implements Serializable {
hasNonIdentifierPropertyNamedId = foundNonIdentifierPropertyNamedId; hasNonIdentifierPropertyNamedId = foundNonIdentifierPropertyNamedId;
versionPropertyIndex = tempVersionProperty; versionPropertyIndex = tempVersionProperty;
hasLazyProperties = hasLazy; hasLazyProperties = hasLazy;
if (hasLazyProperties) LOG.lazyPropertyFetchingAvailable(name); if (hasLazyProperties) {
LOG.lazyPropertyFetchingAvailable(name);
}
lazy = persistentClass.isLazy() && ( lazy = persistentClass.isLazy() && (
// TODO: this disables laziness even in non-pojo entity modes: // 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 * @return The entity-mode
*/ */
public EntityMode getEntityMode(); EntityMode getEntityMode();
/** /**
* Create an entity instance initialized with the given identifier. * 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 Use {@link #instantiate(Serializable, SessionImplementor)} instead.
*/ */
@Deprecated
@SuppressWarnings( {"JavaDoc"}) @SuppressWarnings( {"JavaDoc"})
public Object instantiate(Serializable id) throws HibernateException; Object instantiate(Serializable id) throws HibernateException;
/** /**
* Create an entity instance initialized with the given identifier. * Create an entity instance initialized with the given identifier.
@ -73,7 +74,7 @@ public interface EntityTuplizer extends Tuplizer {
* *
* @return The instantiated entity. * @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. * Extract the identifier value from the given entity.
@ -87,7 +88,8 @@ public interface EntityTuplizer extends Tuplizer {
* *
* @deprecated Use {@link #getIdentifier(Object,SessionImplementor)} instead. * @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. * Extract the identifier value from the given entity.
@ -97,7 +99,7 @@ public interface EntityTuplizer extends Tuplizer {
* *
* @return The identifier value. * @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. * 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 Use {@link #setIdentifier(Object, Serializable, SessionImplementor)} instead.
*/ */
@Deprecated
@SuppressWarnings( {"JavaDoc"}) @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. * 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 id The value to be injected as the identifier.
* @param session The session from which is requests originates * @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 * 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 Use {@link #resetIdentifier(Object, Serializable, Object, SessionImplementor)} instead
*/ */
@Deprecated
@SuppressWarnings( {"UnusedDeclaration"}) @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 * 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 currentVersion The version value to inject into the entity.
* @param session The session from which the request originated * @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. * 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. * @return The value of the version property, or null if not versioned.
* @throws HibernateException Indicates a problem accessing the version property * @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. * Inject the value of a particular property.
@ -164,7 +168,7 @@ public interface EntityTuplizer extends Tuplizer {
* @param value The property value to inject. * @param value The property value to inject.
* @throws HibernateException Indicates a problem access the property * @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. * Inject the value of a particular property.
@ -174,7 +178,7 @@ public interface EntityTuplizer extends Tuplizer {
* @param value The property value to inject. * @param value The property value to inject.
* @throws HibernateException Indicates a problem access the property * @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) * 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. * @return The insertable property values.
* @throws HibernateException Indicates a problem access the properties * @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; throws HibernateException;
/** /**
@ -196,7 +200,7 @@ public interface EntityTuplizer extends Tuplizer {
* @return The current value of the given property on the given entity. * @return The current value of the given property on the given entity.
* @throws HibernateException Indicates a problem access the property * @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. * 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 lazyPropertiesAreUnfetched Are defined lazy properties currently unfecthed
* @param session The session initializing this entity. * @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? * Does this entity, for this mode, present a possibility for proxying?
* *
* @return True if this tuplizer can generate proxies for this entity. * @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 * Generates an appropriate proxy representation of this entity for this
@ -223,7 +227,7 @@ public interface EntityTuplizer extends Tuplizer {
* @return The generate proxies. * @return The generate proxies.
* @throws HibernateException Indicates an error generating the proxy. * @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 * 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. * @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. * 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 * @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? * 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. * @param entity The entity to be check for uninitialized lazy properties.
* @return True if uninitialized lazy properties were found; false otherwise. * @return True if uninitialized lazy properties were found; false otherwise.
*/ */
public boolean hasUninitializedLazyProperties(Object entity); boolean hasUninitializedLazyProperties(Object entity);
/** /**
* Is it an instrumented POJO? * Is it an instrumented POJO?
* *
* @return {@code true} if the entity class is instrumented; {@code false} otherwise. * @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}. * Get any {@link EntityNameResolver EntityNameResolvers} associated with this {@link Tuplizer}.
* *
* @return The associated resolvers. May be null or empty. * @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. * 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. * @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. * Retrieve the getter for the identifier property. May return null.
* *
* @return The getter for the identifier property. * @return The getter for the identifier property.
*/ */
public Getter getIdentifierGetter(); Getter getIdentifierGetter();
/** /**
* Retrieve the getter for the version property. May return null. * Retrieve the getter for the version property. May return null.
* *
* @return The getter for the version property. * @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 * @author Brett Meyer
*/ */
public abstract class AbstractStandardBasicType<T> 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 static final Size DEFAULT_SIZE = new Size( 19, 2, 255, Size.LobMultiplier.NONE ); // to match legacy behavior
private final Size dictatedSize = new Size(); private final Size dictatedSize = new Size();
@ -85,14 +85,6 @@ public abstract class AbstractStandardBasicType<T>
return fromString( xml ); 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() { protected MutabilityPlan<T> getMutabilityPlan() {
return javaTypeDescriptor.getMutabilityPlan(); return javaTypeDescriptor.getMutabilityPlan();
} }

View File

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

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