HHH-9803 - Checkstyle fix ups

This commit is contained in:
Steve Ebersole 2015-05-18 01:48:38 -05:00
parent 42bb59354f
commit bbfacee64d
147 changed files with 3216 additions and 3198 deletions

View File

@ -26,7 +26,6 @@ package org.hibernate;
import java.io.Serializable;
import java.util.Iterator;
import org.hibernate.resource.jdbc.spi.StatementInspector;
import org.hibernate.type.Type;
/**
@ -71,7 +70,7 @@ public interface Interceptor {
*
* @throws CallbackException Thrown if the interceptor encounters any problems handling the callback.
*/
public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException;
boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException;
/**
* Called when an object is detected to be dirty, during a flush. The interceptor may modify the detected
@ -94,7 +93,13 @@ public interface Interceptor {
*
* @throws CallbackException Thrown if the interceptor encounters any problems handling the callback.
*/
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException;
boolean onFlushDirty(
Object entity,
Serializable id,
Object[] currentState,
Object[] previousState,
String[] propertyNames,
Type[] types) throws CallbackException;
/**
* Called before an object is saved. The interceptor may modify the <tt>state</tt>, which will be used for
@ -110,7 +115,7 @@ public interface Interceptor {
*
* @throws CallbackException Thrown if the interceptor encounters any problems handling the callback.
*/
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException;
boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException;
/**
* Called before an object is deleted. It is not recommended that the interceptor modify the <tt>state</tt>.
@ -123,7 +128,7 @@ public interface Interceptor {
*
* @throws CallbackException Thrown if the interceptor encounters any problems handling the callback.
*/
public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException;
void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException;
/**
* Called before a collection is (re)created.
@ -133,7 +138,7 @@ public interface Interceptor {
*
* @throws CallbackException Thrown if the interceptor encounters any problems handling the callback.
*/
public void onCollectionRecreate(Object collection, Serializable key) throws CallbackException;
void onCollectionRecreate(Object collection, Serializable key) throws CallbackException;
/**
* Called before a collection is deleted.
@ -143,7 +148,7 @@ public interface Interceptor {
*
* @throws CallbackException Thrown if the interceptor encounters any problems handling the callback.
*/
public void onCollectionRemove(Object collection, Serializable key) throws CallbackException;
void onCollectionRemove(Object collection, Serializable key) throws CallbackException;
/**
* Called before a collection is updated.
@ -153,7 +158,7 @@ public interface Interceptor {
*
* @throws CallbackException Thrown if the interceptor encounters any problems handling the callback.
*/
public void onCollectionUpdate(Object collection, Serializable key) throws CallbackException;
void onCollectionUpdate(Object collection, Serializable key) throws CallbackException;
/**
* Called before a flush.
@ -162,7 +167,7 @@ public interface Interceptor {
*
* @throws CallbackException Thrown if the interceptor encounters any problems handling the callback.
*/
public void preFlush(Iterator entities) throws CallbackException;
void preFlush(Iterator entities) throws CallbackException;
/**
* Called after a flush that actually ends in execution of the SQL statements required to synchronize
@ -172,7 +177,7 @@ public interface Interceptor {
*
* @throws CallbackException Thrown if the interceptor encounters any problems handling the callback.
*/
public void postFlush(Iterator entities) throws CallbackException;
void postFlush(Iterator entities) throws CallbackException;
/**
* Called to distinguish between transient and detached entities. The return value determines the
@ -186,7 +191,7 @@ public interface Interceptor {
* @param entity a transient or detached entity
* @return Boolean or <tt>null</tt> to choose default behaviour
*/
public Boolean isTransient(Object entity);
Boolean isTransient(Object entity);
/**
* Called from <tt>flush()</tt>. The return value determines whether the entity is updated
@ -207,7 +212,13 @@ public interface Interceptor {
*
* @throws CallbackException Thrown if the interceptor encounters any problems handling the callback.
*/
public int[] findDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types);
int[] findDirty(
Object entity,
Serializable id,
Object[] currentState,
Object[] previousState,
String[] propertyNames,
Type[] types);
/**
* Instantiate the entity class. Return <tt>null</tt> to indicate that Hibernate should use
* the default constructor of the class. The identifier property of the returned instance
@ -221,7 +232,7 @@ public interface Interceptor {
*
* @throws CallbackException Thrown if the interceptor encounters any problems handling the callback.
*/
public Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException;
Object instantiate(String entityName, EntityMode entityMode, Serializable id) throws CallbackException;
/**
* Get the entity name for a persistent or transient instance.
@ -232,7 +243,7 @@ public interface Interceptor {
*
* @throws CallbackException Thrown if the interceptor encounters any problems handling the callback.
*/
public String getEntityName(Object object) throws CallbackException;
String getEntityName(Object object) throws CallbackException;
/**
* Get a fully loaded entity instance that is cached externally.
@ -244,7 +255,7 @@ public interface Interceptor {
*
* @throws CallbackException Thrown if the interceptor encounters any problems handling the callback.
*/
public Object getEntity(String entityName, Serializable id) throws CallbackException;
Object getEntity(String entityName, Serializable id) throws CallbackException;
/**
* Called when a Hibernate transaction is begun via the Hibernate <tt>Transaction</tt>
@ -253,21 +264,21 @@ public interface Interceptor {
*
* @param tx The Hibernate transaction facade object
*/
public void afterTransactionBegin(Transaction tx);
void afterTransactionBegin(Transaction tx);
/**
* Called before a transaction is committed (but not before rollback).
*
* @param tx The Hibernate transaction facade object
*/
public void beforeTransactionCompletion(Transaction tx);
void beforeTransactionCompletion(Transaction tx);
/**
* Called after a transaction is committed or rolled back.
*
* @param tx The Hibernate transaction facade object
*/
public void afterTransactionCompletion(Transaction tx);
void afterTransactionCompletion(Transaction tx);
/**
* Called when sql string is being prepared.
@ -278,5 +289,5 @@ public interface Interceptor {
* to inspect and alter SQL statements.
*/
@Deprecated
public String onPrepareStatement(String sql);
String onPrepareStatement(String sql);
}

View File

@ -25,8 +25,6 @@ package org.hibernate;
import javax.transaction.Synchronization;
import org.hibernate.engine.transaction.spi.IsolationDelegate;
import org.hibernate.engine.transaction.spi.LocalStatus;
import org.hibernate.resource.transaction.spi.TransactionStatus;
/**
@ -53,16 +51,16 @@ public interface Transaction {
*
* @throws HibernateException Indicates a problem beginning the transaction.
*/
public void begin();
void begin();
/**
* Commit this transaction. This might entail a number of things depending on the context:<ul>
* <li>
* If this transaction is the {@link #isInitiator initiator}, {@link Session#flush} the {@link Session}
* with which it is associated (unless {@link Session} is in {@link FlushMode#MANUAL}).
* If the underlying transaction was initiated from this Transaction the Session will be flushed,
* unless the Session is in {@link FlushMode#MANUAL} FlushMode.
* </li>
* <li>
* If this transaction is the {@link #isInitiator initiator}, commit the underlying transaction.
* If the underlying transaction was initiated from this Transaction, commit the underlying transaction.
* </li>
* <li>
* Coordinate various callbacks
@ -71,7 +69,7 @@ public interface Transaction {
*
* @throws HibernateException Indicates a problem committing the transaction.
*/
public void commit();
void commit();
/**
* Rollback this transaction. Either rolls back the underlying transaction or ensures it cannot later commit
@ -79,7 +77,7 @@ public interface Transaction {
*
* @throws HibernateException Indicates a problem rolling back the transaction.
*/
public void rollback();
void rollback();
/**
* Get the current local status of this transaction.
@ -89,7 +87,7 @@ public interface Transaction {
*
* @return The current local status.
*/
public TransactionStatus getStatus();
TransactionStatus getStatus();
/**
* Register a user synchronization callback for this transaction.
@ -98,25 +96,25 @@ public interface Transaction {
*
* @throws HibernateException Indicates a problem registering the synchronization.
*/
public void registerSynchronization(Synchronization synchronization) throws HibernateException;
void registerSynchronization(Synchronization synchronization) throws HibernateException;
/**
* Set the transaction timeout for any transaction started by a subsequent call to {@link #begin} on this instance.
*
* @param seconds The number of seconds before a timeout.
*/
public void setTimeout(int seconds);
void setTimeout(int seconds);
/**
* Retrieve the transaction timeout set for this transaction. A negative indicates no timeout has been set.
*
* @return The timeout, in seconds.
*/
public int getTimeout();
int getTimeout();
/**
* Make a best effort to mark the underlying transaction for rollback only.
*/
public void markRollbackOnly();
void markRollbackOnly();
}

View File

@ -23,7 +23,6 @@
*/
package org.hibernate.boot;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.internal.util.StringHelper;
@ -36,35 +35,41 @@ public enum SchemaAutoTooling {
/**
* Drop the schema and recreate it on SessionFactory startup.
*/
CREATE,
CREATE( "create" ),
/**
* Drop the schema and recreate it on SessionFactory startup. Additionally, drop the
* schema on SessionFactory shutdown.
*/
CREATE_DROP,
CREATE_DROP( "create-drop" ),
/**
* Update (alter) the schema on SessionFactory startup.
*/
UPDATE,
UPDATE( "update" ),
/**
* Validate the schema on SessionFactory startup.
*/
VALIDATE;
VALIDATE( "validate" );
private final String externalForm;
SchemaAutoTooling(String externalForm) {
this.externalForm = externalForm;
}
public static SchemaAutoTooling interpret(String configurationValue) {
if ( StringHelper.isEmpty( configurationValue ) ) {
return null;
}
else if ( "validate".equals( configurationValue ) ) {
else if ( VALIDATE.externalForm.equals( configurationValue ) ) {
return VALIDATE;
}
else if ( "update".equals( configurationValue ) ) {
else if ( UPDATE.externalForm.equals( configurationValue ) ) {
return UPDATE;
}
else if ( "create".equals( configurationValue ) ) {
else if ( CREATE.externalForm.equals( configurationValue ) ) {
return CREATE;
}
else if ( "create-drop".equals( configurationValue ) ) {
else if ( CREATE_DROP.externalForm.equals( configurationValue ) ) {
return CREATE_DROP;
}
else {

View File

@ -35,7 +35,6 @@ import org.hibernate.boot.archive.scan.spi.ScanOptions;
import org.hibernate.boot.archive.scan.spi.ScanParameters;
import org.hibernate.boot.archive.scan.spi.ScanResult;
import org.jboss.jandex.ClassInfo;
import org.jboss.logging.Logger;
/**

View File

@ -26,7 +26,6 @@ package org.hibernate.boot.internal;
import java.lang.reflect.Constructor;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.persistence.Converter;

View File

@ -31,33 +31,45 @@ import java.util.List;
* @author Steve Ebersole
*/
public interface EntityInfo extends ToolingHintContainer {
public String getName();
public String getEntityName();
String getName();
public Boolean isAbstract();
public Boolean isLazy();
public String getProxy();
public int getBatchSize();
public boolean isDynamicInsert();
public boolean isDynamicUpdate();
public boolean isSelectBeforeUpdate();
String getEntityName();
public List<JaxbHbmTuplizerType> getTuplizer();
public String getPersister();
Boolean isAbstract();
public JaxbHbmLoaderType getLoader();
public JaxbHbmCustomSqlDmlType getSqlInsert();
public JaxbHbmCustomSqlDmlType getSqlUpdate();
public JaxbHbmCustomSqlDmlType getSqlDelete();
Boolean isLazy();
public List<JaxbHbmSynchronizeType> getSynchronize();
String getProxy();
public List<JaxbHbmFetchProfileType> getFetchProfile();
int getBatchSize();
public List<JaxbHbmResultSetMappingType> getResultset();
boolean isDynamicInsert();
public List<JaxbHbmNamedNativeQueryType> getSqlQuery();
public List<JaxbHbmNamedQueryType> getQuery();
boolean isDynamicUpdate();
public List getAttributes();
boolean isSelectBeforeUpdate();
List<JaxbHbmTuplizerType> getTuplizer();
String getPersister();
JaxbHbmLoaderType getLoader();
JaxbHbmCustomSqlDmlType getSqlInsert();
JaxbHbmCustomSqlDmlType getSqlUpdate();
JaxbHbmCustomSqlDmlType getSqlDelete();
List<JaxbHbmSynchronizeType> getSynchronize();
List<JaxbHbmFetchProfileType> getFetchProfile();
List<JaxbHbmResultSetMappingType> getResultset();
List<JaxbHbmNamedNativeQueryType> getSqlQuery();
List<JaxbHbmNamedQueryType> getQuery();
List getAttributes();
}

View File

@ -31,41 +31,59 @@ import java.util.List;
* @author Steve Ebersole
*/
public interface PluralAttributeInfo extends AttributeMapping, TableInformationContainer, ToolingHintContainer {
public JaxbHbmKeyType getKey();
JaxbHbmKeyType getKey();
public JaxbHbmBasicCollectionElementType getElement();
public JaxbHbmCompositeCollectionElementType getCompositeElement();
public JaxbHbmOneToManyCollectionElementType getOneToMany();
public JaxbHbmManyToManyCollectionElementType getManyToMany();
public JaxbHbmManyToAnyCollectionElementType getManyToAny();
JaxbHbmBasicCollectionElementType getElement();
public String getComment();
public String getCheck();
public String getWhere();
JaxbHbmCompositeCollectionElementType getCompositeElement();
public JaxbHbmLoaderType getLoader();
public JaxbHbmCustomSqlDmlType getSqlInsert();
public JaxbHbmCustomSqlDmlType getSqlUpdate();
public JaxbHbmCustomSqlDmlType getSqlDelete();
public JaxbHbmCustomSqlDmlType getSqlDeleteAll();
JaxbHbmOneToManyCollectionElementType getOneToMany();
public List<JaxbHbmSynchronizeType> getSynchronize();
JaxbHbmManyToManyCollectionElementType getManyToMany();
public JaxbHbmCacheType getCache();
public List<JaxbHbmFilterType> getFilter();
JaxbHbmManyToAnyCollectionElementType getManyToAny();
public String getCascade();
public JaxbHbmFetchStyleWithSubselectEnum getFetch();
public JaxbHbmLazyWithExtraEnum getLazy();
public JaxbHbmOuterJoinEnum getOuterJoin();
String getComment();
public int getBatchSize();
public boolean isInverse();
public boolean isMutable();
public boolean isOptimisticLock();
String getCheck();
public String getCollectionType();
public String getPersister();
String getWhere();
JaxbHbmLoaderType getLoader();
JaxbHbmCustomSqlDmlType getSqlInsert();
JaxbHbmCustomSqlDmlType getSqlUpdate();
JaxbHbmCustomSqlDmlType getSqlDelete();
JaxbHbmCustomSqlDmlType getSqlDeleteAll();
List<JaxbHbmSynchronizeType> getSynchronize();
JaxbHbmCacheType getCache();
List<JaxbHbmFilterType> getFilter();
String getCascade();
JaxbHbmFetchStyleWithSubselectEnum getFetch();
JaxbHbmLazyWithExtraEnum getLazy();
JaxbHbmOuterJoinEnum getOuterJoin();
int getBatchSize();
boolean isInverse();
boolean isMutable();
boolean isOptimisticLock();
String getCollectionType();
String getPersister();
// todo : not available on all. do we need a specific interface for these?
// public String getSort();

View File

@ -29,5 +29,5 @@ package org.hibernate.boot.jaxb.hbm.spi;
* @author Steve Ebersole
*/
public interface SubEntityInfo extends EntityInfo {
public String getExtends();
String getExtends();
}

View File

@ -49,9 +49,9 @@ import org.hibernate.internal.util.compare.EqualsHelper;
*/
public class TypeDefinition implements Serializable {
private final String name;
private final Class typeImplementorClass;
private final Class typeImplementorClass;
private final String[] registrationKeys;
private final Map<String, String> parameters;
private final Map<String, String> parameters;
public TypeDefinition(
String name,
@ -108,8 +108,8 @@ public class TypeDefinition implements Serializable {
}
public Map<String, String> getParameters() {
return parameters;
}
return parameters;
}
public Properties getParametersAsProperties() {
Properties properties = new Properties();

View File

@ -66,7 +66,6 @@ import org.hibernate.internal.util.StringHelper;
import org.hibernate.internal.util.collections.CollectionHelper;
import org.hibernate.internal.util.compare.EqualsHelper;
/**
* @author Steve Ebersole
* @author Hardy Ferentschik
@ -530,9 +529,8 @@ public abstract class AbstractEntitySourceImpl
}
@Override
@SuppressWarnings( {"unchecked"})
public List<JpaCallbackSource> getJpaCallbackClasses() {
return Collections.EMPTY_LIST;
return Collections.emptyList();
}
@Override

View File

@ -41,21 +41,21 @@ class ColumnAttributeSourceImpl
private final String tableName;
private final String columnName;
private final SizeSource sizeSource;
private final TruthValue nullable;
private final TruthValue unique;
private final TruthValue nullable;
private final TruthValue unique;
ColumnAttributeSourceImpl(
ColumnAttributeSourceImpl(
MappingDocument mappingDocument,
String tableName,
String columnName,
SizeSource sizeSource,
TruthValue nullable,
TruthValue nullable,
TruthValue unique) {
super( mappingDocument );
this.tableName = tableName;
this.columnName = columnName;
this.sizeSource = sizeSource;
this.nullable = nullable;
this.nullable = nullable;
this.unique = unique;
}

View File

@ -64,13 +64,13 @@ class ColumnSourceImpl
ColumnSourceImpl(
MappingDocument mappingDocument,
String tableName,
String tableName,
JaxbHbmColumnType columnElement,
TruthValue nullable) {
TruthValue nullable) {
super( mappingDocument );
this.tableName = tableName;
this.columnElement = columnElement;
this.nullable = nullable;
this.tableName = tableName;
this.columnElement = columnElement;
this.nullable = nullable;
}
@Override

View File

@ -97,7 +97,7 @@ public class Helper {
return new Caching( TruthValue.FALSE );
}
final boolean cacheLazyProps = cacheElement.getInclude() == null
final boolean cacheLazyProps = cacheElement.getInclude() == null
|| !"non-lazy".equals( cacheElement.getInclude().value() );
return new Caching(

View File

@ -35,7 +35,7 @@ import org.hibernate.boot.model.source.spi.TableSpecificationSource;
* @author Steve Ebersole
*/
public class SubclassEntitySourceImpl extends AbstractEntitySourceImpl implements SubclassEntitySource {
private final EntitySource container;
private final EntitySource container;
private final TableSpecificationSource primaryTable;
protected SubclassEntitySourceImpl(

View File

@ -41,5 +41,5 @@ public interface CompositeIdentifierSource extends IdentifierSource, EmbeddableS
*
* @return The generator for the named attribute (within the composite).
*/
public IdentifierGeneratorDefinition getIndividualAttributeIdGenerator(String identifierAttributeName);
}
IdentifierGeneratorDefinition getIndividualAttributeIdGenerator(String identifierAttributeName);
}

View File

@ -30,5 +30,5 @@ import org.hibernate.boot.model.naming.ImplicitBasicColumnNameSource;
*/
public interface VersionAttributeSource
extends SingularAttributeSource, RelationalValueSourceContainer, ImplicitBasicColumnNameSource {
public String getUnsavedValue();
}
String getUnsavedValue();
}

View File

@ -53,7 +53,6 @@ import org.hibernate.exception.LockAcquisitionException;
import org.hibernate.exception.LockTimeoutException;
import org.hibernate.exception.SQLGrammarException;
import org.hibernate.exception.spi.SQLExceptionConversionDelegate;
import org.hibernate.hql.spi.id.IdTableSupport;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy;
@ -84,8 +83,7 @@ public abstract class AbstractHANADialect extends Dialect {
@Override
public String processSql(String sql, RowSelection selection) {
final boolean hasOffset = LimitHelper.hasFirstRow( selection );
return new StringBuilder( sql.length() + 20 ).append( sql )
.append( hasOffset ? " limit ? offset ?" : " limit ?" ).toString();
return sql + ( hasOffset ? " limit ? offset ?" : " limit ?" );
}
@Override

View File

@ -31,7 +31,6 @@ import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.dialect.pagination.CUBRIDLimitHandler;
import org.hibernate.dialect.pagination.LimitHandler;
import org.hibernate.engine.spi.RowSelection;
import org.hibernate.type.StandardBasicTypes;
/**

View File

@ -28,7 +28,6 @@ import java.sql.Types;
import java.util.Locale;
import org.hibernate.MappingException;
import org.hibernate.boot.TempTableDdlTransactionHandling;
import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.dialect.pagination.FirstLimitHandler;
import org.hibernate.dialect.pagination.LimitHandler;

View File

@ -41,7 +41,6 @@ import org.hibernate.engine.spi.RowSelection;
import org.hibernate.exception.LockAcquisitionException;
import org.hibernate.exception.LockTimeoutException;
import org.hibernate.exception.spi.SQLExceptionConversionDelegate;
import org.hibernate.hql.spi.id.IdTableSupport;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;

View File

@ -26,43 +26,41 @@ package org.hibernate.dialect;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.pagination.LimitHandler;
import org.hibernate.dialect.pagination.SQL2008StandardLimitHandler;
import org.hibernate.engine.spi.RowSelection;
/**
* An SQL dialect for Oracle 12c.
*
*
* @author zhouyanming (zhouyanming@gmail.com)
*/
public class Oracle12cDialect extends Oracle10gDialect {
public Oracle12cDialect() {
super();
}
public Oracle12cDialect() {
super();
}
@Override
protected void registerDefaultProperties() {
super.registerDefaultProperties();
getDefaultProperties().setProperty( Environment.USE_GET_GENERATED_KEYS, "true" );
}
@Override
public boolean supportsIdentityColumns() {
return true;
}
@Override
protected void registerDefaultProperties() {
super.registerDefaultProperties();
getDefaultProperties().setProperty( Environment.USE_GET_GENERATED_KEYS, "true" );
}
@Override
public boolean supportsInsertSelectIdentity() {
return true;
}
@Override
public boolean supportsIdentityColumns() {
return true;
}
@Override
public String getIdentityColumnString() {
return "generated as identity";
}
@Override
public boolean supportsInsertSelectIdentity() {
return true;
}
@Override
public LimitHandler getLimitHandler() {
return SQL2008StandardLimitHandler.INSTANCE;
}
@Override
public String getIdentityColumnString() {
return "generated as identity";
}
@Override
public LimitHandler getLimitHandler() {
return SQL2008StandardLimitHandler.INSTANCE;
}
}

View File

@ -31,7 +31,6 @@ import java.sql.Types;
import org.hibernate.JDBCException;
import org.hibernate.LockOptions;
import org.hibernate.PessimisticLockException;
import org.hibernate.boot.TempTableDdlTransactionHandling;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.function.NoArgSQLFunction;
import org.hibernate.dialect.function.PositionSubstringFunction;

View File

@ -32,7 +32,6 @@ import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy;
import org.hibernate.internal.util.StringHelper;

View File

@ -33,7 +33,6 @@ import org.hibernate.QueryTimeoutException;
import org.hibernate.dialect.function.NoArgSQLFunction;
import org.hibernate.dialect.pagination.LimitHandler;
import org.hibernate.dialect.pagination.SQLServer2005LimitHandler;
import org.hibernate.engine.spi.RowSelection;
import org.hibernate.exception.LockTimeoutException;
import org.hibernate.exception.spi.SQLExceptionConversionDelegate;
import org.hibernate.internal.util.JdbcExceptionHelper;
@ -89,16 +88,17 @@ public class SQLServer2005Dialect extends SQLServerDialect {
final boolean isNoWait = lockOptions.getTimeOut() == LockOptions.NO_WAIT;
final String noWaitStr = isNoWait ? ", nowait" : "";
switch ( mode ) {
case UPGRADE_NOWAIT:
return tableName + " with (updlock, rowlock, nowait)";
case UPGRADE:
case PESSIMISTIC_WRITE:
case WRITE:
case WRITE: {
return tableName + " with (updlock, rowlock" + noWaitStr + " )";
case PESSIMISTIC_READ:
}
case PESSIMISTIC_READ: {
return tableName + " with (holdlock, rowlock" + noWaitStr + " )";
default:
}
default: {
return tableName;
}
}
}

View File

@ -23,10 +23,10 @@
*/
package org.hibernate.dialect;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.internal.util.StringHelper;
/**
* Microsoft SQL Server 2012 Dialect
*
@ -68,26 +68,29 @@ public class SQLServer2012Dialect extends SQLServer2008Dialect {
public String getQuerySequencesString() {
return "select name from sys.sequences";
}
@Override
public String getQueryHintString(String sql, List<String> hints) {
final String hint = StringHelper.join(", ", hints.iterator());
final String hint = StringHelper.join( ", ", hints.iterator() );
if (StringHelper.isEmpty(hint)) {
if ( StringHelper.isEmpty( hint ) ) {
return sql;
}
final StringBuilder buffer = new StringBuilder(sql.length()
+ hint.length() + 12);
final int pos = sql.indexOf(";");
if (pos > -1) {
buffer.append(sql.substring(0, pos));
} else {
buffer.append(sql);
final StringBuilder buffer = new StringBuilder(
sql.length()
+ hint.length() + 12
);
final int pos = sql.indexOf( ";" );
if ( pos > -1 ) {
buffer.append( sql.substring( 0, pos ) );
}
buffer.append(" OPTION (").append(hint).append(")");
if (pos > -1) {
buffer.append(";");
else {
buffer.append( sql );
}
buffer.append( " OPTION (" ).append( hint ).append( ")" );
if ( pos > -1 ) {
buffer.append( ";" );
}
sql = buffer.toString();

View File

@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.dialect;
import org.hibernate.HibernateException;
import org.hibernate.LockOptions;
import org.hibernate.cfg.Environment;
@ -36,9 +37,9 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Map;
/**
* A dialect for the Teradata database
*
*/
public class Teradata14Dialect extends TeradataDialect {
/**
@ -53,7 +54,7 @@ public class Teradata14Dialect extends TeradataDialect {
registerColumnType( Types.LONGVARCHAR, "VARCHAR(32000)" );
getDefaultProperties().setProperty( Environment.USE_STREAMS_FOR_BINARY, "true" );
getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE,DEFAULT_BATCH_SIZE );
getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, DEFAULT_BATCH_SIZE );
registerFunction( "current_time", new SQLFunctionTemplate( StandardBasicTypes.TIME, "current_time" ) );
registerFunction( "current_date", new SQLFunctionTemplate( StandardBasicTypes.DATE, "current_date" ) );
@ -82,14 +83,14 @@ public class Teradata14Dialect extends TeradataDialect {
*
* @throws HibernateException
*/
public String getTypeName(int code, int length, int precision, int scale) throws HibernateException {
public String getTypeName(int code, int length, int precision, int scale) throws HibernateException {
/*
* We might want a special case for 19,2. This is very common for money types
* and here it is converted to 18,1
*/
float f = precision > 0 ? ( float ) scale / ( float ) precision : 0;
float f = precision > 0 ? (float) scale / (float) precision : 0;
int p = ( precision > 38 ? 38 : precision );
int s = ( precision > 38 ? ( int ) ( 38.0 * f ) : ( scale > 38 ? 38 : scale ) );
int s = ( precision > 38 ? (int) ( 38.0 * f ) : ( scale > 38 ? 38 : scale ) );
return super.getTypeName( code, length, p, s );
}
@ -138,7 +139,7 @@ public class Teradata14Dialect extends TeradataDialect {
@Override
public int registerResultSetOutParameter(CallableStatement statement, int col) throws SQLException {
statement.registerOutParameter(col, Types.REF);
statement.registerOutParameter( col, Types.REF );
col++;
return col;
}
@ -146,7 +147,7 @@ public class Teradata14Dialect extends TeradataDialect {
@Override
public ResultSet getResultSet(CallableStatement cs) throws SQLException {
boolean isResultSet = cs.execute();
while (!isResultSet && cs.getUpdateCount() != -1) {
while ( !isResultSet && cs.getUpdateCount() != -1 ) {
isResultSet = cs.getMoreResults();
}
return cs.getResultSet();
@ -164,18 +165,20 @@ public class Teradata14Dialect extends TeradataDialect {
String constraintName = null;
int errorCode = sqle.getErrorCode();
if (errorCode == 27003) {
constraintName = extractUsingTemplate("Unique constraint (", ") violated.", sqle.getMessage());
} else if (errorCode == 2700) {
constraintName = extractUsingTemplate("Referential constraint", "violation:", sqle.getMessage());
} else if (errorCode == 5317) {
constraintName = extractUsingTemplate("Check constraint (", ") violated.", sqle.getMessage());
if ( errorCode == 27003 ) {
constraintName = extractUsingTemplate( "Unique constraint (", ") violated.", sqle.getMessage() );
}
else if ( errorCode == 2700 ) {
constraintName = extractUsingTemplate( "Referential constraint", "violation:", sqle.getMessage() );
}
else if ( errorCode == 5317 ) {
constraintName = extractUsingTemplate( "Check constraint (", ") violated.", sqle.getMessage() );
}
if (constraintName != null) {
int i = constraintName.indexOf('.');
if (i != -1) {
constraintName = constraintName.substring(i + 1);
if ( constraintName != null ) {
int i = constraintName.indexOf( '.' );
if ( i != -1 ) {
constraintName = constraintName.substring( i + 1 );
}
}
return constraintName;

View File

@ -276,4 +276,4 @@ public class TeradataDialect extends Dialect implements IdTableSupport {
public int getInExpressionCountLimit() {
return PARAM_LIST_SIZE_LIMIT;
}
}
}

View File

@ -43,7 +43,6 @@ import org.hibernate.hql.spi.id.IdTableSupportStandardImpl;
import org.hibernate.hql.spi.id.MultiTableBulkIdStrategy;
import org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy;
import org.hibernate.hql.spi.id.local.AfterUseAction;
import org.hibernate.hql.spi.id.local.LocalTemporaryTableBulkIdStrategy;
import org.hibernate.persister.entity.Lockable;
import org.hibernate.sql.JoinFragment;
import org.hibernate.sql.OracleJoinFragment;

View File

@ -97,7 +97,7 @@ public class BatchingBatch extends AbstractBatchImpl {
notifyObserversImplicitExecution();
performExecution();
batchPosition = 0;
batchExecuted = true;
batchExecuted = true;
}
statementPosition = 0;
}

View File

@ -298,6 +298,7 @@ public class DriverManagerConnectionProviderImpl
}
//CHECKSTYLE:START_ALLOW_FINALIZER
@Override
protected void finalize() throws Throwable {
if ( active ) {
@ -305,5 +306,6 @@ public class DriverManagerConnectionProviderImpl
}
super.finalize();
}
//CHECKSTYLE:END_ALLOW_FINALIZER
}

View File

@ -30,7 +30,6 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Set;
import org.hibernate.engine.jdbc.cursor.internal.StandardRefCursorSupport;
@ -39,7 +38,6 @@ import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.jdbc.env.spi.SQLStateType;
import org.hibernate.engine.jdbc.spi.TypeInfo;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.mapping.Collection;
/**
* Standard implementation of ExtractedDatabaseMetaData

View File

@ -44,7 +44,7 @@ public class ResultSetReturnImpl implements ResultSetReturn {
private final Dialect dialect;
private final SqlStatementLogger sqlStatementLogger;
private final SqlExceptionHelper sqlExceptionHelper;
private boolean isJdbc4 = true;
/**
@ -69,7 +69,7 @@ public class ResultSetReturnImpl implements ResultSetReturn {
@Override
public ResultSet extract(PreparedStatement statement) {
// IMPL NOTE : SQL logged by caller
if (isTypeOf(statement, CallableStatement.class)) {
if ( isTypeOf( statement, CallableStatement.class ) ) {
// We actually need to extract from Callable statement. Although
// this seems needless, Oracle can return an
// OracleCallableStatementWrapper that finds its way to this method,
@ -103,23 +103,23 @@ public class ResultSetReturnImpl implements ResultSetReturn {
}
private boolean isTypeOf(final Statement statement, final Class<? extends Statement> type) {
if (isJdbc4) {
try {
// This is "more correct" than #isInstance, but not always supported.
return statement.isWrapperFor( type );
}
catch (SQLException e) {
// No operation
}
catch (Throwable e) {
// No operation. Note that this catches more than just SQLException to
// cover edge cases where a driver might throw an UnsupportedOperationException, AbstractMethodError,
// etc. If so, skip permanently.
isJdbc4 = false;
}
}
return type.isInstance( statement );
}
if ( isJdbc4 ) {
try {
// This is "more correct" than #isInstance, but not always supported.
return statement.isWrapperFor( type );
}
catch (SQLException e) {
// No operation
}
catch (Throwable e) {
// No operation. Note that this catches more than just SQLException to
// cover edge cases where a driver might throw an UnsupportedOperationException, AbstractMethodError,
// etc. If so, skip permanently.
isJdbc4 = false;
}
}
return type.isInstance( statement );
}
@Override
public ResultSet extract(CallableStatement callableStatement) {
@ -210,7 +210,7 @@ public class ResultSetReturnImpl implements ResultSetReturn {
throw sqlExceptionHelper.convert( e, "could not execute statement" );
}
}
@Override
public int executeUpdate(PreparedStatement statement) {
try {
@ -224,7 +224,7 @@ public class ResultSetReturnImpl implements ResultSetReturn {
jdbcExecuteStatementEnd();
}
}
@Override
public int executeUpdate(Statement statement, String sql) {
sqlStatementLogger.logStatement( sql );

View File

@ -95,7 +95,7 @@ public class SqlExceptionHelper {
* @param sqlExceptionConverter The converter to use.
*/
public void setSqlExceptionConverter(SQLExceptionConverter sqlExceptionConverter) {
this.sqlExceptionConverter = (sqlExceptionConverter == null ? DEFAULT_CONVERTER : sqlExceptionConverter);
this.sqlExceptionConverter = ( sqlExceptionConverter == null ? DEFAULT_CONVERTER : sqlExceptionConverter );
}
// SQLException ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -154,13 +154,13 @@ public class SqlExceptionHelper {
/**
* Contract for handling {@link SQLWarning warnings}
*/
public static interface WarningHandler {
public interface WarningHandler {
/**
* Should processing be done? Allows short-circuiting if not.
*
* @return True to process warnings, false otherwise.
*/
public boolean doProcess();
boolean doProcess();
/**
* Prepare for processing of a {@link SQLWarning warning} stack.
@ -169,14 +169,14 @@ public class SqlExceptionHelper {
*
* @param warning The first warning in the stack.
*/
public void prepare(SQLWarning warning);
void prepare(SQLWarning warning);
/**
* Handle an individual warning in the stack.
*
* @param warning The warning to handle.
*/
public void handleWarning(SQLWarning warning);
void handleWarning(SQLWarning warning);
}
/**
@ -237,7 +237,9 @@ public class SqlExceptionHelper {
/**
* Static access to the standard handler for logging warnings
*/
public static final StandardWarningHandler STANDARD_WARNING_HANDLER = new StandardWarningHandler( DEFAULT_WARNING_MSG );
public static final StandardWarningHandler STANDARD_WARNING_HANDLER = new StandardWarningHandler(
DEFAULT_WARNING_MSG
);
/**
* Generic algorithm to walk the hierarchy of SQLWarnings
@ -268,7 +270,7 @@ public class SqlExceptionHelper {
public void logAndClearWarnings(Connection connection) {
handleAndClearWarnings( connection, STANDARD_WARNING_HANDLER );
}
public void logAndClearWarnings(Statement statement) {
handleAndClearWarnings( statement, STANDARD_WARNING_HANDLER );
}
@ -314,16 +316,16 @@ public class SqlExceptionHelper {
Statement statement,
WarningHandler handler) {
// See HHH-9174. Statement#getWarnings can be an expensive call for many JDBC libs. Don't do it unless
// the log level would actually allow a warning to be logged.
if (LOG.isEnabled(Level.WARN)) {
try {
// the log level would actually allow a warning to be logged.
if ( LOG.isEnabled( Level.WARN ) ) {
try {
walkWarnings( statement.getWarnings(), handler );
}
catch (SQLException sqlException) {
// workaround for WebLogic
LOG.debug( "could not log warnings", sqlException );
}
}
}
try {
// Sybase fail if we don't do that, sigh...
statement.clearWarnings();

View File

@ -138,7 +138,8 @@ public class EntityGraphQueryHint {
queryableCollection, collectionType.getRole(), JoinType.LEFT_OUTER_JOIN, true, false
);
}
} else {
}
else {
explicitFromElement = true;
fromElement.setInProjectionList( true );
fromElement.setFetch( true );

View File

@ -166,7 +166,8 @@ public class QueryPlanCache implements Serializable {
LOG.tracev( "Unable to locate HQL query plan in cache; generating ({0})", queryString );
value = new HQLQueryPlan( queryString, shallow, enabledFilters, factory );
queryPlanCache.putIfAbsent( key, value );
} else {
}
else {
LOG.tracev( "Located HQL query plan in cache ({0})", queryString );
}
return value;

View File

@ -27,7 +27,6 @@ import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
@ -290,7 +289,7 @@ public class ActionQueue {
private void registerCleanupActions(Executable executable) {
beforeTransactionProcesses.register( executable.getBeforeTransactionCompletionProcess() );
if ( session.getFactory().getSettings().isQueryCacheEnabled() ) {
if ( session.getFactory().getSessionFactoryOptions().isQueryCacheEnabled() ) {
invalidateSpaces( executable.getPropertySpaces() );
}
afterTransactionProcesses.register( executable.getAfterTransactionCompletionProcess() );
@ -471,7 +470,7 @@ public class ActionQueue {
}
}
finally {
if ( session.getFactory().getSettings().isQueryCacheEnabled() ) {
if ( session.getFactory().getSessionFactoryOptions().isQueryCacheEnabled() ) {
// Strictly speaking, only a subset of the list may have been processed if a RuntimeException occurs.
// We still invalidate all spaces. I don't see this as a big deal - after all, RuntimeExceptions are
// unexpected.
@ -573,7 +572,7 @@ public class ActionQueue {
}
public void sortCollectionActions() {
if ( session.getFactory().getSettings().isOrderUpdatesEnabled() ) {
if ( session.getFactory().getSessionFactoryOptions().isOrderUpdatesEnabled() ) {
// sort the updates by fk
collectionCreations.sort();
collectionUpdates.sort();
@ -583,11 +582,11 @@ public class ActionQueue {
}
public void sortActions() {
if ( session.getFactory().getSettings().isOrderUpdatesEnabled() ) {
if ( session.getFactory().getSessionFactoryOptions().isOrderUpdatesEnabled() ) {
// sort the updates by pk
updates.sort();
}
if ( session.getFactory().getSettings().isOrderInsertsEnabled() ) {
if ( session.getFactory().getSessionFactoryOptions().isOrderInsertsEnabled() ) {
insertions.sort();
}
}
@ -604,10 +603,12 @@ public class ActionQueue {
}
}
@SuppressWarnings("SimplifiableConditionalExpression")
public boolean hasAfterTransactionActions() {
return isTransactionCoordinatorShared ? false : afterTransactionProcesses.hasActions();
}
@SuppressWarnings("SimplifiableConditionalExpression")
public boolean hasBeforeTransactionActions() {
return isTransactionCoordinatorShared ? false : beforeTransactionProcesses.hasActions();
}
@ -759,7 +760,7 @@ public class ActionQueue {
}
}
if ( session.getFactory().getSettings().isQueryCacheEnabled() ) {
if ( session.getFactory().getSessionFactoryOptions().isQueryCacheEnabled() ) {
session.getFactory().getUpdateTimestampsCache().invalidate(
querySpacesToInvalidate.toArray( new String[querySpacesToInvalidate.size()] ),
session

View File

@ -24,7 +24,6 @@
package org.hibernate.engine.spi;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

View File

@ -27,7 +27,6 @@ import java.io.Serializable;
import java.sql.Connection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.hibernate.CacheMode;
import org.hibernate.Criteria;
@ -38,7 +37,6 @@ import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Transaction;
import org.hibernate.cache.spi.CacheKey;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.engine.jdbc.LobCreationContext;

View File

@ -1,52 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.engine.transaction.spi;
/**
* Enumeration of statuses in which a local transaction facade ({@link org.hibernate.Transaction}) might be.
*
* @author Steve Ebersole
*/
public enum LocalStatus {
/**
* The local transaction has not yet been begun
*/
NOT_ACTIVE,
/**
* The local transaction has been begun, but not yet completed.
*/
ACTIVE,
/**
* The local transaction has been competed successfully.
*/
COMMITTED,
/**
* The local transaction has been rolled back.
*/
ROLLED_BACK,
/**
* The local transaction attempted to commit, but failed.
*/
FAILED_COMMIT
}

View File

@ -171,7 +171,9 @@ public abstract class AbstractFlushingEventListener implements Serializable {
}
}
protected Object getAnything() { return null; }
protected Object getAnything() {
return null;
}
protected CascadingAction getCascadingAction() {
return CascadingActions.SAVE_UPDATE;

View File

@ -33,8 +33,6 @@ import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.type.CollectionType;
import org.jboss.logging.Logger;
/**
* Evict any collections referenced by the object from the session cache.
* This will NOT pick up any collections that were dereferenced, so they

View File

@ -23,8 +23,6 @@
*/
package org.hibernate.event.spi;
import org.hibernate.event.spi.EventSource;
/**
* An observer for detection of multiple entity representations for a persistent entity being merged.
*

View File

@ -76,10 +76,7 @@ public final class HolderInstantiator {
return constructor != null ? new AliasToBeanConstructorResultTransformer( constructor ) : transformer;
}
public HolderInstantiator(
ResultTransformer transformer,
String[] queryReturnAliases
) {
public HolderInstantiator(ResultTransformer transformer, String[] queryReturnAliases) {
this.transformer = transformer;
this.queryReturnAliases = queryReturnAliases;
}
@ -89,9 +86,10 @@ public final class HolderInstantiator {
}
public Object instantiate(Object[] row) {
if(transformer==null) {
if (transformer==null) {
return row;
} else {
}
else {
return transformer.transformTuple(row, queryReturnAliases);
}
}

View File

@ -25,18 +25,14 @@ package org.hibernate.hql.internal;
import java.util.Map;
import org.hibernate.HibernateException;
import org.hibernate.boot.registry.StandardServiceInitiator;
import org.hibernate.boot.registry.selector.spi.StrategySelector;
import org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory;
import org.hibernate.hql.spi.QueryTranslatorFactory;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.service.spi.ServiceRegistryImplementor;
import org.jboss.logging.Logger;
import static org.hibernate.cfg.AvailableSettings.QUERY_TRANSLATOR;
/**

View File

@ -26,7 +26,6 @@ package org.hibernate.hql.internal.ast.tree;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

View File

@ -62,7 +62,7 @@ import org.hibernate.type.Type;
* @author josh
*/
public class FromElement extends HqlSqlWalkerNode implements DisplayableNode, ParameterContainer {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( FromElement.class );
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( FromElement.class );
private String className;
private String classAlias;
@ -132,19 +132,24 @@ public class FromElement extends HqlSqlWalkerNode implements DisplayableNode, Pa
}
public void initializeEntity(
FromClause fromClause,
String className,
EntityPersister persister,
EntityType type,
String classAlias,
String tableAlias) {
FromClause fromClause,
String className,
EntityPersister persister,
EntityType type,
String classAlias,
String tableAlias) {
doInitialize( fromClause, tableAlias, className, classAlias, persister, type );
this.sequence = fromClause.nextFromElementCounter();
initialized = true;
}
private void doInitialize(FromClause fromClause, String tableAlias, String className, String classAlias,
EntityPersister persister, EntityType type) {
private void doInitialize(
FromClause fromClause,
String tableAlias,
String className,
String classAlias,
EntityPersister persister,
EntityType type) {
if ( initialized ) {
throw new IllegalStateException( "Already initialized!!" );
}
@ -163,7 +168,7 @@ public class FromElement extends HqlSqlWalkerNode implements DisplayableNode, Pa
}
@Override
public Type getDataType() {
public Type getDataType() {
return elementType.getDataType();
}
@ -293,12 +298,12 @@ public class FromElement extends HqlSqlWalkerNode implements DisplayableNode, Pa
}
@Override
public int hashCode() {
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
public boolean equals(Object obj) {
return super.equals( obj );
}

View File

@ -331,7 +331,7 @@ public class IdentNode extends FromReferenceNode implements SelectExpression {
}
@Override
public Type getDataType() {
public Type getDataType() {
Type type = super.getDataType();
if ( type != null ) {
return type;
@ -365,7 +365,7 @@ public class IdentNode extends FromReferenceNode implements SelectExpression {
}
@Override
public String getDisplayText() {
public String getDisplayText() {
StringBuilder buf = new StringBuilder();
if (getType() == SqlTokenTypes.ALIAS_REF) {

View File

@ -120,15 +120,15 @@ public class IntoClause extends HqlSqlWalkerNode implements DisplayableNode {
throw new QueryException( "number of select types did not match those for insert" );
}
int parameterCount = 0;
int parameterCount = 0;
for ( int i = 0; i < types.length; i++ ) {
if( selectClause.getParameterPositions().contains(i) ) {
if ( selectClause.getParameterPositions().contains( i ) ) {
parameterCount++;
}
else if ( !areCompatible( types[i], selectTypes[i - parameterCount] ) ) {
throw new QueryException(
"insertion type [" + types[i] + "] and selection type [" +
selectTypes[i - parameterCount] + "] at position " + i + " are not compatible"
"insertion type [" + types[i] + "] and selection type [" +
selectTypes[i - parameterCount] + "] at position " + i + " are not compatible"
);
}
}
@ -142,13 +142,11 @@ public class IntoClause extends HqlSqlWalkerNode implements DisplayableNode {
* @return String - The additional display text.
*/
public String getDisplayText() {
StringBuilder buf = new StringBuilder();
buf.append( "IntoClause{" );
buf.append( "entityName=" ).append( getEntityName() );
buf.append( ",tableName=" ).append( getTableName() );
buf.append( ",columns={" ).append( columnSpec ).append( "}" );
buf.append( "}" );
return buf.toString();
return "IntoClause{"
+ "entityName=" + getEntityName()
+ ",tableName=" + getTableName()
+ ",columns={" + columnSpec + "}"
+ "}";
}
private void initializeColumns() {
@ -185,20 +183,21 @@ public class IntoClause extends HqlSqlWalkerNode implements DisplayableNode {
componentIds.add( propertyNames[i] );
}
}
if ( componentIds.contains(name) ) {
if ( componentIds.contains( name ) ) {
if ( explicitComponentIds == null ) {
explicitComponentIds = new ArrayList( componentIds.size() );
}
explicitComponentIds.add( name );
explicitIdInsertion = explicitComponentIds.size() == componentIds.size();
}
} else if ( name.equals( persister.getIdentifierPropertyName() ) ) {
}
else if ( name.equals( persister.getIdentifierPropertyName() ) ) {
explicitIdInsertion = true;
}
}
if ( persister.isVersioned() ) {
if ( name.equals( persister.getPropertyNames()[ persister.getVersionProperty() ] ) ) {
if ( name.equals( persister.getPropertyNames()[persister.getVersionProperty()] ) ) {
explicitVersionInsertion = true;
}
}
@ -238,6 +237,7 @@ public class IntoClause extends HqlSqlWalkerNode implements DisplayableNode {
*
* @param target The type defined in the into-clause.
* @param source The type defined in the select clause.
*
* @return True if they are assignment compatible.
*/
private boolean areCompatible(Type target, Type source) {

View File

@ -33,7 +33,6 @@ import org.hibernate.hql.spi.QueryTranslator;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.type.LiteralType;
import org.hibernate.type.StringRepresentableType;
import org.hibernate.type.Type;
import org.hibernate.type.descriptor.converter.AttributeConverterTypeAdapter;

View File

@ -62,7 +62,7 @@ public class Node extends antlr.CommonAST {
}
@Override
public void initialize(Token tok) {
public void initialize(Token tok) {
super.initialize(tok);
filename = tok.getFilename();
line = tok.getLine();
@ -72,7 +72,7 @@ public class Node extends antlr.CommonAST {
}
@Override
public void initialize(AST t) {
public void initialize(AST t) {
super.initialize( t );
if ( t instanceof Node ) {
Node n = (Node)t;
@ -88,12 +88,12 @@ public class Node extends antlr.CommonAST {
}
@Override
public int getLine() {
public int getLine() {
return line;
}
@Override
public int getColumn() {
public int getColumn() {
return column;
}

View File

@ -35,11 +35,10 @@ import antlr.collections.AST;
* @author Steve Ebersole
*/
public class OrderByClause extends HqlSqlWalkerNode implements HqlSqlTokenTypes {
public void addOrderFragment(String orderByFragment) {
AST fragment = ASTUtil.create( getASTFactory(), SQL_TOKEN, orderByFragment );
if ( getFirstChild() == null ) {
setFirstChild( fragment );
setFirstChild( fragment );
}
else {
addChild( fragment );

View File

@ -58,11 +58,8 @@ public class ResultVariableRefNode extends HqlSqlWalkerNode {
this.selectExpression = selectExpression;
}
/**
* {@inheritDoc}
*/
@Override
public String getRenderText(SessionFactoryImplementor sessionFactory) {
public String getRenderText(SessionFactoryImplementor sessionFactory) {
int scalarColumnIndex = selectExpression.getScalarColumnIndex();
if ( scalarColumnIndex < 0 ) {
throw new IllegalStateException(

View File

@ -27,10 +27,9 @@ package org.hibernate.hql.internal.ast.tree;
import org.hibernate.hql.internal.antlr.HqlSqlTokenTypes;
import org.hibernate.hql.internal.antlr.SqlTokenTypes;
import org.hibernate.hql.internal.ast.util.ASTUtil;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.jboss.logging.Logger;
import antlr.collections.AST;
/**
@ -39,31 +38,26 @@ import antlr.collections.AST;
* @author Steve Ebersole
*/
public class UpdateStatement extends AbstractRestrictableStatement {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( UpdateStatement.class );
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, UpdateStatement.class.getName());
/**
* @see org.hibernate.hql.internal.ast.tree.Statement#getStatementType()
*/
@Override
public int getStatementType() {
return SqlTokenTypes.UPDATE;
}
/**
* @see org.hibernate.hql.internal.ast.tree.Statement#needsExecutor()
*/
@Override
public boolean needsExecutor() {
return true;
}
@Override
protected int getWhereClauseParentTokenType() {
protected int getWhereClauseParentTokenType() {
return SqlTokenTypes.SET;
}
@Override
protected CoreMessageLogger getLog() {
return LOG;
protected CoreMessageLogger getLog() {
return LOG;
}
public AST getSetClause() {

View File

@ -23,6 +23,7 @@
*
*/
package org.hibernate.hql.internal.classic;
import java.util.Map;
import org.hibernate.QueryException;
@ -39,30 +40,25 @@ import org.hibernate.hql.spi.QueryTranslatorFactory;
* @author Gavin King
*/
public class ClassicQueryTranslatorFactory implements QueryTranslatorFactory {
/**
* @see QueryTranslatorFactory#createQueryTranslator
*/
@Override
public QueryTranslator createQueryTranslator(
String queryIdentifier,
String queryString,
Map filters,
SessionFactoryImplementor factory,
EntityGraphQueryHint entityGraphQueryHint) {
if (entityGraphQueryHint != null) {
String queryString,
Map filters,
SessionFactoryImplementor factory,
EntityGraphQueryHint entityGraphQueryHint) {
if ( entityGraphQueryHint != null ) {
throw new QueryException( "EntityGraphs cannot be applied queries using the classic QueryTranslator!" );
}
return new QueryTranslatorImpl( queryIdentifier, queryString, filters, factory );
}
/**
* @see org.hibernate.hql.spi.QueryTranslatorFactory#createFilterTranslator
*/
@Override
public FilterTranslator createFilterTranslator(
String queryIdentifier,
String queryString,
Map filters,
SessionFactoryImplementor factory) {
Map filters,
SessionFactoryImplementor factory) {
return new QueryTranslatorImpl( queryIdentifier, queryString, filters, factory );
}

View File

@ -23,6 +23,7 @@
*
*/
package org.hibernate.hql.internal.classic;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
@ -51,7 +52,7 @@ public class FromParser implements Parser {
private boolean afterJoinType;
private JoinType joinType = JoinType.INNER_JOIN;
private boolean afterFetch;
//support collection member declarations
//e.g. "from Customer c, in(c.orders) as o"
private boolean memberDeclarations;
@ -59,7 +60,7 @@ public class FromParser implements Parser {
private boolean afterMemberDeclarations;
private String collectionName;
private static final Map<String,JoinType> JOIN_TYPES = new HashMap<String,JoinType>();
private static final Map<String, JoinType> JOIN_TYPES = new HashMap<String, JoinType>();
static {
JOIN_TYPES.put( "left", JoinType.LEFT_OUTER_JOIN );
@ -71,7 +72,7 @@ public class FromParser implements Parser {
public void token(String token, QueryTranslatorImpl q) throws QueryException {
// start by looking for HQL keywords...
String lcToken = token.toLowerCase(Locale.ROOT);
String lcToken = token.toLowerCase( Locale.ROOT );
if ( lcToken.equals( "," ) ) {
if ( !( expectingJoin | expectingAs ) ) {
throw new QueryException( "unexpected token: ," );
@ -81,7 +82,9 @@ public class FromParser implements Parser {
}
else if ( lcToken.equals( "join" ) ) {
if ( !afterJoinType ) {
if ( !( expectingJoin | expectingAs ) ) throw new QueryException( "unexpected token: join" );
if ( !( expectingJoin | expectingAs ) ) {
throw new QueryException( "unexpected token: join" );
}
// inner joins can be abbreviated to 'join'
joinType = JoinType.INNER_JOIN;
expectingJoin = false;
@ -107,7 +110,7 @@ public class FromParser implements Parser {
// 'outer' is optional and is ignored
if ( !afterJoinType ||
( joinType != JoinType.LEFT_OUTER_JOIN && joinType != JoinType.RIGHT_OUTER_JOIN )
) {
) {
throw new QueryException( "unexpected token: outer" );
}
}
@ -130,7 +133,7 @@ public class FromParser implements Parser {
afterClass = true;
}
else if ( lcToken.equals( "in" ) ) {
if (alias == null ){
if ( alias == null ) {
memberDeclarations = true;
afterMemberDeclarations = false;
}
@ -149,15 +152,15 @@ public class FromParser implements Parser {
afterAs = true;
expectingAs = false;
}
else if ( "(".equals( token ) ){
if( !memberDeclarations ) {
else if ( "(".equals( token ) ) {
if ( !memberDeclarations ) {
throw new QueryException( "unexpected token: (" );
}
//TODO alias should be null here
expectingPathExpression = true;
}
else if ( ")".equals( token ) ){
else if ( ")".equals( token ) ) {
// memberDeclarations = false;
// expectingPathExpression = false;
afterMemberDeclarations = true;
@ -218,7 +221,9 @@ public class FromParser implements Parser {
if ( afterClass ) {
// treat it as a classname
Queryable p = q.getEntityPersisterUsingImports( token );
if ( p == null ) throw new QueryException( "persister not found: " + token );
if ( p == null ) {
throw new QueryException( "persister not found: " + token );
}
q.addFromClass( alias, p );
}
else {
@ -226,7 +231,11 @@ public class FromParser implements Parser {
peParser.setJoinType( JoinType.INNER_JOIN );
peParser.setUseThetaStyleJoin( true );
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
);
}
String nm = peParser.addFromCollection( q );
q.setAliasName( alias, nm );
}
@ -236,7 +245,7 @@ public class FromParser implements Parser {
afterClass = false;
expectingJoin = true;
}
else if( memberDeclarations && expectingPathExpression ){
else if ( memberDeclarations && expectingPathExpression ) {
expectingAs = true;
peParser.setJoinType( JoinType.INNER_JOIN );
peParser.setUseThetaStyleJoin( false );
@ -323,10 +332,10 @@ public class FromParser implements Parser {
}
public void end(QueryTranslatorImpl q) {
if( afterMemberDeclarations ) {
if ( afterMemberDeclarations ) {
//The exception throwned by the AST query translator contains the error token location, respensent by line and colum,
//but it hard to get that info here.
throw new QueryException("alias not specified for IN");
throw new QueryException( "alias not specified for IN" );
}
}

View File

@ -38,10 +38,10 @@ import org.hibernate.internal.util.StringHelper;
*/
public class PreprocessingParser implements Parser {
private static final Set HQL_OPERATORS;
private static final Set<String> HQL_OPERATORS;
static {
HQL_OPERATORS = new HashSet();
HQL_OPERATORS = new HashSet<String>();
HQL_OPERATORS.add( "<=" );
HQL_OPERATORS.add( ">=" );
HQL_OPERATORS.add( "=>" );
@ -85,7 +85,9 @@ public class PreprocessingParser implements Parser {
}
quoted = !quoted;
}
if ( quoted ) return;
if ( quoted ) {
return;
}
//ignore whitespace
if ( ParserHelper.isWhitespace( token ) ) return;
@ -142,7 +144,9 @@ public class PreprocessingParser implements Parser {
}
public void end(QueryTranslatorImpl q) throws QueryException {
if ( lastToken != null ) parser.token( lastToken, q );
if ( lastToken != null ) {
parser.token( lastToken, q );
}
parser.end( q );
lastToken = null;
currentCollectionProp = null;
@ -150,8 +154,3 @@ public class PreprocessingParser implements Parser {
}

View File

@ -84,7 +84,7 @@ import org.hibernate.type.Type;
* query string to SQL.
*/
public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( QueryTranslatorImpl.class );
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( QueryTranslatorImpl.class );
private static final String[] NO_RETURN_ALIASES = new String[] {};
@ -156,9 +156,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
*/
public QueryTranslatorImpl(
String queryIdentifier,
String queryString,
Map enabledFilters,
SessionFactoryImplementor factory) {
String queryString,
Map enabledFilters,
SessionFactoryImplementor factory) {
super( factory );
this.queryIdentifier = queryIdentifier;
this.queryString = queryString;
@ -173,9 +173,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
* @param factory The session factory.
*/
public QueryTranslatorImpl(
String queryString,
Map enabledFilters,
SessionFactoryImplementor factory) {
String queryString,
Map enabledFilters,
SessionFactoryImplementor factory) {
this( queryString, queryString, enabledFilters, factory );
}
@ -238,13 +238,15 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
private void compile() throws QueryException, MappingException {
LOG.trace( "Compiling query" );
try {
ParserHelper.parse( new PreprocessingParser( tokenReplacements ),
ParserHelper.parse(
new PreprocessingParser( tokenReplacements ),
queryString,
ParserHelper.HQL_SEPARATORS,
this );
this
);
renderSQL();
}
catch ( QueryException qe ) {
catch (QueryException qe) {
if ( qe.getQueryString() == null ) {
throw qe.wrapWithQueryString( queryString );
}
@ -252,10 +254,10 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
throw qe;
}
}
catch ( MappingException me ) {
catch (MappingException me) {
throw me;
}
catch ( Exception e ) {
catch (Exception e) {
LOG.debug( "Unexpected query compilation problem", e );
e.printStackTrace();
throw new QueryException( "Incorrect query syntax", queryString, e );
@ -268,12 +270,12 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
}
@Override
public String getSQLString() {
public String getSQLString() {
return sqlString;
}
public List<String> collectSqlStrings() {
return ArrayHelper.toList( new String[] { sqlString } );
return ArrayHelper.toList( new String[] {sqlString} );
}
public String getQueryString() {
@ -286,7 +288,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
* @return an array of <tt>EntityPersister</tt>s.
*/
@Override
protected Loadable[] getEntityPersisters() {
protected Loadable[] getEntityPersisters() {
return persisters;
}
@ -320,7 +322,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
}
public String getAliasName(String alias) {
String name = ( String ) aliasNames.get( alias );
String name = (String) aliasNames.get( alias );
if ( name == null ) {
if ( superQuery != null ) {
name = superQuery.getAliasName( alias );
@ -335,10 +337,10 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
String unalias(String path) {
String alias = StringHelper.root( path );
String name = getAliasName( alias );
if (name != null) {
return name + path.substring(alias.length());
if ( name != null ) {
return name + path.substring( alias.length() );
}
return path;
return path;
}
void addEntityToFetch(String name, String oneToOneOwnerName, AssociationType ownerAssociationType) {
@ -368,7 +370,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
}
private String getType(String name) {
String type = ( String ) typeMap.get( name );
String type = (String) typeMap.get( name );
if ( type == null && superQuery != null ) {
type = superQuery.getType( name );
}
@ -376,7 +378,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
}
private String getRole(String name) {
String role = ( String ) collections.get( name );
String role = (String) collections.get( name );
if ( role == null && superQuery != null ) {
role = superQuery.getRole( name );
}
@ -388,7 +390,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
typeMap.containsKey( name ) ||
collections.containsKey( name ) || (
superQuery != null && superQuery.isName( name )
);
);
}
PropertyMapping getPropertyMapping(String name) throws QueryException {
@ -415,7 +417,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
}
private PropertyMapping getDecoratedPropertyMapping(String name) {
return ( PropertyMapping ) decoratedPropertyMappings.get( name );
return (PropertyMapping) decoratedPropertyMappings.get( name );
}
void decoratePropertyMapping(String name, PropertyMapping mapping) {
@ -437,30 +439,30 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
return null;
}
try {
return ( Queryable ) getFactory().getEntityPersister( importedClassName );
return (Queryable) getFactory().getEntityPersister( importedClassName );
}
catch ( MappingException me ) {
catch (MappingException me) {
return null;
}
}
Queryable getEntityPersister(String entityName) throws QueryException {
try {
return ( Queryable ) getFactory().getEntityPersister( entityName );
return (Queryable) getFactory().getEntityPersister( entityName );
}
catch ( Exception e ) {
catch (Exception e) {
throw new QueryException( "persistent class not found: " + entityName );
}
}
QueryableCollection getCollectionPersister(String role) throws QueryException {
try {
return ( QueryableCollection ) getFactory().getCollectionPersister( role );
return (QueryableCollection) getFactory().getCollectionPersister( role );
}
catch ( ClassCastException cce ) {
catch (ClassCastException cce) {
throw new QueryException( "collection role is not queryable: " + role );
}
catch ( Exception e ) {
catch (Exception e) {
throw new QueryException( "collection role not found: " + role );
}
}
@ -558,21 +560,21 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
namedParameters.put( name, list );
}
else {
( ( ArrayList ) o ).add( loc );
( (ArrayList) o ).add( loc );
}
}
@Override
public int[] getNamedParameterLocs(String name) throws QueryException {
public int[] getNamedParameterLocs(String name) throws QueryException {
Object o = namedParameters.get( name );
if ( o == null ) {
throw new QueryException( ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name, queryString );
}
if ( o instanceof Integer ) {
return new int[] { (Integer) o };
return new int[] {(Integer) o};
}
else {
return ArrayHelper.toIntArray( ( ArrayList ) o );
return ArrayHelper.toIntArray( (ArrayList) o );
}
}
@ -599,7 +601,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
suffixes = new String[size];
includeInSelect = new boolean[size];
for ( int i = 0; i < size; i++ ) {
String name = ( String ) returnedTypes.get( i );
String name = (String) returnedTypes.get( i );
//if ( !isName(name) ) throw new QueryException("unknown type: " + name);
persisters[i] = getEntityPersisterForName( name );
// TODO: cannot use generateSuffixes() - it handles the initial suffix differently.
@ -612,7 +614,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
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 );
ownerAssociationTypes[i] = (EntityType) uniqueKeyOwnerReferences.get( name );
}
@ -628,7 +630,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
returnTypes = new Type[scalarSize];
for ( int i = 0; i < scalarSize; i++ ) {
returnTypes[i] = ( Type ) scalarTypes.get( i );
returnTypes[i] = (Type) scalarTypes.get( i );
}
QuerySelect sql = new QuerySelect( getFactory().getDialect() );
@ -665,12 +667,12 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
// initialize the Set of queried identifier spaces (ie. tables)
Iterator iter = collections.values().iterator();
while ( iter.hasNext() ) {
CollectionPersister p = getCollectionPersister( ( String ) iter.next() );
CollectionPersister p = getCollectionPersister( (String) iter.next() );
addQuerySpaces( p.getCollectionSpaces() );
}
iter = typeMap.keySet().iterator();
while ( iter.hasNext() ) {
Queryable p = getEntityPersisterForName( ( String ) iter.next() );
Queryable p = getEntityPersisterForName( (String) iter.next() );
addQuerySpaces( p.getQuerySpaces() );
}
@ -701,7 +703,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
int size = returnedTypes.size();
for ( int k = 0; k < size; k++ ) {
String name = ( String ) returnedTypes.get( k );
String name = (String) returnedTypes.get( k );
String suffix = size == 1 ? "" : Integer.toString( k ) + '_';
sql.addSelectFragmentString( persisters[k].identifierSelectFragment( name, suffix ) );
}
@ -728,7 +730,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
int size = returnedTypes.size();
for ( int k = 0; k < size; k++ ) {
String suffix = size == 1 ? "" : Integer.toString( k ) + '_';
String name = ( String ) returnedTypes.get( k );
String name = (String) returnedTypes.get( k );
sql.addSelectFragmentString( persisters[k].propertySelectFragment( name, suffix, false ) );
}
}
@ -748,7 +750,10 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
for ( int k = 0; k < size; k++ ) {
scalarTypes.add(
getFactory().getTypeResolver().getTypeFactory().manyToOne( persisters[k].getEntityName(), shallowQuery )
getFactory().getTypeResolver().getTypeFactory().manyToOne(
persisters[k].getEntityName(),
shallowQuery
)
);
String[] idColumnNames = persisters[k].getIdentifierColumnNames();
@ -774,7 +779,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
while ( iter.hasNext() ) {
Object next = iter.next();
if ( next instanceof String ) {
String token = ( String ) next;
String token = (String) next;
if ( "(".equals( token ) ) {
parenCount++;
@ -783,7 +788,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
parenCount--;
}
String lc = token.toLowerCase(Locale.ROOT);
String lc = token.toLowerCase( Locale.ROOT );
if ( lc.equals( ", " ) ) {
if ( nolast ) {
nolast = false;
@ -802,7 +807,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
}
else {
nolast = true;
String[] tokens = ( String[] ) next;
String[] tokens = (String[]) next;
for ( int i = 0; i < tokens.length; i++ ) {
buf.append( tokens[i] );
if ( !isSubselect ) {
@ -829,14 +834,16 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
Iterator iter = joins.entrySet().iterator();
while ( iter.hasNext() ) {
Map.Entry me = ( Map.Entry ) iter.next();
String name = ( String ) me.getKey();
JoinSequence join = ( JoinSequence ) me.getValue();
join.setSelector( new JoinSequence.Selector() {
public boolean includeSubclasses(String alias) {
return returnedTypes.contains( alias ) && !isShallowQuery();
}
} );
Map.Entry me = (Map.Entry) iter.next();
String name = (String) me.getKey();
JoinSequence join = (JoinSequence) me.getValue();
join.setSelector(
new JoinSequence.Selector() {
public boolean includeSubclasses(String alias) {
return returnedTypes.contains( alias ) && !isShallowQuery();
}
}
);
if ( typeMap.containsKey( name ) ) {
ojf.addFragment( join.toJoinFragment( enabledFilters, true ) );
@ -863,7 +870,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
void addQuerySpaces(Serializable[] spaces) {
Collections.addAll( querySpaces, spaces );
if ( superQuery != null ) superQuery.addQuerySpaces( spaces );
if ( superQuery != null ) {
superQuery.addQuerySpaces( spaces );
}
}
void setDistinct(boolean distinct) {
@ -874,17 +883,14 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
return superQuery != null;
}
/**
* Overrides method from Loader
*/
@Override
public CollectionPersister[] getCollectionPersisters() {
return collectionPersister == null ? null : new CollectionPersister[] { collectionPersister };
public CollectionPersister[] getCollectionPersisters() {
return collectionPersister == null ? null : new CollectionPersister[] {collectionPersister};
}
@Override
protected String[] getCollectionSuffixes() {
return collectionPersister == null ? null : new String[] { "__" };
protected String[] getCollectionSuffixes() {
return collectionPersister == null ? null : new String[] {"__"};
}
void setCollectionToFetch(String role, String name, String ownerName, String entityName)
@ -898,12 +904,12 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
}
@Override
protected String[] getSuffixes() {
protected String[] getSuffixes() {
return suffixes;
}
@Override
protected String[] getAliases() {
protected String[] getAliases() {
return names;
}
@ -932,28 +938,30 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
//many-to-many
addCollection( collectionName, collectionRole );
try {
join.addJoin( ( AssociationType ) persister.getElementType(),
join.addJoin(
(AssociationType) persister.getElementType(),
elementName,
JoinType.INNER_JOIN,
persister.getElementColumnNames(collectionName) );
persister.getElementColumnNames( collectionName )
);
}
catch ( MappingException me ) {
catch (MappingException me) {
throw new QueryException( me );
}
}
join.addCondition( collectionName, keyColumnNames, " = ?" );
//if ( persister.hasWhere() ) join.addCondition( persister.getSQLWhereString(collectionName) );
EntityType elemType = ( EntityType ) collectionElementType;
EntityType elemType = (EntityType) collectionElementType;
addFrom( elementName, elemType.getAssociatedEntityName(), join );
}
String getPathAlias(String path) {
return ( String ) pathAliases.get( path );
return (String) pathAliases.get( path );
}
JoinSequence getPathJoin(String path) {
return ( JoinSequence ) pathJoins.get( path );
return (JoinSequence) pathJoins.get( path );
}
void addPathAliasAndJoin(String path, String alias, JoinSequence joinSequence) {
@ -982,11 +990,27 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
try {
final List<AfterLoadAction> afterLoadActions = new ArrayList<AfterLoadAction>();
final SqlStatementWrapper wrapper = executeQueryStatement( queryParameters, false, afterLoadActions, session );
final SqlStatementWrapper wrapper = executeQueryStatement(
queryParameters,
false,
afterLoadActions,
session
);
final ResultSet rs = wrapper.getResultSet();
final PreparedStatement st = (PreparedStatement) wrapper.getStatement();
HolderInstantiator hi = HolderInstantiator.createClassicHolderInstantiator(holderConstructor, queryParameters.getResultTransformer());
Iterator result = new IteratorImpl( rs, st, session, queryParameters.isReadOnly( session ), returnTypes, getColumnNames(), hi );
HolderInstantiator hi = HolderInstantiator.createClassicHolderInstantiator(
holderConstructor,
queryParameters.getResultTransformer()
);
Iterator result = new IteratorImpl(
rs,
st,
session,
queryParameters.isReadOnly( session ),
returnTypes,
getColumnNames(),
hi
);
if ( stats ) {
final long endTime = System.nanoTime();
@ -995,31 +1019,31 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
"HQL: " + queryString,
0,
milliseconds
);
);
}
return result;
}
catch ( SQLException sqle ) {
catch (SQLException sqle) {
throw getFactory().getSQLExceptionHelper().convert(
sqle,
"could not execute query using iterate",
getSQLString()
);
);
}
}
public int executeUpdate(QueryParameters queryParameters, SessionImplementor session) throws HibernateException {
throw new UnsupportedOperationException( "Not supported! Use the AST translator...");
throw new UnsupportedOperationException( "Not supported! Use the AST translator..." );
}
@Override
protected boolean[] includeInResultRow() {
protected boolean[] includeInResultRow() {
boolean[] isResultReturned = includeInSelect;
if ( hasScalars ) {
isResultReturned = new boolean[ returnedTypes.size() ];
isResultReturned = new boolean[returnedTypes.size()];
Arrays.fill( isResultReturned, true );
}
return isResultReturned;
@ -1027,7 +1051,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
@Override
protected ResultTransformer resolveResultTransformer(ResultTransformer resultTransformer) {
protected ResultTransformer resolveResultTransformer(ResultTransformer resultTransformer) {
return HolderInstantiator.resolveClassicResultTransformer(
holderConstructor,
resultTransformer
@ -1035,17 +1059,21 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
}
@Override
protected Object getResultColumnOrRow(Object[] row, ResultTransformer transformer, ResultSet rs, SessionImplementor session)
protected Object getResultColumnOrRow(
Object[] row,
ResultTransformer transformer,
ResultSet rs,
SessionImplementor session)
throws SQLException, HibernateException {
Object[] resultRow = getResultRow( row, rs, session );
return ( holderClass == null && resultRow.length == 1 ?
resultRow[ 0 ] :
resultRow[0] :
resultRow
);
}
@Override
protected Object[] getResultRow(Object[] row, ResultSet rs, SessionImplementor session)
protected Object[] getResultRow(Object[] row, ResultSet rs, SessionImplementor session)
throws SQLException, HibernateException {
Object[] resultRow;
if ( hasScalars ) {
@ -1063,14 +1091,14 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
}
@Override
protected List getResultList(List results, ResultTransformer resultTransformer) throws QueryException {
protected List getResultList(List results, ResultTransformer resultTransformer) throws QueryException {
if ( holderClass != null ) {
for ( int i = 0; i < results.size(); i++ ) {
Object[] row = ( Object[] ) results.get( i );
Object[] row = (Object[]) results.get( i );
try {
results.set( i, holderConstructor.newInstance( row ) );
}
catch ( Exception e ) {
catch (Exception e) {
throw new QueryException( "could not instantiate: " + holderClass, e );
}
}
@ -1086,7 +1114,9 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
Object[] result = new Object[selectLength];
int j = 0;
for ( int i = 0; i < row.length; i++ ) {
if ( includeInSelect[i] ) result[j++] = row[i];
if ( includeInSelect[i] ) {
result[j++] = row[i];
}
}
return result;
}
@ -1097,27 +1127,29 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
}
@Override
protected LockMode[] getLockModes(LockOptions lockOptions) {
protected LockMode[] getLockModes(LockOptions lockOptions) {
// unfortunately this stuff can't be cached because
// it is per-invocation, not constant for the
// QueryTranslator instance
HashMap nameLockOptions = new HashMap();
if ( lockOptions == null) {
if ( lockOptions == null ) {
lockOptions = LockOptions.NONE;
}
if ( lockOptions.getAliasLockCount() > 0 ) {
Iterator iter = lockOptions.getAliasLockIterator();
while ( iter.hasNext() ) {
Map.Entry me = ( Map.Entry ) iter.next();
nameLockOptions.put( getAliasName( ( String ) me.getKey() ),
me.getValue() );
Map.Entry me = (Map.Entry) iter.next();
nameLockOptions.put(
getAliasName( (String) me.getKey() ),
me.getValue()
);
}
}
LockMode[] lockModesArray = new LockMode[names.length];
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.getLockMode();
@ -1128,7 +1160,7 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
}
@Override
protected String applyLocks(
protected String applyLocks(
String sql,
QueryParameters parameters,
Dialect dialect,
@ -1137,18 +1169,18 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
final LockOptions lockOptions = parameters.getLockOptions();
final String result;
if ( lockOptions == null ||
( lockOptions.getLockMode() == LockMode.NONE && lockOptions.getAliasLockCount() == 0 ) ) {
( lockOptions.getLockMode() == LockMode.NONE && lockOptions.getAliasLockCount() == 0 ) ) {
return sql;
}
else {
LockOptions locks = new LockOptions();
locks.setLockMode(lockOptions.getLockMode());
locks.setTimeOut(lockOptions.getTimeOut());
locks.setScope(lockOptions.getScope());
locks.setLockMode( lockOptions.getLockMode() );
locks.setTimeOut( lockOptions.getTimeOut() );
locks.setScope( lockOptions.getScope() );
Iterator iter = lockOptions.getAliasLockIterator();
while ( iter.hasNext() ) {
Map.Entry me = ( Map.Entry ) iter.next();
locks.setAliasSpecificLockMode( getAliasName( ( String ) me.getKey() ), (LockMode) me.getValue() );
Map.Entry me = (Map.Entry) iter.next();
locks.setAliasSpecificLockMode( getAliasName( (String) me.getKey() ), (LockMode) me.getValue() );
}
Map keyColumnNames = null;
if ( dialect.forUpdateOfColumns() ) {
@ -1164,13 +1196,13 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
}
@Override
protected boolean upgradeLocks() {
protected boolean upgradeLocks() {
return true;
}
@Override
protected int[] getCollectionOwners() {
return new int[] { collectionOwnerColumn };
protected int[] getCollectionOwners() {
return new int[] {collectionOwnerColumn};
}
protected boolean isCompiled() {
@ -1178,17 +1210,17 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
}
@Override
public String toString() {
public String toString() {
return queryString;
}
@Override
protected int[] getOwners() {
protected int[] getOwners() {
return owners;
}
@Override
protected EntityType[] getOwnerAssociationTypes() {
protected EntityType[] getOwnerAssociationTypes() {
return ownerAssociationTypes;
}
@ -1211,12 +1243,12 @@ public class QueryTranslatorImpl extends BasicLoader implements FilterTranslator
}
@Override
public String getQueryIdentifier() {
public String getQueryIdentifier() {
return queryIdentifier;
}
@Override
protected boolean isSubselectLoadingEnabled() {
protected boolean isSubselectLoadingEnabled() {
return hasSubselectLoadableCollections();
}

View File

@ -156,7 +156,9 @@ public class SelectParser implements Parser {
}
else if ( getFunction( lctoken, q ) != null && token.equals( q.unalias( token ) ) ) {
// the name of an SQL function
if ( !ready ) throw new QueryException( ", expected before aggregate function in SELECT: " + token );
if ( !ready ) {
throw new QueryException( ", expected before aggregate function in SELECT: " + token );
}
aggregate = true;
aggregateAddSelectScalar = true;
aggregateFuncTokenList.add( lctoken );

View File

@ -244,7 +244,7 @@ public class WhereParser implements Parser {
if ( bracketsSinceSelect == -1 ) {
QueryTranslatorImpl subq = new QueryTranslatorImpl(
subselect.toString(),
subselect.toString(),
q.getEnabledFilters(),
q.getFactory()
);
@ -445,7 +445,9 @@ public class WhereParser implements Parser {
catch ( MappingException me ) {
throw new QueryException( me );
}
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 {
//noinspection unchecked
appendToken( q, ( ( LiteralType ) type ).objectToSQLString( constant, q.getFactory().getDialect() ) );

View File

@ -44,12 +44,10 @@ import org.hibernate.type.Type;
* @author josh
*/
public interface QueryTranslator {
// Error message constants.
public static final String ERROR_CANNOT_FETCH_WITH_ITERATE = "fetch may not be used with scroll() or iterate()";
public static final String ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR = "Named parameter does not appear in Query: ";
public static final String ERROR_CANNOT_DETERMINE_TYPE = "Could not determine type of: ";
public static final String ERROR_CANNOT_FORMAT_LITERAL = "Could not format constant value to SQL literal: ";
String ERROR_CANNOT_FETCH_WITH_ITERATE = "fetch may not be used with scroll() or iterate()";
String ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR = "Named parameter does not appear in Query: ";
String ERROR_CANNOT_DETERMINE_TYPE = "Could not determine type of: ";
String ERROR_CANNOT_FORMAT_LITERAL = "Could not format constant value to SQL literal: ";
/**
* Compile a "normal" query. This method may be called multiple
@ -188,5 +186,5 @@ public interface QueryTranslator {
boolean isManipulationStatement();
public Class getDynamicInstantiationResultType();
Class getDynamicInstantiationResultType();
}

View File

@ -23,10 +23,8 @@
*/
package org.hibernate.hql.spi.id;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.hibernate.QueryException;

View File

@ -23,14 +23,12 @@
*/
package org.hibernate.hql.spi.id;
import org.hibernate.hql.spi.id.local.AfterUseAction;
/**
* @author Steve Ebersole
*/
public interface IdTableSupport {
public String generateIdTableName(String baseName);
public String getCreateIdTableCommand();
public String getCreateIdTableStatementOptions();
public String getDropIdTableCommand();
String generateIdTableName(String baseName);
String getCreateIdTableCommand();
String getCreateIdTableStatementOptions();
String getDropIdTableCommand();
}

View File

@ -39,14 +39,14 @@ import org.hibernate.internal.CoreMessageLogger;
* @author Joseph Fifield
*/
public class GUIDGenerator implements IdentifierGenerator {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( GUIDGenerator.class );
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( GUIDGenerator.class );
private static boolean WARNED;
public GUIDGenerator() {
if ( !WARNED ) {
WARNED = true;
LOG.deprecatedUuidGenerator( UUIDGenerator.class.getName(), UUIDGenerationStrategy.class.getName() );
LOG.deprecatedUuidGenerator( UUIDGenerator.class.getName(), UUIDGenerationStrategy.class.getName() );
}
}
@ -61,12 +61,12 @@ public class GUIDGenerator implements IdentifierGenerator {
if ( !rs.next() ) {
throw new HibernateException( "The database returned no GUID identity value" );
}
result = rs.getString(1);
result = rs.getString( 1 );
}
finally {
session.getJdbcCoordinator().getResourceRegistry().release( rs, st );
}
LOG.guidGenerated(result);
LOG.guidGenerated( result );
return result;
}
finally {
@ -79,7 +79,7 @@ public class GUIDGenerator implements IdentifierGenerator {
sqle,
"could not retrieve GUID",
sql
);
);
}
}
}

View File

@ -32,12 +32,11 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.HibernateException;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.type.CustomType;
import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/**
* Factory and helper methods for {@link IdentifierGenerator} framework.
*
@ -45,9 +44,7 @@ import org.jboss.logging.Logger;
* @author Steve Ebersole
*/
public final class IdentifierGeneratorHelper {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class,
IdentifierGeneratorHelper.class.getName());
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( IdentifierGeneratorHelper.class );
/**
* Marker object returned from {@link IdentifierGenerator#generate} to indicate that we should short-circuit any
@ -86,7 +83,8 @@ public final class IdentifierGeneratorHelper {
* @throws SQLException Can be thrown while accessing the result set
* @throws HibernateException Indicates a problem reading back a generated identity value.
*/
public static Serializable getGeneratedIdentity(ResultSet rs, String identifier, Type type) throws SQLException, HibernateException {
public static Serializable getGeneratedIdentity(ResultSet rs, String identifier, Type type)
throws SQLException, HibernateException {
if ( !rs.next() ) {
throw new HibernateException( "The database returned no natively generated identity value" );
}
@ -108,9 +106,10 @@ public final class IdentifierGeneratorHelper {
* @throws SQLException Indicates problems access the result set
* @throws IdentifierGenerationException Indicates an unknown type.
*/
public static Serializable get(ResultSet rs, String identifier, Type type) throws SQLException, IdentifierGenerationException {
public static Serializable get(ResultSet rs, String identifier, Type type)
throws SQLException, IdentifierGenerationException {
if ( ResultSetIdentifierConsumer.class.isInstance( type ) ) {
return ( ( ResultSetIdentifierConsumer ) type ).consumeIdentifier( rs );
return ( (ResultSetIdentifierConsumer) type ).consumeIdentifier( rs );
}
if ( CustomType.class.isInstance( type ) ) {
final CustomType customType = (CustomType) type;
@ -122,12 +121,12 @@ public final class IdentifierGeneratorHelper {
try {
columnCount = rs.getMetaData().getColumnCount();
}
catch(Exception e){
catch (Exception e) {
//Oracle driver will throw NPE
}
Class clazz = type.getReturnedClass();
if (columnCount == 1) {
if ( columnCount == 1 ) {
if ( clazz == Long.class ) {
return rs.getLong( 1 );
}
@ -154,22 +153,22 @@ public final class IdentifierGeneratorHelper {
}
else {
if ( clazz == Long.class ) {
return rs.getLong(identifier);
return rs.getLong( identifier );
}
else if ( clazz == Integer.class ) {
return rs.getInt(identifier);
return rs.getInt( identifier );
}
else if ( clazz == Short.class ) {
return rs.getShort(identifier);
return rs.getShort( identifier );
}
else if ( clazz == String.class ) {
return rs.getString(identifier);
return rs.getString( identifier );
}
else if ( clazz == BigInteger.class ) {
return rs.getBigDecimal(identifier).setScale( 0, BigDecimal.ROUND_UNNECESSARY ).toBigInteger();
return rs.getBigDecimal( identifier ).setScale( 0, BigDecimal.ROUND_UNNECESSARY ).toBigInteger();
}
else if ( clazz == BigDecimal.class ) {
return rs.getBigDecimal(identifier).setScale( 0, BigDecimal.ROUND_UNNECESSARY );
return rs.getBigDecimal( identifier ).setScale( 0, BigDecimal.ROUND_UNNECESSARY );
}
else {
throw new IdentifierGenerationException(
@ -188,19 +187,18 @@ public final class IdentifierGeneratorHelper {
* @return The wrapped type.
*
* @throws IdentifierGenerationException Indicates an unhandled 'clazz'.
*
* @deprecated Use the {@link #getIntegralDataTypeHolder holders} instead.
*/
@Deprecated
public static Number createNumber(long value, Class clazz) throws IdentifierGenerationException {
public static Number createNumber(long value, Class clazz) throws IdentifierGenerationException {
if ( clazz == Long.class ) {
return value;
}
else if ( clazz == Integer.class ) {
return ( int ) value;
return (int) value;
}
else if ( clazz == Short.class ) {
return ( short ) value;
return (short) value;
}
else {
throw new IdentifierGenerationException( "unrecognized id type : " + clazz.getName() );
@ -389,10 +387,10 @@ public final class IdentifierGeneratorHelper {
return value;
}
else if ( exactType == Integer.class ) {
return ( int ) value;
return (int) value;
}
else {
return ( short ) value;
return (short) value;
}
}
@ -409,12 +407,12 @@ public final class IdentifierGeneratorHelper {
}
@Override
public String toString() {
public String toString() {
return "BasicHolder[" + exactType.getName() + "[" + value + "]]";
}
@Override
public boolean equals(Object o) {
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
@ -428,7 +426,7 @@ public final class IdentifierGeneratorHelper {
}
@Override
public int hashCode() {
public int hashCode() {
return (int) ( value ^ ( value >>> 32 ) );
}
}
@ -550,12 +548,12 @@ public final class IdentifierGeneratorHelper {
}
@Override
public String toString() {
public String toString() {
return "BigIntegerHolder[" + value + "]";
}
@Override
public boolean equals(Object o) {
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
@ -571,7 +569,7 @@ public final class IdentifierGeneratorHelper {
}
@Override
public int hashCode() {
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
}
@ -693,12 +691,12 @@ public final class IdentifierGeneratorHelper {
}
@Override
public String toString() {
public String toString() {
return "BigDecimalHolder[" + value + "]";
}
@Override
public boolean equals(Object o) {
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
@ -714,7 +712,7 @@ public final class IdentifierGeneratorHelper {
}
@Override
public int hashCode() {
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
}

View File

@ -23,6 +23,7 @@
*
*/
package org.hibernate.id;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@ -49,10 +50,11 @@ import org.hibernate.id.insert.InsertSelectIdentityInsert;
*/
public class IdentityGenerator extends AbstractPostInsertGenerator {
@Override
public InsertGeneratedIdentifierDelegate getInsertGeneratedIdentifierDelegate(
PostInsertIdentityPersister persister,
Dialect dialect,
boolean isGetGeneratedKeysEnabled) throws HibernateException {
Dialect dialect,
boolean isGetGeneratedKeysEnabled) throws HibernateException {
if ( isGetGeneratedKeysEnabled ) {
return new GetGeneratedKeysDelegate( persister, dialect );
}
@ -79,12 +81,14 @@ public class IdentityGenerator extends AbstractPostInsertGenerator {
this.dialect = dialect;
}
@Override
public IdentifierGeneratingInsert prepareIdentifierGeneratingInsert() {
IdentifierGeneratingInsert insert = new IdentifierGeneratingInsert( dialect );
insert.addIdentityColumn( persister.getRootTableKeyColumnNames()[0] );
return insert;
}
@Override
protected PreparedStatement prepare(String insertSQL, SessionImplementor session) throws SQLException {
return session
.getJdbcCoordinator()
@ -92,7 +96,9 @@ public class IdentityGenerator extends AbstractPostInsertGenerator {
.prepareStatement( insertSQL, PreparedStatement.RETURN_GENERATED_KEYS );
}
public Serializable executeAndExtract(PreparedStatement insert, SessionImplementor session) throws SQLException {
@Override
public Serializable executeAndExtract(PreparedStatement insert, SessionImplementor session)
throws SQLException {
session.getJdbcCoordinator().getResultSetReturn().executeUpdate( insert );
ResultSet rs = null;
try {
@ -127,12 +133,14 @@ public class IdentityGenerator extends AbstractPostInsertGenerator {
this.dialect = dialect;
}
@Override
public IdentifierGeneratingInsert prepareIdentifierGeneratingInsert() {
InsertSelectIdentityInsert insert = new InsertSelectIdentityInsert( dialect );
insert.addIdentityColumn( persister.getRootTableKeyColumnNames()[0] );
return insert;
}
@Override
protected PreparedStatement prepare(String insertSQL, SessionImplementor session) throws SQLException {
return session
.getJdbcCoordinator()
@ -140,7 +148,9 @@ public class IdentityGenerator extends AbstractPostInsertGenerator {
.prepareStatement( insertSQL, PreparedStatement.NO_GENERATED_KEYS );
}
public Serializable executeAndExtract(PreparedStatement insert, SessionImplementor session) throws SQLException {
@Override
public Serializable executeAndExtract(PreparedStatement insert, SessionImplementor session)
throws SQLException {
ResultSet rs = session.getJdbcCoordinator().getResultSetReturn().execute( insert );
try {
return IdentifierGeneratorHelper.getGeneratedIdentity(
@ -175,21 +185,28 @@ public class IdentityGenerator extends AbstractPostInsertGenerator {
this.dialect = dialect;
}
@Override
public IdentifierGeneratingInsert prepareIdentifierGeneratingInsert() {
IdentifierGeneratingInsert insert = new IdentifierGeneratingInsert( dialect );
insert.addIdentityColumn( persister.getRootTableKeyColumnNames()[0] );
return insert;
}
@Override
protected String getSelectSQL() {
return persister.getIdentitySelectString();
}
@Override
protected Serializable getResult(
SessionImplementor session,
ResultSet rs,
Object object) throws SQLException {
return IdentifierGeneratorHelper.getGeneratedIdentity( rs, persister.getRootTableKeyColumnNames()[0], persister.getIdentifierType() );
ResultSet rs,
Object object) throws SQLException {
return IdentifierGeneratorHelper.getGeneratedIdentity(
rs,
persister.getRootTableKeyColumnNames()[0],
persister.getIdentifierType()
);
}
}

View File

@ -55,13 +55,14 @@ import org.hibernate.type.Type;
* @author Brett Meyer
*/
public class IncrementGenerator implements IdentifierGenerator, Configurable {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( IncrementGenerator.class );
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( IncrementGenerator.class );
private Class returnClass;
private String sql;
private IntegralDataTypeHolder previousValueHolder;
@Override
public synchronized Serializable generate(SessionImplementor session, Object object) throws HibernateException {
if ( sql != null ) {
initializePreviousValueHolder( session );
@ -74,7 +75,7 @@ public class IncrementGenerator implements IdentifierGenerator, Configurable {
returnClass = type.getReturnedClass();
ObjectNameNormalizer normalizer =
( ObjectNameNormalizer ) params.get( PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER );
(ObjectNameNormalizer) params.get( PersistentIdentifierGenerator.IDENTIFIER_NORMALIZER );
String column = params.getProperty( "column" );
if ( column == null ) {
@ -96,13 +97,13 @@ public class IncrementGenerator implements IdentifierGenerator, Configurable {
);
StringBuilder buf = new StringBuilder();
for ( int i=0; i < tables.length; i++ ) {
for ( int i = 0; i < tables.length; i++ ) {
final String tableName = normalizer.toDatabaseIdentifierText( tables[i] );
if ( tables.length > 1 ) {
buf.append( "select max(" ).append( column ).append( ") as mx from " );
}
buf.append( Table.qualify( catalog, schema, tableName ) );
if ( i < tables.length-1 ) {
if ( i < tables.length - 1 ) {
buf.append( " union " );
}
}
@ -126,11 +127,11 @@ public class IncrementGenerator implements IdentifierGenerator, Configurable {
try {
ResultSet rs = session.getJdbcCoordinator().getResultSetReturn().extract( st );
try {
if (rs.next()) {
previousValueHolder.initialize(rs, 0L).increment();
if ( rs.next() ) {
previousValueHolder.initialize( rs, 0L ).increment();
}
else {
previousValueHolder.initialize(1L);
else {
previousValueHolder.initialize( 1L );
}
sql = null;
if ( debugEnabled ) {

View File

@ -48,6 +48,7 @@ import org.hibernate.engine.spi.SessionEventListenerManager;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.enhanced.AccessCallback;
import org.hibernate.id.enhanced.LegacyHiLoAlgorithmOptimizer;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.jdbc.AbstractReturningWork;
@ -59,10 +60,7 @@ import org.hibernate.type.LongType;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/**
*
* A hilo <tt>IdentifierGenerator</tt> that returns a <tt>Long</tt>, constructed using
* a hi/lo algorithm. The hi value MUST be fetched in a seperate transaction
* to the <tt>Session</tt> transaction so the generator must be able to obtain
@ -71,14 +69,14 @@ import org.jboss.logging.Logger;
* case a <tt>SequenceHiLoGenerator</tt> would be a better choice (where
* supported).<br>
* <br>
*
* <p/>
* A hilo <tt>IdentifierGenerator</tt> that uses a database
* table to store the last generated values. A table can contains
* several hi values. They are distinct from each other through a key
* <p/>
* <p>This implementation is not compliant with a user connection</p>
* <p/>
*
* <p/>
* <p>Allowed parameters (all of them are optional):</p>
* <ul>
* <li>table: table name (default <tt>hibernate_sequences</tt>)</li>
@ -93,9 +91,7 @@ import org.jboss.logging.Logger;
* @author <a href="mailto:kr@hbt.de">Klaus Richarz</a>.
*/
public class MultipleHiLoPerTableGenerator implements PersistentIdentifierGenerator, Configurable {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class,
MultipleHiLoPerTableGenerator.class.getName());
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( MultipleHiLoPerTableGenerator.class );
public static final String ID_TABLE = "table";
public static final String PK_COLUMN_NAME = "primary_key_column";
@ -138,13 +134,23 @@ public class MultipleHiLoPerTableGenerator implements PersistentIdentifierGenera
int rows;
do {
final PreparedStatement queryPreparedStatement = prepareStatement( connection, query, statementLogger, statsCollector );
final PreparedStatement queryPreparedStatement = prepareStatement(
connection,
query,
statementLogger,
statsCollector
);
try {
final ResultSet rs = executeQuery( queryPreparedStatement, statsCollector );
boolean isInitialized = rs.next();
if ( !isInitialized ) {
value.initialize( 0 );
final PreparedStatement insertPreparedStatement = prepareStatement( connection, insert, statementLogger, statsCollector );
final PreparedStatement insertPreparedStatement = prepareStatement(
connection,
insert,
statementLogger,
statsCollector
);
try {
value.bind( insertPreparedStatement, 1 );
executeUpdate( insertPreparedStatement, statsCollector );
@ -167,7 +173,12 @@ public class MultipleHiLoPerTableGenerator implements PersistentIdentifierGenera
}
final PreparedStatement updatePreparedStatement = prepareStatement( connection, update, statementLogger, statsCollector );
final PreparedStatement updatePreparedStatement = prepareStatement(
connection,
update,
statementLogger,
statsCollector
);
try {
value.copy().increment().bind( updatePreparedStatement, 1 );
value.bind( updatePreparedStatement, 2 );
@ -181,7 +192,7 @@ public class MultipleHiLoPerTableGenerator implements PersistentIdentifierGenera
finally {
updatePreparedStatement.close();
}
} while ( rows==0 );
} while ( rows == 0 );
return value;
}
@ -240,7 +251,8 @@ public class MultipleHiLoPerTableGenerator implements PersistentIdentifierGenera
}
private ResultSet executeQuery(PreparedStatement ps, SessionEventListenerManager statsCollector) throws SQLException {
private ResultSet executeQuery(PreparedStatement ps, SessionEventListenerManager statsCollector)
throws SQLException {
try {
statsCollector.jdbcExecuteStatementStart();
return ps.executeQuery();
@ -252,7 +264,7 @@ public class MultipleHiLoPerTableGenerator implements PersistentIdentifierGenera
@SuppressWarnings({"StatementWithEmptyBody", "deprecation"})
public void configure(Type type, Properties params, JdbcEnvironment jdbcEnv) throws MappingException {
ObjectNameNormalizer normalizer = ( ObjectNameNormalizer ) params.get( IDENTIFIER_NORMALIZER );
ObjectNameNormalizer normalizer = (ObjectNameNormalizer) params.get( IDENTIFIER_NORMALIZER );
qualifiedTableName = QualifiedNameParser.INSTANCE.parse(
ConfigurationHelper.getString( ID_TABLE, params, DEFAULT_TABLE ),
@ -275,31 +287,31 @@ public class MultipleHiLoPerTableGenerator implements PersistentIdentifierGenera
String keyValue = ConfigurationHelper.getString( PK_VALUE_NAME, params, params.getProperty( TABLE ) );
query = "select " +
valueColumnName +
" from " +
jdbcEnv.getDialect().appendLockHint( LockMode.PESSIMISTIC_WRITE, tableName ) +
" where " + pkColumnName + " = '" + keyValue + "'" +
valueColumnName +
" from " +
jdbcEnv.getDialect().appendLockHint( LockMode.PESSIMISTIC_WRITE, tableName ) +
" where " + pkColumnName + " = '" + keyValue + "'" +
jdbcEnv.getDialect().getForUpdateString();
update = "update " +
tableName +
" set " +
valueColumnName +
" = ? where " +
valueColumnName +
" = ? and " +
pkColumnName +
" = '" +
keyValue
+ "'";
tableName +
" set " +
valueColumnName +
" = ? where " +
valueColumnName +
" = ? and " +
pkColumnName +
" = '" +
keyValue
+ "'";
insert = "insert into " + tableName +
"(" + pkColumnName + ", " + valueColumnName + ") " +
"values('"+ keyValue +"', ?)";
"(" + pkColumnName + ", " + valueColumnName + ") " +
"values('" + keyValue + "', ?)";
//hilo config
maxLo = ConfigurationHelper.getInt(MAX_LO, params, Short.MAX_VALUE);
maxLo = ConfigurationHelper.getInt( MAX_LO, params, Short.MAX_VALUE );
returnClass = type.getReturnedClass();
if ( maxLo >= 1 ) {
@ -347,7 +359,7 @@ public class MultipleHiLoPerTableGenerator implements PersistentIdentifierGenera
}
public String[] sqlDropStrings(Dialect dialect) throws HibernateException {
return new String[] { dialect.getDropTableString( tableName ) };
return new String[] {dialect.getDropTableString( tableName )};
}
public Object generatorKey() {

View File

@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.id;
import org.hibernate.HibernateException;
import org.hibernate.boot.model.relational.ExportableProducer;
import org.hibernate.dialect.Dialect;
@ -32,76 +33,78 @@ import org.hibernate.dialect.Dialect;
* All <tt>PersistentIdentifierGenerator</tt>s that also implement
* <tt>Configurable</tt> have access to a special mapping parameter: schema
*
* @see IdentifierGenerator
* @see Configurable
*
* @author Gavin King
* @author Steve Ebersole
*
* @see IdentifierGenerator
* @see Configurable
*/
public interface PersistentIdentifierGenerator extends IdentifierGenerator, ExportableProducer {
/**
* The configuration parameter holding the schema name
*/
public static final String SCHEMA = "schema";
String SCHEMA = "schema";
/**
* The configuration parameter holding the table name for the
* generated id
*/
public static final String TABLE = "target_table";
String TABLE = "target_table";
/**
* The configuration parameter holding the table names for all
* tables for which the id must be unique
*/
public static final String TABLES = "identity_tables";
String TABLES = "identity_tables";
/**
* The configuration parameter holding the primary key column
* name of the generated id
*/
public static final String PK = "target_column";
String PK = "target_column";
/**
* The configuration parameter holding the catalog name
*/
public static final String CATALOG = "catalog";
/**
* The configuration parameter holding the catalog name
*/
String CATALOG = "catalog";
/**
* The key under whcih to find the {@link org.hibernate.boot.model.naming.ObjectNameNormalizer} in the config param map.
*/
public static final String IDENTIFIER_NORMALIZER = "identifier_normalizer";
String IDENTIFIER_NORMALIZER = "identifier_normalizer";
/**
* The SQL required to create the underlying database objects.
*
* @param dialect The dialect against which to generate the create command(s)
* @return The create command(s)
* @throws HibernateException problem creating the create command(s)
*
* @return The create command(s)
*
* @throws HibernateException problem creating the create command(s)
* @deprecated Utilize the ExportableProducer contract instead
*/
@Deprecated
public String[] sqlCreateStrings(Dialect dialect) throws HibernateException;
String[] sqlCreateStrings(Dialect dialect) throws HibernateException;
/**
* The SQL required to remove the underlying database objects.
*
* @param dialect The dialect against which to generate the drop command(s)
* @return The drop command(s)
* @throws HibernateException problem creating the drop command(s)
*
* @return The drop command(s)
*
* @throws HibernateException problem creating the drop command(s)
* @deprecated Utilize the ExportableProducer contract instead
*/
@Deprecated
public String[] sqlDropStrings(Dialect dialect) throws HibernateException;
String[] sqlDropStrings(Dialect dialect) throws HibernateException;
/**
* Return a key unique to the underlying database objects. Prevents us from
* trying to create/remove them multiple times.
*
*
* @return Object an identifying key for this generator
*/
public Object generatorKey();
Object generatorKey();
}

View File

@ -31,8 +31,8 @@ import org.hibernate.id.insert.InsertGeneratedIdentifierDelegate;
* @author Gavin King
*/
public interface PostInsertIdentifierGenerator extends IdentifierGenerator {
public InsertGeneratedIdentifierDelegate getInsertGeneratedIdentifierDelegate(
InsertGeneratedIdentifierDelegate getInsertGeneratedIdentifierDelegate(
PostInsertIdentityPersister persister,
Dialect dialect,
boolean isGetGeneratedKeysEnabled) throws HibernateException;
Dialect dialect,
boolean isGetGeneratedKeysEnabled) throws HibernateException;
}

View File

@ -59,8 +59,8 @@ public class SelectGenerator extends AbstractPostInsertGenerator implements Conf
public InsertGeneratedIdentifierDelegate getInsertGeneratedIdentifierDelegate(
PostInsertIdentityPersister persister,
Dialect dialect,
boolean isGetGeneratedKeysEnabled) throws HibernateException {
Dialect dialect,
boolean isGetGeneratedKeysEnabled) throws HibernateException {
return new SelectGeneratorDelegate( persister, dialect, uniqueKeyPropertyName );
}
@ -69,25 +69,25 @@ public class SelectGenerator extends AbstractPostInsertGenerator implements Conf
return supplied;
}
int[] naturalIdPropertyIndices = persister.getNaturalIdentifierProperties();
if ( naturalIdPropertyIndices == null ){
if ( naturalIdPropertyIndices == null ) {
throw new IdentifierGenerationException(
"no natural-id property defined; need to specify [key] in " +
"generator parameters"
"generator parameters"
);
}
if ( naturalIdPropertyIndices.length > 1 ) {
throw new IdentifierGenerationException(
"select generator does not currently support composite " +
"natural-id properties; need to specify [key] in generator parameters"
"natural-id properties; need to specify [key] in generator parameters"
);
}
if ( persister.getEntityMetamodel().isNaturalIdentifierInsertGenerated() ) {
throw new IdentifierGenerationException(
"natural-id also defined as insert-generated; need to specify [key] " +
"in generator parameters"
"in generator parameters"
);
}
return persister.getPropertyNames() [ naturalIdPropertyIndices[0] ];
return persister.getPropertyNames()[naturalIdPropertyIndices[0]];
}
@ -108,8 +108,8 @@ public class SelectGenerator extends AbstractPostInsertGenerator implements Conf
private SelectGeneratorDelegate(
PostInsertIdentityPersister persister,
Dialect dialect,
String suppliedUniqueKeyPropertyName) {
Dialect dialect,
String suppliedUniqueKeyPropertyName) {
super( persister );
this.persister = persister;
this.dialect = dialect;
@ -133,23 +133,23 @@ public class SelectGenerator extends AbstractPostInsertGenerator implements Conf
protected void bindParameters(
SessionImplementor session,
PreparedStatement ps,
Object entity) throws SQLException {
PreparedStatement ps,
Object entity) throws SQLException {
Object uniqueKeyValue = persister.getPropertyValue( entity, uniqueKeyPropertyName );
uniqueKeyType.nullSafeSet( ps, uniqueKeyValue, 1, session );
}
protected Serializable getResult(
SessionImplementor session,
ResultSet rs,
Object entity) throws SQLException {
ResultSet rs,
Object entity) throws SQLException {
if ( !rs.next() ) {
throw new IdentifierGenerationException(
"the inserted row could not be located by the unique key: " +
uniqueKeyPropertyName
uniqueKeyPropertyName
);
}
return ( Serializable ) idType.nullSafeGet(
return (Serializable) idType.nullSafeGet(
rs,
persister.getRootTableKeyColumnNames(),
session,

View File

@ -63,7 +63,7 @@ import org.jboss.logging.Logger;
public class SequenceGenerator
implements PersistentIdentifierGenerator, BulkInsertionCapableIdentifierGenerator, Configurable {
private static final Logger LOG = Logger.getLogger( SequenceGenerator.class.getName() );
private static final Logger LOG = Logger.getLogger( SequenceGenerator.class.getName() );
/**
* The sequence parameter

View File

@ -54,7 +54,6 @@ import org.jboss.logging.Logger;
* are completely disabled.
*
* @author Steve Ebersole
*
* @deprecated See deprecation discussion on {@link SequenceGenerator}
*/
@Deprecated
@ -62,26 +61,26 @@ public class SequenceIdentityGenerator
extends SequenceGenerator
implements PostInsertIdentifierGenerator {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class,
SequenceIdentityGenerator.class.getName()
);
@Override
public Serializable generate(SessionImplementor s, Object obj) {
public Serializable generate(SessionImplementor s, Object obj) {
return IdentifierGeneratorHelper.POST_INSERT_INDICATOR;
}
@Override
public InsertGeneratedIdentifierDelegate getInsertGeneratedIdentifierDelegate(
PostInsertIdentityPersister persister,
Dialect dialect,
boolean isGetGeneratedKeysEnabled) throws HibernateException {
Dialect dialect,
boolean isGetGeneratedKeysEnabled) throws HibernateException {
return new Delegate( persister, dialect, getSequenceName() );
}
@Override
public void configure(Type type, Properties params, JdbcEnvironment env) throws MappingException {
public void configure(Type type, Properties params, JdbcEnvironment env) throws MappingException {
super.configure( type, params, env );
}
@ -107,13 +106,14 @@ public class SequenceIdentityGenerator
}
@Override
protected PreparedStatement prepare(String insertSQL, SessionImplementor session) throws SQLException {
protected PreparedStatement prepare(String insertSQL, SessionImplementor session) throws SQLException {
return session.getJdbcCoordinator().getStatementPreparer().prepareStatement( insertSQL, keyColumns );
}
@Override
protected Serializable executeAndExtract(PreparedStatement insert, SessionImplementor session) throws SQLException {
session.getJdbcCoordinator().getResultSetReturn().executeUpdate( insert );
protected Serializable executeAndExtract(PreparedStatement insert, SessionImplementor session)
throws SQLException {
session.getJdbcCoordinator().getResultSetReturn().executeUpdate( insert );
return IdentifierGeneratorHelper.getGeneratedIdentity(
insert.getGeneratedKeys(),
getPersister().getRootTableKeyColumnNames()[0],
@ -128,7 +128,7 @@ public class SequenceIdentityGenerator
}
@Override
public Insert setComment(String comment) {
public Insert setComment(String comment) {
// don't allow comments on these insert statements as comments totally
// blow up the Oracle getGeneratedKeys "support" :(
LOG.disallowingInsertStatementComment();

View File

@ -32,13 +32,12 @@ import org.hibernate.MappingException;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.uuid.StandardRandomStrategy;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.type.Type;
import org.hibernate.type.descriptor.java.UUIDTypeDescriptor;
import org.jboss.logging.Logger;
/**
* An {@link IdentifierGenerator} which generates {@link UUID} values using a pluggable
* {@link UUIDGenerationStrategy generation strategy}. The values this generator can return
@ -60,7 +59,7 @@ public class UUIDGenerator implements IdentifierGenerator, Configurable {
public static final String UUID_GEN_STRATEGY = "uuid_gen_strategy";
public static final String UUID_GEN_STRATEGY_CLASS = "uuid_gen_strategy_class";
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, UUIDGenerator.class.getName());
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( UUIDGenerator.class );
private UUIDGenerationStrategy strategy;
private UUIDTypeDescriptor.ValueTransformer valueTransformer;
@ -86,11 +85,11 @@ public class UUIDGenerator implements IdentifierGenerator, Configurable {
strategy = (UUIDGenerationStrategy) strategyClass.newInstance();
}
catch ( Exception ignore ) {
LOG.unableToInstantiateUuidGenerationStrategy(ignore);
LOG.unableToInstantiateUuidGenerationStrategy(ignore);
}
}
catch ( ClassNotFoundException ignore ) {
LOG.unableToLocateUuidGenerationStrategy(strategyClassName);
LOG.unableToLocateUuidGenerationStrategy(strategyClassName);
}
}
}

View File

@ -29,12 +29,11 @@ import java.util.Properties;
import org.hibernate.MappingException;
import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/**
* <b>uuid</b><br>
* <br>
@ -42,13 +41,13 @@ import org.jboss.logging.Logger;
* This string will consist of only hex digits. Optionally,
* the string may be generated with separators between each
* component of the UUID.
*
* <p/>
* Mapping parameters supported: separator.
*
* @author Gavin King
*/
public class UUIDHexGenerator extends AbstractUUIDGenerator implements Configurable {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, UUIDHexGenerator.class.getName());
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( UUIDHexGenerator.class );
private static boolean WARNED;
@ -57,7 +56,7 @@ public class UUIDHexGenerator extends AbstractUUIDGenerator implements Configura
public UUIDHexGenerator() {
if ( !WARNED ) {
WARNED = true;
LOG.usingUuidHexGenerator( this.getClass().getName(), UUIDGenerator.class.getName() );
LOG.usingUuidHexGenerator( this.getClass().getName(), UUIDGenerator.class.getName() );
}
}

View File

@ -61,7 +61,7 @@ import org.hibernate.type.Type;
public class DefaultIdentifierGeneratorFactory
implements MutableIdentifierGeneratorFactory, Serializable, ServiceRegistryAwareService {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( DefaultIdentifierGeneratorFactory.class );
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( DefaultIdentifierGeneratorFactory.class );
private JdbcEnvironment jdbcEnvironment;
private ConcurrentHashMap<String, Class> generatorStrategyToClassNameMap = new ConcurrentHashMap<String, Class>();

View File

@ -23,6 +23,7 @@
*
*/
package org.hibernate.id.insert;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@ -33,9 +34,9 @@ import org.hibernate.pretty.MessageHelper;
/**
* Abstract InsertGeneratedIdentifierDelegate implementation where the
* underlying strategy causes the enerated identitifer to be returned as an
* underlying strategy causes the generated identifier to be returned as an
* effect of performing the insert statement. Thus, there is no need for an
* additional sql statement to determine the generated identitifer.
* additional sql statement to determine the generated identifier.
*
* @author Steve Ebersole
*/
@ -46,6 +47,7 @@ public abstract class AbstractReturningDelegate implements InsertGeneratedIdenti
this.persister = persister;
}
@Override
public final Serializable performInsert(
String insertSQL,
SessionImplementor session,
@ -61,12 +63,12 @@ public abstract class AbstractReturningDelegate implements InsertGeneratedIdenti
releaseStatement( insert, session );
}
}
catch ( SQLException sqle ) {
catch (SQLException sqle) {
throw session.getFactory().getSQLExceptionHelper().convert(
sqle,
"could not insert: " + MessageHelper.infoString( persister ),
insertSQL
);
sqle,
"could not insert: " + MessageHelper.infoString( persister ),
insertSQL
);
}
}
@ -76,7 +78,8 @@ public abstract class AbstractReturningDelegate implements InsertGeneratedIdenti
protected abstract PreparedStatement prepare(String insertSQL, SessionImplementor session) throws SQLException;
protected abstract Serializable executeAndExtract(PreparedStatement insert, SessionImplementor session) throws SQLException;
protected abstract Serializable executeAndExtract(PreparedStatement insert, SessionImplementor session)
throws SQLException;
protected void releaseStatement(PreparedStatement insert, SessionImplementor session) throws SQLException {
session.getJdbcCoordinator().getResourceRegistry().release( insert );

View File

@ -20,9 +20,9 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.id.insert;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
@ -46,6 +46,7 @@ public abstract class AbstractSelectingDelegate implements InsertGeneratedIdenti
this.persister = persister;
}
@Override
public final Serializable performInsert(
String insertSQL,
SessionImplementor session,
@ -65,12 +66,12 @@ public abstract class AbstractSelectingDelegate implements InsertGeneratedIdenti
session.getJdbcCoordinator().afterStatementExecution();
}
}
catch ( SQLException sqle ) {
catch (SQLException sqle) {
throw session.getFactory().getSQLExceptionHelper().convert(
sqle,
"could not insert: " + MessageHelper.infoString( persister ),
insertSQL
);
sqle,
"could not insert: " + MessageHelper.infoString( persister ),
insertSQL
);
}
final String selectSQL = getSelectSQL();
@ -97,11 +98,11 @@ public abstract class AbstractSelectingDelegate implements InsertGeneratedIdenti
}
}
catch ( SQLException sqle ) {
catch (SQLException sqle) {
throw session.getFactory().getSQLExceptionHelper().convert(
sqle,
"could not retrieve generated id after insert: " + MessageHelper.infoString( persister ),
insertSQL
sqle,
"could not retrieve generated id after insert: " + MessageHelper.infoString( persister ),
insertSQL
);
}
}
@ -119,12 +120,13 @@ public abstract class AbstractSelectingDelegate implements InsertGeneratedIdenti
* @param session The session
* @param ps The prepared {@link #getSelectSQL SQL} command
* @param entity The entity being saved.
*
* @throws SQLException
*/
protected void bindParameters(
SessionImplementor session,
PreparedStatement ps,
Object entity) throws SQLException {
PreparedStatement ps,
Object entity) throws SQLException {
}
/**
@ -133,12 +135,14 @@ public abstract class AbstractSelectingDelegate implements InsertGeneratedIdenti
* @param session The session
* @param rs The result set containing the generated primay key values.
* @param entity The entity being saved.
*
* @return The generated identifier
*
* @throws SQLException
*/
protected abstract Serializable getResult(
SessionImplementor session,
ResultSet rs,
Object entity) throws SQLException;
ResultSet rs,
Object entity) throws SQLException;
}

View File

@ -82,18 +82,18 @@ public abstract class AbstractQueryImpl implements Query {
AbstractQueryImpl.class.getName()
);
private static final Object UNSET_PARAMETER = new MarkerObject("<unset parameter>");
private static final Object UNSET_TYPE = new MarkerObject("<unset type>");
private static final Object UNSET_PARAMETER = new MarkerObject( "<unset parameter>" );
private static final Object UNSET_TYPE = new MarkerObject( "<unset type>" );
private final String queryString;
protected final SessionImplementor session;
protected final ParameterMetadata parameterMetadata;
// parameter bind values...
private List values = new ArrayList(4);
private List types = new ArrayList(4);
private Map<String,TypedValue> namedParameters = new HashMap<String, TypedValue>(4);
private Map<String, TypedValue> namedParameterLists = new HashMap<String, TypedValue>(4);
private List values = new ArrayList( 4 );
private List types = new ArrayList( 4 );
private Map<String, TypedValue> namedParameters = new HashMap<String, TypedValue>( 4 );
private Map<String, TypedValue> namedParameterLists = new HashMap<String, TypedValue>( 4 );
private Object optionalObject;
private Serializable optionalId;
@ -111,14 +111,14 @@ public abstract class AbstractQueryImpl implements Query {
private Serializable collectionKey;
private Boolean readOnly;
private ResultTransformer resultTransformer;
private HQLQueryPlan queryPlan;
public AbstractQueryImpl(
String queryString,
FlushMode flushMode,
SessionImplementor session,
ParameterMetadata parameterMetadata) {
FlushMode flushMode,
SessionImplementor session,
ParameterMetadata parameterMetadata) {
this.session = session;
this.queryString = queryString;
this.selection = new RowSelection();
@ -159,7 +159,7 @@ public abstract class AbstractQueryImpl implements Query {
@Override
public Query setCacheRegion(String cacheRegion) {
if (cacheRegion != null) {
if ( cacheRegion != null ) {
this.cacheRegion = cacheRegion.trim();
}
return this;
@ -197,12 +197,12 @@ public abstract class AbstractQueryImpl implements Query {
this.comment = comment;
return this;
}
@Override
public Query addQueryHint(String queryHint) {
queryHints.add( queryHint );
return this;
}
}
@Override
public Integer getFirstResult() {
@ -211,7 +211,7 @@ public abstract class AbstractQueryImpl implements Query {
@Override
public Query setFirstResult(int firstResult) {
selection.setFirstRow( firstResult);
selection.setFirstRow( firstResult );
return this;
}
@ -227,7 +227,7 @@ public abstract class AbstractQueryImpl implements Query {
selection.setMaxRows( null );
}
else {
selection.setMaxRows( maxResults);
selection.setMaxRows( maxResults );
}
return this;
}
@ -239,7 +239,7 @@ public abstract class AbstractQueryImpl implements Query {
@Override
public Query setTimeout(int timeout) {
selection.setTimeout( timeout);
selection.setTimeout( timeout );
return this;
}
@ -250,7 +250,7 @@ public abstract class AbstractQueryImpl implements Query {
@Override
public Query setFetchSize(int fetchSize) {
selection.setFetchSize( fetchSize);
selection.setFetchSize( fetchSize );
return this;
}
@ -280,12 +280,13 @@ public abstract class AbstractQueryImpl implements Query {
this.readOnly = readOnly;
return this;
}
@Override
public Query setResultTransformer(ResultTransformer transformer) {
this.resultTransformer = transformer;
return this;
}
public void setOptionalEntityName(String optionalEntityName) {
this.optionalEntityName = optionalEntityName;
}
@ -301,6 +302,7 @@ public abstract class AbstractQueryImpl implements Query {
SessionImplementor getSession() {
return session;
}
@Override
public abstract LockOptions getLockOptions();
@ -328,6 +330,7 @@ public abstract class AbstractQueryImpl implements Query {
* holds true for all parameter metadata exposed here.
*
* @return Array of named parameter names.
*
* @throws HibernateException
*/
@Override
@ -382,7 +385,7 @@ public abstract class AbstractQueryImpl implements Query {
* @throws QueryException
*/
protected void verifyParameters() throws QueryException {
verifyParameters(false);
verifyParameters( false );
}
/**
@ -391,10 +394,12 @@ public abstract class AbstractQueryImpl implements Query {
*
* @param reserveFirstParameter if true, the first ? will not be verified since
* its needed for e.g. callable statements returning a out parameter
*
* @throws HibernateException
*/
protected void verifyParameters(boolean reserveFirstParameter) throws HibernateException {
if ( parameterMetadata.getNamedParameterNames().size() != namedParameters.size() + namedParameterLists.size() ) {
if ( parameterMetadata.getNamedParameterNames()
.size() != namedParameters.size() + namedParameterLists.size() ) {
Set<String> missingParams = new HashSet<String>( parameterMetadata.getNamedParameterNames() );
missingParams.removeAll( namedParameterLists.keySet() );
missingParams.removeAll( namedParameters.keySet() );
@ -404,8 +409,8 @@ public abstract class AbstractQueryImpl implements Query {
int positionalValueSpan = 0;
for ( int i = 0; i < values.size(); i++ ) {
Object object = types.get( i );
if( values.get( i ) == UNSET_PARAMETER || object == UNSET_TYPE ) {
if ( reserveFirstParameter && i==0 ) {
if ( values.get( i ) == UNSET_PARAMETER || object == UNSET_TYPE ) {
if ( reserveFirstParameter && i == 0 ) {
continue;
}
else {
@ -418,31 +423,31 @@ public abstract class AbstractQueryImpl implements Query {
if ( parameterMetadata.getOrdinalParameterCount() != positionalValueSpan ) {
if ( reserveFirstParameter && parameterMetadata.getOrdinalParameterCount() - 1 != positionalValueSpan ) {
throw new QueryException(
"Expected positional parameter count: " +
(parameterMetadata.getOrdinalParameterCount()-1) +
", actual parameters: " +
values,
getQueryString()
);
"Expected positional parameter count: " +
( parameterMetadata.getOrdinalParameterCount() - 1 ) +
", actual parameters: " +
values,
getQueryString()
);
}
else if ( !reserveFirstParameter ) {
throw new QueryException(
"Expected positional parameter count: " +
parameterMetadata.getOrdinalParameterCount() +
", actual parameters: " +
values,
getQueryString()
);
"Expected positional parameter count: " +
parameterMetadata.getOrdinalParameterCount() +
", actual parameters: " +
values,
getQueryString()
);
}
}
}
public Query setParameter(int position, Object val, Type type) {
if ( parameterMetadata.getOrdinalParameterCount() == 0 ) {
throw new IllegalArgumentException("No positional parameters in query: " + getQueryString() );
throw new IllegalArgumentException( "No positional parameters in query: " + getQueryString() );
}
if ( position < 0 || position > parameterMetadata.getOrdinalParameterCount() - 1 ) {
throw new IllegalArgumentException("Positional parameter does not exist: " + position + " in query: " + getQueryString() );
throw new IllegalArgumentException( "Positional parameter does not exist: " + position + " in query: " + getQueryString() );
}
int size = values.size();
if ( position < size ) {
@ -463,16 +468,16 @@ public abstract class AbstractQueryImpl implements Query {
public Query setParameter(String name, Object val, Type type) {
if ( !parameterMetadata.getNamedParameterNames().contains( name ) ) {
throw new IllegalArgumentException("Parameter " + name + " does not exist as a named parameter in [" + getQueryString() + "]");
throw new IllegalArgumentException( "Parameter " + name + " does not exist as a named parameter in [" + getQueryString() + "]" );
}
else {
namedParameters.put( name, new TypedValue( type, val ) );
return this;
namedParameters.put( name, new TypedValue( type, val ) );
return this;
}
}
public Query setParameter(int position, Object val) throws HibernateException {
if (val == null) {
if ( val == null ) {
setParameter( position, val, StandardBasicTypes.SERIALIZABLE );
}
else {
@ -482,7 +487,7 @@ public abstract class AbstractQueryImpl implements Query {
}
public Query setParameter(String name, Object val) throws HibernateException {
if (val == null) {
if ( val == null ) {
Type type = parameterMetadata.getNamedParameterExpectedType( name );
if ( type == null ) {
type = StandardBasicTypes.SERIALIZABLE;
@ -542,18 +547,18 @@ public abstract class AbstractQueryImpl implements Query {
private Type guessType(Class clazz) throws HibernateException {
String typename = clazz.getName();
Type type = session.getFactory().getTypeResolver().heuristicType(typename);
boolean serializable = type!=null && type instanceof SerializableType;
if (type==null || serializable) {
Type type = session.getFactory().getTypeResolver().heuristicType( typename );
boolean serializable = type != null && type instanceof SerializableType;
if ( type == null || serializable ) {
try {
session.getFactory().getEntityPersister( clazz.getName() );
}
catch (MappingException me) {
if (serializable) {
if ( serializable ) {
return type;
}
else {
throw new HibernateException("Could not determine a type for class: " + typename);
throw new HibernateException( "Could not determine a type for class: " + typename );
}
}
return ( (Session) session ).getTypeHelper().entity( clazz );
@ -564,7 +569,7 @@ public abstract class AbstractQueryImpl implements Query {
}
public Query setString(int position, String val) {
setParameter(position, val, StandardBasicTypes.STRING);
setParameter( position, val, StandardBasicTypes.STRING );
return this;
}
@ -581,62 +586,62 @@ public abstract class AbstractQueryImpl implements Query {
}
public Query setByte(int position, byte val) {
setParameter(position, val, StandardBasicTypes.BYTE);
setParameter( position, val, StandardBasicTypes.BYTE );
return this;
}
public Query setShort(int position, short val) {
setParameter(position, val, StandardBasicTypes.SHORT);
setParameter( position, val, StandardBasicTypes.SHORT );
return this;
}
public Query setInteger(int position, int val) {
setParameter(position, val, StandardBasicTypes.INTEGER);
setParameter( position, val, StandardBasicTypes.INTEGER );
return this;
}
public Query setLong(int position, long val) {
setParameter(position, val, StandardBasicTypes.LONG);
setParameter( position, val, StandardBasicTypes.LONG );
return this;
}
public Query setFloat(int position, float val) {
setParameter(position, val, StandardBasicTypes.FLOAT);
setParameter( position, val, StandardBasicTypes.FLOAT );
return this;
}
public Query setDouble(int position, double val) {
setParameter(position, val, StandardBasicTypes.DOUBLE);
setParameter( position, val, StandardBasicTypes.DOUBLE );
return this;
}
public Query setBinary(int position, byte[] val) {
setParameter(position, val, StandardBasicTypes.BINARY);
setParameter( position, val, StandardBasicTypes.BINARY );
return this;
}
public Query setText(int position, String val) {
setParameter(position, val, StandardBasicTypes.TEXT);
setParameter( position, val, StandardBasicTypes.TEXT );
return this;
}
public Query setSerializable(int position, Serializable val) {
setParameter(position, val, StandardBasicTypes.SERIALIZABLE);
setParameter( position, val, StandardBasicTypes.SERIALIZABLE );
return this;
}
public Query setDate(int position, Date date) {
setParameter(position, date, StandardBasicTypes.DATE);
setParameter( position, date, StandardBasicTypes.DATE );
return this;
}
public Query setTime(int position, Date date) {
setParameter(position, date, StandardBasicTypes.TIME);
setParameter( position, date, StandardBasicTypes.TIME );
return this;
}
public Query setTimestamp(int position, Date date) {
setParameter(position, date, StandardBasicTypes.TIMESTAMP);
setParameter( position, date, StandardBasicTypes.TIMESTAMP );
return this;
}
@ -653,27 +658,27 @@ public abstract class AbstractQueryImpl implements Query {
}
public Query setLocale(int position, Locale locale) {
setParameter(position, locale, StandardBasicTypes.LOCALE);
setParameter( position, locale, StandardBasicTypes.LOCALE );
return this;
}
public Query setCalendar(int position, Calendar calendar) {
setParameter(position, calendar, StandardBasicTypes.CALENDAR);
setParameter( position, calendar, StandardBasicTypes.CALENDAR );
return this;
}
public Query setCalendarDate(int position, Calendar calendar) {
setParameter(position, calendar, StandardBasicTypes.CALENDAR_DATE);
setParameter( position, calendar, StandardBasicTypes.CALENDAR_DATE );
return this;
}
public Query setBinary(String name, byte[] val) {
setParameter(name, val, StandardBasicTypes.BINARY);
setParameter( name, val, StandardBasicTypes.BINARY );
return this;
}
public Query setText(String name, String val) {
setParameter(name, val, StandardBasicTypes.TEXT);
setParameter( name, val, StandardBasicTypes.TEXT );
return this;
}
@ -685,22 +690,22 @@ public abstract class AbstractQueryImpl implements Query {
}
public Query setByte(String name, byte val) {
setParameter(name, val, StandardBasicTypes.BYTE);
setParameter( name, val, StandardBasicTypes.BYTE );
return this;
}
public Query setCharacter(String name, char val) {
setParameter(name, val, StandardBasicTypes.CHARACTER);
setParameter( name, val, StandardBasicTypes.CHARACTER );
return this;
}
public Query setDate(String name, Date date) {
setParameter(name, date, StandardBasicTypes.DATE);
setParameter( name, date, StandardBasicTypes.DATE );
return this;
}
public Query setDouble(String name, double val) {
setParameter(name, val, StandardBasicTypes.DOUBLE);
setParameter( name, val, StandardBasicTypes.DOUBLE );
return this;
}
@ -710,89 +715,89 @@ public abstract class AbstractQueryImpl implements Query {
}
public Query setFloat(String name, float val) {
setParameter(name, val, StandardBasicTypes.FLOAT);
setParameter( name, val, StandardBasicTypes.FLOAT );
return this;
}
public Query setInteger(String name, int val) {
setParameter(name, val, StandardBasicTypes.INTEGER);
setParameter( name, val, StandardBasicTypes.INTEGER );
return this;
}
public Query setLocale(String name, Locale locale) {
setParameter(name, locale, StandardBasicTypes.LOCALE);
setParameter( name, locale, StandardBasicTypes.LOCALE );
return this;
}
public Query setCalendar(String name, Calendar calendar) {
setParameter(name, calendar, StandardBasicTypes.CALENDAR);
setParameter( name, calendar, StandardBasicTypes.CALENDAR );
return this;
}
public Query setCalendarDate(String name, Calendar calendar) {
setParameter(name, calendar, StandardBasicTypes.CALENDAR_DATE);
setParameter( name, calendar, StandardBasicTypes.CALENDAR_DATE );
return this;
}
public Query setLong(String name, long val) {
setParameter(name, val, StandardBasicTypes.LONG);
setParameter( name, val, StandardBasicTypes.LONG );
return this;
}
public Query setSerializable(String name, Serializable val) {
setParameter(name, val, StandardBasicTypes.SERIALIZABLE);
setParameter( name, val, StandardBasicTypes.SERIALIZABLE );
return this;
}
public Query setShort(String name, short val) {
setParameter(name, val, StandardBasicTypes.SHORT);
setParameter( name, val, StandardBasicTypes.SHORT );
return this;
}
public Query setString(String name, String val) {
setParameter(name, val, StandardBasicTypes.STRING);
setParameter( name, val, StandardBasicTypes.STRING );
return this;
}
public Query setTime(String name, Date date) {
setParameter(name, date, StandardBasicTypes.TIME);
setParameter( name, date, StandardBasicTypes.TIME );
return this;
}
public Query setTimestamp(String name, Date date) {
setParameter(name, date, StandardBasicTypes.TIMESTAMP);
setParameter( name, date, StandardBasicTypes.TIMESTAMP );
return this;
}
public Query setBigDecimal(int position, BigDecimal number) {
setParameter(position, number, StandardBasicTypes.BIG_DECIMAL);
setParameter( position, number, StandardBasicTypes.BIG_DECIMAL );
return this;
}
public Query setBigDecimal(String name, BigDecimal number) {
setParameter(name, number, StandardBasicTypes.BIG_DECIMAL);
setParameter( name, number, StandardBasicTypes.BIG_DECIMAL );
return this;
}
public Query setBigInteger(int position, BigInteger number) {
setParameter(position, number, StandardBasicTypes.BIG_INTEGER);
setParameter( position, number, StandardBasicTypes.BIG_INTEGER );
return this;
}
public Query setBigInteger(String name, BigInteger number) {
setParameter(name, number, StandardBasicTypes.BIG_INTEGER);
setParameter( name, number, StandardBasicTypes.BIG_INTEGER );
return this;
}
@Override
public Query setParameterList(String name, Collection vals, Type type) throws HibernateException {
if ( !parameterMetadata.getNamedParameterNames().contains( name ) ) {
throw new IllegalArgumentException("Parameter " + name + " does not exist as a named parameter in [" + getQueryString() + "]");
throw new IllegalArgumentException( "Parameter " + name + " does not exist as a named parameter in [" + getQueryString() + "]" );
}
namedParameterLists.put( name, new TypedValue( type, vals ) );
return this;
}
/**
* Warning: adds new parameters to the argument by side-effect, as well as
* mutating the query string!
@ -812,7 +817,7 @@ public abstract class AbstractQueryImpl implements Query {
*/
private String expandParameterList(String query, String name, TypedValue typedList, Map namedParamsCopy) {
Collection vals = (Collection) typedList.getValue();
// HHH-1123
// Some DBs limit number of IN expressions. For now, warn...
final Dialect dialect = session.getFactory().getDialect();
@ -825,13 +830,10 @@ public abstract class AbstractQueryImpl implements Query {
boolean isJpaPositionalParam = parameterMetadata.getNamedParameterDescriptor( name ).isJpaStyle();
String paramPrefix = isJpaPositionalParam ? "?" : ParserHelper.HQL_VARIABLE_PREFIX;
String placeholder =
new StringBuilder( paramPrefix.length() + name.length() )
.append( paramPrefix ).append( name )
.toString();
String placeholder = paramPrefix + name;
if ( query == null ) {
return query;
return null;
}
int loc = query.indexOf( placeholder );
@ -840,15 +842,15 @@ public abstract class AbstractQueryImpl implements Query {
}
String beforePlaceholder = query.substring( 0, loc );
String afterPlaceholder = query.substring( loc + placeholder.length() );
String afterPlaceholder = query.substring( loc + placeholder.length() );
// check if placeholder is already immediately enclosed in parentheses
// (ignoring whitespace)
boolean isEnclosedInParens =
StringHelper.getLastNonWhitespaceCharacter( beforePlaceholder ) == '(' &&
StringHelper.getFirstNonWhitespaceCharacter( afterPlaceholder ) == ')';
StringHelper.getFirstNonWhitespaceCharacter( afterPlaceholder ) == ')';
if ( vals.size() == 1 && isEnclosedInParens ) {
if ( vals.size() == 1 && isEnclosedInParens ) {
// short-circuit for performance when only 1 value and the
// placeholder is already enclosed in parentheses...
namedParamsCopy.put( name, new TypedValue( type, vals.iterator().next() ) );
@ -885,18 +887,18 @@ public abstract class AbstractQueryImpl implements Query {
throw new QueryException( "Collection must be not null!" );
}
if( vals.size() == 0 ) {
if ( vals.size() == 0 ) {
setParameterList( name, vals, null );
}
else {
setParameterList(name, vals, determineType( name, vals.iterator().next() ) );
setParameterList( name, vals, determineType( name, vals.iterator().next() ) );
}
return this;
}
public Query setParameterList(String name, Object[] vals, Type type) throws HibernateException {
return setParameterList( name, Arrays.asList(vals), type );
return setParameterList( name, Arrays.asList( vals ), type );
}
public Query setParameterList(String name, Object[] values) throws HibernateException {
@ -905,42 +907,41 @@ public abstract class AbstractQueryImpl implements Query {
public Query setProperties(Map map) throws HibernateException {
String[] params = getNamedParameters();
for (int i = 0; i < params.length; i++) {
for ( int i = 0; i < params.length; i++ ) {
String namedParam = params[i];
final Object object = map.get(namedParam);
if(object==null) {
continue;
}
Class retType = object.getClass();
if ( Collection.class.isAssignableFrom( retType ) ) {
setParameterList( namedParam, ( Collection ) object );
}
else if ( retType.isArray() ) {
setParameterList( namedParam, ( Object[] ) object );
}
else {
setParameter( namedParam, object, determineType( namedParam, retType ) );
}
final Object object = map.get( namedParam );
if ( object == null ) {
continue;
}
Class retType = object.getClass();
if ( Collection.class.isAssignableFrom( retType ) ) {
setParameterList( namedParam, (Collection) object );
}
else if ( retType.isArray() ) {
setParameterList( namedParam, (Object[]) object );
}
else {
setParameter( namedParam, object, determineType( namedParam, retType ) );
}
}
return this;
return this;
}
public Query setProperties(Object bean) throws HibernateException {
Class clazz = bean.getClass();
String[] params = getNamedParameters();
for (int i = 0; i < params.length; i++) {
String namedParam = params[i];
for ( String namedParam : params ) {
try {
Getter getter = ReflectHelper.getGetter( clazz, namedParam );
Class retType = getter.getReturnType();
final Object object = getter.get( bean );
if ( Collection.class.isAssignableFrom( retType ) ) {
setParameterList( namedParam, ( Collection ) object );
setParameterList( namedParam, (Collection) object );
}
else if ( retType.isArray() ) {
setParameterList( namedParam, ( Object[] ) object );
setParameterList( namedParam, (Object[]) object );
}
else {
setParameter( namedParam, object, determineType( namedParam, retType ) );
@ -954,8 +955,8 @@ public abstract class AbstractQueryImpl implements Query {
}
public Query setParameters(Object[] values, Type[] types) {
this.values = Arrays.asList(values);
this.types = Arrays.asList(types);
this.values = Arrays.asList( values );
this.types = Arrays.asList( types );
return this;
}
@ -968,12 +969,12 @@ public abstract class AbstractQueryImpl implements Query {
static Object uniqueElement(List list) throws NonUniqueResultException {
int size = list.size();
if (size==0) {
if ( size == 0 ) {
return null;
}
Object first = list.get(0);
for ( int i=1; i<size; i++ ) {
if ( list.get(i)!=first ) {
Object first = list.get( 0 );
for ( int i = 1; i < size; i++ ) {
if ( list.get( i ) != first ) {
throw new NonUniqueResultException( list.size() );
}
}
@ -987,7 +988,7 @@ public abstract class AbstractQueryImpl implements Query {
public Type[] typeArray() {
return ArrayHelper.toTypeArray( getTypes() );
}
public Object[] valueArray() {
return getValues().toArray();
}
@ -1005,7 +1006,7 @@ public abstract class AbstractQueryImpl implements Query {
cacheRegion,
comment,
queryHints,
collectionKey == null ? null : new Serializable[] { collectionKey },
collectionKey == null ? null : new Serializable[] {collectionKey},
optionalObject,
optionalEntityName,
optionalId,
@ -1014,25 +1015,25 @@ public abstract class AbstractQueryImpl implements Query {
queryParameters.setQueryPlan( queryPlan );
return queryParameters;
}
protected void before() {
if ( flushMode!=null ) {
if ( flushMode != null ) {
sessionFlushMode = getSession().getFlushMode();
getSession().setFlushMode(flushMode);
getSession().setFlushMode( flushMode );
}
if ( cacheMode!=null ) {
if ( cacheMode != null ) {
sessionCacheMode = getSession().getCacheMode();
getSession().setCacheMode(cacheMode);
getSession().setCacheMode( cacheMode );
}
}
protected void after() {
if (sessionFlushMode!=null) {
getSession().setFlushMode(sessionFlushMode);
if ( sessionFlushMode != null ) {
getSession().setFlushMode( sessionFlushMode );
sessionFlushMode = null;
}
if (sessionCacheMode!=null) {
getSession().setCacheMode(sessionCacheMode);
if ( sessionCacheMode != null ) {
getSession().setCacheMode( sessionCacheMode );
sessionCacheMode = null;
}
}

View File

@ -43,19 +43,13 @@ import org.hibernate.loader.Loader;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.Type;
import org.jboss.logging.Logger;
/**
* Base implementation of the ScrollableResults interface.
*
* @author Steve Ebersole
*/
public abstract class AbstractScrollableResults implements ScrollableResults {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class,
AbstractScrollableResults.class.getName()
);
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( AbstractScrollableResults.class );
private final ResultSet resultSet;
private final PreparedStatement ps;
@ -66,22 +60,22 @@ public abstract class AbstractScrollableResults implements ScrollableResults {
private HolderInstantiator holderInstantiator;
protected AbstractScrollableResults(
ResultSet rs,
PreparedStatement ps,
SessionImplementor sess,
ResultSet rs,
PreparedStatement ps,
SessionImplementor sess,
Loader loader,
QueryParameters queryParameters,
Type[] types,
HolderInstantiator holderInstantiator) {
this.resultSet=rs;
this.ps=ps;
Type[] types,
HolderInstantiator holderInstantiator) {
this.resultSet = rs;
this.ps = ps;
this.session = sess;
this.loader = loader;
this.queryParameters = queryParameters;
this.types = types;
this.holderInstantiator = holderInstantiator!=null && holderInstantiator.isRequired()
? holderInstantiator
: null;
this.holderInstantiator = holderInstantiator != null && holderInstantiator.isRequired()
? holderInstantiator
: null;
}
protected abstract Object[] getCurrentRow();
@ -123,7 +117,7 @@ public abstract class AbstractScrollableResults implements ScrollableResults {
try {
session.getPersistenceContext().getLoadContexts().cleanup( resultSet );
}
catch( Throwable ignore ) {
catch (Throwable ignore) {
// ignore this error for now
if ( LOG.isTraceEnabled() ) {
LOG.tracev( "Exception trying to cleanup load context : {0}", ignore.getMessage() );
@ -150,15 +144,15 @@ public abstract class AbstractScrollableResults implements ScrollableResults {
* @param returnType a "final" type
*/
protected final Object getFinal(int col, Type returnType) throws HibernateException {
if ( holderInstantiator!=null ) {
throw new HibernateException("query specifies a holder class");
if ( holderInstantiator != null ) {
throw new HibernateException( "query specifies a holder class" );
}
if ( returnType.getReturnedClass()==types[col].getReturnedClass() ) {
return get(col);
if ( returnType.getReturnedClass() == types[col].getReturnedClass() ) {
return get( col );
}
else {
return throwInvalidColumnTypeException(col, types[col], returnType);
return throwInvalidColumnTypeException( col, types[col], returnType );
}
}
@ -171,111 +165,111 @@ public abstract class AbstractScrollableResults implements ScrollableResults {
* @param returnType any type
*/
protected final Object getNonFinal(int col, Type returnType) throws HibernateException {
if ( holderInstantiator!=null ) {
throw new HibernateException("query specifies a holder class");
if ( holderInstantiator != null ) {
throw new HibernateException( "query specifies a holder class" );
}
if ( returnType.getReturnedClass().isAssignableFrom( types[col].getReturnedClass() ) ) {
return get(col);
return get( col );
}
else {
return throwInvalidColumnTypeException(col, types[col], returnType);
return throwInvalidColumnTypeException( col, types[col], returnType );
}
}
@Override
public final BigDecimal getBigDecimal(int col) throws HibernateException {
return (BigDecimal) getFinal(col, StandardBasicTypes.BIG_DECIMAL);
return (BigDecimal) getFinal( col, StandardBasicTypes.BIG_DECIMAL );
}
@Override
public final BigInteger getBigInteger(int col) throws HibernateException {
return (BigInteger) getFinal(col, StandardBasicTypes.BIG_INTEGER);
return (BigInteger) getFinal( col, StandardBasicTypes.BIG_INTEGER );
}
@Override
public final byte[] getBinary(int col) throws HibernateException {
return (byte[]) getFinal(col, StandardBasicTypes.BINARY);
return (byte[]) getFinal( col, StandardBasicTypes.BINARY );
}
@Override
public final String getText(int col) throws HibernateException {
return (String) getFinal(col, StandardBasicTypes.TEXT);
return (String) getFinal( col, StandardBasicTypes.TEXT );
}
@Override
public final Blob getBlob(int col) throws HibernateException {
return (Blob) getNonFinal(col, StandardBasicTypes.BLOB);
return (Blob) getNonFinal( col, StandardBasicTypes.BLOB );
}
@Override
public final Clob getClob(int col) throws HibernateException {
return (Clob) getNonFinal(col, StandardBasicTypes.CLOB);
return (Clob) getNonFinal( col, StandardBasicTypes.CLOB );
}
@Override
public final Boolean getBoolean(int col) throws HibernateException {
return (Boolean) getFinal(col, StandardBasicTypes.BOOLEAN);
return (Boolean) getFinal( col, StandardBasicTypes.BOOLEAN );
}
@Override
public final Byte getByte(int col) throws HibernateException {
return (Byte) getFinal(col, StandardBasicTypes.BYTE);
return (Byte) getFinal( col, StandardBasicTypes.BYTE );
}
@Override
public final Character getCharacter(int col) throws HibernateException {
return (Character) getFinal(col, StandardBasicTypes.CHARACTER);
return (Character) getFinal( col, StandardBasicTypes.CHARACTER );
}
@Override
public final Date getDate(int col) throws HibernateException {
return (Date) getNonFinal(col, StandardBasicTypes.TIMESTAMP);
return (Date) getNonFinal( col, StandardBasicTypes.TIMESTAMP );
}
@Override
public final Calendar getCalendar(int col) throws HibernateException {
return (Calendar) getNonFinal(col, StandardBasicTypes.CALENDAR);
return (Calendar) getNonFinal( col, StandardBasicTypes.CALENDAR );
}
@Override
public final Double getDouble(int col) throws HibernateException {
return (Double) getFinal(col, StandardBasicTypes.DOUBLE);
return (Double) getFinal( col, StandardBasicTypes.DOUBLE );
}
@Override
public final Float getFloat(int col) throws HibernateException {
return (Float) getFinal(col, StandardBasicTypes.FLOAT);
return (Float) getFinal( col, StandardBasicTypes.FLOAT );
}
@Override
public final Integer getInteger(int col) throws HibernateException {
return (Integer) getFinal(col, StandardBasicTypes.INTEGER);
return (Integer) getFinal( col, StandardBasicTypes.INTEGER );
}
@Override
public final Long getLong(int col) throws HibernateException {
return (Long) getFinal(col, StandardBasicTypes.LONG);
return (Long) getFinal( col, StandardBasicTypes.LONG );
}
@Override
public final Short getShort(int col) throws HibernateException {
return (Short) getFinal(col, StandardBasicTypes.SHORT);
return (Short) getFinal( col, StandardBasicTypes.SHORT );
}
@Override
public final String getString(int col) throws HibernateException {
return (String) getFinal(col, StandardBasicTypes.STRING);
return (String) getFinal( col, StandardBasicTypes.STRING );
}
@Override
public final Locale getLocale(int col) throws HibernateException {
return (Locale) getFinal(col, StandardBasicTypes.LOCALE);
return (Locale) getFinal( col, StandardBasicTypes.LOCALE );
}
@Override
public final TimeZone getTimeZone(int col) throws HibernateException {
return (TimeZone) getNonFinal(col, StandardBasicTypes.TIMEZONE);
return (TimeZone) getNonFinal( col, StandardBasicTypes.TIMEZONE );
}
@Override
@ -284,14 +278,14 @@ public abstract class AbstractScrollableResults implements ScrollableResults {
}
private Object throwInvalidColumnTypeException(
int i,
Type type,
Type returnType) throws HibernateException {
int i,
Type type,
Type returnType) throws HibernateException {
throw new HibernateException(
"incompatible column types: " +
type.getName() +
", " +
returnType.getName()
type.getName() +
", " +
returnType.getName()
);
}

View File

@ -105,6 +105,7 @@ public abstract class AbstractSessionImpl
}
}
@Override
public SessionFactoryImplementor getFactory() {
return factory;
}
@ -208,8 +209,8 @@ public abstract class AbstractSessionImpl
}
Query query = new SQLQueryImpl(
nsqlqd,
this,
factory.getQueryPlanCache().getSQLParameterMetadata( nsqlqd.getQueryString() )
this,
factory.getQueryPlanCache().getSQLParameterMetadata( nsqlqd.getQueryString() )
);
query.setComment( "named native SQL query " + queryName );
initQuery( query, nsqlqd );

View File

@ -44,16 +44,12 @@ import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper;
import org.jboss.logging.Logger;
/**
* @author Strong Liu <stliu@hibernate.org>
*/
public class CacheImpl implements CacheImplementor {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class,
CacheImpl.class.getName()
);
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( CacheImpl.class );
private final SessionFactoryImplementor sessionFactory;
private final SessionFactoryOptions settings;
private final transient QueryCache queryCache;
@ -231,10 +227,10 @@ public class CacheImpl implements CacheImplementor {
@Override
public void evictDefaultQueryRegion() {
if ( sessionFactory.getSettings().isQueryCacheEnabled() ) {
if ( LOG.isDebugEnabled() ) {
LOG.debug( "Evicting default query region cache." );
}
if ( sessionFactory.getSessionFactoryOptions().isQueryCacheEnabled() ) {
if ( LOG.isDebugEnabled() ) {
LOG.debug( "Evicting default query region cache." );
}
sessionFactory.getQueryCache().clear();
}
}
@ -246,13 +242,13 @@ public class CacheImpl implements CacheImplementor {
"Region-name cannot be null (use Cache#evictDefaultQueryRegion to evict the default query cache)"
);
}
if ( sessionFactory.getSettings().isQueryCacheEnabled() ) {
if ( sessionFactory.getSessionFactoryOptions().isQueryCacheEnabled() ) {
QueryCache namedQueryCache = queryCaches.get( regionName );
// TODO : cleanup entries in queryCaches + allCacheRegions ?
if ( namedQueryCache != null ) {
if ( LOG.isDebugEnabled() ) {
LOG.debugf( "Evicting query cache, region: %s", regionName );
}
if ( LOG.isDebugEnabled() ) {
LOG.debugf( "Evicting query cache, region: %s", regionName );
}
namedQueryCache.clear();
}
}
@ -261,13 +257,13 @@ public class CacheImpl implements CacheImplementor {
@Override
public void evictQueryRegions() {
evictDefaultQueryRegion();
if ( CollectionHelper.isEmpty( queryCaches ) ) {
return;
}
if ( LOG.isDebugEnabled() ) {
LOG.debug( "Evicting cache of all query regions." );
}
if ( LOG.isDebugEnabled() ) {
LOG.debug( "Evicting cache of all query regions." );
}
for ( QueryCache queryCache : queryCaches.values() ) {
queryCache.clear();
}
@ -278,9 +274,7 @@ public class CacheImpl implements CacheImplementor {
if ( settings.isQueryCacheEnabled() ) {
queryCache.destroy();
Iterator iter = queryCaches.values().iterator();
while ( iter.hasNext() ) {
QueryCache cache = (QueryCache) iter.next();
for ( QueryCache cache : queryCaches.values() ) {
cache.destroy();
}
updateTimestampsCache.destroy();
@ -306,7 +300,7 @@ public class CacheImpl implements CacheImplementor {
QueryCache currentQueryCache = queryCaches.get( regionName );
if ( currentQueryCache == null ) {
synchronized ( allCacheRegions ) {
synchronized (allCacheRegions) {
currentQueryCache = queryCaches.get( regionName );
if ( currentQueryCache == null ) {
currentQueryCache = settings.getQueryCacheFactory()
@ -354,17 +348,17 @@ public class CacheImpl implements CacheImplementor {
return allCacheRegions.get( regionName );
}
@SuppressWarnings({ "unchecked" })
@SuppressWarnings({"unchecked"})
@Override
public Map<String, Region> getAllSecondLevelCacheRegions() {
return new HashMap<String,Region>( allCacheRegions );
return new HashMap<String, Region>( allCacheRegions );
}
@Override
public RegionFactory getRegionFactory() {
return regionFactory;
}
@Override
public void evictAllRegions() {
evictCollectionRegions();

View File

@ -20,9 +20,9 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.internal;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@ -35,6 +35,7 @@ import org.hibernate.type.Type;
/**
* implementation of the <tt>Query</tt> interface for collection filters
*
* @author Gavin King
*/
public class CollectionFilterImpl extends QueryImpl {
@ -43,9 +44,9 @@ public class CollectionFilterImpl extends QueryImpl {
public CollectionFilterImpl(
String queryString,
Object collection,
SessionImplementor session,
ParameterMetadata parameterMetadata) {
Object collection,
SessionImplementor session,
ParameterMetadata parameterMetadata) {
super( queryString, session, parameterMetadata );
this.collection = collection;
}
@ -57,10 +58,10 @@ public class CollectionFilterImpl extends QueryImpl {
public Iterator iterate() throws HibernateException {
verifyParameters();
Map namedParams = getNamedParams();
return getSession().iterateFilter(
collection,
expandParameterLists(namedParams),
getQueryParameters(namedParams)
return getSession().iterateFilter(
collection,
expandParameterLists( namedParams ),
getQueryParameters( namedParams )
);
}
@ -70,10 +71,10 @@ public class CollectionFilterImpl extends QueryImpl {
public List list() throws HibernateException {
verifyParameters();
Map namedParams = getNamedParams();
return getSession().listFilter(
collection,
expandParameterLists(namedParams),
getQueryParameters(namedParams)
return getSession().listFilter(
collection,
expandParameterLists( namedParams ),
getQueryParameters( namedParams )
);
}
@ -81,15 +82,15 @@ public class CollectionFilterImpl extends QueryImpl {
* @see org.hibernate.Query#scroll()
*/
public ScrollableResults scroll() throws HibernateException {
throw new UnsupportedOperationException("Can't scroll filters");
throw new UnsupportedOperationException( "Can't scroll filters" );
}
public Type[] typeArray() {
List typeList = getTypes();
int size = typeList.size();
Type[] result = new Type[size+1];
for (int i=0; i<size; i++) {
result[i+1] = (Type) typeList.get(i);
Type[] result = new Type[size + 1];
for ( int i = 0; i < size; i++ ) {
result[i + 1] = (Type) typeList.get( i );
}
return result;
}
@ -97,9 +98,9 @@ public class CollectionFilterImpl extends QueryImpl {
public Object[] valueArray() {
List valueList = getValues();
int size = valueList.size();
Object[] result = new Object[size+1];
for (int i=0; i<size; i++) {
result[i+1] = valueList.get(i);
Object[] result = new Object[size + 1];
for ( int i = 0; i < size; i++ ) {
result[i + 1] = valueList.get( i );
}
return result;
}

View File

@ -102,8 +102,7 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "I/O reported cached file could not be found : %s : %s", id = 23)
void cachedFileNotFound(String path,
FileNotFoundException error);
void cachedFileNotFound(String path, FileNotFoundException error);
@LogMessage(level = INFO)
@Message(value = "Cache provider: %s", id = 24)
@ -216,8 +215,7 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "DEPRECATED : use [%s] instead with custom [%s] implementation", id = 65)
void deprecatedUuidGenerator(String name,
String name2);
void deprecatedUuidGenerator(String name, String name2);
@LogMessage(level = INFO)
@Message(value = "Disallowing insert statement comment for select-identity due to Oracle driver bug", id = 67)
@ -233,8 +231,7 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = INFO)
@Message(value = "Duplicate import: %s -> %s", id = 71)
void duplicateImport(String entityName,
String rename);
void duplicateImport(String entityName, String rename);
@LogMessage(level = WARN)
@Message(value = "Duplicate joins for class: %s", id = 72)
@ -283,13 +280,11 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = INFO)
@Message(value = "%s %s found", id = 85)
void exceptionHeaderFound(String exceptionHeader,
String metaInfOrmXml);
void exceptionHeaderFound(String exceptionHeader, String metaInfOrmXml);
@LogMessage(level = INFO)
@Message(value = "%s No %s found", id = 86)
void exceptionHeaderNotFound(String exceptionHeader,
String metaInfOrmXml);
void exceptionHeaderNotFound(String exceptionHeader, String metaInfOrmXml);
@LogMessage(level = ERROR)
@Message(value = "Exception in interceptor afterTransactionCompletion()", id = 87)
@ -306,7 +301,7 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = ERROR)
@Message(value = "Expected type: %s, actual value: %s", id = 91)
void expectedType(String name,
String string);
String string);
@LogMessage(level = WARN)
@Message(value = "An item was expired by the cache while it was locked (increase your cache timeout): %s", id = 92)
@ -372,8 +367,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = ERROR)
@Message(value = "Getters of lazy classes cannot be final: %s.%s", id = 112)
void gettersOfLazyClassesCannotBeFinal(String entityName,
String name);
void gettersOfLazyClassesCannotBeFinal(
String entityName,
String name);
@LogMessage(level = WARN)
@Message(value = "GUID identifier generated: %s", id = 113)
@ -389,15 +385,17 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "Config specified explicit optimizer of [%s], but [%s=%s; honoring optimizer setting", id = 116)
void honoringOptimizerSetting(String none,
String incrementParam,
int incrementSize);
void honoringOptimizerSetting(
String none,
String incrementParam,
int incrementSize);
@LogMessage(level = DEBUG)
@Message(value = "HQL: %s, time: %sms, rows: %s", id = 117)
void hql(String hql,
Long valueOf,
Long valueOf2);
void hql(
String hql,
Long valueOf,
Long valueOf2);
@LogMessage(level = WARN)
@Message(value = "HSQLDB supports only READ_UNCOMMITTED isolation", id = 118)
@ -417,13 +415,15 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = ERROR)
@Message(value = "IllegalArgumentException in class: %s, getter method of property: %s", id = 122)
void illegalPropertyGetterArgument(String name,
String propertyName);
void illegalPropertyGetterArgument(
String name,
String propertyName);
@LogMessage(level = ERROR)
@Message(value = "IllegalArgumentException in class: %s, setter method of property: %s", id = 123)
void illegalPropertySetterArgument(String name,
String propertyName);
void illegalPropertySetterArgument(
String name,
String propertyName);
@LogMessage(level = WARN)
@Message(value = "@Immutable used on a non root entity: ignored for %s", id = 124)
@ -460,8 +460,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = ERROR)
@Message(value = "Invalid JNDI name: %s", id = 135)
void invalidJndiName(String name,
@Cause JndiNameException e);
void invalidJndiName(
String name,
@Cause JndiNameException e);
@LogMessage(level = WARN)
@Message(value = "Inapropriate use of @OnDelete on entity, annotation ignored: %s", id = 136)
@ -486,9 +487,10 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = INFO)
@Message(value = "java.sql.Types mapped the same code [%s] multiple times; was [%s]; now [%s]", id = 141)
void JavaSqlTypesMappedSameCodeMultipleTimes(int code,
String old,
String name);
void JavaSqlTypesMappedSameCodeMultipleTimes(
int code,
String old,
String name);
@Message(value = "Javassist Enhancement failed: %s", id = 142)
String javassistEnhancementFailed(String entityName);
@ -517,8 +519,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = ERROR)
@Message(value = "JNDI name %s does not handle a session factory reference", id = 155)
void jndiNameDoesNotHandleSessionFactoryReference(String sfJNDIName,
@Cause ClassCastException e);
void jndiNameDoesNotHandleSessionFactoryReference(
String sfJNDIName,
@Cause ClassCastException e);
@LogMessage(level = INFO)
@Message(value = "Lazy property fetching available for: %s", id = 157)
@ -551,8 +554,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "Function template anticipated %s arguments, but %s arguments encountered", id = 174)
void missingArguments(int anticipatedNumberOfArguments,
int numberOfArguments);
void missingArguments(
int anticipatedNumberOfArguments,
int numberOfArguments);
@LogMessage(level = WARN)
@Message(value = "Class annotated @org.hibernate.annotations.Entity but not javax.persistence.Entity (most likely a user error): %s",
@ -562,8 +566,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = ERROR)
@Message(value = "Error in named query: %s", id = 177)
void namedQueryError(String queryName,
@Cause HibernateException e);
void namedQueryError(
String queryName,
@Cause HibernateException e);
@LogMessage(level = WARN)
@Message(value = "Naming exception occurred accessing factory: %s", id = 178)
@ -593,8 +598,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = ERROR)
@Message(value = "No session factory with JNDI name %s", id = 184)
void noSessionFactoryWithJndiName(String sfJNDIName,
@Cause NameNotFoundException e);
void noSessionFactoryWithJndiName(
String sfJNDIName,
@Cause NameNotFoundException e);
@LogMessage(level = INFO)
@Message(value = "Optimistic lock failures: %s", id = 187)
@ -618,25 +624,29 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = ERROR)
@Message(value = "Error parsing XML (%s) : %s", id = 196)
void parsingXmlError(int lineNumber,
String message);
void parsingXmlError(
int lineNumber,
String message);
@LogMessage(level = ERROR)
@Message(value = "Error parsing XML: %s(%s) %s", id = 197)
void parsingXmlErrorForFile(String file,
int lineNumber,
String message);
void parsingXmlErrorForFile(
String file,
int lineNumber,
String message);
@LogMessage(level = ERROR)
@Message(value = "Warning parsing XML (%s) : %s", id = 198)
void parsingXmlWarning(int lineNumber,
String message);
void parsingXmlWarning(
int lineNumber,
String message);
@LogMessage(level = WARN)
@Message(value = "Warning parsing XML: %s(%s) %s", id = 199)
void parsingXmlWarningForFile(String file,
int lineNumber,
String message);
void parsingXmlWarningForFile(
String file,
int lineNumber,
String message);
@LogMessage(level = WARN)
@Message(value = "Persistence provider caller does not implement the EJB3 spec correctly."
@ -674,8 +684,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "%s has been deprecated in favor of %s; that provider will be used instead.", id = 208)
void providerClassDeprecated(String providerClassName,
String actualProviderClassName);
void providerClassDeprecated(
String providerClassName,
String actualProviderClassName);
@LogMessage(level = WARN)
@Message(value = "proxool properties were encountered, but the %s provider class was not found on the classpath; these properties are going to be ignored.",
@ -721,13 +732,15 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "Recognized obsolete hibernate namespace %s. Use namespace %s instead. Refer to Hibernate 3.6 Migration Guide!",
id = 223)
void recognizedObsoleteHibernateNamespace(String oldHibernateNamespace,
String hibernateNamespace);
void recognizedObsoleteHibernateNamespace(
String oldHibernateNamespace,
String hibernateNamespace);
@LogMessage(level = WARN)
@Message(value = "Property [%s] has been renamed to [%s]; update your properties appropriately", id = 225)
void renamedProperty(Object propertyName,
Object newPropertyName);
void renamedProperty(
Object propertyName,
Object newPropertyName);
@LogMessage(level = INFO)
@Message(value = "Required a different provider: %s", id = 226)
@ -759,8 +772,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "Scoping types to session factory %s after already scoped %s", id = 233)
void scopingTypesToSessionFactoryAfterAlreadyScoped(SessionFactoryImplementor factory,
SessionFactoryImplementor factory2);
void scopingTypesToSessionFactoryAfterAlreadyScoped(
SessionFactoryImplementor factory,
SessionFactoryImplementor factory2);
@LogMessage(level = INFO)
@Message(value = "Searching for mapping documents in jar: %s", id = 235)
@ -792,8 +806,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = ERROR)
@Message(value = "Setters of lazy classes cannot be final: %s.%s", id = 243)
void settersOfLazyClassesCannotBeFinal(String entityName,
String name);
void settersOfLazyClassesCannotBeFinal(
String entityName,
String name);
@LogMessage(level = WARN)
@Message(value = "@Sort not allowed for an indexed collection, annotation ignored.", id = 244)
@ -801,8 +816,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "Manipulation query [%s] resulted in [%s] split queries", id = 245)
void splitQueries(String sourceQuery,
int length);
void splitQueries(
String sourceQuery,
int length);
// @LogMessage(level = ERROR)
// @Message(value = "SQLException escaped proxy", id = 246)
@ -810,8 +826,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "SQL Error: %s, SQLState: %s", id = 247)
void sqlWarning(int errorCode,
String sqlState);
void sqlWarning(
int errorCode,
String sqlState);
@LogMessage(level = INFO)
@Message(value = "Starting query cache at region: %s", id = 248)
@ -855,8 +872,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = ERROR)
@Message(value = "Exception calling user Synchronization [%s] : %s", id = 260)
void synchronizationFailed(Synchronization synchronization,
Throwable t);
void synchronizationFailed(
Synchronization synchronization,
Throwable t);
@LogMessage(level = INFO)
@Message(value = "Table found: %s", id = 261)
@ -888,8 +906,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = INFO)
@Message(value = "Type registration [%s] overrides previous : %s", id = 270)
void typeRegistrationOverridesPrevious(String key,
Type old);
void typeRegistrationOverridesPrevious(
String key,
Type old);
@LogMessage(level = WARN)
@Message(value = "Naming exception occurred accessing Ejb3Configuration", id = 271)
@ -897,8 +916,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = ERROR)
@Message(value = "Error while accessing session factory with JNDI name %s", id = 272)
void unableToAccessSessionFactory(String sfJNDIName,
@Cause NamingException e);
void unableToAccessSessionFactory(
String sfJNDIName,
@Cause NamingException e);
@LogMessage(level = WARN)
@Message(value = "Error accessing type info result set : %s", id = 273)
@ -906,8 +926,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "Unable to apply constraints on DDL for %s", id = 274)
void unableToApplyConstraints(String className,
@Cause Exception e);
void unableToApplyConstraints(
String className,
@Cause Exception e);
@LogMessage(level = WARN)
@Message(value = "Could not bind Ejb3Configuration to JNDI", id = 276)
@ -919,9 +940,10 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = INFO)
@Message(value = "Could not bind value '%s' to parameter: %s; %s", id = 278)
void unableToBindValueToParameter(String nullSafeToString,
int index,
String message);
void unableToBindValueToParameter(
String nullSafeToString,
int index,
String message);
@LogMessage(level = ERROR)
@Message(value = "Unable to build enhancement metamodel for %s", id = 279)
@ -954,8 +976,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = ERROR)
@Message(value = "Error closing input files: %s", id = 286)
void unableToCloseInputFiles(String name,
@Cause IOException e);
void unableToCloseInputFiles(
String name,
@Cause IOException e);
@LogMessage(level = WARN)
@Message(value = "Could not close input stream", id = 287)
@ -963,8 +986,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "Could not close input stream for %s", id = 288)
void unableToCloseInputStreamForResource(String resourceName,
@Cause IOException e);
void unableToCloseInputStreamForResource(
String resourceName,
@Cause IOException e);
@LogMessage(level = INFO)
@Message(value = "Unable to close iterator", id = 289)
@ -976,8 +1000,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = ERROR)
@Message(value = "Error closing output file: %s", id = 291)
void unableToCloseOutputFile(String outputFile,
@Cause IOException e);
void unableToCloseOutputFile(
String outputFile,
@Cause IOException e);
@LogMessage(level = WARN)
@Message(value = "IOException occurred closing output stream", id = 292)
@ -1020,8 +1045,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = ERROR)
@Message(value = "Unable to construct current session context [%s]", id = 302)
void unableToConstructCurrentSessionContext(String impl,
@Cause Throwable e);
void unableToConstructCurrentSessionContext(
String impl,
@Cause Throwable e);
@LogMessage(level = WARN)
@Message(value = "Unable to construct instance of specified SQLExceptionConverter : %s", id = 303)
@ -1033,8 +1059,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "Could not create proxy factory for:%s", id = 305)
void unableToCreateProxyFactory(String entityName,
@Cause HibernateException e);
void unableToCreateProxyFactory(
String entityName,
@Cause HibernateException e);
@LogMessage(level = ERROR)
@Message(value = "Error creating schema ", id = 306)
@ -1042,8 +1069,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "Could not deserialize cache file: %s : %s", id = 307)
void unableToDeserializeCache(String path,
SerializationException error);
void unableToDeserializeCache(
String path,
SerializationException error);
@LogMessage(level = WARN)
@Message(value = "Unable to destroy cache: %s", id = 308)
@ -1051,18 +1079,21 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "Unable to destroy query cache: %s: %s", id = 309)
void unableToDestroyQueryCache(String region,
String message);
void unableToDestroyQueryCache(
String region,
String message);
@LogMessage(level = WARN)
@Message(value = "Unable to destroy update timestamps cache: %s: %s", id = 310)
void unableToDestroyUpdateTimestampsCache(String region,
String message);
void unableToDestroyUpdateTimestampsCache(
String region,
String message);
@LogMessage(level = INFO)
@Message(value = "Unable to determine lock mode value : %s -> %s", id = 311)
void unableToDetermineLockModeValue(String hintName,
Object value);
void unableToDetermineLockModeValue(
String hintName,
Object value);
@Message(value = "Could not determine transaction status", id = 312)
String unableToDetermineTransactionStatus();
@ -1080,8 +1111,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "Error executing resolver [%s] : %s", id = 316)
void unableToExecuteResolver(DialectResolver abstractDialectResolver,
String message);
void unableToExecuteResolver(
DialectResolver abstractDialectResolver,
String message);
@LogMessage(level = INFO)
@Message(value = "Could not find any META-INF/persistence.xml file in the classpath", id = 318)
@ -1093,8 +1125,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "Unable to instantiate configured schema name resolver [%s] %s", id = 320)
void unableToInstantiateConfiguredSchemaNameResolver(String resolverClassName,
String message);
void unableToInstantiateConfiguredSchemaNameResolver(
String resolverClassName,
String message);
@LogMessage(level = WARN)
@Message(value = "Unable to interpret specified optimizer [%s], falling back to noop", id = 321)
@ -1129,8 +1162,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "Unable to locate configured schema name resolver class [%s] %s", id = 331)
void unableToLocateConfiguredSchemaNameResolver(String resolverClassName,
String message);
void unableToLocateConfiguredSchemaNameResolver(
String resolverClassName,
String message);
@LogMessage(level = WARN)
@Message(value = "Unable to locate MBeanServer on JMX service shutdown", id = 332)
@ -1196,8 +1230,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = INFO)
@Message(value = "Could not read column value from result set: %s; %s", id = 349)
void unableToReadColumnValueFromResultSet(String name,
String message);
void unableToReadColumnValueFromResultSet(
String name,
String message);
@Message(value = "Could not read a hi value - you need to populate the table: %s", id = 350)
String unableToReadHiValue(String tableName);
@ -1244,8 +1279,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = INFO)
@Message(value = "Unable to retreive cache from JNDI [%s]: %s", id = 361)
void unableToRetrieveCache(String namespace,
String message);
void unableToRetrieveCache(
String namespace,
String message);
@LogMessage(level = WARN)
@Message(value = "Unable to retrieve type info result set : %s", id = 362)
@ -1257,8 +1293,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = INFO)
@Message(value = "Unable to rollback isolated transaction on error [%s] : [%s]", id = 364)
void unableToRollbackIsolatedTransaction(Exception e,
Exception ignore);
void unableToRollbackIsolatedTransaction(
Exception e,
Exception ignore);
@Message(value = "JTA rollback failed", id = 365)
String unableToRollbackJta();
@ -1277,8 +1314,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = INFO)
@Message(value = "Error stopping service [%s] : %s", id = 369)
void unableToStopService(Class class1,
String string);
void unableToStopService(
Class class1,
String string);
@LogMessage(level = WARN)
@Message(value = "Exception switching from method: [%s] to a method using the column index. Reverting to using: [%<s]",
@ -1306,8 +1344,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = ERROR)
@Message(value = "Could not updateQuery hi value in: %s", id = 376)
void unableToUpdateQueryHiValue(String tableName,
@Cause SQLException e);
void unableToUpdateQueryHiValue(
String tableName,
@Cause SQLException e);
@LogMessage(level = INFO)
@Message(value = "Error wrapping result set", id = 377)
@ -1315,8 +1354,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "I/O reported error writing cached file : %s: %s", id = 378)
void unableToWriteCachedFile(String path,
String message);
void unableToWriteCachedFile(
String path,
String message);
@LogMessage(level = WARN)
@Message(value = "Unexpected literal token type [%s] passed for numeric processing", id = 380)
@ -1375,9 +1415,10 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "The %s.%s.%s version of H2 implements temporary table creation such that it commits current transaction; multi-table, bulk hql/jpaql will not work properly",
id = 393)
void unsupportedMultiTableBulkHqlJpaql(int majorVersion,
int minorVersion,
int buildId);
void unsupportedMultiTableBulkHqlJpaql(
int majorVersion,
int minorVersion,
int buildId);
@LogMessage(level = WARN)
@Message(value = "Oracle 11g is not yet fully supported; using Oracle 10g dialect", id = 394)
@ -1385,8 +1426,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "Usage of obsolete property: %s no longer supported, use: %s", id = 395)
void unsupportedProperty(Object propertyName,
Object newPropertyName);
void unsupportedProperty(
Object propertyName,
Object newPropertyName);
@LogMessage(level = INFO)
@Message(value = "Updating schema", id = 396)
@ -1398,9 +1440,10 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = INFO)
@Message(value = "Explicit segment value for id generator [%s.%s] suggested; using default [%s]", id = 398)
void usingDefaultIdGeneratorSegmentValue(String tableName,
String segmentColumnName,
String defaultToUse);
void usingDefaultIdGeneratorSegmentValue(
String tableName,
String segmentColumnName,
String defaultToUse);
@LogMessage(level = INFO)
@Message(value = "Using default transaction strategy (direct JDBC transactions)", id = 399)
@ -1412,8 +1455,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = INFO)
@Message(value = "using driver [%s] at URL [%s]", id = 401)
void usingDriver(String driverClassName,
String url);
void usingDriver(
String driverClassName,
String url);
@LogMessage(level = WARN)
@Message(value = "Using Hibernate built-in connection pool (not for production use!)", id = 402)
@ -1438,8 +1482,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = WARN)
@Message(value = "Using %s which does not generate IETF RFC 4122 compliant UUID values; consider using %s instead",
id = 409)
void usingUuidHexGenerator(String name,
String name2);
void usingUuidHexGenerator(
String name,
String name2);
@LogMessage(level = INFO)
@Message(value = "Hibernate Validator not found: ignoring", id = 410)
@ -1468,16 +1513,18 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = INFO)
@Message(value = "Adding override for %s: %s", id = 418)
void addingOverrideFor(String name,
String name2);
void addingOverrideFor(
String name,
String name2);
@LogMessage(level = WARN)
@Message(value = "Resolved SqlTypeDescriptor is for a different SQL code. %s has sqlCode=%s; type override %s has sqlCode=%s",
id = 419)
void resolvedSqlTypeDescriptorForDifferentSqlCode(String name,
String valueOf,
String name2,
String valueOf2);
void resolvedSqlTypeDescriptorForDifferentSqlCode(
String name,
String valueOf,
String name2,
String valueOf2);
@LogMessage(level = DEBUG)
@Message(value = "Closing un-released batch", id = 420)
@ -1518,8 +1565,9 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = INFO)
@Message(value = "Encountered legacy TransactionManagerLookup specified; convert to newer %s contract specified via %s setting",
id = 428)
void legacyTransactionManagerStrategy(String name,
String jtaPlatform);
void legacyTransactionManagerStrategy(
String name,
String jtaPlatform);
@LogMessage(level = WARN)
@Message(value = "Setting entity-identifier value binding where one already existed : %s.", id = 429)
@ -1551,16 +1599,17 @@ public interface CoreMessageLogger extends BasicLogger {
void timestampCacheMisses(long updateTimestampsCachePutCount);
@LogMessage(level = WARN)
@Message(value = "Entity manager factory name (%s) is already registered. If entity manager will be clustered "+
@Message(value = "Entity manager factory name (%s) is already registered. If entity manager will be clustered " +
"or passivated, specify a unique value for property '%s'", id = 436)
void entityManagerFactoryAlreadyRegistered(String emfName, String propertyName);
@LogMessage(level = WARN)
@Message(value = "Attempting to save one or more entities that have a non-nullable association with an unsaved transient entity. The unsaved transient entity must be saved in an operation prior to saving these dependent entities.\n" +
"\tUnsaved transient entity: (%s)\n\tDependent entities: (%s)\n\tNon-nullable association(s): (%s)" , id = 437)
void cannotResolveNonNullableTransientDependencies(String transientEntityString,
Set<String> dependentEntityStrings,
Set<String> nonNullableAssociationPaths);
"\tUnsaved transient entity: (%s)\n\tDependent entities: (%s)\n\tNon-nullable association(s): (%s)", id = 437)
void cannotResolveNonNullableTransientDependencies(
String transientEntityString,
Set<String> dependentEntityStrings,
Set<String> nonNullableAssociationPaths);
@LogMessage(level = INFO)
@Message(value = "NaturalId cache puts: %s", id = 438)
@ -1577,7 +1626,7 @@ public interface CoreMessageLogger extends BasicLogger {
@LogMessage(level = INFO)
@Message(value = "Max NaturalId query time: %sms", id = 441)
void naturalIdMaxQueryTime(long naturalIdQueryExecutionMaxTime);
@LogMessage(level = INFO)
@Message(value = "NaturalId queries executed to database: %s", id = 442)
void naturalIdQueriesExecuted(long naturalIdQueriesExecutionCount);
@ -1626,7 +1675,7 @@ public interface CoreMessageLogger extends BasicLogger {
void explicitSkipLockedLockCombo();
@LogMessage(level = INFO)
@Message( value = "'javax.persistence.validation.mode' named multiple values : %s", id = 448 )
@Message(value = "'javax.persistence.validation.mode' named multiple values : %s", id = 448)
void multipleValidationModes(String modes);
@LogMessage(level = WARN)
@ -1651,11 +1700,11 @@ public interface CoreMessageLogger extends BasicLogger {
"delaying afterCompletion processing until the original thread can handle it. [status=%s]"
)
void rollbackFromBackgroundThread(int status);
@LogMessage(level = WARN)
@Message(value = "Exception while loading a class or resource found during scanning", id = 452)
void unableToLoadScannedClassOrResource(@Cause Exception e);
@LogMessage(level = WARN)
@Message(value = "Exception while discovering OSGi service implementations : %s", id = 453)
void unableToDiscoverOsgiService(String service, @Cause Exception e);
@ -1689,7 +1738,7 @@ public interface CoreMessageLogger extends BasicLogger {
"(%2$s=true)"
)
void applyingExplicitDiscriminatorColumnForJoined(String className, String overrideSetting);
// 458-466 reserved for use by master (ORM 5.0.0)
@LogMessage(level = DEBUG)

View File

@ -295,7 +295,8 @@ public class CriteriaImpl implements Criteria, Serializable {
public Integer getTimeout() {
return timeout;
}
@Override
@Override
public Criteria setTimeout(int timeout) {
this.timeout = timeout;
return this;

View File

@ -26,12 +26,9 @@ package org.hibernate.internal;
import org.hibernate.persister.entity.AbstractEntityPersister;
/**
*
* @author Rob Worsnop
*
*/
public class DynamicFilterAliasGenerator implements FilterAliasGenerator {
private String[] tables;
private String rootAlias;
@ -42,10 +39,14 @@ public class DynamicFilterAliasGenerator implements FilterAliasGenerator {
@Override
public String getAlias(String table) {
if (table == null){
if ( table == null ) {
return rootAlias;
} else{
return AbstractEntityPersister.generateTableAlias(rootAlias, AbstractEntityPersister.getTableId(table, tables));
}
else {
return AbstractEntityPersister.generateTableAlias(
rootAlias,
AbstractEntityPersister.getTableId( table, tables )
);
}
}

View File

@ -56,18 +56,18 @@ public class FetchingScrollableResultsImpl extends AbstractScrollableResults {
* @param holderInstantiator Ugh
*/
public FetchingScrollableResultsImpl(
ResultSet rs,
PreparedStatement ps,
SessionImplementor sess,
Loader loader,
QueryParameters queryParameters,
Type[] types,
HolderInstantiator holderInstantiator) {
ResultSet rs,
PreparedStatement ps,
SessionImplementor sess,
Loader loader,
QueryParameters queryParameters,
Type[] types,
HolderInstantiator holderInstantiator) {
super( rs, ps, sess, loader, queryParameters, types, holderInstantiator );
}
@Override
protected Object[] getCurrentRow() {
protected Object[] getCurrentRow() {
return currentRow;
}
@ -97,15 +97,15 @@ public class FetchingScrollableResultsImpl extends AbstractScrollableResults {
try {
afterLast = getResultSet().isAfterLast();
}
catch( SQLException e ) {
catch (SQLException e) {
throw getSession().getFactory().getSQLExceptionHelper().convert(
e,
"exception calling isAfterLast()"
e,
"exception calling isAfterLast()"
);
}
currentPosition++;
currentRow = new Object[] { row };
currentRow = new Object[] {row};
if ( afterLast ) {
if ( maxPosition == null ) {
@ -132,10 +132,10 @@ public class FetchingScrollableResultsImpl extends AbstractScrollableResults {
getSession(),
getQueryParameters(),
false,
( maxPosition != null && currentPosition > maxPosition )
( maxPosition != null && currentPosition > maxPosition )
);
currentRow = new Object[] { loadResult };
currentRow = new Object[] {loadResult};
currentPosition--;
afterScrollOperation();
@ -196,7 +196,7 @@ public class FetchingScrollableResultsImpl extends AbstractScrollableResults {
more = next();
}
}
catch( SQLException e ) {
catch (SQLException e) {
throw getSession().getFactory().getSQLExceptionHelper().convert(
e,
"exception calling isAfterLast()"
@ -224,10 +224,10 @@ public class FetchingScrollableResultsImpl extends AbstractScrollableResults {
try {
getResultSet().beforeFirst();
}
catch( SQLException e ) {
catch (SQLException e) {
throw getSession().getFactory().getSQLExceptionHelper().convert(
e,
"exception calling beforeFirst()"
e,
"exception calling beforeFirst()"
);
}
currentRow = null;
@ -274,12 +274,12 @@ public class FetchingScrollableResultsImpl extends AbstractScrollableResults {
private boolean isResultSetEmpty() {
try {
return currentPosition == 0 && ! getResultSet().isBeforeFirst() && ! getResultSet().isAfterLast();
return currentPosition == 0 && !getResultSet().isBeforeFirst() && !getResultSet().isAfterLast();
}
catch( SQLException e ) {
catch (SQLException e) {
throw getSession().getFactory().getSQLExceptionHelper().convert(
e,
"Could not determine if resultset is empty due to exception calling isBeforeFirst or isAfterLast()"
e,
"Could not determine if resultset is empty due to exception calling isBeforeFirst or isAfterLast()"
);
}
}

View File

@ -32,7 +32,6 @@ import org.hibernate.mapping.PersistentClass;
import org.hibernate.persister.entity.Joinable;
/**
*
* @author Rob Worsnop
*/
public class FilterConfiguration {
@ -42,8 +41,14 @@ public class FilterConfiguration {
private final Map<String, String> aliasTableMap;
private final Map<String, String> aliasEntityMap;
private final PersistentClass persistentClass;
public FilterConfiguration(String name, String condition, boolean autoAliasInjection, Map<String, String> aliasTableMap, Map<String, String> aliasEntityMap, PersistentClass persistentClass) {
public FilterConfiguration(
String name,
String condition,
boolean autoAliasInjection,
Map<String, String> aliasTableMap,
Map<String, String> aliasEntityMap,
PersistentClass persistentClass) {
this.name = name;
this.condition = condition;
this.autoAliasInjection = autoAliasInjection;
@ -65,28 +70,34 @@ public class FilterConfiguration {
}
public Map<String, String> getAliasTableMap(SessionFactoryImplementor factory) {
Map<String,String> mergedAliasTableMap = mergeAliasMaps(factory);
if (!mergedAliasTableMap.isEmpty()){
Map<String, String> mergedAliasTableMap = mergeAliasMaps( factory );
if ( !mergedAliasTableMap.isEmpty() ) {
return mergedAliasTableMap;
} else if (persistentClass != null){
String table = persistentClass.getTable().getQualifiedName(factory.getDialect(),
}
else if ( persistentClass != null ) {
String table = persistentClass.getTable().getQualifiedName(
factory.getDialect(),
factory.getSettings().getDefaultCatalogName(),
factory.getSettings().getDefaultSchemaName());
return Collections.singletonMap(null, table);
} else{
factory.getSettings().getDefaultSchemaName()
);
return Collections.singletonMap( null, table );
}
else {
return Collections.emptyMap();
}
}
private Map<String,String> mergeAliasMaps(SessionFactoryImplementor factory){
Map<String,String> ret = new HashMap<String, String>();
if (aliasTableMap != null){
ret.putAll(aliasTableMap);
private Map<String, String> mergeAliasMaps(SessionFactoryImplementor factory) {
Map<String, String> ret = new HashMap<String, String>();
if ( aliasTableMap != null ) {
ret.putAll( aliasTableMap );
}
if (aliasEntityMap != null){
for (Map.Entry<String, String> entry : aliasEntityMap.entrySet()){
ret.put(entry.getKey(),
Joinable.class.cast(factory.getEntityPersister(entry.getValue())).getTableName());
if ( aliasEntityMap != null ) {
for ( Map.Entry<String, String> entry : aliasEntityMap.entrySet() ) {
ret.put(
entry.getKey(),
Joinable.class.cast( factory.getEntityPersister( entry.getValue() ) ).getTableName()
);
}
}
return ret;

View File

@ -43,7 +43,7 @@ public class FilterHelper {
private final String[] filterNames;
private final String[] filterConditions;
private final boolean[] filterAutoAliasFlags;
private final Map<String,String>[] filterAliasTableMaps;
private final Map<String, String>[] filterAliasTableMaps;
/**
* The map of defined filters. This is expected to be in format
@ -65,7 +65,7 @@ public class FilterHelper {
filterNames[filterCount] = filter.getName();
filterConditions[filterCount] = filter.getCondition();
filterAliasTableMaps[filterCount] = filter.getAliasTableMap( factory );
if ( (filterAliasTableMaps[filterCount].isEmpty() || isTableFromPersistentClass( filterAliasTableMaps[filterCount] )) && filter
if ( ( filterAliasTableMaps[filterCount].isEmpty() || isTableFromPersistentClass( filterAliasTableMaps[filterCount] ) ) && filter
.useAutoAliasInjection() ) {
filterConditions[filterCount] = Template.renderWhereStringTemplate(
filter.getCondition(),
@ -83,9 +83,9 @@ public class FilterHelper {
filterCount++;
}
}
private static boolean isTableFromPersistentClass(Map<String,String> aliasTableMap){
return aliasTableMap.size() == 1 && aliasTableMap.containsKey(null);
private static boolean isTableFromPersistentClass(Map<String, String> aliasTableMap) {
return aliasTableMap.size() == 1 && aliasTableMap.containsKey( null );
}
public boolean isAffectedBy(Map enabledFilters) {
@ -116,17 +116,26 @@ public class FilterHelper {
}
}
}
private String render(FilterAliasGenerator aliasGenerator, int filterIndex){
Map<String,String> aliasTableMap = filterAliasTableMaps[filterIndex];
private String render(FilterAliasGenerator aliasGenerator, int filterIndex) {
Map<String, String> aliasTableMap = filterAliasTableMaps[filterIndex];
String condition = filterConditions[filterIndex];
if (filterAutoAliasFlags[filterIndex]){
return StringHelper.replace(condition, FilterImpl.MARKER, aliasGenerator.getAlias(aliasTableMap.get(null)));
} else if (isTableFromPersistentClass(aliasTableMap)){
return condition.replace("{alias}", aliasGenerator.getAlias(aliasTableMap.get(null)));
} else {
for (Map.Entry<String, String> entry : aliasTableMap.entrySet()){
condition = condition.replace("{"+entry.getKey()+"}", aliasGenerator.getAlias(entry.getValue()));
if ( filterAutoAliasFlags[filterIndex] ) {
return StringHelper.replace(
condition,
FilterImpl.MARKER,
aliasGenerator.getAlias( aliasTableMap.get( null ) )
);
}
else if ( isTableFromPersistentClass( aliasTableMap ) ) {
return condition.replace( "{alias}", aliasGenerator.getAlias( aliasTableMap.get( null ) ) );
}
else {
for ( Map.Entry<String, String> entry : aliasTableMap.entrySet() ) {
condition = condition.replace(
"{" + entry.getKey() + "}",
aliasGenerator.getAlias( entry.getValue() )
);
}
return condition;
}

View File

@ -40,10 +40,11 @@ import org.hibernate.type.Type;
/**
* An implementation of <tt>java.util.Iterator</tt> that is
* returned by <tt>iterate()</tt> query execution methods.
*
* @author Gavin King
*/
public final class IteratorImpl implements HibernateIterator {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( IteratorImpl.class );
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( IteratorImpl.class );
private ResultSet rs;
private final EventSource session;
@ -57,38 +58,36 @@ public final class IteratorImpl implements HibernateIterator {
private HolderInstantiator holderInstantiator;
public IteratorImpl(
ResultSet rs,
PreparedStatement ps,
EventSource sess,
boolean readOnly,
Type[] types,
String[][] columnNames,
HolderInstantiator holderInstantiator)
throws HibernateException, SQLException {
this.rs=rs;
this.ps=ps;
ResultSet rs,
PreparedStatement ps,
EventSource sess,
boolean readOnly,
Type[] types,
String[][] columnNames,
HolderInstantiator holderInstantiator) throws HibernateException, SQLException {
this.rs = rs;
this.ps = ps;
this.session = sess;
this.readOnly = readOnly;
this.types = types;
this.names = columnNames;
this.holderInstantiator = holderInstantiator;
single = types.length==1;
single = types.length == 1;
postNext();
}
public void close() throws JDBCException {
if (ps!=null) {
if ( ps != null ) {
LOG.debug( "Closing iterator" );
session.getJdbcCoordinator().getResourceRegistry().release( ps );
try {
session.getPersistenceContext().getLoadContexts().cleanup( rs );
}
catch( Throwable ignore ) {
catch (Throwable ignore) {
// 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;
@ -98,14 +97,14 @@ public final class IteratorImpl implements HibernateIterator {
}
private void postNext() throws SQLException {
LOG.debug("Attempting to retrieve next results");
LOG.debug( "Attempting to retrieve next results" );
this.hasNext = rs.next();
if (!hasNext) {
LOG.debug("Exhausted results");
if ( !hasNext ) {
LOG.debug( "Exhausted results" );
close();
}
else {
LOG.debug("Retrieved next results");
LOG.debug( "Retrieved next results" );
}
}
@ -115,7 +114,7 @@ public final class IteratorImpl implements HibernateIterator {
public Object next() throws HibernateException {
if ( !hasNext ) {
throw new NoSuchElementException("No more results");
throw new NoSuchElementException( "No more results" );
}
boolean sessionDefaultReadOnlyOrig = session.isDefaultReadOnly();
session.setDefaultReadOnly( readOnly );
@ -128,12 +127,12 @@ public final class IteratorImpl implements HibernateIterator {
}
else {
Object[] currentResults = new Object[types.length];
for (int i=0; i<types.length; i++) {
for ( int i = 0; i < types.length; i++ ) {
currentResults[i] = types[i].nullSafeGet( rs, names[i], session, null );
}
if (isHolder) {
currentResult = holderInstantiator.instantiate(currentResults);
if ( isHolder ) {
currentResult = holderInstantiator.instantiate( currentResults );
}
else {
currentResult = currentResults;
@ -148,7 +147,7 @@ public final class IteratorImpl implements HibernateIterator {
throw session.getFactory().getSQLExceptionHelper().convert(
sqle,
"could not get next iterator result"
);
);
}
finally {
session.setDefaultReadOnly( sessionDefaultReadOnlyOrig );
@ -156,21 +155,21 @@ public final class IteratorImpl implements HibernateIterator {
}
public void remove() {
if (!single) {
throw new UnsupportedOperationException("Not a single column hibernate query result set");
if ( !single ) {
throw new UnsupportedOperationException( "Not a single column hibernate query result set" );
}
if (currentResult==null) {
throw new IllegalStateException("Called Iterator.remove() before next()");
if ( currentResult == null ) {
throw new IllegalStateException( "Called Iterator.remove() before next()" );
}
if ( !( types[0] instanceof EntityType ) ) {
throw new UnsupportedOperationException("Not an entity");
throw new UnsupportedOperationException( "Not an entity" );
}
session.delete(
( (EntityType) types[0] ).getAssociatedEntityName(),
currentResult,
false,
null
null
);
}
}

View File

@ -20,9 +20,9 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.internal;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
@ -43,8 +43,9 @@ import org.hibernate.engine.spi.SessionImplementor;
/**
* default implementation of the <tt>Query</tt> interface,
* for "ordinary" HQL queries (not collection filters)
* @see CollectionFilterImpl
*
* @author Gavin King
* @see CollectionFilterImpl
*/
public class QueryImpl extends AbstractQueryImpl {
@ -52,9 +53,9 @@ public class QueryImpl extends AbstractQueryImpl {
public QueryImpl(
String queryString,
FlushMode flushMode,
SessionImplementor session,
ParameterMetadata parameterMetadata) {
FlushMode flushMode,
SessionImplementor session,
ParameterMetadata parameterMetadata) {
super( queryString, flushMode, session, parameterMetadata );
}
@ -68,9 +69,9 @@ public class QueryImpl extends AbstractQueryImpl {
before();
try {
return getSession().iterate(
expandParameterLists(namedParams),
getQueryParameters(namedParams)
);
expandParameterLists( namedParams ),
getQueryParameters( namedParams )
);
}
finally {
after();
@ -85,10 +86,10 @@ public class QueryImpl extends AbstractQueryImpl {
verifyParameters();
Map namedParams = getNamedParams();
before();
QueryParameters qp = getQueryParameters(namedParams);
qp.setScrollMode(scrollMode);
QueryParameters qp = getQueryParameters( namedParams );
qp.setScrollMode( scrollMode );
try {
return getSession().scroll( expandParameterLists(namedParams), qp );
return getSession().scroll( expandParameterLists( namedParams ), qp );
}
finally {
after();
@ -101,9 +102,9 @@ public class QueryImpl extends AbstractQueryImpl {
before();
try {
return getSession().list(
expandParameterLists(namedParams),
getQueryParameters(namedParams)
);
expandParameterLists( namedParams ),
getQueryParameters( namedParams )
);
}
finally {
after();
@ -115,10 +116,10 @@ public class QueryImpl extends AbstractQueryImpl {
Map namedParams = getNamedParams();
before();
try {
return getSession().executeUpdate(
expandParameterLists( namedParams ),
getQueryParameters( namedParams )
);
return getSession().executeUpdate(
expandParameterLists( namedParams ),
getQueryParameters( namedParams )
);
}
finally {
after();
@ -129,11 +130,11 @@ public class QueryImpl extends AbstractQueryImpl {
lockOptions.setAliasSpecificLockMode( alias, lockMode );
return this;
}
public Query setLockOptions(LockOptions lockOption) {
this.lockOptions.setLockMode(lockOption.getLockMode());
this.lockOptions.setScope(lockOption.getScope());
this.lockOptions.setTimeOut(lockOption.getTimeOut());
this.lockOptions.setLockMode( lockOption.getLockMode() );
this.lockOptions.setScope( lockOption.getScope() );
this.lockOptions.setTimeOut( lockOption.getTimeOut() );
return this;
}

View File

@ -22,6 +22,7 @@
* Boston, MA 02110-1301 USA
*/
package org.hibernate.internal;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
@ -83,16 +84,16 @@ public class SQLQueryImpl extends AbstractQueryImpl implements SQLQuery {
if ( queryDef.getResultSetRef() != null ) {
ResultSetMappingDefinition definition = session.getFactory()
.getResultSetMapping( queryDef.getResultSetRef() );
if (definition == null) {
if ( definition == null ) {
throw new MappingException(
"Unable to find resultset-ref definition: " +
queryDef.getResultSetRef()
);
queryDef.getResultSetRef()
);
}
this.queryReturns = new ArrayList<NativeSQLQueryReturn>(Arrays.asList( definition.getQueryReturns() ));
this.queryReturns = new ArrayList<NativeSQLQueryReturn>( Arrays.asList( definition.getQueryReturns() ) );
}
else if ( queryDef.getQueryReturns() != null && queryDef.getQueryReturns().length > 0 ) {
this.queryReturns = new ArrayList<NativeSQLQueryReturn>(Arrays.asList( queryDef.getQueryReturns()));
this.queryReturns = new ArrayList<NativeSQLQueryReturn>( Arrays.asList( queryDef.getQueryReturns() ) );
}
else {
this.queryReturns = new ArrayList<NativeSQLQueryReturn>();
@ -114,7 +115,7 @@ public class SQLQueryImpl extends AbstractQueryImpl implements SQLQuery {
}
@Override
public List<NativeSQLQueryReturn> getQueryReturns() {
public List<NativeSQLQueryReturn> getQueryReturns() {
prepareQueryReturnsIfNecessary();
return queryReturns;
}
@ -147,9 +148,9 @@ public class SQLQueryImpl extends AbstractQueryImpl implements SQLQuery {
private NativeSQLQuerySpecification generateQuerySpecification(Map namedParams) {
return new NativeSQLQuerySpecification(
expandParameterLists(namedParams),
expandParameterLists( namedParams ),
queryReturns.toArray( new NativeSQLQueryReturn[queryReturns.size()] ),
querySpaces
querySpaces
);
}
@ -176,24 +177,24 @@ public class SQLQueryImpl extends AbstractQueryImpl implements SQLQuery {
}
public Iterator iterate() throws HibernateException {
throw new UnsupportedOperationException("SQL queries do not currently support iteration");
throw new UnsupportedOperationException( "SQL queries do not currently support iteration" );
}
@Override
public QueryParameters getQueryParameters(Map namedParams) {
QueryParameters qp = super.getQueryParameters(namedParams);
qp.setCallable(callable);
public QueryParameters getQueryParameters(Map namedParams) {
QueryParameters qp = super.getQueryParameters( namedParams );
qp.setCallable( callable );
qp.setAutoDiscoverScalarTypes( autoDiscoverTypes );
return qp;
}
@Override
protected void verifyParameters() {
protected void verifyParameters() {
// verifyParameters is called at the start of all execution type methods, so we use that here to perform
// some preparation work.
prepareQueryReturnsIfNecessary();
verifyParameters( callable );
boolean noReturns = queryReturns==null || queryReturns.isEmpty();
boolean noReturns = queryReturns == null || queryReturns.isEmpty();
if ( noReturns ) {
this.autoDiscoverTypes = noReturns;
}
@ -216,7 +217,7 @@ public class SQLQueryImpl extends AbstractQueryImpl implements SQLQuery {
private void prepareQueryReturnsIfNecessary() {
if ( queryReturnBuilders != null ) {
if ( ! queryReturnBuilders.isEmpty() ) {
if ( !queryReturnBuilders.isEmpty() ) {
if ( queryReturns != null ) {
queryReturns.clear();
queryReturns = null;
@ -232,25 +233,25 @@ public class SQLQueryImpl extends AbstractQueryImpl implements SQLQuery {
}
@Override
public String[] getReturnAliases() throws HibernateException {
throw new UnsupportedOperationException("SQL queries do not currently support returning aliases");
public String[] getReturnAliases() throws HibernateException {
throw new UnsupportedOperationException( "SQL queries do not currently support returning aliases" );
}
@Override
public Type[] getReturnTypes() throws HibernateException {
throw new UnsupportedOperationException("not yet implemented for SQL queries");
public Type[] getReturnTypes() throws HibernateException {
throw new UnsupportedOperationException( "not yet implemented for SQL queries" );
}
public Query setLockMode(String alias, LockMode lockMode) {
throw new UnsupportedOperationException("cannot set the lock mode for a native SQL query");
throw new UnsupportedOperationException( "cannot set the lock mode for a native SQL query" );
}
public Query setLockOptions(LockOptions lockOptions) {
throw new UnsupportedOperationException("cannot set lock options for a native SQL query");
throw new UnsupportedOperationException( "cannot set lock options for a native SQL query" );
}
@Override
public LockOptions getLockOptions() {
public LockOptions getLockOptions() {
//we never need to apply locks to the SQL, however the native-sql loader handles this specially
return lockOptions;
}
@ -332,12 +333,12 @@ public class SQLQueryImpl extends AbstractQueryImpl implements SQLQuery {
}
private FetchReturn createFetchJoin(String tableAlias, String path) {
int loc = path.indexOf('.');
int loc = path.indexOf( '.' );
if ( loc < 0 ) {
throw new QueryException( "not a property path: " + path );
}
final String ownerTableAlias = path.substring( 0, loc );
final String joinedPropertyName = path.substring( loc+1 );
final String joinedPropertyName = path.substring( loc + 1 );
return addFetch( tableAlias, ownerTableAlias, joinedPropertyName );
}
@ -400,7 +401,7 @@ public class SQLQueryImpl extends AbstractQueryImpl implements SQLQuery {
private final String alias;
private final String entityName;
private LockMode lockMode = LockMode.READ;
private Map<String,String[]> propertyMappings;
private Map<String, String[]> propertyMappings;
private RootReturnBuilder(String alias, String entityName) {
this.alias = alias;
@ -424,20 +425,21 @@ public class SQLQueryImpl extends AbstractQueryImpl implements SQLQuery {
public ReturnProperty addProperty(final String propertyName) {
if ( propertyMappings == null ) {
propertyMappings = new HashMap<String,String[]>();
propertyMappings = new HashMap<String, String[]>();
}
return new ReturnProperty() {
public ReturnProperty addColumnAlias(String columnAlias) {
String[] columnAliases = propertyMappings.get( propertyName );
if ( columnAliases == null ) {
columnAliases = new String[]{columnAlias};
}else{
String[] newColumnAliases = new String[columnAliases.length + 1];
columnAliases = new String[] {columnAlias};
}
else {
String[] newColumnAliases = new String[columnAliases.length + 1];
System.arraycopy( columnAliases, 0, newColumnAliases, 0, columnAliases.length );
newColumnAliases[columnAliases.length] = columnAlias;
columnAliases = newColumnAliases;
}
propertyMappings.put( propertyName,columnAliases );
propertyMappings.put( propertyName, columnAliases );
return this;
}
};
@ -447,12 +449,13 @@ public class SQLQueryImpl extends AbstractQueryImpl implements SQLQuery {
return new NativeSQLQueryRootReturn( alias, entityName, propertyMappings, lockMode );
}
}
private class FetchReturnBuilder implements FetchReturn, ReturnBuilder {
private final String alias;
private String ownerTableAlias;
private final String joinedPropertyName;
private LockMode lockMode = LockMode.READ;
private Map<String,String[]> propertyMappings;
private Map<String, String[]> propertyMappings;
private FetchReturnBuilder(String alias, String ownerTableAlias, String joinedPropertyName) {
this.alias = alias;
@ -472,27 +475,34 @@ public class SQLQueryImpl extends AbstractQueryImpl implements SQLQuery {
public ReturnProperty addProperty(final String propertyName) {
if ( propertyMappings == null ) {
propertyMappings = new HashMap<String,String[]>();
propertyMappings = new HashMap<String, String[]>();
}
return new ReturnProperty() {
public ReturnProperty addColumnAlias(String columnAlias) {
String[] columnAliases = propertyMappings.get( propertyName );
if ( columnAliases == null ) {
columnAliases = new String[]{columnAlias};
}else{
String[] newColumnAliases = new String[columnAliases.length + 1];
columnAliases = new String[] {columnAlias};
}
else {
String[] newColumnAliases = new String[columnAliases.length + 1];
System.arraycopy( columnAliases, 0, newColumnAliases, 0, columnAliases.length );
newColumnAliases[columnAliases.length] = columnAlias;
columnAliases = newColumnAliases;
}
propertyMappings.put( propertyName,columnAliases );
propertyMappings.put( propertyName, columnAliases );
return this;
}
};
}
public NativeSQLQueryReturn buildReturn() {
return new NativeSQLQueryJoinReturn( alias, ownerTableAlias, joinedPropertyName, propertyMappings, lockMode );
return new NativeSQLQueryJoinReturn(
alias,
ownerTableAlias,
joinedPropertyName,
propertyMappings,
lockMode
);
}
}

View File

@ -28,6 +28,7 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import org.hibernate.HibernateException;
import org.hibernate.JDBCException;
import org.hibernate.ScrollableResults;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SessionImplementor;
@ -55,12 +56,12 @@ public class ScrollableResultsImpl extends AbstractScrollableResults implements
* @param holderInstantiator Ugh
*/
public ScrollableResultsImpl(
ResultSet rs,
PreparedStatement ps,
SessionImplementor sess,
Loader loader,
QueryParameters queryParameters,
Type[] types, HolderInstantiator holderInstantiator) {
ResultSet rs,
PreparedStatement ps,
SessionImplementor sess,
Loader loader,
QueryParameters queryParameters,
Type[] types, HolderInstantiator holderInstantiator) {
super( rs, ps, sess, loader, queryParameters, types, holderInstantiator );
}
@ -72,30 +73,28 @@ public class ScrollableResultsImpl extends AbstractScrollableResults implements
@Override
public boolean scroll(int i) {
try {
final boolean result = getResultSet().relative(i);
prepareCurrentRow(result);
final boolean result = getResultSet().relative( i );
prepareCurrentRow( result );
return result;
}
catch (SQLException sqle) {
throw getSession().getFactory().getSQLExceptionHelper().convert(
sqle,
"could not advance using scroll()"
);
throw convert( sqle, "could not advance using scroll()" );
}
}
protected JDBCException convert(SQLException sqle, String message) {
return getSession().getFactory().getSQLExceptionHelper().convert( sqle, message );
}
@Override
public boolean first() {
try {
final boolean result = getResultSet().first();
prepareCurrentRow(result);
prepareCurrentRow( result );
return result;
}
catch (SQLException sqle) {
throw getSession().getFactory().getSQLExceptionHelper().convert(
sqle,
"could not advance using first()"
);
throw convert( sqle, "could not advance using first()" );
}
}
@ -103,14 +102,11 @@ public class ScrollableResultsImpl extends AbstractScrollableResults implements
public boolean last() {
try {
final boolean result = getResultSet().last();
prepareCurrentRow(result);
prepareCurrentRow( result );
return result;
}
catch (SQLException sqle) {
throw getSession().getFactory().getSQLExceptionHelper().convert(
sqle,
"could not advance using last()"
);
throw convert( sqle, "could not advance using last()" );
}
}
@ -118,14 +114,11 @@ public class ScrollableResultsImpl extends AbstractScrollableResults implements
public boolean next() {
try {
final boolean result = getResultSet().next();
prepareCurrentRow(result);
prepareCurrentRow( result );
return result;
}
catch (SQLException sqle) {
throw getSession().getFactory().getSQLExceptionHelper().convert(
sqle,
"could not advance using next()"
);
throw convert( sqle, "could not advance using next()" );
}
}
@ -133,14 +126,11 @@ public class ScrollableResultsImpl extends AbstractScrollableResults implements
public boolean previous() {
try {
final boolean result = getResultSet().previous();
prepareCurrentRow(result);
prepareCurrentRow( result );
return result;
}
catch (SQLException sqle) {
throw getSession().getFactory().getSQLExceptionHelper().convert(
sqle,
"could not advance using previous()"
);
throw convert( sqle, "could not advance using previous()" );
}
}
@ -150,10 +140,7 @@ public class ScrollableResultsImpl extends AbstractScrollableResults implements
getResultSet().afterLast();
}
catch (SQLException sqle) {
throw getSession().getFactory().getSQLExceptionHelper().convert(
sqle,
"exception calling afterLast()"
);
throw convert( sqle, "exception calling afterLast()" );
}
}
@ -163,10 +150,7 @@ public class ScrollableResultsImpl extends AbstractScrollableResults implements
getResultSet().beforeFirst();
}
catch (SQLException sqle) {
throw getSession().getFactory().getSQLExceptionHelper().convert(
sqle,
"exception calling beforeFirst()"
);
throw convert( sqle, "exception calling beforeFirst()" );
}
}
@ -176,10 +160,7 @@ public class ScrollableResultsImpl extends AbstractScrollableResults implements
return getResultSet().isFirst();
}
catch (SQLException sqle) {
throw getSession().getFactory().getSQLExceptionHelper().convert(
sqle,
"exception calling isFirst()"
);
throw convert( sqle, "exception calling isFirst()" );
}
}
@ -189,23 +170,17 @@ public class ScrollableResultsImpl extends AbstractScrollableResults implements
return getResultSet().isLast();
}
catch (SQLException sqle) {
throw getSession().getFactory().getSQLExceptionHelper().convert(
sqle,
"exception calling isLast()"
);
throw convert( sqle, "exception calling isLast()" );
}
}
@Override
public int getRowNumber() throws HibernateException {
try {
return getResultSet().getRow()-1;
return getResultSet().getRow() - 1;
}
catch (SQLException sqle) {
throw getSession().getFactory().getSQLExceptionHelper().convert(
sqle,
"exception calling getRow()"
);
throw convert( sqle, "exception calling getRow()" );
}
}
@ -216,15 +191,12 @@ public class ScrollableResultsImpl extends AbstractScrollableResults implements
}
try {
final boolean result = getResultSet().absolute(rowNumber);
prepareCurrentRow(result);
final boolean result = getResultSet().absolute( rowNumber );
prepareCurrentRow( result );
return result;
}
catch (SQLException sqle) {
throw getSession().getFactory().getSQLExceptionHelper().convert(
sqle,
"could not advance using absolute()"
);
throw convert( sqle, "could not advance using absolute()" );
}
}
@ -244,11 +216,11 @@ public class ScrollableResultsImpl extends AbstractScrollableResults implements
currentRow = (Object[]) result;
}
else {
currentRow = new Object[] { result };
currentRow = new Object[] {result};
}
if ( getHolderInstantiator() != null ) {
currentRow = new Object[] { getHolderInstantiator().instantiate(currentRow) };
currentRow = new Object[] {getHolderInstantiator().instantiate( currentRow )};
}
afterScrollOperation();

View File

@ -183,11 +183,8 @@ import org.hibernate.type.TypeResolver;
* @author Gavin King
*/
public final class SessionFactoryImpl implements SessionFactoryImplementor {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( SessionFactoryImpl.class );
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class,
SessionFactoryImpl.class.getName()
);
private static final IdentifierGenerator UUID_GENERATOR = UUIDGenerator.buildSessionFactoryUniqueIdentifierGenerator();
private final String name;
@ -639,8 +636,11 @@ public final class SessionFactoryImpl implements SessionFactoryImplementor {
final AccessType accessType = AccessType.fromExternalName( model.getCacheConcurrencyStrategy() );
if ( accessType != null ) {
LOG.tracef( "Building shared cache region for entity data [%s]", model.getEntityName() );
EntityRegion entityRegion = regionFactory.buildEntityRegion( cacheRegionName, properties, CacheDataDescriptionImpl
.decode( model ) );
EntityRegion entityRegion = regionFactory.buildEntityRegion(
cacheRegionName,
properties,
CacheDataDescriptionImpl.decode( model )
);
accessStrategy = entityRegion.buildAccessStrategy( accessType );
cacheAccessStrategiesMap.put( cacheRegionName, accessStrategy );
cacheAccess.addCacheRegion( cacheRegionName, entityRegion );
@ -866,7 +866,7 @@ public final class SessionFactoryImpl implements SessionFactoryImplementor {
@Override
public Reference getReference() {
// from javax.naming.Referenceable
LOG.debug( "Returning a Reference to the SessionFactory" );
LOG.debug( "Returning a Reference to the SessionFactory" );
return new Reference(
SessionFactoryImpl.class.getName(),
new StringRefAddr("uuid", uuid),

View File

@ -40,7 +40,7 @@ import org.hibernate.engine.jndi.spi.JndiService;
/**
* A registry of all {@link SessionFactory} instances for the same classloader as this class.
*
* <p/>
* This registry is used for serialization/deserialization as well as JNDI binding.
*
* @author Steve Ebersole
@ -61,7 +61,7 @@ public class SessionFactoryRegistry {
/**
* A cross-reference for mapping a SessionFactory name to its UUID. Not all SessionFactories get named,
*/
private final ConcurrentHashMap<String,String> nameUuidXref = new ConcurrentHashMap<String, String>();
private final ConcurrentHashMap<String, String> nameUuidXref = new ConcurrentHashMap<String, String>();
private SessionFactoryRegistry() {
LOG.debugf( "Initializing SessionFactoryRegistry : %s", this );
@ -92,7 +92,7 @@ public class SessionFactoryRegistry {
nameUuidXref.put( name, uuid );
}
if ( name == null || ! isNameAlsoJndiName ) {
if ( name == null || !isNameAlsoJndiName ) {
LOG.debug( "Not binding SessionFactory to JNDI, no JNDI name configured" );
return;
}
@ -139,10 +139,10 @@ public class SessionFactoryRegistry {
jndiService.unbind( name );
LOG.factoryUnboundFromJndiName( name );
}
catch ( JndiNameException e ) {
catch (JndiNameException e) {
LOG.invalidJndiName( name, e );
}
catch ( JndiException e ) {
catch (JndiException e) {
LOG.unableToUnbindFactoryFromJndi( e );
}
}
@ -181,7 +181,7 @@ public class SessionFactoryRegistry {
* @return true/false
*/
public boolean hasRegistrations() {
return ! sessionFactoryMap.isEmpty();
return !sessionFactoryMap.isEmpty();
}
public void clearRegistrations() {
@ -203,13 +203,13 @@ public class SessionFactoryRegistry {
private final NamespaceChangeListener listener = new NamespaceChangeListener() {
@Override
public void objectAdded(NamingEvent evt) {
LOG.debugf("A factory was successfully bound to name: %s", evt.getNewBinding().getName());
LOG.debugf( "A factory was successfully bound to name: %s", evt.getNewBinding().getName() );
}
@Override
public void objectRemoved(NamingEvent evt) {
final String jndiName = evt.getOldBinding().getName();
LOG.factoryUnboundFromName( jndiName );
LOG.factoryUnboundFromName( jndiName );
final String uuid = nameUuidXref.remove( jndiName );
if ( uuid == null ) {
@ -232,7 +232,7 @@ public class SessionFactoryRegistry {
@Override
public void namingExceptionThrown(NamingExceptionEvent evt) {
//noinspection ThrowableResultOfMethodCallIgnored
LOG.namingExceptionAccessingFactory(evt.getException());
LOG.namingExceptionAccessingFactory( evt.getException() );
}
};

View File

@ -165,16 +165,14 @@ import org.hibernate.resource.transaction.spi.TransactionStatus;
import org.hibernate.stat.SessionStatistics;
import org.hibernate.stat.internal.SessionStatisticsImpl;
import org.jboss.logging.Logger;
/**
* Concrete implementation of a Session.
*
* <p/>
* Exposes two interfaces:<ul>
* <li>{@link Session} to the application</li>
* <li>{@link org.hibernate.engine.spi.SessionImplementor} to other Hibernate components (SPI)</li>
* <li>{@link Session} to the application</li>
* <li>{@link org.hibernate.engine.spi.SessionImplementor} to other Hibernate components (SPI)</li>
* </ul>
*
* <p/>
* This class is not thread-safe.
*
* @author Gavin King
@ -187,11 +185,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
// a separate class responsible for generating/dispatching events just duplicates most of the Session methods...
// passing around separate interceptor, factory, actionQueue, and persistentContext is not manageable...
private static final CoreMessageLogger LOG = Logger.getMessageLogger(
CoreMessageLogger.class,
SessionImpl.class.getName()
);
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( SessionImpl.class );
private static final boolean TRACE_ENABLED = LOG.isTraceEnabled();
private transient long timestamp;
@ -277,6 +271,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
if ( statementInspector == null ) {
this.statementInspector = new StatementInspector() {
@Override
@SuppressWarnings("deprecation")
public String inspect(String sql) {
return SessionImpl.this.interceptor.onPrepareStatement( sql );
}
@ -293,7 +288,10 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
this.autoJoinTransactions = autoJoinTransactions;
this.jdbcCoordinator = new JdbcCoordinatorImpl( connection, this );
this.transactionCoordinator = getTransactionCoordinatorBuilder().buildTransactionCoordinator( this.jdbcCoordinator, this );
this.transactionCoordinator = getTransactionCoordinatorBuilder().buildTransactionCoordinator(
this.jdbcCoordinator,
this
);
this.currentHibernateTransaction = getTransaction();
}
else {
@ -334,7 +332,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
}
actionQueue.beforeTransactionCompletion();
try {
interceptor.beforeTransactionCompletion( currentHibernateTransaction );
SessionImpl.this.interceptor.beforeTransactionCompletion( currentHibernateTransaction );
}
catch (Throwable t) {
LOG.exceptionInBeforeTransactionCompletionInterceptor( t );
@ -557,7 +555,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
* @param success Was the operation a success
*/
public void afterOperation(boolean success) {
if ( ! isTransactionInProgress() ) {
if ( !isTransactionInProgress() ) {
jdbcCoordinator.afterTransaction();
}
}
@ -590,12 +588,12 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
throw new NullPointerException( "null object passed to getCurrentLockMode()" );
}
if ( object instanceof HibernateProxy ) {
object = ( (HibernateProxy) object ).getHibernateLazyInitializer().getImplementation(this);
object = ( (HibernateProxy) object ).getHibernateLazyInitializer().getImplementation( this );
if ( object == null ) {
return LockMode.NONE;
}
}
EntityEntry e = persistenceContext.getEntry(object);
EntityEntry e = persistenceContext.getEntry( object );
if ( e == null ) {
throw new TransientObjectException( "Given object not associated with the session" );
}
@ -604,7 +602,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
"The given object was deleted",
e.getId(),
e.getPersister().getEntityName()
);
);
}
return e.getLockMode();
}
@ -614,7 +612,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
errorIfClosed();
// todo : should this get moved to PersistentContext?
// logically, is PersistentContext the "thing" to which an interceptor gets attached?
final Object result = persistenceContext.getEntity(key);
final Object result = persistenceContext.getEntity( key );
if ( result == null ) {
final Object newObject = interceptor.getEntity( key.getEntityName(), key.getIdentifier() );
if ( newObject != null ) {
@ -641,8 +639,9 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
}
private void delayedAfterCompletion() {
if(transactionCoordinator instanceof JtaTransactionCoordinatorImpl) {
((JtaTransactionCoordinatorImpl)transactionCoordinator).getSynchronizationCallbackCoordinator().processAnyDelayedAfterCompletion();
if ( transactionCoordinator instanceof JtaTransactionCoordinatorImpl ) {
( (JtaTransactionCoordinatorImpl) transactionCoordinator ).getSynchronizationCallbackCoordinator()
.processAnyDelayedAfterCompletion();
}
}
@ -733,7 +732,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
@Override
public LockRequest buildLockRequest(LockOptions lockOptions) {
return new LockRequestImpl(lockOptions);
return new LockRequestImpl( lockOptions );
}
@Override
@ -884,7 +883,8 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
}
@Override
public void delete(String entityName, Object object, boolean isCascadeDeleteEnabled, Set transientEntities) throws HibernateException {
public void delete(String entityName, Object object, boolean isCascadeDeleteEnabled, Set transientEntities)
throws HibernateException {
if ( TRACE_ENABLED && persistenceContext.isRemovingOrphanBeforeUpates() ) {
logRemoveOrphanBeforeUpdates( "before continuing", entityName, object );
}
@ -954,12 +954,12 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
@Override
public void load(Object object, Serializable id) throws HibernateException {
LoadEvent event = new LoadEvent(id, object, this);
LoadEvent event = new LoadEvent( id, object, this );
fireLoad( event, LoadEventListener.RELOAD );
}
@Override
public Object load(Class entityClass, Serializable id) throws HibernateException {
public <T> T load(Class<T> entityClass, Serializable id) throws HibernateException {
return this.byId( entityClass ).getReference( id );
}
@ -969,7 +969,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
}
@Override
public Object get(Class entityClass, Serializable id) throws HibernateException {
public <T> T get(Class<T> entityClass, Serializable id) throws HibernateException {
return this.byId( entityClass ).load( id );
}
@ -978,7 +978,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
return this.byId( entityName ).load( id );
}
/**
/**
* Load the data for the object with the specified id into a newly created object.
* This is only called when lazily initializing a proxy.
* Do NOT return a proxy.
@ -986,24 +986,25 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
@Override
public Object immediateLoad(String entityName, Serializable id) throws HibernateException {
if ( LOG.isDebugEnabled() ) {
EntityPersister persister = getFactory().getEntityPersister(entityName);
EntityPersister persister = getFactory().getEntityPersister( entityName );
LOG.debugf( "Initializing proxy: %s", MessageHelper.infoString( persister, id, getFactory() ) );
}
LoadEvent event = new LoadEvent(id, entityName, true, this);
fireLoad(event, LoadEventListener.IMMEDIATE_LOAD);
LoadEvent event = new LoadEvent( id, entityName, true, this );
fireLoad( event, LoadEventListener.IMMEDIATE_LOAD );
return event.getResult();
}
@Override
public Object internalLoad(String entityName, Serializable id, boolean eager, boolean nullable) throws HibernateException {
public Object internalLoad(String entityName, Serializable id, boolean eager, boolean nullable)
throws HibernateException {
// todo : remove
LoadEventListener.LoadType type = nullable
? LoadEventListener.INTERNAL_LOAD_NULLABLE
: eager
? LoadEventListener.INTERNAL_LOAD_EAGER
: LoadEventListener.INTERNAL_LOAD_LAZY;
LoadEvent event = new LoadEvent(id, entityName, true, this);
? LoadEventListener.INTERNAL_LOAD_EAGER
: LoadEventListener.INTERNAL_LOAD_LAZY;
LoadEvent event = new LoadEvent( id, entityName, true, this );
fireLoad( event, type );
if ( !nullable ) {
UnresolvableObjectException.throwIfNull( event.getResult(), id, entityName );
@ -1012,12 +1013,12 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
}
@Override
public Object load(Class entityClass, Serializable id, LockMode lockMode) throws HibernateException {
public <T> T load(Class<T> entityClass, Serializable id, LockMode lockMode) throws HibernateException {
return this.byId( entityClass ).with( new LockOptions( lockMode ) ).getReference( id );
}
@Override
public Object load(Class entityClass, Serializable id, LockOptions lockOptions) throws HibernateException {
public <T> T load(Class<T> entityClass, Serializable id, LockOptions lockOptions) throws HibernateException {
return this.byId( entityClass ).with( lockOptions ).getReference( id );
}
@ -1032,12 +1033,12 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
}
@Override
public Object get(Class entityClass, Serializable id, LockMode lockMode) throws HibernateException {
public <T> T get(Class<T> entityClass, Serializable id, LockMode lockMode) throws HibernateException {
return this.byId( entityClass ).with( new LockOptions( lockMode ) ).load( id );
}
@Override
public Object get(Class entityClass, Serializable id, LockOptions lockOptions) throws HibernateException {
public <T> T get(Class<T> entityClass, Serializable id, LockOptions lockOptions) throws HibernateException {
return this.byId( entityClass ).with( lockOptions ).load( id );
}
@ -1050,7 +1051,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
public Object get(String entityName, Serializable id, LockOptions lockOptions) throws HibernateException {
return this.byId( entityName ).with( lockOptions ).load( id );
}
@Override
public IdentifierLoadAccessImpl byId(String entityName) {
return new IdentifierLoadAccessImpl( entityName );
@ -1058,7 +1059,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
@Override
public <T> IdentifierLoadAccessImpl<T> byId(Class<T> entityClass) {
return new IdentifierLoadAccessImpl( entityClass );
return new IdentifierLoadAccessImpl<T>( entityClass );
}
@Override
@ -1067,8 +1068,8 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
}
@Override
public NaturalIdLoadAccess byNaturalId(Class entityClass) {
return new NaturalIdLoadAccessImpl( entityClass );
public <T> NaturalIdLoadAccess<T> byNaturalId(Class<T> entityClass) {
return new NaturalIdLoadAccessImpl<T>( entityClass );
}
@Override
@ -1077,8 +1078,8 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
}
@Override
public SimpleNaturalIdLoadAccess bySimpleNaturalId(Class entityClass) {
return new SimpleNaturalIdLoadAccessImpl( entityClass );
public <T> SimpleNaturalIdLoadAccess<T> bySimpleNaturalId(Class<T> entityClass) {
return new SimpleNaturalIdLoadAccessImpl<T>( entityClass );
}
private void fireLoad(LoadEvent event, LoadType loadType) {
@ -1160,7 +1161,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
@Override
public void replicate(String entityName, Object obj, ReplicationMode replicationMode)
throws HibernateException {
throws HibernateException {
fireReplicate( new ReplicateEvent( entityName, obj, replicationMode, this ) );
}
@ -1200,7 +1201,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
*/
protected boolean autoFlushIfRequired(Set querySpaces) throws HibernateException {
errorIfClosed();
if ( ! isTransactionInProgress() ) {
if ( !isTransactionInProgress() ) {
// do not auto-flush while outside a transaction
return false;
}
@ -1234,7 +1235,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
errorIfClosed();
checkTransactionSynchStatus();
if ( persistenceContext.getCascadeLevel() > 0 ) {
throw new HibernateException("Flush during cascade is dangerous");
throw new HibernateException( "Flush during cascade is dangerous" );
}
FlushEvent flushEvent = new FlushEvent( this );
for ( FlushEventListener listener : listeners( EventType.FLUSH ) ) {
@ -1249,14 +1250,15 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
if ( LOG.isDebugEnabled() ) {
LOG.debugf(
"Flushing to force deletion of re-saved object: %s",
MessageHelper.infoString( entityEntry.getPersister(), entityEntry.getId(), getFactory() ) );
MessageHelper.infoString( entityEntry.getPersister(), entityEntry.getId(), getFactory() )
);
}
if ( persistenceContext.getCascadeLevel() > 0 ) {
throw new ObjectDeletedException(
"deleted object would be re-saved by cascade (remove deleted object from associations)",
entityEntry.getId(),
entityEntry.getPersister().getEntityName()
"deleted object would be re-saved by cascade (remove deleted object from associations)",
entityEntry.getId(),
entityEntry.getPersister().getEntityName()
);
}
@ -1268,12 +1270,12 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
errorIfClosed();
checkTransactionSynchStatus();
queryParameters.validateParameters();
HQLQueryPlan plan = queryParameters.getQueryPlan();
if (plan == null) {
if ( plan == null ) {
plan = getHQLQueryPlan( query, false );
}
autoFlushIfRequired( plan.getQuerySpaces() );
List results = Collections.EMPTY_LIST;
@ -1314,27 +1316,29 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
}
@Override
public int executeNativeUpdate(NativeSQLQuerySpecification nativeQuerySpecification,
QueryParameters queryParameters) throws HibernateException {
errorIfClosed();
checkTransactionSynchStatus();
queryParameters.validateParameters();
NativeSQLQueryPlan plan = getNativeSQLQueryPlan( nativeQuerySpecification );
public int executeNativeUpdate(
NativeSQLQuerySpecification nativeQuerySpecification,
QueryParameters queryParameters) throws HibernateException {
errorIfClosed();
checkTransactionSynchStatus();
queryParameters.validateParameters();
NativeSQLQueryPlan plan = getNativeSQLQueryPlan( nativeQuerySpecification );
autoFlushIfRequired( plan.getCustomQuery().getQuerySpaces() );
autoFlushIfRequired( plan.getCustomQuery().getQuerySpaces() );
boolean success = false;
int result = 0;
try {
result = plan.performExecuteUpdate(queryParameters, this);
success = true;
} finally {
afterOperation( success );
delayedAfterCompletion();
boolean success = false;
int result = 0;
try {
result = plan.performExecuteUpdate( queryParameters, this );
success = true;
}
return result;
}
finally {
afterOperation( success );
delayedAfterCompletion();
}
return result;
}
@Override
public Iterator iterate(String query, QueryParameters queryParameters) throws HibernateException {
@ -1376,9 +1380,9 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
checkTransactionSynchStatus();
CollectionFilterImpl filter = new CollectionFilterImpl(
queryString,
collection,
this,
getFilterQueryPlan( collection, queryString, null, false ).getParameterMetadata()
collection,
this,
getFilterQueryPlan( collection, queryString, null, false ).getParameterMetadata()
);
filter.setComment( queryString );
delayedAfterCompletion();
@ -1406,7 +1410,11 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
public Object instantiate(EntityPersister persister, Serializable id) throws HibernateException {
errorIfClosed();
checkTransactionSynchStatus();
Object result = interceptor.instantiate( persister.getEntityName(), persister.getEntityMetamodel().getEntityMode(), id );
Object result = interceptor.instantiate(
persister.getEntityName(),
persister.getEntityMetamodel().getEntityMode(),
id
);
if ( result == null ) {
result = persister.instantiate( id, this );
}
@ -1439,7 +1447,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
errorIfClosed();
checkTransactionSynchStatus();
LOG.tracev( "Setting cache mode to: {0}", cacheMode );
this.cacheMode= cacheMode;
this.cacheMode = cacheMode;
}
@Override
@ -1453,7 +1461,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
@Override
public EntityPersister getEntityPersister(final String entityName, final Object object) {
errorIfClosed();
if (entityName==null) {
if ( entityName == null ) {
return factory.getEntityPersister( guessEntityName( object ) );
}
else {
@ -1465,11 +1473,11 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
try {
return factory.getEntityPersister( entityName ).getSubclassEntityPersister( object, getFactory() );
}
catch( HibernateException e ) {
catch (HibernateException e) {
try {
return getEntityPersister( null, object );
}
catch( HibernateException e2 ) {
catch (HibernateException e2) {
throw e;
}
}
@ -1489,7 +1497,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
return li.getIdentifier();
}
else {
EntityEntry entry = persistenceContext.getEntry(object);
EntityEntry entry = persistenceContext.getEntry( object );
if ( entry == null ) {
throw new TransientObjectException( "The instance was not associated with this session" );
}
@ -1508,7 +1516,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
return getProxyIdentifier( object );
}
else {
EntityEntry entry = persistenceContext.getEntry(object);
EntityEntry entry = persistenceContext.getEntry( object );
return entry != null ? entry.getId() : null;
}
}
@ -1527,7 +1535,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
}
CollectionEntry entry = persistenceContext.getCollectionEntryOrNull( collection );
final CollectionPersister roleBeforeFlush = (entry == null) ? null : entry.getLoadedPersister();
final CollectionPersister roleBeforeFlush = ( entry == null ) ? null : entry.getLoadedPersister();
FilterQueryPlan plan = null;
if ( roleBeforeFlush == null ) {
@ -1535,7 +1543,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
// get its state into the database in order to execute query
flush();
entry = persistenceContext.getCollectionEntryOrNull( collection );
CollectionPersister roleAfterFlush = (entry == null) ? null : entry.getLoadedPersister();
CollectionPersister roleAfterFlush = ( entry == null ) ? null : entry.getLoadedPersister();
if ( roleAfterFlush == null ) {
throw new QueryException( "The collection was unreferenced" );
}
@ -1559,7 +1567,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
// might need to run a different filter entirely after the flush
// because the collection role may have changed
entry = persistenceContext.getCollectionEntryOrNull( collection );
CollectionPersister roleAfterFlush = (entry == null) ? null : entry.getLoadedPersister();
CollectionPersister roleAfterFlush = ( entry == null ) ? null : entry.getLoadedPersister();
if ( roleBeforeFlush != roleAfterFlush ) {
if ( roleAfterFlush == null ) {
throw new QueryException( "The collection was dereferenced" );
@ -1584,7 +1592,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
@Override
public List listFilter(Object collection, String filter, QueryParameters queryParameters)
throws HibernateException {
throws HibernateException {
errorIfClosed();
checkTransactionSynchStatus();
FilterQueryPlan plan = getFilterQueryPlan( collection, filter, queryParameters, false );
@ -1598,7 +1606,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
}
finally {
dontFlushFromFind--;
afterOperation(success);
afterOperation( success );
delayedAfterCompletion();
}
return results;
@ -1606,7 +1614,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
@Override
public Iterator iterateFilter(Object collection, String filter, QueryParameters queryParameters)
throws HibernateException {
throws HibernateException {
errorIfClosed();
checkTransactionSynchStatus();
FilterQueryPlan plan = getFilterQueryPlan( collection, filter, queryParameters, true );
@ -1626,7 +1634,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
public Criteria createCriteria(String entityName, String alias) {
errorIfClosed();
checkTransactionSynchStatus();
return new CriteriaImpl(entityName, alias, this);
return new CriteriaImpl( entityName, alias, this );
}
@Override
@ -1640,19 +1648,19 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
public Criteria createCriteria(String entityName) {
errorIfClosed();
checkTransactionSynchStatus();
return new CriteriaImpl(entityName, this);
return new CriteriaImpl( entityName, this );
}
@Override
public ScrollableResults scroll(Criteria criteria, ScrollMode scrollMode) {
// TODO: Is this guaranteed to always be CriteriaImpl?
CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;
errorIfClosed();
checkTransactionSynchStatus();
String entityName = criteriaImpl.getEntityOrClassName();
CriteriaLoader loader = new CriteriaLoader(
getOuterJoinLoadable(entityName),
getOuterJoinLoadable( entityName ),
factory,
criteriaImpl,
entityName,
@ -1661,7 +1669,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
autoFlushIfRequired( loader.getQuerySpaces() );
dontFlushFromFind++;
try {
return loader.scroll(this, scrollMode);
return loader.scroll( this, scrollMode );
}
finally {
delayedAfterCompletion();
@ -1673,7 +1681,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
public List list(Criteria criteria) throws HibernateException {
// TODO: Is this guaranteed to always be CriteriaImpl?
CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;
final NaturalIdLoadAccess naturalIdLoadAccess = this.tryNaturalIdLoadAccess( criteriaImpl );
if ( naturalIdLoadAccess != null ) {
// EARLY EXIT!
@ -1687,7 +1695,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
CriteriaLoader[] loaders = new CriteriaLoader[size];
Set spaces = new HashSet();
for( int i=0; i <size; i++ ) {
for ( int i = 0; i < size; i++ ) {
loaders[i] = new CriteriaLoader(
getOuterJoinLoadable( implementors[i] ),
@ -1695,28 +1703,28 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
criteriaImpl,
implementors[i],
getLoadQueryInfluencers()
);
);
spaces.addAll( loaders[i].getQuerySpaces() );
}
autoFlushIfRequired(spaces);
autoFlushIfRequired( spaces );
List results = Collections.EMPTY_LIST;
dontFlushFromFind++;
boolean success = false;
try {
for( int i=0; i<size; i++ ) {
final List currentResults = loaders[i].list(this);
currentResults.addAll(results);
for ( int i = 0; i < size; i++ ) {
final List currentResults = loaders[i].list( this );
currentResults.addAll( results );
results = currentResults;
}
success = true;
}
finally {
dontFlushFromFind--;
afterOperation(success);
afterOperation( success );
delayedAfterCompletion();
}
@ -1730,7 +1738,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
* @param criteria The criteria to check as a complete natural identifier lookup.
*
* @return A fully configured NaturalIdLoadAccess or null, if null is returned the standard CriteriaImpl execution
* should be performed
* should be performed
*/
private NaturalIdLoadAccess tryNaturalIdLoadAccess(CriteriaImpl criteria) {
// See if the criteria lookup is by naturalId
@ -1764,8 +1772,8 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
final NaturalIdLoadAccess naturalIdLoader = this.byNaturalId( entityName );
// Build NaturalIdLoadAccess and in the process verify all naturalId properties were specified
for ( int i = 0; i < naturalIdentifierProperties.length; i++ ) {
final String naturalIdProperty = propertyNames[naturalIdentifierProperties[i]];
for ( int naturalIdentifierProperty : naturalIdentifierProperties ) {
final String naturalIdProperty = propertyNames[naturalIdentifierProperty];
final Object naturalIdValue = naturalIdValues.get( naturalIdProperty );
if ( naturalIdValue == null ) {
@ -1777,18 +1785,20 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
}
// Critera query contains a valid naturalId, use the new API
LOG.warn( "Session.byNaturalId(" + entityName
+ ") should be used for naturalId queries instead of Restrictions.naturalId() from a Criteria" );
LOG.warn(
"Session.byNaturalId(" + entityName
+ ") should be used for naturalId queries instead of Restrictions.naturalId() from a Criteria"
);
return naturalIdLoader;
}
private OuterJoinLoadable getOuterJoinLoadable(String entityName) throws MappingException {
EntityPersister persister = factory.getEntityPersister(entityName);
if ( !(persister instanceof OuterJoinLoadable) ) {
EntityPersister persister = factory.getEntityPersister( entityName );
if ( !( persister instanceof OuterJoinLoadable ) ) {
throw new MappingException( "class persister is not OuterJoinLoadable: " + entityName );
}
return ( OuterJoinLoadable ) persister;
return (OuterJoinLoadable) persister;
}
@Override
@ -1804,7 +1814,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
//if it is an uninitialized proxy, pointing
//with this session, then when it is accessed,
//the underlying instance will be "contained"
return li.getSession()==this;
return li.getSession() == this;
}
else {
//if it is initialized, see if the underlying
@ -1859,7 +1869,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
@Override
public ScrollableResults scrollCustomQuery(CustomQuery customQuery, QueryParameters queryParameters)
throws HibernateException {
throws HibernateException {
errorIfClosed();
checkTransactionSynchStatus();
@ -1873,7 +1883,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
dontFlushFromFind++; //stops flush being called multiple times if this method is recursively called
try {
return loader.scroll(queryParameters, this);
return loader.scroll( queryParameters, this );
}
finally {
delayedAfterCompletion();
@ -1884,7 +1894,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
// basically just an adapted copy of find(CriteriaImpl)
@Override
public List listCustomQuery(CustomQuery customQuery, QueryParameters queryParameters)
throws HibernateException {
throws HibernateException {
errorIfClosed();
checkTransactionSynchStatus();
@ -1899,14 +1909,14 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
dontFlushFromFind++;
boolean success = false;
try {
List results = loader.list(this, queryParameters);
List results = loader.list( this, queryParameters );
success = true;
return results;
}
finally {
dontFlushFromFind--;
delayedAfterCompletion();
afterOperation(success);
afterOperation( success );
}
}
@ -1918,7 +1928,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
@Override
public void initializeCollection(PersistentCollection collection, boolean writing)
throws HibernateException {
throws HibernateException {
errorIfClosed();
checkTransactionSynchStatus();
InitializeCollectionEvent event = new InitializeCollectionEvent( collection, this );
@ -1930,8 +1940,8 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
@Override
public String bestGuessEntityName(Object object) {
if (object instanceof HibernateProxy) {
LazyInitializer initializer = ( ( HibernateProxy ) object ).getHibernateLazyInitializer();
if ( object instanceof HibernateProxy ) {
LazyInitializer initializer = ( (HibernateProxy) object ).getHibernateLazyInitializer();
// it is possible for this method to be called during flush processing,
// so make certain that we do not accidentally initialize an uninitialized proxy
if ( initializer.isUninitialized() ) {
@ -1939,9 +1949,9 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
}
object = initializer.getImplementation();
}
EntityEntry entry = persistenceContext.getEntry(object);
if (entry==null) {
return guessEntityName(object);
EntityEntry entry = persistenceContext.getEntry( object );
if ( entry == null ) {
return guessEntityName( object );
}
else {
return entry.getPersister().getEntityName();
@ -1952,14 +1962,14 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
public String getEntityName(Object object) {
errorIfClosed();
checkTransactionSynchStatus();
if (object instanceof HibernateProxy) {
if ( object instanceof HibernateProxy ) {
if ( !persistenceContext.containsProxy( object ) ) {
throw new TransientObjectException("proxy was not associated with the session");
throw new TransientObjectException( "proxy was not associated with the session" );
}
object = ( (HibernateProxy) object ).getHibernateLazyInitializer().getImplementation();
}
EntityEntry entry = persistenceContext.getEntry(object);
EntityEntry entry = persistenceContext.getEntry( object );
if ( entry == null ) {
throwTransientObjectException( object );
}
@ -1969,8 +1979,8 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
private void throwTransientObjectException(Object object) throws HibernateException {
throw new TransientObjectException(
"object references an unsaved transient instance - save the transient instance before flushing: " +
guessEntityName(object)
);
guessEntityName( object )
);
}
@Override
@ -1998,17 +2008,17 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
@Override
public String toString() {
StringBuilder buf = new StringBuilder(500)
.append( "SessionImpl(" );
StringBuilder buf = new StringBuilder( 500 )
.append( "SessionImpl(" );
if ( !isClosed() ) {
buf.append(persistenceContext)
.append(";")
.append(actionQueue);
buf.append( persistenceContext )
.append( ";" )
.append( actionQueue );
}
else {
buf.append("<closed>");
buf.append( "<closed>" );
}
return buf.append(')').toString();
return buf.append( ')' ).toString();
}
@Override
@ -2028,7 +2038,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
@Override
public SessionStatistics getStatistics() {
checkTransactionSynchStatus();
return new SessionStatisticsImpl(this);
return new SessionStatisticsImpl( this );
}
@Override
@ -2164,6 +2174,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
* Used by JDK serialization...
*
* @param ois The input stream from which we are being read...
*
* @throws IOException Indicates a general IO stream exception
* @throws ClassNotFoundException Indicates a class resolution issue
*/
@ -2191,7 +2202,10 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
jdbcCoordinator = JdbcCoordinatorImpl.deserialize( ois, this );
this.transactionCoordinator = getTransactionCoordinatorBuilder().buildTransactionCoordinator( jdbcCoordinator, this );
this.transactionCoordinator = getTransactionCoordinatorBuilder().buildTransactionCoordinator(
jdbcCoordinator,
this
);
persistenceContext = StatefulPersistenceContext.deserialize( ois, this );
actionQueue = ActionQueue.deserialize( ois, this );
@ -2202,7 +2216,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
// filter, which will fail when called before FilterImpl.afterDeserialize( factory );
// Instead lookup the filter by name and then call FilterImpl.afterDeserialize( factory ).
for ( String filterName : loadQueryInfluencers.getEnabledFilterNames() ) {
((FilterImpl) loadQueryInfluencers.getEnabledFilter( filterName )).afterDeserialize( factory );
( (FilterImpl) loadQueryInfluencers.getEnabledFilter( filterName ) ).afterDeserialize( factory );
}
}
@ -2210,6 +2224,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
* Used by JDK serialization...
*
* @param oos The output stream to which we are being written...
*
* @throws IOException Indicates a general IO stream exception
*/
private void writeObject(ObjectOutputStream oos) throws IOException {
@ -2353,7 +2368,8 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
}
}
private static class SharedSessionBuilderImpl extends SessionFactoryImpl.SessionBuilderImpl implements SharedSessionBuilder {
private static class SharedSessionBuilderImpl extends SessionFactoryImpl.SessionBuilderImpl
implements SharedSessionBuilder {
private final SessionImpl session;
private boolean shareTransactionContext;
@ -2511,9 +2527,10 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
private class LockRequestImpl implements LockRequest {
private final LockOptions lockOptions;
private LockRequestImpl(LockOptions lo) {
lockOptions = new LockOptions();
LockOptions.copy(lo, lockOptions);
LockOptions.copy( lo, lockOptions );
}
@Override
@ -2523,7 +2540,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
@Override
public LockRequest setLockMode(LockMode lockMode) {
lockOptions.setLockMode(lockMode);
lockOptions.setLockMode( lockMode );
return this;
}
@ -2534,7 +2551,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
@Override
public LockRequest setTimeOut(int timeout) {
lockOptions.setTimeOut(timeout);
lockOptions.setTimeOut( timeout );
return this;
}
@ -2545,7 +2562,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
@Override
public LockRequest setScope(boolean scope) {
lockOptions.setScope(scope);
lockOptions.setScope( scope );
return this;
}
@ -2596,7 +2613,10 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
try {
fireLoad( event, LoadEventListener.LOAD );
if ( event.getResult() == null ) {
getFactory().getEntityNotFoundDelegate().handleEntityNotFound( entityPersister.getEntityName(), id );
getFactory().getEntityNotFoundDelegate().handleEntityNotFound(
entityPersister.getEntityName(),
id
);
}
success = true;
return (T) event.getResult();
@ -2639,7 +2659,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
return factory.locateEntityPersister( entityName );
}
private abstract class BaseNaturalIdLoadAccessImpl<T> {
private abstract class BaseNaturalIdLoadAccessImpl<T> {
private final EntityPersister entityPersister;
private LockOptions lockOptions;
private boolean synchronizationEnabled = true;
@ -2647,7 +2667,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
private BaseNaturalIdLoadAccessImpl(EntityPersister entityPersister) {
this.entityPersister = entityPersister;
if ( ! entityPersister.hasNaturalIdentifier() ) {
if ( !entityPersister.hasNaturalIdentifier() ) {
throw new HibernateException(
String.format( "Entity [%s] did not define a natural id", entityPersister.getEntityName() )
);
@ -2679,7 +2699,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
}
protected void performAnyNeededCrossReferenceSynchronizations() {
if ( ! synchronizationEnabled ) {
if ( !synchronizationEnabled ) {
// synchronization (this process) was disabled
return;
}
@ -2687,13 +2707,14 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
// only mutable natural-ids need this processing
return;
}
if ( ! isTransactionInProgress() ) {
if ( !isTransactionInProgress() ) {
// not in a transaction so skip synchronization
return;
}
final boolean debugEnabled = LOG.isDebugEnabled();
for ( Serializable pk : getPersistenceContext().getNaturalIdHelper().getCachedPkResolutions( entityPersister ) ) {
for ( Serializable pk : getPersistenceContext().getNaturalIdHelper()
.getCachedPkResolutions( entityPersister ) ) {
final EntityKey entityKey = generateEntityKey( pk, entityPersister );
final Object entity = getPersistenceContext().getEntity( entityKey );
final EntityEntry entry = getPersistenceContext().getEntry( entity );
@ -2742,7 +2763,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
private final Map<String, Object> naturalIdParameters = new LinkedHashMap<String, Object>();
private NaturalIdLoadAccessImpl(EntityPersister entityPersister) {
super(entityPersister);
super( entityPersister );
}
private NaturalIdLoadAccessImpl(String entityName) {
@ -2752,7 +2773,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
private NaturalIdLoadAccessImpl(Class entityClass) {
this( locateEntityPersister( entityClass ) );
}
@Override
public NaturalIdLoadAccessImpl<T> with(LockOptions lockOptions) {
return (NaturalIdLoadAccessImpl<T>) super.with( lockOptions );
@ -2800,20 +2821,24 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
}
}
private class SimpleNaturalIdLoadAccessImpl<T> extends BaseNaturalIdLoadAccessImpl<T> implements SimpleNaturalIdLoadAccess<T> {
private class SimpleNaturalIdLoadAccessImpl<T> extends BaseNaturalIdLoadAccessImpl<T>
implements SimpleNaturalIdLoadAccess<T> {
private final String naturalIdAttributeName;
private SimpleNaturalIdLoadAccessImpl(EntityPersister entityPersister) {
super(entityPersister);
super( entityPersister );
if ( entityPersister.getNaturalIdentifierProperties().length != 1 ) {
throw new HibernateException(
String.format( "Entity [%s] did not define a simple natural id", entityPersister.getEntityName() )
String.format(
"Entity [%s] did not define a simple natural id",
entityPersister.getEntityName()
)
);
}
final int naturalIdAttributePosition = entityPersister.getNaturalIdentifierProperties()[0];
this.naturalIdAttributeName = entityPersister.getPropertyNames()[ naturalIdAttributePosition ];
this.naturalIdAttributeName = entityPersister.getPropertyNames()[naturalIdAttributePosition];
}
private SimpleNaturalIdLoadAccessImpl(String entityName) {
@ -2828,7 +2853,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
public final SimpleNaturalIdLoadAccessImpl<T> with(LockOptions lockOptions) {
return (SimpleNaturalIdLoadAccessImpl<T>) super.with( lockOptions );
}
private Map<String, Object> getNaturalIdParameters(Object naturalIdValue) {
return Collections.singletonMap( naturalIdAttributeName, naturalIdValue );
}
@ -2897,7 +2922,7 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
return true;
}
final TransactionStatus status = currentHibernateTransaction.getStatus();
return status == TransactionStatus.ACTIVE || status ==TransactionStatus.COMMITTING;
return status == TransactionStatus.ACTIVE || status == TransactionStatus.COMMITTING;
}
private static final ExceptionMapper STANDARD_EXCEPTION_MAPPER = new ExceptionMapper() {
@ -2927,8 +2952,8 @@ public final class SessionImpl extends AbstractSessionImpl implements EventSourc
@Override
public boolean shouldDoManagedFlush(SessionImpl session) {
boolean isFlushModeNever = session.isFlushModeNever();
return (!isFlushModeNever &&
!session.flushBeforeCompletionEnabled) ||
return ( !isFlushModeNever &&
!session.flushBeforeCompletionEnabled ) ||
!session.isClosed()
&& !isFlushModeNever
&& session.flushBeforeCompletionEnabled;

View File

@ -80,7 +80,7 @@ import org.hibernate.resource.transaction.spi.TransactionStatus;
* @author Steve Ebersole
*/
public class StatelessSessionImpl extends AbstractSessionImpl implements StatelessSession {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( StatelessSessionImpl.class );
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( StatelessSessionImpl.class );
private TransactionCoordinator transactionCoordinator;
@ -124,7 +124,10 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
);
this.jdbcCoordinator = new JdbcCoordinatorImpl( connection, this );
this.transactionCoordinator = getTransactionCoordinatorBuilder().buildTransactionCoordinator( jdbcCoordinator, this );
this.transactionCoordinator = getTransactionCoordinatorBuilder().buildTransactionCoordinator(
jdbcCoordinator,
this
);
this.currentHibernateTransaction = getTransaction();
this.timestamp = timestamp;
}
@ -149,7 +152,7 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
@Override
public Serializable insert(Object entity) {
errorIfClosed();
return insert(null, entity);
return insert( null, entity );
}
@Override
@ -167,10 +170,10 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
}
}
if ( id == IdentifierGeneratorHelper.POST_INSERT_INDICATOR ) {
id = persister.insert(state, entity, this);
id = persister.insert( state, entity, this );
}
else {
persister.insert(id, state, entity, this);
persister.insert( id, state, entity, this );
}
persister.setIdentifier( entity, id, this );
return id;
@ -200,26 +203,26 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
@Override
public void update(Object entity) {
errorIfClosed();
update(null, entity);
update( null, entity );
}
@Override
public void update(String entityName, Object entity) {
errorIfClosed();
EntityPersister persister = getEntityPersister(entityName, entity);
EntityPersister persister = getEntityPersister( entityName, entity );
Serializable id = persister.getIdentifier( entity, this );
Object[] state = persister.getPropertyValues( entity );
Object oldVersion;
if ( persister.isVersioned() ) {
oldVersion = persister.getVersion( entity );
Object newVersion = Versioning.increment( oldVersion, persister.getVersionType(), this );
Versioning.setVersion(state, newVersion, persister);
Versioning.setVersion( state, newVersion, persister );
persister.setPropertyValues( entity, state );
}
else {
oldVersion = null;
}
persister.update(id, state, null, false, null, oldVersion, entity, null, this);
persister.update( id, state, null, false, null, oldVersion, entity, null, this );
}
@ -237,14 +240,14 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
@Override
public Object get(String entityName, Serializable id) {
return get(entityName, id, LockMode.NONE);
return get( entityName, id, LockMode.NONE );
}
@Override
public Object get(String entityName, Serializable id, LockMode lockMode) {
errorIfClosed();
Object result = getFactory().getEntityPersister(entityName)
.load(id, null, lockMode, this);
Object result = getFactory().getEntityPersister( entityName )
.load( id, null, lockMode, this );
if ( temporaryPersistenceContext.isLoadFinished() ) {
temporaryPersistenceContext.clear();
}
@ -302,20 +305,20 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
@Override
public Object immediateLoad(String entityName, Serializable id)
throws HibernateException {
throw new SessionException("proxies cannot be fetched by a stateless session");
throw new SessionException( "proxies cannot be fetched by a stateless session" );
}
@Override
public void initializeCollection(
PersistentCollection collection,
boolean writing) throws HibernateException {
throw new SessionException("collections cannot be fetched by a stateless session");
boolean writing) throws HibernateException {
throw new SessionException( "collections cannot be fetched by a stateless session" );
}
@Override
public Object instantiate(
String entityName,
Serializable id) throws HibernateException {
Serializable id) throws HibernateException {
errorIfClosed();
return getFactory().getEntityPersister( entityName ).instantiate( id, this );
}
@ -323,9 +326,9 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
@Override
public Object internalLoad(
String entityName,
Serializable id,
boolean eager,
boolean nullable) throws HibernateException {
Serializable id,
boolean eager,
boolean nullable) throws HibernateException {
errorIfClosed();
EntityPersister persister = getFactory().getEntityPersister( entityName );
// first, try to load it from the temp PC associated to this SS
@ -351,13 +354,13 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
@Override
public Iterator iterateFilter(Object collection, String filter, QueryParameters queryParameters)
throws HibernateException {
throws HibernateException {
throw new UnsupportedOperationException();
}
@Override
public List listFilter(Object collection, String filter, QueryParameters queryParameters)
throws HibernateException {
throws HibernateException {
throw new UnsupportedOperationException();
}
@ -411,10 +414,10 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
@Override
public String bestGuessEntityName(Object object) {
if (object instanceof HibernateProxy) {
if ( object instanceof HibernateProxy ) {
object = ( (HibernateProxy) object ).getHibernateLazyInitializer().getImplementation();
}
return guessEntityName(object);
return guessEntityName( object );
}
@Override
@ -436,7 +439,7 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
success = true;
}
finally {
afterOperation(success);
afterOperation( success );
}
temporaryPersistenceContext.clear();
return result;
@ -466,7 +469,7 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
public EntityPersister getEntityPersister(String entityName, Object object)
throws HibernateException {
errorIfClosed();
if ( entityName==null ) {
if ( entityName == null ) {
return factory.getEntityPersister( guessEntityName( object ) );
}
else {
@ -576,14 +579,14 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
success = true;
}
finally {
afterOperation(success);
afterOperation( success );
}
temporaryPersistenceContext.clear();
return results;
}
public void afterOperation(boolean success) {
if ( ! isTransactionInProgress() ) {
if ( !isTransactionInProgress() ) {
jdbcCoordinator.afterTransaction();
}
}
@ -597,7 +600,7 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
@Override
public Criteria createCriteria(String entityName, String alias) {
errorIfClosed();
return new CriteriaImpl(entityName, alias, this);
return new CriteriaImpl( entityName, alias, this );
}
@Override
@ -609,44 +612,44 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
@Override
public Criteria createCriteria(String entityName) {
errorIfClosed();
return new CriteriaImpl(entityName, this);
return new CriteriaImpl( entityName, this );
}
@Override
public ScrollableResults scroll(Criteria criteria, ScrollMode scrollMode) {
// TODO: Is this guaranteed to always be CriteriaImpl?
CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;
errorIfClosed();
String entityName = criteriaImpl.getEntityOrClassName();
CriteriaLoader loader = new CriteriaLoader(
getOuterJoinLoadable( entityName ),
factory,
criteriaImpl,
entityName,
getLoadQueryInfluencers()
factory,
criteriaImpl,
entityName,
getLoadQueryInfluencers()
);
return loader.scroll(this, scrollMode);
return loader.scroll( this, scrollMode );
}
@Override
@SuppressWarnings( {"unchecked"})
@SuppressWarnings({"unchecked"})
public List list(Criteria criteria) throws HibernateException {
// TODO: Is this guaranteed to always be CriteriaImpl?
CriteriaImpl criteriaImpl = (CriteriaImpl) criteria;
errorIfClosed();
String[] implementors = factory.getImplementors( criteriaImpl.getEntityOrClassName() );
int size = implementors.length;
CriteriaLoader[] loaders = new CriteriaLoader[size];
for( int i=0; i <size; i++ ) {
for ( int i = 0; i < size; i++ ) {
loaders[i] = new CriteriaLoader(
getOuterJoinLoadable( implementors[i] ),
factory,
criteriaImpl,
implementors[i],
getLoadQueryInfluencers()
factory,
criteriaImpl,
implementors[i],
getLoadQueryInfluencers()
);
}
@ -654,42 +657,42 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
List results = Collections.EMPTY_LIST;
boolean success = false;
try {
for( int i=0; i<size; i++ ) {
final List currentResults = loaders[i].list(this);
currentResults.addAll(results);
for ( int i = 0; i < size; i++ ) {
final List currentResults = loaders[i].list( this );
currentResults.addAll( results );
results = currentResults;
}
success = true;
}
finally {
afterOperation(success);
afterOperation( success );
}
temporaryPersistenceContext.clear();
return results;
}
private OuterJoinLoadable getOuterJoinLoadable(String entityName) throws MappingException {
EntityPersister persister = factory.getEntityPersister(entityName);
if ( !(persister instanceof OuterJoinLoadable) ) {
EntityPersister persister = factory.getEntityPersister( entityName );
if ( !( persister instanceof OuterJoinLoadable ) ) {
throw new MappingException( "class persister is not OuterJoinLoadable: " + entityName );
}
return ( OuterJoinLoadable ) persister;
return (OuterJoinLoadable) persister;
}
@Override
public List listCustomQuery(CustomQuery customQuery, QueryParameters queryParameters)
throws HibernateException {
throws HibernateException {
errorIfClosed();
CustomLoader loader = new CustomLoader( customQuery, getFactory() );
boolean success = false;
List results;
try {
results = loader.list(this, queryParameters);
results = loader.list( this, queryParameters );
success = true;
}
finally {
afterOperation(success);
afterOperation( success );
}
temporaryPersistenceContext.clear();
return results;
@ -697,7 +700,7 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
@Override
public ScrollableResults scrollCustomQuery(CustomQuery customQuery, QueryParameters queryParameters)
throws HibernateException {
throws HibernateException {
errorIfClosed();
CustomLoader loader = new CustomLoader( customQuery, getFactory() );
return loader.scroll( queryParameters, this );
@ -725,19 +728,21 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
}
@Override
public int executeNativeUpdate(NativeSQLQuerySpecification nativeSQLQuerySpecification,
public int executeNativeUpdate(
NativeSQLQuerySpecification nativeSQLQuerySpecification,
QueryParameters queryParameters) throws HibernateException {
errorIfClosed();
queryParameters.validateParameters();
NativeSQLQueryPlan plan = getNativeSQLQueryPlan(nativeSQLQuerySpecification);
NativeSQLQueryPlan plan = getNativeSQLQueryPlan( nativeSQLQuerySpecification );
boolean success = false;
int result = 0;
try {
result = plan.performExecuteUpdate(queryParameters, this);
result = plan.performExecuteUpdate( queryParameters, this );
success = true;
} finally {
afterOperation(success);
}
finally {
afterOperation( success );
}
temporaryPersistenceContext.clear();
return result;
@ -774,7 +779,7 @@ public class StatelessSessionImpl extends AbstractSessionImpl implements Statele
&& !isFlushModeNever()
&& !JtaStatusHelper.isRollback(
getJtaPlatform().getCurrentStatus()
));
) );
}
catch (SystemException se) {
throw new HibernateException( "could not determine transaction status in beforeCompletion()", se );

View File

@ -111,7 +111,7 @@ public final class BytesHelper {
throw new IllegalArgumentException( "Expecting 8 byte values to construct a long" );
}
long value = 0;
for (int i=0; i<8; i++) {
for (int i=0; i<8; i++) {
value = (value << 8) | (bytes[i] & 0xff);
}
return value;

View File

@ -20,7 +20,6 @@
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.internal.util;
@ -35,11 +34,11 @@ import org.hibernate.HibernateException;
/**
* An object that is shallow-coneable
*
*
* @author Steve Ebersole
*/
public class Cloneable {
private static final Object[] READER_METHOD_ARGS = new Object[0];
/**
@ -51,12 +50,13 @@ public class Cloneable {
*/
public Object shallowCopy() {
return AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
return copyListeners();
}
}
);
new PrivilegedAction() {
@Override
public Object run() {
return copyListeners();
}
}
);
}
/**
@ -68,13 +68,14 @@ public class Cloneable {
*/
public void validate() throws HibernateException {
AccessController.doPrivileged(
new PrivilegedAction() {
public Object run() {
checkListeners();
return null;
}
}
);
new PrivilegedAction() {
@Override
public Object run() {
checkListeners();
return null;
}
}
);
}
@ -86,21 +87,19 @@ public class Cloneable {
internalCheckListeners( beanInfo );
copy = getClass().newInstance();
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
for ( int i = 0, max = pds.length; i < max; i++ ) {
for ( PropertyDescriptor pd : pds ) {
try {
pds[i].getWriteMethod().invoke(
pd.getWriteMethod().invoke(
copy,
new Object[] {
pds[i].getReadMethod().invoke( this, READER_METHOD_ARGS )
}
);
pd.getReadMethod().invoke( this, READER_METHOD_ARGS )
);
}
catch( Throwable t ) {
throw new HibernateException( "Unable copy copy listener [" + pds[i].getName() + "]" );
catch (Throwable t) {
throw new HibernateException( "Unable copy copy listener [" + pd.getName() + "]" );
}
}
}
catch( Exception t ) {
catch (Exception t) {
throw new HibernateException( "Unable to copy listeners", t );
}
finally {
@ -110,7 +109,7 @@ public class Cloneable {
Introspector.flushFromCaches( getClass() );
}
}
return copy;
}
@ -120,7 +119,7 @@ public class Cloneable {
beanInfo = Introspector.getBeanInfo( getClass(), Object.class );
internalCheckListeners( beanInfo );
}
catch( IntrospectionException t ) {
catch (IntrospectionException t) {
throw new HibernateException( "Unable to validate listener config", t );
}
finally {
@ -135,28 +134,27 @@ public class Cloneable {
private void internalCheckListeners(BeanInfo beanInfo) {
PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
try {
for ( int i = 0, max = pds.length; i < max; i++ ) {
final Object listener = pds[i].getReadMethod().invoke( this, READER_METHOD_ARGS );
for ( PropertyDescriptor pd : pds ) {
final Object listener = pd.getReadMethod().invoke( this, READER_METHOD_ARGS );
if ( listener == null ) {
throw new HibernateException( "Listener [" + pds[i].getName() + "] was null" );
throw new HibernateException( "Listener [" + pd.getName() + "] was null" );
}
if ( listener.getClass().isArray() ) {
Object[] listenerArray = (Object[]) listener;
int length = listenerArray.length;
for ( int index = 0 ; index < length ; index++ ) {
if ( listenerArray[index] == null ) {
throw new HibernateException( "Listener in [" + pds[i].getName() + "] was null" );
for ( Object aListenerArray : listenerArray ) {
if ( aListenerArray == null ) {
throw new HibernateException( "Listener in [" + pd.getName() + "] was null" );
}
}
}
}
}
catch( HibernateException e ) {
catch (HibernateException e) {
throw e;
}
catch( Throwable t ) {
catch (Throwable t) {
throw new HibernateException( "Unable to validate listener config" );
}
}
}

View File

@ -33,34 +33,34 @@ import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.cfg.Environment;
import org.hibernate.internal.CoreLogging;
import org.hibernate.internal.CoreMessageLogger;
import org.jboss.logging.Logger;
/**
* A simple class to centralize logic needed to locate config files on the system.
*
* @todo : Update usages to use {@link org.hibernate.boot.registry.classloading.spi.ClassLoaderService}
*
* @author Steve Ebersole
* @todo : Update usages to use {@link org.hibernate.boot.registry.classloading.spi.ClassLoaderService}
*/
public final class ConfigHelper {
private static final CoreMessageLogger LOG = Logger.getMessageLogger(CoreMessageLogger.class, ConfigHelper.class.getName());
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( ConfigHelper.class );
/** 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
* assumes that the incoming path is an actual URL string (file://, etc). If this
* does not work, then the next attempts try to locate this UURL as a java system
* resource.
*
* @param path The path representing the config location.
*
* @return An appropriate URL or null.
*/
public static URL locateConfig(final String path) {
try {
return new URL(path);
return new URL( path );
}
catch(MalformedURLException e) {
return findAsResource(path);
catch (MalformedURLException e) {
return findAsResource( path );
}
}
@ -70,6 +70,7 @@ public final class ConfigHelper {
* java system resource.
*
* @param path The path representing the config location.
*
* @return An appropriate URL or null.
*/
public static URL findAsResource(final String path) {
@ -78,91 +79,101 @@ public final class ConfigHelper {
// First, try to locate this resource through the current
// context classloader.
ClassLoader contextClassLoader = ClassLoaderHelper.getContextClassLoader();
if (contextClassLoader!=null) {
url = contextClassLoader.getResource(path);
if ( contextClassLoader != null ) {
url = contextClassLoader.getResource( path );
}
if (url != null) {
if ( url != null ) {
return url;
}
// Next, try to locate this resource through this class's classloader
url = ConfigHelper.class.getClassLoader().getResource(path);
if (url != null) {
url = ConfigHelper.class.getClassLoader().getResource( path );
if ( url != null ) {
return url;
}
// Next, try to locate this resource through the system classloader
url = ClassLoader.getSystemClassLoader().getResource(path);
url = ClassLoader.getSystemClassLoader().getResource( path );
// Anywhere else we should look?
return url;
}
/** Open an InputStream to the URL represented by the incoming path. First makes a call
/**
* Open an InputStream to the URL represented by the incoming path. First makes a call
* to {@link #locateConfig(java.lang.String)} in order to find an appropriate URL.
* {@link java.net.URL#openStream()} is then called to obtain the stream.
*
* @param path The path representing the config location.
*
* @return An input stream to the requested config resource.
*
* @throws HibernateException Unable to open stream to that resource.
*/
public static InputStream getConfigStream(final String path) throws HibernateException {
final URL url = ConfigHelper.locateConfig(path);
final URL url = ConfigHelper.locateConfig( path );
if (url == null) {
String msg = LOG.unableToLocateConfigFile(path);
LOG.error(msg);
throw new HibernateException(msg);
if ( url == null ) {
String msg = LOG.unableToLocateConfigFile( path );
LOG.error( msg );
throw new HibernateException( msg );
}
try {
return url.openStream();
}
catch(IOException e) {
throw new HibernateException("Unable to open config file: " + path, e);
}
}
catch (IOException e) {
throw new HibernateException( "Unable to open config file: " + path, e );
}
}
/** Open an Reader to the URL represented by the incoming path. First makes a call
/**
* Open an Reader to the URL represented by the incoming path. First makes a call
* to {@link #locateConfig(java.lang.String)} in order to find an appropriate URL.
* {@link java.net.URL#openStream()} is then called to obtain a stream, which is then
* wrapped in a Reader.
*
* @param path The path representing the config location.
*
* @return An input stream to the requested config resource.
*
* @throws HibernateException Unable to open reader to that resource.
*/
public static Reader getConfigStreamReader(final String path) throws HibernateException {
return new InputStreamReader( getConfigStream(path) );
return new InputStreamReader( getConfigStream( path ) );
}
/** Loads a properties instance based on the data at the incoming config location.
/**
* Loads a properties instance based on the data at the incoming config location.
*
* @param path The path representing the config location.
*
* @return The loaded properties instance.
*
* @throws HibernateException Unable to load properties from that resource.
*/
public static Properties getConfigProperties(String path) throws HibernateException {
try {
Properties properties = new Properties();
properties.load( getConfigStream(path) );
properties.load( getConfigStream( path ) );
return properties;
}
catch(IOException e) {
throw new HibernateException("Unable to load properties from specified config file: " + path, e);
catch (IOException e) {
throw new HibernateException( "Unable to load properties from specified config file: " + path, e );
}
}
private ConfigHelper() {}
private ConfigHelper() {
}
public static InputStream getResourceAsStream(String resource) {
String stripped = resource.startsWith("/")
? resource.substring(1)
String stripped = resource.startsWith( "/" )
? resource.substring( 1 )
: resource;
InputStream stream = null;
ClassLoader classLoader = ClassLoaderHelper.getContextClassLoader();
if (classLoader!=null) {
if ( classLoader != null ) {
stream = classLoader.getResourceAsStream( stripped );
}
if ( stream == null ) {
@ -180,7 +191,7 @@ public final class ConfigHelper {
public static InputStream getUserResourceAsStream(String resource) {
boolean hasLeadingSlash = resource.startsWith( "/" );
String stripped = hasLeadingSlash ? resource.substring(1) : resource;
String stripped = hasLeadingSlash ? resource.substring( 1 ) : resource;
InputStream stream = null;

View File

@ -39,18 +39,20 @@ import org.hibernate.type.Type;
/**
* Renders entities and query parameters to a nicely readable string.
*
* @author Gavin King
*/
public final class EntityPrinter {
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( EntityPrinter.class );
private static final CoreMessageLogger LOG = CoreLogging.messageLogger( EntityPrinter.class );
private SessionFactoryImplementor factory;
private SessionFactoryImplementor factory;
/**
* Renders an entity to a string.
*
* @param entityName the entity name
* @param entity an actual entity object, not a proxy!
*
* @return the entity rendered to a string
*/
public String toString(String entityName, Object entity) throws HibernateException {
@ -60,23 +62,26 @@ public final class EntityPrinter {
return entity.getClass().getName();
}
Map<String,String> result = new HashMap<String,String>();
Map<String, String> result = new HashMap<String, String>();
if ( entityPersister.hasIdentifierProperty() ) {
result.put(
entityPersister.getIdentifierPropertyName(),
entityPersister.getIdentifierType().toLoggableString( entityPersister.getIdentifier( entity ), factory )
entityPersister.getIdentifierPropertyName(),
entityPersister.getIdentifierType().toLoggableString(
entityPersister.getIdentifier( entity ),
factory
)
);
}
Type[] types = entityPersister.getPropertyTypes();
String[] names = entityPersister.getPropertyNames();
Object[] values = entityPersister.getPropertyValues( entity );
for ( int i=0; i<types.length; i++ ) {
if ( !names[i].startsWith("_") ) {
String strValue = values[i]==LazyPropertyInitializer.UNFETCHED_PROPERTY ?
values[i].toString() :
types[i].toLoggableString( values[i], factory );
for ( int i = 0; i < types.length; i++ ) {
if ( !names[i].startsWith( "_" ) ) {
String strValue = values[i] == LazyPropertyInitializer.UNFETCHED_PROPERTY ?
values[i].toString() :
types[i].toLoggableString( values[i], factory );
result.put( names[i], strValue );
}
}
@ -85,16 +90,16 @@ public final class EntityPrinter {
public String toString(Type[] types, Object[] values) throws HibernateException {
StringBuilder buffer = new StringBuilder();
for ( int i=0; i<types.length; i++ ) {
if ( types[i]!=null ) {
for ( int i = 0; i < types.length; i++ ) {
if ( types[i] != null ) {
buffer.append( types[i].toLoggableString( values[i], factory ) ).append( ", " );
}
}
return buffer.toString();
}
public String toString(Map<String,TypedValue> namedTypedValues) throws HibernateException {
Map<String,String> result = new HashMap<String,String>();
public String toString(Map<String, TypedValue> namedTypedValues) throws HibernateException {
Map<String, String> result = new HashMap<String, String>();
for ( Map.Entry<String, TypedValue> entry : namedTypedValues.entrySet() ) {
result.put(
entry.getKey(), entry.getValue().getType().toLoggableString(
@ -107,19 +112,19 @@ public final class EntityPrinter {
}
// Cannot use Map as an argument because it clashes with the previous method (due to type erasure)
public void toString(Iterable<Map.Entry<EntityKey,Object>> entitiesByEntityKey) throws HibernateException {
if ( ! LOG.isDebugEnabled() || ! entitiesByEntityKey.iterator().hasNext() ) {
public void toString(Iterable<Map.Entry<EntityKey, Object>> entitiesByEntityKey) throws HibernateException {
if ( !LOG.isDebugEnabled() || !entitiesByEntityKey.iterator().hasNext() ) {
return;
}
LOG.debug( "Listing entities:" );
int i=0;
for ( Map.Entry<EntityKey,Object> entityKeyAndEntity : entitiesByEntityKey ) {
if (i++>20) {
LOG.debug("More......");
LOG.debug( "Listing entities:" );
int i = 0;
for ( Map.Entry<EntityKey, Object> entityKeyAndEntity : entitiesByEntityKey ) {
if ( i++ > 20 ) {
LOG.debug( "More......" );
break;
}
LOG.debug( toString( entityKeyAndEntity.getKey().getEntityName(), entityKeyAndEntity.getValue() ) );
LOG.debug( toString( entityKeyAndEntity.getKey().getEntityName(), entityKeyAndEntity.getValue() ) );
}
}

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